Files
EasyDesignCollection/lib/update/update_service.dart
T
admin 440e017203 fix(android): 修复 release 版无法联网(缺 INTERNET 权限);发布 v1.2.2
- 根因:Flutter 模板只在 debug/profile 清单中声明 INTERNET,release 包默认没有,
  导致发布版「检查更新」与「AI 生成」全部无法联网
- 主清单补充 INTERNET 权限,并新增 network_security_config:仅对更新服务器
  放行明文 HTTP(其余域名仍禁止)
- UpdateService.check 支持传入模拟版本(自检用);新增 tool/check_update.dart
  开发自检工具,可直接验证更新链路
- 版本号 1.2.2+14
2026-10-09 10:12:19 +08:00

187 lines
6.4 KiB
Dart
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
/// 应用内更新服务:从 Gitea 仓库的「发布(Releases)」检查新版本并下载更新包。
///
/// 服务器约定(当前仓库 http://124.220.63.9:30000/admin/Sequence-Diagram):
/// - 检查:`GET /api/v1/repos/{owner}/{repo}/releases/latest`(公开仓库,无需鉴权);
/// - 更新说明:使用 Release 的正文(Markdown);
/// - 安装包:使用 Release 附件——安卓为 `.apk`,Windows 为 `.zip`(绿色版整包)。
///
/// 采用 Release 附件而不是把安装包提交进 git:仓库历史不会被大文件撑大,
/// 客户端仍可通过稳定的下载地址获取(Gitea 会 302 到附件实际存储位置)。
library;
import 'dart:convert';
import 'dart:io';
import '../version.dart';
/// Gitea 服务器与仓库定位。
class UpdateServer {
/// 服务器根地址。
static const String host = 'http://124.220.63.9:30000';
/// 仓库拥有者。
static const String owner = 'admin';
/// 仓库名称。
static const String repo = 'Sequence-Diagram';
/// 版本检查接口(最新正式发布)。
static String get latestReleaseApi =>
'$host/api/v1/repos/$owner/$repo/releases/latest';
}
/// 一次可用的更新。
class UpdateInfo {
/// 构造。
const UpdateInfo({
required this.version,
required this.notes,
required this.assetName,
required this.assetUrl,
required this.assetSize,
});
/// 远端版本号(已去掉 `v` 前缀,如 `1.2.1`)。
final String version;
/// 更新说明(Markdown 文本)。
final String notes;
/// 安装包文件名(如 `sequence_diagram_android_v1.2.1_release.apk`)。
final String assetName;
/// 安装包下载地址。
final String assetUrl;
/// 安装包大小(字节;未知为 0)。
final int assetSize;
}
/// 版本比较:[remote] 是否比 [current] 更新。
///
/// 按点分数字段逐段比较,容忍 `v` 前缀与 `-` / `+` 后缀(如 `v1.2.1-rc1`)。
bool isNewerVersion(String remote, String current) {
List<int> parse(String v) {
final String core =
v.trim().replaceAll(RegExp(r'^[vV]'), '').split(RegExp(r'[-+]')).first;
final List<int> parts = <int>[];
for (final String s in core.split('.')) {
parts.add(int.tryParse(s) ?? 0);
}
return parts;
}
final List<int> a = parse(remote);
final List<int> b = parse(current);
final int n = a.length > b.length ? a.length : b.length;
for (int i = 0; i < n; i++) {
final int x = i < a.length ? a[i] : 0;
final int y = i < b.length ? b[i] : 0;
if (x != y) return x > y;
}
return false;
}
/// 更新服务:检查 + 下载。
class UpdateService {
UpdateService._();
/// 检查更新。
///
/// [currentVersion] 为当前版本(缺省用 [kAppVersion];自检工具可传入模拟值)。
/// 远端版本高于当前版本且存在当前平台的安装包时返回 [UpdateInfo];
/// 无更新(或尚未发布任何版本)返回 null;网络 / 服务器异常抛出 [Exception],
/// 由调用方决定是否静默。
static Future<UpdateInfo?> check({String? currentVersion}) async {
final String current = currentVersion ?? kAppVersion;
final HttpClient client = HttpClient()
..connectionTimeout = const Duration(seconds: 8);
try {
final HttpClientRequest req =
await client.getUrl(Uri.parse(UpdateServer.latestReleaseApi));
final HttpClientResponse res = await req.close();
if (res.statusCode == 404) return null; // 还没有任何发布
final String text = await res.transform(utf8.decoder).join();
if (res.statusCode != 200) {
throw Exception('服务器返回 ${res.statusCode}');
}
final Map<String, dynamic> j = jsonDecode(text) as Map<String, dynamic>;
final String tag = (j['tag_name'] as String?) ?? '';
if (!isNewerVersion(tag, current)) return null;
final String notes = (j['body'] as String?) ?? '';
// 选择当前平台的安装包:安卓取 .apk;Windows 优先 .zip(绿色版整包)。
bool isTarget(String n) {
final String l = n.toLowerCase();
if (Platform.isAndroid) return l.endsWith('.apk');
return l.endsWith('.zip');
}
final List<dynamic> assets =
(j['assets'] as List<dynamic>?) ?? const <dynamic>[];
String name = '';
String url = '';
int size = 0;
for (final dynamic a in assets) {
final Map<String, dynamic> m = a as Map<String, dynamic>;
final String an = (m['name'] as String?) ?? '';
if (an.isEmpty || !isTarget(an)) continue;
name = an;
url = (m['browser_download_url'] as String?) ?? '';
size = (m['size'] as num?)?.toInt() ?? 0;
break;
}
if (name.isEmpty || url.isEmpty) return null;
return UpdateInfo(
version: tag.trim().replaceAll(RegExp(r'^[vV]'), ''),
notes: notes,
assetName: name,
assetUrl: url,
assetSize: size,
);
} finally {
client.close(force: true);
}
}
/// 流式下载 [url] 到 [destPath]。
///
/// [onProgress] 回调 `(0..1 进度, 已接收字节)`;总长未知时进度为 -1。
/// [isCancelled] 返回 true 时中断下载并抛出「已取消」。
static Future<void> download({
required String url,
required String destPath,
void Function(double progress, int received)? onProgress,
bool Function()? isCancelled,
}) async {
final HttpClient client = HttpClient()
..connectionTimeout = const Duration(seconds: 15);
IOSink? sink;
try {
final HttpClientRequest req = await client.getUrl(Uri.parse(url));
final HttpClientResponse res = await req.close();
if (res.statusCode != 200) {
throw Exception('下载失败:服务器返回 ${res.statusCode}');
}
final int total = res.contentLength; // -1 表示未知
final File f = File(destPath);
await f.parent.create(recursive: true);
sink = f.openWrite();
int received = 0;
await for (final List<int> chunk in res) {
if (isCancelled?.call() ?? false) throw Exception('已取消');
sink.add(chunk);
received += chunk.length;
onProgress?.call(total > 0 ? received / total : -1, received);
}
await sink.flush();
await sink.close();
sink = null;
} finally {
if (sink != null) {
try {
await sink.close();
} catch (_) {}
}
client.close(force: true);
}
}
}