After adding the fonctionality for apk publish9

This commit is contained in:
Your Name 2026-10-31 12:18:23 +02:00
parent 319705c597
commit 2891329e8f
13 changed files with 184 additions and 17 deletions

View File

@ -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,

View File

@ -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;

View File

@ -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

View File

@ -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;

View File

@ -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;

View File

@ -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;

View File

@ -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()
}
}
}
}

View File

@ -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 {

View File

@ -31,6 +31,8 @@ class AppUpdateCoordinator {
Future<AppUpdateCheckResult?> 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<void> 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() ??

View File

@ -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?,

View File

@ -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<File> 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,
),
);

View File

@ -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<void> _setKeepAwake(bool enable) async {
try {
await _keepAwakeChannel.invokeMethod<void>(enable ? 'enable' : 'disable');
} catch (_) {
// Best-effort — missing platform channel must not block download.
}
}

View File

@ -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