# Path: mobsf/MobSF/utils.py
# def api_key():
#     """Print REST API Key."""
#     if os.environ.get('MOBSF_API_KEY'):
#         logger.info('\nAPI Key read from environment variable')
#         return os.environ['MOBSF_API_KEY']
# 
#     secret_file = os.path.join(settings.MobSF_HOME, 'secret')
#     if is_file_exists(secret_file):
#         try:
#             _api_key = open(secret_file).read().strip()
#             return gen_sha256_hash(_api_key)
#         except Exception:
#             logger.exception('Cannot Read API Key')
# 
# 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
from pathlib import Path
from django.conf import settings
from django.shortcuts import (
    loader,
    render,
)
from mobsf.MobSF.utils import (
    api_key,
    print_n_send_error_response,
)
from mobsf.StaticAnalyzer.views.common.shared_func import (
    find_java_source_folder,
)
                yield loader.render_to_string(
                    'static_analysis/treeview_folder.html',
                    {'file': mfile.name,
                     'subfiles': _index(mfile, root_len)},
                )
                continue
            yield loader.render_to_string(
                'static_analysis/treeview_file.html',
                {'file': mfile.name,
                 'path': mfile.as_posix()[root_len + 1: -len(mfile.name)]},
            )
    return _index(root_dir, original_root_dir_len)


def run(request):
    """Source Tree - Java/Smali view."""
    try:
        logger.info('Listing Source files')
        match = re.match('^[0-9a-f]{32}$', request.GET['md5'])
        if not match:
            return print_n_send_error_response(request, 'Scan hash not found')
        md5 = request.GET['md5']
        typ = request.GET['type']
        base = Path(settings.UPLD_DIR) / md5
        if typ == 'smali':
            src = base / 'smali_source'
        else:
            try:
                src = find_java_source_folder(base)[0]
            except StopIteration:

# Path: mobsf/MobSF/utils.py
# def api_key():
#     """Print REST API Key."""
#     if os.environ.get('MOBSF_API_KEY'):
#         logger.info('\nAPI Key read from environment variable')
#         return os.environ['MOBSF_API_KEY']
# 
#     secret_file = os.path.join(settings.MobSF_HOME, 'secret')
#     if is_file_exists(secret_file):
#         try:
#             _api_key = open(secret_file).read().strip()
#             return gen_sha256_hash(_api_key)
#         except Exception:
#             logger.exception('Cannot Read API Key')
# 
# 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/source_tree.py
import logging
import re
from pathlib import Path
from django.conf import settings
from django.shortcuts import (
    loader,
    render,
)
from mobsf.MobSF.utils import (
    api_key,
    print_n_send_error_response,
)
from mobsf.StaticAnalyzer.views.common.shared_func import (
    find_java_source_folder,
)

                yield loader.render_to_string(
                    'static_analysis/treeview_folder.html',
                    {'file': mfile.name,
                     'subfiles': _index(mfile, root_len)},
                )
                continue
            yield loader.render_to_string(
                'static_analysis/treeview_file.html',
                {'file': mfile.name,
                 'path': mfile.as_posix()[root_len + 1: -len(mfile.name)]},
            )
    return _index(root_dir, original_root_dir_len)


def run(request):
    """Source Tree - Java/Smali view."""
    try:
        logger.info('Listing Source files')
        match = re.match('^[0-9a-f]{32}$', request.GET['md5'])
        if not match:
            return print_n_send_error_response(request, 'Scan hash not found')
        md5 = request.GET['md5']
        typ = request.GET['type']
        base = Path(settings.UPLD_DIR) / md5
        if typ == 'smali':
            src = base / 'smali_source'
        else:
            try:
                src = find_java_source_folder(base)[0]
            except StopIteration:

                return print_n_send_error_response(