基于自定义规则的番剧采集APP,支持流媒体在线观看,支持弹幕,支持实时超分辨率。
refactor: sync (#2055)
Prediditbf33de83449d
diff --git a/lib/modules/collect/collect_sync_merger.dart b/lib/modules/collect/collect_sync_merger.dartnew file mode 100644index 00000000..4a959690--- /dev/null+++ b/lib/modules/collect/collect_sync_merger.dart@@ -0,0 +1,226 @@+import 'package:kazumi/modules/bangumi/bangumi_collection.dart';+import 'package:kazumi/modules/bangumi/sync_priority.dart';+import 'package:kazumi/modules/collect/collect_change_module.dart';+import 'package:kazumi/modules/collect/collect_module.dart';+import 'package:kazumi/modules/collect/collect_type_mapper.dart';++class CollectiblesMergeResult {+ const CollectiblesMergeResult({+ required this.collectibles,+ required this.changes,+ });++ final List<CollectedBangumi> collectibles;+ final List<CollectedBangumiChange> changes;+}++class BangumiUploadMutation {+ const BangumiUploadMutation({+ required this.bangumiId,+ required this.type,+ });++ final int bangumiId;+ final int type;+}++class BangumiLocalMutation {+ const BangumiLocalMutation({+ required this.collectible,+ required this.changeAction,+ });++ final CollectedBangumi collectible;+ final int changeAction;+}++class BangumiCollectiblesMergePlan {+ const BangumiCollectiblesMergePlan({+ required this.localOnlyUploads,+ required this.remoteOnlyPuts,+ required this.conflictUploads,+ required this.conflictLocalUpdates,+ });++ final List<BangumiUploadMutation> localOnlyUploads;+ final List<BangumiLocalMutation> remoteOnlyPuts;+ final List<BangumiUploadMutation> conflictUploads;+ final List<BangumiLocalMutation> conflictLocalUpdates;++ int get totalOperations =>+ localOnlyUploads.length ++ remoteOnlyPuts.length ++ conflictUploads.length ++ conflictLocalUpdates.length;+}++class CollectSyncMerger {+ static CollectiblesMergeResult mergeWebDav({+ required List<CollectedBangumi> localCollectibles,+ required List<CollectedBangumiChange> localChanges,+ required List<CollectedBangumi> remoteCollectibles,+ required List<CollectedBangumiChange> remoteChanges,+ }) {+ final mergedCollectibles =+ remoteCollectibles.map(_copyCollectible).toList();+ final newLocalChanges = localChanges.where((localChange) {+ return !remoteChanges+ .any((remoteChange) => remoteChange.id == localChange.id);+ }).toList()+ ..sort((a, b) => a.timestamp.compareTo(b.timestamp));++ for (final change in newLocalChanges) {+ if (change.action == 3) {+ mergedCollectibles+ .removeWhere((item) => item.bangumiItem.id == change.bangumiID);+ continue;+ }++ final localCollectible = _findCollectible(+ localCollectibles,+ change.bangumiID,+ );+ if (localCollectible == null) {+ continue;+ }++ final changedCollectible = CollectedBangumi(+ localCollectible.bangumiItem,+ localCollectible.time,+ change.type,+ );+ final index = mergedCollectibles.indexWhere(+ (item) => item.bangumiItem.id == change.bangumiID,+ );++ if (change.action == 1) {+ if (index == -1) {+ mergedCollectibles.add(changedCollectible);+ } else {+ mergedCollectibles[index] = changedCollectible;+ }+ } else if (change.action == 2 && index != -1) {+ mergedCollectibles[index] = changedCollectible;+ }+ }++ final mergedChanges = <int, CollectedBangumiChange>{+ for (final change in remoteChanges) change.id: change,+ for (final change in newLocalChanges) change.id: change,+ }.values.toList();++ return CollectiblesMergeResult(+ collectibles: mergedCollectibles,+ changes: mergedChanges,+ );+ }++ static BangumiCollectiblesMergePlan planBangumi({+ required List<CollectedBangumi> localCollectibles,+ required List<BangumiCollection> remoteCollections,+ required BangumiSyncPriority priority,+ }) {+ final localMap = {+ for (final item in localCollectibles) item.bangumiItem.id: item,+ };+ final remoteMap = <int, BangumiCollection>{};+ for (final item in remoteCollections) {+ final remoteCollectType = item.type.toCollectType();+ if (!remoteCollectType.isCollected) {+ continue;+ }+ remoteMap[item.bangumiId] = item;+ }++ final localOnlyIds = localMap.keys+ .toSet()+ .difference(remoteMap.keys.toSet())+ .toList()+ ..sort();+ final remoteOnlyIds = remoteMap.keys+ .toSet()+ .difference(localMap.keys.toSet())+ .toList()+ ..sort();+ final sharedIds = localMap.keys+ .toSet()+ .intersection(remoteMap.keys.toSet())+ .toList()+ ..sort();+ final mismatchIds = <int>[];+ for (final id in sharedIds) {+ if (localMap[id]!.type != remoteMap[id]!.type.toCollectType().value) {+ mismatchIds.add(id);+ }+ }++ final localOnlyUploads = [+ for (final id in localOnlyIds)+ BangumiUploadMutation(bangumiId: id, type: localMap[id]!.type),+ ];+ final remoteOnlyPuts = [+ for (final id in remoteOnlyIds)+ BangumiLocalMutation(+ collectible: _fromBangumiCollection(remoteMap[id]!),+ changeAction: 1,+ ),+ ];++ final conflictUploads = <BangumiUploadMutation>[];+ final conflictLocalUpdates = <BangumiLocalMutation>[];+ if (priority == BangumiSyncPriority.localFirst) {+ for (final id in mismatchIds) {+ conflictUploads.add(+ BangumiUploadMutation(bangumiId: id, type: localMap[id]!.type),+ );+ }+ } else {+ for (final id in mismatchIds) {+ conflictLocalUpdates.add(+ BangumiLocalMutation(+ collectible: _fromBangumiCollection(remoteMap[id]!),+ changeAction: 2,+ ),+ );+ }+ }++ return BangumiCollectiblesMergePlan(+ localOnlyUploads: localOnlyUploads,+ remoteOnlyPuts: remoteOnlyPuts,+ conflictUploads: conflictUploads,+ conflictLocalUpdates: conflictLocalUpdates,+ );+ }++ static CollectedBangumi _fromBangumiCollection(BangumiCollection remote) {+ final localType = remote.type.toCollectType();+ return CollectedBangumi(+ remote.toBangumiItem(),+ remote.updatedAt,+ localType.value,+ );+ }++ static CollectedBangumi? _findCollectible(+ List<CollectedBangumi> collectibles,+ int bangumiId,+ ) {+ for (final collectible in collectibles) {+ if (collectible.bangumiItem.id == bangumiId) {+ return collectible;+ }+ }+ return null;+ }++ static CollectedBangumi _copyCollectible(CollectedBangumi collectible) {+ return CollectedBangumi(+ collectible.bangumiItem,+ collectible.time,+ collectible.type,+ );+ }++ CollectSyncMerger._();+}diff --git a/lib/modules/collect/collect_sync_plan.dart b/lib/modules/collect/collect_sync_plan.dartnew file mode 100644index 00000000..b364627a--- /dev/null+++ b/lib/modules/collect/collect_sync_plan.dart@@ -0,0 +1,28 @@+class CollectSyncPlan {+ const CollectSyncPlan({+ required this.webDavEnabled,+ required this.webDavCollectiblesEnabled,+ required this.bangumiEnabled,+ });++ final bool webDavEnabled;+ final bool webDavCollectiblesEnabled;+ final bool bangumiEnabled;++ bool get shouldSyncWebDavCollectibles =>+ webDavEnabled && webDavCollectiblesEnabled;++ bool get shouldSyncBangumi => bangumiEnabled;++ bool get canSync => shouldSyncWebDavCollectibles || shouldSyncBangumi;++ bool shouldUploadWebDavAfterBangumi({+ required bool webDavSynced,+ required bool bangumiSynced,+ }) {+ return shouldSyncWebDavCollectibles &&+ shouldSyncBangumi &&+ webDavSynced &&+ bangumiSynced;+ }+}diff --git a/lib/pages/collect/collect_controller.dart b/lib/pages/collect/collect_controller.dartindex d94edaf8..c92c3767 100644--- a/lib/pages/collect/collect_controller.dart+++ b/lib/pages/collect/collect_controller.dart@@ -221,6 +221,12 @@ abstract class _CollectController with Store {}Future<bool> syncCollectibles({bool showSuccessToast = true}) async {+ final bool webDavCollectEnable =+ setting.get(SettingBoxKey.webDavEnableCollect, defaultValue: false);+ if (!webDavCollectEnable) {+ KazumiDialog.showToast(message: '未开启WebDav收藏同步');+ return false;+ }if (!WebDav().initialized) {KazumiDialog.showToast(message: '未开启WebDav同步或配置无效');return false;@@ -238,7 +244,9 @@ abstract class _CollectController with Store {}try {await WebDav().syncCollectibles();- KazumiDialog.showToast(message: 'WebDav同步完成');+ if (showSuccessToast) {+ KazumiDialog.showToast(message: 'WebDav同步完成');+ }} catch (e) {KazumiDialog.showToast(message: 'WebDav同步失败 $e');return false;@@ -248,8 +256,15 @@ abstract class _CollectController with Store {}/// Only upload local collectibles and change logs to WebDAV, without downloading and merging.- /// After bangumi sync finished, call this method to push local changes to WebDAV.- Future<bool> uploadCollectiblesToWebDav({bool showSuccessToast = true}) async {+ /// Used by full sync to push Bangumi-updated local changes back to WebDAV.+ Future<bool> uploadCollectiblesToWebDav(+ {bool showSuccessToast = true}) async {+ final bool webDavCollectEnable =+ setting.get(SettingBoxKey.webDavEnableCollect, defaultValue: false);+ if (!webDavCollectEnable) {+ KazumiDialog.showToast(message: '未开启WebDav收藏同步');+ return false;+ }if (!WebDav().initialized) {KazumiDialog.showToast(message: '未开启WebDav同步或配置无效');return false;@@ -296,7 +311,8 @@ abstract class _CollectController with Store {}await _collectCrudRepository.clearFavorites();loadCollectibles();- KazumiLogger().d('GStorage: detected $count uncategorized favorites, migrated to collectibles');+ KazumiLogger().d(+ 'GStorage: detected $count uncategorized favorites, migrated to collectibles');}}@@ -316,15 +332,12 @@ abstract class _CollectController with Store {List<BangumiItem> filterBangumiByType(List<BangumiItem> bangumiList, CollectType excludeType) {final excludeIds = getBangumiIdsByType(excludeType);- return bangumiList- .where((item) => !excludeIds.contains(item.id))- .toList();+ return bangumiList.where((item) => !excludeIds.contains(item.id)).toList();}/// Sync Bangumi collectibles.Future<bool> syncCollectiblesBangumi(- {void Function(String message, int current, int total)?- onProgress,+ {void Function(String message, int current, int total)? onProgress,bool showSuccessToast = true}) async {final bool syncEnable =setting.get(SettingBoxKey.bangumiSyncEnable, defaultValue: false);diff --git a/lib/pages/collect/collect_page.dart b/lib/pages/collect/collect_page.dartindex a48a8a53..dc58699c 100644--- a/lib/pages/collect/collect_page.dart+++ b/lib/pages/collect/collect_page.dart@@ -13,6 +13,7 @@ import 'package:kazumi/bean/appbar/sys_app_bar.dart';import 'package:provider/provider.dart';import 'package:kazumi/bean/widget/collect_button.dart';import 'package:hive_ce/hive.dart';+import 'package:kazumi/modules/collect/collect_sync_plan.dart';import 'package:kazumi/utils/storage.dart';class CollectPage extends StatefulWidget {@@ -73,7 +74,8 @@ class _CollectPageState extends State<CollectPage>children: [const Text('收藏全量同步中',- style: TextStyle(fontSize: 16, fontWeight: FontWeight.w600),+ style:+ TextStyle(fontSize: 16, fontWeight: FontWeight.w600),),const SizedBox(height: 12),ValueListenableBuilder<String>(@@ -83,7 +85,8 @@ class _CollectPageState extends State<CollectPage>const SizedBox(height: 12),ValueListenableBuilder<double?>(valueListenable: progressValue,- builder: (_, value, __) => LinearProgressIndicator(value: value),+ builder: (_, value, __) =>+ LinearProgressIndicator(value: value),),],),@@ -96,31 +99,33 @@ class _CollectPageState extends State<CollectPage>}String _buildFullSyncSummary({- required bool webDavEnabled,- required bool bangumiEnabled,+ required CollectSyncPlan plan,required bool webDavSynced,required bool bangumiSynced,required bool webDavUploaded,}) {final List<String> states = [];- if (webDavEnabled) {+ if (plan.shouldSyncWebDavCollectibles) {states.add(webDavSynced ? 'WebDav 已同步' : 'WebDav 未完成');}- if (bangumiEnabled) {+ if (plan.shouldSyncBangumi) {states.add(bangumiSynced ? 'Bangumi 已同步' : 'Bangumi 未完成');}- if (webDavEnabled && bangumiEnabled && webDavSynced && bangumiSynced) {+ if (plan.shouldSyncWebDavCollectibles &&+ plan.shouldSyncBangumi &&+ webDavSynced &&+ bangumiSynced) {states.add(webDavUploaded ? 'WebDav 已回传最新数据' : 'WebDav 未回传最新数据');}return states.join(',');}Future<void> _runFullSync({- required bool webDavEnabled,- required bool bangumiEnabled,+ required CollectSyncPlan plan,}) async {final ValueNotifier<double?> progressValue = ValueNotifier<double?>(null);- final ValueNotifier<String> progressText = ValueNotifier<String>('准备开始同步收藏...');+ final ValueNotifier<String> progressText =+ ValueNotifier<String>('准备开始同步收藏...');_showFullSyncProgressDialog(progressValue: progressValue,@@ -134,21 +139,24 @@ class _CollectPageState extends State<CollectPage>bool webDavUploaded = false;try {- if (webDavEnabled) {+ if (plan.shouldSyncWebDavCollectibles) {progressText.value = '正在同步 WebDav 收藏...';progressValue.value = null;webDavSynced =await collectController.syncCollectibles(showSuccessToast: false);}- if (bangumiEnabled) {+ if (plan.shouldSyncBangumi) {bangumiSynced = await _syncBangumiWithProgress(progressValue: progressValue,progressText: progressText,);}- if (webDavEnabled && bangumiEnabled && webDavSynced && bangumiSynced) {+ if (plan.shouldUploadWebDavAfterBangumi(+ webDavSynced: webDavSynced,+ bangumiSynced: bangumiSynced,+ )) {progressText.value = '正在回传最新收藏到 WebDav...';progressValue.value = null;webDavUploaded = await collectController.uploadCollectiblesToWebDav(@@ -165,8 +173,7 @@ class _CollectPageState extends State<CollectPage>KazumiDialog.showToast(message: _buildFullSyncSummary(- webDavEnabled: webDavEnabled,- bangumiEnabled: bangumiEnabled,+ plan: plan,webDavSynced: webDavSynced,bangumiSynced: bangumiSynced,webDavUploaded: webDavUploaded,@@ -247,10 +254,17 @@ class _CollectPageState extends State<CollectPage>floatingActionButton: FloatingActionButton(onPressed: () async {bool webDavenable = await setting.get(SettingBoxKey.webDavEnable,- defaultValue: false);- bool bgmSyncEnable = await setting.get(SettingBoxKey.bangumiSyncEnable,- defaultValue: false);- if (!webDavenable && !bgmSyncEnable) {+ defaultValue: false);+ bool webDavCollectEnable = await setting+ .get(SettingBoxKey.webDavEnableCollect, defaultValue: false);+ bool bgmSyncEnable = await setting+ .get(SettingBoxKey.bangumiSyncEnable, defaultValue: false);+ final syncPlan = CollectSyncPlan(+ webDavEnabled: webDavenable,+ webDavCollectiblesEnabled: webDavCollectEnable,+ bangumiEnabled: bgmSyncEnable,+ );+ if (!syncPlan.canSync) {KazumiDialog.showToast(message: '同步功能不可用,请至少开启一个同步功能');return;}@@ -266,8 +280,7 @@ class _CollectPageState extends State<CollectPage>});try {await _runFullSync(- webDavEnabled: webDavenable,- bangumiEnabled: bgmSyncEnable,+ plan: syncPlan,);} finally {if (mounted) {@@ -326,8 +339,8 @@ class _CollectPageState extends State<CollectPage>CustomScrollView(slivers: [SliverPadding(- padding: const EdgeInsets.fromLTRB(- StyleString.cardSpace, StyleString.cardSpace, StyleString.cardSpace, 0),+ padding: const EdgeInsets.fromLTRB(StyleString.cardSpace,+ StyleString.cardSpace, StyleString.cardSpace, 0),sliver: SliverGrid(gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(mainAxisSpacing: StyleString.cardSpace - 2,diff --git a/lib/pages/webdav_editor/webdav_setting.dart b/lib/pages/webdav_editor/webdav_setting.dartindex df638a34..0a1ac846 100644--- a/lib/pages/webdav_editor/webdav_setting.dart+++ b/lib/pages/webdav_editor/webdav_setting.dart@@ -19,6 +19,7 @@ class _PlayerSettingsPageState extends State<WebDavSettingsPage> {Box setting = GStorage.setting;late bool webDavEnable;late bool webDavEnableHistory;+ late bool webDavEnableCollect;late bool enableGitProxy;late bool bangumiSyncEnable;@@ -28,6 +29,8 @@ class _PlayerSettingsPageState extends State<WebDavSettingsPage> {webDavEnable = setting.get(SettingBoxKey.webDavEnable, defaultValue: false);webDavEnableHistory =setting.get(SettingBoxKey.webDavEnableHistory, defaultValue: false);+ webDavEnableCollect =+ setting.get(SettingBoxKey.webDavEnableCollect, defaultValue: false);enableGitProxy =setting.get(SettingBoxKey.enableGitProxy, defaultValue: false);bangumiSyncEnable =@@ -210,8 +213,11 @@ class _PlayerSettingsPageState extends State<WebDavSettingsPage> {}if (!webDavEnable) {webDavEnableHistory = false;+ webDavEnableCollect = false;await setting.put(SettingBoxKey.webDavEnableHistory, false);+ await setting.put(+ SettingBoxKey.webDavEnableCollect, false);}await setting.put(SettingBoxKey.webDavEnable, webDavEnable);if (mounted) {@@ -239,6 +245,22 @@ class _PlayerSettingsPageState extends State<WebDavSettingsPage> {style: TextStyle(fontFamily: fontFamily)),initialValue: webDavEnableHistory,),+ SettingsTile.switchTile(+ onToggle: (value) async {+ if (!webDavEnable) {+ KazumiDialog.showToast(message: '请先开启WEBDAV同步');+ return;+ }+ webDavEnableCollect = value ?? !webDavEnableCollect;+ await setting.put(+ SettingBoxKey.webDavEnableCollect, webDavEnableCollect);+ setState(() {});+ },+ title: Text('收藏同步', style: TextStyle(fontFamily: fontFamily)),+ description: Text('允许 WebDAV 参与追番状态同步',+ style: TextStyle(fontFamily: fontFamily)),+ initialValue: webDavEnableCollect,+ ),SettingsTile.navigation(onPressed: (_) async {Modular.to.pushNamed('/settings/webdav/editor');@@ -252,7 +274,8 @@ class _PlayerSettingsPageState extends State<WebDavSettingsPage> {updateWebdav();},title: Text('手动上传', style: TextStyle(fontFamily: fontFamily)),- description: Text('立即上传观看记录到WEBDAV', style: TextStyle(fontFamily: fontFamily)),+ description: Text('立即上传观看记录到WEBDAV',+ style: TextStyle(fontFamily: fontFamily)),),SettingsTile(trailing: const Icon(Icons.cloud_download_rounded),@@ -260,7 +283,8 @@ class _PlayerSettingsPageState extends State<WebDavSettingsPage> {downloadWebdav();},title: Text('手动下载', style: TextStyle(fontFamily: fontFamily)),- description: Text('立即下载观看记录到本地', style: TextStyle(fontFamily: fontFamily)),+ description: Text('立即下载观看记录到本地',+ style: TextStyle(fontFamily: fontFamily)),),],),diff --git a/lib/utils/bangumi_sync_service.dart b/lib/utils/bangumi_sync_service.dartindex 87487e3d..286a1e90 100644--- a/lib/utils/bangumi_sync_service.dart+++ b/lib/utils/bangumi_sync_service.dart@@ -1,13 +1,10 @@import 'package:hive_ce/hive.dart';import 'dart:async';import 'package:kazumi/bean/dialog/dialog_helper.dart';-import 'package:kazumi/modules/collect/collect_module.dart';-import 'package:kazumi/modules/collect/collect_type.dart';+import 'package:kazumi/modules/collect/collect_sync_merger.dart';import 'package:kazumi/utils/storage.dart';import 'package:kazumi/utils/logger.dart';-import 'package:kazumi/modules/bangumi/bangumi_collection.dart';import 'package:kazumi/modules/bangumi/sync_priority.dart';-import 'package:kazumi/modules/collect/collect_type_mapper.dart';import 'package:kazumi/request/apis/bangumi_api.dart';/// Bangumi 同步服务工具类@@ -162,38 +159,12 @@ class BangumiSyncService {);// 2. 与本地数据对比,进行乐观合并(单向填充)之后,按照优先级处理冲突- final localCollectibles = GStorage.collectibles.values.toList();- final localMap = {- for (final item in localCollectibles) item.bangumiItem.id: item,- };- final remoteMap = <int, BangumiCollection>{};- for (final item in remoteCollection) {- final remoteCollectType = item.type.toCollectType();- if (!remoteCollectType.isCollected) {- KazumiLogger().w(- 'Bangumi: skip remote collectible with unsupported type '- '${item.type.value} for id=${item.bangumiId}',- );- continue;- }- remoteMap[item.bangumiId] = item;- }-- final localOnlyIds =- localMap.keys.toSet().difference(remoteMap.keys.toSet());- final remoteOnlyIds =- remoteMap.keys.toSet().difference(localMap.keys.toSet());- final sharedIds =- localMap.keys.toSet().intersection(remoteMap.keys.toSet());- final mismatchIds = <int>[];- for (final id in sharedIds) {- if (localMap[id]!.type != remoteMap[id]!.type.toCollectType().value) {- mismatchIds.add(id);- }- }-- final totalOperations =- localOnlyIds.length + remoteOnlyIds.length + mismatchIds.length;+ final mergePlan = CollectSyncMerger.planBangumi(+ localCollectibles: GStorage.collectibles.values.toList(),+ remoteCollections: remoteCollection,+ priority: priority,+ );+ final totalOperations = mergePlan.totalOperations;if (totalOperations == 0) {onProgress?.call('未发现状态差异,无需同步', 1, 1);@@ -202,16 +173,16 @@ class BangumiSyncService {int syncedCount = 0;// 3. 仅本地有:直接上传到 Bangumi- if (localOnlyIds.isNotEmpty) {+ if (mergePlan.localOnlyUploads.isNotEmpty) {onProgress?.call('正在上传本地新增状态', syncedCount, totalOperations);- for (final id in localOnlyIds) {+ for (final upload in mergePlan.localOnlyUploads) {final updated = await BangumiApi.updateBangumiByType(- id,- localMap[id]!.type,+ upload.bangumiId,+ upload.type,);if (!updated) {onProgress?.call('上传本地新增状态失败', syncedCount, totalOperations);- throw Exception('同步失败:条目 $id 上传到 Bangumi 失败');+ throw Exception('同步失败:条目 ${upload.bangumiId} 上传到 Bangumi 失败');}syncedCount++;onProgress?.call('正在上传本地新增状态', syncedCount, totalOperations);@@ -219,18 +190,15 @@ class BangumiSyncService {}// 4. 仅远程有:直接补到本地- if (remoteOnlyIds.isNotEmpty) {+ if (mergePlan.remoteOnlyPuts.isNotEmpty) {onProgress?.call('正在补全本地缺失状态', syncedCount, totalOperations);- for (final id in remoteOnlyIds) {- final remote = remoteMap[id]!;- final localType = remote.type.toCollectType();- final collected = CollectedBangumi(- remote.toBangumiItem(),- remote.updatedAt,- localType.value,+ for (final mutation in mergePlan.remoteOnlyPuts) {+ await GStorage.putCollectible(mutation.collectible);+ await _recordCollectibleChange(+ mutation.collectible.bangumiItem.id,+ mutation.changeAction,+ mutation.collectible.type,);- await GStorage.putCollectible(collected);- await _recordCollectibleChange(id, 1, localType.value);syncedCount++;onProgress?.call('正在补全本地缺失状态', syncedCount, totalOperations);}@@ -239,25 +207,26 @@ class BangumiSyncService {// 5. 双方都有但不一致:按优先级处理if (priority == BangumiSyncPriority.localFirst) {onProgress?.call('本地优先:正在处理冲突状态', syncedCount, totalOperations);- for (final id in mismatchIds) {- final updated =- await BangumiApi.updateBangumiByType(id, localMap[id]!.type);+ for (final upload in mergePlan.conflictUploads) {+ final updated = await BangumiApi.updateBangumiByType(+ upload.bangumiId,+ upload.type,+ );if (updated != true) {- throw Exception('同步失败:条目 $id 上传到 Bangumi 失败');+ throw Exception('同步失败:条目 ${upload.bangumiId} 上传到 Bangumi 失败');}syncedCount++;onProgress?.call('本地优先:正在处理冲突状态', syncedCount, totalOperations);}} else {onProgress?.call('Bangumi优先:正在处理冲突状态', syncedCount, totalOperations);- for (final id in mismatchIds) {- final local = localMap[id]!;- final remote = remoteMap[id]!;- final localType = remote.type.toCollectType();- local.type = localType.value;- local.time = remote.updatedAt;- await GStorage.putCollectible(local);- await _recordCollectibleChange(id, 2, localType.value);+ for (final mutation in mergePlan.conflictLocalUpdates) {+ await GStorage.putCollectible(mutation.collectible);+ await _recordCollectibleChange(+ mutation.collectible.bangumiItem.id,+ mutation.changeAction,+ mutation.collectible.type,+ );syncedCount++;onProgress?.call('Bangumi优先:正在处理冲突状态', syncedCount, totalOperations);diff --git a/lib/utils/storage.dart b/lib/utils/storage.dartindex f54d3b31..fe60c356 100644--- a/lib/utils/storage.dart+++ b/lib/utils/storage.dart@@ -8,6 +8,7 @@ import 'package:kazumi/modules/bangumi/bangumi_tag.dart';import 'package:kazumi/modules/history/history_module.dart';import 'package:kazumi/modules/collect/collect_module.dart';import 'package:kazumi/modules/collect/collect_change_module.dart';+import 'package:kazumi/modules/collect/collect_sync_merger.dart';import 'package:kazumi/modules/search/search_history_module.dart';import 'package:kazumi/modules/download/download_module.dart';@@ -156,7 +157,8 @@ class GStorage {collectibles = await _openBoxSafe<CollectedBangumi>('collectibles');histories = await _openBoxSafe<History>('histories');setting = await _openBoxSafe<dynamic>('setting');- collectChanges = await _openBoxSafe<CollectedBangumiChange>('collectchanges');+ collectChanges =+ await _openBoxSafe<CollectedBangumiChange>('collectchanges');shieldList = await _openBoxSafe<String>('shieldList');searchHistory = await _openBoxSafe<SearchHistory>('searchHistory');downloads = await _openBoxSafe<DownloadRecord>('downloads');@@ -168,7 +170,9 @@ class GStorage {try {return await Hive.openBox<T>(boxName);} catch (e) {- KazumiLogger().e('GStorage: Box "$boxName" corrupted, attempting recovery', error: e);+ KazumiLogger().e(+ 'GStorage: Box "$boxName" corrupted, attempting recovery',+ error: e);// Delete the corrupted box filesawait _deleteBoxFiles(boxName);@@ -176,10 +180,12 @@ class GStorage {// Try to open again (will create a new empty box)try {final box = await Hive.openBox<T>(boxName);- KazumiLogger().i('GStorage: Box "$boxName" recovered successfully (data lost)');+ KazumiLogger()+ .i('GStorage: Box "$boxName" recovered successfully (data lost)');return box;} catch (e2) {- KazumiLogger().e('GStorage: Failed to recover box "$boxName"', error: e2);+ KazumiLogger()+ .e('GStorage: Failed to recover box "$boxName"', error: e2);rethrow;}}@@ -202,7 +208,8 @@ class GStorage {KazumiLogger().i('GStorage: Deleted lock file: $boxName.lock');}} catch (e) {- KazumiLogger().e('GStorage: Failed to delete box files for "$boxName"', error: e);+ KazumiLogger()+ .e('GStorage: Failed to delete box files for "$boxName"', error: e);}}@@ -294,90 +301,29 @@ class GStorage {static Future<void> patchCollectibles(List<CollectedBangumi> remoteCollectibles,List<CollectedBangumiChange> remoteChanges) async {- await _runCollectChangesWriteExclusive(() async {- final localCollectibles = collectibles.values.toList();- final localChanges = collectChanges.values.toList();-- final List<CollectedBangumiChange> newLocalChanges =- localChanges.where((localChange) {- return !remoteChanges- .any((remoteChange) => remoteChange.id == localChange.id);- }).toList();-- newLocalChanges.sort((a, b) => a.timestamp.compareTo(b.timestamp));-- // Process local changes- for (var change in newLocalChanges) {- // For delete action, we don't need to look up the local collectible.- // We can directly remove the item from the remote list.- if (change.action == 3) {- // Action 3: delete- remoteCollectibles- .removeWhere((b) => b.bangumiItem.id == change.bangumiID);- } else {- // For add/update, we still need to look up the local collectible.- final changedBangumiID = change.bangumiID.toString();- for (var localCollect in localCollectibles) {- if (localCollect.bangumiItem.id.toString() == changedBangumiID) {- if (change.action == 1) {- // Action 1: add- final exists = remoteCollectibles- .any((b) => b.bangumiItem.id == localCollect.bangumiItem.id);- if (!exists) {- remoteCollectibles.add(localCollect);- } else {- final index = remoteCollectibles.indexWhere(- (b) => b.bangumiItem.id == localCollect.bangumiItem.id);- localCollect.type = change.type;- if (index != -1) {- // Update the entry with local data.- remoteCollectibles[index] = localCollect;- }- }- } else if (change.action == 2) {- // Action 2: update- final index = remoteCollectibles.indexWhere(- (b) => b.bangumiItem.id == localCollect.bangumiItem.id);- localCollect.type = change.type;- if (index != -1) {- // Update the entry with local data.- remoteCollectibles[index] = localCollect;- }- }- break;- }- }- }- }+ await _runCollectChangesWriteExclusive(() async {+ final mergeResult = CollectSyncMerger.mergeWebDav(+ localCollectibles: collectibles.values.toList(),+ localChanges: collectChanges.values.toList(),+ remoteCollectibles: remoteCollectibles,+ remoteChanges: remoteChanges,+ );- // merge local changes with remote changes- final Map<int, CollectedBangumiChange> mergedMap = {};- for (var change in remoteChanges) {- mergedMap[change.id] = change;- }- for (var change in newLocalChanges) {- if (!mergedMap.containsKey(change.id)) {- mergedMap[change.id] = change;+ // Update local storage+ await collectibles.clear();+ for (var collect in mergeResult.collectibles) {+ await collectibles.put(collect.bangumiItem.id, collect);}- }- final List<CollectedBangumiChange> mergedChanges =- mergedMap.values.toList();-- // Update local storage- await collectibles.clear();- for (var collect in remoteCollectibles) {- await collectibles.put(collect.bangumiItem.id, collect);- }- await collectibles.flush();+ await collectibles.flush();- await collectChanges.clear();- for (var change in mergedChanges) {- await collectChanges.put(change.id, change);- }- await collectChanges.flush();+ await collectChanges.clear();+ for (var change in mergeResult.changes) {+ await collectChanges.put(change.id, change);+ }+ await collectChanges.flush();- _collectChangeIdInitialized = false;- _initializeNextCollectChangeIdLocked();+ _collectChangeIdInitialized = false;+ _initializeNextCollectChangeIdLocked();});}diff --git a/test/collect_sync_test.dart b/test/collect_sync_test.dartnew file mode 100644index 00000000..86160769--- /dev/null+++ b/test/collect_sync_test.dart@@ -0,0 +1,264 @@+import 'package:flutter_test/flutter_test.dart';+import 'package:kazumi/modules/bangumi/bangumi_collection.dart';+import 'package:kazumi/modules/bangumi/bangumi_collection_type.dart';+import 'package:kazumi/modules/bangumi/bangumi_item.dart';+import 'package:kazumi/modules/bangumi/sync_priority.dart';+import 'package:kazumi/modules/bangumi/bangumi_tag.dart';+import 'package:kazumi/modules/collect/collect_change_module.dart';+import 'package:kazumi/modules/collect/collect_module.dart';+import 'package:kazumi/modules/collect/collect_sync_merger.dart';+import 'package:kazumi/modules/collect/collect_sync_plan.dart';+import 'package:kazumi/modules/collect/collect_type.dart';++void main() {+ group('CollectSyncPlan', () {+ test('keeps WebDAV history-only mode out of collectible sync', () {+ const plan = CollectSyncPlan(+ webDavEnabled: true,+ webDavCollectiblesEnabled: false,+ bangumiEnabled: false,+ );++ expect(plan.shouldSyncWebDavCollectibles, isFalse);+ expect(plan.shouldSyncBangumi, isFalse);+ expect(plan.canSync, isFalse);+ });++ test('allows Bangumi-only sync while WebDAV is enabled for history', () {+ const plan = CollectSyncPlan(+ webDavEnabled: true,+ webDavCollectiblesEnabled: false,+ bangumiEnabled: true,+ );++ expect(plan.shouldSyncWebDavCollectibles, isFalse);+ expect(plan.shouldSyncBangumi, isTrue);+ expect(plan.canSync, isTrue);+ });++ test('allows WebDAV-only collectible sync', () {+ const plan = CollectSyncPlan(+ webDavEnabled: true,+ webDavCollectiblesEnabled: true,+ bangumiEnabled: false,+ );++ expect(plan.shouldSyncWebDavCollectibles, isTrue);+ expect(plan.shouldSyncBangumi, isFalse);+ expect(plan.canSync, isTrue);+ });++ test('uploads back to WebDAV only after both sources finished', () {+ const plan = CollectSyncPlan(+ webDavEnabled: true,+ webDavCollectiblesEnabled: true,+ bangumiEnabled: true,+ );++ expect(+ plan.shouldUploadWebDavAfterBangumi(+ webDavSynced: true,+ bangumiSynced: true,+ ),+ isTrue,+ );+ expect(+ plan.shouldUploadWebDavAfterBangumi(+ webDavSynced: true,+ bangumiSynced: false,+ ),+ isFalse,+ );+ });+ });++ group('CollectSyncMerger', () {+ test('merges local change log into WebDAV collectibles', () {+ final mergeResult = CollectSyncMerger.mergeWebDav(+ localCollectibles: [+ _collect(1, CollectType.watching, 10),+ _collect(2, CollectType.watched, 20),+ _collect(3, CollectType.abandoned, 30),+ ],+ localChanges: [+ _change(10, 1, 1, CollectType.watching, 10),+ _change(11, 2, 2, CollectType.watched, 20),+ _change(12, 3, 3, CollectType.abandoned, 30),+ ],+ remoteCollectibles: [+ _collect(2, CollectType.planToWatch, 5),+ _collect(3, CollectType.watching, 5),+ _collect(4, CollectType.onHold, 5),+ ],+ remoteChanges: [+ _change(9, 4, 1, CollectType.onHold, 5),+ ],+ );++ expect(_typesById(mergeResult.collectibles), {+ 1: CollectType.watching.value,+ 2: CollectType.watched.value,+ 4: CollectType.onHold.value,+ });+ expect(mergeResult.changes.map((change) => change.id), [9, 10, 11, 12]);+ });++ test('plans Bangumi changes after local and WebDAV already diverged', () {+ final webDavResult = CollectSyncMerger.mergeWebDav(+ localCollectibles: [+ _collect(1, CollectType.watching, 10),+ ],+ localChanges: [+ _change(10, 1, 1, CollectType.watching, 10),+ ],+ remoteCollectibles: [+ _collect(2, CollectType.watched, 5),+ _collect(4, CollectType.onHold, 5),+ ],+ remoteChanges: [+ _change(9, 2, 1, CollectType.watched, 5),+ _change(8, 4, 1, CollectType.onHold, 5),+ ],+ );++ final bangumiPlan = CollectSyncMerger.planBangumi(+ localCollectibles: webDavResult.collectibles,+ remoteCollections: [+ _remote(1, BangumiCollectionType.watched, 40),+ _remote(2, BangumiCollectionType.watched, 20),+ _remote(3, BangumiCollectionType.onHold, 30),+ ],+ priority: BangumiSyncPriority.bangumiFirst,+ );++ expect(bangumiPlan.totalOperations, 3);+ expect(+ bangumiPlan.localOnlyUploads.map((upload) => upload.bangumiId),+ [4],+ );+ expect(+ bangumiPlan.localOnlyUploads.single.type, CollectType.onHold.value);+ expect(+ bangumiPlan.remoteOnlyPuts.map(+ (mutation) => mutation.collectible.bangumiItem.id,+ ),+ [3],+ );+ expect(+ bangumiPlan.conflictLocalUpdates.map(+ (mutation) => mutation.collectible.bangumiItem.id,+ ),+ [1],+ );+ expect(+ bangumiPlan.conflictLocalUpdates.single.collectible.type,+ CollectType.watched.value,+ );+ expect(bangumiPlan.conflictUploads, isEmpty);+ });++ test('uses local priority and skips unsupported Bangumi collection types',+ () {+ final plan = CollectSyncMerger.planBangumi(+ localCollectibles: [+ _collect(1, CollectType.watching, 10),+ ],+ remoteCollections: [+ _remote(1, BangumiCollectionType.watched, 40),+ _remote(2, BangumiCollectionType.unknown, 50),+ ],+ priority: BangumiSyncPriority.localFirst,+ );++ expect(plan.totalOperations, 1);+ expect(plan.conflictUploads.single.bangumiId, 1);+ expect(plan.conflictUploads.single.type, CollectType.watching.value);+ expect(plan.remoteOnlyPuts, isEmpty);+ expect(plan.conflictLocalUpdates, isEmpty);+ });+ });+}++CollectedBangumi _collect(int id, CollectType type, int timestamp) {+ return CollectedBangumi(+ _item(id),+ DateTime.fromMillisecondsSinceEpoch(timestamp * 1000),+ type.value,+ );+}++CollectedBangumiChange _change(+ int id,+ int bangumiId,+ int action,+ CollectType type,+ int timestamp,+) {+ return CollectedBangumiChange(+ id,+ bangumiId,+ action,+ type.value,+ timestamp,+ );+}++BangumiCollection _remote(+ int id,+ BangumiCollectionType type,+ int timestamp,+) {+ return BangumiCollection(+ id,+ '2026-01-01',+ DateTime.fromMillisecondsSinceEpoch(timestamp * 1000),+ type,+ 'subject $id',+ '条目 $id',+ '',+ 0,+ 12,+ 0,+ const {+ 'large': '',+ 'common': '',+ 'medium': '',+ 'small': '',+ 'grid': '',+ },+ const [],+ );+}++BangumiItem _item(int id) {+ return BangumiItem(+ id: id,+ type: 2,+ name: 'subject $id',+ nameCn: '条目 $id',+ summary: '',+ airDate: '2026-01-01',+ airWeekday: 4,+ rank: 0,+ images: const {+ 'large': '',+ 'common': '',+ 'medium': '',+ 'small': '',+ 'grid': '',+ },+ tags: const <BangumiTag>[],+ alias: const [],+ ratingScore: 0,+ votes: 0,+ votesCount: const [],+ info: '',+ );+}++Map<int, int> _typesById(List<CollectedBangumi> collectibles) {+ return {+ for (final collectible in collectibles)+ collectible.bangumiItem.id: collectible.type,+ };+}