# Path: mobsf/DynamicAnalyzer/views/android/dynamic_analyzer.py
# def dynamic_analyzer(request, checksum, api=False):
#     """Android Dynamic Analyzer Environment."""
#     try:
#         identifier = None
#         activities = None
#         exported_activities = None
#         if api:
#             reinstall = request.POST.get('re_install', '1')
#             install = request.POST.get('install', '1')
#         else:
#             reinstall = request.GET.get('re_install', '1')
#             install = request.GET.get('install', '1')
#         if not is_md5(checksum):
#             # We need this check since checksum is not validated
#             # in REST API
#             return print_n_send_error_response(
#                 request,
#                 'Invalid Parameters',
#                 api)
#         package = get_package_name(checksum)
#         if not package:
#             return print_n_send_error_response(
#                 request,
#                 'Cannot get package name from checksum',
#                 api)
#         logger.info('Creating Dynamic Analysis Environment for %s', package)
#         try:
#             identifier = get_device()
#         except Exception:
#             pass
#         if not identifier:
#             msg = ('Is the android instance running? MobSF cannot'
#                    ' find android instance identifier. '
#                    'Please run an android instance and refresh'
#                    ' this page. If this error persists,'
#                    ' set ANALYZER_IDENTIFIER in '
#                    f'{get_config_loc()}')
#             return print_n_send_error_response(request, msg, api)
# 
#         # Get activities from the static analyzer results
#         try:
#             static_android_db = StaticAnalyzerAndroid.objects.get(
#                 MD5=checksum)
#             exported_activities = python_list(
#                 static_android_db.EXPORTED_ACTIVITIES)
#             activities = python_list(
#                 static_android_db.ACTIVITIES)
#         except ObjectDoesNotExist:
#             logger.warning(
#                 'Failed to get Activities. '
#                 'Static Analysis not completed for the app.')
#         env = Environment(identifier)
#         if not env.connect_n_mount():
#             msg = 'Cannot Connect to ' + identifier
#             return print_n_send_error_response(request, msg, api)
#         version = env.get_android_version()
#         logger.info('Android Version identified as %s', version)
#         xposed_first_run = False
#         if not env.is_mobsfyied(version):
#             msg = ('This Android instance is not MobSFyed/Outdated.\n'
#                    'MobSFying the android runtime environment')
#             logger.warning(msg)
#             if not env.mobsfy_init():
#                 return print_n_send_error_response(
#                     request,
#                     'Failed to MobSFy the instance',
#                     api)
#             if version < 5:
#                 xposed_first_run = True
#         if xposed_first_run:
#             msg = ('Have you MobSFyed the instance before'
#                    ' attempting Dynamic Analysis?'
#                    ' Install Framework for Xposed.'
#                    ' Restart the device and enable'
#                    ' all Xposed modules. And finally'
#                    ' restart the device once again.')
#             return print_n_send_error_response(request, msg, api)
#         # Clean up previous analysis
#         env.dz_cleanup(checksum)
#         # Configure Web Proxy
#         env.configure_proxy(package, request)
#         # Supported in Android 5+
#         env.enable_adb_reverse_tcp(version)
#         # Apply Global Proxy to device
#         env.set_global_proxy(version)
#         # Start Clipboard monitor
#         env.start_clipmon()
#         # Get Screen Resolution
#         screen_width, screen_height = env.get_screen_res()
#         if install == '1':
#             # Install APK
#             apk_path = Path(settings.UPLD_DIR) / checksum / f'{checksum}.apk'
#             status, output = env.install_apk(
#                 apk_path.as_posix(),
#                 package,
#                 reinstall)
#             if not status:
#                 # Unset Proxy
#                 env.unset_global_proxy()
#                 msg = (f'This APK cannot be installed. Is this APK '
#                        f'compatible the Android VM/Emulator?\n{output}')
#                 return print_n_send_error_response(
#                     request,
#                     msg,
#                     api)
#         logger.info('Testing Environment is Ready!')
#         context = {'screen_width': screen_width,
#                    'screen_height': screen_height,
#                    'package': package,
#                    'hash': checksum,
#                    'android_version': version,
#                    'version': settings.MOBSF_VER,
#                    'activities': activities,
#                    'exported_activities': exported_activities,
#                    'title': 'Dynamic Analyzer'}
#         template = 'dynamic_analysis/android/dynamic_analyzer.html'
#         if api:
#             return context
#         return render(request, template, context)
#     except Exception:
#         logger.exception('Dynamic Analyzer')
#         return print_n_send_error_response(
#             request,
#             'Dynamic Analysis Failed.',
#             api)
# 
# Path: mobsf/DynamicAnalyzer/views/android/report.py
# def key(d, key_name):
# def view_report(request, checksum, api=False):
# def view_file(request, api=False):
# 
# Path: mobsf/DynamicAnalyzer/views/android/tests_common.py
# def start_activity(request, api=False):
# def activity_tester(request, api=False):
# def download_data(request, api=False):
# def collect_logs(request, api=False):
# def tls_tests(request, api=False):


from django.views.decorators.csrf import csrf_exempt
from mobsf.MobSF.views.helpers import request_method
from mobsf.MobSF.views.api.api_middleware import make_api_response
from mobsf.DynamicAnalyzer.views.android import (
    dynamic_analyzer,
    operations,
    report,
    tests_common,
    tests_frida,
)
# -*- coding: utf_8 -*-
"""MobSF REST API V 1."""




# Dynamic Analyzer APIs
@request_method(['GET'])
@csrf_exempt
def api_get_apps(request):
    """GET - Get Apps for dynamic analysis API."""
    resp = dynamic_analyzer.dynamic_analysis(request, True)
    if 'error' in resp:
        return make_api_response(resp, 500)
    return make_api_response(resp, 200)


@request_method(['POST'])
@csrf_exempt
def api_start_analysis(request):
    """POST - Start Dynamic Analysis."""
    if 'hash' not in request.POST:
        return make_api_response(
            {'error': 'Missing Parameters'}, 422)

# Path: mobsf/DynamicAnalyzer/views/android/dynamic_analyzer.py
# def dynamic_analyzer(request, checksum, api=False):
#     """Android Dynamic Analyzer Environment."""
#     try:
#         identifier = None
#         activities = None
#         exported_activities = None
#         if api:
#             reinstall = request.POST.get('re_install', '1')
#             install = request.POST.get('install', '1')
#         else:
#             reinstall = request.GET.get('re_install', '1')
#             install = request.GET.get('install', '1')
#         if not is_md5(checksum):
#             # We need this check since checksum is not validated
#             # in REST API
#             return print_n_send_error_response(
#                 request,
#                 'Invalid Parameters',
#                 api)
#         package = get_package_name(checksum)
#         if not package:
#             return print_n_send_error_response(
#                 request,
#                 'Cannot get package name from checksum',
#                 api)
#         logger.info('Creating Dynamic Analysis Environment for %s', package)
#         try:
#             identifier = get_device()
#         except Exception:
#             pass
#         if not identifier:
#             msg = ('Is the android instance running? MobSF cannot'
#                    ' find android instance identifier. '
#                    'Please run an android instance and refresh'
#                    ' this page. If this error persists,'
#                    ' set ANALYZER_IDENTIFIER in '
#                    f'{get_config_loc()}')
#             return print_n_send_error_response(request, msg, api)
# 
#         # Get activities from the static analyzer results
#         try:
#             static_android_db = StaticAnalyzerAndroid.objects.get(
#                 MD5=checksum)
#             exported_activities = python_list(
#                 static_android_db.EXPORTED_ACTIVITIES)
#             activities = python_list(
#                 static_android_db.ACTIVITIES)
#         except ObjectDoesNotExist:
#             logger.warning(
#                 'Failed to get Activities. '
#                 'Static Analysis not completed for the app.')
#         env = Environment(identifier)
#         if not env.connect_n_mount():
#             msg = 'Cannot Connect to ' + identifier
#             return print_n_send_error_response(request, msg, api)
#         version = env.get_android_version()
#         logger.info('Android Version identified as %s', version)
#         xposed_first_run = False
#         if not env.is_mobsfyied(version):
#             msg = ('This Android instance is not MobSFyed/Outdated.\n'
#                    'MobSFying the android runtime environment')
#             logger.warning(msg)
#             if not env.mobsfy_init():
#                 return print_n_send_error_response(
#                     request,
#                     'Failed to MobSFy the instance',
#                     api)
#             if version < 5:
#                 xposed_first_run = True
#         if xposed_first_run:
#             msg = ('Have you MobSFyed the instance before'
#                    ' attempting Dynamic Analysis?'
#                    ' Install Framework for Xposed.'
#                    ' Restart the device and enable'
#                    ' all Xposed modules. And finally'
#                    ' restart the device once again.')
#             return print_n_send_error_response(request, msg, api)
#         # Clean up previous analysis
#         env.dz_cleanup(checksum)
#         # Configure Web Proxy
#         env.configure_proxy(package, request)
#         # Supported in Android 5+
#         env.enable_adb_reverse_tcp(version)
#         # Apply Global Proxy to device
#         env.set_global_proxy(version)
#         # Start Clipboard monitor
#         env.start_clipmon()
#         # Get Screen Resolution
#         screen_width, screen_height = env.get_screen_res()
#         if install == '1':
#             # Install APK
#             apk_path = Path(settings.UPLD_DIR) / checksum / f'{checksum}.apk'
#             status, output = env.install_apk(
#                 apk_path.as_posix(),
#                 package,
#                 reinstall)
#             if not status:
#                 # Unset Proxy
#                 env.unset_global_proxy()
#                 msg = (f'This APK cannot be installed. Is this APK '
#                        f'compatible the Android VM/Emulator?\n{output}')
#                 return print_n_send_error_response(
#                     request,
#                     msg,
#                     api)
#         logger.info('Testing Environment is Ready!')
#         context = {'screen_width': screen_width,
#                    'screen_height': screen_height,
#                    'package': package,
#                    'hash': checksum,
#                    'android_version': version,
#                    'version': settings.MOBSF_VER,
#                    'activities': activities,
#                    'exported_activities': exported_activities,
#                    'title': 'Dynamic Analyzer'}
#         template = 'dynamic_analysis/android/dynamic_analyzer.html'
#         if api:
#             return context
#         return render(request, template, context)
#     except Exception:
#         logger.exception('Dynamic Analyzer')
#         return print_n_send_error_response(
#             request,
#             'Dynamic Analysis Failed.',
#             api)
# 
# Path: mobsf/DynamicAnalyzer/views/android/report.py
# def key(d, key_name):
# def view_report(request, checksum, api=False):
# def view_file(request, api=False):
# 
# Path: mobsf/DynamicAnalyzer/views/android/tests_common.py
# def start_activity(request, api=False):
# def activity_tester(request, api=False):
# def download_data(request, api=False):
# def collect_logs(request, api=False):
# def tls_tests(request, api=False):


# Path: mobsf/MobSF/views/api/api_dynamic_analysis.py
from django.views.decorators.csrf import csrf_exempt
from mobsf.MobSF.views.helpers import request_method
from mobsf.MobSF.views.api.api_middleware import make_api_response
from mobsf.DynamicAnalyzer.views.android import (
    dynamic_analyzer,
    operations,
    report,
    tests_common,
    tests_frida,
)

# -*- coding: utf_8 -*-
"""MobSF REST API V 1."""




# Dynamic Analyzer APIs
@request_method(['GET'])
@csrf_exempt
def api_get_apps(request):
    """GET - Get Apps for dynamic analysis API."""
    resp = dynamic_analyzer.dynamic_analysis(request, True)
    if 'error' in resp:
        return make_api_response(resp, 500)
    return make_api_response(resp, 200)


@request_method(['POST'])
@csrf_exempt
def api_start_analysis(request):
    """POST - Start Dynamic Analysis."""
    if 'hash' not in request.POST:
        return make_api_response(
            {'error': 'Missing Parameters'}, 422)

    resp = dynamic_analyzer.dynamic_analyzer(