From 2891329e8f31cc4cd0d34a73733f41a79ed3defb Mon Sep 17 00:00:00 2001 From: Your Name Date: Sat, 31 Oct 2026 12:18:23 +0200 Subject: [PATCH] After adding the fonctionality for apk publish9 --- .../src/services/mobileAppReleaseService.ts | 6 ++ .../vps-gateway/nginx/prediqo.conf.template | 14 +++++ docs/MOBILE_APP_RELEASES.md | 3 +- nginx/default-http-only.conf.template | 16 ++++++ nginx/default-https-custom-port.conf.template | 15 +++++ nginx/default.conf.template | 15 +++++ .../kotlin/com/prediqo/mobile/MainActivity.kt | 25 ++++++++- .../lib/core/network/api_client.dart | 5 +- .../app_update/app_update_coordinator.dart | 17 ++++-- .../app_update/data/app_update_models.dart | 4 ++ .../data/app_update_repository.dart | 55 ++++++++++++++++--- .../presentation/app_update_dialog.dart | 24 +++++++- prediqo_mobile/pubspec.yaml | 2 +- 13 files changed, 184 insertions(+), 17 deletions(-) diff --git a/backend/src/services/mobileAppReleaseService.ts b/backend/src/services/mobileAppReleaseService.ts index bce2fb5d..9f383848 100644 --- a/backend/src/services/mobileAppReleaseService.ts +++ b/backend/src/services/mobileAppReleaseService.ts @@ -383,6 +383,8 @@ export type UpdateCheckResult = { fileSizeBytes: number | null; sha256: string | null; downloadUrl: string | null; + /** Same-origin API path — prefer this on mobile so APP_PUBLIC_URL host mismatches do not apply. */ + downloadPath: string | null; minSupportedVersionCode: number; checkIntervalSeconds: number; publishedAt: string | null; @@ -423,6 +425,7 @@ export async function checkAndroidUpdate(input: { fileSizeBytes: null, sha256: null, downloadUrl: null, + downloadPath: null, minSupportedVersionCode: minSupported, checkIntervalSeconds: settings.checkIntervalSeconds, publishedAt: null, @@ -455,6 +458,7 @@ export async function checkAndroidUpdate(input: { fileSizeBytes: latest.fileSizeBytes, sha256: latest.sha256, downloadUrl: publicDownloadUrl(latest.id, token), + downloadPath: publicDownloadPath(latest.id, token), publishedAt: latest.publishedAt?.toISOString() ?? null, packageName: latest.packageName, }; @@ -558,6 +562,7 @@ export async function evaluateClientVersionGate(versionCode: number | null): Pro fileSizeBytes: null, sha256: null, downloadUrl: null, + downloadPath: null, minSupportedVersionCode: settings.minSupportedVersionCode, checkIntervalSeconds: settings.checkIntervalSeconds, publishedAt: null, @@ -580,6 +585,7 @@ export async function evaluateClientVersionGate(versionCode: number | null): Pro fileSizeBytes: target.fileSizeBytes, sha256: target.sha256, downloadUrl: publicDownloadUrl(target.id, token), + downloadPath: publicDownloadPath(target.id, token), minSupportedVersionCode: settings.minSupportedVersionCode, checkIntervalSeconds: settings.checkIntervalSeconds, publishedAt: target.publishedAt?.toISOString() ?? null, diff --git a/deploy/vps-gateway/nginx/prediqo.conf.template b/deploy/vps-gateway/nginx/prediqo.conf.template index c356ab61..35ca7ff9 100644 --- a/deploy/vps-gateway/nginx/prediqo.conf.template +++ b/deploy/vps-gateway/nginx/prediqo.conf.template @@ -10,6 +10,20 @@ server { client_max_body_size 200m; + location ~ ^/api/v1/app-updates/android/download/ { + proxy_pass http://crypto_wallet_api:4000; + proxy_http_version 1.1; + proxy_set_header Host $host; + proxy_set_header X-Real-IP $remote_addr; + proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; + proxy_set_header X-Forwarded-Proto $scheme; + proxy_buffering off; + proxy_request_buffering off; + proxy_connect_timeout 60s; + proxy_send_timeout 1800s; + proxy_read_timeout 1800s; + } + location ~ ^/api/v1/admin/mobile-releases/[^/]+/apk$ { proxy_pass http://crypto_wallet_api:4000; proxy_http_version 1.1; diff --git a/docs/MOBILE_APP_RELEASES.md b/docs/MOBILE_APP_RELEASES.md index eb1ec82c..428e9bae 100644 --- a/docs/MOBILE_APP_RELEASES.md +++ b/docs/MOBILE_APP_RELEASES.md @@ -77,7 +77,8 @@ The API reads the signing cert from APK Signature Scheme **v2/v3** (and JAR v1 w - Policies: - optional / recommended → dismissible dialog - mandatory (or below `min_supported_version_code`) → blocking dialog; sensitive APIs return **426** -- Download over HTTPS with HMAC token; size + SHA-256 verified before install +- Download uses the **same host as `API_BASE_URL`** (path `/api/v1/app-updates/android/download/...`), not `APP_PUBLIC_URL` — avoids slow/failing hits on a different HTTPS port +- HMAC token; size + SHA-256 verified before install; screen kept awake during download - Android system installer prompt is never bypassed ## Backup & VPS migration diff --git a/nginx/default-http-only.conf.template b/nginx/default-http-only.conf.template index f914c252..7e357160 100644 --- a/nginx/default-http-only.conf.template +++ b/nginx/default-http-only.conf.template @@ -12,6 +12,22 @@ server { root /var/www/certbot; } + # Public APK download — stream without buffering (mobile clients need steady bytes). + location ~ ^/api/v1/app-updates/android/download/ { + set $backend_api backend; + proxy_pass http://$backend_api:4000; + proxy_http_version 1.1; + proxy_set_header Host $host; + proxy_set_header X-Real-IP $remote_addr; + proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; + proxy_set_header X-Forwarded-Proto $scheme; + proxy_buffering off; + proxy_request_buffering off; + proxy_connect_timeout 60s; + proxy_send_timeout 1800s; + proxy_read_timeout 1800s; + } + # Large APK uploads: long body/proxy timeouts, stream to API (no full nginx buffer). location ~ ^/api/v1/admin/mobile-releases/[^/]+/apk$ { set $backend_api backend; diff --git a/nginx/default-https-custom-port.conf.template b/nginx/default-https-custom-port.conf.template index 0481e9ae..06ba8b44 100644 --- a/nginx/default-https-custom-port.conf.template +++ b/nginx/default-https-custom-port.conf.template @@ -27,6 +27,21 @@ server { client_max_body_size 200m; + location ~ ^/api/v1/app-updates/android/download/ { + set $backend_api backend; + proxy_pass http://$backend_api:4000; + proxy_http_version 1.1; + proxy_set_header Host $host; + proxy_set_header X-Real-IP $remote_addr; + proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; + proxy_set_header X-Forwarded-Proto $scheme; + proxy_buffering off; + proxy_request_buffering off; + proxy_connect_timeout 60s; + proxy_send_timeout 1800s; + proxy_read_timeout 1800s; + } + location ~ ^/api/v1/admin/mobile-releases/[^/]+/apk$ { set $backend_api backend; proxy_pass http://$backend_api:4000; diff --git a/nginx/default.conf.template b/nginx/default.conf.template index 9c39dfed..caed43e5 100644 --- a/nginx/default.conf.template +++ b/nginx/default.conf.template @@ -25,6 +25,21 @@ server { client_max_body_size 200m; + location ~ ^/api/v1/app-updates/android/download/ { + set $backend_api backend; + proxy_pass http://$backend_api:4000; + proxy_http_version 1.1; + proxy_set_header Host $host; + proxy_set_header X-Real-IP $remote_addr; + proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; + proxy_set_header X-Forwarded-Proto $scheme; + proxy_buffering off; + proxy_request_buffering off; + proxy_connect_timeout 60s; + proxy_send_timeout 1800s; + proxy_read_timeout 1800s; + } + location ~ ^/api/v1/admin/mobile-releases/[^/]+/apk$ { set $backend_api backend; proxy_pass http://$backend_api:4000; diff --git a/prediqo_mobile/android/app/src/main/kotlin/com/prediqo/mobile/MainActivity.kt b/prediqo_mobile/android/app/src/main/kotlin/com/prediqo/mobile/MainActivity.kt index 187fc275..a4b12b14 100644 --- a/prediqo_mobile/android/app/src/main/kotlin/com/prediqo/mobile/MainActivity.kt +++ b/prediqo_mobile/android/app/src/main/kotlin/com/prediqo/mobile/MainActivity.kt @@ -1,5 +1,28 @@ package com.prediqo.mobile +import android.view.WindowManager import io.flutter.embedding.android.FlutterActivity +import io.flutter.embedding.engine.FlutterEngine +import io.flutter.plugin.common.MethodChannel -class MainActivity : FlutterActivity() +class MainActivity : FlutterActivity() { + private val keepAwakeChannel = "tloto/keep_awake" + + override fun configureFlutterEngine(flutterEngine: FlutterEngine) { + super.configureFlutterEngine(flutterEngine) + MethodChannel(flutterEngine.dartExecutor.binaryMessenger, keepAwakeChannel) + .setMethodCallHandler { call, result -> + when (call.method) { + "enable" -> { + window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON) + result.success(null) + } + "disable" -> { + window.clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON) + result.success(null) + } + else -> result.notImplemented() + } + } + } +} diff --git a/prediqo_mobile/lib/core/network/api_client.dart b/prediqo_mobile/lib/core/network/api_client.dart index 74d85d8a..d50c481d 100644 --- a/prediqo_mobile/lib/core/network/api_client.dart +++ b/prediqo_mobile/lib/core/network/api_client.dart @@ -129,8 +129,11 @@ class _AuthInterceptor extends Interceptor { final path = err.requestOptions.path; final uriPath = err.requestOptions.uri.path; final isAuthEndpoint = _isCredentialAuthPath(path) || _isCredentialAuthPath(uriPath); + final skipRefresh = err.requestOptions.extra['skipAuthRefresh'] == true || + path.contains('/app-updates/android') || + uriPath.contains('/app-updates/android'); - if (err.response?.statusCode == 401 && !isAuthEndpoint) { + if (err.response?.statusCode == 401 && !isAuthEndpoint && !skipRefresh) { final refreshed = await _refreshAccessToken(); if (refreshed) { try { diff --git a/prediqo_mobile/lib/features/app_update/app_update_coordinator.dart b/prediqo_mobile/lib/features/app_update/app_update_coordinator.dart index 8b797fb4..f81c55db 100644 --- a/prediqo_mobile/lib/features/app_update/app_update_coordinator.dart +++ b/prediqo_mobile/lib/features/app_update/app_update_coordinator.dart @@ -31,6 +31,8 @@ class AppUpdateCoordinator { Future checkAndPrompt({ required bool force, required bool blockNavigationIfMandatory, + /// When true (header icon tap), show even if the user previously chose Later. + bool ignoreSnooze = false, }) async { AppUpdateCheckResult? result; try { @@ -46,11 +48,14 @@ class AppUpdateCoordinator { final prefs = await SharedPreferences.getInstance(); final lastPromptMs = prefs.getInt('tloto_update_last_prompt_ms') ?? 0; final now = DateTime.now().millisecondsSinceEpoch; - if (!force && !result.isMandatory && now - lastPromptMs < interval * 1000) { + // Interval throttle applies to automatic prompts only — not manual icon taps. + if (!ignoreSnooze && !force && !result.isMandatory && now - lastPromptMs < interval * 1000) { return result; } - final show = await _repository.shouldShowOptional(result); + final show = ignoreSnooze + ? result.updateAvailable + : await _repository.shouldShowOptional(result); if (!result.updateAvailable || !show) return result; final ctx = rootNavigatorKey.currentContext; @@ -66,9 +71,13 @@ class AppUpdateCoordinator { return result; } - /// Legacy tap handler: prefer in-app flow, else open APP_STORE_URL. + /// Header update icon: always re-open the dialog when an update is available. Future handleManualTap(BuildContext context) async { - final result = await checkAndPrompt(force: true, blockNavigationIfMandatory: false); + final result = await checkAndPrompt( + force: true, + blockNavigationIfMandatory: false, + ignoreSnooze: true, + ); if (result != null && result.updateAvailable) return; final store = _config?.appStoreUrl?.trim() ?? diff --git a/prediqo_mobile/lib/features/app_update/data/app_update_models.dart b/prediqo_mobile/lib/features/app_update/data/app_update_models.dart index 74b0b552..5f734fa3 100644 --- a/prediqo_mobile/lib/features/app_update/data/app_update_models.dart +++ b/prediqo_mobile/lib/features/app_update/data/app_update_models.dart @@ -13,6 +13,7 @@ class AppUpdateCheckResult { this.fileSizeBytes, this.sha256, this.downloadUrl, + this.downloadPath, this.publishedAt, this.packageName, }); @@ -27,6 +28,8 @@ class AppUpdateCheckResult { final int? fileSizeBytes; final String? sha256; final String? downloadUrl; + /// Prefer over [downloadUrl] — same host as the app's API base URL. + final String? downloadPath; final int minSupportedVersionCode; final int checkIntervalSeconds; final String? publishedAt; @@ -49,6 +52,7 @@ class AppUpdateCheckResult { fileSizeBytes: (json['fileSizeBytes'] as num?)?.toInt(), sha256: json['sha256'] as String?, downloadUrl: json['downloadUrl'] as String?, + downloadPath: json['downloadPath'] as String?, minSupportedVersionCode: (json['minSupportedVersionCode'] as num?)?.toInt() ?? 1, checkIntervalSeconds: (json['checkIntervalSeconds'] as num?)?.toInt() ?? 21600, publishedAt: json['publishedAt'] as String?, diff --git a/prediqo_mobile/lib/features/app_update/data/app_update_repository.dart b/prediqo_mobile/lib/features/app_update/data/app_update_repository.dart index c34a5e53..84c41e07 100644 --- a/prediqo_mobile/lib/features/app_update/data/app_update_repository.dart +++ b/prediqo_mobile/lib/features/app_update/data/app_update_repository.dart @@ -142,35 +142,76 @@ class AppUpdateRepository { } catch (_) {} } + /// Prefer same host as [ApiClient.baseUrl] (web is fast on :9080; APP_PUBLIC_URL may be :9443). + String resolveDownloadTarget(AppUpdateCheckResult update) { + final path = update.downloadPath?.trim(); + if (path != null && path.isNotEmpty) { + if (path.startsWith('http://') || path.startsWith('https://')) { + return _rewriteToApiOrigin(path); + } + return path.startsWith('/') ? path : '/$path'; + } + final url = update.downloadUrl?.trim(); + if (url == null || url.isEmpty) { + throw AppException('Missing download URL'); + } + return _rewriteToApiOrigin(url); + } + + String _rewriteToApiOrigin(String absoluteOrRelative) { + final api = Uri.parse(_api.baseUrl); + final uri = Uri.parse(absoluteOrRelative); + if (!uri.hasScheme) { + final path = absoluteOrRelative.startsWith('/') ? absoluteOrRelative : '/$absoluteOrRelative'; + return path; + } + return uri + .replace( + scheme: api.scheme, + host: api.host, + port: api.hasPort ? api.port : null, + ) + .toString(); + } + /// Downloads APK to temp dir, verifies size + SHA-256, returns local file. Future downloadApk( AppUpdateCheckResult update, { void Function(int received, int total)? onProgress, CancelToken? cancelToken, }) async { - final url = update.downloadUrl; - if (url == null || url.isEmpty) { - throw AppException('Missing download URL'); - } + final target = resolveDownloadTarget(update); final dir = await getTemporaryDirectory(); final file = File('${dir.path}/tloto-update-${update.versionCode}.apk'); if (await file.exists()) { await file.delete(); } - final releaseId = _releaseIdFromUrl(url); + final releaseId = _releaseIdFromUrl(target) ?? _releaseIdFromUrl(update.downloadUrl ?? ''); await reportEvent(eventType: 'download_start', releaseId: releaseId, versionCode: update.versionCode); try { + // Relative paths use the app's API base (same fast path as the website). await _api.dio.download( - url, + target, file.path, cancelToken: cancelToken, onReceiveProgress: onProgress, + deleteOnError: true, + lengthHeader: Headers.contentLengthHeader, options: Options( - receiveTimeout: const Duration(minutes: 10), + // Large APKs on mobile uplinks — keep receiving as long as bytes arrive. + receiveTimeout: const Duration(minutes: 45), sendTimeout: const Duration(minutes: 2), + connectTimeout: const Duration(seconds: 30), followRedirects: true, + maxRedirects: 5, + responseType: ResponseType.stream, + headers: { + // Avoid JSON Accept confusing some proxies for binary streams. + Headers.acceptHeader: 'application/vnd.android.package-archive,*/*', + }, + extra: {'skipAuthRefresh': true}, validateStatus: (s) => s != null && s < 400, ), ); diff --git a/prediqo_mobile/lib/features/app_update/presentation/app_update_dialog.dart b/prediqo_mobile/lib/features/app_update/presentation/app_update_dialog.dart index 63cda510..a6a323d3 100644 --- a/prediqo_mobile/lib/features/app_update/presentation/app_update_dialog.dart +++ b/prediqo_mobile/lib/features/app_update/presentation/app_update_dialog.dart @@ -1,5 +1,6 @@ import 'package:dio/dio.dart'; import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; import 'package:open_filex/open_filex.dart'; import '../../../core/theme/app_colors.dart'; @@ -7,6 +8,8 @@ import '../../../l10n/app_strings.dart'; import '../data/app_update_models.dart'; import '../data/app_update_repository.dart'; +const _keepAwakeChannel = MethodChannel('tloto/keep_awake'); + String _formatBytes(int? n) { if (n == null) return '—'; if (n < 1024 * 1024) return '${(n / 1024).toFixed(1)} KB'; @@ -60,13 +63,20 @@ class _AppUpdateDialogState extends State<_AppUpdateDialog> { _progress = 0; }); _cancelToken = CancelToken(); + // Keep the screen on — Android sleep commonly aborts long APK downloads. + await _setKeepAwake(true); try { final file = await widget.repository.downloadApk( widget.update, cancelToken: _cancelToken, onProgress: (received, total) { - if (!mounted || total <= 0) return; - setState(() => _progress = received / total); + if (!mounted) return; + if (total > 0) { + setState(() => _progress = received / total); + } else if (received > 0) { + // Server omitted Content-Length — show indeterminate progress still moving. + setState(() => _progress = null); + } }, ); if (!mounted) return; @@ -86,6 +96,16 @@ class _AppUpdateDialogState extends State<_AppUpdateDialog> { _downloading = false; _error = e.toString(); }); + } finally { + await _setKeepAwake(false); + } + } + + Future _setKeepAwake(bool enable) async { + try { + await _keepAwakeChannel.invokeMethod(enable ? 'enable' : 'disable'); + } catch (_) { + // Best-effort — missing platform channel must not block download. } } diff --git a/prediqo_mobile/pubspec.yaml b/prediqo_mobile/pubspec.yaml index cdf2a936..70bbba38 100644 --- a/prediqo_mobile/pubspec.yaml +++ b/prediqo_mobile/pubspec.yaml @@ -1,7 +1,7 @@ name: prediqo_mobile description: "Tloto mobile app - prediction games and crypto wallet." publish_to: 'none' -version: 2.0.2+3 +version: 2.0.2+6 environment: sdk: ^3.9.2