基于自定义规则的番剧采集APP,支持流媒体在线观看,支持弹幕,支持实时超分辨率。
refactor: webdav history sync (#2056)
Predidit88c616a836d7
diff --git a/lib/modules/history/history_sync.dart b/lib/modules/history/history_sync.dartnew file mode 100644index 00000000..1a4d8f47--- /dev/null+++ b/lib/modules/history/history_sync.dart@@ -0,0 +1,577 @@+import 'dart:convert';+import 'dart:math';++import 'package:kazumi/modules/bangumi/bangumi_item.dart';+import 'package:kazumi/modules/bangumi/bangumi_tag.dart';+import 'package:kazumi/modules/history/history_module.dart';++enum HistorySyncOp {+ upsertProgress('upsertProgress'),+ deleteHistory('deleteHistory'),+ clearAll('clearAll');++ const HistorySyncOp(this.value);++ final String value;++ static HistorySyncOp fromValue(String value) {+ return HistorySyncOp.values.firstWhere(+ (op) => op.value == value,+ orElse: () => throw FormatException('Unknown history sync op: $value'),+ );+ }+}++class HistorySyncDevice {+ static String generateDeviceId() {+ final random = Random.secure();+ final bytes = List<int>.generate(16, (_) => random.nextInt(256));+ bytes[6] = (bytes[6] & 0x0f) | 0x40;+ bytes[8] = (bytes[8] & 0x3f) | 0x80;+ final hex = bytes.map((b) => b.toRadixString(16).padLeft(2, '0')).join();+ return [+ hex.substring(0, 8),+ hex.substring(8, 12),+ hex.substring(12, 16),+ hex.substring(16, 20),+ hex.substring(20),+ ].join('-');+ }+}++class HistorySyncEvent {+ const HistorySyncEvent({+ required this.eventId,+ required this.deviceId,+ required this.seq,+ required this.op,+ required this.updatedAt,+ this.entityKey,+ this.bangumiItem,+ this.adapterName,+ this.episode,+ this.road,+ this.progressMs,+ this.lastSrc,+ this.lastWatchEpisodeName,+ });++ final String eventId;+ final String deviceId;+ final int seq;+ final HistorySyncOp op;+ final int updatedAt;+ final String? entityKey;+ final BangumiItem? bangumiItem;+ final String? adapterName;+ final int? episode;+ final int? road;+ final int? progressMs;+ final String? lastSrc;+ final String? lastWatchEpisodeName;++ String get version => HistorySyncVersion.of(+ updatedAt: updatedAt,+ eventId: eventId,+ );++ factory HistorySyncEvent.upsertProgress({+ required String deviceId,+ required int seq,+ required History history,+ required int episode,+ required int road,+ required int progressMs,+ required int updatedAt,+ }) {+ return HistorySyncEvent(+ eventId: '$deviceId:$seq',+ deviceId: deviceId,+ seq: seq,+ op: HistorySyncOp.upsertProgress,+ updatedAt: updatedAt,+ entityKey: history.key,+ bangumiItem: history.bangumiItem,+ adapterName: history.adapterName,+ episode: episode,+ road: road,+ progressMs: progressMs,+ lastSrc: history.lastSrc,+ lastWatchEpisodeName: history.lastWatchEpisodeName,+ );+ }++ factory HistorySyncEvent.deleteHistory({+ required String deviceId,+ required int seq,+ required String entityKey,+ required int updatedAt,+ }) {+ return HistorySyncEvent(+ eventId: '$deviceId:$seq',+ deviceId: deviceId,+ seq: seq,+ op: HistorySyncOp.deleteHistory,+ updatedAt: updatedAt,+ entityKey: entityKey,+ );+ }++ factory HistorySyncEvent.clearAll({+ required String deviceId,+ required int seq,+ required int updatedAt,+ }) {+ return HistorySyncEvent(+ eventId: '$deviceId:$seq',+ deviceId: deviceId,+ seq: seq,+ op: HistorySyncOp.clearAll,+ updatedAt: updatedAt,+ );+ }++ factory HistorySyncEvent.fromJson(Map<String, dynamic> json) {+ return HistorySyncEvent(+ eventId: json['eventId'] as String,+ deviceId: json['deviceId'] as String,+ seq: (json['seq'] as num).toInt(),+ op: HistorySyncOp.fromValue(json['op'] as String),+ updatedAt: (json['updatedAt'] as num).toInt(),+ entityKey: json['entityKey'] as String?,+ bangumiItem: json['bangumiItem'] == null+ ? null+ : HistorySyncCodec.bangumiItemFromJson(+ Map<String, dynamic>.from(json['bangumiItem'] as Map),+ ),+ adapterName: json['adapterName'] as String?,+ episode: (json['episode'] as num?)?.toInt(),+ road: (json['road'] as num?)?.toInt(),+ progressMs: (json['progressMs'] as num?)?.toInt(),+ lastSrc: json['lastSrc'] as String?,+ lastWatchEpisodeName: json['lastWatchEpisodeName'] as String?,+ );+ }++ Map<String, dynamic> toJson() {+ return {+ 'eventId': eventId,+ 'deviceId': deviceId,+ 'seq': seq,+ 'op': op.value,+ 'updatedAt': updatedAt,+ if (entityKey != null) 'entityKey': entityKey,+ if (bangumiItem != null)+ 'bangumiItem': HistorySyncCodec.bangumiItemToJson(bangumiItem!),+ if (adapterName != null) 'adapterName': adapterName,+ if (episode != null) 'episode': episode,+ if (road != null) 'road': road,+ if (progressMs != null) 'progressMs': progressMs,+ if (lastSrc != null) 'lastSrc': lastSrc,+ if (lastWatchEpisodeName != null)+ 'lastWatchEpisodeName': lastWatchEpisodeName,+ };+ }+}++class HistorySyncSnapshot {+ const HistorySyncSnapshot({+ required this.generatedAt,+ required this.histories,+ required this.itemVersions,+ required this.progressVersions,+ required this.deletedVersions,+ this.clearVersion,+ });++ final int generatedAt;+ final List<History> histories;+ final Map<String, String> itemVersions;+ final Map<String, Map<int, String>> progressVersions;+ final Map<String, String> deletedVersions;+ final String? clearVersion;++ factory HistorySyncSnapshot.empty() {+ return HistorySyncSnapshot(+ generatedAt: DateTime.now().millisecondsSinceEpoch,+ histories: const [],+ itemVersions: const {},+ progressVersions: const {},+ deletedVersions: const {},+ );+ }++ factory HistorySyncSnapshot.fromHistories(List<History> histories) {+ final itemVersions = <String, String>{};+ final progressVersions = <String, Map<int, String>>{};+ for (final history in histories) {+ final version = HistorySyncVersion.of(+ updatedAt: history.lastWatchTime.millisecondsSinceEpoch,+ eventId: 'local-import:${history.key}',+ );+ itemVersions[history.key] = version;+ progressVersions[history.key] = {+ for (final entry in history.progresses.entries) entry.key: version,+ };+ }+ return HistorySyncSnapshot(+ generatedAt: DateTime.now().millisecondsSinceEpoch,+ histories: histories,+ itemVersions: itemVersions,+ progressVersions: progressVersions,+ deletedVersions: const {},+ );+ }++ factory HistorySyncSnapshot.fromJson(Map<String, dynamic> json) {+ final progressJson = Map<String, dynamic>.from(+ (json['progressVersions'] as Map?) ?? const {},+ );+ return HistorySyncSnapshot(+ generatedAt: (json['generatedAt'] as num?)?.toInt() ??+ DateTime.now().millisecondsSinceEpoch,+ histories: ((json['histories'] as List?) ?? const [])+ .map((item) => HistorySyncCodec.historyFromJson(+ Map<String, dynamic>.from(item as Map),+ ))+ .toList(),+ itemVersions: Map<String, String>.from(+ (json['itemVersions'] as Map?) ?? const {},+ ),+ progressVersions: {+ for (final entry in progressJson.entries)+ entry.key: (Map<String, dynamic>.from(entry.value as Map)).map(+ (episode, version) => MapEntry(int.parse(episode), '$version'),+ ),+ },+ deletedVersions: Map<String, String>.from(+ (json['deletedVersions'] as Map?) ?? const {},+ ),+ clearVersion: json['clearVersion'] as String?,+ );+ }++ Map<String, dynamic> toJson() {+ return {+ 'schemaVersion': 1,+ 'generatedAt': generatedAt,+ 'histories': histories+ .map((history) => HistorySyncCodec.historyToJson(history))+ .toList(),+ 'itemVersions': itemVersions,+ 'progressVersions': {+ for (final entry in progressVersions.entries)+ entry.key: {+ for (final episodeVersion in entry.value.entries)+ episodeVersion.key.toString(): episodeVersion.value,+ },+ },+ 'deletedVersions': deletedVersions,+ if (clearVersion != null) 'clearVersion': clearVersion,+ };+ }+}++class HistorySyncState {+ HistorySyncState._({+ required Map<String, History> histories,+ required Map<String, String> itemVersions,+ required Map<String, Map<int, String>> progressVersions,+ required Map<String, String> deletedVersions,+ required this.clearVersion,+ }) : histories = Map.of(histories),+ itemVersions = Map.of(itemVersions),+ progressVersions = progressVersions.map(+ (key, value) => MapEntry(key, Map<int, String>.of(value)),+ ),+ deletedVersions = Map.of(deletedVersions);++ factory HistorySyncState.fromSnapshot(HistorySyncSnapshot snapshot) {+ return HistorySyncState._(+ histories: {+ for (final history in snapshot.histories) history.key: history+ },+ itemVersions: snapshot.itemVersions,+ progressVersions: snapshot.progressVersions,+ deletedVersions: snapshot.deletedVersions,+ clearVersion: snapshot.clearVersion,+ );+ }++ final Map<String, History> histories;+ final Map<String, String> itemVersions;+ final Map<String, Map<int, String>> progressVersions;+ final Map<String, String> deletedVersions;+ String? clearVersion;++ void apply(HistorySyncEvent event) {+ switch (event.op) {+ case HistorySyncOp.upsertProgress:+ _applyUpsert(event);+ case HistorySyncOp.deleteHistory:+ _applyDelete(event);+ case HistorySyncOp.clearAll:+ _applyClear(event);+ }+ }++ HistorySyncSnapshot toSnapshot() {+ return HistorySyncSnapshot(+ generatedAt: DateTime.now().millisecondsSinceEpoch,+ histories: histories.values.toList(),+ itemVersions: itemVersions,+ progressVersions: progressVersions,+ deletedVersions: deletedVersions,+ clearVersion: clearVersion,+ );+ }++ void _applyUpsert(HistorySyncEvent event) {+ final entityKey = event.entityKey;+ final bangumiItem = event.bangumiItem;+ final adapterName = event.adapterName;+ final episode = event.episode;+ final road = event.road;+ final progressMs = event.progressMs;+ if (entityKey == null ||+ bangumiItem == null ||+ adapterName == null ||+ episode == null ||+ road == null ||+ progressMs == null) {+ throw const FormatException('Invalid upsertProgress history event');+ }+ if (!_isNewerThanClear(event.version)) {+ return;+ }+ final deletedVersion = deletedVersions[entityKey];+ if (deletedVersion != null &&+ HistorySyncVersion.compare(event.version, deletedVersion) <= 0) {+ return;+ }++ final current = histories[entityKey] ??+ History(+ bangumiItem,+ episode,+ adapterName,+ DateTime.fromMillisecondsSinceEpoch(event.updatedAt),+ event.lastSrc ?? '',+ event.lastWatchEpisodeName ?? '',+ );++ final itemVersion = itemVersions[entityKey];+ if (itemVersion == null ||+ HistorySyncVersion.compare(event.version, itemVersion) >= 0) {+ current.bangumiItem = bangumiItem;+ current.adapterName = adapterName;+ current.lastWatchEpisode = episode;+ current.lastWatchTime =+ DateTime.fromMillisecondsSinceEpoch(event.updatedAt);+ if ((event.lastSrc ?? '').isNotEmpty) {+ current.lastSrc = event.lastSrc!;+ }+ if ((event.lastWatchEpisodeName ?? '').isNotEmpty) {+ current.lastWatchEpisodeName = event.lastWatchEpisodeName!;+ }+ itemVersions[entityKey] = event.version;+ }++ final episodeVersions = progressVersions.putIfAbsent(entityKey, () => {});+ final progressVersion = episodeVersions[episode];+ if (progressVersion == null ||+ HistorySyncVersion.compare(event.version, progressVersion) >= 0) {+ current.progresses[episode] = Progress(episode, road, progressMs);+ episodeVersions[episode] = event.version;+ }+ histories[entityKey] = current;+ deletedVersions.remove(entityKey);+ }++ void _applyDelete(HistorySyncEvent event) {+ final entityKey = event.entityKey;+ if (entityKey == null || !_isNewerThanClear(event.version)) {+ return;+ }+ final itemVersion = itemVersions[entityKey];+ final deletedVersion = deletedVersions[entityKey];+ final newerThanItem = itemVersion == null ||+ HistorySyncVersion.compare(event.version, itemVersion) >= 0;+ final newerThanDelete = deletedVersion == null ||+ HistorySyncVersion.compare(event.version, deletedVersion) >= 0;+ if (newerThanItem && newerThanDelete) {+ histories.remove(entityKey);+ itemVersions.remove(entityKey);+ progressVersions.remove(entityKey);+ deletedVersions[entityKey] = event.version;+ }+ }++ void _applyClear(HistorySyncEvent event) {+ if (!_isNewerThanClear(event.version)) {+ return;+ }+ histories.clear();+ itemVersions.clear();+ progressVersions.clear();+ deletedVersions.clear();+ clearVersion = event.version;+ }++ bool _isNewerThanClear(String version) {+ final currentClearVersion = clearVersion;+ return currentClearVersion == null ||+ HistorySyncVersion.compare(version, currentClearVersion) > 0;+ }+}++class HistorySyncMerger {+ static HistorySyncSnapshot merge({+ required HistorySyncSnapshot snapshot,+ required Iterable<HistorySyncEvent> events,+ }) {+ final state = HistorySyncState.fromSnapshot(snapshot);+ final sortedEvents = events.toList()+ ..sort((a, b) => HistorySyncVersion.compare(a.version, b.version));+ for (final event in sortedEvents) {+ state.apply(event);+ }+ return state.toSnapshot();+ }++ HistorySyncMerger._();+}++class HistorySyncVersion {+ static String of({+ required int updatedAt,+ required String eventId,+ }) {+ return '${updatedAt.toString().padLeft(16, '0')}|$eventId';+ }++ static int compare(String a, String b) {+ return a.compareTo(b);+ }++ HistorySyncVersion._();+}++class HistorySyncCodec {+ static List<HistorySyncEvent> eventsFromJsonLines(String content) {+ return const LineSplitter()+ .convert(content)+ .map((line) => line.trim())+ .where((line) => line.isNotEmpty)+ .map((line) => HistorySyncEvent.fromJson(+ Map<String, dynamic>.from(jsonDecode(line) as Map),+ ))+ .toList();+ }++ static String eventsToJsonLines(Iterable<HistorySyncEvent> events) {+ final lines = events.map((event) => jsonEncode(event.toJson())).join('\n');+ return lines.isEmpty ? '' : '$lines\n';+ }++ static History historyFromJson(Map<String, dynamic> json) {+ final history = History(+ bangumiItemFromJson(+ Map<String, dynamic>.from(json['bangumiItem'] as Map)),+ (json['lastWatchEpisode'] as num).toInt(),+ json['adapterName'] as String,+ DateTime.fromMillisecondsSinceEpoch(+ (json['lastWatchTime'] as num).toInt()),+ json['lastSrc'] as String? ?? '',+ json['lastWatchEpisodeName'] as String? ?? '',+ );+ history.progresses = {+ for (final entry+ in Map<String, dynamic>.from(json['progresses'] as Map).entries)+ int.parse(entry.key): progressFromJson(+ Map<String, dynamic>.from(entry.value as Map),+ ),+ };+ return history;+ }++ static Map<String, dynamic> historyToJson(History history) {+ return {+ 'bangumiItem': bangumiItemToJson(history.bangumiItem),+ 'lastWatchEpisode': history.lastWatchEpisode,+ 'adapterName': history.adapterName,+ 'lastWatchTime': history.lastWatchTime.millisecondsSinceEpoch,+ 'lastSrc': history.lastSrc,+ 'lastWatchEpisodeName': history.lastWatchEpisodeName,+ 'progresses': {+ for (final entry in history.progresses.entries)+ entry.key.toString(): progressToJson(entry.value),+ },+ };+ }++ static Progress progressFromJson(Map<String, dynamic> json) {+ return Progress(+ (json['episode'] as num).toInt(),+ (json['road'] as num).toInt(),+ (json['progressMs'] as num).toInt(),+ );+ }++ static Map<String, dynamic> progressToJson(Progress progress) {+ return {+ 'episode': progress.episode,+ 'road': progress.road,+ 'progressMs': progress.progress.inMilliseconds,+ };+ }++ static BangumiItem bangumiItemFromJson(Map<String, dynamic> json) {+ return BangumiItem(+ id: (json['id'] as num).toInt(),+ type: (json['type'] as num).toInt(),+ name: json['name'] as String? ?? '',+ nameCn: json['nameCn'] as String? ?? '',+ summary: json['summary'] as String? ?? '',+ airDate: json['airDate'] as String? ?? '',+ airWeekday: (json['airWeekday'] as num?)?.toInt() ?? 0,+ rank: (json['rank'] as num?)?.toInt() ?? 0,+ images: Map<String, String>.from((json['images'] as Map?) ?? const {}),+ tags: ((json['tags'] as List?) ?? const [])+ .map((tag) =>+ BangumiTag.fromJson(Map<String, dynamic>.from(tag as Map)))+ .toList(),+ alias: ((json['alias'] as List?) ?? const [])+ .map((alias) => alias.toString())+ .toList(),+ ratingScore: (json['ratingScore'] as num?)?.toDouble() ?? 0,+ votes: (json['votes'] as num?)?.toInt() ?? 0,+ votesCount: ((json['votesCount'] as List?) ?? const [])+ .map((vote) => (vote as num).toInt())+ .toList(),+ info: json['info'] as String? ?? '',+ );+ }++ static Map<String, dynamic> bangumiItemToJson(BangumiItem item) {+ return {+ 'id': item.id,+ 'type': item.type,+ 'name': item.name,+ 'nameCn': item.nameCn,+ 'summary': item.summary,+ 'airDate': item.airDate,+ 'airWeekday': item.airWeekday,+ 'rank': item.rank,+ 'images': item.images,+ 'tags': item.tags.map((tag) => tag.toJson()).toList(),+ 'alias': item.alias,+ 'ratingScore': item.ratingScore,+ 'votes': item.votes,+ 'votesCount': item.votesCount,+ 'info': item.info,+ };+ }++ HistorySyncCodec._();+}diff --git a/lib/pages/init_page.dart b/lib/pages/init_page.dartindex 5f6f0e92..183005dc 100644--- a/lib/pages/init_page.dart+++ b/lib/pages/init_page.dart@@ -146,13 +146,21 @@ class _InitPageState extends State<InitPage> {try {await webDav.init();try {- await webDav.downloadAndPatchHistory();+ await webDav.syncHistory();KazumiLogger().i('WebDav: Completed syncing watch history');- } catch (e) {- KazumiDialog.showToast(message: "同步观看记录失败 ${e.toString()}");+ } catch (e, stackTrace) {+ KazumiLogger().w(+ 'WebDav: automatic watch history sync failed',+ error: e,+ stackTrace: stackTrace,+ );}- } catch (e) {- KazumiDialog.showToast(message: "初始化WebDav失败 ${e.toString()}");+ } catch (e, stackTrace) {+ KazumiLogger().w(+ 'WebDav: automatic initialization failed',+ error: e,+ stackTrace: stackTrace,+ );}}}@@ -223,7 +231,9 @@ class _InitPageState extends State<InitPage> {Future<void> _showShortcutDialog() async {if (!Platform.isWindows) return;- if (setting.get(SettingBoxKey.shortcutDialogShown, defaultValue: false)) return;+ if (setting.get(SettingBoxKey.shortcutDialogShown, defaultValue: false)) {+ return;+ }final create = await KazumiDialog.show<bool>(clickMaskDismiss: false,@@ -233,7 +243,8 @@ class _InitPageState extends State<InitPage> {actions: [TextButton(onPressed: () => KazumiDialog.dismiss(popWith: false),- child: Text('暂不创建', style: TextStyle(color: Theme.of(context).colorScheme.outline)),+ child: Text('暂不创建',+ style: TextStyle(color: Theme.of(context).colorScheme.outline)),),TextButton(onPressed: () => KazumiDialog.dismiss(popWith: true),diff --git a/lib/pages/player/player_item.dart b/lib/pages/player/player_item.dartindex 1ee74d1b..a971cabc 100644--- a/lib/pages/player/player_item.dart+++ b/lib/pages/player/player_item.dart@@ -475,12 +475,14 @@ class _PlayerItemState extends State<PlayerItem>unawaited(_updateAndroidPIPActions(force: true));}- Future<void> _uploadHistoryToWebDav() async {+ Future<void> _syncHistoryWithWebDav() async {if (webDavEnable && webDavEnableHistory) {try {var webDav = WebDav();- await webDav.updateHistory();- } catch (_) {}+ await webDav.syncHistory();+ } catch (e) {+ KazumiLogger().w('WebDav: auto history sync failed', error: e);+ }}}@@ -559,7 +561,7 @@ class _PlayerItemState extends State<PlayerItem>playerController.lockPanel = false;playerController.danmakuController.clear();- await _uploadHistoryToWebDav();+ await _syncHistoryWithWebDav();}void handleProgressBarDragStart(ThumbDragDetails details) {@@ -893,20 +895,18 @@ class _PlayerItemState extends State<PlayerItem>if (playerController.playerPlaying &&!videoPageController.loading &&!videoPageController.isOfflineMode) {- if (!WebDav().isHistorySyncing) {- final pluginName = videoPageController.isOfflineMode- ? videoPageController.offlinePluginName- : videoPageController.currentPlugin.name;- historyController.updateHistory(- videoPageController.actualEpisodeNumber,- videoPageController.currentRoad,- pluginName,- videoPageController.bangumiItem,- playerController.playerPosition,- videoPageController.src,- videoPageController.roadList[videoPageController.currentRoad]- .identifier[videoPageController.currentEpisode - 1]);- }+ final pluginName = videoPageController.isOfflineMode+ ? videoPageController.offlinePluginName+ : videoPageController.currentPlugin.name;+ historyController.updateHistory(+ videoPageController.actualEpisodeNumber,+ videoPageController.currentRoad,+ pluginName,+ videoPageController.bangumiItem,+ playerController.playerPosition,+ videoPageController.src,+ videoPageController.roadList[videoPageController.currentRoad]+ .identifier[videoPageController.currentEpisode - 1]);}// 自动播放下一集if (playerController.completed &&diff --git a/lib/pages/webdav_editor/webdav_setting.dart b/lib/pages/webdav_editor/webdav_setting.dartindex 0a1ac846..600dda90 100644--- a/lib/pages/webdav_editor/webdav_setting.dart+++ b/lib/pages/webdav_editor/webdav_setting.dart@@ -1,6 +1,7 @@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/logger.dart';import 'package:kazumi/utils/storage.dart';import 'package:kazumi/utils/webdav.dart';import 'package:hive_ce/hive.dart';@@ -44,43 +45,25 @@ class _PlayerSettingsPageState extends State<WebDavSettingsPage> {}}- Future<void> checkWebDav() async {- var webDavURL =- await setting.get(SettingBoxKey.webDavURL, defaultValue: '');- if (webDavURL == '') {- await setting.put(SettingBoxKey.webDavEnable, false);- KazumiDialog.showToast(message: '未找到有效的webdav配置');- return;- }- try {- KazumiDialog.showToast(message: '尝试从WebDav同步');- var webDav = WebDav();- await webDav.downloadAndPatchHistory();- KazumiDialog.showToast(message: '同步成功');- } catch (e) {- if (e.toString().contains('Error: Not Found')) {- KazumiDialog.showToast(message: '配置成功, 这是一个不存在已有同步文件的全新WebDav');- } else {- KazumiDialog.showToast(message: '同步失败 ${e.toString()}');- }- }- }-- Future<void> updateWebdav() async {+ Future<void> syncHistoryWithWebDav() async {var webDavEnable =await setting.get(SettingBoxKey.webDavEnable, defaultValue: false);if (webDavEnable) {- KazumiDialog.showToast(message: '尝试上传到WebDav');+ KazumiLogger().i('WebDav: manual history sync started');+ KazumiDialog.showToast(message: '正在同步观看记录');var webDav = WebDav();try {await webDav.ping();try {- await webDav.updateHistory();- KazumiDialog.showToast(message: 'WebDav同步成功');+ await webDav.syncHistory();+ KazumiLogger().i('WebDav: manual history sync completed');+ KazumiDialog.showToast(message: '观看记录同步完成');} catch (e) {- KazumiDialog.showToast(message: 'WebDav同步失败 ${e.toString()}');+ KazumiLogger().w('WebDav: manual history sync failed', error: e);+ KazumiDialog.showToast(message: '观看记录同步失败 ${e.toString()}');}} catch (e) {+ KazumiLogger().w('WebDav: manual history sync ping failed', error: e);KazumiDialog.showToast(message: 'WebDav连接失败');}} else {@@ -88,28 +71,6 @@ class _PlayerSettingsPageState extends State<WebDavSettingsPage> {}}- Future<void> downloadWebdav() async {- var webDavEnable =- await setting.get(SettingBoxKey.webDavEnable, defaultValue: false);- if (webDavEnable) {- KazumiDialog.showToast(message: '尝试从WebDav同步');- var webDav = WebDav();- try {- await webDav.ping();- try {- await webDav.downloadAndPatchHistory();- KazumiDialog.showToast(message: 'WebDav同步成功');- } catch (e) {- KazumiDialog.showToast(message: 'WebDav同步失败 ${e.toString()}');- }- } catch (e) {- KazumiDialog.showToast(message: 'WebDAV连接失败');- }- } else {- KazumiDialog.showToast(message: '未开启WebDav同步或配置无效');- }- }-@overrideWidget build(BuildContext context) {final fontFamily = Theme.of(context).textTheme.bodyMedium?.fontFamily;@@ -269,21 +230,13 @@ class _PlayerSettingsPageState extends State<WebDavSettingsPage> {style: TextStyle(fontFamily: fontFamily)),),SettingsTile(- trailing: const Icon(Icons.cloud_upload_rounded),+ trailing: const Icon(Icons.sync_rounded),onPressed: (_) {- updateWebdav();+ syncHistoryWithWebDav();},- title: Text('手动上传', style: TextStyle(fontFamily: fontFamily)),- description: Text('立即上传观看记录到WEBDAV',+ title: Text('立即同步观看记录',style: TextStyle(fontFamily: fontFamily)),- ),- SettingsTile(- trailing: const Icon(Icons.cloud_download_rounded),- onPressed: (_) {- downloadWebdav();- },- title: Text('手动下载', style: TextStyle(fontFamily: fontFamily)),- description: Text('立即下载观看记录到本地',+ description: Text('与WEBDAV双向合并观看记录',style: TextStyle(fontFamily: fontFamily)),),],diff --git a/lib/repositories/history_repository.dart b/lib/repositories/history_repository.dartindex b3f71cf0..297dabd6 100644--- a/lib/repositories/history_repository.dart+++ b/lib/repositories/history_repository.dart@@ -1,6 +1,7 @@import 'package:kazumi/utils/storage.dart';import 'package:kazumi/modules/bangumi/bangumi_item.dart';import 'package:kazumi/modules/history/history_module.dart';+import 'package:kazumi/utils/history_sync_service.dart';import 'package:kazumi/utils/logger.dart';/// 历史记录数据访问接口@@ -41,7 +42,8 @@ abstract class IHistoryRepository {/// [bangumiItem] 番剧信息/// [adapterName] 适配器名称/// 返回观看进度,不存在返回null- Progress? getLastWatchingProgress(BangumiItem bangumiItem, String adapterName);+ Progress? getLastWatchingProgress(+ BangumiItem bangumiItem, String adapterName);/// 查找特定集数的观看进度///@@ -49,7 +51,8 @@ abstract class IHistoryRepository {/// [adapterName] 适配器名称/// [episode] 集数/// 返回观看进度,不存在返回null- Progress? findProgress(BangumiItem bangumiItem, String adapterName, int episode);+ Progress? findProgress(+ BangumiItem bangumiItem, String adapterName, int episode);/// 删除历史记录///@@ -61,7 +64,8 @@ abstract class IHistoryRepository {/// [bangumiItem] 番剧信息/// [adapterName] 适配器名称/// [episode] 集数- Future<void> clearProgress(BangumiItem bangumiItem, String adapterName, int episode);+ Future<void> clearProgress(+ BangumiItem bangumiItem, String adapterName, int episode);/// 清空所有历史记录Future<void> clearAllHistories();@@ -128,8 +132,10 @@ class HistoryRepository implements IHistoryRepository {}// 获取或创建历史记录- var history = _historiesBox.get(History.getKey(adapterName, bangumiItem)) ??- History(bangumiItem, episode, adapterName, DateTime.now(), lastSrc, lastWatchEpisodeName);+ var history =+ _historiesBox.get(History.getKey(adapterName, bangumiItem)) ??+ History(bangumiItem, episode, adapterName, DateTime.now(),+ lastSrc, lastWatchEpisodeName);// 更新历史记录history.lastWatchEpisode = episode;@@ -152,6 +158,14 @@ class HistoryRepository implements IHistoryRepository {// 保存到存储await _historiesBox.put(history.key, history);+ await HistorySyncService().appendSafely(+ () => HistorySyncService().appendUpsertProgress(+ history: history,+ episode: episode,+ road: road,+ progressMs: progress.inMilliseconds,+ ),+ );} catch (e, stackTrace) {KazumiLogger().e('GStorage: update history failed. bangumi=${bangumiItem.name}, episode=$episode',@@ -162,7 +176,8 @@ class HistoryRepository implements IHistoryRepository {}@override- Progress? getLastWatchingProgress(BangumiItem bangumiItem, String adapterName) {+ Progress? getLastWatchingProgress(+ BangumiItem bangumiItem, String adapterName) {try {var history = _historiesBox.get(History.getKey(adapterName, bangumiItem));return history?.progresses[history.lastWatchEpisode];@@ -177,7 +192,8 @@ class HistoryRepository implements IHistoryRepository {}@override- Progress? findProgress(BangumiItem bangumiItem, String adapterName, int episode) {+ Progress? findProgress(+ BangumiItem bangumiItem, String adapterName, int episode) {try {var history = _historiesBox.get(History.getKey(adapterName, bangumiItem));return history?.progresses[episode];@@ -195,6 +211,9 @@ class HistoryRepository implements IHistoryRepository {Future<void> deleteHistory(History history) async {try {await _historiesBox.delete(history.key);+ await HistorySyncService().appendSafely(+ () => HistorySyncService().appendDeleteHistory(history),+ );} catch (e, stackTrace) {KazumiLogger().e('GStorage: delete history failed. bangumi=${history.bangumiItem.name}',@@ -205,12 +224,22 @@ class HistoryRepository implements IHistoryRepository {}@override- Future<void> clearProgress(BangumiItem bangumiItem, String adapterName, int episode) async {+ Future<void> clearProgress(+ BangumiItem bangumiItem, String adapterName, int episode) async {try {var history = _historiesBox.get(History.getKey(adapterName, bangumiItem));if (history != null && history.progresses[episode] != null) {history.progresses[episode]!.progress = Duration.zero;await _historiesBox.put(history.key, history);+ await HistorySyncService().appendSafely(+ () => HistorySyncService().appendUpsertProgress(+ history: history,+ episode: episode,+ road: history.progresses[episode]!.road,+ progressMs: 0,+ updatedAt: DateTime.now().millisecondsSinceEpoch,+ ),+ );}} catch (e, stackTrace) {KazumiLogger().e(@@ -225,6 +254,9 @@ class HistoryRepository implements IHistoryRepository {Future<void> clearAllHistories() async {try {await _historiesBox.clear();+ await HistorySyncService().appendSafely(+ () => HistorySyncService().appendClearAll(),+ );} catch (e, stackTrace) {KazumiLogger().e('GStorage: clear all histories failed',diff --git a/lib/utils/history_sync_service.dart b/lib/utils/history_sync_service.dartnew file mode 100644index 00000000..2c1b7673--- /dev/null+++ b/lib/utils/history_sync_service.dart@@ -0,0 +1,162 @@+import 'dart:io';++import 'package:kazumi/modules/history/history_module.dart';+import 'package:kazumi/modules/history/history_sync.dart';+import 'package:kazumi/utils/logger.dart';+import 'package:kazumi/utils/storage.dart';+import 'package:path_provider/path_provider.dart';++class HistorySyncService {+ static const int compactLocalLogThresholdBytes = 1024 * 1024;++ HistorySyncService._internal();++ static final HistorySyncService _instance = HistorySyncService._internal();++ factory HistorySyncService() => _instance;++ Future<String> getDeviceId() async {+ final setting = GStorage.setting;+ final existing = setting+ .get(SettingBoxKey.historySyncDeviceId, defaultValue: '')+ .toString();+ if (existing.isNotEmpty) {+ return existing;+ }+ final deviceId = HistorySyncDevice.generateDeviceId();+ await setting.put(SettingBoxKey.historySyncDeviceId, deviceId);+ return deviceId;+ }++ Future<void> appendUpsertProgress({+ required History history,+ required int episode,+ required int road,+ required int progressMs,+ int? updatedAt,+ }) async {+ final event = HistorySyncEvent.upsertProgress(+ deviceId: await getDeviceId(),+ seq: await _nextSeq(),+ history: history,+ episode: episode,+ road: road,+ progressMs: progressMs,+ updatedAt: updatedAt ?? history.lastWatchTime.millisecondsSinceEpoch,+ );+ await appendEvent(event);+ }++ Future<void> appendDeleteHistory(History history) async {+ final event = HistorySyncEvent.deleteHistory(+ deviceId: await getDeviceId(),+ seq: await _nextSeq(),+ entityKey: history.key,+ updatedAt: DateTime.now().millisecondsSinceEpoch,+ );+ await appendEvent(event);+ }++ Future<void> appendClearAll() async {+ final event = HistorySyncEvent.clearAll(+ deviceId: await getDeviceId(),+ seq: await _nextSeq(),+ updatedAt: DateTime.now().millisecondsSinceEpoch,+ );+ await appendEvent(event);+ }++ Future<void> appendEvent(HistorySyncEvent event) async {+ final file = await localChangeLogFile();+ await file.parent.create(recursive: true);+ await file.writeAsString(+ HistorySyncCodec.eventsToJsonLines([event]),+ mode: FileMode.append,+ flush: true,+ );+ }++ Future<List<HistorySyncEvent>> readLocalEvents() async {+ final file = await localChangeLogFile();+ if (!await file.exists()) {+ return [];+ }+ final content = await file.readAsString();+ return HistorySyncCodec.eventsFromJsonLines(content);+ }++ Future<String> readLocalEventLines() async {+ final file = await localChangeLogFile();+ if (!await file.exists()) {+ return '';+ }+ return file.readAsString();+ }++ Future<void> replaceLocalEvents(Iterable<HistorySyncEvent> events) async {+ final file = await localChangeLogFile();+ await file.parent.create(recursive: true);+ await file.writeAsString(+ HistorySyncCodec.eventsToJsonLines(events),+ flush: true,+ );+ }++ Future<bool> shouldCompactLocalLog() async {+ final file = await localChangeLogFile();+ if (!await file.exists()) {+ return false;+ }+ return file.lengthSync() > compactLocalLogThresholdBytes;+ }++ HistorySyncSnapshot buildSnapshotFromLocal() {+ return HistorySyncSnapshot.fromHistories(+ GStorage.histories.values.toList());+ }++ Future<void> applySnapshotToLocal(HistorySyncSnapshot snapshot) async {+ await GStorage.histories.clear();+ for (final history in snapshot.histories) {+ await GStorage.histories.put(history.key, history);+ }+ await GStorage.histories.flush();+ }++ Future<File> localChangeLogFile() async {+ final directory = await getApplicationSupportDirectory();+ return File('${directory.path}/webdavTemp/history.local.jsonl');+ }++ Future<int> _nextSeq() async {+ final setting = GStorage.setting;+ final value = setting.get(+ SettingBoxKey.historySyncSequence,+ defaultValue: 0,+ );+ final next = value is int ? value + 1 : 1;+ await setting.put(SettingBoxKey.historySyncSequence, next);+ return next;+ }++ Future<void> appendSafely(Future<void> Function() append) async {+ final webDavEnable =+ GStorage.setting.get(SettingBoxKey.webDavEnable, defaultValue: false);+ final historySyncEnable = GStorage.setting.get(+ SettingBoxKey.webDavEnableHistory,+ defaultValue: false,+ );+ if (webDavEnable != true || historySyncEnable != true) {+ return;+ }+ try {+ await append();+ } catch (e, stackTrace) {+ KazumiLogger().e(+ 'HistorySync: failed to append local change',+ error: e,+ stackTrace: stackTrace,+ );+ }+ }+}diff --git a/lib/utils/storage.dart b/lib/utils/storage.dartindex fe60c356..0b000b32 100644--- a/lib/utils/storage.dart+++ b/lib/utils/storage.dart@@ -417,5 +417,8 @@ class SettingBoxKey {bangumiAccessToken = 'bangumiAccessToken',bangumiSyncPriority = 'bangumiSyncPriority',bangumiImmediateSyncToastEnable = 'bangumiImmediateSyncToastEnable',- brightnessVolumeGesture = 'brightnessVolumeGesture';+ brightnessVolumeGesture = 'brightnessVolumeGesture',+ historySyncDeviceId = 'historySyncDeviceId',+ historySyncSequence = 'historySyncSequence',+ historySyncSnapshotInitialized = 'historySyncSnapshotInitialized';}diff --git a/lib/utils/webdav.dart b/lib/utils/webdav.dartindex a196075b..c98303ec 100644--- a/lib/utils/webdav.dart+++ b/lib/utils/webdav.dart@@ -1,13 +1,23 @@import 'dart:io';+import 'dart:convert';+import 'dart:async';+import 'dart:typed_data';import 'package:webdav_client/webdav_client.dart' as webdav;import 'package:hive_ce/hive.dart';import 'package:path_provider/path_provider.dart';+import 'package:kazumi/modules/history/history_sync.dart';import 'package:kazumi/utils/storage.dart';import 'package:kazumi/utils/logger.dart';import 'package:kazumi/modules/collect/collect_module.dart';import 'package:kazumi/modules/collect/collect_change_module.dart';+import 'package:kazumi/utils/history_sync_service.dart';class WebDav {+ static const String _syncRootPath = '/kazumiSync';+ static const String _historyRootPath = '$_syncRootPath/history';+ static const String _historyChangesPath = '$_historyRootPath/changes';+ static const String _historySnapshotPath = '$_historyRootPath/snapshot.json';+late String webDavURL;late String webDavUsername;late String webDavPassword;@@ -15,8 +25,8 @@ class WebDav {late webdav.Client client;bool initialized = false;- // make sure only one upload history task at a timebool isHistorySyncing = false;+ Future<void> _webDavOperationQueue = Future.value();WebDav._internal();static final WebDav _instance = WebDav._internal();@@ -42,62 +52,66 @@ class WebDav {debug: false,);client.setHeaders({'accept-charset': 'utf-8'});+ client.c.options.contentType = 'application/octet-stream';try {await client.ping();- try {- // KazumiLogger().log(Level.warning, 'webDav backup directory not exists, creating');- await client.mkdir('/kazumiSync');- if (!await webDavLocalTempDirectory.exists()) {- await webDavLocalTempDirectory.create(recursive: true);- }- initialized = true;- KazumiLogger().i('WebDav: webDav backup directory create success');- } catch (_) {- KazumiLogger().e('WebDav: webDav backup directory create failed');- rethrow;- }+ await _ensureRemoteDirectory(_syncRootPath);+ await _ensureLocalTempDirectory();+ initialized = true;+ KazumiLogger().i('WebDav: webDav backup directory ready');} catch (e) {KazumiLogger().e('WebDav: WebDAV ping failed', error: e);rethrow;}}- Future<void> update(String boxName) async {+ Future<T> _runWebDavExclusive<T>(Future<T> Function() action) {+ final previousOperation = _webDavOperationQueue;+ final completer = Completer<T>();+ _webDavOperationQueue = (() async {+ try {+ await previousOperation;+ } catch (_) {}+ try {+ completer.complete(await action());+ } catch (e, stackTrace) {+ completer.completeError(e, stackTrace);+ }+ })();+ return completer.future;+ }++ Future<void> _updateBox(String boxName) async {var directory = await getApplicationSupportDirectory();- final localFilePath = '${directory.path}/hive/$boxName.hive';+ final localFilePath = '${directory.path}/hive/$boxName.hive';final tempFilePath = '${webDavLocalTempDirectory.path}/$boxName.tmp';- final webDavPath = '/kazumiSync/$boxName.tmp';- await File(localFilePath)- .copy(tempFilePath);+ final webDavPath = '$_syncRootPath/$boxName.tmp';+ await File(localFilePath).copy(tempFilePath);try {await client.remove('$webDavPath.cache');} catch (_) {}- await client.writeFromFile(tempFilePath,- '$webDavPath.cache', onProgress: (c, t) {- // print(c / t);- });+ await client.writeFromFile(tempFilePath, '$webDavPath.cache');try {await client.remove(webDavPath);} catch (_) {KazumiLogger().w('WebDav: former backup file not exist');}- await client.rename(- '$webDavPath.cache', webDavPath, true);+ await client.rename('$webDavPath.cache', webDavPath, true);try {await File(tempFilePath).delete();} catch (_) {}}- Future<void> updateHistory() async {+ Future<void> syncHistory() async {if (isHistorySyncing) {KazumiLogger().w('WebDav: History is currently syncing');throw Exception('History is currently syncing');}isHistorySyncing = true;try {- await update('histories');+ await _runWebDavExclusive(_syncHistory);} catch (e) {- KazumiLogger().e('WebDav: update history failed', error: e);+ KazumiLogger().e('WebDav: history sync failed', error: e);rethrow;} finally {isHistorySyncing = false;@@ -105,97 +119,292 @@ class WebDav {}Future<void> updateCollectibles() async {- // don't try muliti thread update here- // some webdav server may not support muliti thread write- // you will get 423 locked errortry {- await update('collectibles');- if (GStorage.collectChanges.isNotEmpty) {- await update('collectchanges');- }+ await _runWebDavExclusive(() async {+ await _updateBox('collectibles');+ if (GStorage.collectChanges.isNotEmpty) {+ await _updateBox('collectchanges');+ }+ });} catch (e) {KazumiLogger().e('WebDav: update collectibles failed', error: e);rethrow;}}- Future<void> download(String boxName) async {+ Future<void> _downloadBox(String boxName) async {String fileName = '$boxName.tmp';final existingFile = File('${webDavLocalTempDirectory.path}/$fileName');if (await existingFile.exists()) {await existingFile.delete();}- await client.read2File('/kazumiSync/$fileName', existingFile.path,- onProgress: (c, t) {- // print(c / t);- });+ await client.read2File('$_syncRootPath/$fileName', existingFile.path);}- Future<void> downloadAndPatchHistory() async {- if (isHistorySyncing) {- KazumiLogger().w('WebDav: History is currently syncing');- throw Exception('History is currently syncing');- }- isHistorySyncing = true;- String fileName = 'histories.tmp';- try {- final existingFile = File('${webDavLocalTempDirectory.path}/$fileName');- await download('histories');- await GStorage.patchHistory(existingFile.path);- } catch (e) {- KazumiLogger()- .e('WebDav: download and patch history failed', error: e);- rethrow;- } finally {- isHistorySyncing = false;- }+ Future<void> syncCollectibles() async {+ return _runWebDavExclusive(_syncCollectibles);}- Future<void> syncCollectibles() async {+ Future<void> _syncCollectibles() async {List<CollectedBangumi> remoteCollectibles = [];List<CollectedBangumiChange> remoteChanges = [];- final files = await client.readDir('/kazumiSync');- final collectiblesExists = files.any((file) => file.name == 'collectibles.tmp');- final changesExists = files.any((file) => file.name == 'collectchanges.tmp');+ final files = await client.readDir(_syncRootPath);+ final collectiblesExists =+ files.any((file) => file.name == 'collectibles.tmp');+ final changesExists =+ files.any((file) => file.name == 'collectchanges.tmp');if (!collectiblesExists && !changesExists) {- await updateCollectibles();+ await _updateBox('collectibles');+ if (GStorage.collectChanges.isNotEmpty) {+ await _updateBox('collectchanges');+ }return;}-+List<Future<void>> downloadFutures = [];if (collectiblesExists) {- downloadFutures.add(download('collectibles').catchError((e) {+ downloadFutures.add(_downloadBox('collectibles').catchError((e) {KazumiLogger().e('WebDav: download collectibles failed', error: e);throw Exception('WebDav: download collectibles failed');}));}if (changesExists) {- downloadFutures.add(download('collectchanges').catchError((e) {+ downloadFutures.add(_downloadBox('collectchanges').catchError((e) {KazumiLogger().e('WebDav: download collectchanges failed', error: e);throw Exception('WebDav: download collectchanges failed');}));}if (downloadFutures.isNotEmpty) {await Future.wait(downloadFutures);- }+ }try {if (collectiblesExists) {remoteCollectibles = await GStorage.getCollectiblesFromFile(- '${webDavLocalTempDirectory.path}/collectibles.tmp');+ '${webDavLocalTempDirectory.path}/collectibles.tmp');}if (changesExists) {remoteChanges = await GStorage.getCollectChangesFromFile(- '${webDavLocalTempDirectory.path}/collectchanges.tmp');- }+ '${webDavLocalTempDirectory.path}/collectchanges.tmp');+ }} catch (e) {KazumiLogger().e('WebDav: get collectibles failed', error: e);- throw Exception('WebDav: get collectibles from file failed');+ throw Exception('WebDav: get collectibles from file failed');}if (remoteChanges.isNotEmpty || remoteCollectibles.isNotEmpty) {await GStorage.patchCollectibles(remoteCollectibles, remoteChanges);}- await updateCollectibles();+ await _updateBox('collectibles');+ if (GStorage.collectChanges.isNotEmpty) {+ await _updateBox('collectchanges');+ }+ }++ Future<void> _syncHistory() async {+ await _ensureHistoryStorage();+ final historySync = HistorySyncService();+ final localEvents = await historySync.readLocalEvents();+ final localStateEvents = await _eventsFromLocalHistories();+ var remoteSnapshot =+ await _readHistorySnapshot() ?? HistorySyncSnapshot.empty();+ final remoteEvents = await _readRemoteHistoryEvents();++ if (remoteSnapshot.histories.isEmpty &&+ remoteSnapshot.itemVersions.isEmpty &&+ remoteEvents.isEmpty &&+ await _tryImportLegacyHistory()) {+ remoteSnapshot = historySync.buildSnapshotFromLocal();+ await _writeHistorySnapshot(remoteSnapshot);+ }++ final mergedSnapshot = HistorySyncMerger.merge(+ snapshot: remoteSnapshot,+ events: [+ ...remoteEvents,+ ...localStateEvents,+ ...localEvents,+ ],+ );+ await historySync.applySnapshotToLocal(mergedSnapshot);++ if (localEvents.isNotEmpty) {+ await _writeDeviceHistoryChanges(localEvents);+ }++ final snapshotInitialized = GStorage.setting.get(+ SettingBoxKey.historySyncSnapshotInitialized,+ defaultValue: false,+ );+ if (snapshotInitialized != true ||+ await historySync.shouldCompactLocalLog()) {+ await _writeHistorySnapshot(mergedSnapshot);+ await historySync.replaceLocalEvents(const []);+ await _writeDeviceHistoryChanges(const []);+ await GStorage.setting.put(+ SettingBoxKey.historySyncSnapshotInitialized,+ true,+ );+ }+ }++ Future<void> _ensureHistoryStorage() async {+ await _ensureLocalTempDirectory();+ await _ensureRemoteDirectory(_syncRootPath);+ await _ensureRemoteDirectory(_historyRootPath);+ await _ensureRemoteDirectory(_historyChangesPath);+ }++ Future<void> _ensureLocalTempDirectory() async {+ if (!await webDavLocalTempDirectory.exists()) {+ await webDavLocalTempDirectory.create(recursive: true);+ }+ }++ Future<void> _ensureRemoteDirectory(String path) async {+ try {+ await client.mkdir(path);+ } catch (e) {+ if (!await _remoteEntryExists(path)) {+ rethrow;+ }+ }+ }++ Future<bool> _remoteEntryExists(String path) async {+ final normalized = path.endsWith('/') && path.length > 1+ ? path.substring(0, path.length - 1)+ : path;+ final index = normalized.lastIndexOf('/');+ final parent = index <= 0 ? '/' : normalized.substring(0, index);+ final name = normalized.substring(index + 1);+ try {+ final files = await client.readDir(parent);+ return files.any((file) => file.name == name);+ } catch (_) {+ return false;+ }+ }++ Future<HistorySyncSnapshot?> _readHistorySnapshot() async {+ try {+ final content = await _readRemoteText(_historySnapshotPath);+ return HistorySyncSnapshot.fromJson(+ Map<String, dynamic>.from(jsonDecode(content) as Map),+ );+ } catch (e) {+ KazumiLogger().w('WebDav: history snapshot not available', error: e);+ return null;+ }+ }++ Future<List<HistorySyncEvent>> _readRemoteHistoryEvents() async {+ final events = <HistorySyncEvent>[];+ final files = await client.readDir(_historyChangesPath);+ for (final file in files) {+ final name = file.name ?? '';+ if (!name.endsWith('.jsonl') || file.size == 0) {+ continue;+ }+ try {+ final content = await _readRemoteText('$_historyChangesPath/$name');+ events.addAll(HistorySyncCodec.eventsFromJsonLines(content));+ } catch (e) {+ KazumiLogger().w(+ 'WebDav: failed to read history change log $name',+ error: e,+ );+ }+ }+ return events;+ }++ Future<List<HistorySyncEvent>> _eventsFromLocalHistories() async {+ final events = <HistorySyncEvent>[];+ for (final history in GStorage.histories.values) {+ for (final progress in history.progresses.values) {+ events.add(+ HistorySyncEvent(+ eventId:+ 'local-state:${history.key}:${progress.episode}:${progress.road}',+ deviceId: 'local-state',+ seq: 0,+ op: HistorySyncOp.upsertProgress,+ updatedAt: history.lastWatchTime.millisecondsSinceEpoch,+ entityKey: history.key,+ bangumiItem: history.bangumiItem,+ adapterName: history.adapterName,+ episode: progress.episode,+ road: progress.road,+ progressMs: progress.progress.inMilliseconds,+ lastSrc: history.lastSrc,+ lastWatchEpisodeName: history.lastWatchEpisodeName,+ ),+ );+ }+ }+ return events;+ }++ Future<bool> _tryImportLegacyHistory() async {+ try {+ final fileName = 'histories.tmp';+ final existingFile = File('${webDavLocalTempDirectory.path}/$fileName');+ if (await existingFile.exists()) {+ await existingFile.delete();+ }+ await client.read2File('$_syncRootPath/$fileName', existingFile.path);+ await GStorage.patchHistory(existingFile.path);+ KazumiLogger().i('WebDav: imported legacy history backup');+ return true;+ } catch (e) {+ KazumiLogger().w('WebDav: no legacy history backup imported', error: e);+ return false;+ }+ }++ Future<void> _writeHistorySnapshot(HistorySyncSnapshot snapshot) async {+ await _writeRemoteText(+ _historySnapshotPath,+ jsonEncode(snapshot.toJson()),+ );+ }++ Future<void> _writeDeviceHistoryChanges(+ Iterable<HistorySyncEvent> events,+ ) async {+ final deviceId = await HistorySyncService().getDeviceId();+ final remotePath = '$_historyChangesPath/$deviceId.jsonl';+ final content = HistorySyncCodec.eventsToJsonLines(events);+ if (content.isEmpty) {+ try {+ await client.remove(remotePath);+ } catch (_) {}+ return;+ }+ await _writeRemoteText(remotePath, content);+ }++ Future<String> _readRemoteText(String remotePath) async {+ final bytes = await client.read(remotePath);+ return utf8.decode(bytes);+ }++ Future<void> _writeRemoteText(String remotePath, String content) async {+ final bytes = Uint8List.fromList(utf8.encode(content));+ final response = await client.c.req(+ client,+ 'PUT',+ remotePath,+ data: bytes,+ optionsHandler: (options) {+ options.contentType = 'application/octet-stream';+ },+ );+ final statusCode = response.statusCode;+ if (statusCode == 200 || statusCode == 201 || statusCode == 204) {+ return;+ }+ throw Exception('WebDav: PUT $remotePath failed with $statusCode');}Future<void> ping() async {diff --git a/test/history_sync_test.dart b/test/history_sync_test.dartnew file mode 100644index 00000000..0858fadc--- /dev/null+++ b/test/history_sync_test.dart@@ -0,0 +1,234 @@+import 'package:flutter_test/flutter_test.dart';+import 'package:kazumi/modules/bangumi/bangumi_item.dart';+import 'package:kazumi/modules/bangumi/bangumi_tag.dart';+import 'package:kazumi/modules/history/history_module.dart';+import 'package:kazumi/modules/history/history_sync.dart';++void main() {+ group('HistorySyncDevice', () {+ test('generates stable UUID-shaped identifiers', () {+ final first = HistorySyncDevice.generateDeviceId();+ final second = HistorySyncDevice.generateDeviceId();++ expect(first, isNot(second));+ expect(+ first,+ matches(RegExp(+ r'^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$',+ )),+ );+ });+ });++ group('HistorySyncMerger', () {+ test('merges progress per episode instead of replacing whole history', () {+ final merged = HistorySyncMerger.merge(+ snapshot: HistorySyncSnapshot.empty(),+ events: [+ _upsert(+ deviceId: 'device-a',+ seq: 1,+ updatedAt: 1000,+ episode: 1,+ progressMs: 10 * 1000,+ ),+ _upsert(+ deviceId: 'device-b',+ seq: 1,+ updatedAt: 2000,+ episode: 2,+ progressMs: 20 * 1000,+ ),+ ],+ );++ final history = merged.histories.single;+ expect(history.lastWatchEpisode, 2);+ expect(history.progresses[1]!.progress.inSeconds, 10);+ expect(history.progresses[2]!.progress.inSeconds, 20);+ });++ test('clearAll prevents older events from being resurrected', () {+ final merged = HistorySyncMerger.merge(+ snapshot: HistorySyncSnapshot.empty(),+ events: [+ _upsert(+ deviceId: 'device-a',+ seq: 1,+ updatedAt: 1000,+ episode: 1,+ progressMs: 10,+ ),+ HistorySyncEvent.clearAll(+ deviceId: 'device-b',+ seq: 1,+ updatedAt: 2000,+ ),+ _upsert(+ deviceId: 'device-a',+ seq: 2,+ updatedAt: 1500,+ episode: 2,+ progressMs: 20,+ ),+ _upsert(+ deviceId: 'device-c',+ seq: 1,+ updatedAt: 3000,+ episode: 3,+ progressMs: 30,+ ),+ ],+ );++ expect(merged.histories, hasLength(1));+ expect(merged.histories.single.lastWatchEpisode, 3);+ expect(merged.histories.single.progresses.keys, [3]);+ expect(merged.clearVersion, isNotNull);+ });++ test('deleteHistory blocks older upserts but allows newer watches', () {+ final entityKey = History.getKey('plugin', _item(1));+ final merged = HistorySyncMerger.merge(+ snapshot: HistorySyncSnapshot.empty(),+ events: [+ _upsert(+ deviceId: 'device-a',+ seq: 1,+ updatedAt: 1000,+ episode: 1,+ progressMs: 10,+ ),+ HistorySyncEvent.deleteHistory(+ deviceId: 'device-b',+ seq: 1,+ entityKey: entityKey,+ updatedAt: 2000,+ ),+ _upsert(+ deviceId: 'device-a',+ seq: 2,+ updatedAt: 1500,+ episode: 2,+ progressMs: 20,+ ),+ _upsert(+ deviceId: 'device-a',+ seq: 3,+ updatedAt: 2500,+ episode: 3,+ progressMs: 30,+ ),+ ],+ );++ expect(merged.histories, hasLength(1));+ expect(merged.histories.single.progresses.keys, [3]);+ expect(merged.deletedVersions, isEmpty);+ });++ test('uses deterministic tie-breakers when timestamps are equal', () {+ final merged = HistorySyncMerger.merge(+ snapshot: HistorySyncSnapshot.empty(),+ events: [+ _upsert(+ deviceId: 'device-a',+ seq: 1,+ updatedAt: 1000,+ episode: 1,+ progressMs: 10,+ ),+ _upsert(+ deviceId: 'device-b',+ seq: 1,+ updatedAt: 1000,+ episode: 1,+ progressMs: 20,+ ),+ ],+ );++ expect(+ merged.histories.single.progresses[1]!.progress.inMilliseconds, 20);+ });+ });++ group('HistorySyncCodec', () {+ test('round-trips events through json lines', () {+ final events = [+ _upsert(+ deviceId: 'device-a',+ seq: 1,+ updatedAt: 1000,+ episode: 1,+ progressMs: 10,+ ),+ HistorySyncEvent.clearAll(+ deviceId: 'device-a',+ seq: 2,+ updatedAt: 2000,+ ),+ ];++ final lines = HistorySyncCodec.eventsToJsonLines(events);+ final restored = HistorySyncCodec.eventsFromJsonLines(lines);++ expect(+ restored.map((event) => event.eventId), ['device-a:1', 'device-a:2']);+ expect(restored.first.bangumiItem!.id, 1);+ });+ });+}++HistorySyncEvent _upsert({+ required String deviceId,+ required int seq,+ required int updatedAt,+ required int episode,+ required int progressMs,+}) {+ final history = History(+ _item(1),+ episode,+ 'plugin',+ DateTime.fromMillisecondsSinceEpoch(updatedAt),+ 'https://example.com/video',+ 'EP$episode',+ );+ history.progresses[episode] = Progress(episode, 0, progressMs);+ return HistorySyncEvent.upsertProgress(+ deviceId: deviceId,+ seq: seq,+ history: history,+ episode: episode,+ road: 0,+ progressMs: progressMs,+ updatedAt: updatedAt,+ );+}++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: '',+ );+}