247 lines
9.8 KiB
Dart
247 lines
9.8 KiB
Dart
/// App 自动更新:版本检查 → 下载(进度条)→ 拉起系统安装器。
|
||
///
|
||
/// 版本号与 pubspec 的 version 同步维护(kAppVersion)。
|
||
/// 后端接口:GET /api/app/config(latest_version/min_version/notes/download_url),
|
||
/// GET /api/app/download 返回 APK 流。
|
||
library;
|
||
|
||
import 'package:dio/dio.dart';
|
||
import 'package:flutter/foundation.dart';
|
||
import 'package:flutter/material.dart';
|
||
import 'package:open_filex/open_filex.dart';
|
||
import 'package:path_provider/path_provider.dart';
|
||
|
||
import '../../core/network/api_client.dart';
|
||
import '../../core/theme/app_colors.dart';
|
||
|
||
const kAppVersion = '1.4.7'; // 与 pubspec.yaml version 同步
|
||
|
||
/// 比较语义化版本:a < b 返回 -1,> 返回 1,相等 0
|
||
int compareVersion(String a, String b) {
|
||
final pa = a.split('.').map((s) => int.tryParse(s) ?? 0).toList();
|
||
final pb = b.split('.').map((s) => int.tryParse(s) ?? 0).toList();
|
||
for (var i = 0; i < 3; i++) {
|
||
final x = i < pa.length ? pa[i] : 0;
|
||
final y = i < pb.length ? pb[i] : 0;
|
||
if (x != y) return x < y ? -1 : 1;
|
||
}
|
||
return 0;
|
||
}
|
||
|
||
/// 全局升级蒙版状态:非 null 时在 App 最顶层盖住一切(登录页/首页均被覆盖),
|
||
/// 必须处理(立即更新 或 非强制时的稍后再说)。
|
||
final ValueNotifier<Map<String, dynamic>?> updateGate = ValueNotifier(null);
|
||
|
||
/// 蒙版式升级层:挂在 MaterialApp.builder 最顶层,路由跳转不影响。
|
||
class UpdateGateOverlay extends StatelessWidget {
|
||
const UpdateGateOverlay({super.key, required this.child});
|
||
|
||
final Widget child;
|
||
|
||
@override
|
||
Widget build(BuildContext context) {
|
||
return ValueListenableBuilder<Map<String, dynamic>?>(
|
||
valueListenable: updateGate,
|
||
builder: (context, info, _) {
|
||
if (info == null) return child;
|
||
return Stack(
|
||
children: [
|
||
child,
|
||
Positioned.fill(child: UpdateGateCard(info: info)),
|
||
],
|
||
);
|
||
},
|
||
);
|
||
}
|
||
}
|
||
|
||
class UpdateGateCard extends StatefulWidget {
|
||
const UpdateGateCard({super.key, required this.info});
|
||
|
||
final Map<String, dynamic> info;
|
||
|
||
@override
|
||
State<UpdateGateCard> createState() => _UpdateGateCardState();
|
||
}
|
||
|
||
class _UpdateGateCardState extends State<UpdateGateCard> {
|
||
double _progress = -1; // -1 未开始;0~1 下载中;2 已拉起安装器
|
||
String? _err;
|
||
|
||
bool get _force => widget.info['force'] == true;
|
||
bool get _downloading => _progress >= 0 && _progress < 2;
|
||
|
||
Future<void> _downloadAndInstall() async {
|
||
setState(() => _err = null);
|
||
try {
|
||
final dir = await getTemporaryDirectory();
|
||
final filePath =
|
||
'${dir.path}/xuanlong-${widget.info['latest']}.apk';
|
||
setState(() => _progress = 0);
|
||
await Dio().download(
|
||
'${activeBaseUrl.value}${widget.info['url']}',
|
||
filePath,
|
||
onReceiveProgress: (n, total) {
|
||
if (total > 0) setState(() => _progress = n / total);
|
||
},
|
||
);
|
||
setState(() => _progress = 2);
|
||
final r = await OpenFilex.open(filePath,
|
||
type: 'application/vnd.android.package-archive');
|
||
if (r.type != ResultType.done) {
|
||
setState(() => _err = '无法拉起安装器(${r.message}),请检查"安装未知应用"权限');
|
||
} else if (!_force) {
|
||
// 非强制:装起安装器后放行;强制版保持蒙版直至 App 重启为新版
|
||
Future<void>.delayed(const Duration(seconds: 2),
|
||
() => updateGate.value = null);
|
||
}
|
||
} catch (e) {
|
||
setState(() {
|
||
_progress = -1;
|
||
_err = '下载失败:$e';
|
||
});
|
||
}
|
||
}
|
||
|
||
@override
|
||
Widget build(BuildContext context) {
|
||
return Material(
|
||
color: Colors.black87,
|
||
child: GestureDetector(
|
||
onTap: () {}, // 吸收点击,防止穿透到底层页面
|
||
child: Center(
|
||
child: Padding(
|
||
padding: const EdgeInsets.all(24),
|
||
child: Container(
|
||
constraints: const BoxConstraints(maxWidth: 420),
|
||
padding: const EdgeInsets.all(20),
|
||
decoration: BoxDecoration(
|
||
color: XlColors.surface,
|
||
borderRadius: BorderRadius.circular(16),
|
||
border: Border.all(color: XlColors.borderGold, width: 1.2),
|
||
),
|
||
child: Column(
|
||
mainAxisSize: MainAxisSize.min,
|
||
crossAxisAlignment: CrossAxisAlignment.start,
|
||
children: [
|
||
Row(children: [
|
||
Container(width: 4, height: 16, color: XlColors.gold),
|
||
const SizedBox(width: 8),
|
||
Text('发现新版本 v${widget.info['latest']}',
|
||
style: const TextStyle(
|
||
fontSize: 17,
|
||
fontWeight: FontWeight.w700,
|
||
color: XlColors.porcelain)),
|
||
]),
|
||
if ((widget.info['notes'] ?? '') != '')
|
||
Padding(
|
||
padding: const EdgeInsets.only(top: 10),
|
||
child: Text(widget.info['notes'],
|
||
style: const TextStyle(
|
||
fontSize: 13, color: XlColors.clay, height: 1.6)),
|
||
),
|
||
if ((widget.info['size'] ?? 0) > 0)
|
||
Padding(
|
||
padding: const EdgeInsets.only(top: 6),
|
||
child: Text('大小 ${(widget.info['size'] as int) ~/ 1048576}MB',
|
||
style:
|
||
const TextStyle(fontSize: 12, color: XlColors.clay)),
|
||
),
|
||
const SizedBox(height: 14),
|
||
if (_downloading)
|
||
Column(children: [
|
||
LinearProgressIndicator(value: _progress, color: XlColors.gold, minHeight: 4),
|
||
const SizedBox(height: 6),
|
||
Text('下载中 ${(_progress * 100).toStringAsFixed(0)}%',
|
||
style: const TextStyle(fontSize: 12, color: XlColors.goldLight)),
|
||
]),
|
||
if (_progress == 2)
|
||
const Text('已下载,请在系统安装器中确认安装',
|
||
style: TextStyle(fontSize: 12, color: XlColors.goldLight)),
|
||
if (_err != null)
|
||
Padding(
|
||
padding: const EdgeInsets.only(top: 8),
|
||
child: Text(_err!, style: const TextStyle(fontSize: 12, color: XlColors.rise)),
|
||
),
|
||
const SizedBox(height: 16),
|
||
Row(children: [
|
||
if (!_force && _progress == -1)
|
||
Expanded(
|
||
child: OutlinedButton(
|
||
onPressed: () => updateGate.value = null,
|
||
style: OutlinedButton.styleFrom(
|
||
side: const BorderSide(color: XlColors.clay)),
|
||
child: const Text('稍后再说',
|
||
style: TextStyle(fontSize: 14, color: XlColors.clay)),
|
||
),
|
||
),
|
||
if (!_force && _progress == -1) const SizedBox(width: 12),
|
||
Expanded(
|
||
child: FilledButton(
|
||
onPressed: _downloading ? null : _downloadAndInstall,
|
||
style: FilledButton.styleFrom(
|
||
backgroundColor: XlColors.vermilion,
|
||
padding: const EdgeInsets.symmetric(vertical: 12)),
|
||
child: Text(
|
||
_downloading ? '下载中…' : (_progress == 2 ? '重新拉起安装' : '立即更新'),
|
||
style: const TextStyle(fontSize: 14, color: Colors.white)),
|
||
),
|
||
),
|
||
]),
|
||
],
|
||
),
|
||
),
|
||
),
|
||
),
|
||
),
|
||
);
|
||
}
|
||
}
|
||
|
||
/// 拉取版本信息(失败抛异常,由调用方决定重试策略)。
|
||
/// 返回 null = 已是最新;非 null = 需要更新(含全部证据)。
|
||
Future<Map<String, dynamic>?> _fetchUpdate(ApiClient api) async {
|
||
final cfg = await api.get('/api/app/config');
|
||
final latest = (cfg['latest_version'] ?? '') as String;
|
||
final min = (cfg['min_version'] ?? '') as String;
|
||
debugPrint('[UpdateCheck] latest=' + latest + ' min=' + min + ' 当前=' + kAppVersion + ' url=' + (cfg['download_url'] ?? ''));
|
||
if (latest.isEmpty || compareVersion(kAppVersion, latest) >= 0) {
|
||
debugPrint('[UpdateCheck] 已是最新或无发布 → 不弹');
|
||
return null;
|
||
}
|
||
debugPrint('[UpdateCheck] 需要更新 → 弹窗');
|
||
return {
|
||
'latest': latest,
|
||
'force': min.isNotEmpty && compareVersion(kAppVersion, min) < 0,
|
||
'notes': (cfg['notes'] ?? '') as String,
|
||
'url': (cfg['download_url'] ?? '') as String,
|
||
'size': (cfg['size'] ?? 0) as int,
|
||
};
|
||
}
|
||
|
||
/// 冷启动必检:网络未就绪/后端暂不可达时每 5 秒重试,直到拿到明确结果
|
||
/// (成功获取版本信息)或达到上限(24 次 × 5s ≈ 2 分钟)。检查到新版立即置蒙版。
|
||
Future<void> pollUpdateAtStartup(ApiClient api) async {
|
||
for (var attempt = 1; attempt <= 24; attempt++) {
|
||
try {
|
||
final upd = await _fetchUpdate(api);
|
||
if (upd != null) updateGate.value = upd;
|
||
debugPrint('[UpdateCheck] 冷启动检查完成(第' + attempt.toString() + '次)');
|
||
return; // 拿到明确结果即结束
|
||
} catch (e) {
|
||
debugPrint('[UpdateCheck] 第' + attempt.toString() + '次失败: ' + e.toString());
|
||
await Future<void>.delayed(const Duration(seconds: 5));
|
||
}
|
||
}
|
||
}
|
||
|
||
/// 手动检查(设置页):单次,失败返回 null。
|
||
Future<Map<String, dynamic>?> checkUpdate(ApiClient api) async {
|
||
try {
|
||
return await _fetchUpdate(api);
|
||
} catch (e) {
|
||
debugPrint('[UpdateCheck] config请求失败: ' + e.toString());
|
||
return null;
|
||
}
|
||
}
|