基于自定义规则的番剧采集APP,支持流媒体在线观看,支持弹幕,支持实时超分辨率。
feat(update): let users pick the update download source (#2667)
文质彬彬的大锤4960f9c04246
diff --git a/lib/bean/dialog/update_available_dialog.dart b/lib/bean/dialog/update_available_dialog.dartnew file mode 100644index 00000000..f5d175fe--- /dev/null+++ b/lib/bean/dialog/update_available_dialog.dart@@ -0,0 +1,248 @@+import 'package:flutter/material.dart';+import 'package:kazumi/bean/dialog/dialog.dart';+import 'package:kazumi/bean/settings/settings_dropdown_tile.dart';+import 'package:kazumi/bean/settings/settings_list.dart';+import 'package:kazumi/bean/widget/state_presentation.dart';+import 'package:kazumi/bean/widget/tonal_card.dart';+import 'package:kazumi/services/update/auto_updater.dart';+import 'package:kazumi/services/update/update_download_source.dart';+import 'package:kazumi/utils/date_time.dart';+import 'package:url_launcher/url_launcher.dart';++typedef UpdateDialogChoice = ({+ InstallationType type,+ UpdateDownloadSource source,+});++/// Pops with an [UpdateDialogChoice] when the user starts the update.+class UpdateAvailableDialog extends StatefulWidget {+ const UpdateAvailableDialog({+ super.key,+ required this.updateInfo,+ this.onDisableAutoUpdateChanged,+ });++ final UpdateInfo updateInfo;++ /// Shows the auto-update opt-out when non-null.+ final ValueChanged<bool>? onDisableAutoUpdateChanged;++ @override+ State<UpdateAvailableDialog> createState() => _UpdateAvailableDialogState();+}++class _UpdateAvailableDialogState extends State<UpdateAvailableDialog> {+ final _notesController = ScrollController();+ var _source = UpdateDownloadSource.mirror;+ late var _type = widget.updateInfo.recommendedInstallationType;+ var _disableAutoUpdate = false;++ @override+ void dispose() {+ _notesController.dispose();+ super.dispose();+ }++ @override+ Widget build(BuildContext context) {+ final theme = Theme.of(context);+ final colors = theme.colorScheme;+ final downloadInApp = _type.downloadsInApp;++ return AlertDialog(+ constraints: const BoxConstraints(minWidth: 280, maxWidth: 440),+ insetPadding: const EdgeInsets.all(24),+ backgroundColor: colors.surfaceContainerHigh,+ surfaceTintColor: Colors.transparent,+ shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(28)),+ clipBehavior: Clip.antiAlias,+ scrollable: true,+ titlePadding: const EdgeInsets.fromLTRB(24, 24, 24, 0),+ title: _buildHeader(context, downloadInApp),+ contentPadding: const EdgeInsets.fromLTRB(24, 16, 24, 16),+ content: SizedBox(+ width: 392,+ child: Column(+ mainAxisSize: MainAxisSize.min,+ crossAxisAlignment: CrossAxisAlignment.stretch,+ children: [+ _buildReleaseNotes(context),+ if (downloadInApp) ...[+ const SizedBox(height: 20),+ _buildDownloadOptions(),+ ],+ if (widget.onDisableAutoUpdateChanged != null) ...[+ const SizedBox(height: 8),+ CheckboxListTile(+ value: _disableAutoUpdate,+ onChanged: (value) {+ setState(() => _disableAutoUpdate = value ?? false);+ widget.onDisableAutoUpdateChanged!(_disableAutoUpdate);+ },+ dense: true,+ visualDensity: VisualDensity.compact,+ controlAffinity: ListTileControlAffinity.leading,+ contentPadding: EdgeInsets.zero,+ shape: RoundedRectangleBorder(+ borderRadius: BorderRadius.circular(12),+ ),+ title: Text('不再自动检查', style: theme.textTheme.bodyMedium),+ ),+ ],+ ],+ ),+ ),+ actionsPadding: const EdgeInsets.fromLTRB(24, 0, 24, 24),+ actionsOverflowButtonSpacing: 8,+ actions: [+ TextButton(+ style: TextButton.styleFrom(minimumSize: const Size(64, 48)),+ onPressed: () => KazumiDialog.dismiss(context: context),+ child: const Text('稍后'),+ ),+ StateActionButton(+ onPressed: () => KazumiDialog.dismiss(+ context: context,+ popWith: (type: _type, source: _source),+ ),+ icon: downloadInApp+ ? Icons.download_rounded+ : Icons.open_in_new_rounded,+ text: downloadInApp ? '更新' : '前往下载',+ ),+ ],+ );+ }++ Widget _buildHeader(BuildContext context, bool downloadInApp) {+ final theme = Theme.of(context);+ final colors = theme.colorScheme;+ final info = widget.updateInfo;+ // The fallback action already opens the release page.+ final showReleasePage = downloadInApp && info.releaseNotes.isNotEmpty;++ return Row(+ children: [+ StateIconBadge(+ icon: Icons.system_update_alt_rounded,+ size: 48,+ iconSize: 24,+ backgroundColor: colors.primaryContainer,+ foregroundColor: colors.onPrimaryContainer,+ ),+ const SizedBox(width: 16),+ Expanded(+ child: Column(+ crossAxisAlignment: CrossAxisAlignment.start,+ children: [+ Text(+ '发现新版本',+ style: theme.textTheme.headlineSmall?.copyWith(+ color: colors.onSurface,+ fontWeight: FontWeight.w600,+ ),+ ),+ const SizedBox(height: 4),+ Wrap(+ crossAxisAlignment: WrapCrossAlignment.center,+ spacing: 8,+ runSpacing: 4,+ children: [+ Container(+ padding:+ const EdgeInsets.symmetric(horizontal: 10, vertical: 2),+ decoration: BoxDecoration(+ color: colors.secondaryContainer,+ borderRadius: BorderRadius.circular(8),+ ),+ child: Text(+ info.version,+ style: theme.textTheme.labelLarge?.copyWith(+ color: colors.onSecondaryContainer,+ ),+ ),+ ),+ if (info.publishedAt.isNotEmpty)+ Text(+ formatDate(info.publishedAt),+ style: theme.textTheme.bodyMedium?.copyWith(+ color: colors.onSurfaceVariant,+ ),+ ),+ if (showReleasePage)+ TextButton.icon(+ style: TextButton.styleFrom(+ visualDensity: VisualDensity.compact,+ tapTargetSize: MaterialTapTargetSize.shrinkWrap,+ padding: const EdgeInsets.symmetric(horizontal: 8),+ ),+ onPressed: () => launchUrl(+ Uri.parse(info.releaseNotes),+ mode: LaunchMode.externalApplication,+ ),+ iconAlignment: IconAlignment.end,+ icon: const Icon(Icons.open_in_new_rounded, size: 16),+ label: const Text('更新日志'),+ ),+ ],+ ),+ ],+ ),+ ),+ ],+ );+ }++ Widget _buildReleaseNotes(BuildContext context) {+ final theme = Theme.of(context);+ final maxHeight =+ (MediaQuery.sizeOf(context).height * 0.22).clamp(96.0, 180.0);++ return TonalCard(+ padding: const EdgeInsets.fromLTRB(16, 12, 4, 12),+ child: ConstrainedBox(+ constraints: BoxConstraints(maxHeight: maxHeight),+ child: Scrollbar(+ controller: _notesController,+ child: SingleChildScrollView(+ controller: _notesController,+ padding: const EdgeInsets.only(right: 12),+ child: Text(+ widget.updateInfo.description.trim(),+ style: theme.textTheme.bodyMedium?.copyWith(+ color: theme.colorScheme.onSurfaceVariant,+ ),+ ),+ ),+ ),+ ),+ );+ }++ Widget _buildDownloadOptions() {+ final types = widget.updateInfo.availableInstallationTypes;+ return SettingsSection(+ margin: EdgeInsets.zero,+ tiles: [+ SettingsDropdownTile<UpdateDownloadSource>(+ leading: Icons.cloud_download_rounded,+ title: const Text('下载源'),+ value: _source,+ options: {+ for (final source in UpdateDownloadSource.values)+ source: source.label,+ },+ onChanged: (source) => setState(() => _source = source),+ ),+ if (types.length > 1)+ SettingsDropdownTile<InstallationType>(+ leading: Icons.inventory_2_rounded,+ title: const Text('安装类型'),+ value: _type,+ options: {for (final type in types) type: type.label},+ onChanged: (type) => setState(() => _type = type),+ ),+ ],+ );+ }+}diff --git a/lib/request/core/network_error_mapper.dart b/lib/request/core/network_error_mapper.dartindex a26730f8..8410b349 100644--- a/lib/request/core/network_error_mapper.dart+++ b/lib/request/core/network_error_mapper.dart@@ -66,7 +66,12 @@ class NetworkErrorMapper {stackTrace: error.stackTrace,);case DioExceptionType.unknown:- final connection = await _connectionLabel();+ var connection = '';+ try {+ connection = await _connectionLabel().timeout(+ const Duration(seconds: 1),+ );+ } catch (_) {}return NetworkException(type: NetworkExceptionType.unknown,message: '$connection 网络异常'.trimLeft(),diff --git a/lib/services/update/auto_updater.dart b/lib/services/update/auto_updater.dartindex 7c4b2749..bed98c4c 100644--- a/lib/services/update/auto_updater.dart+++ b/lib/services/update/auto_updater.dart@@ -3,27 +3,35 @@ import 'dart:io';import 'package:dio/dio.dart';import 'package:flutter/material.dart';import 'package:kazumi/bean/dialog/dialog_helper.dart';+import 'package:kazumi/bean/dialog/update_available_dialog.dart';import 'package:kazumi/request/clients/download_http_client.dart';import 'package:kazumi/request/config/api_endpoints.dart';import 'package:kazumi/services/logging/logger.dart';+import 'package:kazumi/services/update/update_download_source.dart';+import 'package:kazumi/services/update/update_downloader.dart';import 'package:kazumi/services/storage/storage.dart';import 'package:open_filex/open_filex.dart';import 'package:path_provider/path_provider.dart';import 'package:url_launcher/url_launcher.dart';import 'package:kazumi/utils/device.dart';-import 'package:kazumi/utils/date_time.dart';-import 'package:kazumi/utils/crypto.dart';import 'package:kazumi/utils/version.dart';enum InstallationType {- windowsMsix,- windowsPortable,- linuxDeb,- linuxTar,- macosDmg,- androidApk,- ios,- unknown,+ windowsMsix('MSIX'),+ windowsPortable('ZIP'),+ linuxDeb('DEB'),+ linuxTar('TAR'),+ macosDmg('DMG'),+ androidApk('APK'),+ ios('IPA'),+ unknown('未知类型');++ const InstallationType(this.label);++ final String label;++ /// Types without a matching asset are updated from the release page.+ bool get downloadsInApp => getUpdateFilePatterns(this).isNotEmpty;}class UpdateInfo {@@ -69,17 +77,6 @@ Map<String, dynamic>? getUpdateAssetForType(}}-String getUpdateDownloadUrlFromAsset(Map<String, dynamic>? asset) {- if (asset == null) {- return '';- }- final mirrorUrl = asset['mirror_download_url'] as String? ?? '';- if (mirrorUrl.isNotEmpty) {- return mirrorUrl;- }- return asset['browser_download_url'] as String? ?? '';-}-String getUpdateFileHashFromAsset(Map<String, dynamic> asset) {final digest = asset['digest'] as String? ?? '';if (digest.startsWith('sha256:')) {@@ -197,175 +194,30 @@ class AutoUpdater {}}- void _showUpdateDialog(UpdateInfo updateInfo, {bool isAutoCheck = false}) {- KazumiDialog.show(- builder: (context) {- return AlertDialog(- title: Text('发现新版本 ${updateInfo.version}'),- content: SingleChildScrollView(- child: Column(- mainAxisSize: MainAxisSize.min,- crossAxisAlignment: CrossAxisAlignment.start,- children: [- Text(updateInfo.description),- if (updateInfo.publishedAt.isNotEmpty) ...[- const SizedBox(height: 8),- Text(- '发布时间: ${formatDate(updateInfo.publishedAt)}',- style: Theme.of(context).textTheme.bodySmall,- ),- ],- const SizedBox(height: 8),- if (!Platform.isLinux && !Platform.isIOS) ...[- Container(- padding: const EdgeInsets.all(8),- decoration: BoxDecoration(- color:- Theme.of(context).colorScheme.surfaceContainerHighest,- borderRadius: BorderRadius.circular(4),- ),- child: Column(- crossAxisAlignment: CrossAxisAlignment.start,- children: [- Text(- '选择安装类型:',- style: Theme.of(context).textTheme.labelSmall,- ),- const SizedBox(height: 8),- ...updateInfo.availableInstallationTypes.map((type) {- return Container(- margin: const EdgeInsets.symmetric(vertical: 2),- child: Material(- color: Colors.transparent,- child: InkWell(- borderRadius: BorderRadius.circular(4),- onTap: () {- KazumiDialog.dismiss();- _downloadUpdateWithType(updateInfo, type);- },- child: Container(- padding: const EdgeInsets.symmetric(- horizontal: 12, vertical: 8),- decoration: BoxDecoration(- border: Border.all(- color: Theme.of(context)- .colorScheme- .outline- .withValues(alpha: 0.3),- ),- borderRadius: BorderRadius.circular(4),- ),- child: Row(- children: [- Icon(- Icons.download,- size: 16,- color: Theme.of(context)- .colorScheme- .primary,- ),- const SizedBox(width: 8),- Expanded(- child: Text(- _getInstallationTypeDescription(type),- style: Theme.of(context)- .textTheme- .bodySmall,- ),- ),- Icon(- Icons.arrow_forward_ios,- size: 12,- color: Theme.of(context)- .colorScheme- .outline,- ),- ],- ),- ),- ),- ),- );- }),- ],- ),- ),- ],- ],- ),- ),- actions: [- if (isAutoCheck)- TextButton(- onPressed: () {- GStorage.putSetting(SettingsKeys.autoUpdate, false);- KazumiDialog.dismiss();- KazumiDialog.showToast(message: '已关闭自动更新');- },- child: Text(- '关闭自动更新',- style:- TextStyle(color: Theme.of(context).colorScheme.outline),- ),- ),- TextButton(- onPressed: () => KazumiDialog.dismiss(),- child: Text(- '稍后提醒',- style: TextStyle(color: Theme.of(context).colorScheme.outline),- ),- ),- if (updateInfo.releaseNotes.isNotEmpty)- TextButton(- onPressed: () {- launchUrl(Uri.parse(updateInfo.releaseNotes),- mode: LaunchMode.externalApplication);- },- child: const Text('查看详情'),- ),- TextButton(- onPressed: () {- KazumiDialog.dismiss();- if (updateInfo.availableInstallationTypes.isNotEmpty) {- _downloadUpdateWithType(- updateInfo, updateInfo.availableInstallationTypes.first);- }- },- child: const Text('立即更新'),- ),- ],- );- },+ Future<void> _showUpdateDialog(UpdateInfo updateInfo,+ {bool isAutoCheck = false}) async {+ var disableAutoUpdate = false;+ final choice = await KazumiDialog.show<UpdateDialogChoice>(+ builder: (context) => UpdateAvailableDialog(+ updateInfo: updateInfo,+ onDisableAutoUpdateChanged:+ isAutoCheck ? (value) => disableAutoUpdate = value : null,+ ),);- }-- String _getInstallationTypeDescription(InstallationType type) {- switch (type) {- case InstallationType.windowsMsix:- return 'Windows MSIX 包';- case InstallationType.windowsPortable:- return 'Windows 便携版 (ZIP)';- case InstallationType.linuxDeb:- return 'Linux DEB 包';- case InstallationType.linuxTar:- return 'Linux TAR 包';- case InstallationType.macosDmg:- return 'macOS DMG 镜像';- case InstallationType.androidApk:- return 'Android APK';- case InstallationType.ios:- return 'iOS ipa';- case InstallationType.unknown:- return '未知安装类型';+ if (disableAutoUpdate) {+ GStorage.putSetting(SettingsKeys.autoUpdate, false);+ KazumiDialog.showToast(message: '已关闭自动更新');+ }+ if (choice != null) {+ _downloadUpdateWithType(updateInfo, choice.type, choice.source);}}Future<void> _downloadUpdateWithType(- UpdateInfo updateInfo, InstallationType selectedType) async {+ UpdateInfo updateInfo, InstallationType selectedType,+ UpdateDownloadSource source) async {try {- if (selectedType == InstallationType.ios ||- selectedType == InstallationType.linuxDeb ||- selectedType == InstallationType.linuxTar) {+ if (!selectedType.downloadsInApp) {String releaseUrl = updateInfo.releaseNotes;if (releaseUrl.isEmpty) {releaseUrl = ApiEndpoints.latestApp;@@ -375,11 +227,9 @@ class AutoUpdater {}final asset = getUpdateAssetForType(updateInfo.assets, selectedType);- final downloadUrl = getUpdateDownloadUrlFromAsset(asset);+ final downloadUrl = getUpdateDownloadUrlFromAsset(asset, source);if (asset == null || downloadUrl.isEmpty) {- KazumiDialog.showToast(- message:- '没有找到 ${_getInstallationTypeDescription(selectedType)} 的下载链接');+ KazumiDialog.showToast(message: '没有找到 ${selectedType.label} 的下载链接');return;}@@ -443,53 +293,28 @@ class AutoUpdater {);_showDownloadCompleteDialog(downloadPath, updateInfo);- }, onError: (e, _) {- String errorMessage = '下载失败';- if (e.toString().contains('Permission denied') ||- e.toString().contains('Operation not permitted')) {- errorMessage = '权限不足,文件已保存到应用临时目录';- } else if (e.toString().contains('No space left')) {- errorMessage = '磁盘空间不足';- } else if (e.toString().contains('Network')) {- errorMessage = '网络连接错误';- } else if (e.toString().contains('文件完整性验证失败')) {- errorMessage = '文件完整性验证失败,可能是网络传输错误';- }+ }, onError: (e, stackTrace) {+ final errorMessage = getUpdateDownloadErrorMessage(e);KazumiDialog.show(builder: (context) {return AlertDialog(title: const Text('下载失败'),- content: Column(- mainAxisSize: MainAxisSize.min,- crossAxisAlignment: CrossAxisAlignment.start,- children: [- Text(errorMessage),- const SizedBox(height: 8),- Text(- '错误详情: ${e.toString()}',- style: Theme.of(context).textTheme.bodySmall,- ),- ],- ),+ content: Text(errorMessage),actions: [TextButton(onPressed: () => KazumiDialog.dismiss(context: context),child: const Text('确定'),),- TextButton(- onPressed: () {- KazumiDialog.dismiss(context: context);- _downloadUpdate(updateInfo, expectedHash);- },- child: const Text('重试'),- ),],);},);- KazumiLogger().e('Update: download update failed', error: e);+ KazumiLogger().e(+ 'Update: download failed | source=${updateInfo.downloadUrl} | '+ '${describeUpdateDownloadError(e, stackTrace)}',+ error: e);});}@@ -584,63 +409,16 @@ class AutoUpdater {Future<String> _downloadFile(String url, String version, String expectedHash,CancelToken cancelToken) async {- // Dio cancellation does not cover filesystem preparation or hash checks.- void checkCancelled() {- if (cancelToken.isCancelled) throw cancelToken.cancelError!;- }-- checkCancelled();- final fileName = _getFileNameFromUrl(url, version);final tempDir = await getTemporaryDirectory();- checkCancelled();- final filePath = '${tempDir.path}/$fileName';- final file = File(filePath);- if (await file.exists()) {- try {- final localHash = await calculateFileHash(file);- checkCancelled();- if (localHash == expectedHash) {- KazumiLogger().i(- 'Update: file already exists and hash verified, skipping download: $filePath');- _downloadProgress.value = 1.0;- return filePath;- } else {- KazumiLogger().i(- 'Update: file hash mismatch detected (local: $localHash, expected: $expectedHash), deleting and re-downloading');- await file.delete();- }- } catch (e) {- checkCancelled();- KazumiLogger().w(- 'Update: file verification failed, deleting and re-downloading',- error: e);- if (await file.exists()) {- await file.delete();- }- }- }-- checkCancelled();-- await _downloadClient.download(- url,- filePath,+ return downloadUpdateFile(+ url: url,+ filePath: '${tempDir.path}/${_getFileNameFromUrl(url, version)}',+ expectedHash: expectedHash,cancelToken: cancelToken,onReceiveProgress: (received, total) {- if (!cancelToken.isCancelled && total > 0) {- _downloadProgress.value = received / total;- }+ _downloadProgress.value = total > 0 ? received / total : 0;},);- final downloadedHash = await calculateFileHash(file);- checkCancelled();- if (downloadedHash != expectedHash) {- await file.delete();- throw Exception('文件完整性验证失败: 期望 $expectedHash,实际 $downloadedHash');- }- KazumiLogger().i('Update: file downloaded and hash verified: $filePath');-- return filePath;}void _installUpdate(diff --git a/lib/services/update/update_download_source.dart b/lib/services/update/update_download_source.dartnew file mode 100644index 00000000..4d5cd229--- /dev/null+++ b/lib/services/update/update_download_source.dart@@ -0,0 +1,9 @@+enum UpdateDownloadSource {+ github,+ mirror;++ String get label => switch (this) {+ github => 'GitHub',+ mirror => '镜像',+ };+}diff --git a/lib/services/update/update_downloader.dart b/lib/services/update/update_downloader.dartnew file mode 100644index 00000000..c84bca92--- /dev/null+++ b/lib/services/update/update_downloader.dart@@ -0,0 +1,155 @@+import 'dart:io';++import 'package:dio/dio.dart';+import 'package:kazumi/request/clients/download_http_client.dart';+import 'package:kazumi/request/core/network_exception.dart';+import 'package:kazumi/services/logging/logger.dart';+import 'package:kazumi/services/update/update_download_source.dart';+import 'package:kazumi/utils/crypto.dart';++String getUpdateDownloadUrlFromAsset(+ Map<String, dynamic>? asset, UpdateDownloadSource source) {+ final url = asset?[switch (source) {+ UpdateDownloadSource.mirror => 'mirror_download_url',+ UpdateDownloadSource.github => 'browser_download_url',+ }];+ return url is String ? url.trim() : '';+}++class UpdateIntegrityException implements Exception {+ const UpdateIntegrityException(this.expected, this.actual);++ final String expected;+ final String actual;++ @override+ String toString() => '文件完整性验证失败: 期望 $expected,实际 $actual';+}++Iterable<Object> _errorChain(Object error) sync* {+ final seen = Set<Object>.identity();+ Object? current = error;+ while (current != null && seen.add(current)) {+ yield current;+ current = switch (current) {+ NetworkException() => current.rawError,+ DioException() => current.error,+ _ => null,+ };+ }+}++String describeUpdateDownloadError(Object error, StackTrace stackTrace) {+ final causes = _errorChain(error).map((cause) => switch (cause) {+ DioException() => 'DioException(type=${cause.type.name}, '+ 'status=${cause.response?.statusCode}, message=${cause.message})',+ _ => '${cause.runtimeType}: $cause',+ });+ final stack =+ error is NetworkException ? error.stackTrace ?? stackTrace : stackTrace;+ return '${causes.join(' -> ')} | stack=$stack';+}++String getUpdateDownloadErrorMessage(Object error) {+ final causes = _errorChain(error).toList();+ final fileError = causes.whereType<FileSystemException>().firstOrNull;+ if (fileError != null) {+ final code = fileError.osError?.errorCode;+ final windows = Platform.isWindows;+ if (windows ? code == 5 : code == 1 || code == 13) {+ return '无法写入更新文件,请检查临时目录权限';+ }+ if (windows ? code == 112 || code == 39 : code == 28) {+ return '磁盘空间不足';+ }+ return '更新文件读写失败';+ }+ if (error is UpdateIntegrityException) {+ return '文件完整性验证失败,可能是网络传输错误';+ }+ final networkType =+ causes.whereType<NetworkException>().firstOrNull?.type;+ switch (networkType) {+ case NetworkExceptionType.connectionTimeout ||+ NetworkExceptionType.receiveTimeout ||+ NetworkExceptionType.sendTimeout:+ return '下载超时,请稍后重试';+ case NetworkExceptionType.connectionError ||+ NetworkExceptionType.badResponse ||+ NetworkExceptionType.badCertificate:+ return '网络连接错误';+ default:+ if (causes.any((cause) =>+ cause is SocketException ||+ cause is HttpException ||+ cause is HandshakeException)) {+ return '网络连接错误';+ }+ return '下载失败';+ }+}++/// Reuses a verified cached file; otherwise downloads into a private temp+/// directory and only moves the file to [filePath] after the hash matches.+Future<String> downloadUpdateFile({+ required String url,+ required String filePath,+ required String expectedHash,+ required CancelToken cancelToken,+ required ProgressCallback onReceiveProgress,+}) async {+ // Dio cancellation does not cover filesystem work or hashing.+ void checkCancelled() {+ if (cancelToken.isCancelled) throw cancelToken.cancelError!;+ }++ final hash = expectedHash.toLowerCase();+ if (!RegExp(r'^[a-f0-9]{64}$').hasMatch(hash)) {+ throw ArgumentError('更新缺少有效的 SHA256 校验值');+ }++ final file = File(filePath);+ if (await file.exists()) {+ String? localHash;+ try {+ localHash = await calculateFileHash(file);+ } catch (e) {+ KazumiLogger().w('Update: cached file verification failed', error: e);+ }+ checkCancelled();+ if (localHash == hash) {+ onReceiveProgress(1, 1);+ return filePath;+ }+ await file.delete();+ }++ checkCancelled();+ final downloadDir = await file.parent.createTemp('kazumi-update-');+ try {+ final partial = File('${downloadDir.path}/download.part');+ await DownloadHttpClient.instance.download(+ url,+ partial.path,+ cancelToken: cancelToken,+ onReceiveProgress: (received, total) {+ if (!cancelToken.isCancelled) onReceiveProgress(received, total);+ },+ );+ checkCancelled();+ final downloadedHash = await calculateFileHash(partial);+ checkCancelled();+ if (downloadedHash != hash) {+ throw UpdateIntegrityException(hash, downloadedHash);+ }+ await partial.rename(filePath);+ onReceiveProgress(1, 1);+ return filePath;+ } finally {+ try {+ await downloadDir.delete(recursive: true);+ } catch (e) {+ KazumiLogger().w('Update: temp download cleanup failed', error: e);+ }+ }+}