# Path: mobsf/MobSF/utils.py
# def is_safe_path(safe_root, check_path):
#     """Detect Path Traversal."""
#     safe_root = os.path.realpath(os.path.normpath(safe_root))
#     check_path = os.path.realpath(os.path.normpath(check_path))
#     return os.path.commonprefix([check_path, safe_root]) == safe_root
# 
# 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 ntpath
from pathlib import Path
from django.conf import settings
from django.shortcuts import render
from django.utils.html import escape
from mobsf.MobSF.forms import FormUtil
from mobsf.MobSF.utils import (
    is_safe_path,
    print_n_send_error_response,
)
from mobsf.StaticAnalyzer.views.common.shared_func import (
    find_java_source_folder,
)
from mobsf.StaticAnalyzer.forms import (
    ViewSourceAndroidApiForm,
    ViewSourceAndroidForm,
)


def run(request, api=False):
    """View the source of a file."""
    try:
        logger.info('View Android Source File')
        exp = 'Error Description'
        if api:
            fil = request.POST['file']
            md5 = request.POST['hash']
            typ = request.POST['type']
            viewsource_form = ViewSourceAndroidApiForm(request.POST)
        else:
            fil = request.GET['file']
            md5 = request.GET['md5']
            typ = request.GET['type']
            viewsource_form = ViewSourceAndroidForm(request.GET)
        if not viewsource_form.is_valid():
            err = FormUtil.errors_message(viewsource_form)
            return print_n_send_error_response(request, err, api, exp)

        base = Path(settings.UPLD_DIR) / md5
        if typ == 'smali':
            src = base / 'smali_source'
            syntax = 'smali'
        else:
            try:
                src, syntax, _ = find_java_source_folder(base)
            except StopIteration:
                msg = 'Invalid Directory Structure'

# Path: mobsf/MobSF/utils.py
# def is_safe_path(safe_root, check_path):
#     """Detect Path Traversal."""
#     safe_root = os.path.realpath(os.path.normpath(safe_root))
#     check_path = os.path.realpath(os.path.normpath(check_path))
#     return os.path.commonprefix([check_path, safe_root]) == safe_root
# 
# 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/view_source.py
import logging
import ntpath
from pathlib import Path
from django.conf import settings
from django.shortcuts import render
from django.utils.html import escape
from mobsf.MobSF.forms import FormUtil
from mobsf.MobSF.utils import (
    is_safe_path,
    print_n_send_error_response,
)
from mobsf.StaticAnalyzer.views.common.shared_func import (
    find_java_source_folder,
)
from mobsf.StaticAnalyzer.forms import (
    ViewSourceAndroidApiForm,
    ViewSourceAndroidForm,
)



def run(request, api=False):
    """View the source of a file."""
    try:
        logger.info('View Android Source File')
        exp = 'Error Description'
        if api:
            fil = request.POST['file']
            md5 = request.POST['hash']
            typ = request.POST['type']
            viewsource_form = ViewSourceAndroidApiForm(request.POST)
        else:
            fil = request.GET['file']
            md5 = request.GET['md5']
            typ = request.GET['type']
            viewsource_form = ViewSourceAndroidForm(request.GET)
        if not viewsource_form.is_valid():
            err = FormUtil.errors_message(viewsource_form)
            return print_n_send_error_response(request, err, api, exp)

        base = Path(settings.UPLD_DIR) / md5
        if typ == 'smali':
            src = base / 'smali_source'
            syntax = 'smali'
        else:
            try:
                src, syntax, _ = find_java_source_folder(base)
            except StopIteration:
                msg = 'Invalid Directory Structure'

                return print_n_send_error_response(request, msg, api)