# Path: mobsf/MobSF/utils.py
# def print_n_send_error_response(request,
#                                 msg,
#                                 api=False,
#                                 exp='Description'):
#     """Print and log errors."""
#     logger.error(msg)
#     if api:
#         api_response = {'error': msg}
#         return api_response
#     else:
#         context = {
#             'title': 'Error',
#             'exp': exp,
#             'doc': msg,
#             'version': settings.MOBSF_VER,
#         }
#         template = 'general/error.html'
#         return render(request, template, context, status=500)
# 
# Path: mobsf/StaticAnalyzer/views/common/shared_func.py
# def find_java_source_folder(base_folder: Path):
#     # Find the correct java/kotlin source folder for APK/source zip
#     # Returns a Tuple of - (SRC_PATH, SRC_TYPE, SRC_SYNTAX)
#     return next(p for p in [(base_folder / 'java_source',
#                              'java', '*.java'),
#                             (base_folder / 'app' / 'src' / 'main' / 'java',
#                              'java', '*.java'),
#                             (base_folder / 'app' / 'src' / 'main' / 'kotlin',
#                              'kotlin', '*.kt'),
#                             (base_folder / 'src',
#                              'java', '*.java')]
#                 if p[0].exists())


import logging
import re
import json
from pathlib import Path
from django.conf import settings
from django.http import JsonResponse
from django.utils.html import escape
from mobsf.MobSF.utils import print_n_send_error_response
from mobsf.StaticAnalyzer.views.common.shared_func import (
    find_java_source_folder,
)
            except StopIteration:
                msg = 'Invalid Directory Structure'
                return print_n_send_error_response(request, msg, True)

        exts = ['.java', '.kt', '.smali']
        files = [p for p in src.rglob('*') if p.suffix in exts]
        for fname in files:
            file_path = fname.as_posix()
            rpath = file_path.replace(src.as_posix(), '')
            rpath = rpath[1:]
            if search_type == 'content':
                dat = fname.read_text('utf-8', 'ignore')
                if query.lower() in dat.lower():
                    matches.add(escape(rpath))
            elif search_type == 'filename' and \
                    query.lower() in fname.name.lower():
                matches.add(escape(rpath))

        flz = len(matches)
        context = {
            'title': 'Search Results',
            'matches': list(matches),
            'term': query,
            'found': str(flz),
            'search_type': search_type,
            'version': settings.MOBSF_VER,
        }
        return JsonResponse(json.dumps(context), safe=False)
    except Exception:
        logger.exception('Searching Failed')

# Path: mobsf/MobSF/utils.py
# def print_n_send_error_response(request,
#                                 msg,
#                                 api=False,
#                                 exp='Description'):
#     """Print and log errors."""
#     logger.error(msg)
#     if api:
#         api_response = {'error': msg}
#         return api_response
#     else:
#         context = {
#             'title': 'Error',
#             'exp': exp,
#             'doc': msg,
#             'version': settings.MOBSF_VER,
#         }
#         template = 'general/error.html'
#         return render(request, template, context, status=500)
# 
# Path: mobsf/StaticAnalyzer/views/common/shared_func.py
# def find_java_source_folder(base_folder: Path):
#     # Find the correct java/kotlin source folder for APK/source zip
#     # Returns a Tuple of - (SRC_PATH, SRC_TYPE, SRC_SYNTAX)
#     return next(p for p in [(base_folder / 'java_source',
#                              'java', '*.java'),
#                             (base_folder / 'app' / 'src' / 'main' / 'java',
#                              'java', '*.java'),
#                             (base_folder / 'app' / 'src' / 'main' / 'kotlin',
#                              'kotlin', '*.kt'),
#                             (base_folder / 'src',
#                              'java', '*.java')]
#                 if p[0].exists())


# Path: mobsf/StaticAnalyzer/views/android/find.py
import logging
import re
import json
from pathlib import Path
from django.conf import settings
from django.http import JsonResponse
from django.utils.html import escape
from mobsf.MobSF.utils import print_n_send_error_response
from mobsf.StaticAnalyzer.views.common.shared_func import (
    find_java_source_folder,
)

            except StopIteration:
                msg = 'Invalid Directory Structure'
                return print_n_send_error_response(request, msg, True)

        exts = ['.java', '.kt', '.smali']
        files = [p for p in src.rglob('*') if p.suffix in exts]
        for fname in files:
            file_path = fname.as_posix()
            rpath = file_path.replace(src.as_posix(), '')
            rpath = rpath[1:]
            if search_type == 'content':
                dat = fname.read_text('utf-8', 'ignore')
                if query.lower() in dat.lower():
                    matches.add(escape(rpath))
            elif search_type == 'filename' and \
                    query.lower() in fname.name.lower():
                matches.add(escape(rpath))

        flz = len(matches)
        context = {
            'title': 'Search Results',
            'matches': list(matches),
            'term': query,
            'found': str(flz),
            'search_type': search_type,
            'version': settings.MOBSF_VER,
        }
        return JsonResponse(json.dumps(context), safe=False)
    except Exception:
        logger.exception('Searching Failed')

        return print_n_send_error_response(