|
| 1 | +import datetime |
| 2 | +from flask import Flask, request, redirect, jsonify |
| 3 | + |
| 4 | +app = Flask(__name__) |
| 5 | + |
| 6 | +class AppRedirect: |
| 7 | + @staticmethod |
| 8 | + def redirect(options): |
| 9 | + user_agent = request.headers.get('User-Agent') |
| 10 | + browser_moved_to_background = False |
| 11 | + |
| 12 | + def try_to_open_in_multiple_phases(urls): |
| 13 | + nonlocal browser_moved_to_background |
| 14 | + current_index = 0 |
| 15 | + redirect_time = None |
| 16 | + |
| 17 | + def next_phase(): |
| 18 | + nonlocal current_index, redirect_time |
| 19 | + if len(urls) > current_index: |
| 20 | + if browser_moved_to_background: |
| 21 | + print('Browser moved to the background, we assume that we are done here') |
| 22 | + return |
| 23 | + |
| 24 | + if redirect_time and (datetime.now() - redirect_time).total_seconds() > 3: |
| 25 | + print('Enough time has passed, the app is probably open') |
| 26 | + else: |
| 27 | + redirect_time = datetime.now() |
| 28 | + return redirect(urls[current_index]) |
| 29 | + |
| 30 | + return next_phase() |
| 31 | + |
| 32 | + has_ios = bool(options.get("iosApp") or options.get("iosAppStore")) |
| 33 | + has_android = bool(options.get("android")) |
| 34 | + has_overall_fallback = bool(options.get("overallFallback")) |
| 35 | + |
| 36 | + if has_ios and ("iPhone" in user_agent or "iPad" in user_agent or "iPod" in user_agent): |
| 37 | + urls = [] |
| 38 | + if options.get("iosApp"): |
| 39 | + urls.append(options["iosApp"]) |
| 40 | + if options.get("iosAppStore"): |
| 41 | + urls.append(options["iosAppStore"]) |
| 42 | + return try_to_open_in_multiple_phases(urls) |
| 43 | + |
| 44 | + elif has_android and "Android" in user_agent: |
| 45 | + intent = options["android"] |
| 46 | + intent_url = f'intent://{intent["host"]}#Intent;' \ |
| 47 | + f'scheme={intent["scheme"]};' \ |
| 48 | + f'package={intent["package"]};' \ |
| 49 | + f'{f"action={intent["action"]};" if intent.get("action") else ""}' \ |
| 50 | + f'{f"category={intent["category"]};" if intent.get("category") else ""}' \ |
| 51 | + f'{f"component={intent["component"]};" if intent.get("component") else ""}' \ |
| 52 | + f'{f"S.browser_fallback_url={intent["fallback"]};" if intent.get("fallback") else ""}' \ |
| 53 | + 'end' |
| 54 | + return redirect(intent_url) |
| 55 | + |
| 56 | + elif has_overall_fallback: |
| 57 | + return redirect(options["overallFallback"]) |
| 58 | + |
| 59 | + else: |
| 60 | + return jsonify({"message": "Unknown platform and no overallFallback URL, nothing to do"}), 400 |
0 commit comments