Skip to content

基于自定义规则的番剧采集APP,支持流媒体在线观看,支持弹幕,支持实时超分辨率。

feat(sync): optimize Bangumi collection sync (#2523)

zhn11005d1569b39f92
diff --git a/lib/modules/bangumi/bangumi_collection.dart b/lib/modules/bangumi/bangumi_collection.dart
index b51bfe1a..f7f29fed 100644
--- a/lib/modules/bangumi/bangumi_collection.dart
+++ b/lib/modules/bangumi/bangumi_collection.dart
@@ -75,9 +75,14 @@ class BangumiCollection {
}
factory BangumiCollection.fromJson(Map json) {
- final subject = json['subject'];
+ final subject = json['subject'] as Map? ?? const <String, dynamic>{};
+ final bangumiId = (subject['id'] as int?) ?? (json['subject_id'] as int?);
+ if (bangumiId == null || bangumiId <= 0) {
+ throw const FormatException(
+ 'BangumiCollection: invalid or missing bangumi id');
+ }
final subjectImages = Map<String, String>.from(
- subject['images'] ??
+ (subject['images'] as Map?) ??
const <String, String>{
'large': '',
'common': '',
@@ -90,17 +95,27 @@ class BangumiCollection {
.whereType<Map>()
.map((tag) => Map<String, dynamic>.from(tag))
.toList();
+ final updatedAtStr = json['updated_at'] as String?;
+ if (updatedAtStr == null || updatedAtStr.trim().isEmpty) {
+ throw const FormatException(
+ 'BangumiCollection: missing or empty updated_at');
+ }
+ final updatedAt = DateTime.tryParse(updatedAtStr);
+ if (updatedAt == null) {
+ throw const FormatException(
+ 'BangumiCollection: invalid updated_at format');
+ }
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'],
+ bangumiId,
+ subject['date'] as String?,
+ updatedAt,
+ BangumiCollectionType.fromValue(json['type'] as int? ?? 0),
+ subject['name'] as String? ?? '',
+ subject['name_cn'] as String? ?? '',
+ subject['short_summary'] as String? ?? '',
+ (subject['score'] as num?)?.toDouble() ?? 0.0,
+ subject['eps'] as int? ?? 0,
+ subject['rank'] as int? ?? 0,
subjectImages,
subjectTags,
);
diff --git a/lib/modules/bangumi/sync_priority.dart b/lib/modules/bangumi/sync_priority.dart
index ed7f07f3..c2851a68 100644
--- a/lib/modules/bangumi/sync_priority.dart
+++ b/lib/modules/bangumi/sync_priority.dart
@@ -1,6 +1,7 @@
enum BangumiSyncPriority {
localFirst(0, '本地优先'),
- bangumiFirst(1, 'Bangumi优先');
+ bangumiFirst(1, 'Bangumi优先'),
+ timeFirst(2, '最新优先');
const BangumiSyncPriority(this.value, this.label);
diff --git a/lib/modules/collect/collect_sync_merger.dart b/lib/modules/collect/collect_sync_merger.dart
index 4a959690..69016db3 100644
--- a/lib/modules/collect/collect_sync_merger.dart
+++ b/lib/modules/collect/collect_sync_merger.dart
@@ -174,7 +174,7 @@ class CollectSyncMerger {
BangumiUploadMutation(bangumiId: id, type: localMap[id]!.type),
);
}
- } else {
+ } else if (priority == BangumiSyncPriority.bangumiFirst) {
for (final id in mismatchIds) {
conflictLocalUpdates.add(
BangumiLocalMutation(
@@ -183,6 +183,24 @@ class CollectSyncMerger {
),
);
}
+ } else if (priority == BangumiSyncPriority.timeFirst) {
+ for (final id in mismatchIds) {
+ final localTime = localMap[id]!.time;
+ final remoteTime = remoteMap[id]!.updatedAt;
+ if (localTime.isAfter(remoteTime) ||
+ localTime.isAtSameMomentAs(remoteTime)) {
+ conflictUploads.add(
+ BangumiUploadMutation(bangumiId: id, type: localMap[id]!.type),
+ );
+ } else {
+ conflictLocalUpdates.add(
+ BangumiLocalMutation(
+ collectible: _fromBangumiCollection(remoteMap[id]!),
+ changeAction: 2,
+ ),
+ );
+ }
+ }
}
return BangumiCollectiblesMergePlan(
diff --git a/lib/request/apis/bangumi_api.dart b/lib/request/apis/bangumi_api.dart
index b271c3c0..5dffc62f 100644
--- a/lib/request/apis/bangumi_api.dart
+++ b/lib/request/apis/bangumi_api.dart
@@ -15,6 +15,7 @@ import 'package:kazumi/modules/collect/collect_type_mapper.dart';
import 'package:kazumi/modules/bangumi/bangumi_collection_type.dart';
import 'package:kazumi/modules/comments/comment_item.dart';
import 'package:kazumi/utils/search_parser.dart';
+import 'package:kazumi/utils/async_rate_limiter.dart';
class BangumiSearchPage {
const BangumiSearchPage({
@@ -28,6 +29,8 @@ class BangumiSearchPage {
class BangumiApi {
static final BangumiClient _client = BangumiClient.instance;
+ static final AsyncRateLimiter _writeRateLimiter =
+ AsyncRateLimiter(const Duration(milliseconds: 250));
static Future<List<List<BangumiItem>>> getCalendar() async {
List<List<BangumiItem>> bangumiCalendar = [];
@@ -558,7 +561,7 @@ class BangumiApi {
BangumiCollectionType.abandoned,
],
String? username,
- required int limit,
+ int limit = 50,
void Function(String message, int current, int total)? onProgress,
}) async {
final List<BangumiCollection> bangumiCollection = [];
@@ -574,68 +577,138 @@ class BangumiApi {
}
try {
- const Duration requestInterval = Duration(milliseconds: 250);
+ final rateLimiter =
+ AsyncRateLimiter(const Duration(milliseconds: 200));
+ const int concurrency = 3;
- for (final collectionType in includeBangumiTypes) {
- if (collectionType == BangumiCollectionType.unknown) {
- continue;
+ Future<Map> fetchPageData(int offset, int pageLimit) async {
+ await rateLimiter.acquire();
+ final url = ApiEndpoints.formatUrl(
+ ApiEndpoints.bangumiAuthAPIMirrorDomain +
+ ApiEndpoints.bangumiGetAllCollections,
+ [resolvedUsername, pageLimit, offset]);
+ final jsonData = await _client.get(
+ url,
+ requiresAuth: true,
+ );
+ if (jsonData is! Map || jsonData['data'] is! List) {
+ KazumiLogger().e(
+ 'BangumiApi: invalid collection response format at offset=$offset',
+ );
+ throw const FormatException(
+ 'BangumiApi: Invalid collection response format');
}
- int offset = 0;
- int? total;
- bool totalInitialized = false;
- while (true) {
- dynamic jsonData;
- try {
- final url = ApiEndpoints.formatUrl(
- ApiEndpoints.bangumiAuthAPIMirrorDomain +
- ApiEndpoints.bangumiGetCollection,
- [resolvedUsername, limit, offset, collectionType.value]);
- jsonData = await _client.get(
- url,
- requiresAuth: true,
- );
- } catch (e) {
- KazumiLogger().e(
- 'BangumiApi: fetch collection failed. type=${collectionType.value}, offset=$offset',
- error: e,
- );
- rethrow;
- }
-
- final Map jsonMap = jsonData;
- final List<dynamic> jsonList = jsonMap['data'];
- total ??= jsonMap['total'];
- if (!totalInitialized && total != null) {
- progressTotal += total;
- totalInitialized = true;
- }
+ return jsonData;
+ }
- 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(
- 'BangumiApi: parse collection item failed: ${e.toString()}',
- error: e,
- );
- failedItemCount++;
+ List<BangumiCollection> parsePageItems(List<dynamic> jsonList) {
+ final List<BangumiCollection> items = [];
+ for (dynamic jsonItem in jsonList) {
+ if (jsonItem is Map) {
+ try {
+ final collection = BangumiCollection.fromJson(jsonItem);
+ if (includeBangumiTypes.contains(collection.type)) {
+ items.add(collection);
}
+ } catch (e) {
+ KazumiLogger().e(
+ 'BangumiApi: parse collection item failed: ${e.toString()}',
+ error: e,
+ );
+ failedItemCount++;
}
}
+ }
+ return items;
+ }
- if (jsonList.isEmpty || (total != null && offset + limit >= total)) {
+ final firstPageJson = await fetchPageData(0, limit);
+ final int? rawTotal = firstPageJson['total'] as int?;
+ final serverLimit = (firstPageJson['limit'] as int?) ?? limit;
+ final effectiveLimit = (serverLimit > 0) ? serverLimit : limit;
+ final List<dynamic> firstPageList =
+ firstPageJson['data'] as List<dynamic>;
+
+ if (rawTotal == null) {
+ KazumiLogger().e(
+ 'BangumiApi: missing or invalid total in collection response',
+ );
+ throw const FormatException(
+ 'BangumiApi: missing total in collection response');
+ }
+ final int total = rawTotal;
+
+ final firstPageReceivedCount = firstPageList.length;
+ final firstPageItems = parsePageItems(firstPageList);
+ bangumiCollection.addAll(firstPageItems);
+ progressCurrent += firstPageList.length;
+
+ if (total > 0 && firstPageReceivedCount == 0) {
+ KazumiLogger().e(
+ 'BangumiApi: received empty data on first page while total > 0 (total=$total)',
+ );
+ throw const FormatException(
+ 'BangumiApi: received empty data on first page while total > 0');
+ }
+ progressTotal = total;
+ onProgress?.call(
+ '正在拉取 Bangumi 收藏',
+ progressCurrent,
+ progressTotal,
+ );
+
+ if (total == 0 || firstPageReceivedCount >= total) {
+ KazumiLogger()
+ .d('get Bangumi collection count: ${bangumiCollection.length}');
+ KazumiLogger().d('get item failed count: $failedItemCount');
+ return bangumiCollection;
+ }
+
+ final remainingOffsets = <int>[];
+ for (int off = effectiveLimit; off < total; off += effectiveLimit) {
+ remainingOffsets.add(off);
+ }
+
+ final Map<int, List<BangumiCollection>> pageResults = {};
+ final offsetsQueue = List<int>.from(remainingOffsets);
+
+ Future<void> worker() async {
+ while (offsetsQueue.isNotEmpty) {
+ final offset = offsetsQueue.removeAt(0);
+ final pageJson = await fetchPageData(offset, effectiveLimit);
+ final List<dynamic> jsonList = pageJson['data'] as List<dynamic>;
+ final items = parsePageItems(jsonList);
+ pageResults[offset] = items;
+
+ progressCurrent += jsonList.length;
+ onProgress?.call(
+ '正在拉取 Bangumi 收藏',
+ progressCurrent > progressTotal ? progressTotal : progressCurrent,
+ progressTotal,
+ );
+
+ if (jsonList.length < serverLimit && offset + jsonList.length >= total) {
+ offsetsQueue.clear();
break;
}
+ }
+ }
- offset += limit;
- await Future.delayed(requestInterval);
+ final workerCount = remainingOffsets.length < concurrency
+ ? remainingOffsets.length
+ : concurrency;
+ await Future.wait(List.generate(workerCount, (_) => worker()));
+
+ final Set<int> seenBangumiIds =
+ bangumiCollection.map((e) => e.bangumiId).toSet();
+ for (final offset in remainingOffsets) {
+ final items = pageResults[offset];
+ if (items != null) {
+ for (final item in items) {
+ if (seenBangumiIds.add(item.bangumiId)) {
+ bangumiCollection.add(item);
+ }
+ }
}
}
} catch (e) {
@@ -651,7 +724,7 @@ class BangumiApi {
/// Update the Bangumi collection by ID
static Future<bool> updateBangumiById(
int id, Map<String, dynamic> data) async {
- const Duration requestInterval = Duration(milliseconds: 250);
+ await _writeRateLimiter.acquire();
try {
await _client.post(
ApiEndpoints.formatUrl(
@@ -683,8 +756,6 @@ class BangumiApi {
} catch (e) {
KazumiLogger().e('Network: update bangumi collection failed', error: e);
rethrow;
- } finally {
- await Future.delayed(requestInterval);
}
}
diff --git a/lib/request/config/api_endpoints.dart b/lib/request/config/api_endpoints.dart
index 219606d8..ca888ddc 100644
--- a/lib/request/config/api_endpoints.dart
+++ b/lib/request/config/api_endpoints.dart
@@ -75,9 +75,9 @@ class ApiEndpoints {
/// 新增或修改用户单个条目收藏
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}';
+ /// 获取用户全部收藏(不限类型)。用户名,分页参数1(limit),分页参数2(offset)
+ static const String bangumiGetAllCollections =
+ '/v0/users/{0}/collections?subject_type=2&limit={1}&offset={2}';
/// Bangumi Next API Domain
static const String bangumiAPINextDomain = 'https://next.bgm.tv';
diff --git a/lib/services/sync/bangumi_sync_service.dart b/lib/services/sync/bangumi_sync_service.dart
index 9ca1b435..e0670b12 100644
--- a/lib/services/sync/bangumi_sync_service.dart
+++ b/lib/services/sync/bangumi_sync_service.dart
@@ -147,7 +147,7 @@ class BangumiSyncService {
// 1. 全量拉取远程收藏
final remoteCollection = await BangumiApi.getBangumiCollectibles(
username: username,
- limit: 100,
+ limit: 50,
onProgress: onProgress,
);
@@ -198,21 +198,25 @@ class BangumiSyncService {
}
// 5. 双方都有但不一致:按优先级处理
- if (priority == BangumiSyncPriority.localFirst) {
- onProgress?.call('本地优先:正在处理冲突状态', syncedCount, totalOperations);
+ if (mergePlan.conflictUploads.isNotEmpty) {
+ onProgress?.call(
+ '${priority.label}:正在上传冲突状态', syncedCount, totalOperations);
for (final upload in mergePlan.conflictUploads) {
final updated = await BangumiApi.updateBangumiByType(
upload.bangumiId,
upload.type,
);
- if (updated != true) {
+ if (!updated) {
throw Exception('同步失败:条目 ${upload.bangumiId} 上传到 Bangumi 失败');
}
syncedCount++;
- onProgress?.call('本地优先:正在处理冲突状态', syncedCount, totalOperations);
+ onProgress?.call(
+ '${priority.label}:正在上传冲突状态', syncedCount, totalOperations);
}
- } else {
- onProgress?.call('Bangumi优先:正在处理冲突状态', syncedCount, totalOperations);
+ }
+ if (mergePlan.conflictLocalUpdates.isNotEmpty) {
+ onProgress?.call(
+ '${priority.label}:正在更新本地冲突状态', syncedCount, totalOperations);
for (final mutation in mergePlan.conflictLocalUpdates) {
await GStorage.putCollectible(mutation.collectible);
await _recordCollectibleChange(
@@ -222,7 +226,7 @@ class BangumiSyncService {
);
syncedCount++;
onProgress?.call(
- 'Bangumi优先:正在处理冲突状态', syncedCount, totalOperations);
+ '${priority.label}:正在更新本地冲突状态', syncedCount, totalOperations);
}
}
onProgress?.call('Bangumi 状态同步完成', 1, 1);
diff --git a/lib/utils/async_rate_limiter.dart b/lib/utils/async_rate_limiter.dart
new file mode 100644
index 00000000..bb505711
--- /dev/null
+++ b/lib/utils/async_rate_limiter.dart
@@ -0,0 +1,27 @@
+import 'dart:async';
+
+/// Ensures asynchronous operations are spaced apart by at least a minimum interval.
+class AsyncRateLimiter {
+ AsyncRateLimiter(this.period);
+
+ final Duration period;
+ DateTime _nextAllowedTime = DateTime.now();
+
+ /// Waits until the next allowed time slot and reserves the following slot.
+ Future<void> acquire() async {
+ final now = DateTime.now();
+ final scheduledTime =
+ _nextAllowedTime.isAfter(now) ? _nextAllowedTime : now;
+ _nextAllowedTime = scheduledTime.add(period);
+ final waitDuration = scheduledTime.difference(now);
+ if (waitDuration > Duration.zero) {
+ await Future.delayed(waitDuration);
+ }
+ }
+
+ /// Runs [action] after acquiring a rate-limited time slot.
+ Future<T> run<T>(Future<T> Function() action) async {
+ await acquire();
+ return await action();
+ }
+}
diff --git a/test/async_rate_limiter_test.dart b/test/async_rate_limiter_test.dart
new file mode 100644
index 00000000..b2b39c2d
--- /dev/null
+++ b/test/async_rate_limiter_test.dart
@@ -0,0 +1,75 @@
+import 'package:flutter_test/flutter_test.dart';
+import 'package:kazumi/utils/async_rate_limiter.dart';
+
+void main() {
+ group('AsyncRateLimiter', () {
+ test('first acquire completes immediately without unnecessary delay', () async {
+ final limiter = AsyncRateLimiter(const Duration(milliseconds: 50));
+ final stopwatch = Stopwatch()..start();
+ await limiter.acquire();
+ stopwatch.stop();
+
+ expect(stopwatch.elapsedMilliseconds, lessThan(30));
+ });
+
+ test('serial sequential calls maintain at least period spacing', () async {
+ const period = Duration(milliseconds: 40);
+ final limiter = AsyncRateLimiter(period);
+
+ final timestamps = <int>[];
+ final stopwatch = Stopwatch()..start();
+
+ for (var i = 0; i < 3; i++) {
+ await limiter.acquire();
+ timestamps.add(stopwatch.elapsedMilliseconds);
+ }
+
+ expect(timestamps.length, 3);
+ for (var i = 1; i < timestamps.length; i++) {
+ final diff = timestamps[i] - timestamps[i - 1];
+ expect(diff, greaterThanOrEqualTo(35));
+ }
+ });
+
+ test('concurrent callers are spaced apart into sequential time slots', () async {
+ const period = Duration(milliseconds: 40);
+ final limiter = AsyncRateLimiter(period);
+
+ final completionTimes = <int>[];
+ final stopwatch = Stopwatch()..start();
+
+ await Future.wait(
+ List.generate(4, (index) async {
+ await limiter.acquire();
+ completionTimes.add(stopwatch.elapsedMilliseconds);
+ }),
+ );
+
+ expect(completionTimes.length, 4);
+ for (var i = 1; i < completionTimes.length; i++) {
+ final diff = completionTimes[i] - completionTimes[i - 1];
+ expect(diff, greaterThanOrEqualTo(35));
+ }
+ });
+
+ test('run passes return value and preserves rate limit on failure', () async {
+ const period = Duration(milliseconds: 40);
+ final limiter = AsyncRateLimiter(period);
+
+ final stopwatch = Stopwatch()..start();
+
+ final firstResult = await limiter.run(() async => 'success');
+ expect(firstResult, 'success');
+
+ await expectLater(
+ limiter.run(() async => throw StateError('action error')),
+ throwsStateError,
+ );
+
+ final secondResult = await limiter.run(() async => 'recovered');
+ expect(secondResult, 'recovered');
+
+ expect(stopwatch.elapsedMilliseconds, greaterThanOrEqualTo(70));
+ });
+ });
+}
diff --git a/test/collect_sync_test.dart b/test/collect_sync_test.dart
index 86160769..5bcd419b 100644
--- a/test/collect_sync_test.dart
+++ b/test/collect_sync_test.dart
@@ -176,6 +176,178 @@ void main() {
expect(plan.remoteOnlyPuts, isEmpty);
expect(plan.conflictLocalUpdates, isEmpty);
});
+
+ test('resolves conflicts with timeFirst (local newer, remote newer, same moment)', () {
+ final plan = CollectSyncMerger.planBangumi(
+ localCollectibles: [
+ // id 1: local newer (timestamp 50 vs remote 10)
+ _collect(1, CollectType.watching, 50),
+ // id 2: remote newer (timestamp 10 vs remote 50)
+ _collect(2, CollectType.planToWatch, 10),
+ // id 3: same moment (timestamp 30 vs remote 30) -> default to local (conflictUploads)
+ _collect(3, CollectType.onHold, 30),
+ // id 4: local only
+ _collect(4, CollectType.watched, 20),
+ ],
+ remoteCollections: [
+ _remote(1, BangumiCollectionType.watched, 10),
+ _remote(2, BangumiCollectionType.watched, 50),
+ _remote(3, BangumiCollectionType.abandoned, 30),
+ // id 5: remote only
+ _remote(5, BangumiCollectionType.planToWatch, 40),
+ ],
+ priority: BangumiSyncPriority.timeFirst,
+ );
+
+ expect(plan.totalOperations, 5);
+ // local only upload
+ expect(plan.localOnlyUploads.map((u) => u.bangumiId), [4]);
+ expect(plan.localOnlyUploads.single.type, CollectType.watched.value);
+ // remote only put
+ expect(plan.remoteOnlyPuts.map((p) => p.collectible.bangumiItem.id), [5]);
+ expect(plan.remoteOnlyPuts.single.collectible.type, CollectType.planToWatch.value);
+ // conflict uploads: id 1 (local newer), id 3 (same moment)
+ expect(plan.conflictUploads.map((u) => u.bangumiId), [1, 3]);
+ expect(plan.conflictUploads.firstWhere((u) => u.bangumiId == 1).type, CollectType.watching.value);
+ expect(plan.conflictUploads.firstWhere((u) => u.bangumiId == 3).type, CollectType.onHold.value);
+ // conflict local updates: id 2 (remote newer)
+ expect(plan.conflictLocalUpdates.map((u) => u.collectible.bangumiItem.id), [2]);
+ expect(plan.conflictLocalUpdates.single.collectible.type, CollectType.watched.value);
+ });
+ });
+
+ group('BangumiSyncPriority', () {
+ test('fromValue maps correctly including timeFirst and fallback', () {
+ expect(BangumiSyncPriority.fromValue(0), BangumiSyncPriority.localFirst);
+ expect(BangumiSyncPriority.fromValue(1), BangumiSyncPriority.bangumiFirst);
+ expect(BangumiSyncPriority.fromValue(2), BangumiSyncPriority.timeFirst);
+ expect(BangumiSyncPriority.fromValue(999), BangumiSyncPriority.localFirst);
+ expect(BangumiSyncPriority.timeFirst.value, 2);
+ expect(BangumiSyncPriority.timeFirst.label, '最新优先');
+ });
+ });
+
+ group('BangumiCollection.fromJson', () {
+ test('parses normal JSON correctly', () {
+ final collection = BangumiCollection.fromJson({
+ 'updated_at': '2026-08-30T14:00:00Z',
+ 'type': 2,
+ 'subject': {
+ 'id': 12345,
+ 'date': '2026-04-01',
+ 'name': 'Original Name',
+ 'name_cn': '中文名',
+ 'short_summary': '这是一部动画',
+ 'score': 8.5,
+ 'eps': 24,
+ 'rank': 42,
+ 'images': {
+ 'large': 'https://example.com/large.jpg',
+ },
+ 'tags': [
+ {'name': '科幻', 'count': 100},
+ ],
+ },
+ });
+
+ expect(collection.bangumiId, 12345);
+ expect(collection.name, 'Original Name');
+ expect(collection.nameCn, '中文名');
+ expect(collection.shortSummary, '这是一部动画');
+ expect(collection.score, 8.5);
+ expect(collection.eps, 24);
+ expect(collection.rank, 42);
+ expect(collection.type, BangumiCollectionType.watched);
+ expect(collection.updatedAt, DateTime.parse('2026-08-30T14:00:00Z'));
+ expect(collection.images['large'], 'https://example.com/large.jpg');
+ expect(collection.tags.length, 1);
+ });
+
+ test('handles missing or malformed fields defensively while requiring valid updated_at', () {
+ final collection = BangumiCollection.fromJson({
+ 'updated_at': '2026-08-30T14:00:00Z',
+ 'type': 1,
+ 'subject': {
+ 'id': 999,
+ 'score': 7, // integer instead of double
+ // missing short_summary, eps, rank, images, tags
+ },
+ });
+
+ expect(collection.bangumiId, 999);
+ expect(collection.score, 7.0);
+ expect(collection.shortSummary, '');
+ expect(collection.eps, 0);
+ expect(collection.rank, 0);
+ expect(collection.updatedAt, DateTime.parse('2026-08-30T14:00:00Z'));
+ expect(collection.images['large'], '');
+ expect(collection.tags, isEmpty);
+ });
+
+ test('throws FormatException on missing, empty, or invalid updated_at', () {
+ expect(
+ () => BangumiCollection.fromJson({
+ 'type': 1,
+ 'subject': {'id': 999},
+ }),
+ throwsA(isA<FormatException>()),
+ );
+
+ expect(
+ () => BangumiCollection.fromJson({
+ 'updated_at': '',
+ 'type': 1,
+ 'subject': {'id': 999},
+ }),
+ throwsA(isA<FormatException>()),
+ );
+
+ expect(
+ () => BangumiCollection.fromJson({
+ 'updated_at': 'invalid-date-string',
+ 'type': 1,
+ 'subject': {'id': 999},
+ }),
+ throwsA(isA<FormatException>()),
+ );
+ });
+
+ test('falls back to subject_id when subject.id is missing', () {
+ final collection = BangumiCollection.fromJson({
+ 'updated_at': '2026-08-30T14:00:00Z',
+ 'subject_id': 888,
+ 'type': 1,
+ 'subject': {
+ 'name': 'Fallback Name',
+ },
+ });
+ expect(collection.bangumiId, 888);
+ expect(collection.name, 'Fallback Name');
+ });
+
+ test('throws FormatException when subject id is missing or invalid', () {
+ expect(
+ () => BangumiCollection.fromJson({
+ 'type': 1,
+ 'subject': {
+ 'name': 'No ID',
+ },
+ }),
+ throwsA(isA<FormatException>()),
+ );
+
+ expect(
+ () => BangumiCollection.fromJson({
+ 'subject_id': 0,
+ 'type': 1,
+ 'subject': {
+ 'id': 0,
+ 'name': 'Zero ID',
+ },
+ }),
+ throwsA(isA<FormatException>()),
+ );
+ });
});
}