基于自定义规则的番剧采集APP,支持流媒体在线观看,支持弹幕,支持实时超分辨率。
feat: bangumi integrate (#2001)
華仔3317d9c4d4b7
diff --git a/lib/bean/widget/collect_button.dart b/lib/bean/widget/collect_button.dartindex 209b6fc0..094a1bd2 100644--- a/lib/bean/widget/collect_button.dart+++ b/lib/bean/widget/collect_button.dart@@ -123,9 +123,13 @@ class _CollectButtonState extends State<CollectButton> {menuChildren: List<MenuItemButton>.generate(6,(int index) => MenuItemButton(- onPressed: () {+ onPressed: () async {if (index != collectType && mounted) {- collectController.addCollect(widget.bangumiItem, type: index);+ await collectController.addCollect(widget.bangumiItem, type: index);+ // 防止状态错误刷新+ if (!mounted) {+ return;+ }setState(() {});}},diff --git a/lib/modules/bangumi/bangumi_collection.dart b/lib/modules/bangumi/bangumi_collection.dartnew file mode 100644index 00000000..08b11be0--- /dev/null+++ b/lib/modules/bangumi/bangumi_collection.dart@@ -0,0 +1,108 @@+import 'package:kazumi/modules/bangumi/bangumi_item.dart';++import 'bangumi_collection_type.dart';++/// NOTE: 该类仅用于解析 Bangumi API 返回的收藏数据,不适用本地收藏+class BangumiCollection {+ /// 最后更新时间+ DateTime updatedAt;++ /// Bangumi ID+ int bangumiId;++ /// Bangumi 收藏类型。+ BangumiCollectionType type;++ /// 上映日期+ String? date;++ /// 番剧名称+ String name;++ /// 番剧中文名称+ String nameCn;++ /// 简介+ String shortSummary;++ /// 平均评分+ double score;++ /// 总集数+ int eps;++ /// 排名+ int rank;++ /// 图片链接,包含 large、common、medium、small、grid 五种尺寸+ Map<String, String> images;++ /// 标签列表,每个标签包含 name 和 count 字段+ List<Map<String, dynamic>> tags;++ BangumiCollection(+ this.bangumiId,+ this.date,+ this.updatedAt,+ this.type,+ this.name,+ this.nameCn,+ this.shortSummary,+ this.score,+ this.eps,+ this.rank,+ this.images,+ this.tags);++ BangumiItem toBangumiItem() {+ return BangumiItem.fromJson({+ 'id': bangumiId,+ 'type': 2,+ 'name': name,+ 'name_cn': nameCn,+ 'summary': shortSummary,+ 'date': date ?? '',+ 'images': images,+ 'tags': tags,+ 'rating': {+ 'rank': rank,+ 'score': score,+ 'total': 0,+ 'count': List<int>.filled(10, 0),+ },+ 'info': '',+ });+ }++ factory BangumiCollection.fromJson(Map json) {+ final subject = json['subject'];+ final subjectImages = Map<String, String>.from(+ subject['images'] ??+ const <String, String>{+ 'large': '',+ 'common': '',+ 'medium': '',+ 'small': '',+ 'grid': '',+ },+ );+ final subjectTags = ((subject['tags'] ?? const <dynamic>[]) as List)+ .whereType<Map>()+ .map((tag) => Map<String, dynamic>.from(tag))+ .toList();+ return BangumiCollection(+ subject['id'],+ subject['date'],+ DateTime.parse(json['updated_at']),+ BangumiCollectionType.fromValue(json['type']),+ subject['name'],+ subject['name_cn'],+ subject['short_summary'],+ (subject['score'] as num).toDouble(),+ subject['eps'],+ subject['rank'],+ subjectImages,+ subjectTags,+ );+ }+}diff --git a/lib/modules/bangumi/bangumi_collection_type.dart b/lib/modules/bangumi/bangumi_collection_type.dartnew file mode 100644index 00000000..231d6699--- /dev/null+++ b/lib/modules/bangumi/bangumi_collection_type.dart@@ -0,0 +1,27 @@+/// Bangumi 收藏类型枚举+/// via: https://bangumi.github.io/api/#/model-CollectionType+enum BangumiCollectionType {+ unknown(0, '未知'),++ planToWatch(1, '想看'),++ watched(2, '看过'),++ watching(3, '在看'),++ onHold(4, '搁置'),++ abandoned(5, '抛弃');++ const BangumiCollectionType(this.value, this.label);++ final int value;+ final String label;++ static BangumiCollectionType fromValue(int value) {+ return BangumiCollectionType.values.firstWhere(+ (type) => type.value == value,+ orElse: () => BangumiCollectionType.unknown,+ );+ }+}diff --git a/lib/modules/bangumi/sync_priority.dart b/lib/modules/bangumi/sync_priority.dartnew file mode 100644index 00000000..ed7f07f3--- /dev/null+++ b/lib/modules/bangumi/sync_priority.dart@@ -0,0 +1,16 @@+enum BangumiSyncPriority {+ localFirst(0, '本地优先'),+ bangumiFirst(1, 'Bangumi优先');++ const BangumiSyncPriority(this.value, this.label);++ final int value;+ final String label;++ static BangumiSyncPriority fromValue(int value) {+ return BangumiSyncPriority.values.firstWhere(+ (item) => item.value == value,+ orElse: () => BangumiSyncPriority.localFirst,+ );+ }+}diff --git a/lib/modules/collect/collect_module.dart b/lib/modules/collect/collect_module.dartindex 48801ac8..74dccb53 100644--- a/lib/modules/collect/collect_module.dart+++ b/lib/modules/collect/collect_module.dart@@ -1,5 +1,6 @@import 'package:hive_ce/hive.dart';import 'package:kazumi/modules/bangumi/bangumi_item.dart';+import 'package:kazumi/modules/collect/collect_type.dart';part 'collect_module.g.dart';@@ -11,6 +12,7 @@ class CollectedBangumi {@HiveField(1)DateTime time;+ /// Refer to [CollectType]// 1. 在看// 2. 想看// 3. 搁置diff --git a/lib/modules/collect/collect_type_mapper.dart b/lib/modules/collect/collect_type_mapper.dartnew file mode 100644index 00000000..d6051cd0--- /dev/null+++ b/lib/modules/collect/collect_type_mapper.dart@@ -0,0 +1,35 @@+import 'package:kazumi/modules/bangumi/bangumi_collection_type.dart';+import 'package:kazumi/modules/collect/collect_type.dart';++/// Converting [BangumiCollectionType] to local [CollectType].+extension BangumiCollectionTypeMapper on BangumiCollectionType {++ /// Converts this Bangumi collection type to the equivalent local type.+ CollectType toCollectType() {+ return switch (this) {+ BangumiCollectionType.planToWatch => CollectType.planToWatch,+ BangumiCollectionType.watched => CollectType.watched,+ BangumiCollectionType.watching => CollectType.watching,+ BangumiCollectionType.onHold => CollectType.onHold,+ BangumiCollectionType.abandoned => CollectType.abandoned,+ BangumiCollectionType.unknown => CollectType.none,+ };+ }+}++/// Converting [CollectType] to [BangumiCollectionType].+extension CollectTypeBangumiMapper on CollectType {++ /// Converts this local collection type to the equivalent Bangumi type.+ BangumiCollectionType? toBangumiCollectionType() {+ return switch (this) {+ CollectType.planToWatch => BangumiCollectionType.planToWatch,+ CollectType.watched => BangumiCollectionType.watched,+ CollectType.watching => BangumiCollectionType.watching,+ CollectType.onHold => BangumiCollectionType.onHold,+ CollectType.abandoned => BangumiCollectionType.abandoned,+ CollectType.none => null,+ };+ }++}diff --git a/lib/pages/bangumi/bangumi_module.dart b/lib/pages/bangumi/bangumi_module.dartnew file mode 100644index 00000000..26f06726--- /dev/null+++ b/lib/pages/bangumi/bangumi_module.dart@@ -0,0 +1,12 @@+import 'package:kazumi/pages/bangumi/bangumi_setting.dart';+import 'package:flutter_modular/flutter_modular.dart';++class BangumiModule extends Module {+ @override+ void binds(i) {}++ @override+ void routes(r) {+ r.child("/", child: (_) => const BangumiEditorPage());+ }+}\ No newline at end of filediff --git a/lib/pages/bangumi/bangumi_setting.dart b/lib/pages/bangumi/bangumi_setting.dartnew file mode 100644index 00000000..51c660ff--- /dev/null+++ b/lib/pages/bangumi/bangumi_setting.dart@@ -0,0 +1,334 @@+import 'package:card_settings_ui/card_settings_ui.dart';+import 'package:flutter/material.dart';+import 'package:kazumi/bean/appbar/sys_app_bar.dart';+import 'package:kazumi/bean/dialog/dialog_helper.dart';+import 'package:kazumi/modules/bangumi/sync_priority.dart';+import 'package:kazumi/utils/bangumi_sync_service.dart';+import 'package:kazumi/utils/storage.dart';+import 'package:hive_ce/hive.dart';+import 'package:url_launcher/url_launcher.dart';++class BangumiEditorPage extends StatefulWidget {+ const BangumiEditorPage({super.key});++ @override+ State<BangumiEditorPage> createState() => _BangumiEditorPageState();+}++class _BangumiEditorPageState extends State<BangumiEditorPage> {+ final TextEditingController bangumiTokenController = TextEditingController();+ Box setting = GStorage.setting;+ bool passwordVisible = false;+ bool isVerifying = false;+ late bool bangumiImmediateSyncToastEnable;+ late int syncPriority;+ bool syncCollectiblesing = false;+ final MenuController syncPriorityMenuController = MenuController();++ @override+ void initState() {+ super.initState();+ bangumiTokenController.text =+ setting.get(SettingBoxKey.bangumiAccessToken, defaultValue: '');+ bangumiImmediateSyncToastEnable = setting.get(+ SettingBoxKey.bangumiImmediateSyncToastEnable,+ defaultValue: true,+ );+ syncPriority =+ setting.get(SettingBoxKey.bangumiSyncPriority, defaultValue: 0);+ }++ @override+ void dispose() {+ bangumiTokenController.dispose();+ super.dispose();+ }++ Future<void> updateSyncPriority(int value) async {+ await setting.put(SettingBoxKey.bangumiSyncPriority, value);+ if (!mounted) return;+ setState(() {+ syncPriority = value;+ });+ }++ Future<void> syncWithProgress() async {+ final syncEnable =+ setting.get(SettingBoxKey.bangumiSyncEnable, defaultValue: false);+ if (!syncEnable) {+ KazumiDialog.showToast(message: '请先开启 Bangumi 同步');+ return;+ }++ final ValueNotifier<double?> progressValue = ValueNotifier<double?>(null);+ final ValueNotifier<String> progressText =+ ValueNotifier<String>('准备同步 Bangumi 状态...');++ try {+ setState(() {+ syncCollectiblesing = true;+ });++ KazumiDialog.show(+ clickMaskDismiss: false,+ builder: (context) {+ return PopScope(+ canPop: false,+ child: Dialog(+ child: Padding(+ padding: const EdgeInsets.all(20.0),+ child: SizedBox(+ width: 340,+ child: Column(+ mainAxisSize: MainAxisSize.min,+ crossAxisAlignment: CrossAxisAlignment.start,+ children: [+ const Text(+ 'Bangumi 同步进行中',+ style: TextStyle(+ fontSize: 16,+ fontWeight: FontWeight.w600,+ ),+ ),+ const SizedBox(height: 12),+ ValueListenableBuilder<String>(+ valueListenable: progressText,+ builder: (_, value, __) => Text(value),+ ),+ const SizedBox(height: 12),+ ValueListenableBuilder<double?>(+ valueListenable: progressValue,+ builder: (_, value, __) =>+ LinearProgressIndicator(value: value),+ ),+ ],+ ),+ ),+ ),+ ),+ );+ },+ );++ final bangumi = BangumiSyncService();+ await bangumi.ping();+ await bangumi.syncCollectibles(+ onProgress: (message, current, total) {+ progressText.value =+ total > 0 ? '$message ($current/$total)' : message;+ if (total > 0) {+ progressValue.value = (current / total).clamp(0.0, 1.0);+ } else {+ progressValue.value = null;+ }+ },+ );+ } catch (e) {+ KazumiDialog.showToast(message: 'Bangumi同步失败 $e');+ } finally {+ if (KazumiDialog.observer.hasKazumiDialog) {+ KazumiDialog.dismiss();+ }+ progressValue.dispose();+ progressText.dispose();+ if (mounted) {+ setState(() {+ syncCollectiblesing = false;+ });+ }+ }+ }++ @override+ Widget build(BuildContext context) {+ final fontFamily = Theme.of(context).textTheme.bodyMedium?.fontFamily;+ return PopScope(+ canPop: !syncCollectiblesing,+ child: Scaffold(+ appBar: const SysAppBar(title: Text('Bangumi 配置')),+ body: SingleChildScrollView(+ padding: const EdgeInsets.all(16.0),+ child: Center(+ child: SizedBox(+ width: (MediaQuery.of(context).size.width > 1000) ? 1000 : null,+ child: Column(+ children: [+ TextField(+ controller: bangumiTokenController,+ obscureText: !passwordVisible,+ decoration: InputDecoration(+ labelText: 'Bangumi Access Token',+ border: const OutlineInputBorder(),+ suffixIcon: IconButton(+ onPressed: () {+ setState(() {+ passwordVisible = !passwordVisible;+ });+ },+ icon: Icon(passwordVisible+ ? Icons.visibility_rounded+ : Icons.visibility_off_rounded),+ ),+ ),+ ),+ const SizedBox(height: 16),+ SettingsSection(+ margin: EdgeInsetsDirectional.zero,+ tiles: [+ SettingsTile.switchTile(+ onToggle: (value) async {+ bangumiImmediateSyncToastEnable =+ value ?? !bangumiImmediateSyncToastEnable;+ await setting.put(+ SettingBoxKey.bangumiImmediateSyncToastEnable,+ bangumiImmediateSyncToastEnable,+ );+ if (mounted) {+ setState(() {});+ }+ },+ title: Text('即时同步提示',+ style: TextStyle(fontFamily: fontFamily)),+ description: Text('点击追番按钮触发即时同步时显示提示框'),+ initialValue: bangumiImmediateSyncToastEnable,+ ),+ SettingsTile.navigation(+ onPressed: (_) async {+ if (syncPriorityMenuController.isOpen) {+ syncPriorityMenuController.close();+ } else {+ syncPriorityMenuController.open();+ }+ },+ title: Text('同步优先级',+ style: TextStyle(fontFamily: fontFamily)),+ description: Text('当本地与 Bangumi 状态不一致时优先使用哪个状态'),+ value: MenuAnchor(+ consumeOutsideTap: true,+ controller: syncPriorityMenuController,+ builder: (context, controller, child) => Text(+ BangumiSyncPriority.fromValue(syncPriority).label,+ style: TextStyle(fontFamily: fontFamily)),+ menuChildren: [+ for (final entry in BangumiSyncPriority.values)+ MenuItemButton(+ requestFocusOnHover: false,+ onPressed: () =>+ updateSyncPriority(entry.value),+ child: Container(+ height: 48,+ constraints:+ BoxConstraints(minWidth: 112),+ child: Align(+ alignment: Alignment.centerLeft,+ child: Text(+ entry.label,+ style: TextStyle(+ color: entry.value == syncPriority+ ? Theme.of(context)+ .colorScheme+ .primary+ : null,+ fontFamily: fontFamily,+ ),+ ),+ )))+ ]),+ ),+ SettingsTile(+ trailing: syncCollectiblesing+ ? const SizedBox(+ width: 20,+ height: 20,+ child: CircularProgressIndicator(strokeWidth: 2),+ )+ : const Icon(Icons.sync_rounded),+ onPressed: (_) async {+ await syncWithProgress();+ },+ title: Text("立即同步状态"),+ description: Text('同步状态不一致或仅存在于本地/远端的条目'),+ ),+ ],+ ),+ const SizedBox(height: 16),+ GestureDetector(+ onTap: () async {+ final url =+ Uri.parse('https://next.bgm.tv/demo/access-token');+ if (await canLaunchUrl(url)) {+ await launchUrl(url,+ mode: LaunchMode.externalApplication);+ } else {+ KazumiDialog.showToast(message: '无法打开链接');+ }+ },+ child: Text(+ '你可以点击此处前往 Bangumi 生成 Access Token',+ style: TextStyle(+ fontSize: 12,+ color: Theme.of(context).colorScheme.primary,+ fontFamily: fontFamily,+ decoration: TextDecoration.underline,+ ),+ ),+ ),+ ],+ ),+ ),+ ),+ ),+ floatingActionButton: FloatingActionButton(+ onPressed: isVerifying+ ? null+ : () async {+ final token = bangumiTokenController.text.trim();+ final bool bangumiSyncEnable =+ setting.get(SettingBoxKey.bangumiSyncEnable,+ defaultValue: false);++ if (token.isEmpty && bangumiSyncEnable) {+ KazumiDialog.showToast(message: 'Access Token 不能为空');+ return;+ }+ setState(() {+ isVerifying = true;+ });+ await setting.put(SettingBoxKey.bangumiAccessToken, token);+ final bangumi = BangumiSyncService();++ if (token.isEmpty) {+ bangumi.reset();+ KazumiDialog.showToast(message: 'Bangumi Token 为空,请检查');+ if (!mounted) return;+ setState(() {+ isVerifying = false;+ });+ return;+ }++ KazumiDialog.showToast(message: '正在测试 Bangumi Token...');+ try {+ await bangumi.init();+ } catch (e) {+ KazumiDialog.showToast(message: '验证失败:${e.toString()}');+ await setting.put(SettingBoxKey.bangumiSyncEnable, false);+ if (!mounted) return;+ setState(() {+ isVerifying = false;+ });+ return;+ }++ KazumiDialog.showToast(message: '测试成功,用户名:${bangumi.username}');+ if (!mounted) return;+ setState(() {+ isVerifying = false;+ });+ },+ child: const Icon(Icons.save),+ ),+ ),+ );+ }+}diff --git a/lib/pages/collect/collect_controller.dart b/lib/pages/collect/collect_controller.dartindex e8d41487..d94edaf8 100644--- a/lib/pages/collect/collect_controller.dart+++ b/lib/pages/collect/collect_controller.dart@@ -1,9 +1,11 @@+import 'package:flutter/material.dart';import 'package:flutter_modular/flutter_modular.dart';+import 'package:url_launcher/url_launcher.dart';import 'package:kazumi/bean/dialog/dialog_helper.dart';import 'package:kazumi/modules/bangumi/bangumi_item.dart';import 'package:kazumi/modules/collect/collect_module.dart';-import 'package:kazumi/modules/collect/collect_change_module.dart';import 'package:kazumi/modules/collect/collect_type.dart';+import 'package:kazumi/utils/bangumi_sync_service.dart';import 'package:kazumi/utils/storage.dart';import 'package:kazumi/utils/webdav.dart';import 'package:kazumi/repositories/collect_crud_repository.dart';@@ -14,6 +16,14 @@ import 'package:kazumi/utils/logger.dart';part 'collect_controller.g.dart';+// Define actions for handling Bangumi collect deletion.+enum _BangumiDeleteSyncAction {+ deleteLocalOnly,+ markAbandoned,+ openWeb,+ cancel,+}+class CollectController = _CollectController with _$CollectController;abstract class _CollectController with Store {@@ -42,41 +52,178 @@ abstract class _CollectController with Store {await deleteCollect(bangumiItem);return;}++ // 1. Sync with Bangumi if enabled+ final bool syncSucceeded = await _syncBangumiCollectIfEnabled(+ bangumiItem.id,+ type,+ );+ if (!syncSucceeded) {+ return;+ }++ final int currentCollectType = getCollectType(bangumiItem);+ final int collectChangeAction = currentCollectType == 0 ? 1 : 2;++ // 2. Update local database and change logsawait _collectCrudRepository.addCollectible(bangumiItem, type);- final int collectChangeId = (DateTime.now().millisecondsSinceEpoch ~/ 1000);- final CollectedBangumiChange collectChange = CollectedBangumiChange(- collectChangeId,- bangumiItem.id,- 1,- type,- (DateTime.now().millisecondsSinceEpoch ~/ 1000));- await _collectCrudRepository.addCollectChange(collectChange);+ await GStorage.appendCollectChange(+ bangumiId: bangumiItem.id,+ action: collectChangeAction,+ type: type,+ );loadCollectibles();}@actionFuture<void> deleteCollect(BangumiItem bangumiItem) async {+ // Resolve how to handle deletion with user+ final action = await _resolveBangumiDeleteSyncAction(bangumiItem);+ switch (action) {+ case _BangumiDeleteSyncAction.markAbandoned:+ await addCollect(+ bangumiItem,+ type: CollectType.abandoned.value,+ );+ return;++ case _BangumiDeleteSyncAction.openWeb:+ await _deleteCollectLocally(bangumiItem);+ await _openBangumiSubjectPage(bangumiItem.id);+ return;++ case _BangumiDeleteSyncAction.deleteLocalOnly:+ await _deleteCollectLocally(bangumiItem);+ return;++ case _BangumiDeleteSyncAction.cancel:+ case null:+ return;+ }+ }++ Future<void> _deleteCollectLocally(BangumiItem bangumiItem) async {await _collectCrudRepository.deleteCollectible(bangumiItem.id);- final int collectChangeId = (DateTime.now().millisecondsSinceEpoch ~/ 1000);- final CollectedBangumiChange collectChange = CollectedBangumiChange(- collectChangeId,- bangumiItem.id,- 3,- 5,- (DateTime.now().millisecondsSinceEpoch ~/ 1000));- await _collectCrudRepository.addCollectChange(collectChange);+ await GStorage.appendCollectChange(+ bangumiId: bangumiItem.id,+ action: 3,+ type: 5,+ );loadCollectibles();}+ Future<_BangumiDeleteSyncAction?> _resolveBangumiDeleteSyncAction(+ BangumiItem bangumiItem) async {+ final bool syncEnable =+ setting.get(SettingBoxKey.bangumiSyncEnable, defaultValue: false);+ if (!syncEnable) {+ return _BangumiDeleteSyncAction.deleteLocalOnly;+ }++ final bangumi = BangumiSyncService();+ if (!bangumi.initialized) {+ return _BangumiDeleteSyncAction.deleteLocalOnly;+ }++ return KazumiDialog.show<_BangumiDeleteSyncAction>(+ clickMaskDismiss: true,+ builder: (context) => AlertDialog(+ title: const Text('Bangumi 不支持删除收藏'),+ content: const Text(+ '因为安全考虑,Bangumi 未提供删除接口,您可以选择把本地和远端标记为“抛弃”,或者选择仅删除本地收藏并打开网页后手动删除 Bangumi 数据。',+ ),+ actions: [+ TextButton(+ onPressed: () {+ Navigator.of(context).pop(_BangumiDeleteSyncAction.cancel);+ },+ child: const Text('取消'),+ ),+ TextButton(+ onPressed: () {+ Navigator.of(context).pop(_BangumiDeleteSyncAction.openWeb);+ },+ child: const Text('打开网页'),+ ),+ FilledButton(+ onPressed: () {+ Navigator.of(context).pop(_BangumiDeleteSyncAction.markAbandoned);+ },+ child: const Text('标记为抛弃'),+ ),+ ],+ ),+ );+ }++ Future<void> _openBangumiSubjectPage(int bangumiId) async {+ final url = Uri.parse('https://bangumi.tv/subject/$bangumiId');+ if (await canLaunchUrl(url)) {+ await launchUrl(url, mode: LaunchMode.externalApplication);+ return;+ }+ KazumiDialog.showToast(message: '无法打开 Bangumi 网页');+ }++ Future<bool> _syncBangumiCollectIfEnabled(+ int bangumiId, int localType) async {+ final bool syncEnable =+ setting.get(SettingBoxKey.bangumiSyncEnable, defaultValue: false);+ final bool showImmediateSyncToast = setting.get(+ SettingBoxKey.bangumiImmediateSyncToastEnable,+ defaultValue: true,+ );++ if (!syncEnable) {+ return true;+ }++ final bangumi = BangumiSyncService();+ if (!bangumi.initialized) {+ KazumiDialog.showToast(message: 'Bangumi 未初始化,同步失败,已取消本次状态修改');+ KazumiLogger().w(+ 'Bangumi: immediate collect sync skipped because Bangumi is not initialized. '+ 'bangumiId=$bangumiId, type=$localType',+ );+ return false;+ }+ try {+ if (showImmediateSyncToast) {+ KazumiDialog.showToast(message: '正在同步到 Bangumi...');+ }+ final bool synced =+ await bangumi.syncCollectibleWhenIdle(bangumiId, localType);+ if (synced && showImmediateSyncToast) {+ KazumiDialog.showToast(message: '已同步到 Bangumi');+ return true;+ } else if (!synced) {+ KazumiDialog.showToast(message: '同步到 Bangumi 失败,已取消本次状态修改');+ KazumiLogger().w(+ 'Bangumi: immediate collect sync did not complete. bangumiId=$bangumiId, type=$localType',+ );+ return false;+ }+ return true;+ } catch (e, stackTrace) {+ KazumiDialog.showToast(message: '同步到 Bangumi 失败,已取消本次状态修改: $e');+ KazumiLogger().e(+ 'Bangumi: immediate collect sync failed. bangumiId=$bangumiId, type=$localType',+ error: e,+ stackTrace: stackTrace,+ );+ return false;+ }+ }+Future<void> updateLocalCollect(BangumiItem bangumiItem) async {await _collectCrudRepository.updateCollectible(bangumiItem);loadCollectibles();}- Future<void> syncCollectibles() async {+ Future<bool> syncCollectibles({bool showSuccessToast = true}) async {if (!WebDav().initialized) {KazumiDialog.showToast(message: '未开启WebDav同步或配置无效');- return;+ return false;}bool flag = true;try {@@ -87,14 +234,47 @@ abstract class _CollectController with Store {flag = false;}if (!flag) {- return;+ return false;}try {await WebDav().syncCollectibles();- } catch (e){+ KazumiDialog.showToast(message: 'WebDav同步完成');+ } catch (e) {KazumiDialog.showToast(message: 'WebDav同步失败 $e');+ return false;}loadCollectibles();+ return true;+ }++ /// 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 {+ if (!WebDav().initialized) {+ KazumiDialog.showToast(message: '未开启WebDav同步或配置无效');+ return false;+ }+ bool flag = true;+ try {+ await WebDav().ping();+ } catch (e) {+ KazumiLogger().e('WebDav: WebDav connection failed', error: e);+ KazumiDialog.showToast(message: 'WebDav连接失败: $e');+ flag = false;+ }+ if (!flag) {+ return false;+ }+ try {+ await WebDav().updateCollectibles();+ if (showSuccessToast) {+ KazumiDialog.showToast(message: 'WebDav上传完成');+ }+ } catch (e) {+ KazumiDialog.showToast(message: 'WebDav上传失败 $e');+ return false;+ }+ return true;}// migrate collect from old version (favorites)@@ -102,10 +282,20 @@ abstract class _CollectController with Store {if (favorites.isNotEmpty) {int count = 0;for (BangumiItem bangumiItem in favorites) {- await addCollect(bangumiItem, type: 1);+ // Migration should never depend on runtime Bangumi initialization.+ // Persist locally and append change logs, then let later sync handle remote updates.+ final int currentCollectType = getCollectType(bangumiItem);+ final int collectChangeAction = currentCollectType == 0 ? 1 : 2;+ await _collectCrudRepository.addCollectible(bangumiItem, 1);+ await GStorage.appendCollectChange(+ bangumiId: bangumiItem.id,+ action: collectChangeAction,+ type: 1,+ );count++;}await _collectCrudRepository.clearFavorites();+ loadCollectibles();KazumiLogger().d('GStorage: detected $count uncategorized favorites, migrated to collectibles');}}@@ -130,4 +320,43 @@ abstract class _CollectController with Store {.where((item) => !excludeIds.contains(item.id)).toList();}++ /// Sync Bangumi collectibles.+ Future<bool> syncCollectiblesBangumi(+ {void Function(String message, int current, int total)?+ onProgress,+ bool showSuccessToast = true}) async {+ final bool syncEnable =+ setting.get(SettingBoxKey.bangumiSyncEnable, defaultValue: false);+ if (!syncEnable) {+ KazumiDialog.showToast(message: '未开启Bangumi同步,请先在设置中启用');+ return false;+ }++ if (!BangumiSyncService().initialized) {+ KazumiDialog.showToast(message: 'Bangumi同步已开启但未初始化,请检查Token后重试');+ return false;+ }+ try {+ await BangumiSyncService().ping();+ try {+ final hasChanges =+ await BangumiSyncService().syncCollectibles(onProgress: onProgress);+ if (showSuccessToast) {+ KazumiDialog.showToast(+ message: hasChanges ? 'Bangumi同步完成' : '未发现状态差异,无需同步',+ );+ }+ } catch (e) {+ KazumiDialog.showToast(message: 'Bangumi同步失败 $e');+ return false;+ }+ } catch (e) {+ KazumiLogger().e('Bangumi: Bangumi connection failed', error: e);+ KazumiDialog.showToast(message: 'Bangumi访问失败: $e');+ return false;+ }+ loadCollectibles();+ return true;+ }}diff --git a/lib/pages/collect/collect_page.dart b/lib/pages/collect/collect_page.dartindex 1419cdda..90adb6cf 100644--- a/lib/pages/collect/collect_page.dart+++ b/lib/pages/collect/collect_page.dart@@ -1,3 +1,5 @@+import 'dart:async';+import 'package:flutter_mobx/flutter_mobx.dart';import 'package:kazumi/bean/dialog/dialog_helper.dart';import 'package:kazumi/modules/collect/collect_module.dart';@@ -29,7 +31,153 @@ class _CollectPageState extends State<CollectPage>bool syncCollectiblesing = false;Box setting = GStorage.setting;+ Future<bool> _syncBangumiWithProgress({+ required ValueNotifier<double?> progressValue,+ required ValueNotifier<String> progressText,+ }) async {+ progressText.value = '准备同步 Bangumi 收藏...';+ progressValue.value = null;++ await Future<void>.delayed(const Duration(milliseconds: 80));++ return collectController.syncCollectiblesBangumi(+ showSuccessToast: false,+ onProgress: (message, current, total) {+ progressText.value = total > 0 ? '$message ($current/$total)' : message;+ if (total > 0) {+ progressValue.value = (current / total).clamp(0.0, 1.0);+ } else {+ progressValue.value = null;+ }+ },+ );+ }++ void _showFullSyncProgressDialog({+ required ValueNotifier<double?> progressValue,+ required ValueNotifier<String> progressText,+ }) {+ unawaited(KazumiDialog.show(+ clickMaskDismiss: false,+ builder: (context) {+ return PopScope(+ canPop: false,+ child: Dialog(+ child: Padding(+ padding: const EdgeInsets.all(20.0),+ child: SizedBox(+ width: 340,+ child: Column(+ mainAxisSize: MainAxisSize.min,+ crossAxisAlignment: CrossAxisAlignment.start,+ children: [+ const Text(+ '收藏全量同步中',+ style: TextStyle(fontSize: 16, fontWeight: FontWeight.w600),+ ),+ const SizedBox(height: 12),+ ValueListenableBuilder<String>(+ valueListenable: progressText,+ builder: (_, value, __) => Text(value),+ ),+ const SizedBox(height: 12),+ ValueListenableBuilder<double?>(+ valueListenable: progressValue,+ builder: (_, value, __) => LinearProgressIndicator(value: value),+ ),+ ],+ ),+ ),+ ),+ ),+ );+ },+ ));+ }++ String _buildFullSyncSummary({+ required bool webDavEnabled,+ required bool bangumiEnabled,+ required bool webDavSynced,+ required bool bangumiSynced,+ required bool webDavUploaded,+ }) {+ final List<String> states = [];+ if (webDavEnabled) {+ states.add(webDavSynced ? 'WebDav 已同步' : 'WebDav 未完成');+ }+ if (bangumiEnabled) {+ states.add(bangumiSynced ? 'Bangumi 已同步' : 'Bangumi 未完成');+ }+ if (webDavEnabled && bangumiEnabled && webDavSynced && bangumiSynced) {+ states.add(webDavUploaded ? 'WebDav 已回传最新数据' : 'WebDav 未回传最新数据');+ }+ return states.join(',');+ }++ Future<void> _runFullSync({+ required bool webDavEnabled,+ required bool bangumiEnabled,+ }) async {+ final ValueNotifier<double?> progressValue = ValueNotifier<double?>(null);+ final ValueNotifier<String> progressText = ValueNotifier<String>('准备开始同步收藏...');++ _showFullSyncProgressDialog(+ progressValue: progressValue,+ progressText: progressText,+ );++ await Future<void>.delayed(const Duration(milliseconds: 80));++ bool webDavSynced = false;+ bool bangumiSynced = false;+ bool webDavUploaded = false;++ try {+ if (webDavEnabled) {+ progressText.value = '正在同步 WebDav 收藏...';+ progressValue.value = null;+ webDavSynced =+ await collectController.syncCollectibles(showSuccessToast: false);+ }++ if (bangumiEnabled) {+ bangumiSynced = await _syncBangumiWithProgress(+ progressValue: progressValue,+ progressText: progressText,+ );+ }++ if (webDavEnabled && bangumiEnabled && webDavSynced && bangumiSynced) {+ progressText.value = '正在回传最新收藏到 WebDav...';+ progressValue.value = null;+ webDavUploaded = await collectController.uploadCollectiblesToWebDav(+ showSuccessToast: false,+ );+ }+ } finally {+ if (KazumiDialog.observer.hasKazumiDialog) {+ KazumiDialog.dismiss();+ }+ progressValue.dispose();+ progressText.dispose();+ }++ KazumiDialog.showToast(+ message: _buildFullSyncSummary(+ webDavEnabled: webDavEnabled,+ bangumiEnabled: bangumiEnabled,+ webDavSynced: webDavSynced,+ bangumiSynced: bangumiSynced,+ webDavUploaded: webDavUploaded,+ ),+ );+ }+void onBackPressed(BuildContext context) {+ if (syncCollectiblesing) {+ return;+ }if (KazumiDialog.observer.hasKazumiDialog) {KazumiDialog.dismiss();return;@@ -69,6 +217,9 @@ class _CollectPageState extends State<CollectPage>if (didPop) {return;}+ if (syncCollectiblesing) {+ return;+ }onBackPressed(context);},child: Scaffold(@@ -96,9 +247,11 @@ class _CollectPageState extends State<CollectPage>floatingActionButton: FloatingActionButton(onPressed: () async {bool webDavenable = await setting.get(SettingBoxKey.webDavEnable,- defaultValue: false);- if (!webDavenable) {- KazumiDialog.showToast(message: 'webDav未启用, 同步功能不可用');+ defaultValue: false);+ bool bgmSyncEnable = await setting.get(SettingBoxKey.bangumiSyncEnable,+ defaultValue: false);+ if (!webDavenable && !bgmSyncEnable) {+ KazumiDialog.showToast(message: '同步功能不可用,请至少开启一个同步功能');return;}if (showDelete) {@@ -111,10 +264,18 @@ class _CollectPageState extends State<CollectPage>setState(() {syncCollectiblesing = true;});- await collectController.syncCollectibles();- setState(() {- syncCollectiblesing = false;- });+ try {+ await _runFullSync(+ webDavEnabled: webDavenable,+ bangumiEnabled: bgmSyncEnable,+ );+ } finally {+ if (mounted) {+ setState(() {+ syncCollectiblesing = false;+ });+ }+ }},child: syncCollectiblesing? const SizedBox(diff --git a/lib/pages/init_page.dart b/lib/pages/init_page.dartindex b2d4f1e2..5f6f0e92 100644--- a/lib/pages/init_page.dart+++ b/lib/pages/init_page.dart@@ -3,6 +3,7 @@ import 'package:flutter/material.dart';import 'package:hive_ce/hive.dart';import 'package:kazumi/bean/dialog/dialog_helper.dart';import 'package:kazumi/pages/my/my_controller.dart';+import 'package:kazumi/utils/bangumi_sync_service.dart';import 'package:kazumi/utils/webdav.dart';import 'package:kazumi/utils/storage.dart';import 'package:kazumi/plugins/plugins_controller.dart';@@ -47,6 +48,7 @@ class _InitPageState extends State<InitPage> {_loadShaders();_loadDanmakuShield();_webDavInit();+ _bangumiInit();try {await downloadController.init();_setupBackgroundDownloadNavigation();@@ -155,6 +157,30 @@ class _InitPageState extends State<InitPage> {}}+ Future<void> _bangumiInit() async {+ bool bangumiEnable = await setting.get(+ SettingBoxKey.bangumiSyncEnable,+ defaultValue: false,+ );+ if (bangumiEnable) {+ var bangumi = BangumiSyncService();+ KazumiLogger().i('Bangumi: Starting Bangumi initialization');+ try {+ await bangumi.init();+ } catch (e) {+ bangumi.reset();+ await setting.put(SettingBoxKey.bangumiSyncEnable, false);+ KazumiLogger().w(+ 'Bangumi: initialization failed, disabling Bangumi sync until user re-enables it',+ error: e,+ );+ KazumiDialog.showToast(+ message: '初始化Bangumi失败,已关闭 Bangumi 同步: ${e.toString()}',+ );+ }+ }+ }+Future<void> _checkRunningOnX11() async {if (!Platform.isLinux) {return;diff --git a/lib/pages/settings/settings_module.dart b/lib/pages/settings/settings_module.dartindex 474b4527..d7a6376a 100644--- a/lib/pages/settings/settings_module.dart+++ b/lib/pages/settings/settings_module.dart@@ -15,6 +15,7 @@ import 'package:kazumi/pages/webdav_editor/webdav_module.dart';import 'package:kazumi/pages/settings/keyboard_settings.dart';import 'package:kazumi/pages/settings/download_settings.dart';import 'package:kazumi/pages/download/download_page_module.dart';+import 'package:kazumi/pages/bangumi/bangumi_module.dart';class SettingsModule extends Module {@override@@ -38,5 +39,6 @@ class SettingsModule extends Module {r.module("/danmaku", module: DanmakuModule());r.module("/download", module: DownloadModule());r.child("/download-settings", child: (_) => const DownloadSettingsPage());+ r.module("/bangumi", module: BangumiModule());}}diff --git a/lib/pages/webdav_editor/webdav_setting.dart b/lib/pages/webdav_editor/webdav_setting.dartindex 817c6f77..2a571606 100644--- a/lib/pages/webdav_editor/webdav_setting.dart+++ b/lib/pages/webdav_editor/webdav_setting.dart@@ -1,5 +1,6 @@import 'package:flutter/material.dart';import 'package:kazumi/bean/dialog/dialog_helper.dart';+import 'package:kazumi/utils/bangumi_sync_service.dart';import 'package:kazumi/utils/storage.dart';import 'package:kazumi/utils/webdav.dart';import 'package:hive_ce/hive.dart';@@ -19,6 +20,7 @@ class _PlayerSettingsPageState extends State<WebDavSettingsPage> {late bool webDavEnable;late bool webDavEnableHistory;late bool enableGitProxy;+ late bool bangumiSyncEnable;@overridevoid initState() {@@ -28,6 +30,8 @@ class _PlayerSettingsPageState extends State<WebDavSettingsPage> {setting.get(SettingBoxKey.webDavEnableHistory, defaultValue: false);enableGitProxy =setting.get(SettingBoxKey.enableGitProxy, defaultValue: false);+ bangumiSyncEnable =+ setting.get(SettingBoxKey.bangumiSyncEnable, defaultValue: false);}void onBackPressed(BuildContext context) {@@ -69,12 +73,12 @@ class _PlayerSettingsPageState extends State<WebDavSettingsPage> {await webDav.ping();try {await webDav.updateHistory();- KazumiDialog.showToast(message: '同步成功');+ KazumiDialog.showToast(message: 'WebDav同步成功');} catch (e) {- KazumiDialog.showToast(message: '同步失败 ${e.toString()}');+ KazumiDialog.showToast(message: 'WebDav同步失败 ${e.toString()}');}} catch (e) {- KazumiDialog.showToast(message: 'WebDAV连接失败');+ KazumiDialog.showToast(message: 'WebDav连接失败');}} else {KazumiDialog.showToast(message: '未开启WebDav同步或配置无效');@@ -91,9 +95,9 @@ class _PlayerSettingsPageState extends State<WebDavSettingsPage> {await webDav.ping();try {await webDav.downloadAndPatchHistory();- KazumiDialog.showToast(message: '同步成功');+ KazumiDialog.showToast(message: 'WebDav同步成功');} catch (e) {- KazumiDialog.showToast(message: '同步失败 ${e.toString()}');+ KazumiDialog.showToast(message: 'WebDav同步失败 ${e.toString()}');}} catch (e) {KazumiDialog.showToast(message: 'WebDAV连接失败');@@ -206,6 +210,57 @@ class _PlayerSettingsPageState extends State<WebDavSettingsPage> {),],),+ SettingsSection(+ title: Text('Bangumi', style: TextStyle(fontFamily: fontFamily)),+ tiles: [+ SettingsTile.switchTile(+ onToggle: (value) async {+ final tBangumiEnableSync = value ?? !bangumiSyncEnable;+ final bangumi = BangumiSyncService();+ if (tBangumiEnableSync == true) {+ final token = setting.get(+ SettingBoxKey.bangumiAccessToken,+ defaultValue: '').toString().trim();+ if (token.isEmpty) {+ KazumiDialog.showToast(+ message: '请先配置 Bangumi 的 Access Token');+ return;+ } else {+ if (!bangumi.initialized) {+ try {+ await bangumi.init();+ } catch (e) {+ KazumiDialog.showToast(+ message: "Bangumi 初始化失败,请稍后再试");+ return;+ }+ }+ }+ }+ bangumiSyncEnable = tBangumiEnableSync;+ await setting.put(+ SettingBoxKey.bangumiSyncEnable, bangumiSyncEnable);+ if (!mounted) {+ return;+ }+ setState(() {});+ },+ title: Text('Bangumi 同步', style: TextStyle(fontFamily: fontFamily)),+ description: Text('允许与Bangumi自动同步收藏/追番状态', style: TextStyle(fontFamily: fontFamily)),+ initialValue: bangumiSyncEnable,+ ),+ SettingsTile.navigation(+ onPressed: (_) async {+ await Modular.to.pushNamed('/settings/bangumi/');+ bangumiSyncEnable = setting.get(+ SettingBoxKey.bangumiSyncEnable,+ defaultValue: false);+ setState(() {});+ },+ title: Text('Bangumi 配置', style: TextStyle(fontFamily: fontFamily)),+ ),+ ],+ ),],),),diff --git a/lib/repositories/collect_crud_repository.dart b/lib/repositories/collect_crud_repository.dartindex cb4710d1..6979a743 100644--- a/lib/repositories/collect_crud_repository.dart+++ b/lib/repositories/collect_crud_repository.dart@@ -56,7 +56,6 @@ abstract class ICollectCrudRepository {/// 基于Hive实现的收藏CRUD数据访问层class CollectCrudRepository implements ICollectCrudRepository {final _collectiblesBox = GStorage.collectibles;- final _collectChangesBox = GStorage.collectChanges;final _favoritesBox = GStorage.favorites;@override@@ -107,8 +106,7 @@ class CollectCrudRepository implements ICollectCrudRepository {DateTime.now(),type,);- await _collectiblesBox.put(bangumiItem.id, collectedBangumi);- await _collectiblesBox.flush();+ await GStorage.putCollectible(collectedBangumi);} catch (e, stackTrace) {KazumiLogger().e('GStorage: add collectible failed. id=${bangumiItem.id}, type=$type',@@ -130,8 +128,7 @@ class CollectCrudRepository implements ICollectCrudRepository {return;}collectible.bangumiItem = bangumiItem;- await _collectiblesBox.put(bangumiItem.id, collectible);- await _collectiblesBox.flush();+ await GStorage.putCollectible(collectible);} catch (e, stackTrace) {KazumiLogger().e('GStorage: update collectible failed. id=${bangumiItem.id}',@@ -145,8 +142,7 @@ class CollectCrudRepository implements ICollectCrudRepository {@overrideFuture<void> deleteCollectible(int id) async {try {- await _collectiblesBox.delete(id);- await _collectiblesBox.flush();+ await GStorage.deleteCollectible(id);} catch (e, stackTrace) {KazumiLogger().e('GStorage: delete collectible failed. id=$id',@@ -160,8 +156,7 @@ class CollectCrudRepository implements ICollectCrudRepository {@overrideFuture<void> addCollectChange(CollectedBangumiChange change) async {try {- await _collectChangesBox.put(change.id, change);- await _collectChangesBox.flush();+ await GStorage.putCollectChange(change);} catch (e, stackTrace) {KazumiLogger().e('GStorage: record collect change failed. changeId=${change.id}',diff --git a/lib/request/api.dart b/lib/request/api.dartindex cc541d07..f83a93fe 100644--- a/lib/request/api.dart+++ b/lib/request/api.dart@@ -31,6 +31,12 @@ class Api {static const String bangumiCharacterByID = '/v0/subjects/{0}/characters';/// 从条目ID获取剧集IDstatic const String bangumiEpisodeByID = '/v0/episodes';+ /// 返回当前 Access Token 对应的用户信息+ static const String bangumiUsernameByToken = '/v0/me';+ /// 新增或修改用户单个条目收藏+ static const String bangumiSetCollection = '/v0/users/-/collections/{0}';+ /// 获取用户收藏。用户名,分页参数1,分页参数2+ static const String bangumiGetCollection = '/v0/users/{0}/collections?subject_type=2&limit={1}&offset={2}&type={3}';/// Bangumi Next API Domainstatic const String bangumiAPINextDomain = 'https://next.bgm.tv';diff --git a/lib/request/bangumi.dart b/lib/request/bangumi.dartindex 63bce7f2..409692cf 100644--- a/lib/request/bangumi.dart+++ b/lib/request/bangumi.dart@@ -1,3 +1,6 @@+import 'dart:ffi';++import 'package:dio/dio.dart';import 'package:kazumi/utils/logger.dart';import 'package:kazumi/request/api.dart';import 'package:kazumi/request/request.dart';@@ -7,6 +10,10 @@ import 'package:kazumi/modules/characters/characters_response.dart';import 'package:kazumi/modules/bangumi/episode_item.dart';import 'package:kazumi/modules/character/character_full_item.dart';import 'package:kazumi/modules/staff/staff_response.dart';+import 'package:kazumi/modules/bangumi/bangumi_collection.dart';+import 'package:kazumi/modules/collect/collect_type.dart';+import 'package:kazumi/modules/collect/collect_type_mapper.dart';+import 'package:kazumi/modules/bangumi/bangumi_collection_type.dart';class BangumiHTTP {// why the api havn't been replaced by getCalendarBySearch?@@ -305,4 +312,172 @@ class BangumiHTTP {}return characterFullItem;}++ static Future<String?> getUsername() async {+ try {+ final res = await Request().get(+ Api.formatUrl(Api.bangumiAPIDomain + Api.bangumiUsernameByToken, []),+ extra: {'customError': '', 'requiresBangumiAuth': true},+ shouldRethrow: true,+ );+ if (res.data['id'] != null) {+ return res.data['username'] ?? 'Unknown';+ }+ } on DioException catch (e) {+ if (e.response?.statusCode == 401) {+ KazumiLogger().e('Bangumi token unauthorized, please check your token');+ throw StateError('Bangumi token 未授权,请检查您的 token');+ }+ rethrow;+ } catch (e) {+ KazumiLogger().e('Network: get username failed', error: e);+ }+ return null;+ }++ /// Get the Bangumi collection of the current user+ static Future<List<BangumiCollection>> getBangumiCollectibles({+ List<BangumiCollectionType> includeBangumiTypes = const [+ BangumiCollectionType.planToWatch,+ BangumiCollectionType.watched,+ BangumiCollectionType.watching,+ BangumiCollectionType.onHold,+ BangumiCollectionType.abandoned,+ ],+ String? username,+ required int limit,+ void Function(String message, int current, int total)? onProgress,+ }) async {+ final List<BangumiCollection> bangumiCollection = [];+ final resolvedUsername =+ username != null && username.isNotEmpty ? username : await getUsername();+ int failedItemCount = 0;+ int progressCurrent = 0;+ int progressTotal = 0;+ if (resolvedUsername == null) {+ KazumiLogger().w('get username failed');+ return [];+ }++ try {+ const Duration requestInterval = Duration(milliseconds: 250);++ for (final collectionType in includeBangumiTypes) {+ if (collectionType == BangumiCollectionType.unknown) {+ continue;+ }+ int offset = 0;+ int? total;+ bool totalInitialized = false;+ while (true) {+ Response<dynamic> res;+ try {+ final url = Api.formatUrl(+ Api.bangumiAPIDomain + Api.bangumiGetCollection,+ [resolvedUsername, limit, offset, collectionType.value]);+ res = await Request().get(+ url,+ extra: {'customError': '', 'requiresBangumiAuth': true},+ shouldRethrow: true,+ );+ } catch (e) {+ KazumiLogger().e(+ 'BangumiHTTP: fetch collection failed. type=${collectionType.value}, offset=$offset',+ error: e,+ );+ rethrow;+ }++ final Map jsonData = res.data;+ final List<dynamic> jsonList = jsonData['data'];+ total ??= jsonData['total'];+ if (!totalInitialized && total != null) {+ progressTotal += total;+ totalInitialized = true;+ }++ for (dynamic jsonItem in jsonList) {+ if (jsonItem is Map<String, dynamic>) {+ try {+ bangumiCollection.add(BangumiCollection.fromJson(jsonItem));+ progressCurrent++;+ onProgress?.call(+ '正在拉取${collectionType.label}收藏',+ progressCurrent,+ progressTotal,+ );+ } catch (e) {+ KazumiLogger().e(+ 'BangumiHTTP: parse collection item failed: ${e.toString()}',+ error: e,+ );+ failedItemCount++;+ }+ }+ }++ if (jsonList.isEmpty || (total != null && offset + limit >= total)) {+ break;+ }++ offset += limit;+ await Future.delayed(requestInterval);+ }+ }+ } catch (e) {+ KazumiLogger().e('Network: get bangumi collection failed', error: e);+ rethrow;+ }+ KazumiLogger()+ .d('get Bangumi collection count: ${bangumiCollection.length}');+ KazumiLogger().d('get item failed count: $failedItemCount');+ return bangumiCollection;+ }++ /// Update the Bangumi collection by ID+ static Future<bool> updateBangumiById(+ int id, Map<String, dynamic> data) async {+ const Duration requestInterval = Duration(milliseconds: 250);+ try {+ await Request().post(+ Api.formatUrl(Api.bangumiAPIDomain + Api.bangumiSetCollection, [id]),+ data: data,+ extra: {'customError': '', 'requiresBangumiAuth': true},+ shouldRethrow: true,+ );+ KazumiLogger().d('Update to Bangumi: Id: $id');+ return true;+ } on DioException catch (e) {+ String str;+ switch (e.response?.statusCode) {+ case 400:+ str = 'Validation Error 验证错误';+ break;+ case 401:+ str = 'Unauthorized 未经授权';+ break;+ case 404:+ str = 'User not found 用户不存在';+ break;+ default:+ str = 'Error $e';+ }+ KazumiLogger().e('BangumiApi: $str', error: e);+ return false;+ } catch (e) {+ KazumiLogger().e('Network: update bangumi collection failed', error: e);+ rethrow;+ } finally {+ await Future.delayed(requestInterval);+ }+ }++ /// Update the Bangumi collection by Type+ static Future<bool> updateBangumiByType(int id, int localType) async {+ final type = CollectType.fromValue(localType).toBangumiCollectionType();+ if (type == null) {+ return false;+ }+ return await updateBangumiById(id, {'type': type.value});+ }}diff --git a/lib/request/interceptor.dart b/lib/request/interceptor.dartindex 2560ed05..1588cac1 100644--- a/lib/request/interceptor.dart+++ b/lib/request/interceptor.dart@@ -34,7 +34,22 @@ class ApiInterceptor extends Interceptor {}if (options.path.contains(Api.bangumiAPIDomain) ||options.path.contains(Api.bangumiAPINextDomain)) {- options.headers = bangumiHTTPHeader;+ final mergedHeaders = <String, dynamic>{+ ...options.headers,+ ...bangumiHTTPHeader,+ };+ final bool bangumiSyncEnable =+ setting.get(SettingBoxKey.bangumiSyncEnable, defaultValue: false);+ final bool requiresBangumiAuth =+ options.extra['requiresBangumiAuth'] == true;+ final String token = setting+ .get(SettingBoxKey.bangumiAccessToken, defaultValue: '')+ .toString()+ .trim();+ if ((bangumiSyncEnable || requiresBangumiAuth) && token.isNotEmpty) {+ mergedHeaders['Authorization'] = 'Bearer $token';+ }+ options.headers = mergedHeaders;}handler.next(options);}diff --git a/lib/request/request.dart b/lib/request/request.dartindex f470e96c..c2084112 100644--- a/lib/request/request.dart+++ b/lib/request/request.dart@@ -118,18 +118,41 @@ class Request {};}+ // Merge extra options into the main options+ void _applyExtraOptions(Options options, Map? extra) {+ if (extra == null) {+ return;+ }++ if (extra['ua'] != null) {+ options.headers = {+ ...?options.headers,+ 'user-agent': headerUa(type: extra['ua']),+ };+ }++ if (extra['customError'] != null) {+ options.extra = {+ ...?options.extra,+ 'customError': extra['customError'],+ };+ }++ if (extra['requiresBangumiAuth'] != null) {+ options.extra = {+ ...?options.extra,+ 'requiresBangumiAuth': extra['requiresBangumiAuth'],+ };+ }+ }+Future<Response> get(url, {data, options, cancelToken, extra, bool shouldRethrow = false}) async {Response response;ResponseType resType = ResponseType.json;options ??= Options();if (extra != null) {- resType = extra!['resType'] ?? ResponseType.json;- if (extra['ua'] != null) {- options.headers = {'user-agent': headerUa(type: extra['ua'])};- }- if (extra['customError'] != null) {- options.extra = {'customError': extra['customError']};- }+ resType = extra['resType'] ?? ResponseType.json;+ _applyExtraOptions(options, extra);}options.responseType = resType;try {@@ -158,6 +181,13 @@ class Request {Future<Response> post(url, {data, queryParameters, options, cancelToken, extra, bool shouldRethrow = false}) async {// print('post-data: $data');Response response;+ ResponseType resType = ResponseType.json;+ options ??= Options();+ if (extra != null) {+ resType = extra['resType'] ?? ResponseType.json;+ _applyExtraOptions(options, extra);+ }+ options.responseType = resType;try {response = await dio.post(url,@@ -186,4 +216,4 @@ class Request {String headerUa({type = 'mob'}) {return Utils.getRandomUA();}-}\ No newline at end of file+}diff --git a/lib/utils/bangumi_sync_service.dart b/lib/utils/bangumi_sync_service.dartnew file mode 100644index 00000000..772d99f0--- /dev/null+++ b/lib/utils/bangumi_sync_service.dart@@ -0,0 +1,274 @@+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/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/bangumi.dart';++/// Bangumi 同步服务工具类+class BangumiSyncService {+ /// Current username, set by ping()+ String username = '';++ /// Init status, set after ping() in init()+ bool initialized = false;++ /// Hive+ Box setting = GStorage.setting;++ /// Number of queued Bangumi operations waiting+ int _queuedOperationCount = 0;++ /// Number of Bangumi operations running+ int _activeOperationCount = 0;++ /// Serial queue for all Bangumi operations+ Future<void> _operationQueue = Future.value();++ /// Whether any Bangumi operation is active or already queued.+ bool get isUsing => _queuedOperationCount > 0 || _activeOperationCount > 0;++ String get _configuredToken => setting+ .get(SettingBoxKey.bangumiAccessToken, defaultValue: '')+ .toString()+ .trim();++ BangumiSyncService._internal();+ static final BangumiSyncService _instance = BangumiSyncService._internal();+ factory BangumiSyncService() => _instance;++ void reset() {+ initialized = false;+ username = '';+ }++ Future<void> init() async {+ initialized = false;+ username = '';+ if (_configuredToken.isEmpty) {+ throw Exception('请先填写Bangumi Access Token');+ }+ try {+ await ping();+ initialized = true;+ } catch (e) {+ KazumiLogger().e('Bangumi: Bangumi ping failed', error: e);+ rethrow;+ }+ }++ Future<void> ping() async {+ if (isUsing) {+ throw Exception('Bangumi: 当前有操作正在进行,请稍后再试');+ }+ await _runExclusive(() async {+ try {+ final name = await BangumiHTTP.getUsername();+ if (name == null) {+ throw Exception('Bangumi: 获取用户名失败');+ } else {+ username = name;+ }+ } catch (e) {+ KazumiLogger().e('Bangumi: Bangumi ping failed', error: e);+ rethrow;+ }+ });+ }++ /// Update a single collectible on Bangumi, waiting for current Bangumi work+ /// to finish and serializing multiple immediate update requests.+ Future<bool> syncCollectibleWhenIdle(int bangumiId, int localType) {+ return _runExclusive(() async {+ return BangumiHTTP.updateBangumiByType(+ bangumiId,+ localType,+ );+ });+ }++ Future<T> _runExclusive<T>(Future<T> Function() action) {+ final completer = Completer<T>();+ final previousOperation = _operationQueue;+ _queuedOperationCount++;++ _operationQueue = (() async {+ try {+ await previousOperation;+ } catch (_) {}++ _queuedOperationCount--;+ _activeOperationCount++;+ try {+ completer.complete(await action());+ } catch (e, stackTrace) {+ completer.completeError(e, stackTrace);+ } finally {+ _activeOperationCount--;+ }+ })();++ return completer.future;+ }++ /// Record a collectible change (used for WebDAV incremental sync)+ /// [action] 1 代表新增(add),2 代表修改(update)+ /// [type] via: [CollectType]+ Future<void> _recordCollectibleChange(+ int bangumiId,+ int action,+ int type,+ ) async {+ await GStorage.appendCollectChange(+ bangumiId: bangumiId,+ action: action,+ type: type,+ );+ }++ /// Sync Bangumi collectibles with local data+ Future<bool> syncCollectibles({+ void Function(String message, int current, int total)? onProgress,+ }) async {+ final syncEnable =+ setting.get(SettingBoxKey.bangumiSyncEnable, defaultValue: false);+ if (!syncEnable) {+ KazumiDialog.showToast(message: '同步已关闭');+ KazumiLogger().i('Bangumi: sync disabled');+ return false;+ }+ if (isUsing) {+ KazumiLogger().w('Bangumi is currently syncing');+ throw Exception('Bangumi 正在同步');+ }+ return _runExclusive(() async {+ try {+ onProgress?.call('开始同步 Bangumi 状态', 0, 0);++ final priority = BangumiSyncPriority.fromValue(+ setting.get(SettingBoxKey.bangumiSyncPriority, defaultValue: 0),+ );++ // 1. 全量拉取远程收藏+ final remoteCollection = await BangumiHTTP.getBangumiCollectibles(+ username: username,+ limit: 100,+ onProgress: onProgress,+ );++ // 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;++ if (totalOperations == 0) {+ onProgress?.call('未发现状态差异,无需同步', 1, 1);+ return false;+ }++ int syncedCount = 0;+ // 3. 仅本地有:直接上传到 Bangumi+ if (localOnlyIds.isNotEmpty) {+ onProgress?.call('正在上传本地新增状态', syncedCount, totalOperations);+ for (final id in localOnlyIds) {+ final updated = await BangumiHTTP.updateBangumiByType(+ id,+ localMap[id]!.type,+ );+ if (!updated) {+ onProgress?.call('上传本地新增状态失败', syncedCount, totalOperations);+ throw Exception('同步失败:条目 $id 上传到 Bangumi 失败');+ }+ syncedCount++;+ onProgress?.call('正在上传本地新增状态', syncedCount, totalOperations);+ }+ }++ // 4. 仅远程有:直接补到本地+ if (remoteOnlyIds.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,+ );+ await GStorage.putCollectible(collected);+ await _recordCollectibleChange(id, 1, localType.value);+ syncedCount++;+ onProgress?.call('正在补全本地缺失状态', syncedCount, totalOperations);+ }+ }++ // 5. 双方都有但不一致:按优先级处理+ if (priority == BangumiSyncPriority.localFirst) {+ onProgress?.call('本地优先:正在处理冲突状态', syncedCount, totalOperations);+ for (final id in mismatchIds) {+ final updated =+ await BangumiHTTP.updateBangumiByType(id, localMap[id]!.type);+ if (updated != true) {+ throw Exception('同步失败:条目 $id 上传到 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);+ syncedCount++;+ onProgress?.call(+ 'Bangumi优先:正在处理冲突状态', syncedCount, totalOperations);+ }+ }+ onProgress?.call('Bangumi 状态同步完成', 1, 1);+ return true;+ } catch (e) {+ KazumiLogger().e('Bangumi sync failed', error: e);+ rethrow;+ }+ });+ }+}diff --git a/lib/utils/storage.dart b/lib/utils/storage.dartindex 6c3e9294..b903bc80 100644--- a/lib/utils/storage.dart+++ b/lib/utils/storage.dart@@ -1,3 +1,4 @@+import 'dart:async';import 'dart:io';import 'package:hive_ce/hive.dart';import 'package:kazumi/utils/logger.dart';@@ -24,6 +25,119 @@ class GStorage {/// Hive directory path, initialized during init()static String? _hivePath;+ /// Queue to serialize write operations+ static Future<void> _collectChangesWriteQueue = Future.value();++ /// Next ID+ static int _nextCollectChangeId = 0;++ /// Flag to indicate if the next ID has initialized+ static bool _collectChangeIdInitialized = false;++ /// Ensure collect-related write sequentially+ static Future<T> _runCollectChangesWriteExclusive<T>(+ Future<T> Function() action,+ ) {+ final completer = Completer<T>();+ final previousWrite = _collectChangesWriteQueue;++ _collectChangesWriteQueue = (() async {+ try {+ await previousWrite;+ } catch (_) {}++ try {+ completer.complete(await action());+ } catch (e, stackTrace) {+ completer.completeError(e, stackTrace);+ }+ })();++ return completer.future;+ }++ /// init id generator+ static void _initializeNextCollectChangeIdLocked() {+ if (_collectChangeIdInitialized) {+ return;+ }++ var maxExistingId = 0;+ for (final key in collectChanges.keys) {+ if (key is int && key > maxExistingId) {+ maxExistingId = key;+ }+ }++ _nextCollectChangeId = maxExistingId;+ _collectChangeIdInitialized = true;+ }++ /// Generate id for collect change+ static int _generateCollectChangeIdLocked() {+ _initializeNextCollectChangeIdLocked();++ final currentSeconds = DateTime.now().millisecondsSinceEpoch ~/ 1000;+ // Ensure ID is greater than any existing ID, or equal to current timestamp.+ var nextId = _nextCollectChangeId < currentSeconds+ ? currentSeconds+ : _nextCollectChangeId + 1;+ while (collectChanges.containsKey(nextId)) {+ nextId++;+ }+ _nextCollectChangeId = nextId;+ return nextId;+ }++ /// Append a new collect change+ static Future<CollectedBangumiChange> appendCollectChange({+ required int bangumiId,+ required int action,+ required int type,+ int? timestamp,+ }) {+ return _runCollectChangesWriteExclusive(() async {+ final change = CollectedBangumiChange(+ _generateCollectChangeIdLocked(),+ bangumiId,+ action,+ type,+ timestamp ?? (DateTime.now().millisecondsSinceEpoch ~/ 1000),+ );+ await collectChanges.put(change.id, change);+ await collectChanges.flush();+ return change;+ });+ }++ /// Update an existing collect change+ static Future<void> putCollectChange(CollectedBangumiChange change) {+ return _runCollectChangesWriteExclusive(() async {+ _initializeNextCollectChangeIdLocked();+ if (change.id > _nextCollectChangeId) {+ _nextCollectChangeId = change.id;+ }+ await collectChanges.put(change.id, change);+ await collectChanges.flush();+ });+ }++ /// Put a collectible using the same write queue+ static Future<void> putCollectible(CollectedBangumi collectible) {+ return _runCollectChangesWriteExclusive(() async {+ await collectibles.put(collectible.bangumiItem.id, collectible);+ await collectibles.flush();+ });+ }++ /// Delete a collectible using the shared collect write queue.+ static Future<void> deleteCollectible(int bangumiId) {+ return _runCollectChangesWriteExclusive(() async {+ await collectibles.delete(bangumiId);+ await collectibles.flush();+ });+ }+static Future init() async {_hivePath = '${(await getApplicationSupportDirectory()).path}/hive';@@ -180,8 +294,9 @@ class GStorage {static Future<void> patchCollectibles(List<CollectedBangumi> remoteCollectibles,List<CollectedBangumiChange> remoteChanges) async {- List<CollectedBangumi> localCollectibles = collectibles.values.toList();- List<CollectedBangumiChange> localChanges = collectChanges.values.toList();+ await _runCollectChangesWriteExclusive(() async {+ final localCollectibles = collectibles.values.toList();+ final localChanges = collectChanges.values.toList();final List<CollectedBangumiChange> newLocalChanges =localChanges.where((localChange) {@@ -253,10 +368,17 @@ class GStorage {for (var collect in remoteCollectibles) {await collectibles.put(collect.bangumiItem.id, collect);}+ await collectibles.flush();+await collectChanges.clear();for (var change in mergedChanges) {await collectChanges.put(change.id, change);}+ await collectChanges.flush();++ _collectChangeIdInitialized = false;+ _initializeNextCollectChangeIdLocked();+ });}// Prevent instantiation@@ -343,5 +465,9 @@ class SettingBoxKey {downloadParallelEpisodes = 'downloadParallelEpisodes',downloadParallelSegments = 'downloadParallelSegments',downloadDanmaku = 'downloadDanmaku',- shortcutDialogShown = 'shortcutDialogShown';+ shortcutDialogShown = 'shortcutDialogShown',+ bangumiSyncEnable = 'bangumiSyncEnable',+ bangumiAccessToken = 'bangumiAccessToken',+ bangumiSyncPriority = 'bangumiSyncPriority',+ bangumiImmediateSyncToastEnable = 'bangumiImmediateSyncToastEnable';}