274 lines
8.7 KiB
Dart
274 lines
8.7 KiB
Dart
import 'dart:convert';
|
||
import 'dart:io';
|
||
|
||
import 'package:code_editor/l10n/app_localizations.dart';
|
||
import 'package:code_editor/providers/settings_provider.dart';
|
||
import 'package:flutter/material.dart';
|
||
import 'package:flutter/services.dart';
|
||
import 'package:url_launcher/url_launcher.dart';
|
||
|
||
/// 应用版本更新信息(Gitea Releases)
|
||
class AppUpdateInfo {
|
||
const AppUpdateInfo({
|
||
required this.versionCode,
|
||
required this.versionName,
|
||
required this.changelog,
|
||
required this.downloadUrl,
|
||
required this.hasUpdate,
|
||
this.apkSize = '',
|
||
});
|
||
|
||
final int versionCode;
|
||
final String versionName;
|
||
final String changelog;
|
||
final String downloadUrl;
|
||
final bool hasUpdate;
|
||
final String apkSize;
|
||
}
|
||
|
||
/// 基于自建 Gitea Releases 的版本更新检查服务
|
||
class AppUpdateService {
|
||
AppUpdateService._();
|
||
|
||
static final AppUpdateService instance = AppUpdateService._();
|
||
|
||
static const String fallbackVersionName = '1.0.3';
|
||
static const String updateUrl =
|
||
'https://gitea.lzxnone.cloud/api/v1/repos/lzxnone/LN-Code-Editor/releases/latest';
|
||
static const MethodChannel _nativeChannel =
|
||
MethodChannel('com.lzxnone.code_editor/native');
|
||
|
||
String? _cachedAppVersion;
|
||
|
||
Future<String> getCurrentAppVersion() async {
|
||
if (_cachedAppVersion != null && _cachedAppVersion!.isNotEmpty) {
|
||
return _cachedAppVersion!;
|
||
}
|
||
try {
|
||
final version = await _nativeChannel.invokeMethod<String>('getAppVersion');
|
||
if (version != null && version.trim().isNotEmpty) {
|
||
_cachedAppVersion = version.trim();
|
||
return _cachedAppVersion!;
|
||
}
|
||
} catch (_) {}
|
||
return fallbackVersionName;
|
||
}
|
||
|
||
Future<List<String>> _getSupportedAbis() async {
|
||
try {
|
||
final abis = await _nativeChannel.invokeListMethod<String>('getSupportedAbis');
|
||
if (abis != null) return abis;
|
||
} catch (_) {}
|
||
return const [];
|
||
}
|
||
|
||
/// 检查 Gitea 最新 Release 是否有新版本
|
||
Future<AppUpdateInfo> checkUpdate() async {
|
||
final currentVersion = await getCurrentAppVersion();
|
||
final supportedAbis = await _getSupportedAbis();
|
||
|
||
final client = HttpClient()..connectionTimeout = const Duration(seconds: 8);
|
||
try {
|
||
final request = await client.getUrl(Uri.parse(updateUrl));
|
||
request.headers.set(HttpHeaders.acceptHeader, 'application/json');
|
||
request.headers.set(HttpHeaders.userAgentHeader, 'LN-Code-Editor-Android');
|
||
|
||
final response = await request.close().timeout(const Duration(seconds: 8));
|
||
final body = await utf8.decodeStream(response);
|
||
if (response.statusCode != HttpStatus.ok) {
|
||
throw HttpException('HTTP ${response.statusCode}', uri: Uri.parse(updateUrl));
|
||
}
|
||
return parseReleaseJson(
|
||
body,
|
||
currentVersion: currentVersion,
|
||
supportedAbis: supportedAbis,
|
||
);
|
||
} finally {
|
||
client.close(force: true);
|
||
}
|
||
}
|
||
|
||
/// 启动静默自动检查,发现新版且未被抑制时弹窗提醒
|
||
Future<void> checkAutoUpdate(
|
||
BuildContext context,
|
||
SettingsProvider settings,
|
||
) async {
|
||
if (!settings.autoCheckUpdate) return;
|
||
try {
|
||
final info = await checkUpdate();
|
||
if (!context.mounted) return;
|
||
if (info.hasUpdate &&
|
||
info.versionCode > settings.suppressedUpdateVersionCode) {
|
||
await showUpdateDialog(context, info, settings: settings);
|
||
}
|
||
} catch (_) {}
|
||
}
|
||
|
||
/// 展示更新弹窗
|
||
Future<void> showUpdateDialog(
|
||
BuildContext context,
|
||
AppUpdateInfo info, {
|
||
SettingsProvider? settings,
|
||
}) async {
|
||
if (!context.mounted) return;
|
||
final l10n = AppLocalizations.of(context)!;
|
||
final displayVersion = info.versionName.toLowerCase().startsWith('v')
|
||
? 'V${info.versionName.substring(1)}'
|
||
: 'V${info.versionName}';
|
||
|
||
await showDialog<void>(
|
||
context: context,
|
||
builder: (dialogContext) {
|
||
return AlertDialog(
|
||
title: Text(l10n.newVersionAvailableTitle(displayVersion)),
|
||
content: ConstrainedBox(
|
||
constraints: const BoxConstraints(maxHeight: 280),
|
||
child: SingleChildScrollView(
|
||
child: Text(info.changelog),
|
||
),
|
||
),
|
||
actions: [
|
||
if (settings != null)
|
||
TextButton(
|
||
onPressed: () {
|
||
settings.setSuppressedUpdateVersionCode(info.versionCode);
|
||
Navigator.of(dialogContext).pop();
|
||
},
|
||
child: Text(l10n.dontShowAgainForVersion),
|
||
),
|
||
TextButton(
|
||
onPressed: () => Navigator.of(dialogContext).pop(),
|
||
child: Text(l10n.cancel),
|
||
),
|
||
FilledButton(
|
||
onPressed: () async {
|
||
Navigator.of(dialogContext).pop();
|
||
if (info.downloadUrl.isNotEmpty) {
|
||
await launchUrl(
|
||
Uri.parse(info.downloadUrl),
|
||
mode: LaunchMode.externalApplication,
|
||
);
|
||
}
|
||
},
|
||
child: Text(l10n.downloadUpdate),
|
||
),
|
||
],
|
||
);
|
||
},
|
||
);
|
||
}
|
||
|
||
@visibleForTesting
|
||
static AppUpdateInfo parseReleaseJson(
|
||
String rawJson, {
|
||
required String currentVersion,
|
||
List<String> supportedAbis = const [],
|
||
}) {
|
||
final json = jsonDecode(rawJson) as Map<String, dynamic>;
|
||
final rawTag = (json['tag_name'] as String? ?? '').trim();
|
||
final versionName = rawTag.replaceFirst(RegExp(r'^[vV]'), '');
|
||
final versionCode = parseVersionCode(versionName);
|
||
final rawBody = (json['body'] as String? ?? '').trim();
|
||
final releaseName = (json['name'] as String? ?? '').trim();
|
||
final changelog = rawBody.isNotEmpty ? rawBody : releaseName;
|
||
final fallbackUrl = (json['html_url'] as String? ?? '').trim();
|
||
|
||
final (downloadUrl, apkSize) = _selectApkAsset(
|
||
json['assets'],
|
||
supportedAbis: supportedAbis,
|
||
fallbackUrl: fallbackUrl,
|
||
);
|
||
|
||
return AppUpdateInfo(
|
||
versionCode: versionCode,
|
||
versionName: versionName,
|
||
changelog: changelog,
|
||
downloadUrl: downloadUrl,
|
||
hasUpdate: isNewerVersion(versionName, currentVersion),
|
||
apkSize: apkSize,
|
||
);
|
||
}
|
||
|
||
static (String, String) _selectApkAsset(
|
||
dynamic assets, {
|
||
required List<String> supportedAbis,
|
||
required String fallbackUrl,
|
||
}) {
|
||
if (assets is! List || assets.isEmpty) {
|
||
return (fallbackUrl, '');
|
||
}
|
||
|
||
final apkAssets = <({String name, String url, int size})>[];
|
||
for (final item in assets) {
|
||
if (item is! Map) continue;
|
||
final name = (item['name'] as String? ?? '').trim();
|
||
final url = (item['browser_download_url'] as String? ?? '').trim();
|
||
final size = (item['size'] as num?)?.toInt() ?? 0;
|
||
if (name.toLowerCase().endsWith('.apk') && url.isNotEmpty) {
|
||
apkAssets.add((name: name, url: url, size: size));
|
||
}
|
||
}
|
||
|
||
if (apkAssets.isEmpty) {
|
||
return (fallbackUrl, '');
|
||
}
|
||
|
||
({String name, String url, int size})? matched;
|
||
for (final abi in supportedAbis) {
|
||
final lowerAbi = abi.toLowerCase();
|
||
for (final asset in apkAssets) {
|
||
if (asset.name.toLowerCase().contains(lowerAbi)) {
|
||
matched = asset;
|
||
break;
|
||
}
|
||
}
|
||
if (matched != null) break;
|
||
}
|
||
|
||
matched ??= apkAssets
|
||
.where((a) => a.name.toLowerCase().contains('universal'))
|
||
.firstOrNull;
|
||
matched ??= apkAssets.first;
|
||
|
||
final sizeText = matched.size > 0
|
||
? '${(matched.size / (1024 * 1024)).toStringAsFixed(2)} MB'
|
||
: '';
|
||
return (matched.url, sizeText);
|
||
}
|
||
|
||
@visibleForTesting
|
||
static bool isNewerVersion(String remoteVersion, String currentVersion) {
|
||
final remoteParts = _parseVersionParts(remoteVersion);
|
||
final currentParts = _parseVersionParts(currentVersion);
|
||
if (remoteParts.isEmpty) return false;
|
||
|
||
final maxLen =
|
||
remoteParts.length > currentParts.length ? remoteParts.length : currentParts.length;
|
||
for (var i = 0; i < maxLen; i++) {
|
||
final r = i < remoteParts.length ? remoteParts[i] : 0;
|
||
final c = i < currentParts.length ? currentParts[i] : 0;
|
||
if (r != c) return r > c;
|
||
}
|
||
return false;
|
||
}
|
||
|
||
@visibleForTesting
|
||
static int parseVersionCode(String versionName) {
|
||
final parts = _parseVersionParts(versionName);
|
||
if (parts.isEmpty) return 0;
|
||
final major = parts.isNotEmpty ? parts[0] : 0;
|
||
final minor = parts.length > 1 ? parts[1] : 0;
|
||
final patch = parts.length > 2 ? parts[2] : 0;
|
||
return major * 10000 + minor * 100 + patch;
|
||
}
|
||
|
||
static List<int> _parseVersionParts(String version) {
|
||
final cleaned = version.trim().replaceFirst(RegExp(r'^[vV]'), '');
|
||
if (cleaned.isEmpty) return const [];
|
||
return cleaned.split('.').map((seg) {
|
||
final match = RegExp(r'^\d+').firstMatch(seg);
|
||
return match != null ? int.parse(match.group(0)!) : 0;
|
||
}).toList();
|
||
}
|
||
}
|