feat(update): 应用内更新(检查/下载/安装)与发版流程;版本 1.2.0
- 工具栏新增检查更新按钮:启动静默检查,发现新版本时显示红色角标; 未检测到新版本或安装包时弹窗提示「当前已是最新版本」 - 更新源:Gitea Releases(说明 = Release 正文 Markdown;安装包 = 附件, 不进入 git 历史,仓库保持精简) - 安卓:下载 APK → FileProvider + 系统安装器直接覆盖安装(签名一致) - Windows:下载绿色版 zip → 解压 → 生成替换脚本,主程序退出后原地覆盖并自动重启 - 新增 lib/update/update_service.dart、lib/ui/update_dialog.dart、lib/version.dart - 安卓侧:REQUEST_INSTALL_PACKAGES + FileProvider + installApk/getCacheDir 通道 + androidx.core - 发版工具:scripts/publish_release.ps1(打包 dist、创建 Release、上传附件) - 测试:test/update_version_test.dart(版本比较 4 组);启动检查在测试环境自动跳过 - 版本号 1.2.0+12;BUILD-NOTES 补充应用内更新与发版流程
This commit is contained in:
+69
-1
@@ -22,11 +22,14 @@ import '../model/units.dart';
|
||||
import '../persistence/android_docs.dart';
|
||||
import '../state/app_controller.dart';
|
||||
import '../theme/tokens.dart';
|
||||
import '../update/update_service.dart';
|
||||
import '../version.dart';
|
||||
import 'ai_dialog.dart';
|
||||
import 'app_logo.dart';
|
||||
import 'canvas_overlays.dart';
|
||||
import 'canvas_view.dart';
|
||||
import 'dialogs.dart';
|
||||
import 'update_dialog.dart';
|
||||
|
||||
/// 应用外壳组件:承载主界面布局与文件/侧栏等交互逻辑。
|
||||
class AppShell extends StatefulWidget {
|
||||
@@ -94,13 +97,21 @@ class _AppShellState extends State<AppShell> {
|
||||
/// 右侧栏是否收起为贴边轨道。
|
||||
bool get _rightRail => !_rightDocked && !_rightFloat;
|
||||
|
||||
/// 订阅控制器变化以便刷新界面。
|
||||
/// 订阅控制器变化以便刷新界面;启动后延迟静默检查更新。
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
c.addListener(_onChange);
|
||||
// 延迟几秒再检查,避免与启动渲染争资源。
|
||||
WidgetsBinding.instance.addPostFrameCallback((_) => _autoCheckUpdate());
|
||||
}
|
||||
|
||||
// ---- 应用内更新状态 ----
|
||||
/// 检测到的新版本信息;为空表示暂无更新(或尚未检查 / 检查失败)。
|
||||
UpdateInfo? _update;
|
||||
/// 是否正在手动检查更新(防止重复点击)。
|
||||
bool _checkingUpdate = false;
|
||||
|
||||
/// 是否已完成一次按平台 / 屏幕宽度的默认布局初始化。
|
||||
bool _layoutInited = false;
|
||||
|
||||
@@ -431,6 +442,61 @@ class _AppShellState extends State<AppShell> {
|
||||
);
|
||||
}
|
||||
|
||||
// ===================== 应用内更新 =====================
|
||||
|
||||
/// 启动后静默检查更新:发现新版本时在工具栏按钮上显示红色角标。
|
||||
Future<void> _autoCheckUpdate() async {
|
||||
// 测试环境不发起网络检查(避免 pending timer 与真实请求)。
|
||||
if (Platform.environment['FLUTTER_TEST'] == 'true') return;
|
||||
await Future<void>.delayed(const Duration(seconds: 3));
|
||||
if (!mounted || _update != null) return;
|
||||
try {
|
||||
final UpdateInfo? info = await UpdateService.check();
|
||||
if (mounted && info != null) setState(() => _update = info);
|
||||
} catch (_) {
|
||||
// 静默失败:不打扰用户
|
||||
}
|
||||
}
|
||||
|
||||
/// 更新检查按钮:检测到新版本时叠加红色角标。
|
||||
Widget _updateBtn(Tokens t) {
|
||||
final UpdateInfo? info = _update;
|
||||
final Widget btn = _iconBtn(t, Icons.system_update_alt, _openUpdate,
|
||||
tooltip: info == null ? '检查更新' : '发现新版本 v${info.version}');
|
||||
if (info == null) return btn;
|
||||
return Badge(backgroundColor: t.danger, smallSize: 8, child: btn);
|
||||
}
|
||||
|
||||
/// 打开更新对话框:已有检测结果时直接弹出,否则先检查一次。
|
||||
Future<void> _openUpdate() async {
|
||||
if (_checkingUpdate) return;
|
||||
UpdateInfo? info = _update;
|
||||
if (info == null) {
|
||||
_checkingUpdate = true;
|
||||
c.setStatus('正在检查更新…');
|
||||
try {
|
||||
info = await UpdateService.check();
|
||||
} catch (e) {
|
||||
if (mounted) c.setStatus('检查更新失败:$e');
|
||||
} finally {
|
||||
_checkingUpdate = false;
|
||||
}
|
||||
if (!mounted) return;
|
||||
if (info == null) {
|
||||
// 没有更新的说明与安装包:明确提示当前已是最新版本。
|
||||
c.setStatus('已是最新版本(v$kAppVersion)');
|
||||
await showMessage(context, '检查更新', '当前已是最新版本(v$kAppVersion)。');
|
||||
return;
|
||||
}
|
||||
setState(() => _update = info);
|
||||
}
|
||||
if (!mounted) return;
|
||||
await showDialog<void>(
|
||||
context: context,
|
||||
builder: (_) => UpdateDialog(controller: c, info: info!),
|
||||
);
|
||||
}
|
||||
|
||||
// ===================== 工具栏(自适应 / 紧凑) =====================
|
||||
|
||||
/// 构建顶部工具栏:左侧为品牌与文件/编辑操作,右侧为导出、缩放、
|
||||
@@ -522,6 +588,7 @@ class _AppShellState extends State<AppShell> {
|
||||
sideToggleRight,
|
||||
_iconBtn(t, Icons.help_outline, () =>
|
||||
showDialog<void>(context: context, builder: (_) => const HelpDialog()), tooltip: '帮助 F1'),
|
||||
_updateBtn(t),
|
||||
_themeToggle(t),
|
||||
];
|
||||
} else {
|
||||
@@ -561,6 +628,7 @@ class _AppShellState extends State<AppShell> {
|
||||
sideToggleRight,
|
||||
_iconBtn(t, Icons.help_outline, () =>
|
||||
showDialog<void>(context: context, builder: (_) => const HelpDialog()), tooltip: '帮助 F1'),
|
||||
_updateBtn(t),
|
||||
_themeToggle(t),
|
||||
];
|
||||
}
|
||||
|
||||
+1
-1
@@ -2124,7 +2124,7 @@ class HelpDialog extends StatelessWidget {
|
||||
Text('时序图设计 · Sequence Diagram Studio',
|
||||
style: TextStyle(color: t.text, fontSize: 15, fontWeight: FontWeight.w700)),
|
||||
const SizedBox(height: 4),
|
||||
Text('V1.1.0(${android ? '安卓版' : 'Windows 版'})',
|
||||
Text('V1.2.0(${android ? '安卓版' : 'Windows 版'})',
|
||||
style: TextStyle(color: t.dim, fontSize: 12)),
|
||||
],
|
||||
),
|
||||
|
||||
@@ -0,0 +1,319 @@
|
||||
/// 应用内更新对话框。
|
||||
///
|
||||
/// 展示新版本号、更新说明(Release 正文即为 Markdown 文本)与安装包信息;
|
||||
/// 底部提供「立即更新」按钮与下载进度条:
|
||||
/// - Android:下载 APK 到应用缓存目录,经 FileProvider 交给系统安装程序;
|
||||
/// - Windows:下载绿色版整包(zip),解压后生成替换脚本——等待本程序退出、
|
||||
/// 原地覆盖 dist 目录并自动重启,无需安装。
|
||||
library;
|
||||
|
||||
import 'dart:io';
|
||||
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter/services.dart';
|
||||
|
||||
import '../state/app_controller.dart';
|
||||
import '../theme/tokens.dart';
|
||||
import '../update/update_service.dart';
|
||||
import '../version.dart';
|
||||
import 'dialogs.dart';
|
||||
|
||||
/// 应用内更新对话框。
|
||||
class UpdateDialog extends StatefulWidget {
|
||||
/// 构造;[info] 为本次检测到的更新信息。
|
||||
const UpdateDialog({super.key, required this.controller, required this.info});
|
||||
|
||||
/// 全局应用控制器(用于状态栏提示)。
|
||||
final AppController controller;
|
||||
|
||||
/// 更新信息。
|
||||
final UpdateInfo info;
|
||||
|
||||
@override
|
||||
State<UpdateDialog> createState() => _UpdateDialogState();
|
||||
}
|
||||
|
||||
class _UpdateDialogState extends State<UpdateDialog> {
|
||||
/// 与安卓原生桥接(复用现有 `seqstudio/docs` 通道)。
|
||||
static const MethodChannel _channel = MethodChannel('seqstudio/docs');
|
||||
|
||||
bool _busy = false;
|
||||
bool _cancelled = false;
|
||||
bool _done = false;
|
||||
double _progress = -1;
|
||||
int _received = 0;
|
||||
String _status = '';
|
||||
String? _error;
|
||||
|
||||
/// 「立即更新」:按平台执行下载与安装 / 覆盖更新。
|
||||
Future<void> _start() async {
|
||||
setState(() {
|
||||
_busy = true;
|
||||
_error = null;
|
||||
_cancelled = false;
|
||||
_done = false;
|
||||
_progress = -1;
|
||||
_received = 0;
|
||||
_status = '正在下载更新包…';
|
||||
});
|
||||
try {
|
||||
if (Platform.isAndroid) {
|
||||
await _updateAndroid();
|
||||
} else if (Platform.isWindows) {
|
||||
await _updateWindows();
|
||||
} else {
|
||||
throw Exception('当前平台暂不支持应用内更新');
|
||||
}
|
||||
} catch (e) {
|
||||
if (mounted) {
|
||||
setState(() {
|
||||
_error = '$e';
|
||||
_busy = false;
|
||||
});
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (mounted) setState(() => _busy = false);
|
||||
}
|
||||
|
||||
/// 安卓:下载 APK → 交给系统安装程序。
|
||||
Future<void> _updateAndroid() async {
|
||||
final String? dir = await _channel.invokeMethod<String>('getCacheDir');
|
||||
if (dir == null || dir.isEmpty) throw Exception('无法获取应用缓存目录');
|
||||
final String dest = '$dir${Platform.pathSeparator}${widget.info.assetName}';
|
||||
await UpdateService.download(
|
||||
url: widget.info.assetUrl,
|
||||
destPath: dest,
|
||||
isCancelled: () => _cancelled,
|
||||
onProgress: _onProgress,
|
||||
);
|
||||
if (_cancelled) throw Exception('已取消');
|
||||
if (mounted) setState(() => _status = '正在启动系统安装程序…');
|
||||
await _channel.invokeMethod<bool>('installApk', <String, dynamic>{'path': dest});
|
||||
if (mounted) {
|
||||
setState(() {
|
||||
_status = '已交给系统安装程序,请在弹出的界面完成安装。';
|
||||
_done = true;
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/// Windows:下载绿色版整包 → 解压 → 生成替换脚本 → 退出并自动重启。
|
||||
Future<void> _updateWindows() async {
|
||||
final Directory tmp = await Directory.systemTemp.createTemp('seq_update_');
|
||||
final String zipPath = '${tmp.path}\\update.zip';
|
||||
await UpdateService.download(
|
||||
url: widget.info.assetUrl,
|
||||
destPath: zipPath,
|
||||
isCancelled: () => _cancelled,
|
||||
onProgress: _onProgress,
|
||||
);
|
||||
if (_cancelled) throw Exception('已取消');
|
||||
|
||||
if (mounted) setState(() => _status = '正在解压更新包…');
|
||||
final String extractDir = '${tmp.path}\\app';
|
||||
await Directory(extractDir).create(recursive: true);
|
||||
final ProcessResult r =
|
||||
await Process.run('tar', <String>['-xf', zipPath, '-C', extractDir]);
|
||||
if (r.exitCode != 0) throw Exception('解压失败:${r.stderr}');
|
||||
|
||||
// 兼容两种打包方式:zip 根目录即程序文件,或多包一层 dist/。
|
||||
String srcDir = extractDir;
|
||||
if (!File('$extractDir\\sequence_diagram.exe').existsSync()) {
|
||||
if (File('$extractDir\\dist\\sequence_diagram.exe').existsSync()) {
|
||||
srcDir = '$extractDir\\dist';
|
||||
} else {
|
||||
throw Exception('更新包内容不完整(未找到 sequence_diagram.exe)');
|
||||
}
|
||||
}
|
||||
|
||||
if (mounted) setState(() => _status = '正在准备覆盖更新…');
|
||||
final String appDir = File(Platform.resolvedExecutable).parent.path;
|
||||
final String batPath = '${tmp.path}\\apply_update.bat';
|
||||
// 生成替换脚本:等待本程序退出 → 原地覆盖 → 重新启动。
|
||||
// 内容保持纯 ASCII,源/目标路径通过参数传入(cmd 以 UTF-16 接收参数,
|
||||
// 中文安装路径也能正确处理);脚本文件本身不包含路径,避免编码问题。
|
||||
File(batPath).writeAsStringSync(
|
||||
'@echo off\r\n'
|
||||
':wait\r\n'
|
||||
'tasklist /fi "IMAGENAME eq sequence_diagram.exe" | find /i "sequence_diagram.exe" >nul\r\n'
|
||||
'if not errorlevel 1 (\r\n'
|
||||
' ping -n 1 -w 600 127.0.0.1 >nul\r\n'
|
||||
' goto wait\r\n'
|
||||
')\r\n'
|
||||
'xcopy /e /i /y /q "%~1\\*" "%~2\\"\r\n'
|
||||
'start "" "%~2\\sequence_diagram.exe"\r\n'
|
||||
'del "%~f0"\r\n',
|
||||
flush: true,
|
||||
);
|
||||
await Process.start(
|
||||
'cmd',
|
||||
<String>['/c', batPath, srcDir, appDir],
|
||||
mode: ProcessStartMode.detached,
|
||||
);
|
||||
if (mounted) {
|
||||
setState(() {
|
||||
_status = '更新就绪,软件即将重启完成覆盖…';
|
||||
_done = true;
|
||||
});
|
||||
}
|
||||
await Future<void>.delayed(const Duration(milliseconds: 900));
|
||||
exit(0);
|
||||
}
|
||||
|
||||
/// 下载进度回调:刷新进度条与状态文本。
|
||||
void _onProgress(double progress, int received) {
|
||||
if (!mounted) return;
|
||||
setState(() {
|
||||
_progress = progress;
|
||||
_received = received;
|
||||
});
|
||||
}
|
||||
|
||||
/// 取消 / 关闭按钮:下载中先中断下载。
|
||||
void _cancel() {
|
||||
_cancelled = true;
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final Tokens t = context.tok;
|
||||
final UpdateInfo info = widget.info;
|
||||
final String sizeText = info.assetSize > 0
|
||||
? '${(info.assetSize / 1048576).toStringAsFixed(1)} MB'
|
||||
: '';
|
||||
return Dialog(
|
||||
backgroundColor: t.dialog,
|
||||
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(14)),
|
||||
child: scaledDialogBox(
|
||||
context,
|
||||
620,
|
||||
560,
|
||||
Padding(
|
||||
padding: const EdgeInsets.all(18),
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: <Widget>[
|
||||
// 标题
|
||||
Row(
|
||||
children: <Widget>[
|
||||
Icon(Icons.system_update_alt, size: 21, color: t.accent),
|
||||
const SizedBox(width: 8),
|
||||
Text('发现新版本 v${info.version}',
|
||||
style: TextStyle(color: t.text, fontSize: 17, fontWeight: FontWeight.w700)),
|
||||
const Spacer(),
|
||||
Text('当前 v$kAppVersion', style: TextStyle(color: t.dim, fontSize: 11.5)),
|
||||
],
|
||||
),
|
||||
const SizedBox(height: 4),
|
||||
Text(
|
||||
'安装包:${info.assetName}${sizeText.isEmpty ? '' : '($sizeText)'}',
|
||||
style: TextStyle(color: t.dim, fontSize: 11),
|
||||
maxLines: 1,
|
||||
overflow: TextOverflow.ellipsis,
|
||||
),
|
||||
const Divider(height: 20),
|
||||
|
||||
// 更新说明(Release 正文)
|
||||
Text('更新内容', style: TextStyle(color: t.sub, fontSize: 12.5, fontWeight: FontWeight.w600)),
|
||||
const SizedBox(height: 6),
|
||||
Expanded(
|
||||
child: Container(
|
||||
width: double.infinity,
|
||||
padding: const EdgeInsets.all(12),
|
||||
decoration: BoxDecoration(
|
||||
color: t.panel2,
|
||||
borderRadius: BorderRadius.circular(10),
|
||||
border: Border.all(color: t.line2),
|
||||
),
|
||||
child: SingleChildScrollView(
|
||||
child: SelectableText(
|
||||
info.notes.trim().isEmpty ? '(本次更新未提供说明)' : info.notes,
|
||||
style: TextStyle(color: t.text, fontSize: 12.5, height: 1.7),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
|
||||
// 进度 / 状态 / 错误
|
||||
if (_busy || _done) ...<Widget>[
|
||||
const SizedBox(height: 12),
|
||||
ClipRRect(
|
||||
borderRadius: BorderRadius.circular(3),
|
||||
child: LinearProgressIndicator(
|
||||
value: _done ? 1 : (_progress >= 0 ? _progress : null),
|
||||
minHeight: 5,
|
||||
color: t.accent2,
|
||||
backgroundColor: t.line2,
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 6),
|
||||
Row(
|
||||
children: <Widget>[
|
||||
Expanded(
|
||||
child: Text(_status, style: TextStyle(color: t.sub, fontSize: 12)),
|
||||
),
|
||||
if (_busy && _progress >= 0)
|
||||
Text('${(_progress * 100).clamp(0, 100).toStringAsFixed(0)}% · '
|
||||
'${(_received / 1048576).toStringAsFixed(1)} MB',
|
||||
style: TextStyle(color: t.dim, fontSize: 11)),
|
||||
],
|
||||
),
|
||||
],
|
||||
if (_error != null) ...<Widget>[
|
||||
const SizedBox(height: 10),
|
||||
Container(
|
||||
width: double.infinity,
|
||||
padding: const EdgeInsets.all(10),
|
||||
decoration: BoxDecoration(
|
||||
color: _error == '已取消' ? t.panel2 : t.danger.withValues(alpha: 0.12),
|
||||
borderRadius: BorderRadius.circular(8),
|
||||
border: Border.all(
|
||||
color: _error == '已取消' ? t.line2 : t.danger.withValues(alpha: 0.5)),
|
||||
),
|
||||
child: Text(_error!,
|
||||
style: TextStyle(
|
||||
color: _error == '已取消' ? t.sub : t.danger,
|
||||
fontSize: 12,
|
||||
height: 1.5)),
|
||||
),
|
||||
],
|
||||
const SizedBox(height: 14),
|
||||
|
||||
// 操作按钮
|
||||
Row(
|
||||
children: <Widget>[
|
||||
Expanded(
|
||||
child: Text(
|
||||
Platform.isAndroid ? '下载后由系统安装程序完成安装(签名一致可直接覆盖)' : '绿色版原地覆盖,软件会自动重启',
|
||||
style: TextStyle(color: t.dim, fontSize: 11),
|
||||
),
|
||||
),
|
||||
TextButton(
|
||||
onPressed: () {
|
||||
if (_busy) _cancel();
|
||||
Navigator.pop(context);
|
||||
},
|
||||
child: Text(_busy ? '取消下载' : '关闭'),
|
||||
),
|
||||
const SizedBox(width: 8),
|
||||
FilledButton.icon(
|
||||
onPressed: _busy || _done ? null : _start,
|
||||
icon: const Icon(Icons.download, size: 16),
|
||||
label: Text(_done ? '已完成' : '立即更新'),
|
||||
style: FilledButton.styleFrom(
|
||||
backgroundColor: t.accent2,
|
||||
foregroundColor: Colors.white,
|
||||
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(9)),
|
||||
padding: const EdgeInsets.symmetric(horizontal: 18, vertical: 12),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,184 @@
|
||||
/// 应用内更新服务:从 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._();
|
||||
|
||||
/// 检查更新。
|
||||
///
|
||||
/// 远端版本高于 [kAppVersion] 且存在当前平台的安装包时返回 [UpdateInfo];
|
||||
/// 无更新(或尚未发布任何版本)返回 null;网络 / 服务器异常抛出 [Exception],
|
||||
/// 由调用方决定是否静默。
|
||||
static Future<UpdateInfo?> check() async {
|
||||
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, kAppVersion)) 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);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
/// 应用版本号(与 `pubspec.yaml` 的 version 保持一致)。
|
||||
///
|
||||
/// 应用内更新检查用它判断服务器发布的版本是否更新;
|
||||
/// **每次发版必须与 pubspec 同步更新**(见 BUILD-NOTES 的发布流程)。
|
||||
const String kAppVersion = '1.2.0';
|
||||
Reference in New Issue
Block a user