Skip to content

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

feat: offline cache (#1682)

林晨85dd49746423
diff --git a/lib/hive_registrar.g.dart b/lib/hive_registrar.g.dart
index deac3ad0..96dd3665 100644
--- a/lib/hive_registrar.g.dart
+++ b/lib/hive_registrar.g.dart
@@ -7,6 +7,7 @@ import 'package:kazumi/modules/bangumi/bangumi_item.dart';
import 'package:kazumi/modules/bangumi/bangumi_tag.dart';
import 'package:kazumi/modules/collect/collect_change_module.dart';
import 'package:kazumi/modules/collect/collect_module.dart';
+import 'package:kazumi/modules/download/download_module.dart';
import 'package:kazumi/modules/history/history_module.dart';
import 'package:kazumi/modules/search/search_history_module.dart';
@@ -16,6 +17,8 @@ extension HiveRegistrar on HiveInterface {
registerAdapter(BangumiTagAdapter());
registerAdapter(CollectedBangumiAdapter());
registerAdapter(CollectedBangumiChangeAdapter());
+ registerAdapter(DownloadEpisodeAdapter());
+ registerAdapter(DownloadRecordAdapter());
registerAdapter(HistoryAdapter());
registerAdapter(ProgressAdapter());
registerAdapter(SearchHistoryAdapter());
@@ -28,6 +31,8 @@ extension IsolatedHiveRegistrar on IsolatedHiveInterface {
registerAdapter(BangumiTagAdapter());
registerAdapter(CollectedBangumiAdapter());
registerAdapter(CollectedBangumiChangeAdapter());
+ registerAdapter(DownloadEpisodeAdapter());
+ registerAdapter(DownloadRecordAdapter());
registerAdapter(HistoryAdapter());
registerAdapter(ProgressAdapter());
registerAdapter(SearchHistoryAdapter());
diff --git a/lib/main.dart b/lib/main.dart
index e03fa901..d529a7c5 100644
--- a/lib/main.dart
+++ b/lib/main.dart
@@ -34,10 +34,13 @@ void main() async {
}
try {
- await Hive.initFlutter(
- '${(await getApplicationSupportDirectory()).path}/hive');
+ final hivePath = '${(await getApplicationSupportDirectory()).path}/hive';
+ await Hive.initFlutter(hivePath);
await GStorage.init();
- } catch (_) {
+ } catch (e) {
+ // Log the error for debugging (if logger is available)
+ debugPrint('Storage initialization failed: $e');
+
if (Platform.isWindows) {
await windowManager.ensureInitialized();
windowManager.waitUntilReadyToShow(null, () async {
diff --git a/lib/modules/danmaku/danmaku_module.dart b/lib/modules/danmaku/danmaku_module.dart
index 7a3e38a8..c8f0a22d 100644
--- a/lib/modules/danmaku/danmaku_module.dart
+++ b/lib/modules/danmaku/danmaku_module.dart
@@ -24,4 +24,16 @@ class Danmaku {
String sourceValue = parts[3];
return Danmaku(time: timeValue, message: messageValue, type: typeValue, color: color, source: sourceValue);
}
+
+ /// 序列化为 JSON 格式 (与 fromJson 格式一致)
+ Map<String, dynamic> toJson() {
+ // 只存储 RGB 部分 (与 DanDanPlay API 格式一致)
+ final colorValue = ((color.r * 255).toInt() << 16) |
+ ((color.g * 255).toInt() << 8) |
+ (color.b * 255).toInt();
+ return {
+ 'm': message,
+ 'p': '$time,$type,$colorValue,$source',
+ };
+ }
}
\ No newline at end of file
diff --git a/lib/modules/download/download_module.dart b/lib/modules/download/download_module.dart
new file mode 100644
index 00000000..94dd6867
--- /dev/null
+++ b/lib/modules/download/download_module.dart
@@ -0,0 +1,117 @@
+import 'package:hive_ce/hive.dart';
+
+part 'download_module.g.dart';
+
+@HiveType(typeId: 7)
+class DownloadRecord {
+ @HiveField(0)
+ int bangumiId;
+
+ @HiveField(1)
+ String bangumiName;
+
+ @HiveField(2)
+ String bangumiCover;
+
+ @HiveField(3)
+ String pluginName;
+
+ @HiveField(4)
+ Map<int, DownloadEpisode> episodes;
+
+ @HiveField(5)
+ DateTime createdAt;
+
+ String get key => '${pluginName}_$bangumiId';
+
+ DownloadRecord(
+ this.bangumiId,
+ this.bangumiName,
+ this.bangumiCover,
+ this.pluginName,
+ this.episodes,
+ this.createdAt,
+ );
+}
+
+@HiveType(typeId: 8)
+class DownloadEpisode {
+ @HiveField(0)
+ int episodeNumber;
+
+ @HiveField(1)
+ String episodeName;
+
+ @HiveField(2)
+ int road;
+
+ /// 0=pending 1=resolving 2=downloading 3=completed 4=failed 5=paused
+ @HiveField(3)
+ int status;
+
+ @HiveField(4)
+ double progressPercent;
+
+ @HiveField(5)
+ int totalSegments;
+
+ @HiveField(6)
+ int downloadedSegments;
+
+ @HiveField(7)
+ String localM3u8Path;
+
+ @HiveField(8)
+ String downloadDirectory;
+
+ @HiveField(9)
+ String networkM3u8Url;
+
+ @HiveField(10)
+ DateTime? completedAt;
+
+ @HiveField(11, defaultValue: '')
+ String errorMessage;
+
+ @HiveField(12, defaultValue: 0)
+ int totalBytes;
+
+ @HiveField(13, defaultValue: '')
+ String episodePageUrl;
+
+ /// 缓存的弹幕数据 (JSON 字符串格式)
+ @HiveField(14, defaultValue: '')
+ String danmakuData;
+
+ /// DanDanPlay 番剧 ID (用于弹幕查询缓存)
+ @HiveField(15, defaultValue: 0)
+ int danDanBangumiID;
+
+ DownloadEpisode(
+ this.episodeNumber,
+ this.episodeName,
+ this.road,
+ this.status,
+ this.progressPercent,
+ this.totalSegments,
+ this.downloadedSegments,
+ this.localM3u8Path,
+ this.downloadDirectory,
+ this.networkM3u8Url,
+ this.completedAt,
+ this.errorMessage,
+ this.totalBytes,
+ this.episodePageUrl, {
+ this.danmakuData = '',
+ this.danDanBangumiID = 0,
+ });
+}
+
+class DownloadStatus {
+ static const int pending = 0;
+ static const int resolving = 1;
+ static const int downloading = 2;
+ static const int completed = 3;
+ static const int failed = 4;
+ static const int paused = 5;
+}
diff --git a/lib/modules/download/download_module.g.dart b/lib/modules/download/download_module.g.dart
new file mode 100644
index 00000000..116844b1
--- /dev/null
+++ b/lib/modules/download/download_module.g.dart
@@ -0,0 +1,135 @@
+// GENERATED CODE - DO NOT MODIFY BY HAND
+
+part of 'download_module.dart';
+
+// **************************************************************************
+// TypeAdapterGenerator
+// **************************************************************************
+
+class DownloadRecordAdapter extends TypeAdapter<DownloadRecord> {
+ @override
+ final typeId = 7;
+
+ @override
+ DownloadRecord read(BinaryReader reader) {
+ final numOfFields = reader.readByte();
+ final fields = <int, dynamic>{
+ for (int i = 0; i < numOfFields; i++) reader.readByte(): reader.read(),
+ };
+ return DownloadRecord(
+ (fields[0] as num).toInt(),
+ fields[1] as String,
+ fields[2] as String,
+ fields[3] as String,
+ (fields[4] as Map).cast<int, DownloadEpisode>(),
+ fields[5] as DateTime,
+ );
+ }
+
+ @override
+ void write(BinaryWriter writer, DownloadRecord obj) {
+ writer
+ ..writeByte(6)
+ ..writeByte(0)
+ ..write(obj.bangumiId)
+ ..writeByte(1)
+ ..write(obj.bangumiName)
+ ..writeByte(2)
+ ..write(obj.bangumiCover)
+ ..writeByte(3)
+ ..write(obj.pluginName)
+ ..writeByte(4)
+ ..write(obj.episodes)
+ ..writeByte(5)
+ ..write(obj.createdAt);
+ }
+
+ @override
+ int get hashCode => typeId.hashCode;
+
+ @override
+ bool operator ==(Object other) =>
+ identical(this, other) ||
+ other is DownloadRecordAdapter &&
+ runtimeType == other.runtimeType &&
+ typeId == other.typeId;
+}
+
+class DownloadEpisodeAdapter extends TypeAdapter<DownloadEpisode> {
+ @override
+ final typeId = 8;
+
+ @override
+ DownloadEpisode read(BinaryReader reader) {
+ final numOfFields = reader.readByte();
+ final fields = <int, dynamic>{
+ for (int i = 0; i < numOfFields; i++) reader.readByte(): reader.read(),
+ };
+ return DownloadEpisode(
+ (fields[0] as num).toInt(),
+ fields[1] as String,
+ (fields[2] as num).toInt(),
+ (fields[3] as num).toInt(),
+ (fields[4] as num).toDouble(),
+ (fields[5] as num).toInt(),
+ (fields[6] as num).toInt(),
+ fields[7] as String,
+ fields[8] as String,
+ fields[9] as String,
+ fields[10] as DateTime?,
+ fields[11] == null ? '' : fields[11] as String,
+ fields[12] == null ? 0 : (fields[12] as num).toInt(),
+ fields[13] == null ? '' : fields[13] as String,
+ danmakuData: fields[14] == null ? '' : fields[14] as String,
+ danDanBangumiID: fields[15] == null ? 0 : (fields[15] as num).toInt(),
+ );
+ }
+
+ @override
+ void write(BinaryWriter writer, DownloadEpisode obj) {
+ writer
+ ..writeByte(16)
+ ..writeByte(0)
+ ..write(obj.episodeNumber)
+ ..writeByte(1)
+ ..write(obj.episodeName)
+ ..writeByte(2)
+ ..write(obj.road)
+ ..writeByte(3)
+ ..write(obj.status)
+ ..writeByte(4)
+ ..write(obj.progressPercent)
+ ..writeByte(5)
+ ..write(obj.totalSegments)
+ ..writeByte(6)
+ ..write(obj.downloadedSegments)
+ ..writeByte(7)
+ ..write(obj.localM3u8Path)
+ ..writeByte(8)
+ ..write(obj.downloadDirectory)
+ ..writeByte(9)
+ ..write(obj.networkM3u8Url)
+ ..writeByte(10)
+ ..write(obj.completedAt)
+ ..writeByte(11)
+ ..write(obj.errorMessage)
+ ..writeByte(12)
+ ..write(obj.totalBytes)
+ ..writeByte(13)
+ ..write(obj.episodePageUrl)
+ ..writeByte(14)
+ ..write(obj.danmakuData)
+ ..writeByte(15)
+ ..write(obj.danDanBangumiID);
+ }
+
+ @override
+ int get hashCode => typeId.hashCode;
+
+ @override
+ bool operator ==(Object other) =>
+ identical(this, other) ||
+ other is DownloadEpisodeAdapter &&
+ runtimeType == other.runtimeType &&
+ typeId == other.typeId;
+}
diff --git a/lib/pages/download/download_controller.dart b/lib/pages/download/download_controller.dart
new file mode 100644
index 00000000..d8825279
--- /dev/null
+++ b/lib/pages/download/download_controller.dart
@@ -0,0 +1,621 @@
+import 'dart:convert';
+import 'package:flutter_modular/flutter_modular.dart';
+import 'package:hive_ce/hive.dart';
+import 'package:kazumi/modules/download/download_module.dart';
+import 'package:kazumi/modules/danmaku/danmaku_module.dart';
+import 'package:kazumi/plugins/plugins.dart';
+import 'package:kazumi/plugins/plugins_controller.dart';
+import 'package:kazumi/repositories/download_repository.dart';
+import 'package:kazumi/utils/download_manager.dart';
+import 'package:kazumi/utils/logger.dart';
+import 'package:kazumi/utils/storage.dart';
+import 'package:kazumi/providers/providers.dart';
+import 'package:kazumi/request/damaku.dart';
+import 'package:mobx/mobx.dart';
+
+part 'download_controller.g.dart';
+
+class DownloadController = _DownloadController with _$DownloadController;
+
+abstract class _DownloadController with Store {
+ final _repository = Modular.get<IDownloadRepository>();
+ final _downloadManager = Modular.get<IDownloadManager>();
+
+ @observable
+ ObservableList<DownloadRecord> records = ObservableList<DownloadRecord>();
+
+ /// Queue for episodes waiting to be resolved via WebView (one at a time)
+ final List<_ResolveRequest> _resolveQueue = [];
+ bool _isResolving = false;
+
+ void init() {
+ final temp = _repository.getAllRecords();
+ records.clear();
+ records.addAll(temp);
+
+ // Reset any incomplete states to 'paused' on startup
+ // This includes 'pending' because the in-memory queue is lost on restart
+ for (final record in records) {
+ bool changed = false;
+ for (final entry in record.episodes.entries) {
+ if (entry.value.status == DownloadStatus.downloading ||
+ entry.value.status == DownloadStatus.resolving ||
+ entry.value.status == DownloadStatus.pending) {
+ entry.value.status = DownloadStatus.paused;
+ changed = true;
+ }
+ }
+ if (changed) {
+ _repository.putRecord(record);
+ }
+ }
+
+ _downloadManager.onProgress = _onDownloadProgress;
+ }
+
+ /// Speed data (in-memory, not persisted)
+ final Map<String, double> _speeds = {};
+
+ void _onDownloadProgress(
+ String recordKey, int episodeNumber, DownloadEpisode episode, double speed) {
+ _repository.updateEpisode(recordKey, episodeNumber, episode);
+ // Store speed in memory
+ final key = '${recordKey}_$episodeNumber';
+ _speeds[key] = speed;
+ refreshRecords();
+ }
+
+ /// Get current download speed for an episode (bytes/sec)
+ double getSpeed(int bangumiId, String pluginName, int episodeNumber) {
+ final key = '${pluginName}_${bangumiId}_$episodeNumber';
+ return _speeds[key] ?? 0.0;
+ }
+
+ /// Format speed to human-readable string
+ String formatSpeed(double bytesPerSec) {
+ if (bytesPerSec < 1024) return '${bytesPerSec.toStringAsFixed(0)} B/s';
+ if (bytesPerSec < 1024 * 1024) {
+ return '${(bytesPerSec / 1024).toStringAsFixed(1)} KB/s';
+ }
+ return '${(bytesPerSec / 1024 / 1024).toStringAsFixed(1)} MB/s';
+ }
+
+ @action
+ void refreshRecords() {
+ final temp = _repository.getAllRecords();
+ records.clear();
+ records.addAll(temp);
+ }
+
+ Plugin? _findPlugin(String pluginName) {
+ final pluginsController = Modular.get<PluginsController>();
+ for (final plugin in pluginsController.pluginList) {
+ if (plugin.name == pluginName) return plugin;
+ }
+ return null;
+ }
+
+ DownloadRecord? getRecord(int bangumiId, String pluginName) {
+ return _repository.getRecordByBangumiId(bangumiId, pluginName);
+ }
+
+ DownloadEpisode? getEpisode(
+ int bangumiId, String pluginName, int episodeNumber) {
+ return _repository.getEpisode(bangumiId, pluginName, episodeNumber);
+ }
+
+ DownloadEpisode? getEpisodeByUrl(
+ int bangumiId, String pluginName, String episodePageUrl) {
+ return _repository.getEpisodeByUrl(bangumiId, pluginName, episodePageUrl);
+ }
+
+ String? getLocalVideoPath(
+ int bangumiId, String pluginName, int episodeNumber) {
+ final episode = _repository.getEpisode(bangumiId, pluginName, episodeNumber);
+ return _downloadManager.getLocalVideoPath(episode);
+ }
+
+ List<DownloadEpisode> getCompletedEpisodes(int bangumiId, String pluginName) {
+ return _repository.getCompletedEpisodes(bangumiId, pluginName);
+ }
+
+ /// 获取缓存的弹幕数据
+ /// 返回 null 表示没有缓存
+ List<Danmaku>? getCachedDanmakus(int bangumiId, String pluginName, int episodeNumber) {
+ final episode = _repository.getEpisode(bangumiId, pluginName, episodeNumber);
+ if (episode == null || episode.danmakuData.isEmpty) {
+ return null;
+ }
+ try {
+ final List<dynamic> jsonList = jsonDecode(episode.danmakuData);
+ return jsonList.map((json) => Danmaku.fromJson(json)).toList();
+ } catch (e) {
+ KazumiLogger().w('DownloadController: failed to parse cached danmaku', error: e);
+ return null;
+ }
+ }
+
+ /// 更新缓存的弹幕数据(用于离线播放时在线获取后保存)
+ Future<void> updateCachedDanmakus(
+ int bangumiId,
+ String pluginName,
+ int episodeNumber,
+ List<Danmaku> danmakus,
+ int danDanBangumiID,
+ ) async {
+ final recordKey = '${pluginName}_$bangumiId';
+ final record = _repository.getRecord(recordKey);
+ if (record == null) return;
+ final episode = record.episodes[episodeNumber];
+ if (episode == null) return;
+
+ try {
+ final danmakuJson = jsonEncode(danmakus.map((d) => d.toJson()).toList());
+ episode.danmakuData = danmakuJson;
+ episode.danDanBangumiID = danDanBangumiID;
+ await _repository.updateEpisode(recordKey, episodeNumber, episode);
+ KazumiLogger().i('DownloadController: updated cached danmakus for episode $episodeNumber');
+ } catch (e) {
+ KazumiLogger().w('DownloadController: failed to update cached danmaku', error: e);
+ }
+ }
+
+ Future<void> startDownload({
+ required int bangumiId,
+ required String bangumiName,
+ required String bangumiCover,
+ required String pluginName,
+ required int episodeNumber,
+ required String episodeName,
+ required int road,
+ required String episodePageUrl,
+ }) async {
+ final recordKey = '${pluginName}_$bangumiId';
+
+ final record = _repository.getRecord(recordKey) ??
+ DownloadRecord(
+ bangumiId,
+ bangumiName,
+ bangumiCover,
+ pluginName,
+ {},
+ DateTime.now(),
+ );
+
+ // 检查是否已有相同 URL 的下载(防止列表重排序后重复下载)
+ if (episodePageUrl.isNotEmpty) {
+ for (final entry in record.episodes.entries) {
+ if (entry.value.episodePageUrl == episodePageUrl) {
+ KazumiLogger().i(
+ 'DownloadController: episode URL already exists at position ${entry.key}, skipping');
+ return;
+ }
+ }
+ }
+
+ final episode = DownloadEpisode(
+ episodeNumber,
+ episodeName,
+ road,
+ DownloadStatus.resolving,
+ 0.0,
+ 0,
+ 0,
+ '',
+ '',
+ '', // networkM3u8Url - will be filled after WebView resolves
+ null,
+ '',
+ 0,
+ episodePageUrl,
+ );
+
+ record.episodes[episodeNumber] = episode;
+ await _repository.putRecord(record);
+ refreshRecords();
+
+ // Queue for WebView resolution
+ _resolveQueue.add(_ResolveRequest(
+ recordKey: recordKey,
+ bangumiId: bangumiId,
+ pluginName: pluginName,
+ episodeNumber: episodeNumber,
+ episodePageUrl: episodePageUrl,
+ ));
+ _processResolveQueue();
+ }
+
+ /// Process the resolve queue one at a time (sequential WebView resolution)
+ Future<void> _processResolveQueue() async {
+ if (_isResolving || _resolveQueue.isEmpty) return;
+ _isResolving = true;
+
+ while (_resolveQueue.isNotEmpty) {
+ final request = _resolveQueue.removeAt(0);
+ await _resolveAndEnqueue(request);
+ }
+
+ _isResolving = false;
+ }
+
+ /// Resolve a single episode's M3U8 URL via headless WebView, then enqueue download
+ Future<void> _resolveAndEnqueue(_ResolveRequest request) async {
+ final plugin = _findPlugin(request.pluginName);
+ if (plugin == null) {
+ _failEpisode(request.recordKey, request.episodeNumber, '找不到插件 ${request.pluginName}');
+ return;
+ }
+
+ final record = _repository.getRecord(request.recordKey);
+ if (record == null) return;
+ final episode = record.episodes[request.episodeNumber];
+ if (episode == null) return;
+
+ // Skip if already cancelled/deleted
+ if (episode.status != DownloadStatus.resolving) return;
+
+ final fullUrl = plugin.buildFullUrl(request.episodePageUrl);
+
+ KazumiLogger().i(
+ 'DownloadController: resolving video URL for episode ${request.episodeNumber} from $fullUrl');
+
+ String? m3u8Url;
+ final provider = WebViewVideoSourceProvider();
+ try {
+ final source = await provider.resolve(
+ fullUrl,
+ useLegacyParser: plugin.useLegacyParser,
+ timeout: const Duration(seconds: 30),
+ );
+ m3u8Url = source.url;
+ } on VideoSourceTimeoutException {
+ KazumiLogger().w('DownloadController: WebView resolution timed out');
+ } on VideoSourceCancelledException {
+ KazumiLogger().i('DownloadController: WebView resolution cancelled');
+ } catch (e) {
+ KazumiLogger().e('DownloadController: WebView resolution failed', error: e);
+ } finally {
+ provider.dispose();
+ }
+
+ if (m3u8Url == null || m3u8Url.isEmpty) {
+ _failEpisode(request.recordKey, request.episodeNumber, '解析视频源超时');
+ return;
+ }
+
+ KazumiLogger().i(
+ 'DownloadController: resolved M3U8 URL for episode ${request.episodeNumber}: $m3u8Url');
+
+ // Update episode with resolved URL
+ final freshRecord = _repository.getRecord(request.recordKey);
+ if (freshRecord == null) return;
+ final freshEpisode = freshRecord.episodes[request.episodeNumber];
+ if (freshEpisode == null) return;
+
+ // Check if user cancelled during resolution
+ if (freshEpisode.status != DownloadStatus.resolving) return;
+
+ freshEpisode.networkM3u8Url = m3u8Url;
+ freshEpisode.status = DownloadStatus.downloading;
+ await _repository.updateEpisode(
+ request.recordKey, request.episodeNumber, freshEpisode);
+ refreshRecords();
+
+ // Now enqueue the actual download
+ final httpHeaders = plugin.buildHttpHeaders();
+ bool adBlockerEnabled = _repository.getForceAdBlocker() || plugin.adBlocker;
+
+ await _downloadManager.enqueue(DownloadRequest(
+ recordKey: request.recordKey,
+ bangumiId: request.bangumiId,
+ pluginName: request.pluginName,
+ episodeNumber: request.episodeNumber,
+ m3u8Url: m3u8Url,
+ httpHeaders: httpHeaders,
+ adBlockerEnabled: adBlockerEnabled,
+ episode: freshEpisode,
+ ));
+
+ // 检查是否启用弹幕缓存(并行获取,不阻塞视频下载)
+ final Box setting = GStorage.setting;
+ final bool downloadDanmaku = setting.get(SettingBoxKey.downloadDanmaku, defaultValue: true);
+ if (downloadDanmaku) {
+ // 异步获取弹幕,不等待完成
+ _fetchAndCacheDanmakuAsync(
+ request.recordKey,
+ request.bangumiId,
+ request.episodeNumber,
+ );
+ }
+ }
+
+ /// 异步获取并缓存弹幕数据(不阻塞视频下载)
+ void _fetchAndCacheDanmakuAsync(String recordKey, int bangumiId, int episodeNumber) {
+ // 使用 Future 在后台执行,不阻塞调用者
+ Future(() async {
+ try {
+ KazumiLogger().i('DownloadController: fetching danmaku for episode $episodeNumber (async)');
+
+ // 获取 DanDan 番剧 ID
+ final danDanBangumiID = await DanmakuRequest.getDanDanBangumiIDByBgmBangumiID(bangumiId);
+ if (danDanBangumiID == 0) {
+ KazumiLogger().w('DownloadController: failed to get DanDan bangumiID for $bangumiId');
+ return;
+ }
+
+ // 获取弹幕列表
+ final danmakus = await DanmakuRequest.getDanDanmaku(danDanBangumiID, episodeNumber);
+ if (danmakus.isEmpty) {
+ KazumiLogger().i('DownloadController: no danmaku found for episode $episodeNumber');
+ return;
+ }
+
+ // 序列化弹幕数据
+ final danmakuJson = jsonEncode(danmakus.map((d) => d.toJson()).toList());
+
+ // 更新存储(重新获取最新的 episode 数据)
+ final record = _repository.getRecord(recordKey);
+ if (record == null) return;
+ final episode = record.episodes[episodeNumber];
+ if (episode == null) return;
+
+ episode.danmakuData = danmakuJson;
+ episode.danDanBangumiID = danDanBangumiID;
+ await _repository.updateEpisode(recordKey, episodeNumber, episode);
+
+ KazumiLogger().i('DownloadController: cached ${danmakus.length} danmakus for episode $episodeNumber');
+ } catch (e) {
+ // 弹幕获取失败不影响下载
+ KazumiLogger().w('DownloadController: failed to fetch danmaku', error: e);
+ }
+ });
+ }
+
+ void _failEpisode(String recordKey, int episodeNumber, String message) {
+ final record = _repository.getRecord(recordKey);
+ if (record == null) return;
+ final episode = record.episodes[episodeNumber];
+ if (episode == null) return;
+ episode.status = DownloadStatus.failed;
+ episode.errorMessage = message;
+ _repository.updateEpisode(recordKey, episodeNumber, episode);
+ refreshRecords();
+ KazumiLogger().w('DownloadController: episode $episodeNumber failed: $message');
+ }
+
+ Future<void> pauseDownload(
+ int bangumiId, String pluginName, int episodeNumber) async {
+ final recordKey = '${pluginName}_$bangumiId';
+ _downloadManager.pause(recordKey, episodeNumber);
+
+ // Also remove from resolve queue if still pending
+ _resolveQueue.removeWhere((r) =>
+ r.recordKey == recordKey && r.episodeNumber == episodeNumber);
+
+ final record = _repository.getRecord(recordKey);
+ if (record != null) {
+ final episode = record.episodes[episodeNumber];
+ if (episode != null) {
+ episode.status = DownloadStatus.paused;
+ await _repository.updateEpisode(recordKey, episodeNumber, episode);
+ refreshRecords();
+ }
+ }
+ }
+
+ Future<void> retryDownload({
+ required int bangumiId,
+ required String pluginName,
+ required int episodeNumber,
+ }) async {
+ final recordKey = '${pluginName}_$bangumiId';
+ final record = _repository.getRecord(recordKey);
+ if (record == null) return;
+ final episode = record.episodes[episodeNumber];
+ if (episode == null) return;
+
+ final plugin = _findPlugin(pluginName);
+ if (plugin == null) {
+ _failEpisode(recordKey, episodeNumber, '找不到插件 $pluginName');
+ return;
+ }
+
+ // If we already have a resolved M3U8 URL, go directly to download
+ if (episode.networkM3u8Url.isNotEmpty) {
+ episode.status = DownloadStatus.downloading;
+ episode.errorMessage = '';
+ episode.progressPercent = 0.0;
+ episode.downloadedSegments = 0;
+ await _repository.updateEpisode(recordKey, episodeNumber, episode);
+ refreshRecords();
+
+ final httpHeaders = plugin.buildHttpHeaders();
+ bool adBlockerEnabled = _repository.getForceAdBlocker() || plugin.adBlocker;
+
+ await _downloadManager.enqueue(DownloadRequest(
+ recordKey: recordKey,
+ bangumiId: bangumiId,
+ pluginName: pluginName,
+ episodeNumber: episodeNumber,
+ m3u8Url: episode.networkM3u8Url,
+ httpHeaders: httpHeaders,
+ adBlockerEnabled: adBlockerEnabled,
+ episode: episode,
+ ));
+ } else {
+ // Need to re-resolve via WebView
+ episode.status = DownloadStatus.resolving;
+ episode.errorMessage = '';
+ episode.progressPercent = 0.0;
+ episode.downloadedSegments = 0;
+ await _repository.updateEpisode(recordKey, episodeNumber, episode);
+ refreshRecords();
+
+ _resolveQueue.add(_ResolveRequest(
+ recordKey: recordKey,
+ bangumiId: bangumiId,
+ pluginName: pluginName,
+ episodeNumber: episodeNumber,
+ episodePageUrl: episode.episodePageUrl,
+ ));
+ _processResolveQueue();
+ }
+ }
+
+ Future<void> cancelDownload(
+ int bangumiId, String pluginName, int episodeNumber) async {
+ final recordKey = '${pluginName}_$bangumiId';
+ _downloadManager.cancel(recordKey, episodeNumber);
+ _resolveQueue.removeWhere((r) =>
+ r.recordKey == recordKey && r.episodeNumber == episodeNumber);
+ await _downloadManager.deleteEpisodeFiles(
+ bangumiId, pluginName, episodeNumber);
+ await _repository.deleteEpisode(recordKey, episodeNumber);
+ refreshRecords();
+ }
+
+ Future<void> deleteRecord(int bangumiId, String pluginName) async {
+ final recordKey = '${pluginName}_$bangumiId';
+ final record = _repository.getRecord(recordKey);
+ if (record != null) {
+ for (final ep in record.episodes.keys) {
+ _downloadManager.cancel(recordKey, ep);
+ }
+ }
+ _resolveQueue.removeWhere((r) => r.recordKey == recordKey);
+ await _downloadManager.deleteRecordFiles(bangumiId, pluginName);
+ await _repository.deleteRecord(recordKey);
+ refreshRecords();
+ }
+
+ Future<void> deleteEpisode(
+ int bangumiId, String pluginName, int episodeNumber) async {
+ final recordKey = '${pluginName}_$bangumiId';
+ _downloadManager.cancel(recordKey, episodeNumber);
+ _resolveQueue.removeWhere((r) =>
+ r.recordKey == recordKey && r.episodeNumber == episodeNumber);
+ await _downloadManager.deleteEpisodeFiles(
+ bangumiId, pluginName, episodeNumber);
+ await _repository.deleteEpisode(recordKey, episodeNumber);
+ refreshRecords();
+ }
+
+ /// Priority download - skip the queue and start immediately
+ Future<void> priorityDownload({
+ required int bangumiId,
+ required String pluginName,
+ required int episodeNumber,
+ }) async {
+ final recordKey = '${pluginName}_$bangumiId';
+ final record = _repository.getRecord(recordKey);
+ if (record == null) return;
+ final episode = record.episodes[episodeNumber];
+ if (episode == null) return;
+
+ final plugin = _findPlugin(pluginName);
+ if (plugin == null) {
+ _failEpisode(recordKey, episodeNumber, '找不到插件 $pluginName');
+ return;
+ }
+
+ // Remove from resolve queue if waiting
+ _resolveQueue.removeWhere((r) =>
+ r.recordKey == recordKey && r.episodeNumber == episodeNumber);
+
+ if (episode.networkM3u8Url.isNotEmpty) {
+ episode.status = DownloadStatus.downloading;
+ episode.errorMessage = '';
+ await _repository.updateEpisode(recordKey, episodeNumber, episode);
+ refreshRecords();
+
+ final httpHeaders = plugin.buildHttpHeaders();
+ bool adBlockerEnabled = _repository.getForceAdBlocker() || plugin.adBlocker;
+
+ await _downloadManager.enqueuePriority(DownloadRequest(
+ recordKey: recordKey,
+ bangumiId: bangumiId,
+ pluginName: pluginName,
+ episodeNumber: episodeNumber,
+ m3u8Url: episode.networkM3u8Url,
+ httpHeaders: httpHeaders,
+ adBlockerEnabled: adBlockerEnabled,
+ episode: episode,
+ ));
+ } else {
+ // Need to resolve first - add to front of resolve queue
+ episode.status = DownloadStatus.resolving;
+ episode.errorMessage = '';
+ await _repository.updateEpisode(recordKey, episodeNumber, episode);
+ refreshRecords();
+
+ _resolveQueue.insert(0, _ResolveRequest(
+ recordKey: recordKey,
+ bangumiId: bangumiId,
+ pluginName: pluginName,
+ episodeNumber: episodeNumber,
+ episodePageUrl: episode.episodePageUrl,
+ ));
+ _processResolveQueue();
+ }
+ }
+
+ /// Resume all incomplete downloads for a record
+ Future<void> resumeAllDownloads(int bangumiId, String pluginName) async {
+ final recordKey = '${pluginName}_$bangumiId';
+ final record = _repository.getRecord(recordKey);
+ if (record == null) return;
+
+ final incompleteEpisodes = record.episodes.entries
+ .where((e) =>
+ e.value.status == DownloadStatus.paused ||
+ e.value.status == DownloadStatus.failed ||
+ e.value.status == DownloadStatus.pending)
+ .toList()
+ ..sort((a, b) => a.key.compareTo(b.key));
+
+ for (final entry in incompleteEpisodes) {
+ await retryDownload(
+ bangumiId: bangumiId,
+ pluginName: pluginName,
+ episodeNumber: entry.key,
+ );
+ }
+
+ if (incompleteEpisodes.isNotEmpty) {
+ KazumiLogger().i(
+ 'DownloadController: resumed ${incompleteEpisodes.length} downloads for $recordKey',
+ );
+ }
+ }
+
+ int completedCount(DownloadRecord record) {
+ return record.episodes.values
+ .where((e) => e.status == DownloadStatus.completed)
+ .length;
+ }
+
+ String formatBytes(int bytes) {
+ if (bytes < 1024) return '$bytes B';
+ if (bytes < 1024 * 1024) return '${(bytes / 1024).toStringAsFixed(1)} KB';
+ if (bytes < 1024 * 1024 * 1024) {
+ return '${(bytes / 1024 / 1024).toStringAsFixed(1)} MB';
+ }
+ return '${(bytes / 1024 / 1024 / 1024).toStringAsFixed(1)} GB';
+ }
+}
+
+class _ResolveRequest {
+ final String recordKey;
+ final int bangumiId;
+ final String pluginName;
+ final int episodeNumber;
+ final String episodePageUrl;
+
+ _ResolveRequest({
+ required this.recordKey,
+ required this.bangumiId,
+ required this.pluginName,
+ required this.episodeNumber,
+ required this.episodePageUrl,
+ });
+}
diff --git a/lib/pages/download/download_controller.g.dart b/lib/pages/download/download_controller.g.dart
new file mode 100644
index 00000000..0fed7f93
--- /dev/null
+++ b/lib/pages/download/download_controller.g.dart
@@ -0,0 +1,48 @@
+// GENERATED CODE - DO NOT MODIFY BY HAND
+
+part of 'download_controller.dart';
+
+// **************************************************************************
+// StoreGenerator
+// **************************************************************************
+
+// ignore_for_file: non_constant_identifier_names, unnecessary_brace_in_string_interps, unnecessary_lambdas, prefer_expression_function_bodies, lines_longer_than_80_chars, avoid_as, avoid_annotating_with_dynamic, no_leading_underscores_for_local_identifiers
+
+mixin _$DownloadController on _DownloadController, Store {
+ late final _$recordsAtom =
+ Atom(name: '_DownloadController.records', context: context);
+
+ @override
+ ObservableList<DownloadRecord> get records {
+ _$recordsAtom.reportRead();
+ return super.records;
+ }
+
+ @override
+ set records(ObservableList<DownloadRecord> value) {
+ _$recordsAtom.reportWrite(value, super.records, () {
+ super.records = value;
+ });
+ }
+
+ late final _$_DownloadControllerActionController =
+ ActionController(name: '_DownloadController', context: context);
+
+ @override
+ void refreshRecords() {
+ final _$actionInfo = _$_DownloadControllerActionController.startAction(
+ name: '_DownloadController.refreshRecords');
+ try {
+ return super.refreshRecords();
+ } finally {
+ _$_DownloadControllerActionController.endAction(_$actionInfo);
+ }
+ }
+
+ @override
+ String toString() {
+ return '''
+records: ${records}
+ ''';
+ }
+}
diff --git a/lib/pages/download/download_episode_sheet.dart b/lib/pages/download/download_episode_sheet.dart
new file mode 100644
index 00000000..1035fde4
--- /dev/null
+++ b/lib/pages/download/download_episode_sheet.dart
@@ -0,0 +1,263 @@
+import 'package:flutter/material.dart';
+import 'package:flutter_modular/flutter_modular.dart';
+import 'package:kazumi/bean/dialog/dialog_helper.dart';
+import 'package:kazumi/modules/download/download_module.dart';
+import 'package:kazumi/modules/roads/road_module.dart';
+import 'package:kazumi/pages/download/download_controller.dart';
+import 'package:kazumi/pages/video/video_controller.dart';
+
+class DownloadEpisodeSheet extends StatefulWidget {
+ final int road;
+
+ const DownloadEpisodeSheet({super.key, required this.road});
+
+ @override
+ State<DownloadEpisodeSheet> createState() => _DownloadEpisodeSheetState();
+}
+
+class _DownloadEpisodeSheetState extends State<DownloadEpisodeSheet> {
+ final VideoPageController videoPageController =
+ Modular.get<VideoPageController>();
+ final DownloadController downloadController =
+ Modular.get<DownloadController>();
+
+ final Set<int> _selectedEpisodes = {};
+
+ Road get currentRoadData => videoPageController.roadList[widget.road];
+ int get episodeCount => currentRoadData.data.length;
+
+ @override
+ Widget build(BuildContext context) {
+ final record = downloadController.getRecord(
+ videoPageController.bangumiItem.id,
+ videoPageController.currentPlugin.name,
+ );
+ final downloadedUrls = <String>{};
+ if (record != null) {
+ for (final entry in record.episodes.entries) {
+ if (entry.value.status == DownloadStatus.completed ||
+ entry.value.status == DownloadStatus.downloading ||
+ entry.value.status == DownloadStatus.pending) {
+ if (entry.value.episodePageUrl.isNotEmpty) {
+ downloadedUrls.add(entry.value.episodePageUrl);
+ }
+ }
+ }
+ }
+
+ return DraggableScrollableSheet(
+ initialChildSize: 0.6,
+ minChildSize: 0.3,
+ maxChildSize: 0.9,
+ expand: false,
+ builder: (context, scrollController) {
+ return Column(
+ children: [
+ // Header
+ Padding(
+ padding: const EdgeInsets.fromLTRB(16, 16, 16, 8),
+ child: Row(
+ mainAxisAlignment: MainAxisAlignment.spaceBetween,
+ children: [
+ const Text(
+ '选择要下载的集数',
+ style: TextStyle(fontSize: 16, fontWeight: FontWeight.bold),
+ ),
+ Text(
+ '已选 ${_selectedEpisodes.length} 集',
+ style: TextStyle(
+ fontSize: 14,
+ color: Theme.of(context).colorScheme.primary,
+ ),
+ ),
+ ],
+ ),
+ ),
+ // Select all / deselect all
+ Padding(
+ padding: const EdgeInsets.symmetric(horizontal: 16),
+ child: Row(
+ children: [
+ TextButton(
+ onPressed: () {
+ setState(() {
+ _selectedEpisodes.clear();
+ for (int i = 1; i <= episodeCount; i++) {
+ final url = currentRoadData.data[i - 1];
+ if (!downloadedUrls.contains(url)) {
+ _selectedEpisodes.add(i);
+ }
+ }
+ });
+ },
+ child: const Text('全选'),
+ ),
+ TextButton(
+ onPressed: () {
+ setState(() {
+ _selectedEpisodes.clear();
+ });
+ },
+ child: const Text('取消全选'),
+ ),
+ ],
+ ),
+ ),
+ // Grid
+ Expanded(
+ child: GridView.builder(
+ controller: scrollController,
+ padding: const EdgeInsets.symmetric(horizontal: 12),
+ gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
+ crossAxisCount: 3,
+ crossAxisSpacing: 8,
+ mainAxisSpacing: 8,
+ mainAxisExtent: 56,
+ ),
+ itemCount: episodeCount,
+ itemBuilder: (context, index) {
+ final episodeNumber = index + 1;
+ final episodeUrl = currentRoadData.data[index];
+ final isDownloaded = downloadedUrls.contains(episodeUrl);
+ final isSelected =
+ _selectedEpisodes.contains(episodeNumber);
+ final identifier = currentRoadData.identifier[index];
+
+ return Material(
+ color: isDownloaded
+ ? Theme.of(context)
+ .colorScheme
+ .surfaceContainerHighest
+ .withValues(alpha: 0.5)
+ : isSelected
+ ? Theme.of(context)
+ .colorScheme
+ .primaryContainer
+ : Theme.of(context)
+ .colorScheme
+ .onInverseSurface,
+ borderRadius: BorderRadius.circular(8),
+ clipBehavior: Clip.hardEdge,
+ child: InkWell(
+ onTap: isDownloaded
+ ? null
+ : () {
+ setState(() {
+ if (isSelected) {
+ _selectedEpisodes.remove(episodeNumber);
+ } else {
+ _selectedEpisodes.add(episodeNumber);
+ }
+ });
+ },
+ child: Stack(
+ children: [
+ Center(
+ child: Padding(
+ padding: const EdgeInsets.symmetric(
+ horizontal: 8),
+ child: Text(
+ identifier,
+ maxLines: 2,
+ overflow: TextOverflow.ellipsis,
+ textAlign: TextAlign.center,
+ style: TextStyle(
+ fontSize: 13,
+ color: isDownloaded
+ ? Theme.of(context)
+ .colorScheme
+ .outline
+ : null,
+ ),
+ ),
+ ),
+ ),
+ if (isDownloaded)
+ Positioned(
+ top: 4,
+ right: 4,
+ child: Icon(
+ Icons.check_circle,
+ size: 14,
+ color:
+ Theme.of(context).colorScheme.outline,
+ ),
+ ),
+ if (isSelected)
+ Positioned(
+ top: 4,
+ right: 4,
+ child: Icon(
+ Icons.check_circle,
+ size: 14,
+ color: Theme.of(context)
+ .colorScheme
+ .primary,
+ ),
+ ),
+ ],
+ ),
+ ),
+ );
+ },
+ ),
+ ),
+ // Action buttons
+ Padding(
+ padding: const EdgeInsets.fromLTRB(16, 8, 16, 16),
+ child: SafeArea(
+ child: Row(
+ mainAxisAlignment: MainAxisAlignment.end,
+ children: [
+ TextButton(
+ onPressed: () => Navigator.pop(context),
+ child: const Text('取消'),
+ ),
+ const SizedBox(width: 12),
+ FilledButton(
+ onPressed: _selectedEpisodes.isEmpty
+ ? null
+ : () => _startBatchDownload(context),
+ child: Text('开始下载(${_selectedEpisodes.length})'),
+ ),
+ ],
+ ),
+ ),
+ ),
+ ],
+ );
+ },
+ );
+ }
+
+ void _startBatchDownload(BuildContext context) {
+ Navigator.pop(context);
+
+ final plugin = videoPageController.currentPlugin;
+ final bangumiItem = videoPageController.bangumiItem;
+
+ final sortedEpisodes = _selectedEpisodes.toList()..sort();
+
+ for (final episodeNumber in sortedEpisodes) {
+ final episodePageUrl = currentRoadData.data[episodeNumber - 1];
+ final identifier = currentRoadData.identifier[episodeNumber - 1];
+
+ downloadController.startDownload(
+ bangumiId: bangumiItem.id,
+ bangumiName: bangumiItem.nameCn.isNotEmpty
+ ? bangumiItem.nameCn
+ : bangumiItem.name,
+ bangumiCover: bangumiItem.images['large'] ?? '',
+ pluginName: plugin.name,
+ episodeNumber: episodeNumber,
+ episodeName: identifier,
+ road: widget.road,
+ episodePageUrl: episodePageUrl,
+ );
+ }
+
+ KazumiDialog.showToast(
+ message: '已添加 ${sortedEpisodes.length} 集到下载队列,可在下载管理中查看',
+ );
+ }
+}
diff --git a/lib/pages/download/download_page.dart b/lib/pages/download/download_page.dart
new file mode 100644
index 00000000..31e65e51
--- /dev/null
+++ b/lib/pages/download/download_page.dart
@@ -0,0 +1,420 @@
+import 'package:flutter/material.dart';
+import 'package:flutter_mobx/flutter_mobx.dart';
+import 'package:flutter_modular/flutter_modular.dart';
+import 'package:kazumi/bean/appbar/sys_app_bar.dart';
+import 'package:kazumi/bean/dialog/dialog_helper.dart';
+import 'package:kazumi/modules/download/download_module.dart';
+import 'package:kazumi/modules/bangumi/bangumi_item.dart';
+import 'package:kazumi/pages/download/download_controller.dart';
+import 'package:kazumi/pages/video/video_controller.dart';
+
+class DownloadPage extends StatefulWidget {
+ const DownloadPage({super.key});
+
+ @override
+ State<DownloadPage> createState() => _DownloadPageState();
+}
+
+class _DownloadPageState extends State<DownloadPage> {
+ final DownloadController downloadController =
+ Modular.get<DownloadController>();
+
+ @override
+ void initState() {
+ super.initState();
+ downloadController.refreshRecords();
+ }
+
+ @override
+ Widget build(BuildContext context) {
+ return Scaffold(
+ appBar: const SysAppBar(title: Text('下载管理')),
+ body: Observer(builder: (context) {
+ if (downloadController.records.isEmpty) {
+ return const Center(
+ child: Text('暂无离线下载'),
+ );
+ }
+ return ListView.builder(
+ padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 8),
+ itemCount: downloadController.records.length,
+ itemBuilder: (context, index) {
+ final record = downloadController.records[index];
+ return _buildRecordCard(record);
+ },
+ );
+ }),
+ );
+ }
+
+ Widget _buildRecordCard(DownloadRecord record) {
+ final episodes = record.episodes.values.toList()
+ ..sort((a, b) => a.episodeNumber.compareTo(b.episodeNumber));
+ final completedCount = downloadController.completedCount(record);
+
+ return Card(
+ margin: const EdgeInsets.only(bottom: 12),
+ clipBehavior: Clip.antiAlias,
+ child: Column(
+ crossAxisAlignment: CrossAxisAlignment.start,
+ children: [
+ // Header
+ ListTile(
+ leading: ClipRRect(
+ borderRadius: BorderRadius.circular(4),
+ child: Image.network(
+ record.bangumiCover,
+ width: 48,
+ height: 64,
+ fit: BoxFit.cover,
+ errorBuilder: (_, __, ___) => Container(
+ width: 48,
+ height: 64,
+ color: Theme.of(context).colorScheme.surfaceContainerHighest,
+ child: const Icon(Icons.movie_outlined),
+ ),
+ ),
+ ),
+ title: Text(
+ record.bangumiName,
+ maxLines: 1,
+ overflow: TextOverflow.ellipsis,
+ ),
+ subtitle: Text(
+ '来源: ${record.pluginName} · $completedCount/${episodes.length} 已完成',
+ style: TextStyle(
+ fontSize: 12,
+ color: Theme.of(context).colorScheme.outline,
+ ),
+ ),
+ trailing: PopupMenuButton<String>(
+ onSelected: (value) {
+ if (value == 'delete') {
+ _confirmDeleteRecord(record);
+ } else if (value == 'resume_all') {
+ downloadController.resumeAllDownloads(
+ record.bangumiId,
+ record.pluginName,
+ );
+ KazumiDialog.showToast(message: '已开始恢复下载');
+ }
+ },
+ itemBuilder: (context) => [
+ const PopupMenuItem(
+ value: 'resume_all',
+ child: Text('开始全部'),
+ ),
+ const PopupMenuItem(
+ value: 'delete',
+ child: Text('删除全部'),
+ ),
+ ],
+ ),
+ ),
+ // Episode list
+ ...episodes.map((ep) => _buildEpisodeTile(record, ep)),
+ ],
+ ),
+ );
+ }
+
+ Widget _buildEpisodeTile(DownloadRecord record, DownloadEpisode episode) {
+ final statusIcon = _getStatusIcon(episode);
+ final statusText = _getStatusText(record, episode);
+
+ return Padding(
+ padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 4),
+ child: Row(
+ children: [
+ statusIcon,
+ const SizedBox(width: 8),
+ Expanded(
+ child: Column(
+ crossAxisAlignment: CrossAxisAlignment.start,
+ children: [
+ Text(
+ episode.episodeName.isNotEmpty
+ ? episode.episodeName
+ : '第${episode.episodeNumber}集',
+ maxLines: 1,
+ overflow: TextOverflow.ellipsis,
+ style: const TextStyle(fontSize: 14),
+ ),
+ const SizedBox(height: 2),
+ Text(
+ statusText,
+ style: TextStyle(
+ fontSize: 12,
+ color: episode.status == DownloadStatus.failed
+ ? Theme.of(context).colorScheme.error
+ : Theme.of(context).colorScheme.outline,
+ ),
+ ),
+ ],
+ ),
+ ),
+ if (episode.status == DownloadStatus.downloading) ...[
+ SizedBox(
+ width: 60,
+ child: LinearProgressIndicator(
+ value: episode.progressPercent,
+ minHeight: 3,
+ ),
+ ),
+ const SizedBox(width: 8),
+ ],
+ ..._getActionButtons(record, episode),
+ ],
+ ),
+ );
+ }
+
+ Widget _getStatusIcon(DownloadEpisode episode) {
+ switch (episode.status) {
+ case DownloadStatus.completed:
+ return Icon(Icons.offline_pin,
+ size: 20, color: Theme.of(context).colorScheme.primary);
+ case DownloadStatus.downloading:
+ return SizedBox(
+ width: 20,
+ height: 20,
+ child: CircularProgressIndicator(
+ value: episode.progressPercent,
+ strokeWidth: 2,
+ ),
+ );
+ case DownloadStatus.failed:
+ return Icon(Icons.error_outline,
+ size: 20, color: Theme.of(context).colorScheme.error);
+ case DownloadStatus.paused:
+ return Icon(Icons.pause_circle_outline,
+ size: 20, color: Theme.of(context).colorScheme.outline);
+ case DownloadStatus.pending:
+ return Icon(Icons.hourglass_empty,
+ size: 20, color: Theme.of(context).colorScheme.outline);
+ case DownloadStatus.resolving:
+ return const SizedBox(
+ width: 20,
+ height: 20,
+ child: CircularProgressIndicator(strokeWidth: 2),
+ );
+ default:
+ return const SizedBox(width: 20, height: 20);
+ }
+ }
+
+ String _getStatusText(DownloadRecord record, DownloadEpisode episode) {
+ switch (episode.status) {
+ case DownloadStatus.completed:
+ return '已完成 ${downloadController.formatBytes(episode.totalBytes)}';
+ case DownloadStatus.downloading:
+ final speed = downloadController.getSpeed(
+ record.bangumiId,
+ record.pluginName,
+ episode.episodeNumber,
+ );
+ final speedText = speed > 0 ? ' · ${downloadController.formatSpeed(speed)}' : '';
+ return '${(episode.progressPercent * 100).toStringAsFixed(0)}% '
+ '${episode.downloadedSegments}/${episode.totalSegments}$speedText';
+ case DownloadStatus.failed:
+ return episode.errorMessage.isNotEmpty ? episode.errorMessage : '下载失败';
+ case DownloadStatus.paused:
+ return '已暂停 ${(episode.progressPercent * 100).toStringAsFixed(0)}%';
+ case DownloadStatus.pending:
+ return '等待中';
+ case DownloadStatus.resolving:
+ return '解析视频源中';
+ default:
+ return '';
+ }
+ }
+
+ List<Widget> _getActionButtons(
+ DownloadRecord record, DownloadEpisode episode) {
+ final buttons = <Widget>[];
+
+ switch (episode.status) {
+ case DownloadStatus.completed:
+ buttons.add(IconButton(
+ icon: Icon(Icons.play_circle_outline,
+ size: 20, color: Theme.of(context).colorScheme.primary),
+ onPressed: () => _playEpisode(record, episode),
+ tooltip: '播放',
+ visualDensity: VisualDensity.compact,
+ ));
+ break;
+ case DownloadStatus.downloading:
+ buttons.add(IconButton(
+ icon: const Icon(Icons.pause, size: 20),
+ onPressed: () => downloadController.pauseDownload(
+ record.bangumiId,
+ record.pluginName,
+ episode.episodeNumber,
+ ),
+ tooltip: '暂停',
+ visualDensity: VisualDensity.compact,
+ ));
+ break;
+ case DownloadStatus.paused:
+ buttons.add(IconButton(
+ icon: const Icon(Icons.play_arrow, size: 20),
+ onPressed: () => downloadController.retryDownload(
+ bangumiId: record.bangumiId,
+ pluginName: record.pluginName,
+ episodeNumber: episode.episodeNumber,
+ ),
+ tooltip: '继续',
+ visualDensity: VisualDensity.compact,
+ ));
+ break;
+ case DownloadStatus.failed:
+ buttons.add(IconButton(
+ icon: const Icon(Icons.refresh, size: 20),
+ onPressed: () => downloadController.retryDownload(
+ bangumiId: record.bangumiId,
+ pluginName: record.pluginName,
+ episodeNumber: episode.episodeNumber,
+ ),
+ tooltip: '重试',
+ visualDensity: VisualDensity.compact,
+ ));
+ break;
+ case DownloadStatus.pending:
+ buttons.add(IconButton(
+ icon: Icon(Icons.priority_high,
+ size: 20, color: Theme.of(context).colorScheme.primary),
+ onPressed: () {
+ downloadController.priorityDownload(
+ bangumiId: record.bangumiId,
+ pluginName: record.pluginName,
+ episodeNumber: episode.episodeNumber,
+ );
+ KazumiDialog.showToast(message: '已插队优先下载');
+ },
+ tooltip: '优先下载',
+ visualDensity: VisualDensity.compact,
+ ));
+ break;
+ default:
+ break;
+ }
+
+ buttons.add(IconButton(
+ icon: const Icon(Icons.delete_outline, size: 20),
+ onPressed: () => _confirmDeleteEpisode(record, episode),
+ tooltip: '删除',
+ visualDensity: VisualDensity.compact,
+ ));
+
+ return buttons;
+ }
+
+ void _playEpisode(DownloadRecord record, DownloadEpisode episode) {
+ final localPath = downloadController.getLocalVideoPath(
+ record.bangumiId,
+ record.pluginName,
+ episode.episodeNumber,
+ );
+ if (localPath == null) {
+ KazumiDialog.showToast(message: '本地文件不存在');
+ return;
+ }
+
+ // 构建 BangumiItem
+ final bangumiItem = BangumiItem(
+ id: record.bangumiId,
+ type: 2,
+ name: record.bangumiName,
+ nameCn: record.bangumiName,
+ summary: '',
+ airDate: '',
+ airWeekday: 0,
+ rank: 0,
+ images: {'large': record.bangumiCover},
+ tags: [],
+ alias: [],
+ ratingScore: 0.0,
+ votes: 0,
+ votesCount: [],
+ info: '',
+ );
+
+ // 获取所有已下载集数(通过 Controller 委托给 Repository 层)
+ final downloadedEpisodes = downloadController.getCompletedEpisodes(
+ record.bangumiId,
+ record.pluginName,
+ );
+
+ // 初始化离线模式
+ final videoPageController = Modular.get<VideoPageController>();
+ videoPageController.initForOfflinePlayback(
+ bangumiItem: bangumiItem,
+ pluginName: record.pluginName,
+ episodeNumber: episode.episodeNumber,
+ episodeName: episode.episodeName,
+ road: episode.road,
+ videoPath: localPath,
+ downloadedEpisodes: downloadedEpisodes,
+ );
+
+ // 导航到 VideoPage
+ Modular.to.pushNamed('/video/');
+ }
+
+ void _confirmDeleteEpisode(DownloadRecord record, DownloadEpisode episode) {
+ KazumiDialog.show(
+ builder: (context) => AlertDialog(
+ title: const Text('删除下载'),
+ content: Text('确定要删除「${episode.episodeName.isNotEmpty ? episode.episodeName : '第${episode.episodeNumber}集'}」的下载文件吗?'),
+ actions: [
+ TextButton(
+ onPressed: () => KazumiDialog.dismiss(),
+ child: Text(
+ '取消',
+ style: TextStyle(color: Theme.of(context).colorScheme.outline),
+ ),
+ ),
+ TextButton(
+ onPressed: () {
+ downloadController.deleteEpisode(
+ record.bangumiId,
+ record.pluginName,
+ episode.episodeNumber,
+ );
+ KazumiDialog.dismiss();
+ },
+ child: const Text('删除'),
+ ),
+ ],
+ ),
+ );
+ }
+
+ void _confirmDeleteRecord(DownloadRecord record) {
+ KazumiDialog.show(
+ builder: (context) => AlertDialog(
+ title: const Text('删除全部下载'),
+ content: Text('确定要删除「${record.bangumiName}」的所有下载文件吗?'),
+ actions: [
+ TextButton(
+ onPressed: () => KazumiDialog.dismiss(),
+ child: Text(
+ '取消',
+ style: TextStyle(color: Theme.of(context).colorScheme.outline),
+ ),
+ ),
+ TextButton(
+ onPressed: () {
+ downloadController.deleteRecord(
+ record.bangumiId,
+ record.pluginName,
+ );
+ KazumiDialog.dismiss();
+ },
+ child: const Text('删除'),
+ ),
+ ],
+ ),
+ );
+ }
+}
diff --git a/lib/pages/download/download_page_module.dart b/lib/pages/download/download_page_module.dart
new file mode 100644
index 00000000..9a8ea6cd
--- /dev/null
+++ b/lib/pages/download/download_page_module.dart
@@ -0,0 +1,9 @@
+import 'package:flutter_modular/flutter_modular.dart';
+import 'package:kazumi/pages/download/download_page.dart';
+
+class DownloadModule extends Module {
+ @override
+ void routes(r) {
+ r.child("/", child: (_) => const DownloadPage());
+ }
+}
diff --git a/lib/pages/index_module.dart b/lib/pages/index_module.dart
index ce6a511a..0a00015c 100644
--- a/lib/pages/index_module.dart
+++ b/lib/pages/index_module.dart
@@ -19,6 +19,9 @@ import 'package:kazumi/repositories/collect_repository.dart';
import 'package:kazumi/repositories/search_history_repository.dart';
import 'package:kazumi/repositories/collect_crud_repository.dart';
import 'package:kazumi/repositories/history_repository.dart';
+import 'package:kazumi/repositories/download_repository.dart';
+import 'package:kazumi/utils/download_manager.dart';
+import 'package:kazumi/pages/download/download_controller.dart';
class IndexModule extends Module {
@override
@@ -31,6 +34,8 @@ class IndexModule extends Module {
i.addSingleton<ISearchHistoryRepository>(SearchHistoryRepository.new);
i.addSingleton<ICollectCrudRepository>(CollectCrudRepository.new);
i.addSingleton<IHistoryRepository>(HistoryRepository.new);
+ i.addSingleton<IDownloadRepository>(DownloadRepository.new);
+ i.addSingleton<IDownloadManager>(DownloadManager.new);
// Controller层
i.addSingleton(PopularController.new);
@@ -41,6 +46,7 @@ class IndexModule extends Module {
i.addSingleton(HistoryController.new);
i.addSingleton(MyController.new);
i.addSingleton(ShadersController.new);
+ i.addSingleton(DownloadController.new);
}
@override
diff --git a/lib/pages/init_page.dart b/lib/pages/init_page.dart
index 3c2f7ffb..483c07f4 100644
--- a/lib/pages/init_page.dart
+++ b/lib/pages/init_page.dart
@@ -14,6 +14,7 @@ import 'package:kazumi/utils/utils.dart';
import 'package:provider/provider.dart';
import 'package:kazumi/bean/settings/theme_provider.dart';
import 'package:kazumi/shaders/shaders_controller.dart';
+import 'package:kazumi/pages/download/download_controller.dart';
class InitPage extends StatefulWidget {
const InitPage({super.key});
@@ -27,6 +28,7 @@ class _InitPageState extends State<InitPage> {
final CollectController collectController = Modular.get<CollectController>();
final ShadersController shadersController = Modular.get<ShadersController>();
final MyController myController = Modular.get<MyController>();
+ final DownloadController downloadController = Modular.get<DownloadController>();
Box setting = GStorage.setting;
late final ThemeProvider themeProvider;
@@ -42,6 +44,12 @@ class _InitPageState extends State<InitPage> {
_loadShaders();
_loadDanmakuShield();
_webDavInit();
+ try {
+ downloadController.init();
+ } catch (e) {
+ KazumiLogger().e('InitPage: downloadController.init() failed', error: e);
+ // 下载记录初始化失败不应阻止应用启动
+ }
await _checkRunningOnX11();
await _pluginInit();
diff --git a/lib/pages/my/my_page.dart b/lib/pages/my/my_page.dart
index 63c2f41f..e16cf4f9 100644
--- a/lib/pages/my/my_page.dart
+++ b/lib/pages/my/my_page.dart
@@ -59,6 +59,22 @@ class _MyPageState extends State<MyPage> {
title: Text('历史记录', style: TextStyle(fontFamily: fontFamily)),
description: Text('查看播放历史记录', style: TextStyle(fontFamily: fontFamily)),
),
+ SettingsTile.navigation(
+ onPressed: (_) {
+ Modular.to.pushNamed('/settings/download/');
+ },
+ leading: const Icon(Icons.download_rounded),
+ title: Text('下载管理', style: TextStyle(fontFamily: fontFamily)),
+ description: Text('查看和管理离线下载', style: TextStyle(fontFamily: fontFamily)),
+ ),
+ SettingsTile.navigation(
+ onPressed: (_) {
+ Modular.to.pushNamed('/settings/download-settings');
+ },
+ leading: const Icon(Icons.settings_rounded),
+ title: Text('下载设置', style: TextStyle(fontFamily: fontFamily)),
+ description: Text('配置下载并发数等参数', style: TextStyle(fontFamily: fontFamily)),
+ ),
SettingsTile.navigation(
onPressed: (_) {
Modular.to.pushNamed('/settings/plugin/');
diff --git a/lib/pages/player/player_controller.dart b/lib/pages/player/player_controller.dart
index ef22e69e..7670fa47 100644
--- a/lib/pages/player/player_controller.dart
+++ b/lib/pages/player/player_controller.dart
@@ -22,6 +22,7 @@ import 'package:kazumi/utils/syncplay.dart';
import 'package:kazumi/utils/syncplay_endpoint.dart';
import 'package:kazumi/utils/external_player.dart';
import 'package:url_launcher/url_launcher_string.dart';
+import 'package:kazumi/pages/download/download_controller.dart';
part 'player_controller.g.dart';
@@ -190,8 +191,37 @@ abstract class _PlayerController with Store {
StreamSubscription<Track>? playerTracksSubscription;
StreamSubscription<double?>? playerAudioBitrateSubscription;
+ bool _isLocalPlayback = false;
+
Future<void> init(String url, {int offset = 0}) async {
- videoUrl = url;
+ // Check for local cached version
+ _isLocalPlayback = false;
+
+ // 离线模式下直接使用传入的本地路径
+ if (videoPageController.isOfflineMode) {
+ videoUrl = url;
+ _isLocalPlayback = true;
+ KazumiLogger().i('PlayerController: offline mode, using local path $url');
+ } else {
+ try {
+ final downloadController = Modular.get<DownloadController>();
+ final localPath = downloadController.getLocalVideoPath(
+ videoPageController.bangumiItem.id,
+ videoPageController.currentPlugin.name,
+ videoPageController.currentEpisode,
+ );
+ if (localPath != null) {
+ videoUrl = localPath;
+ _isLocalPlayback = true;
+ KazumiLogger().i('PlayerController: using local cache $localPath');
+ } else {
+ videoUrl = url;
+ }
+ } catch (_) {
+ videoUrl = url;
+ }
+ }
+
playing = false;
loading = true;
isBuffering = true;
@@ -223,8 +253,8 @@ abstract class _PlayerController with Store {
if (episodeFromTitle == 0) {
episodeFromTitle = videoPageController.currentEpisode;
}
- getDanDanmakuByBgmBangumiID(
- videoPageController.bangumiItem.id, episodeFromTitle);
+ // 加载弹幕 (离线模式优先从缓存加载,无缓存时尝试在线获取)
+ _loadDanmaku(episodeFromTitle);
mediaPlayer ??= await createVideoController(offset: offset);
if (Utils.isDesktop()) {
@@ -318,17 +348,25 @@ abstract class _PlayerController with Store {
setting.get(SettingBoxKey.playerDebugMode, defaultValue: false);
bool forceAdBlocker =
setting.get(SettingBoxKey.forceAdBlocker, defaultValue: false);
- bool adBlockerEnabled = forceAdBlocker || videoPageController.currentPlugin.adBlocker;
- if (videoPageController.currentPlugin.userAgent == '') {
- userAgent = Utils.getRandomUA();
- } else {
- userAgent = videoPageController.currentPlugin.userAgent;
+ // 离线模式下不需要 adBlocker 和 HTTP 头
+ bool adBlockerEnabled = _isLocalPlayback
+ ? false
+ : (forceAdBlocker || videoPageController.currentPlugin.adBlocker);
+ String referer = '';
+ if (!_isLocalPlayback) {
+ if (videoPageController.currentPlugin.userAgent == '') {
+ userAgent = Utils.getRandomUA();
+ } else {
+ userAgent = videoPageController.currentPlugin.userAgent;
+ }
+ referer = videoPageController.currentPlugin.referer;
}
- String referer = videoPageController.currentPlugin.referer;
- var httpHeaders = {
- 'user-agent': userAgent,
- if (referer.isNotEmpty) 'referer': referer,
- };
+ var httpHeaders = _isLocalPlayback
+ ? <String, String>{}
+ : {
+ 'user-agent': userAgent,
+ if (referer.isNotEmpty) 'referer': referer,
+ };
mediaPlayer = Player(
configuration: PlayerConfiguration(
@@ -568,6 +606,81 @@ abstract class _PlayerController with Store {
setting.put(SettingBoxKey.arrowKeySkipTime, time);
}
+ /// 加载弹幕 (离线模式优先从缓存加载,无缓存时尝试在线获取)
+ Future<void> _loadDanmaku(int episode) async {
+ if (videoPageController.isOfflineMode) {
+ // 离线模式:先从缓存加载,无缓存时尝试在线获取
+ await _loadCachedDanmaku(episode);
+ } else {
+ // 在线模式:从网络获取弹幕
+ getDanDanmakuByBgmBangumiID(
+ videoPageController.bangumiItem.id, episode);
+ }
+ }
+
+ /// 从下载缓存加载弹幕,如果缓存为空且有网络则尝试在线获取
+ Future<void> _loadCachedDanmaku(int episode) async {
+ if (danmakuLoading) {
+ KazumiLogger().i('PlayerController: danmaku is loading, ignore duplicate request');
+ return;
+ }
+
+ KazumiLogger().i('PlayerController: attempting to load cached danmaku for episode $episode');
+ danmakuLoading = true;
+ try {
+ danDanmakus.clear();
+ final downloadController = Modular.get<DownloadController>();
+ final cachedDanmakus = downloadController.getCachedDanmakus(
+ videoPageController.bangumiItem.id,
+ videoPageController.offlinePluginName,
+ videoPageController.actualEpisodeNumber,
+ );
+
+ if (cachedDanmakus != null && cachedDanmakus.isNotEmpty) {
+ addDanmakus(cachedDanmakus);
+ KazumiLogger().i('PlayerController: loaded ${cachedDanmakus.length} cached danmakus');
+ } else {
+ // 缓存为空,尝试在线获取
+ KazumiLogger().i('PlayerController: no cached danmaku, attempting online fetch');
+ try {
+ bangumiID = await DanmakuRequest.getDanDanBangumiIDByBgmBangumiID(
+ videoPageController.bangumiItem.id);
+ if (bangumiID != 0) {
+ var res = await DanmakuRequest.getDanDanmaku(bangumiID, episode);
+ if (res.isNotEmpty) {
+ addDanmakus(res);
+ KazumiLogger().i('PlayerController: fetched ${res.length} danmakus online');
+ // 将获取的弹幕保存到缓存,供下次离线使用
+ _saveDanmakuToCache(downloadController, res);
+ }
+ }
+ } catch (e) {
+ KazumiLogger().w('PlayerController: failed to fetch danmaku online (may be offline)', error: e);
+ }
+ }
+ } catch (e) {
+ KazumiLogger().w('PlayerController: failed to load cached danmaku', error: e);
+ } finally {
+ danmakuLoading = false;
+ }
+ }
+
+ /// 将弹幕保存到下载缓存
+ void _saveDanmakuToCache(DownloadController downloadController, List<Danmaku> danmakus) {
+ try {
+ downloadController.updateCachedDanmakus(
+ videoPageController.bangumiItem.id,
+ videoPageController.offlinePluginName,
+ videoPageController.actualEpisodeNumber,
+ danmakus,
+ bangumiID,
+ );
+ KazumiLogger().i('PlayerController: saved ${danmakus.length} danmakus to cache');
+ } catch (e) {
+ KazumiLogger().w('PlayerController: failed to save danmaku to cache', error: e);
+ }
+ }
+
Future<void> getDanDanmakuByBgmBangumiID(
int bgmBangumiID, int episode) async {
if (danmakuLoading) {
@@ -619,7 +732,10 @@ abstract class _PlayerController with Store {
}
void lanunchExternalPlayer() async {
- String referer = videoPageController.currentPlugin.referer;
+ // 离线模式下没有 referer
+ String referer = videoPageController.isOfflineMode
+ ? ''
+ : videoPageController.currentPlugin.referer;
if ((Platform.isAndroid || Platform.isWindows) && referer.isEmpty) {
if (await ExternalPlayer.launchURLWithMIME(videoUrl, 'video/mp4')) {
KazumiDialog.dismiss();
diff --git a/lib/pages/player/player_item.dart b/lib/pages/player/player_item.dart
index 7c148fad..cd4da250 100644
--- a/lib/pages/player/player_item.dart
+++ b/lib/pages/player/player_item.dart
@@ -694,10 +694,15 @@ class _PlayerItemState extends State<PlayerItem>
// 历史记录相关
if (playerController.playerPlaying && !videoPageController.loading) {
if (!WebDav().isHistorySyncing) {
+ // 离线模式使用 offlinePluginName,在线模式使用 currentPlugin.name
+ final pluginName = videoPageController.isOfflineMode
+ ? videoPageController.offlinePluginName
+ : videoPageController.currentPlugin.name;
+ // 使用 actualEpisodeNumber 获取实际的集数编号(离线模式下 currentEpisode 是列表位置)
historyController.updateHistory(
- videoPageController.currentEpisode,
+ videoPageController.actualEpisodeNumber,
videoPageController.currentRoad,
- videoPageController.currentPlugin.name,
+ pluginName,
videoPageController.bangumiItem,
playerController.playerPosition,
videoPageController.src,
diff --git a/lib/pages/player/player_item_panel.dart b/lib/pages/player/player_item_panel.dart
index f310fe0e..d8d4c111 100644
--- a/lib/pages/player/player_item_panel.dart
+++ b/lib/pages/player/player_item_panel.dart
@@ -17,6 +17,9 @@ import 'package:hive_ce/hive.dart';
import 'package:kazumi/utils/storage.dart';
import 'package:audio_video_progress_bar/audio_video_progress_bar.dart';
import 'package:kazumi/utils/timed_shutdown_service.dart';
+import 'package:kazumi/pages/download/download_controller.dart';
+import 'package:kazumi/pages/download/download_episode_sheet.dart';
+import 'package:kazumi/modules/download/download_module.dart';
class PlayerItemPanel extends StatefulWidget {
const PlayerItemPanel({
@@ -85,6 +88,7 @@ class _PlayerItemPanelState extends State<PlayerItemPanel> {
final VideoPageController videoPageController =
Modular.get<VideoPageController>();
final PlayerController playerController = Modular.get<PlayerController>();
+ final DownloadController downloadController = Modular.get<DownloadController>();
final TextEditingController textController = TextEditingController();
final FocusNode textFieldFocus = FocusNode();
// SVG Caches
@@ -1053,6 +1057,50 @@ class _PlayerItemPanelState extends State<PlayerItemPanel> {
);
}
+ void _downloadCurrentEpisode() {
+ final currentEpisode = videoPageController.currentEpisode;
+ final currentRoad = videoPageController.currentRoad;
+ final roadData = videoPageController.roadList[currentRoad];
+ final bangumiItem = videoPageController.bangumiItem;
+ final plugin = videoPageController.currentPlugin;
+
+ // 检查是否已下载(优先使用 URL 匹配,兼容列表重排序)
+ final episodePageUrl = roadData.data[currentEpisode - 1];
+ final existingEpisode = downloadController.getEpisodeByUrl(
+ bangumiItem.id, plugin.name, episodePageUrl);
+ if (existingEpisode != null &&
+ (existingEpisode.status == DownloadStatus.completed ||
+ existingEpisode.status == DownloadStatus.downloading ||
+ existingEpisode.status == DownloadStatus.pending)) {
+ KazumiDialog.showToast(message: '当前集已在下载列表中');
+ return;
+ }
+
+ downloadController.startDownload(
+ bangumiId: bangumiItem.id,
+ bangumiName: bangumiItem.nameCn.isNotEmpty
+ ? bangumiItem.nameCn
+ : bangumiItem.name,
+ bangumiCover: bangumiItem.images['large'] ?? '',
+ pluginName: plugin.name,
+ episodeNumber: currentEpisode,
+ episodeName: roadData.identifier[currentEpisode - 1],
+ road: currentRoad,
+ episodePageUrl: roadData.data[currentEpisode - 1],
+ );
+ KazumiDialog.showToast(message: '已添加到下载队列');
+ }
+
+ void _showBatchDownloadSheet() {
+ showModalBottomSheet(
+ context: context,
+ isScrollControlled: true,
+ builder: (context) => DownloadEpisodeSheet(
+ road: videoPageController.currentRoad,
+ ),
+ );
+ }
+
Widget get topControlWidget {
return Observer(
builder: (context) {
@@ -1217,6 +1265,45 @@ class _PlayerItemPanelState extends State<PlayerItemPanel> {
),
),
),
+ // 下载
+ SubmenuButton(
+ menuChildren: [
+ MenuItemButton(
+ onPressed: () {
+ _downloadCurrentEpisode();
+ },
+ child: Container(
+ height: 48,
+ constraints: BoxConstraints(minWidth: 112),
+ child: Align(
+ alignment: Alignment.centerLeft,
+ child: Text("下载当前集"),
+ ),
+ ),
+ ),
+ MenuItemButton(
+ onPressed: () {
+ _showBatchDownloadSheet();
+ },
+ child: Container(
+ height: 48,
+ constraints: BoxConstraints(minWidth: 112),
+ child: Align(
+ alignment: Alignment.centerLeft,
+ child: Text("批量下载"),
+ ),
+ ),
+ ),
+ ],
+ child: Container(
+ height: 48,
+ constraints: BoxConstraints(minWidth: 112),
+ child: Align(
+ alignment: Alignment.centerLeft,
+ child: Text("下载"),
+ ),
+ ),
+ ),
// 定时关闭
SubmenuButton(
menuChildren: [
diff --git a/lib/pages/settings/download_settings.dart b/lib/pages/settings/download_settings.dart
new file mode 100644
index 00000000..6736f309
--- /dev/null
+++ b/lib/pages/settings/download_settings.dart
@@ -0,0 +1,138 @@
+import 'package:flutter/material.dart';
+import 'package:hive_ce/hive.dart';
+import 'package:kazumi/bean/appbar/sys_app_bar.dart';
+import 'package:kazumi/utils/storage.dart';
+import 'package:card_settings_ui/card_settings_ui.dart';
+
+class DownloadSettingsPage extends StatefulWidget {
+ const DownloadSettingsPage({super.key});
+
+ @override
+ State<DownloadSettingsPage> createState() => _DownloadSettingsPageState();
+}
+
+class _DownloadSettingsPageState extends State<DownloadSettingsPage> {
+ Box setting = GStorage.setting;
+ late int parallelEpisodes;
+ late int parallelSegments;
+ late bool downloadDanmaku;
+
+ @override
+ void initState() {
+ super.initState();
+ parallelEpisodes = setting.get(
+ SettingBoxKey.downloadParallelEpisodes,
+ defaultValue: 2,
+ );
+ parallelSegments = setting.get(
+ SettingBoxKey.downloadParallelSegments,
+ defaultValue: 3,
+ );
+ downloadDanmaku = setting.get(
+ SettingBoxKey.downloadDanmaku,
+ defaultValue: true,
+ );
+ }
+
+ @override
+ Widget build(BuildContext context) {
+ final fontFamily = Theme.of(context).textTheme.bodyMedium?.fontFamily;
+ return Scaffold(
+ appBar: const SysAppBar(title: Text('下载设置')),
+ body: SettingsList(
+ maxWidth: 1000,
+ sections: [
+ SettingsSection(
+ title: Text('并发设置', style: TextStyle(fontFamily: fontFamily)),
+ tiles: [
+ SettingsTile(
+ title: Text('同时下载集数', style: TextStyle(fontFamily: fontFamily)),
+ description: Column(
+ crossAxisAlignment: CrossAxisAlignment.start,
+ children: [
+ Text(
+ '同时下载 $parallelEpisodes 集',
+ style: TextStyle(fontFamily: fontFamily),
+ ),
+ Slider(
+ value: parallelEpisodes.toDouble(),
+ min: 1,
+ max: 5,
+ divisions: 4,
+ label: '$parallelEpisodes',
+ onChanged: (value) {
+ setState(() => parallelEpisodes = value.toInt());
+ setting.put(
+ SettingBoxKey.downloadParallelEpisodes,
+ parallelEpisodes,
+ );
+ },
+ ),
+ ],
+ ),
+ ),
+ SettingsTile(
+ title: Text('分片并发数', style: TextStyle(fontFamily: fontFamily)),
+ description: Column(
+ crossAxisAlignment: CrossAxisAlignment.start,
+ children: [
+ Text(
+ '每集同时下载 $parallelSegments 个分片',
+ style: TextStyle(fontFamily: fontFamily),
+ ),
+ Slider(
+ value: parallelSegments.toDouble(),
+ min: 1,
+ max: 10,
+ divisions: 9,
+ label: '$parallelSegments',
+ onChanged: (value) {
+ setState(() => parallelSegments = value.toInt());
+ setting.put(
+ SettingBoxKey.downloadParallelSegments,
+ parallelSegments,
+ );
+ },
+ ),
+ ],
+ ),
+ ),
+ ],
+ ),
+ SettingsSection(
+ title: Text('缓存设置', style: TextStyle(fontFamily: fontFamily)),
+ tiles: [
+ SettingsTile.switchTile(
+ onToggle: (value) {
+ setState(() => downloadDanmaku = value ?? !downloadDanmaku);
+ setting.put(SettingBoxKey.downloadDanmaku, downloadDanmaku);
+ },
+ title: Text('缓存弹幕', style: TextStyle(fontFamily: fontFamily)),
+ description: Text(
+ '下载视频时同时缓存弹幕数据',
+ style: TextStyle(fontFamily: fontFamily),
+ ),
+ initialValue: downloadDanmaku,
+ ),
+ ],
+ ),
+ SettingsSection(
+ title: Text('说明', style: TextStyle(fontFamily: fontFamily)),
+ tiles: [
+ SettingsTile(
+ title: Text('关于并发设置', style: TextStyle(fontFamily: fontFamily)),
+ description: Text(
+ '• 集数并发:同时下载多少集视频\n'
+ '• 分片并发:每集内同时下载多少个视频片段\n'
+ '• 较高的并发可提升速度,但可能被服务器限制\n'
+ '• 修改后对新开始的下载生效',
+ style: TextStyle(fontFamily: fontFamily),
+ ),
+ ),
+ ],
+ ),
+ ],
+ ),
+ );
+ }
+}
diff --git a/lib/pages/settings/settings_module.dart b/lib/pages/settings/settings_module.dart
index 6bd6dac6..8cd805ec 100644
--- a/lib/pages/settings/settings_module.dart
+++ b/lib/pages/settings/settings_module.dart
@@ -11,6 +11,8 @@ import 'package:kazumi/pages/settings/super_resolution_settings.dart';
import 'package:kazumi/pages/settings/proxy/proxy_module.dart';
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';
class SettingsModule extends Module {
@override
@@ -30,5 +32,7 @@ class SettingsModule extends Module {
r.module("/plugin", module: PluginModule());
r.module("/history", module: HistoryModule());
r.module("/danmaku", module: DanmakuModule());
+ r.module("/download", module: DownloadModule());
+ r.child("/download-settings", child: (_) => const DownloadSettingsPage());
}
}
diff --git a/lib/pages/video/video_controller.dart b/lib/pages/video/video_controller.dart
index 83c1f06f..bbf15814 100644
--- a/lib/pages/video/video_controller.dart
+++ b/lib/pages/video/video_controller.dart
@@ -2,9 +2,14 @@ import 'package:kazumi/modules/roads/road_module.dart';
import 'package:kazumi/plugins/plugins_controller.dart';
import 'package:flutter_modular/flutter_modular.dart';
import 'package:kazumi/plugins/plugins.dart';
-import 'package:kazumi/pages/webview/webview_controller.dart';
import 'package:kazumi/pages/history/history_controller.dart';
+import 'package:kazumi/pages/player/player_controller.dart';
import 'package:kazumi/modules/bangumi/bangumi_item.dart';
+import 'package:kazumi/modules/download/download_module.dart';
+import 'package:kazumi/repositories/download_repository.dart';
+import 'package:kazumi/utils/download_manager.dart';
+import 'package:kazumi/providers/providers.dart';
+import 'package:kazumi/bean/dialog/dialog_helper.dart';
import 'package:mobx/mobx.dart';
import 'package:kazumi/utils/utils.dart';
import 'package:kazumi/utils/logger.dart';
@@ -54,6 +59,13 @@ abstract class _VideoPageController with Store {
@observable
int historyOffset = 0;
+ /// 离线播放模式
+ @observable
+ bool isOfflineMode = false;
+
+ /// 离线视频本地路径
+ String? _offlineVideoPath;
+
/// 和 bangumiItem 中的标题不同,此标题来自于视频源
String title = '';
@@ -64,16 +76,104 @@ abstract class _VideoPageController with Store {
late Plugin currentPlugin;
+ /// 离线模式下的虚拟插件名
+ String _offlinePluginName = '';
+
/// 用于取消正在进行的 queryRoads 操作
CancelToken? _queryRoadsCancelToken;
final PluginsController pluginsController = Modular.get<PluginsController>();
final HistoryController historyController = Modular.get<HistoryController>();
+ /// Repository 层依赖(用于离线模式)
+ final IDownloadRepository _downloadRepository = Modular.get<IDownloadRepository>();
+ final IDownloadManager _downloadManager = Modular.get<IDownloadManager>();
+
+ /// 长生命周期的视频源提供者(页面生命周期内复用,WebView 实例在 Provider 内复用)
+ WebViewVideoSourceProvider? _videoSourceProvider;
+
+ /// 初始化离线播放模式
+ void initForOfflinePlayback({
+ required BangumiItem bangumiItem,
+ required String pluginName,
+ required int episodeNumber,
+ required String episodeName,
+ required int road,
+ required String videoPath,
+ required List<DownloadEpisode> downloadedEpisodes,
+ }) {
+ this.bangumiItem = bangumiItem;
+ _offlinePluginName = pluginName;
+ currentRoad = road;
+ title = bangumiItem.nameCn.isNotEmpty ? bangumiItem.nameCn : bangumiItem.name;
+ isOfflineMode = true;
+ _offlineVideoPath = videoPath;
+ // 离线模式不需要解析视频源,直接设置 loading 为 false
+ loading = false;
+
+ // 构建仅包含已下载集数的 roadList
+ _buildOfflineRoadList(downloadedEpisodes);
+
+ // currentEpisode 是列表中的 1-based 位置,而非实际集数编号
+ // 在 roadList.data 中查找 episodeNumber 对应的位置
+ final index = roadList[currentRoad].data.indexOf(episodeNumber.toString());
+ currentEpisode = index >= 0 ? index + 1 : 1;
+ KazumiLogger().i('VideoPageController: initialized for offline playback, episode $episodeNumber (position: $currentEpisode)');
+ }
+
+ /// 构建离线模式的 roadList
+ void _buildOfflineRoadList(List<DownloadEpisode> episodes) {
+ roadList.clear();
+ episodes.sort((a, b) => a.episodeNumber.compareTo(b.episodeNumber));
+ // 使用 '播放列表1' 作为名称,与 UI 代码兼容
+ roadList.add(Road(
+ name: '播放列表1',
+ // data 存储实际的 episodeNumber(字符串形式),用于离线播放时查找本地文件
+ data: episodes.map((e) => e.episodeNumber.toString()).toList(),
+ identifier: episodes.map((e) =>
+ e.episodeName.isNotEmpty ? e.episodeName : '第${e.episodeNumber}集'
+ ).toList(),
+ ));
+ }
+
+ /// 重置离线模式状态
+ void resetOfflineMode() {
+ isOfflineMode = false;
+ _offlineVideoPath = null;
+ _offlinePluginName = '';
+ }
+
+ /// 获取离线视频路径(用于 VideoPage 初始化播放器)
+ String? get offlineVideoPath => _offlineVideoPath;
+
+ /// 获取离线模式下的插件名
+ String get offlinePluginName => _offlinePluginName;
+
+ /// 获取当前实际的集数编号
+ /// 在线模式下直接返回 currentEpisode
+ /// 离线模式下从 roadList.data 中获取实际的 episodeNumber
+ int get actualEpisodeNumber {
+ if (isOfflineMode && roadList.isNotEmpty) {
+ try {
+ return int.parse(roadList[currentRoad].data[currentEpisode - 1]);
+ } catch (_) {
+ return currentEpisode;
+ }
+ }
+ return currentEpisode;
+ }
+
Future<void> changeEpisode(int episode,
{int currentRoad = 0, int offset = 0}) async {
currentEpisode = episode;
this.currentRoad = currentRoad;
+
+ if (isOfflineMode) {
+ // 离线模式:从下载记录获取本地路径
+ await _changeOfflineEpisode(episode, offset);
+ return;
+ }
+
String chapterName = roadList[currentRoad].identifier[episode - 1];
KazumiLogger().i('VideoPageController: changed to $chapterName');
String urlItem = roadList[currentRoad].data[episode - 1];
@@ -83,10 +183,84 @@ abstract class _VideoPageController with Store {
} else {
urlItem = currentPlugin.baseUrl + urlItem;
}
- final webviewItemController = Modular.get<WebviewItemController>();
- await webviewItemController.loadUrl(
- urlItem, currentPlugin.useNativePlayer, currentPlugin.useLegacyParser,
- offset: offset);
+
+ // 统一使用 Provider 模式解析视频源
+ await _resolveWithProvider(urlItem, offset);
+ }
+
+ /// 离线模式下切换集数
+ /// [episode] 是列表中的位置(从 1 开始),需要从 roadList.data 中获取实际的 episodeNumber
+ Future<void> _changeOfflineEpisode(int episode, int offset) async {
+ // 从 roadList.data 中获取实际的 episodeNumber
+ final actualEpisodeNumber = int.tryParse(roadList[currentRoad].data[episode - 1]);
+ if (actualEpisodeNumber == null) {
+ KazumiLogger().e('VideoPageController: failed to parse episode number from roadList data: ${roadList[currentRoad].data[episode - 1]}');
+ KazumiDialog.showToast(message: '集数解析失败');
+ return;
+ }
+
+ final localPath = _getLocalVideoPath(
+ bangumiItem.id,
+ _offlinePluginName,
+ actualEpisodeNumber,
+ );
+ if (localPath == null) {
+ KazumiDialog.showToast(message: '该集数未下载');
+ return;
+ }
+ _offlineVideoPath = localPath;
+ loading = false;
+
+ KazumiLogger().i('VideoPageController: offline episode changed to $actualEpisodeNumber (index: $episode), path: $localPath');
+
+ // 直接初始化播放器
+ final playerController = Modular.get<PlayerController>();
+ playerController.init(localPath, offset: offset);
+ }
+
+ /// 获取本地视频路径(通过 Repository 层)
+ String? _getLocalVideoPath(int bangumiId, String pluginName, int episodeNumber) {
+ final episode = _downloadRepository.getEpisode(bangumiId, pluginName, episodeNumber);
+ return _downloadManager.getLocalVideoPath(episode);
+ }
+
+ /// 使用 VideoSourceProvider 解析视频源(原生播放器模式)
+ Future<void> _resolveWithProvider(String url, int offset) async {
+ // 取消上一次正在进行的解析,但不 dispose Provider
+ _videoSourceProvider?.cancel();
+
+ loading = true;
+ _videoSourceProvider ??= WebViewVideoSourceProvider();
+
+ try {
+ final source = await _videoSourceProvider!.resolve(
+ url,
+ useLegacyParser: currentPlugin.useLegacyParser,
+ offset: offset,
+ );
+
+ loading = false;
+ KazumiLogger().i('VideoPageController: resolved video URL: ${source.url}');
+
+ // 直接初始化播放器
+ final playerController = Modular.get<PlayerController>();
+ playerController.init(source.url, offset: source.offset);
+ } on VideoSourceTimeoutException {
+ KazumiLogger().w('VideoPageController: video URL resolution timed out');
+ loading = false;
+ } on VideoSourceCancelledException {
+ KazumiLogger().i('VideoPageController: video URL resolution cancelled');
+ // 不设置 loading = false,因为可能是切换到新的集数
+ } catch (e) {
+ KazumiLogger().e('VideoPageController: video URL resolution failed', error: e);
+ loading = false;
+ }
+ }
+
+ /// 取消当前视频源解析并销毁 Provider(页面退出时调用)
+ void cancelVideoSourceResolution() {
+ _videoSourceProvider?.dispose();
+ _videoSourceProvider = null;
}
Future<void> queryBangumiEpisodeCommentsByID(int id, int episode) async {
diff --git a/lib/pages/video/video_controller.g.dart b/lib/pages/video/video_controller.g.dart
index 0b8cde66..578551f3 100644
--- a/lib/pages/video/video_controller.g.dart
+++ b/lib/pages/video/video_controller.g.dart
@@ -153,6 +153,22 @@ mixin _$VideoPageController on _VideoPageController, Store {
});
}
+ late final _$isOfflineModeAtom =
+ Atom(name: '_VideoPageController.isOfflineMode', context: context);
+
+ @override
+ bool get isOfflineMode {
+ _$isOfflineModeAtom.reportRead();
+ return super.isOfflineMode;
+ }
+
+ @override
+ set isOfflineMode(bool value) {
+ _$isOfflineModeAtom.reportWrite(value, super.isOfflineMode, () {
+ super.isOfflineMode = value;
+ });
+ }
+
late final _$roadListAtom =
Atom(name: '_VideoPageController.roadList', context: context);
@@ -181,6 +197,7 @@ isCommentsAscending: ${isCommentsAscending},
isPip: ${isPip},
showTabBody: ${showTabBody},
historyOffset: ${historyOffset},
+isOfflineMode: ${isOfflineMode},
roadList: ${roadList}
''';
}
diff --git a/lib/pages/video/video_module.dart b/lib/pages/video/video_module.dart
index 6e99d0aa..815c2868 100644
--- a/lib/pages/video/video_module.dart
+++ b/lib/pages/video/video_module.dart
@@ -1,6 +1,5 @@
import 'package:kazumi/pages/video/video_page.dart';
import 'package:flutter_modular/flutter_modular.dart';
-import 'package:kazumi/pages/webview/webview_controller.dart';
import 'package:kazumi/pages/player/player_controller.dart';
class VideoModule extends Module {
@@ -12,6 +11,5 @@ class VideoModule extends Module {
@override
void binds(i) {
i.addSingleton(PlayerController.new);
- i.addSingleton(WebviewItemControllerFactory.getController);
}
}
diff --git a/lib/pages/video/video_page.dart b/lib/pages/video/video_page.dart
index 8ec125a5..ac7ce9ae 100644
--- a/lib/pages/video/video_page.dart
+++ b/lib/pages/video/video_page.dart
@@ -2,11 +2,8 @@ import 'dart:async';
import 'package:canvas_danmaku/models/danmaku_content_item.dart';
import 'package:flutter/material.dart';
import 'package:flutter_modular/flutter_modular.dart';
-import 'package:kazumi/bean/appbar/sys_app_bar.dart';
import 'package:kazumi/pages/player/player_controller.dart';
import 'package:kazumi/pages/video/video_controller.dart';
-import 'package:kazumi/pages/webview/webview_item.dart';
-import 'package:kazumi/pages/webview/webview_controller.dart';
import 'package:kazumi/pages/history/history_controller.dart';
import 'package:kazumi/utils/logger.dart';
import 'package:kazumi/pages/player/player_item.dart';
@@ -21,6 +18,9 @@ import 'package:scrollview_observer/scrollview_observer.dart';
import 'package:kazumi/pages/player/episode_comments_sheet.dart';
import 'package:window_manager/window_manager.dart';
import 'package:kazumi/bean/widget/embedded_native_control_area.dart';
+import 'package:kazumi/pages/download/download_controller.dart';
+import 'package:kazumi/pages/download/download_episode_sheet.dart';
+import 'package:kazumi/modules/download/download_module.dart';
import 'package:kazumi/utils/timed_shutdown_service.dart';
class VideoPage extends StatefulWidget {
@@ -37,8 +37,8 @@ class _VideoPageState extends State<VideoPage>
Modular.get<VideoPageController>();
final PlayerController playerController = Modular.get<PlayerController>();
final HistoryController historyController = Modular.get<HistoryController>();
- final WebviewItemController webviewItemController =
- Modular.get<WebviewItemController>();
+ final DownloadController downloadController =
+ Modular.get<DownloadController>();
late bool playResume;
bool showDebugLog = false;
List<String> webviewLogLines = [];
@@ -54,19 +54,6 @@ class _VideoPageState extends State<VideoPage>
// 当前播放列表
late int currentRoad;
- // webview init events listener
- late final StreamSubscription<bool> _initSubscription;
-
- // webview logs events listener
- late final StreamSubscription<String> _logSubscription;
-
- // webview video loaded events listener
- late final StreamSubscription<bool> _videoLoadedSubscription;
-
- // webview video source events listener
- // The first parameter is the video source URL and the second parameter is the video offset (start position)
- late final StreamSubscription<(String, int)> _videoURLSubscription;
-
// disable animation.
late final bool disableAnimations;
@@ -100,61 +87,19 @@ class _VideoPageState extends State<VideoPage>
parent: animation,
curve: Curves.easeIn,
));
- videoPageController.currentEpisode = 1;
- videoPageController.currentRoad = 0;
- videoPageController.historyOffset = 0;
- videoPageController.showTabBody = true;
+
playResume = setting.get(SettingBoxKey.playResume, defaultValue: true);
disableAnimations =
setting.get(SettingBoxKey.playerDisableAnimations, defaultValue: false);
- var progress = historyController.lastWatching(
- videoPageController.bangumiItem,
- videoPageController.currentPlugin.name);
- if (progress != null) {
- if (videoPageController.roadList.length > progress.road) {
- if (videoPageController.roadList[progress.road].data.length >=
- progress.episode) {
- videoPageController.currentEpisode = progress.episode;
- videoPageController.currentRoad = progress.road;
- if (playResume) {
- videoPageController.historyOffset = progress.progress.inSeconds;
- }
- }
- }
+
+ if (videoPageController.isOfflineMode) {
+ // 离线模式:跳过 WebView 订阅,直接初始化播放器
+ _initOfflineMode();
+ } else {
+ // 在线模式:设置 WebView 订阅
+ _initOnlineMode();
}
- currentRoad = videoPageController.currentRoad;
- // webview events listener
- _initSubscription = webviewItemController.onInitialized.listen((event) {
- if (event) {
- changeEpisode(videoPageController.currentEpisode,
- currentRoad: videoPageController.currentRoad,
- offset: videoPageController.historyOffset);
- }
- });
- _videoLoadedSubscription =
- webviewItemController.onVideoLoading.listen((event) {
- videoPageController.loading = event;
- });
- _videoURLSubscription =
- webviewItemController.onVideoURLParser.listen((event) {
- final (mediaUrl, offset) = event;
- playerController.init(mediaUrl, offset: offset);
- });
- _logSubscription = webviewItemController.onLog.listen((event) {
- KazumiLogger().i('WebViewParser: $event');
- if (event == 'clear') {
- clearWebviewLog();
- return;
- }
- if (event == 'showDebug') {
- showDebugConsole();
- return;
- }
- setState(() {
- webviewLogLines.add(event);
- });
- });
_syncChatSubscription = playerController.syncPlayChatStream.listen((event) {
final localUsername = playerController.syncplayController?.username ?? '';
final String displayText = '${event.username}:${event.message}';
@@ -174,6 +119,62 @@ class _VideoPageState extends State<VideoPage>
});
}
+ void _initOfflineMode() {
+ videoPageController.showTabBody = true;
+ videoPageController.historyOffset = 0;
+ currentRoad = videoPageController.currentRoad;
+
+ // 检查历史记录(使用离线插件名)
+ var progress = historyController.lastWatching(
+ videoPageController.bangumiItem,
+ videoPageController.offlinePluginName);
+ if (progress != null && playResume) {
+ // 在离线模式下,只恢复播放进度,不改变集数(因为用户已选择特定集数)
+ videoPageController.historyOffset = progress.progress.inSeconds;
+ }
+
+ // 初始化播放器(loading 已在 initForOfflinePlayback 中设置为 false)
+ WidgetsBinding.instance.addPostFrameCallback((_) {
+ if (videoPageController.offlineVideoPath != null) {
+ playerController.init(
+ videoPageController.offlineVideoPath!,
+ offset: videoPageController.historyOffset,
+ );
+ }
+ });
+ }
+
+ void _initOnlineMode() {
+ videoPageController.currentEpisode = 1;
+ videoPageController.currentRoad = 0;
+ videoPageController.historyOffset = 0;
+ videoPageController.showTabBody = true;
+
+ var progress = historyController.lastWatching(
+ videoPageController.bangumiItem,
+ videoPageController.currentPlugin.name);
+ if (progress != null) {
+ if (videoPageController.roadList.length > progress.road) {
+ if (videoPageController.roadList[progress.road].data.length >=
+ progress.episode) {
+ videoPageController.currentEpisode = progress.episode;
+ videoPageController.currentRoad = progress.road;
+ if (playResume) {
+ videoPageController.historyOffset = progress.progress.inSeconds;
+ }
+ }
+ }
+ }
+ currentRoad = videoPageController.currentRoad;
+
+ // 使用 Provider 模式启动播放
+ WidgetsBinding.instance.addPostFrameCallback((_) {
+ changeEpisode(videoPageController.currentEpisode,
+ currentRoad: videoPageController.currentRoad,
+ offset: videoPageController.historyOffset);
+ });
+ }
+
@override
void dispose() {
try {
@@ -185,18 +186,6 @@ class _VideoPageState extends State<VideoPage>
try {
animation.dispose();
} catch (_) {}
- try {
- _initSubscription.cancel();
- } catch (_) {}
- try {
- _videoLoadedSubscription.cancel();
- } catch (_) {}
- try {
- _videoURLSubscription.cancel();
- } catch (_) {}
- try {
- _logSubscription.cancel();
- } catch (_) {}
try {
_syncChatSubscription.cancel();
} catch (_) {}
@@ -205,6 +194,8 @@ class _VideoPageState extends State<VideoPage>
} catch (e) {
KazumiLogger().e('VideoPageController: failed to dispose playerController', error: e);
}
+ // 取消正在进行的视频源解析
+ videoPageController.cancelVideoSourceResolution();
if (!Utils.isDesktop()) {
try {
ScreenBrightnessPlatform.instance.resetApplicationScreenBrightness();
@@ -212,6 +203,8 @@ class _VideoPageState extends State<VideoPage>
}
videoPageController.episodeInfo.reset();
videoPageController.episodeCommentsList.clear();
+ // 重置离线模式
+ videoPageController.resetOfflineMode();
Utils.unlockScreenRotation();
tabController.dispose();
// Cancel timed shutdown when leaving anime page
@@ -511,10 +504,7 @@ class _VideoPageState extends State<VideoPage>
}
return Observer(builder: (context) {
return Scaffold(
- appBar: ((videoPageController.currentPlugin.useNativePlayer ||
- videoPageController.isFullscreen)
- ? null
- : SysAppBar(title: Text(videoPageController.title))),
+ appBar: null,
body: SafeArea(
top: !videoPageController.isFullscreen,
// set iOS and Android navigation bar to immersive
@@ -620,8 +610,7 @@ class _VideoPageState extends State<VideoPage>
child: Stack(
children: [
Positioned.fill(
- child: (videoPageController.currentPlugin.useNativePlayer &&
- playerController.loading)
+ child: playerController.loading
? Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
@@ -666,8 +655,7 @@ class _VideoPageState extends State<VideoPage>
),
Visibility(
visible: (videoPageController.loading ||
- (videoPageController.currentPlugin.useNativePlayer &&
- playerController.loading)) &&
+ playerController.loading) &&
showDebugLog,
child: Container(
color: Colors.black,
@@ -689,9 +677,7 @@ class _VideoPageState extends State<VideoPage>
),
),
),
- ((videoPageController.currentPlugin.useNativePlayer ||
- videoPageController.isFullscreen))
- ? Stack(
+ Stack(
children: [
Positioned(
top: 0,
@@ -751,14 +737,12 @@ class _VideoPageState extends State<VideoPage>
),
),
],
- )
- : Container(),
+ ),
],
),
),
Positioned.fill(
- child: (!videoPageController.currentPlugin.useNativePlayer ||
- playerController.loading)
+ child: playerController.loading
? Container()
: PlayerItem(
openMenu: openTabBodyAnimated,
@@ -772,16 +756,6 @@ class _VideoPageState extends State<VideoPage>
pauseForTimedShutdown: pauseForTimedShutdown,
),
),
-
- /// workaround for webview_windows
- /// The webview_windows component cannot be removed from the widget tree; otherwise, it can never be reinitialized.
- Positioned(
- child: SizedBox(
- height: (videoPageController.loading ||
- videoPageController.currentPlugin.useNativePlayer)
- ? 0
- : null,
- child: const WebviewItem()))
],
);
}
@@ -853,11 +827,67 @@ class _VideoPageState extends State<VideoPage>
),
),
),
+ // 离线模式下隐藏下载按钮
+ if (!videoPageController.isOfflineMode)
+ SizedBox(
+ height: 34,
+ child: IconButton(
+ icon: const Icon(Icons.download_rounded, size: 20),
+ tooltip: '批量下载',
+ onPressed: () {
+ showModalBottomSheet(
+ context: context,
+ isScrollControlled: true,
+ builder: (context) =>
+ DownloadEpisodeSheet(road: currentRoad),
+ );
+ },
+ ),
+ ),
],
),
);
}
+ Widget _buildDownloadStatusIcon(int episodeNumber, String episodePageUrl) {
+ // 离线模式下不显示下载状态图标
+ if (videoPageController.isOfflineMode) return const SizedBox.shrink();
+ final bangumiId = videoPageController.bangumiItem.id;
+ final pluginName = videoPageController.currentPlugin.name;
+ final episode = downloadController.getEpisodeByUrl(bangumiId, pluginName, episodePageUrl)
+ ?? downloadController.getEpisode(bangumiId, pluginName, episodeNumber);
+ if (episode == null) return const SizedBox.shrink();
+ switch (episode.status) {
+ case DownloadStatus.completed:
+ return Icon(Icons.offline_pin,
+ size: 16, color: Theme.of(context).colorScheme.primary);
+ case DownloadStatus.downloading:
+ return SizedBox(
+ width: 16,
+ height: 16,
+ child: CircularProgressIndicator(
+ value: episode.progressPercent,
+ strokeWidth: 2,
+ ),
+ );
+ case DownloadStatus.failed:
+ return Icon(Icons.error_outline,
+ size: 16, color: Theme.of(context).colorScheme.error);
+ case DownloadStatus.paused:
+ return Icon(Icons.pause_circle_outline,
+ size: 16, color: Theme.of(context).colorScheme.outline);
+ case DownloadStatus.pending:
+ case DownloadStatus.resolving:
+ return SizedBox(
+ width: 16,
+ height: 16,
+ child: CircularProgressIndicator(strokeWidth: 2),
+ );
+ default:
+ return const SizedBox.shrink();
+ }
+ }
+
Widget get menuBody {
var cardList = <Widget>[];
for (var road in videoPageController.roadList) {
@@ -914,6 +944,7 @@ class _VideoPageState extends State<VideoPage>
? Theme.of(context).colorScheme.primary
: Theme.of(context).colorScheme.onSurface),
)),
+ _buildDownloadStatusIcon(count0, urlItem),
const SizedBox(width: 2),
],
),
diff --git a/lib/pages/webview/webview_controller_impel/webview_controller_impel.dart b/lib/pages/webview/webview_controller_impel/webview_controller_impel.dart
deleted file mode 100644
index 1add3744..00000000
--- a/lib/pages/webview/webview_controller_impel/webview_controller_impel.dart
+++ /dev/null
@@ -1,328 +0,0 @@
-import 'dart:async';
-import 'package:kazumi/utils/logger.dart';
-import 'package:kazumi/utils/utils.dart';
-import 'package:kazumi/pages/webview/webview_controller.dart';
-import 'package:webview_flutter/webview_flutter.dart';
-
-class WebviewItemControllerImpel
- extends WebviewItemController<WebViewController> {
- // workaround for webview_flutter lib.
- // webview_flutter lib won't change currentUrl after redirect using window.location.href.
- // which causes multiple redirects to the same url.
- // so we need to store the currentUrl manually
- String currentUrl = '';
-
- Timer? ifrmaeParserTimer;
- Timer? videoParserTimer;
-
- @override
- Future<void> init() async {
- webviewController ??= WebViewController();
- initEventController.add(true);
- }
-
- @override
- Future<void> loadUrl(String url, bool useNativePlayer, bool useLegacyParser,
- {int offset = 0}) async {
- ifrmaeParserTimer?.cancel();
- videoParserTimer?.cancel();
- await unloadPage();
- await setDesktopUserAgent();
- count = 0;
- currentUrl = '';
- this.offset = offset;
- isIframeLoaded = false;
- isVideoSourceLoaded = false;
- videoLoadingEventController.add(true);
- await webviewController!
- .setNavigationDelegate(NavigationDelegate(onUrlChange: (currentUrl) {
- KazumiLogger().i('WebView: current URL: ${currentUrl.url}');
- if (useNativePlayer && !useLegacyParser) {
- addBlobParser();
- addInviewIframeBridge();
- }
- // addFullscreenListener();
- }));
- await webviewController!.setJavaScriptMode(JavaScriptMode.unrestricted);
- await webviewController!.addJavaScriptChannel('JSBridgeDebug',
- onMessageReceived: (JavaScriptMessage message) {
- logEventController.add('Callback received: ${message.message}');
- logEventController.add(
- 'If there is audio but no video, please report it to the rule developer.');
- if ((message.message.contains('http') ||
- message.message.startsWith('//')) &&
- !message.message.contains('googleads') &&
- !message.message.contains('googlesyndication.com') &&
- !message.message.contains('prestrain.html') &&
- !message.message.contains('prestrain%2Ehtml') &&
- !message.message.contains('adtrafficquality') &&
- currentUrl != message.message) {
- logEventController.add('Parsing video source ${message.message}');
- currentUrl = Uri.encodeFull(message.message);
- redirctWithReferer(message.message);
- if (Utils.decodeVideoSource(currentUrl) != Uri.encodeFull(currentUrl) &&
- useNativePlayer &&
- useLegacyParser) {
- isIframeLoaded = true;
- isVideoSourceLoaded = true;
- videoLoadingEventController.add(false);
- logEventController.add(
- 'Loading video source ${Utils.decodeVideoSource(currentUrl)}');
- unloadPage();
- videoParserEventController
- .add((Utils.decodeVideoSource(currentUrl), offset));
- }
- }
- });
- await webviewController!.addJavaScriptChannel('IframeRedirectBridge',
- onMessageReceived: (JavaScriptMessage message) {
- logEventController.add('Redirect to: ${message.message}');
- if (!useNativePlayer) {
- Future.delayed(const Duration(seconds: 2), () {
- isIframeLoaded = true;
- videoLoadingEventController.add(false);
- });
- }
- });
- if (!useLegacyParser) {
- await webviewController!.addJavaScriptChannel('VideoBridgeDebug',
- onMessageReceived: (JavaScriptMessage message) {
- logEventController.add('Callback received: ${message.message}');
- if (message.message.contains('http') && !isVideoSourceLoaded) {
- logEventController.add('Loading video source: ${message.message}');
- isIframeLoaded = true;
- isVideoSourceLoaded = true;
- videoLoadingEventController.add(false);
- if (useNativePlayer) {
- unloadPage();
- videoParserEventController.add((message.message, offset));
- }
- }
- });
- }
- await webviewController!.loadRequest(Uri.parse(url));
-
- ifrmaeParserTimer = Timer.periodic(const Duration(seconds: 1), (timer) {
- if (isIframeLoaded) {
- timer.cancel();
- } else {
- count++;
- parseIframeUrl();
- }
- });
- if (useNativePlayer) {
- videoParserTimer = Timer.periodic(const Duration(seconds: 1), (timer) {
- if (isVideoSourceLoaded) {
- timer.cancel();
- } else {
- if (count >= 15) {
- timer.cancel();
- isIframeLoaded = true;
- logEventController.add('clear');
- logEventController.add('解析视频资源超时');
- logEventController.add('请切换到其他播放列表或视频源');
- logEventController.add('showDebug');
- } else {
- if (!useLegacyParser) {
- parseVideoSource();
- }
- }
- }
- });
- }
- }
-
- @override
- Future<void> unloadPage() async {
- await webviewController!
- .removeJavaScriptChannel('JSBridgeDebug')
- .catchError((_) {});
- await webviewController!
- .removeJavaScriptChannel('VideoBridgeDebug')
- .catchError((_) {});
- await webviewController!
- .removeJavaScriptChannel('IframeRedirectBridge')
- .catchError((_) {});
- await webviewController!.loadRequest(Uri.parse('about:blank'));
- await webviewController!.clearCache();
- ifrmaeParserTimer?.cancel();
- videoParserTimer?.cancel();
- }
-
- @override
- void dispose() {
- unloadPage();
- }
-
- Future<void> parseIframeUrl() async {
- await webviewController!.runJavaScript('''
- var iframes = document.getElementsByTagName('iframe');
- JSBridgeDebug.postMessage('The number of iframe tags is' + iframes.length);
- for (var i = 0; i < iframes.length; i++) {
- var iframe = iframes[i];
- var src = iframe.getAttribute('src');
- if (src) {
- JSBridgeDebug.postMessage(src);
- }
-
- if (src && src.trim() !== '' && (src.startsWith('http') || src.startsWith('//')) && !src.includes('googleads') && !src.includes('adtrafficquality') && !src.includes('googlesyndication.com') && !src.includes('google.com') && !src.includes('prestrain.html') && !src.includes('prestrain%2Ehtml')) {
- IframeRedirectBridge.postMessage(src);
- break;
- }
- }
- ''');
- }
-
- Future<void> redirctWithReferer(String src) async {
- await webviewController!.runJavaScript('window.location.href = "$src";');
- }
-
- // 非blob资源
- Future<void> parseVideoSource() async {
- await webviewController!.runJavaScript('''
- var videos = document.querySelectorAll('video');
- VideoBridgeDebug.postMessage('The number of video tags is' + videos.length);
- for (var i = 0; i < videos.length; i++) {
- var src = videos[i].getAttribute('src');
- if (src && src.trim() !== '' && !src.startsWith('blob:') && !src.includes('googleads')) {
- VideoBridgeDebug.postMessage(src);
- break;
- }
- }
- document.querySelectorAll('iframe').forEach((iframe) => {
- try {
- iframe.contentWindow.eval(`
- var videos = document.querySelectorAll('video');
- window.parent.postMessage({ message: 'videoMessage:' + 'The number of video tags is' + videos.length }, "*");
- for (var i = 0; i < videos.length; i++) {
- var src = videos[i].getAttribute('src');
- if (src && src.trim() !== '' && !src.startsWith('blob:') && !src.includes('googleads')) {
- window.parent.postMessage({ message: 'videoMessage:' + src }, "*");
- }
- }
- `);
- } catch { }
- });
- ''');
- }
-
- // blob资源
- Future<void> addBlobParser() async {
- await webviewController!.runJavaScript('''
- const _r_text = window.Response.prototype.text;
- window.Response.prototype.text = function () {
- return new Promise((resolve, reject) => {
- _r_text.call(this).then((text) => {
- resolve(text);
- if (text.trim().startsWith("#EXTM3U")) {
- VideoBridgeDebug.postMessage(this.url);
- }
- }).catch(reject);
- });
- }
-
- const _open = window.XMLHttpRequest.prototype.open;
- window.XMLHttpRequest.prototype.open = function (...args) {
- this.addEventListener("load", () => {
- try {
- let content = this.responseText;
- if (content.trim().startsWith("#EXTM3U") && args[1] !== null && args[1] !== undefined) {
- VideoBridgeDebug.postMessage(args[1]);
- };
- } catch { }
- });
- return _open.apply(this, args);
- }
-
- function injectIntoIframe(iframe) {
- try {
- const iframeWindow = iframe.contentWindow;
- if (!iframeWindow) return;
-
- const iframe_r_text = iframeWindow.Response.prototype.text;
- iframeWindow.Response.prototype.text = function () {
- return new Promise((resolve, reject) => {
- iframe_r_text.call(this).then((text) => {
- resolve(text);
- if (text.trim().startsWith("#EXTM3U")) {
- VideoBridgeDebug.postMessage(this.url);
- }
- }).catch(reject);
- });
- }
-
- const iframe_open = iframeWindow.XMLHttpRequest.prototype.open;
- iframeWindow.XMLHttpRequest.prototype.open = function (...args) {
- this.addEventListener("load", () => {
- try {
- let content = this.responseText;
- if (content.trim().startsWith("#EXTM3U") && args[1] !== null && args[1] !== undefined) {
- console.log(args[1]);
- VideoBridgeDebug.postMessage(args[1]);
- };
- } catch { }
- });
- return iframe_open.apply(this, args);
- }
- } catch (e) {
- console.error('iframe inject failed:', e);
- }
- }
-
- function setupIframeListeners() {
- document.querySelectorAll('iframe').forEach(iframe => {
- if (iframe.contentDocument) {
- injectIntoIframe(iframe);
- }
- iframe.addEventListener('load', () => injectIntoIframe(iframe));
- });
-
- const observer = new MutationObserver(mutations => {
- mutations.forEach(mutation => {
- if (mutation.type === 'childList') {
- mutation.addedNodes.forEach(node => {
- if (node.nodeName === 'IFRAME') {
- node.addEventListener('load', () => injectIntoIframe(node));
- }
- if (node.querySelectorAll) {
- node.querySelectorAll('iframe').forEach(iframe => {
- iframe.addEventListener('load', () => injectIntoIframe(iframe));
- });
- }
- });
- }
- });
- });
-
- observer.observe(document.body, { childList: true, subtree: true });
- }
-
- if (document.readyState === 'loading') {
- document.addEventListener('DOMContentLoaded', setupIframeListeners);
- } else {
- setupIframeListeners();
- }
- ''');
- }
-
- Future<void> addInviewIframeBridge() async {
- await webviewController!.runJavaScript('''
- window.addEventListener("message", function(event) {
- if (event.data) {
- if (event.data.message && event.data.message.startsWith('videoMessage:')) {
- const msg = event.data.message.replace(/^videoMessage:/, '');
- if (msg !== null && msg !== undefined && msg !== "") {
- VideoBridgeDebug.postMessage(msg);
- }
- }
- }
- });
- ''');
- }
-
- // 设定UA
- Future<void> setDesktopUserAgent() async {
- String desktopUserAgent = Utils.getRandomUA();
- await webviewController!.setUserAgent(desktopUserAgent);
- }
-}
diff --git a/lib/pages/webview/webview_item.dart b/lib/pages/webview/webview_item.dart
deleted file mode 100644
index 2b3d8452..00000000
--- a/lib/pages/webview/webview_item.dart
+++ /dev/null
@@ -1,38 +0,0 @@
-import 'dart:io';
-import 'package:flutter/material.dart';
-import 'package:kazumi/pages/webview/webview_item_impel/webview_android_item_impel.dart';
-import 'package:kazumi/pages/webview/webview_item_impel/webview_item_impel.dart';
-import 'package:kazumi/pages/webview/webview_item_impel/webview_windows_item_impel.dart';
-import 'package:kazumi/pages/webview/webview_item_impel/webview_linux_item_impel.dart';
-import 'package:kazumi/pages/webview/webview_item_impel/webview_apple_item_impel.dart';
-import 'package:kazumi/utils/utils.dart';
-
-class WebviewItem extends StatefulWidget {
- const WebviewItem({super.key});
-
- @override
- State<WebviewItem> createState() => _WebviewItemState();
-}
-
-class _WebviewItemState extends State<WebviewItem> {
- @override
- Widget build(BuildContext context) {
- return webviewUniversal;
- }
-}
-
-Widget get webviewUniversal {
- if (Platform.isWindows) {
- return const WebviewWindowsItemImpel();
- }
- if (Platform.isLinux) {
- return const WebviewLinuxItemImpel();
- }
- if (Platform.isMacOS || Platform.isIOS) {
- return const WebviewAppleItemImpel();
- }
- if (Platform.isAndroid && Utils.isDocumentStartScriptSupported) {
- return const WebviewAndroidItemImpel();
- }
- return const WebviewItemImpel();
-}
diff --git a/lib/pages/webview/webview_item_impel/webview_android_item_impel.dart b/lib/pages/webview/webview_item_impel/webview_android_item_impel.dart
deleted file mode 100644
index a4e75465..00000000
--- a/lib/pages/webview/webview_item_impel/webview_android_item_impel.dart
+++ /dev/null
@@ -1,38 +0,0 @@
-import 'package:flutter/material.dart';
-import 'package:kazumi/pages/webview/webview_controller.dart';
-import 'package:flutter_modular/flutter_modular.dart';
-import 'package:kazumi/pages/webview/webview_controller_impel/webview_android_controller_impel.dart';
-
-class WebviewAndroidItemImpel extends StatefulWidget {
- const WebviewAndroidItemImpel({super.key});
-
- @override
- State<WebviewAndroidItemImpel> createState() =>
- _WebviewAndroidItemImpelState();
-}
-
-class _WebviewAndroidItemImpelState extends State<WebviewAndroidItemImpel> {
- final webviewAndroidItemController =
- Modular.get<WebviewItemController>() as WebviewAndroidItemControllerImpel;
-
- @override
- void initState() {
- super.initState();
- webviewAndroidItemController.init();
- }
-
- @override
- void dispose() {
- webviewAndroidItemController.dispose();
- super.dispose();
- }
-
- @override
- Widget build(BuildContext context) {
- return Container(
- height: MediaQuery.of(context).size.width * 9.0 / (16.0),
- width: MediaQuery.of(context).size.width,
- color: Colors.black,
- child: const Center(child: Text('此平台不支持Webview规则', style: TextStyle(color: Colors.white))));
- }
-}
diff --git a/lib/pages/webview/webview_item_impel/webview_apple_item_impel.dart b/lib/pages/webview/webview_item_impel/webview_apple_item_impel.dart
deleted file mode 100644
index 0de9c7ce..00000000
--- a/lib/pages/webview/webview_item_impel/webview_apple_item_impel.dart
+++ /dev/null
@@ -1,41 +0,0 @@
-import 'package:flutter/material.dart';
-import 'package:kazumi/pages/webview/webview_controller.dart';
-import 'package:flutter_modular/flutter_modular.dart';
-
-class WebviewAppleItemImpel extends StatefulWidget {
- const WebviewAppleItemImpel({super.key});
-
- @override
- State<WebviewAppleItemImpel> createState() => _WebviewAppleItemImpelState();
-}
-
-class _WebviewAppleItemImpelState extends State<WebviewAppleItemImpel> {
- final webviewAppleItemController = Modular.get<WebviewItemController>();
-
- @override
- void initState() {
- super.initState();
- webviewAppleItemController.init();
- }
-
- @override
- void dispose() {
- webviewAppleItemController.dispose();
- super.dispose();
- }
-
- @override
- Widget build(BuildContext context) {
- return Container(
- height: MediaQuery.of(context).size.width * 9.0 / (16.0),
- width: MediaQuery.of(context).size.width,
- color: Colors.black,
- child: const Center(
- child: Text(
- '此平台不支持Webview规则',
- style: TextStyle(color: Colors.white),
- ),
- ),
- );
- }
-}
diff --git a/lib/pages/webview/webview_item_impel/webview_item_impel.dart b/lib/pages/webview/webview_item_impel/webview_item_impel.dart
deleted file mode 100644
index 0459cc8a..00000000
--- a/lib/pages/webview/webview_item_impel/webview_item_impel.dart
+++ /dev/null
@@ -1,55 +0,0 @@
-import 'package:flutter/material.dart';
-import 'package:webview_flutter/webview_flutter.dart';
-import 'package:flutter_modular/flutter_modular.dart';
-import 'package:kazumi/pages/webview/webview_controller.dart';
-
-class WebviewItemImpel extends StatefulWidget {
- const WebviewItemImpel({super.key});
-
- @override
- State<WebviewItemImpel> createState() => _WebviewItemImpelState();
-}
-
-class _WebviewItemImpelState extends State<WebviewItemImpel> {
- final webviewItemController = Modular.get<WebviewItemController>();
-
- @override
- void initState() {
- super.initState();
- initPlatformState();
- }
-
- @override
- void dispose() {
- webviewItemController.dispose();
- super.dispose();
- }
-
- @override
- Widget build(BuildContext context) {
- return compositeView;
- }
-
- Future<void> initPlatformState() async {
- // 初始化Webview
- if (webviewItemController.webviewController == null) {
- await webviewItemController.init();
- }
- if (!mounted) return;
- setState(() {});
- }
-
- Widget get compositeView {
- if (webviewItemController.webviewController == null) {
- return const Text(
- 'Not Initialized',
- style: TextStyle(
- fontSize: 24.0,
- fontWeight: FontWeight.w900,
- ),
- );
- } else {
- return WebViewWidget(controller: webviewItemController.webviewController);
- }
- }
-}
diff --git a/lib/pages/webview/webview_item_impel/webview_linux_item_impel.dart b/lib/pages/webview/webview_item_impel/webview_linux_item_impel.dart
deleted file mode 100644
index f94a18ce..00000000
--- a/lib/pages/webview/webview_item_impel/webview_linux_item_impel.dart
+++ /dev/null
@@ -1,35 +0,0 @@
-import 'package:flutter/material.dart';
-import 'package:flutter_modular/flutter_modular.dart';
-import 'package:kazumi/pages/webview/webview_controller.dart';
-
-class WebviewLinuxItemImpel extends StatefulWidget {
- const WebviewLinuxItemImpel({super.key});
-
- @override
- State<WebviewLinuxItemImpel> createState() => _WebviewLinuxItemImpelState();
-}
-
-class _WebviewLinuxItemImpelState extends State<WebviewLinuxItemImpel> {
- final webviewLinuxItemController = Modular.get<WebviewItemController>();
-
- @override
- void initState() {
- super.initState();
- webviewLinuxItemController.init();
- }
-
- @override
- void dispose() {
- webviewLinuxItemController.dispose();
- super.dispose();
- }
-
- @override
- Widget build(BuildContext context) {
- return Container(
- height: MediaQuery.of(context).size.width * 9.0 / (16.0),
- width: MediaQuery.of(context).size.width,
- color: Colors.black,
- child: const Center(child: Text('此平台不支持Webview规则')));
- }
-}
diff --git a/lib/pages/webview/webview_item_impel/webview_windows_item_impel.dart b/lib/pages/webview/webview_item_impel/webview_windows_item_impel.dart
deleted file mode 100644
index e452cfef..00000000
--- a/lib/pages/webview/webview_item_impel/webview_windows_item_impel.dart
+++ /dev/null
@@ -1,75 +0,0 @@
-import 'dart:async';
-import 'package:flutter/material.dart';
-import 'package:webview_windows/webview_windows.dart';
-import 'package:flutter_modular/flutter_modular.dart';
-import 'package:window_manager/window_manager.dart';
-import 'package:kazumi/pages/video/video_controller.dart';
-import 'package:kazumi/pages/webview/webview_controller.dart';
-
-class WebviewWindowsItemImpel extends StatefulWidget {
- const WebviewWindowsItemImpel({super.key});
-
- @override
- State<WebviewWindowsItemImpel> createState() =>
- _WebviewWindowsItemImpelState();
-}
-
-class _WebviewWindowsItemImpelState extends State<WebviewWindowsItemImpel> {
- final List<StreamSubscription> _subscriptions = [];
- final webviewDesktopItemController = Modular.get<WebviewItemController>();
- final VideoPageController videoPageController =
- Modular.get<VideoPageController>();
-
- @override
- void initState() {
- super.initState();
- initPlatformState();
- }
-
- @override
- void dispose() {
- for (var s in _subscriptions) {
- try {
- s.cancel();
- } catch (_) {}
- }
- webviewDesktopItemController.dispose();
- super.dispose();
- }
-
- Future<void> initPlatformState() async {
- // 初始化Webview
- if (webviewDesktopItemController.webviewController == null) {
- await webviewDesktopItemController.init();
- }
- // 接受全屏事件
- _subscriptions.add(webviewDesktopItemController
- .webviewController.containsFullScreenElementChanged
- .listen((flag) {
- videoPageController.isFullscreen = flag;
- windowManager.setFullScreen(flag);
- }));
- if (!mounted) return;
-
- setState(() {});
- }
-
- Widget get compositeView {
- if (webviewDesktopItemController.webviewController == null) {
- return const Text(
- 'Not Initialized',
- style: TextStyle(
- fontSize: 24.0,
- fontWeight: FontWeight.w900,
- ),
- );
- } else {
- return Webview(webviewDesktopItemController.webviewController);
- }
- }
-
- @override
- Widget build(BuildContext context) {
- return compositeView;
- }
-}
diff --git a/lib/plugins/plugins.dart b/lib/plugins/plugins.dart
index 895212c3..05ea5275 100644
--- a/lib/plugins/plugins.dart
+++ b/lib/plugins/plugins.dart
@@ -263,6 +263,21 @@ class Plugin {
return resp.data.toString();
}
+ String buildFullUrl(String urlItem) {
+ if (urlItem.contains(baseUrl) ||
+ urlItem.contains(baseUrl.replaceAll('https', 'http'))) {
+ return urlItem;
+ }
+ return baseUrl + urlItem;
+ }
+
+ Map<String, String> buildHttpHeaders() {
+ return {
+ 'user-agent': userAgent.isEmpty ? Utils.getRandomUA() : userAgent,
+ if (referer.isNotEmpty) 'referer': referer,
+ };
+ }
+
PluginSearchResponse testQueryBangumi(String htmlString) {
List<SearchItem> searchItems = [];
var htmlElement = parse(htmlString).documentElement!;
diff --git a/lib/providers/providers.dart b/lib/providers/providers.dart
new file mode 100644
index 00000000..00d4dd1b
--- /dev/null
+++ b/lib/providers/providers.dart
@@ -0,0 +1,24 @@
+/// Video Source Provider 模块
+///
+/// 提供视频源解析的抽象层,支持:
+/// - WebView 在线解析
+///
+/// 使用示例:
+/// ```dart
+/// final provider = WebViewVideoSourceProvider();
+/// try {
+/// final source = await provider.resolve(
+/// episodeUrl,
+/// useLegacyParser: false,
+/// );
+/// print('Video URL: ${source.url}');
+/// } on VideoSourceTimeoutException {
+/// print('解析超时');
+/// } finally {
+/// provider.dispose();
+/// }
+/// ```
+library;
+
+export 'video_source_provider.dart';
+export 'webview_video_source_provider.dart';
diff --git a/lib/providers/video_source_provider.dart b/lib/providers/video_source_provider.dart
new file mode 100644
index 00000000..aea3c4a3
--- /dev/null
+++ b/lib/providers/video_source_provider.dart
@@ -0,0 +1,92 @@
+import 'dart:async';
+
+/// 视频源类型
+enum VideoSourceType {
+ /// 在线解析(WebView)
+ online,
+ /// 本地缓存
+ cached,
+}
+
+/// 视频源解析结果
+class VideoSource {
+ /// 视频 URL (M3U8/MP4/本地路径)
+ final String url;
+
+ /// 播放偏移量(秒)
+ final int offset;
+
+ /// 视频源类型
+ final VideoSourceType type;
+
+ const VideoSource({
+ required this.url,
+ required this.offset,
+ required this.type,
+ });
+
+ @override
+ String toString() => 'VideoSource(url: $url, offset: $offset, type: $type)';
+}
+
+/// 视频源未找到异常
+class VideoSourceNotFoundException implements Exception {
+ final String message;
+ const VideoSourceNotFoundException([this.message = 'Video source not found']);
+
+ @override
+ String toString() => 'VideoSourceNotFoundException: $message';
+}
+
+/// 视频源解析超时异常
+class VideoSourceTimeoutException implements Exception {
+ final Duration timeout;
+ const VideoSourceTimeoutException(this.timeout);
+
+ @override
+ String toString() => 'VideoSourceTimeoutException: Timed out after ${timeout.inSeconds}s';
+}
+
+/// 视频源解析取消异常
+class VideoSourceCancelledException implements Exception {
+ const VideoSourceCancelledException();
+
+ @override
+ String toString() => 'VideoSourceCancelledException: Resolution was cancelled';
+}
+
+/// 视频源提供者接口
+///
+/// 抽象视频源的获取方式,支持多种实现:
+/// - WebView 解析(在线)
+/// - 本地缓存读取
+/// - 组合策略(优先缓存,回退 WebView)
+abstract class IVideoSourceProvider {
+ /// 解析视频源 URL
+ ///
+ /// [episodeUrl] 集数页面 URL
+ /// [useLegacyParser] 是否使用旧版解析器(iframe 监听)
+ /// [offset] 播放偏移量(秒)
+ /// [timeout] 解析超时时间
+ ///
+ /// 返回 [VideoSource] 包含解析后的视频 URL 和元数据
+ ///
+ /// 可能抛出:
+ /// - [VideoSourceNotFoundException] 未找到视频源
+ /// - [VideoSourceTimeoutException] 解析超时
+ /// - [VideoSourceCancelledException] 解析被取消
+ Future<VideoSource> resolve(
+ String episodeUrl, {
+ required bool useLegacyParser,
+ int offset = 0,
+ Duration timeout = const Duration(seconds: 30),
+ });
+
+ /// 取消当前正在进行的解析
+ ///
+ /// 调用后,正在进行的 [resolve] 会抛出 [VideoSourceCancelledException]
+ void cancel();
+
+ /// 释放资源
+ void dispose();
+}
diff --git a/lib/providers/webview_video_source_provider.dart b/lib/providers/webview_video_source_provider.dart
new file mode 100644
index 00000000..8934094a
--- /dev/null
+++ b/lib/providers/webview_video_source_provider.dart
@@ -0,0 +1,106 @@
+import 'dart:async';
+
+import 'package:kazumi/webview/webview_controller.dart';
+import 'package:kazumi/providers/video_source_provider.dart';
+
+/// WebView 视频源提供者
+///
+/// 使用 WebView 解析视频页面,提取视频源 URL。
+/// WebView 实例在 Provider 生命周期内复用,切换集数时调用 unloadPage 释放页面资源,
+/// 仅在 [dispose] 时才真正销毁 WebView。
+class WebViewVideoSourceProvider implements IVideoSourceProvider {
+ WebviewItemController? _webview;
+ StreamSubscription? _subscription;
+ Completer<VideoSource>? _completer;
+ bool _isCancelled = false;
+
+ @override
+ Future<VideoSource> resolve(
+ String episodeUrl, {
+ required bool useLegacyParser,
+ int offset = 0,
+ Duration timeout = const Duration(seconds: 30),
+ }) async {
+ // 取消之前的解析(如果正在进行)
+ _cancelCurrentResolve();
+ _isCancelled = false;
+
+ // 复用或初始化 WebView
+ if (_webview == null) {
+ _webview = WebviewItemControllerFactory.getController();
+ await _webview!.init();
+ }
+
+ if (_isCancelled) {
+ throw const VideoSourceCancelledException();
+ }
+
+ _completer = Completer<VideoSource>();
+
+ try {
+ // 订阅视频源解析结果
+ _subscription = _webview!.onVideoURLParser.listen((event) {
+ if (_completer != null && !_completer!.isCompleted) {
+ _completer!.complete(VideoSource(
+ url: event.$1,
+ offset: event.$2,
+ type: VideoSourceType.online,
+ ));
+ }
+ });
+
+ // 加载 URL 并等待解析结果
+ // Provider 层始终以原生播放器模式解析(WebView 仅用于 URL 提取)
+ await _webview!.loadUrl(
+ episodeUrl,
+ true,
+ useLegacyParser,
+ offset: offset,
+ );
+
+ // 等待结果或超时
+ final result = await _completer!.future.timeout(
+ timeout,
+ onTimeout: () {
+ throw VideoSourceTimeoutException(timeout);
+ },
+ );
+
+ return result;
+ } catch (e) {
+ if (_isCancelled) {
+ throw const VideoSourceCancelledException();
+ }
+ rethrow;
+ } finally {
+ // 解析完成:取消订阅并卸载页面,但保留 WebView 实例
+ await _subscription?.cancel();
+ _subscription = null;
+ _completer = null;
+ await _webview?.unloadPage();
+ }
+ }
+
+ /// 取消当前正在进行的解析,但不销毁 WebView
+ void _cancelCurrentResolve() {
+ _isCancelled = true;
+ if (_completer != null && !_completer!.isCompleted) {
+ _completer!.completeError(const VideoSourceCancelledException());
+ }
+ _subscription?.cancel();
+ _subscription = null;
+ _completer = null;
+ }
+
+ @override
+ void cancel() {
+ _cancelCurrentResolve();
+ }
+
+ @override
+ void dispose() {
+ _cancelCurrentResolve();
+ _webview?.dispose();
+ _webview = null;
+ }
+}
diff --git a/lib/repositories/download_repository.dart b/lib/repositories/download_repository.dart
new file mode 100644
index 00000000..be42bfeb
--- /dev/null
+++ b/lib/repositories/download_repository.dart
@@ -0,0 +1,234 @@
+import 'package:kazumi/utils/storage.dart';
+import 'package:kazumi/modules/download/download_module.dart';
+import 'package:kazumi/utils/logger.dart';
+
+abstract class IDownloadRepository {
+ List<DownloadRecord> getAllRecords();
+ DownloadRecord? getRecord(String key);
+ Future<void> putRecord(DownloadRecord record);
+ Future<void> deleteRecord(String key);
+ Future<void> updateEpisode(String recordKey, int episodeNumber, DownloadEpisode episode);
+ Future<void> deleteEpisode(String recordKey, int episodeNumber);
+ bool getForceAdBlocker();
+
+ /// 获取指定番剧的下载记录
+ ///
+ /// [bangumiId] 番剧 ID
+ /// [pluginName] 插件名称
+ DownloadRecord? getRecordByBangumiId(int bangumiId, String pluginName);
+
+ /// 获取指定集数的下载信息
+ ///
+ /// [bangumiId] 番剧 ID
+ /// [pluginName] 插件名称
+ /// [episodeNumber] 集数编号
+ DownloadEpisode? getEpisode(int bangumiId, String pluginName, int episodeNumber);
+
+ /// 获取已完成下载的集数列表
+ ///
+ /// [bangumiId] 番剧 ID
+ /// [pluginName] 插件名称
+ /// 返回所有已完成下载的集数
+ List<DownloadEpisode> getCompletedEpisodes(int bangumiId, String pluginName);
+
+ /// 通过集数页面 URL 查找下载记录
+ ///
+ /// [bangumiId] 番剧 ID
+ /// [pluginName] 插件名称
+ /// [episodePageUrl] 集数页面 URL
+ /// 当 URL 为空时返回 null(兼容旧数据)
+ DownloadEpisode? getEpisodeByUrl(int bangumiId, String pluginName, String episodePageUrl);
+}
+
+class DownloadRepository implements IDownloadRepository {
+ final _downloadsBox = GStorage.downloads;
+
+ @override
+ List<DownloadRecord> getAllRecords() {
+ final List<DownloadRecord> result = [];
+ try {
+ for (final key in _downloadsBox.keys) {
+ try {
+ final record = _downloadsBox.get(key);
+ if (record != null) {
+ // Merge in-memory progress into the record
+ final cachedEpisodes = _progressCache[key as String];
+ if (cachedEpisodes != null) {
+ for (final entry in cachedEpisodes.entries) {
+ record.episodes[entry.key] = entry.value;
+ }
+ }
+ result.add(record);
+ }
+ } catch (e) {
+ // 单条记录读取失败,跳过该记录并记录日志
+ KazumiLogger().w('DownloadRepository: failed to read record key=$key, skipping', error: e);
+ }
+ }
+ } catch (e) {
+ KazumiLogger().w('DownloadRepository: get all records failed', error: e);
+ }
+ return result;
+ }
+
+ @override
+ DownloadRecord? getRecord(String key) {
+ try {
+ final record = _downloadsBox.get(key);
+ if (record != null) {
+ // Merge in-memory progress into the record
+ final cachedEpisodes = _progressCache[key];
+ if (cachedEpisodes != null) {
+ for (final entry in cachedEpisodes.entries) {
+ record.episodes[entry.key] = entry.value;
+ }
+ }
+ }
+ return record;
+ } catch (e) {
+ KazumiLogger().w('DownloadRepository: get record failed. key=$key', error: e);
+ return null;
+ }
+ }
+
+ @override
+ Future<void> putRecord(DownloadRecord record) async {
+ try {
+ await _downloadsBox.put(record.key, record);
+ await _downloadsBox.flush();
+ } catch (e, stackTrace) {
+ KazumiLogger().e(
+ 'DownloadRepository: put record failed. key=${record.key}',
+ error: e,
+ stackTrace: stackTrace,
+ );
+ rethrow;
+ }
+ }
+
+ @override
+ Future<void> deleteRecord(String key) async {
+ try {
+ await _downloadsBox.delete(key);
+ await _downloadsBox.flush();
+ } catch (e, stackTrace) {
+ KazumiLogger().e(
+ 'DownloadRepository: delete record failed. key=$key',
+ error: e,
+ stackTrace: stackTrace,
+ );
+ rethrow;
+ }
+ }
+
+ /// Track last persisted status to avoid unnecessary writes
+ final Map<String, int> _lastPersistedStatus = {};
+
+ /// In-memory cache for progress updates (not persisted until status changes)
+ final Map<String, Map<int, DownloadEpisode>> _progressCache = {};
+
+ @override
+ Future<void> updateEpisode(String recordKey, int episodeNumber, DownloadEpisode episode) async {
+ try {
+ // Update in-memory cache
+ _progressCache.putIfAbsent(recordKey, () => {});
+ _progressCache[recordKey]![episodeNumber] = episode;
+
+ // Only persist to Hive when status changes (not on every progress update)
+ // This dramatically reduces disk I/O and prevents corruption on crash
+ final statusKey = '${recordKey}_$episodeNumber';
+ final lastStatus = _lastPersistedStatus[statusKey];
+ final shouldPersist = lastStatus != episode.status;
+
+ if (shouldPersist) {
+ final record = _downloadsBox.get(recordKey);
+ if (record == null) return;
+ record.episodes[episodeNumber] = episode;
+ await _downloadsBox.put(recordKey, record);
+ await _downloadsBox.flush();
+ _lastPersistedStatus[statusKey] = episode.status;
+ }
+ } catch (e, stackTrace) {
+ KazumiLogger().e(
+ 'DownloadRepository: update episode failed. key=$recordKey, ep=$episodeNumber',
+ error: e,
+ stackTrace: stackTrace,
+ );
+ rethrow;
+ }
+ }
+
+ /// Get episode with in-memory progress if available
+ DownloadEpisode? getEpisodeWithProgress(String recordKey, int episodeNumber) {
+ // Check in-memory cache first
+ final cached = _progressCache[recordKey]?[episodeNumber];
+ if (cached != null) return cached;
+
+ // Fall back to Hive
+ final record = getRecord(recordKey);
+ return record?.episodes[episodeNumber];
+ }
+
+ @override
+ bool getForceAdBlocker() {
+ return GStorage.setting.get(SettingBoxKey.forceAdBlocker, defaultValue: false);
+ }
+
+ @override
+ Future<void> deleteEpisode(String recordKey, int episodeNumber) async {
+ try {
+ final record = _downloadsBox.get(recordKey);
+ if (record == null) return;
+ record.episodes.remove(episodeNumber);
+ if (record.episodes.isEmpty) {
+ await _downloadsBox.delete(recordKey);
+ } else {
+ await _downloadsBox.put(recordKey, record);
+ }
+ await _downloadsBox.flush();
+ } catch (e, stackTrace) {
+ KazumiLogger().e(
+ 'DownloadRepository: delete episode failed. key=$recordKey, ep=$episodeNumber',
+ error: e,
+ stackTrace: stackTrace,
+ );
+ rethrow;
+ }
+ }
+
+ @override
+ DownloadRecord? getRecordByBangumiId(int bangumiId, String pluginName) {
+ final key = '${pluginName}_$bangumiId';
+ return getRecord(key);
+ }
+
+ @override
+ DownloadEpisode? getEpisode(int bangumiId, String pluginName, int episodeNumber) {
+ final record = getRecordByBangumiId(bangumiId, pluginName);
+ return record?.episodes[episodeNumber];
+ }
+
+ @override
+ List<DownloadEpisode> getCompletedEpisodes(int bangumiId, String pluginName) {
+ final record = getRecordByBangumiId(bangumiId, pluginName);
+ if (record == null) return [];
+
+ return record.episodes.values
+ .where((e) => e.status == DownloadStatus.completed)
+ .toList()
+ ..sort((a, b) => a.episodeNumber.compareTo(b.episodeNumber));
+ }
+
+ @override
+ DownloadEpisode? getEpisodeByUrl(int bangumiId, String pluginName, String episodePageUrl) {
+ if (episodePageUrl.isEmpty) return null;
+ final record = getRecordByBangumiId(bangumiId, pluginName);
+ if (record == null) return null;
+ for (final episode in record.episodes.values) {
+ if (episode.episodePageUrl == episodePageUrl) {
+ return episode;
+ }
+ }
+ return null;
+ }
+}
diff --git a/lib/utils/download_manager.dart b/lib/utils/download_manager.dart
new file mode 100644
index 00000000..54228a7b
--- /dev/null
+++ b/lib/utils/download_manager.dart
@@ -0,0 +1,857 @@
+import 'dart:async';
+import 'dart:io';
+import 'package:dio/dio.dart';
+import 'package:kazumi/modules/download/download_module.dart';
+import 'package:kazumi/utils/m3u8_parser.dart';
+import 'package:kazumi/utils/m3u8_ad_filter.dart';
+import 'package:kazumi/utils/logger.dart';
+import 'package:kazumi/utils/storage.dart';
+import 'package:path_provider/path_provider.dart';
+
+class _NotM3u8Exception implements Exception {
+ final String message;
+ _NotM3u8Exception(this.message);
+ @override
+ String toString() => message;
+}
+
+class DownloadTask {
+ final String recordKey;
+ final int episodeNumber;
+ CancelToken cancelToken;
+ bool isPaused;
+
+ DownloadTask({
+ required this.recordKey,
+ required this.episodeNumber,
+ CancelToken? cancelToken,
+ this.isPaused = false,
+ }) : cancelToken = cancelToken ?? CancelToken();
+}
+
+typedef ProgressCallback = void Function(
+ String recordKey, int episodeNumber, DownloadEpisode episode, double speed);
+
+class DownloadRequest {
+ final String recordKey;
+ final int bangumiId;
+ final String pluginName;
+ final int episodeNumber;
+ final String m3u8Url;
+ final Map<String, String> httpHeaders;
+ final bool adBlockerEnabled;
+ final DownloadEpisode episode;
+
+ const DownloadRequest({
+ required this.recordKey,
+ required this.bangumiId,
+ required this.pluginName,
+ required this.episodeNumber,
+ required this.m3u8Url,
+ required this.httpHeaders,
+ required this.adBlockerEnabled,
+ required this.episode,
+ });
+}
+
+abstract class IDownloadManager {
+ ProgressCallback? onProgress;
+
+ bool isDownloading(String recordKey, int episodeNumber);
+ Future<void> enqueue(DownloadRequest request);
+ Future<void> enqueuePriority(DownloadRequest request);
+ void pause(String recordKey, int episodeNumber);
+ Future<void> resume(DownloadRequest request);
+ void cancel(String recordKey, int episodeNumber);
+ String? getLocalVideoPath(DownloadEpisode? episode);
+ Future<void> deleteEpisodeFiles(int bangumiId, String pluginName, int episodeNumber);
+ Future<void> deleteRecordFiles(int bangumiId, String pluginName);
+ double getSpeed(String recordKey, int episodeNumber);
+}
+
+/// Tracks download speed for a single episode
+class _SpeedTracker {
+ int _lastBytes = 0;
+ DateTime _lastTime = DateTime.now();
+ double currentSpeed = 0.0; // bytes/sec
+
+ void update(int totalBytes) {
+ final now = DateTime.now();
+ final elapsed = now.difference(_lastTime).inMilliseconds;
+ if (elapsed > 500) {
+ // Update speed every 500ms
+ final bytesDownloaded = totalBytes - _lastBytes;
+ currentSpeed = bytesDownloaded / (elapsed / 1000);
+ _lastBytes = totalBytes;
+ _lastTime = now;
+ }
+ }
+
+ void reset() {
+ _lastBytes = 0;
+ _lastTime = DateTime.now();
+ currentSpeed = 0.0;
+ }
+}
+
+class DownloadManager implements IDownloadManager {
+ DownloadManager() {
+ _loadSettings();
+ }
+
+ final Dio _dio = Dio(BaseOptions(
+ connectTimeout: const Duration(seconds: 15),
+ receiveTimeout: const Duration(seconds: 30),
+ ));
+
+ final Map<String, DownloadTask> _activeTasks = {};
+ final List<DownloadRequest> _queue = [];
+ final Map<String, _SpeedTracker> _speedTrackers = {};
+ int maxParallelEpisodes = 2;
+ int maxParallelSegments = 3;
+ int _runningCount = 0;
+
+ @override
+ ProgressCallback? onProgress;
+
+ void _loadSettings() {
+ final setting = GStorage.setting;
+ maxParallelEpisodes = setting.get(
+ SettingBoxKey.downloadParallelEpisodes,
+ defaultValue: 2,
+ );
+ maxParallelSegments = setting.get(
+ SettingBoxKey.downloadParallelSegments,
+ defaultValue: 3,
+ );
+ }
+
+ @override
+ double getSpeed(String recordKey, int episodeNumber) {
+ final key = _taskKey(recordKey, episodeNumber);
+ return _speedTrackers[key]?.currentSpeed ?? 0.0;
+ }
+
+ String _taskKey(String recordKey, int episodeNumber) =>
+ '${recordKey}_$episodeNumber';
+
+ @override
+ bool isDownloading(String recordKey, int episodeNumber) =>
+ _activeTasks.containsKey(_taskKey(recordKey, episodeNumber));
+
+ Future<String> get _downloadBaseDir async {
+ final appSupport = await getApplicationSupportDirectory();
+ return '${appSupport.path}/downloads';
+ }
+
+ String getEpisodeDir(String downloadBase, int bangumiId, String pluginName, int episodeNumber) {
+ return '$downloadBase/${bangumiId}_$pluginName/$episodeNumber';
+ }
+
+ @override
+ Future<void> enqueue(DownloadRequest request) async {
+ final key = _taskKey(request.recordKey, request.episodeNumber);
+ if (_activeTasks.containsKey(key)) return;
+
+ final task = DownloadTask(
+ recordKey: request.recordKey,
+ episodeNumber: request.episodeNumber,
+ );
+
+ if (_runningCount < maxParallelEpisodes) {
+ _runningCount++;
+ _activeTasks[key] = task;
+ _runEpisodeDownload(
+ task: task,
+ bangumiId: request.bangumiId,
+ pluginName: request.pluginName,
+ m3u8Url: request.m3u8Url,
+ httpHeaders: request.httpHeaders,
+ adBlockerEnabled: request.adBlockerEnabled,
+ episode: request.episode,
+ );
+ } else {
+ request.episode.status = DownloadStatus.pending;
+ _queue.add(request);
+ _activeTasks[key] = task;
+ }
+ }
+
+ @override
+ Future<void> enqueuePriority(DownloadRequest request) async {
+ final key = _taskKey(request.recordKey, request.episodeNumber);
+
+ // Remove from queue if already waiting
+ _queue.removeWhere(
+ (r) => r.recordKey == request.recordKey && r.episodeNumber == request.episodeNumber,
+ );
+ _activeTasks.remove(key);
+
+ final task = DownloadTask(
+ recordKey: request.recordKey,
+ episodeNumber: request.episodeNumber,
+ );
+
+ // Start immediately, bypassing the parallel limit (priority download)
+ _runningCount++;
+ _activeTasks[key] = task;
+ _runEpisodeDownload(
+ task: task,
+ bangumiId: request.bangumiId,
+ pluginName: request.pluginName,
+ m3u8Url: request.m3u8Url,
+ httpHeaders: request.httpHeaders,
+ adBlockerEnabled: request.adBlockerEnabled,
+ episode: request.episode,
+ );
+ }
+
+ @override
+ void pause(String recordKey, int episodeNumber) {
+ final key = _taskKey(recordKey, episodeNumber);
+ final task = _activeTasks[key];
+ if (task != null) {
+ task.isPaused = true;
+ task.cancelToken.cancel('paused');
+ }
+ }
+
+ @override
+ Future<void> resume(DownloadRequest request) async {
+ final key = _taskKey(request.recordKey, request.episodeNumber);
+ _activeTasks.remove(key);
+
+ final task = DownloadTask(
+ recordKey: request.recordKey,
+ episodeNumber: request.episodeNumber,
+ );
+ _activeTasks[key] = task;
+
+ if (_runningCount < maxParallelEpisodes) {
+ _runningCount++;
+ _runEpisodeDownload(
+ task: task,
+ bangumiId: request.bangumiId,
+ pluginName: request.pluginName,
+ m3u8Url: request.m3u8Url,
+ httpHeaders: request.httpHeaders,
+ adBlockerEnabled: request.adBlockerEnabled,
+ episode: request.episode,
+ );
+ } else {
+ _queue.add(request);
+ }
+ }
+
+ @override
+ void cancel(String recordKey, int episodeNumber) {
+ final key = _taskKey(recordKey, episodeNumber);
+ final task = _activeTasks[key];
+ if (task != null) {
+ task.cancelToken.cancel('cancelled');
+ _activeTasks.remove(key);
+ _queue.removeWhere(
+ (r) => r.recordKey == recordKey && r.episodeNumber == episodeNumber,
+ );
+ }
+ }
+
+ void _processQueue() {
+ while (_runningCount < maxParallelEpisodes && _queue.isNotEmpty) {
+ final request = _queue.removeAt(0);
+ final key = _taskKey(request.recordKey, request.episodeNumber);
+ final existingTask = _activeTasks[key];
+ if (existingTask == null || existingTask.isPaused || existingTask.cancelToken.isCancelled) {
+ _activeTasks.remove(key);
+ continue;
+ }
+
+ _runningCount++;
+ _runEpisodeDownload(
+ task: existingTask,
+ bangumiId: request.bangumiId,
+ pluginName: request.pluginName,
+ m3u8Url: request.m3u8Url,
+ httpHeaders: request.httpHeaders,
+ adBlockerEnabled: request.adBlockerEnabled,
+ episode: request.episode,
+ );
+ }
+ }
+
+ Future<void> _runEpisodeDownload({
+ required DownloadTask task,
+ required int bangumiId,
+ required String pluginName,
+ required String m3u8Url,
+ required Map<String, String> httpHeaders,
+ required bool adBlockerEnabled,
+ required DownloadEpisode episode,
+ }) async {
+ final key = _taskKey(task.recordKey, task.episodeNumber);
+ try {
+ // Step 1: Fetch M3U8 content
+ episode.status = DownloadStatus.downloading;
+ episode.networkM3u8Url = m3u8Url;
+ _notifyProgress(task.recordKey, task.episodeNumber, episode);
+
+ String m3u8Content;
+ try {
+ m3u8Content = await _fetchM3u8(m3u8Url, httpHeaders, task.cancelToken);
+ } on _NotM3u8Exception {
+ // URL is not an M3U8 playlist, fall back to direct file download
+ KazumiLogger().i(
+ 'DownloadManager: URL is not M3U8, falling back to direct file download '
+ 'for episode ${task.episodeNumber}',
+ );
+ await _runDirectFileDownload(
+ task: task,
+ bangumiId: bangumiId,
+ pluginName: pluginName,
+ videoUrl: m3u8Url,
+ httpHeaders: httpHeaders,
+ episode: episode,
+ );
+ return;
+ }
+
+ // Step 2: Parse M3U8
+ final type = M3u8Parser.detectType(m3u8Content);
+ String mediaM3u8Content = m3u8Content;
+ String mediaM3u8Url = m3u8Url;
+
+ if (type == M3u8Type.master) {
+ final master = M3u8Parser.parseMasterPlaylist(m3u8Content, m3u8Url);
+ final bestVariant = master.bestVariant;
+ mediaM3u8Url = bestVariant.uri;
+ mediaM3u8Content = await _fetchM3u8(mediaM3u8Url, httpHeaders, task.cancelToken);
+ }
+
+ final playlist = M3u8Parser.parseMediaPlaylist(mediaM3u8Content, mediaM3u8Url);
+
+ // 展开嵌套 m3u8 片段(部分源将实际内容嵌套在 m3u8 引用中)
+ final resolvedSegments = await M3u8Parser.resolveNestedSegments(
+ playlist.segments,
+ (url) => _fetchM3u8(url, httpHeaders, task.cancelToken),
+ );
+ final resolvedPlaylist = M3u8MediaPlaylist(
+ segments: resolvedSegments,
+ targetDuration: playlist.targetDuration,
+ isVod: playlist.isVod,
+ );
+
+ if (!resolvedPlaylist.isVod) {
+ episode.status = DownloadStatus.failed;
+ episode.errorMessage = '不支持下载直播流 (无有效分片)';
+ _notifyProgress(task.recordKey, task.episodeNumber, episode);
+ _onTaskComplete(key);
+ return;
+ }
+
+ if (resolvedPlaylist.segments.isEmpty) {
+ episode.status = DownloadStatus.failed;
+ episode.errorMessage = 'M3U8 中未找到可下载的分片';
+ _notifyProgress(task.recordKey, task.episodeNumber, episode);
+ _onTaskComplete(key);
+ return;
+ }
+
+ // Step 3: Ad filtering
+ List<M3u8Segment> segments = resolvedPlaylist.segments;
+ if (adBlockerEnabled) {
+ segments = M3u8AdFilter.filterAds(segments);
+ }
+
+ // Step 4: Create download directory
+ final base = await _downloadBaseDir;
+ final episodeDir = getEpisodeDir(base, bangumiId, pluginName, task.episodeNumber);
+ await Directory(episodeDir).create(recursive: true);
+ episode.downloadDirectory = episodeDir;
+
+ // Step 5: Download encryption keys
+ final keys = M3u8Parser.extractUniqueKeys(
+ M3u8MediaPlaylist(
+ segments: segments,
+ targetDuration: resolvedPlaylist.targetDuration,
+ isVod: true,
+ ),
+ );
+ final keyUriToLocal = <String, String>{};
+ for (int i = 0; i < keys.length; i++) {
+ final keyFile = 'key_$i.key';
+ final keyPath = '$episodeDir/$keyFile';
+ await _downloadFile(keys[i].uri, keyPath, httpHeaders, task.cancelToken);
+ keyUriToLocal[keys[i].uri] = keyFile;
+ }
+
+ // Step 6: Download TS segments
+ episode.totalSegments = segments.length;
+ episode.downloadedSegments = 0;
+ _notifyProgress(task.recordKey, task.episodeNumber, episode);
+
+ // Clean up .tmp files from previous incomplete downloads
+ final episodeDirObj = Directory(episodeDir);
+ if (await episodeDirObj.exists()) {
+ await for (final entity in episodeDirObj.list()) {
+ if (entity.path.endsWith('.tmp')) {
+ try {
+ await entity.delete();
+ } catch (_) {}
+ }
+ }
+ }
+
+ // Check which segments already exist (for resume)
+ final existingSegments = <int>{};
+ for (int i = 0; i < segments.length; i++) {
+ final segFile = File('$episodeDir/seg_${i.toString().padLeft(5, '0')}.ts');
+ if (await segFile.exists() && await segFile.length() > 0) {
+ existingSegments.add(i);
+ episode.downloadedSegments++;
+ }
+ }
+
+ // Download remaining segments with concurrency control
+ final pendingIndices = <int>[];
+ for (int i = 0; i < segments.length; i++) {
+ if (!existingSegments.contains(i)) {
+ pendingIndices.add(i);
+ }
+ }
+
+ int totalBytes = 0;
+ final completer = Completer<void>();
+ int completedCount = 0;
+ int failedCount = 0;
+ final semaphore = _Semaphore(maxParallelSegments);
+
+ // Initialize speed tracker for this episode
+ _speedTrackers[key] = _SpeedTracker();
+
+ if (pendingIndices.isEmpty) {
+ // All segments already downloaded
+ } else {
+ for (final idx in pendingIndices) {
+ if (task.isPaused || task.cancelToken.isCancelled) break;
+
+ await semaphore.acquire();
+ if (task.isPaused || task.cancelToken.isCancelled) {
+ semaphore.release();
+ break;
+ }
+
+ _downloadSegmentWithRetry(
+ segments[idx].uri,
+ '$episodeDir/seg_${idx.toString().padLeft(5, '0')}.ts',
+ httpHeaders,
+ task.cancelToken,
+ ).then((bytes) {
+ totalBytes += bytes;
+ episode.downloadedSegments++;
+ episode.totalBytes = totalBytes;
+ episode.progressPercent =
+ episode.downloadedSegments / episode.totalSegments;
+ // Update speed tracker
+ _speedTrackers[key]?.update(totalBytes);
+ _notifyProgress(task.recordKey, task.episodeNumber, episode);
+ completedCount++;
+ semaphore.release();
+ if (completedCount + failedCount == pendingIndices.length) {
+ completer.complete();
+ }
+ }).catchError((e) {
+ failedCount++;
+ semaphore.release();
+ if (completedCount + failedCount == pendingIndices.length) {
+ completer.complete();
+ }
+ });
+ }
+
+ if (!task.isPaused && !task.cancelToken.isCancelled && pendingIndices.isNotEmpty) {
+ await completer.future;
+ }
+ }
+
+ if (task.isPaused || task.cancelToken.isCancelled) {
+ if (task.isPaused) {
+ episode.status = DownloadStatus.paused;
+ }
+ _notifyProgress(task.recordKey, task.episodeNumber, episode);
+ _onTaskComplete(key);
+ return;
+ }
+
+ if (failedCount > 0) {
+ episode.status = DownloadStatus.failed;
+ episode.errorMessage = '$failedCount 个分片下载失败';
+ _notifyProgress(task.recordKey, task.episodeNumber, episode);
+ _onTaskComplete(key);
+ return;
+ }
+
+ // Step 7: Write local M3U8
+ final targetDuration = adBlockerEnabled
+ ? M3u8AdFilter.calculateTargetDuration(segments)
+ : resolvedPlaylist.targetDuration;
+ final localM3u8 = M3u8Parser.buildLocalM3u8(
+ segments,
+ targetDuration: targetDuration,
+ keyUriToLocal: keyUriToLocal,
+ );
+ final m3u8Path = '$episodeDir/playlist.m3u8';
+ await File(m3u8Path).writeAsString(localM3u8);
+
+ // Step 8: Mark completed
+ episode.status = DownloadStatus.completed;
+ episode.localM3u8Path = m3u8Path;
+ episode.progressPercent = 1.0;
+ episode.completedAt = DateTime.now();
+ _notifyProgress(task.recordKey, task.episodeNumber, episode);
+
+ KazumiLogger().i(
+ 'DownloadManager: episode ${task.episodeNumber} completed. '
+ '${segments.length} segments, ${(totalBytes / 1024 / 1024).toStringAsFixed(1)} MB',
+ );
+ } on DioException catch (e) {
+ if (e.type == DioExceptionType.cancel) {
+ if (task.isPaused) {
+ episode.status = DownloadStatus.paused;
+ }
+ } else {
+ episode.status = DownloadStatus.failed;
+ episode.errorMessage = e.message ?? '网络错误';
+ }
+ _notifyProgress(task.recordKey, task.episodeNumber, episode);
+ } catch (e) {
+ episode.status = DownloadStatus.failed;
+ episode.errorMessage = e.toString();
+ _notifyProgress(task.recordKey, task.episodeNumber, episode);
+ KazumiLogger().e('DownloadManager: episode download failed', error: e);
+ } finally {
+ _onTaskComplete(key);
+ }
+ }
+
+ /// Download a direct video file (non-M3U8) with resume support
+ Future<void> _runDirectFileDownload({
+ required DownloadTask task,
+ required int bangumiId,
+ required String pluginName,
+ required String videoUrl,
+ required Map<String, String> httpHeaders,
+ required DownloadEpisode episode,
+ }) async {
+ final key = _taskKey(task.recordKey, task.episodeNumber);
+ try {
+ final base = await _downloadBaseDir;
+ final episodeDir = getEpisodeDir(base, bangumiId, pluginName, task.episodeNumber);
+ await Directory(episodeDir).create(recursive: true);
+ episode.downloadDirectory = episodeDir;
+
+ final filePath = '$episodeDir/video.mp4';
+ final tmpPath = '$filePath.tmp';
+
+ // Check for existing partial download (for resume)
+ // For direct downloads, .tmp files contain valid partial data and can be resumed
+ int existingBytes = 0;
+ final tmpFile = File(tmpPath);
+ if (await tmpFile.exists()) {
+ existingBytes = await tmpFile.length();
+ }
+
+ episode.totalSegments = 1;
+ episode.downloadedSegments = 0;
+ _notifyProgress(task.recordKey, task.episodeNumber, episode);
+
+ // Use stream response for resume support
+ final requestHeaders = Map<String, String>.from(httpHeaders);
+ bool useRange = existingBytes > 0;
+ if (useRange) {
+ requestHeaders['Range'] = 'bytes=$existingBytes-';
+ }
+
+ Response<ResponseBody> response;
+ try {
+ response = await _dio.get<ResponseBody>(
+ videoUrl,
+ options: Options(
+ headers: requestHeaders,
+ responseType: ResponseType.stream,
+ receiveTimeout: const Duration(minutes: 30),
+ ),
+ cancelToken: task.cancelToken,
+ );
+ } on DioException catch (e) {
+ // Handle 416 Range Not Satisfiable - delete local file and retry without Range
+ if (e.response?.statusCode == 416 && useRange) {
+ KazumiLogger().w(
+ 'DownloadManager: 416 Range Not Satisfiable, deleting tmp file and retrying',
+ );
+ await tmpFile.delete();
+ existingBytes = 0;
+ requestHeaders.remove('Range');
+ response = await _dio.get<ResponseBody>(
+ videoUrl,
+ options: Options(
+ headers: requestHeaders,
+ responseType: ResponseType.stream,
+ receiveTimeout: const Duration(minutes: 30),
+ ),
+ cancelToken: task.cancelToken,
+ );
+ } else {
+ rethrow;
+ }
+ }
+
+ // Parse total size from Content-Range or Content-Length
+ final contentRange = response.headers.value('content-range');
+ final contentLength = int.tryParse(
+ response.headers.value(Headers.contentLengthHeader) ?? '') ?? 0;
+ int totalSize;
+ if (contentRange != null) {
+ // Format: "bytes start-end/total"
+ final totalMatch = RegExp(r'/(\d+)').firstMatch(contentRange);
+ totalSize = totalMatch != null ? int.parse(totalMatch.group(1)!) : 0;
+ } else {
+ totalSize = existingBytes + contentLength;
+ }
+
+ final raf = await tmpFile.open(
+ mode: existingBytes > 0 ? FileMode.append : FileMode.write);
+ int received = existingBytes;
+
+ // Initialize speed tracker for direct file download
+ _speedTrackers[key] = _SpeedTracker();
+
+ try {
+ await for (final chunk in response.data!.stream) {
+ if (task.isPaused || task.cancelToken.isCancelled) break;
+ await raf.writeFrom(chunk);
+ received += chunk.length;
+ episode.totalBytes = received;
+ episode.progressPercent = totalSize > 0 ? received / totalSize : 0;
+ // Update speed tracker
+ _speedTrackers[key]?.update(received);
+ _notifyProgress(task.recordKey, task.episodeNumber, episode);
+ }
+ } finally {
+ await raf.close();
+ }
+
+ if (task.isPaused || task.cancelToken.isCancelled) {
+ if (task.isPaused) {
+ episode.status = DownloadStatus.paused;
+ }
+ _notifyProgress(task.recordKey, task.episodeNumber, episode);
+ _onTaskComplete(key);
+ return;
+ }
+
+ // Rename .tmp to final path
+ await File(tmpPath).rename(filePath);
+
+ // Mark completed
+ episode.status = DownloadStatus.completed;
+ episode.localM3u8Path = filePath;
+ episode.downloadedSegments = 1;
+ episode.progressPercent = 1.0;
+ episode.completedAt = DateTime.now();
+ episode.totalBytes = await File(filePath).length();
+ _notifyProgress(task.recordKey, task.episodeNumber, episode);
+
+ KazumiLogger().i(
+ 'DownloadManager: episode ${task.episodeNumber} completed (direct download). '
+ '${(episode.totalBytes / 1024 / 1024).toStringAsFixed(1)} MB',
+ );
+ } on DioException catch (e) {
+ if (e.type == DioExceptionType.cancel) {
+ if (task.isPaused) {
+ episode.status = DownloadStatus.paused;
+ }
+ } else {
+ episode.status = DownloadStatus.failed;
+ episode.errorMessage = e.message ?? '网络错误';
+ }
+ _notifyProgress(task.recordKey, task.episodeNumber, episode);
+ } catch (e) {
+ episode.status = DownloadStatus.failed;
+ episode.errorMessage = e.toString();
+ _notifyProgress(task.recordKey, task.episodeNumber, episode);
+ KazumiLogger().e('DownloadManager: direct file download failed', error: e);
+ } finally {
+ _onTaskComplete(key);
+ }
+ }
+
+ void _onTaskComplete(String key) {
+ _activeTasks.remove(key);
+ _speedTrackers.remove(key);
+ _runningCount--;
+ _processQueue();
+ }
+
+ void _notifyProgress(
+ String recordKey, int episodeNumber, DownloadEpisode episode) {
+ final key = _taskKey(recordKey, episodeNumber);
+ final speed = _speedTrackers[key]?.currentSpeed ?? 0.0;
+ onProgress?.call(recordKey, episodeNumber, episode, speed);
+ }
+
+ Future<String> _fetchM3u8(
+ String url, Map<String, String> headers, CancelToken cancelToken) async {
+ // Use a separate CancelToken to abort large non-M3U8 responses
+ // without cancelling the entire download task
+ final fetchToken = CancelToken();
+
+ // Forward cancellation from the task's main token
+ if (cancelToken.isCancelled) {
+ throw DioException(
+ type: DioExceptionType.cancel,
+ requestOptions: RequestOptions(path: url),
+ );
+ }
+
+ try {
+ final response = await _dio.get<String>(
+ url,
+ options: Options(
+ headers: headers,
+ responseType: ResponseType.plain,
+ receiveTimeout: const Duration(seconds: 15),
+ ),
+ cancelToken: fetchToken,
+ onReceiveProgress: (received, total) {
+ // Check if parent task was cancelled
+ if (cancelToken.isCancelled) {
+ fetchToken.cancel('task cancelled');
+ return;
+ }
+ // Abort if response is too large (> 2MB, definitely not M3U8)
+ if (received > 2 * 1024 * 1024) {
+ fetchToken.cancel('too large');
+ }
+ },
+ );
+
+ final content = response.data!;
+
+ // Validate M3U8 content
+ final trimmed = content.trimLeft();
+ if (!trimmed.startsWith('#EXTM3U')) {
+ throw _NotM3u8Exception('URL 不是 M3U8 播放列表');
+ }
+
+ return content;
+ } on DioException catch (e) {
+ // Re-throw if the main task was cancelled/paused
+ if (cancelToken.isCancelled) rethrow;
+ // fetchToken cancelled due to too-large response
+ if (e.type == DioExceptionType.cancel) {
+ throw _NotM3u8Exception('响应过大,非 M3U8 播放列表');
+ }
+ rethrow;
+ }
+ }
+
+ Future<void> _downloadFile(String url, String savePath,
+ Map<String, String> headers, CancelToken cancelToken) async {
+ await _dio.download(
+ url,
+ savePath,
+ options: Options(headers: headers),
+ cancelToken: cancelToken,
+ );
+ }
+
+ Future<int> _downloadSegmentWithRetry(
+ String url,
+ String savePath,
+ Map<String, String> headers,
+ CancelToken cancelToken, {
+ int maxRetries = 3,
+ }) async {
+ final tmpPath = '$savePath.tmp';
+ int retryCount = 0;
+ while (true) {
+ try {
+ await _dio.download(
+ url,
+ tmpPath,
+ options: Options(headers: headers),
+ cancelToken: cancelToken,
+ );
+ await File(tmpPath).rename(savePath);
+ return await File(savePath).length();
+ } catch (e) {
+ // Clean up incomplete .tmp file on failure
+ try {
+ final tmpFile = File(tmpPath);
+ if (await tmpFile.exists()) await tmpFile.delete();
+ } catch (_) {}
+ if (cancelToken.isCancelled) rethrow;
+ retryCount++;
+ if (retryCount >= maxRetries) rethrow;
+ final delay = Duration(seconds: [1, 3, 9][retryCount - 1]);
+ await Future.delayed(delay);
+ }
+ }
+ }
+
+ @override
+ Future<void> deleteEpisodeFiles(
+ int bangumiId, String pluginName, int episodeNumber) async {
+ final base = await _downloadBaseDir;
+ final dir = Directory(getEpisodeDir(base, bangumiId, pluginName, episodeNumber));
+ if (await dir.exists()) {
+ await dir.delete(recursive: true);
+ }
+ }
+
+ @override
+ Future<void> deleteRecordFiles(int bangumiId, String pluginName) async {
+ final base = await _downloadBaseDir;
+ final dir = Directory('$base/${bangumiId}_$pluginName');
+ if (await dir.exists()) {
+ await dir.delete(recursive: true);
+ }
+ }
+
+ @override
+ String? getLocalVideoPath(DownloadEpisode? episode) {
+ if (episode == null) return null;
+ if (episode.status != DownloadStatus.completed) return null;
+ if (episode.localM3u8Path.isEmpty) return null;
+ final file = File(episode.localM3u8Path);
+ if (!file.existsSync()) return null;
+ return episode.localM3u8Path;
+ }
+}
+
+class _Semaphore {
+ final int maxCount;
+ int _currentCount = 0;
+ final _waitQueue = <Completer<void>>[];
+
+ _Semaphore(this.maxCount);
+
+ Future<void> acquire() async {
+ if (_currentCount < maxCount) {
+ _currentCount++;
+ return;
+ }
+ final completer = Completer<void>();
+ _waitQueue.add(completer);
+ return completer.future;
+ }
+
+ void release() {
+ if (_waitQueue.isNotEmpty) {
+ final completer = _waitQueue.removeAt(0);
+ completer.complete();
+ } else {
+ _currentCount--;
+ }
+ }
+}
diff --git a/lib/utils/m3u8_ad_filter.dart b/lib/utils/m3u8_ad_filter.dart
new file mode 100644
index 00000000..93784ec8
--- /dev/null
+++ b/lib/utils/m3u8_ad_filter.dart
@@ -0,0 +1,86 @@
+import 'package:kazumi/utils/m3u8_parser.dart';
+
+class M3u8AdFilter {
+ /// Filter ad segments from a media playlist.
+ /// Mimics FFmpeg hls_ad_filter behavior using discontinuity groups.
+ static List<M3u8Segment> filterAds(List<M3u8Segment> segments) {
+ if (segments.isEmpty) return segments;
+
+ // Group segments by discontinuityGroup
+ final groups = <int, List<M3u8Segment>>{};
+ for (final seg in segments) {
+ groups.putIfAbsent(seg.discontinuityGroup, () => []);
+ groups[seg.discontinuityGroup]!.add(seg);
+ }
+
+ // Only one group means no ads detected
+ if (groups.length <= 1) return segments;
+
+ // Calculate total duration per group
+ final groupDurations = <int, double>{};
+ for (final entry in groups.entries) {
+ groupDurations[entry.key] = entry.value.fold<double>(
+ 0.0,
+ (sum, seg) => sum + seg.duration,
+ );
+ }
+
+ // Find the longest group as the "main content" reference
+ double maxDuration = 0;
+ for (final d in groupDurations.values) {
+ if (d > maxDuration) maxDuration = d;
+ }
+
+ // Identify ad groups
+ final adGroups = <int>{};
+ final sortedKeys = groups.keys.toList()..sort();
+
+ for (final groupId in sortedKeys) {
+ final groupDuration = groupDurations[groupId]!;
+
+ // Skip the main content group
+ if (groupDuration == maxDuration) continue;
+
+ bool isAd = false;
+
+ // Short segments relative to main content (< 30%)
+ if (groupDuration < maxDuration * 0.3) {
+ isAd = true;
+ }
+
+ // First or last group with short duration (< 30s)
+ if ((groupId == sortedKeys.first || groupId == sortedKeys.last) &&
+ groupDuration < 30.0) {
+ isAd = true;
+ }
+
+ // Very short segments (< 10s) are almost certainly ads
+ if (groupDuration < 10.0) {
+ isAd = true;
+ }
+
+ if (isAd) {
+ adGroups.add(groupId);
+ }
+ }
+
+ if (adGroups.isEmpty) return segments;
+
+ // Remove ad segments
+ return segments
+ .where((seg) => !adGroups.contains(seg.discontinuityGroup))
+ .toList();
+ }
+
+ /// Calculate the new target duration after filtering
+ static double calculateTargetDuration(List<M3u8Segment> segments) {
+ if (segments.isEmpty) return 0;
+ double maxSegDuration = 0;
+ for (final seg in segments) {
+ if (seg.duration > maxSegDuration) {
+ maxSegDuration = seg.duration;
+ }
+ }
+ return maxSegDuration;
+ }
+}
diff --git a/lib/utils/m3u8_parser.dart b/lib/utils/m3u8_parser.dart
new file mode 100644
index 00000000..56b9faf5
--- /dev/null
+++ b/lib/utils/m3u8_parser.dart
@@ -0,0 +1,326 @@
+class M3u8Key {
+ final String method;
+ final String uri;
+ final String? iv;
+
+ M3u8Key({required this.method, required this.uri, this.iv});
+
+ @override
+ bool operator ==(Object other) =>
+ identical(this, other) ||
+ other is M3u8Key &&
+ method == other.method &&
+ uri == other.uri &&
+ iv == other.iv;
+
+ @override
+ int get hashCode => Object.hash(method, uri, iv);
+
+ @override
+ String toString() {
+ final sb = StringBuffer('#EXT-X-KEY:METHOD=$method,URI="$uri"');
+ if (iv != null) {
+ sb.write(',IV=$iv');
+ }
+ return sb.toString();
+ }
+}
+
+class M3u8Segment {
+ final double duration;
+ final String uri;
+ final int discontinuityGroup;
+ final M3u8Key? key;
+
+ M3u8Segment({
+ required this.duration,
+ required this.uri,
+ required this.discontinuityGroup,
+ this.key,
+ });
+}
+
+class M3u8Variant {
+ final int bandwidth;
+ final String? resolution;
+ final String uri;
+
+ M3u8Variant({required this.bandwidth, this.resolution, required this.uri});
+}
+
+class M3u8MasterPlaylist {
+ final List<M3u8Variant> variants;
+
+ M3u8MasterPlaylist({required this.variants});
+
+ M3u8Variant get bestVariant {
+ return variants.reduce((a, b) => a.bandwidth > b.bandwidth ? a : b);
+ }
+}
+
+class M3u8MediaPlaylist {
+ final List<M3u8Segment> segments;
+ final double targetDuration;
+ final bool isVod;
+
+ M3u8MediaPlaylist({
+ required this.segments,
+ required this.targetDuration,
+ required this.isVod,
+ });
+}
+
+enum M3u8Type { master, media }
+
+class M3u8Parser {
+ static M3u8Type detectType(String content) {
+ if (content.contains('#EXT-X-STREAM-INF')) {
+ return M3u8Type.master;
+ }
+ return M3u8Type.media;
+ }
+
+ static String resolveUrl(String baseUrl, String relativeUrl) {
+ if (relativeUrl.startsWith('http://') || relativeUrl.startsWith('https://')) {
+ return relativeUrl;
+ }
+ final baseUri = Uri.parse(baseUrl);
+ if (relativeUrl.startsWith('/')) {
+ return '${baseUri.scheme}://${baseUri.host}${baseUri.hasPort ? ':${baseUri.port}' : ''}$relativeUrl';
+ }
+ final basePath = baseUrl.substring(0, baseUrl.lastIndexOf('/') + 1);
+ return '$basePath$relativeUrl';
+ }
+
+ static M3u8MasterPlaylist parseMasterPlaylist(String content, String baseUrl) {
+ final lines = content.split('\n').map((l) => l.trim()).toList();
+ final variants = <M3u8Variant>[];
+
+ for (int i = 0; i < lines.length; i++) {
+ final line = lines[i];
+ if (line.startsWith('#EXT-X-STREAM-INF:')) {
+ final attrs = line.substring('#EXT-X-STREAM-INF:'.length);
+ int bandwidth = 0;
+ String? resolution;
+
+ final bandwidthMatch = RegExp(r'BANDWIDTH=(\d+)').firstMatch(attrs);
+ if (bandwidthMatch != null) {
+ bandwidth = int.parse(bandwidthMatch.group(1)!);
+ }
+
+ final resolutionMatch = RegExp(r'RESOLUTION=([^\s,]+)').firstMatch(attrs);
+ if (resolutionMatch != null) {
+ resolution = resolutionMatch.group(1);
+ }
+
+ if (i + 1 < lines.length && !lines[i + 1].startsWith('#')) {
+ final uri = resolveUrl(baseUrl, lines[i + 1]);
+ variants.add(M3u8Variant(bandwidth: bandwidth, resolution: resolution, uri: uri));
+ }
+ }
+ }
+
+ return M3u8MasterPlaylist(variants: variants);
+ }
+
+ static M3u8MediaPlaylist parseMediaPlaylist(String content, String baseUrl) {
+ final lines = content.split('\n').map((l) => l.trim()).toList();
+ final segments = <M3u8Segment>[];
+ double targetDuration = 0;
+ bool hasEndList = false;
+ bool isExplicitVod = false;
+ bool isLiveEvent = false;
+ int currentDiscontinuityGroup = 0;
+ M3u8Key? currentKey;
+ double currentDuration = 0;
+
+ for (int i = 0; i < lines.length; i++) {
+ final line = lines[i];
+
+ if (line.startsWith('#EXT-X-TARGETDURATION:')) {
+ targetDuration = double.parse(line.substring('#EXT-X-TARGETDURATION:'.length));
+ } else if (line == '#EXT-X-ENDLIST') {
+ hasEndList = true;
+ } else if (line == '#EXT-X-PLAYLIST-TYPE:VOD') {
+ isExplicitVod = true;
+ } else if (line == '#EXT-X-PLAYLIST-TYPE:EVENT') {
+ isLiveEvent = true;
+ } else if (line == '#EXT-X-DISCONTINUITY') {
+ currentDiscontinuityGroup++;
+ } else if (line.startsWith('#EXT-X-KEY:')) {
+ currentKey = _parseKey(line, baseUrl);
+ } else if (line.startsWith('#EXTINF:')) {
+ final durationStr = line.substring('#EXTINF:'.length).split(',')[0];
+ currentDuration = double.parse(durationStr);
+ } else if (line.isNotEmpty && !line.startsWith('#')) {
+ final uri = resolveUrl(baseUrl, line);
+ segments.add(M3u8Segment(
+ duration: currentDuration,
+ uri: uri,
+ discontinuityGroup: currentDiscontinuityGroup,
+ key: currentKey,
+ ));
+ currentDuration = 0;
+ }
+ }
+
+ // Consider it VOD if:
+ // 1. Has #EXT-X-ENDLIST, or
+ // 2. Has #EXT-X-PLAYLIST-TYPE:VOD, or
+ // 3. Has finite segments and is not explicitly a live EVENT stream.
+ // Many third-party video sources omit #EXT-X-ENDLIST for VOD content.
+ final bool isVod = hasEndList || isExplicitVod || (!isLiveEvent && segments.isNotEmpty);
+
+ return M3u8MediaPlaylist(
+ segments: segments,
+ targetDuration: targetDuration,
+ isVod: isVod,
+ );
+ }
+
+ static M3u8Key? _parseKey(String line, String baseUrl) {
+ final attrs = line.substring('#EXT-X-KEY:'.length);
+
+ final methodMatch = RegExp(r'METHOD=([^,]+)').firstMatch(attrs);
+ final method = methodMatch?.group(1) ?? 'NONE';
+
+ if (method == 'NONE') return null;
+
+ final uriMatch = RegExp(r'URI="([^"]+)"').firstMatch(attrs);
+ final uri = uriMatch != null ? resolveUrl(baseUrl, uriMatch.group(1)!) : '';
+
+ final ivMatch = RegExp(r'IV=(0x[0-9a-fA-F]+)').firstMatch(attrs);
+ final iv = ivMatch?.group(1);
+
+ return M3u8Key(method: method, uri: uri, iv: iv);
+ }
+
+ static List<M3u8Key> extractUniqueKeys(M3u8MediaPlaylist playlist) {
+ final seen = <String>{};
+ final keys = <M3u8Key>[];
+ for (final seg in playlist.segments) {
+ if (seg.key != null && !seen.contains(seg.key!.uri)) {
+ seen.add(seg.key!.uri);
+ keys.add(seg.key!);
+ }
+ }
+ return keys;
+ }
+
+ static String buildLocalM3u8(
+ List<M3u8Segment> segments, {
+ required double targetDuration,
+ Map<String, String> keyUriToLocal = const {},
+ }) {
+ final sb = StringBuffer();
+ sb.writeln('#EXTM3U');
+ sb.writeln('#EXT-X-VERSION:3');
+ sb.writeln('#EXT-X-TARGETDURATION:${targetDuration.ceil()}');
+ sb.writeln('#EXT-X-MEDIA-SEQUENCE:0');
+
+ int lastDiscontinuityGroup = 0;
+ M3u8Key? lastKey;
+
+ for (int i = 0; i < segments.length; i++) {
+ final seg = segments[i];
+
+ if (seg.discontinuityGroup != lastDiscontinuityGroup && i > 0) {
+ sb.writeln('#EXT-X-DISCONTINUITY');
+ lastDiscontinuityGroup = seg.discontinuityGroup;
+ }
+
+ if (seg.key != lastKey) {
+ if (seg.key == null) {
+ sb.writeln('#EXT-X-KEY:METHOD=NONE');
+ } else {
+ final localUri = keyUriToLocal[seg.key!.uri] ?? seg.key!.uri;
+ final keySb = StringBuffer('#EXT-X-KEY:METHOD=${seg.key!.method},URI="$localUri"');
+ if (seg.key!.iv != null) {
+ keySb.write(',IV=${seg.key!.iv}');
+ }
+ sb.writeln(keySb.toString());
+ }
+ lastKey = seg.key;
+ }
+
+ sb.writeln('#EXTINF:${seg.duration.toStringAsFixed(6)},');
+ sb.writeln('seg_${i.toString().padLeft(5, '0')}.ts');
+ }
+
+ sb.writeln('#EXT-X-ENDLIST');
+ return sb.toString();
+ }
+
+ static bool _isM3u8Url(String url) {
+ final path = Uri.parse(url).path.toLowerCase();
+ return path.endsWith('.m3u8');
+ }
+
+ /// 展开嵌套 M3U8 片段。
+ /// [fetcher] 异步回调,给定 URL 返回 M3U8 文本内容。
+ /// [maxDepth] 递归深度上限,防止无限嵌套。
+ static Future<List<M3u8Segment>> resolveNestedSegments(
+ List<M3u8Segment> segments,
+ Future<String> Function(String url) fetcher, {
+ int maxDepth = 3,
+ }) async {
+ if (maxDepth <= 0) return segments;
+ if (!segments.any((s) => _isM3u8Url(s.uri))) return segments;
+
+ final result = <M3u8Segment>[];
+ int groupOffset = 0;
+
+ for (final seg in segments) {
+ if (!_isM3u8Url(seg.uri)) {
+ result.add(M3u8Segment(
+ duration: seg.duration,
+ uri: seg.uri,
+ discontinuityGroup: seg.discontinuityGroup + groupOffset,
+ key: seg.key,
+ ));
+ continue;
+ }
+
+ // 该 segment 的 URI 指向嵌套 m3u8,展开
+ try {
+ final content = await fetcher(seg.uri);
+ final nested = parseMediaPlaylist(content, seg.uri);
+ final resolved = await resolveNestedSegments(
+ nested.segments, fetcher, maxDepth: maxDepth - 1,
+ );
+
+ if (resolved.isEmpty) continue;
+
+ final nestedBase = seg.discontinuityGroup + groupOffset;
+ int maxNestedGroup = 0;
+ for (final ns in resolved) {
+ if (ns.discontinuityGroup > maxNestedGroup) {
+ maxNestedGroup = ns.discontinuityGroup;
+ }
+ }
+
+ for (final ns in resolved) {
+ result.add(M3u8Segment(
+ duration: ns.duration,
+ uri: ns.uri,
+ discontinuityGroup: ns.discontinuityGroup + nestedBase,
+ key: ns.key,
+ ));
+ }
+
+ // 后续 segment 的 group 需要额外偏移,避免碰撞
+ groupOffset += maxNestedGroup;
+ } catch (e) {
+ // 获取/解析失败,保留原始 segment
+ result.add(M3u8Segment(
+ duration: seg.duration,
+ uri: seg.uri,
+ discontinuityGroup: seg.discontinuityGroup + groupOffset,
+ key: seg.key,
+ ));
+ }
+ }
+
+ return result;
+ }
+}
diff --git a/lib/utils/storage.dart b/lib/utils/storage.dart
index cfba132f..6df7b725 100644
--- a/lib/utils/storage.dart
+++ b/lib/utils/storage.dart
@@ -8,6 +8,7 @@ import 'package:kazumi/modules/history/history_module.dart';
import 'package:kazumi/modules/collect/collect_module.dart';
import 'package:kazumi/modules/collect/collect_change_module.dart';
import 'package:kazumi/modules/search/search_history_module.dart';
+import 'package:kazumi/modules/download/download_module.dart';
class GStorage {
/// Don't use favorites box, it's replaced by collectibles.
@@ -18,8 +19,14 @@ class GStorage {
static late Box<String> shieldList;
static late final Box<dynamic> setting;
static late Box<SearchHistory> searchHistory;
+ static late Box<DownloadRecord> downloads;
+
+ /// Hive directory path, initialized during init()
+ static String? _hivePath;
static Future init() async {
+ _hivePath = '${(await getApplicationSupportDirectory()).path}/hive';
+
Hive.registerAdapter(BangumiItemAdapter());
Hive.registerAdapter(BangumiTagAdapter());
Hive.registerAdapter(CollectedBangumiAdapter());
@@ -27,13 +34,62 @@ class GStorage {
Hive.registerAdapter(HistoryAdapter());
Hive.registerAdapter(CollectedBangumiChangeAdapter());
Hive.registerAdapter(SearchHistoryAdapter());
- favorites = await Hive.openBox('favorites');
- collectibles = await Hive.openBox('collectibles');
- histories = await Hive.openBox('histories');
- setting = await Hive.openBox('setting');
- collectChanges = await Hive.openBox('collectchanges');
- shieldList = await Hive.openBox('shieldList');
- searchHistory = await Hive.openBox('searchHistory');
+ Hive.registerAdapter(DownloadRecordAdapter());
+ Hive.registerAdapter(DownloadEpisodeAdapter());
+
+ // Open each box with automatic recovery on corruption
+ favorites = await _openBoxSafe<BangumiItem>('favorites');
+ collectibles = await _openBoxSafe<CollectedBangumi>('collectibles');
+ histories = await _openBoxSafe<History>('histories');
+ setting = await _openBoxSafe<dynamic>('setting');
+ collectChanges = await _openBoxSafe<CollectedBangumiChange>('collectchanges');
+ shieldList = await _openBoxSafe<String>('shieldList');
+ searchHistory = await _openBoxSafe<SearchHistory>('searchHistory');
+ downloads = await _openBoxSafe<DownloadRecord>('downloads');
+ }
+
+ /// Open a Hive box with automatic recovery on corruption.
+ /// If the box is corrupted, delete it and create a new empty one.
+ static Future<Box<T>> _openBoxSafe<T>(String boxName) async {
+ try {
+ return await Hive.openBox<T>(boxName);
+ } catch (e) {
+ KazumiLogger().e('GStorage: Box "$boxName" corrupted, attempting recovery', error: e);
+
+ // Delete the corrupted box files
+ await _deleteBoxFiles(boxName);
+
+ // Try to open again (will create a new empty box)
+ try {
+ final box = await Hive.openBox<T>(boxName);
+ KazumiLogger().i('GStorage: Box "$boxName" recovered successfully (data lost)');
+ return box;
+ } catch (e2) {
+ KazumiLogger().e('GStorage: Failed to recover box "$boxName"', error: e2);
+ rethrow;
+ }
+ }
+ }
+
+ /// Delete Hive box files for a given box name
+ static Future<void> _deleteBoxFiles(String boxName) async {
+ if (_hivePath == null) return;
+
+ final boxFile = File('$_hivePath/$boxName.hive');
+ final lockFile = File('$_hivePath/$boxName.lock');
+
+ try {
+ if (await boxFile.exists()) {
+ await boxFile.delete();
+ KazumiLogger().i('GStorage: Deleted corrupted box file: $boxName.hive');
+ }
+ if (await lockFile.exists()) {
+ await lockFile.delete();
+ KazumiLogger().i('GStorage: Deleted lock file: $boxName.lock');
+ }
+ } catch (e) {
+ KazumiLogger().e('GStorage: Failed to delete box files for "$boxName"', error: e);
+ }
}
static Future<void> backupBox(String boxName, String backupFilePath) async {
@@ -271,5 +327,8 @@ class SettingBoxKey {
proxyEnable = 'proxyEnable',
proxyConfigured = 'proxyConfigured',
proxyUrl = 'proxyUrl',
- showRating = 'showRating';
+ showRating = 'showRating',
+ downloadParallelEpisodes = 'downloadParallelEpisodes',
+ downloadParallelSegments = 'downloadParallelSegments',
+ downloadDanmaku = 'downloadDanmaku';
}
diff --git a/lib/pages/webview/webview_controller.dart b/lib/webview/webview_controller.dart
similarity index 81%
rename from lib/pages/webview/webview_controller.dart
rename to lib/webview/webview_controller.dart
index a48896f0..3a95e60a 100644
--- a/lib/pages/webview/webview_controller.dart
+++ b/lib/webview/webview_controller.dart
@@ -1,11 +1,11 @@
import 'dart:io';
import 'dart:async';
-import 'package:kazumi/pages/webview/webview_controller_impel/webview_android_controller_impel.dart';
-import 'package:kazumi/pages/webview/webview_controller_impel/webview_controller_impel.dart';
-import 'package:kazumi/pages/webview/webview_controller_impel/webview_windows_controller_impel.dart';
-import 'package:kazumi/pages/webview/webview_controller_impel/webview_linux_controller_impel.dart';
-import 'package:kazumi/pages/webview/webview_controller_impel/webview_apple_controller_impel.dart';
+import 'package:kazumi/webview/webview_controller_impel/webview_android_controller_impel.dart';
+import 'package:kazumi/webview/webview_controller_impel/webview_controller_impel.dart';
+import 'package:kazumi/webview/webview_controller_impel/webview_windows_controller_impel.dart';
+import 'package:kazumi/webview/webview_controller_impel/webview_linux_controller_impel.dart';
+import 'package:kazumi/webview/webview_controller_impel/webview_apple_controller_impel.dart';
import 'package:kazumi/utils/utils.dart';
abstract class WebviewItemController<T> {
diff --git a/lib/pages/webview/webview_controller_impel/webview_android_controller_impel.dart b/lib/webview/webview_controller_impel/webview_android_controller_impel.dart
similarity index 99%
rename from lib/pages/webview/webview_controller_impel/webview_android_controller_impel.dart
rename to lib/webview/webview_controller_impel/webview_android_controller_impel.dart
index 8fd93165..242a22f7 100644
--- a/lib/pages/webview/webview_controller_impel/webview_android_controller_impel.dart
+++ b/lib/webview/webview_controller_impel/webview_android_controller_impel.dart
@@ -3,7 +3,7 @@ import 'package:kazumi/utils/utils.dart';
import 'package:kazumi/utils/storage.dart';
import 'package:kazumi/utils/proxy_utils.dart';
import 'package:kazumi/utils/logger.dart';
-import 'package:kazumi/pages/webview/webview_controller.dart';
+import 'package:kazumi/webview/webview_controller.dart';
import 'package:flutter_inappwebview_platform_interface/flutter_inappwebview_platform_interface.dart';
import 'package:flutter_inappwebview_android/flutter_inappwebview_android.dart'
as android_webview;
diff --git a/lib/pages/webview/webview_controller_impel/webview_apple_controller_impel.dart b/lib/webview/webview_controller_impel/webview_apple_controller_impel.dart
similarity index 99%
rename from lib/pages/webview/webview_controller_impel/webview_apple_controller_impel.dart
rename to lib/webview/webview_controller_impel/webview_apple_controller_impel.dart
index 95ddc270..918aa894 100644
--- a/lib/pages/webview/webview_controller_impel/webview_apple_controller_impel.dart
+++ b/lib/webview/webview_controller_impel/webview_apple_controller_impel.dart
@@ -2,7 +2,7 @@ import 'dart:async';
import 'dart:collection';
import 'package:kazumi/utils/logger.dart';
import 'package:kazumi/utils/utils.dart';
-import 'package:kazumi/pages/webview/webview_controller.dart';
+import 'package:kazumi/webview/webview_controller.dart';
import 'package:flutter_inappwebview_platform_interface/flutter_inappwebview_platform_interface.dart';
class WebviewAppleItemControllerImpel
diff --git a/lib/webview/webview_controller_impel/webview_controller_impel.dart b/lib/webview/webview_controller_impel/webview_controller_impel.dart
new file mode 100644
index 00000000..bc005c2d
--- /dev/null
+++ b/lib/webview/webview_controller_impel/webview_controller_impel.dart
@@ -0,0 +1,486 @@
+import 'dart:async';
+import 'package:kazumi/utils/utils.dart';
+import 'package:kazumi/utils/storage.dart';
+import 'package:kazumi/utils/proxy_utils.dart';
+import 'package:kazumi/utils/logger.dart';
+import 'package:kazumi/webview/webview_controller.dart';
+import 'package:flutter_inappwebview_platform_interface/flutter_inappwebview_platform_interface.dart';
+import 'package:flutter_inappwebview_android/flutter_inappwebview_android.dart'
+ as android_webview;
+
+class WebviewItemControllerImpel
+ extends WebviewItemController<PlatformInAppWebViewController> {
+ PlatformHeadlessInAppWebView? headlessWebView;
+ Timer? loadingMonitorTimer;
+ bool hasRegisteredHandlers = false;
+ bool shouldInjectIframeRedirect = false;
+ bool useNativePlayer = false;
+ bool useLegacyParser = false;
+
+ @override
+ Future<void> init() async {
+ await _setupProxy();
+ headlessWebView ??= PlatformHeadlessInAppWebView(
+ PlatformHeadlessInAppWebViewCreationParams(
+ initialSettings: InAppWebViewSettings(
+ userAgent: Utils.getRandomUA(),
+ mediaPlaybackRequiresUserGesture: true,
+ cacheEnabled: false,
+ blockNetworkImage: true,
+ loadsImagesAutomatically: false,
+ upgradeKnownHostsToHTTPS: false,
+ safeBrowsingEnabled: false,
+ mixedContentMode: MixedContentMode.MIXED_CONTENT_COMPATIBILITY_MODE,
+ geolocationEnabled: false,
+ ),
+ onWebViewCreated: (controller) {
+ print('[WebView] Created (legacy fallback)');
+ webviewController = controller;
+ initEventController.add(true);
+ },
+ onLoadStart: (controller, url) async {
+ logEventController.add('started loading: $url');
+ if (url.toString() != 'about:blank') {
+ await _onLoadStart();
+ }
+ },
+ onLoadStop: (controller, url) async {
+ logEventController.add('loading completed: $url');
+ if (url.toString() != 'about:blank') {
+ await _onLoadStop();
+ }
+ },
+ ),
+ );
+ await headlessWebView?.run();
+ }
+
+ @override
+ Future<void> loadUrl(String url, bool useNativePlayer, bool useLegacyParser,
+ {int offset = 0}) async {
+ await unloadPage();
+ if (!hasRegisteredHandlers) {
+ _addJavaScriptHandlers(useNativePlayer, useLegacyParser);
+ hasRegisteredHandlers = true;
+ }
+ count = 0;
+ this.offset = offset;
+ this.useNativePlayer = useNativePlayer;
+ this.useLegacyParser = useLegacyParser;
+ isIframeLoaded = false;
+ isVideoSourceLoaded = false;
+ shouldInjectIframeRedirect = true;
+ videoLoadingEventController.add(true);
+
+ await webviewController?.loadUrl(urlRequest: URLRequest(url: WebUri(url)));
+ loadingMonitorTimer = Timer.periodic(const Duration(seconds: 1), (timer) {
+ if (isVideoSourceLoaded || isIframeLoaded) {
+ timer.cancel();
+ } else {
+ count++;
+ if (count >= 15) {
+ timer.cancel();
+ logEventController.add('clear');
+ logEventController.add('解析视频资源超时');
+ logEventController.add('请切换到其他播放列表或视频源');
+ logEventController.add('showDebug');
+ }
+ }
+ });
+ }
+
+ void _addJavaScriptHandlers(bool useNativePlayer, bool useLegacyParser) {
+ logEventController.add('Adding LogBridge handler');
+ webviewController?.addJavaScriptHandler(
+ handlerName: 'LogBridge',
+ callback: (args) {
+ String message = args[0].toString();
+ if (message.contains('about:blank')) {
+ return;
+ }
+ logEventController.add(message);
+ });
+
+ if (!useNativePlayer) {
+ logEventController.add('Adding IframeRedirectBridge handler');
+ webviewController?.addJavaScriptHandler(
+ handlerName: 'IframeRedirectBridge',
+ callback: (args) {
+ String message = args[0].toString();
+ logEventController.add('Redirect to: $message');
+ Future.delayed(const Duration(seconds: 2), () {
+ isIframeLoaded = true;
+ videoLoadingEventController.add(false);
+ });
+ });
+ } else if (useLegacyParser) {
+ logEventController.add('Adding JSBridgeDebug handler');
+ webviewController?.addJavaScriptHandler(
+ handlerName: 'JSBridgeDebug',
+ callback: (args) {
+ String message = args[0].toString();
+ logEventController.add('Callback received: $message');
+ logEventController.add(
+ 'If there is audio but no video, please report it to the rule developer.');
+ if ((message.contains('http') || message.startsWith('//')) &&
+ !message.contains('googleads') &&
+ !message.contains('googlesyndication.com') &&
+ !message.contains('prestrain.html') &&
+ !message.contains('prestrain%2Ehtml') &&
+ !message.contains('adtrafficquality')) {
+ logEventController.add('Parsing video source $message');
+ String encodedUrl = Uri.encodeFull(message);
+ if (Utils.decodeVideoSource(encodedUrl) != encodedUrl) {
+ isIframeLoaded = true;
+ isVideoSourceLoaded = true;
+ videoLoadingEventController.add(false);
+ logEventController.add(
+ 'Loading video source ${Utils.decodeVideoSource(encodedUrl)}');
+ unloadPage();
+ videoParserEventController
+ .add((Utils.decodeVideoSource(encodedUrl), offset));
+ }
+ }
+ });
+ } else {
+ logEventController.add('Adding VideoBridgeDebug handler');
+ webviewController?.addJavaScriptHandler(
+ handlerName: 'VideoBridgeDebug',
+ callback: (args) {
+ String message = args[0].toString();
+ logEventController.add('Callback received: $message');
+ if (message.contains('http') && !isVideoSourceLoaded) {
+ logEventController.add('Loading video source: $message');
+ isIframeLoaded = true;
+ isVideoSourceLoaded = true;
+ videoLoadingEventController.add(false);
+ unloadPage();
+ videoParserEventController.add((message, offset));
+ }
+ });
+ }
+ }
+
+ Future<void> _onLoadStart() async {
+ if (useNativePlayer && !useLegacyParser) {
+ logEventController.add('Injecting blob parser script (onLoadStart)');
+ await webviewController?.evaluateJavascript(source: """
+ try { window.flutter_inappwebview.callHandler('LogBridge', 'BlobParser script loaded: ' + window.location.href); } catch(e) {}
+ const _r_text = window.Response.prototype.text;
+ window.Response.prototype.text = function () {
+ return new Promise((resolve, reject) => {
+ _r_text.call(this).then((text) => {
+ resolve(text);
+ if (text.trim().startsWith("#EXTM3U")) {
+ window.flutter_inappwebview.callHandler('LogBridge', 'M3U8 source found: ' + this.url);
+ window.flutter_inappwebview.callHandler('VideoBridgeDebug', this.url);
+ }
+ }).catch(reject);
+ });
+ }
+
+ const _open = window.XMLHttpRequest.prototype.open;
+ window.XMLHttpRequest.prototype.open = function (...args) {
+ this.addEventListener("load", () => {
+ try {
+ let content = this.responseText;
+ if (content.trim().startsWith("#EXTM3U")) {
+ window.flutter_inappwebview.callHandler('LogBridge', 'M3U8 source found: ' + args[1]);
+ window.flutter_inappwebview.callHandler('VideoBridgeDebug', args[1]);
+ };
+ } catch {}
+ });
+ return _open.apply(this, args);
+ };
+
+ function injectIntoIframe(iframe) {
+ try {
+ const iframeWindow = iframe.contentWindow;
+ if (!iframeWindow) return;
+
+ const iframe_r_text = iframeWindow.Response.prototype.text;
+ iframeWindow.Response.prototype.text = function () {
+ return new Promise((resolve, reject) => {
+ iframe_r_text.call(this).then((text) => {
+ resolve(text);
+ if (text.trim().startsWith("#EXTM3U")) {
+ window.flutter_inappwebview.callHandler('LogBridge', 'M3U8 source found in iframe: ' + this.url);
+ window.flutter_inappwebview.callHandler('VideoBridgeDebug', this.url);
+ }
+ }).catch(reject);
+ });
+ }
+
+ const iframe_open = iframeWindow.XMLHttpRequest.prototype.open;
+ iframeWindow.XMLHttpRequest.prototype.open = function (...args) {
+ this.addEventListener("load", () => {
+ try {
+ let content = this.responseText;
+ if (content.trim().startsWith("#EXTM3U") && args[1] !== null && args[1] !== undefined) {
+ window.flutter_inappwebview.callHandler('LogBridge', 'M3U8 source found in iframe: ' + args[1]);
+ window.flutter_inappwebview.callHandler('VideoBridgeDebug', args[1]);
+ };
+ } catch {}
+ });
+ return iframe_open.apply(this, args);
+ }
+ } catch (e) {
+ console.error('iframe inject failed:', e);
+ }
+ }
+
+ function setupIframeListeners() {
+ document.querySelectorAll('iframe').forEach(iframe => {
+ if (iframe.contentDocument) {
+ injectIntoIframe(iframe);
+ }
+ iframe.addEventListener('load', () => injectIntoIframe(iframe));
+ });
+
+ const observer = new MutationObserver(mutations => {
+ mutations.forEach(mutation => {
+ if (mutation.type === 'childList') {
+ mutation.addedNodes.forEach(node => {
+ if (node.nodeName === 'IFRAME') {
+ node.addEventListener('load', () => injectIntoIframe(node));
+ }
+ if (node.querySelectorAll) {
+ node.querySelectorAll('iframe').forEach(iframe => {
+ iframe.addEventListener('load', () => injectIntoIframe(iframe));
+ });
+ }
+ });
+ }
+ });
+ });
+
+ if (document.body) {
+ observer.observe(document.body, { childList: true, subtree: true });
+ } else {
+ document.addEventListener('DOMContentLoaded', () => {
+ observer.observe(document.body, { childList: true, subtree: true });
+ });
+ }
+ }
+
+ if (document.readyState === 'loading') {
+ document.addEventListener('DOMContentLoaded', setupIframeListeners);
+ } else {
+ setupIframeListeners();
+ }
+ """);
+ }
+
+ if (!useNativePlayer && shouldInjectIframeRedirect) {
+ logEventController.add('Injecting IframeRedirect script (onLoadStart)');
+ shouldInjectIframeRedirect = false;
+ await webviewController?.evaluateJavascript(source: """
+ try { window.flutter_inappwebview.callHandler('LogBridge', 'IframeRedirectBridge script loaded: ' + window.location.href); } catch(e) {}
+ const _observer = new MutationObserver((mutations) => {
+ window.flutter_inappwebview.callHandler('LogBridge', 'Scanning for iframes...');
+ for (const mutation of mutations) {
+ if (mutation.type === "attributes" && mutation.target.nodeName === "IFRAME") {
+ if (processIframeElement(mutation.target)) return;
+ continue;
+ }
+ for (const node of mutation.addedNodes) {
+ if (node.nodeName === "IFRAME") {
+ if (processIframeElement(node)) return;
+ }
+ if (node.querySelectorAll) {
+ for (const iframe of node.querySelectorAll("iframe")) {
+ if (processIframeElement(iframe)) return;
+ }
+ }
+ }
+ }
+ });
+
+ function processIframeElement(iframe) {
+ window.flutter_inappwebview.callHandler('LogBridge', 'Processing iframe element');
+ let src = iframe.getAttribute("src");
+ if (src && src.trim() !== '' && (src.startsWith('http') || src.startsWith('//')) && !src.includes('googleads') && !src.includes('adtrafficquality') && !src.includes('googlesyndication.com') && !src.includes('google.com') && !src.includes('prestrain.html') && !src.includes('prestrain%2Ehtml')) {
+ _observer.disconnect();
+ window.flutter_inappwebview.callHandler("IframeRedirectBridge", src);
+ window.location.href = src;
+ return true;
+ }
+ }
+
+ function setupIframeProcessing() {
+ for (const iframe of document.querySelectorAll("iframe")) {
+ if (processIframeElement(iframe)) return;
+ }
+ _observer.observe(document.body, {
+ childList: true,
+ subtree: true,
+ attributes: true,
+ attributeFilter: ["src"],
+ });
+ }
+
+ if (document.readyState === 'loading') {
+ document.addEventListener('DOMContentLoaded', setupIframeProcessing);
+ } else {
+ setupIframeProcessing();
+ }
+ """);
+ }
+ }
+
+ Future<void> _onLoadStop() async {
+ if (useNativePlayer && !useLegacyParser) {
+ logEventController.add('Injecting video tag parser script (onLoadStop)');
+ await webviewController?.evaluateJavascript(source: """
+ window.flutter_inappwebview.callHandler('LogBridge', 'VideoTagParser script loaded: ' + window.location.href);
+ const _observer = new MutationObserver((mutations) => {
+ window.flutter_inappwebview.callHandler('LogBridge', 'Scanning for video elements...');
+ for (const mutation of mutations) {
+ if (mutation.type === "attributes" && mutation.target.nodeName === "VIDEO") {
+ if (processVideoElement(mutation.target)) return;
+ continue;
+ }
+ for (const node of mutation.addedNodes) {
+ if (node.nodeName === "VIDEO") {
+ if (processVideoElement(node)) return;
+ }
+ if (node.querySelectorAll) {
+ for (const video of node.querySelectorAll("video")) {
+ if (processVideoElement(video)) return;
+ }
+ }
+ }
+ }
+ });
+ function processVideoElement(video) {
+ window.flutter_inappwebview.callHandler('LogBridge', 'Scanning video element for source URL');
+ let src = video.getAttribute('src');
+ if (src && src.trim() !== '' && !src.startsWith('blob:') && !src.includes('googleads')) {
+ _observer.disconnect();
+ window.flutter_inappwebview.callHandler('LogBridge', 'VIDEO source found: ' + src);
+ window.flutter_inappwebview.callHandler('VideoBridgeDebug', src);
+ return true;
+ }
+ const sources = video.getElementsByTagName('source');
+ for (let source of sources) {
+ src = source.getAttribute('src');
+ if (src && src.trim() !== '' && !src.startsWith('blob:') && !src.includes('googleads')) {
+ _observer.disconnect();
+ window.flutter_inappwebview.callHandler('LogBridge', 'VIDEO source found (source tag): ' + src);
+ window.flutter_inappwebview.callHandler('VideoBridgeDebug', src);
+ return true;
+ }
+ }
+ }
+
+ function setupVideoProcessing() {
+ for (const video of document.querySelectorAll("video")) {
+ if (processVideoElement(video)) return;
+ }
+ _observer.observe(document.body, {
+ childList: true,
+ subtree: true,
+ attributes: true,
+ attributeFilter: ['src']
+ });
+ }
+ if (document.readyState === 'loading') {
+ document.addEventListener('DOMContentLoaded', setupVideoProcessing);
+ } else {
+ setupVideoProcessing();
+ }
+ """);
+ }
+
+ if (useNativePlayer && useLegacyParser) {
+ logEventController.add('Injecting JSBridgeDebug script (onLoadStop)');
+ await webviewController?.evaluateJavascript(source: """
+ window.flutter_inappwebview.callHandler('LogBridge', 'JSBridgeDebug script loaded: ' + window.location.href);
+ function processIframeElement(iframe) {
+ window.flutter_inappwebview.callHandler('LogBridge', 'Processing iframe element');
+ let src = iframe.getAttribute('src');
+ if (src) {
+ window.flutter_inappwebview.callHandler('JSBridgeDebug', src);
+ }
+ }
+
+ const _observer = new MutationObserver((mutations) => {
+ window.flutter_inappwebview.callHandler('LogBridge', 'Scanning for iframes...');
+ mutations.forEach(mutation => {
+ if (mutation.type === 'attributes' && mutation.target.nodeName === 'IFRAME') {
+ processIframeElement(mutation.target);
+ } else {
+ mutation.addedNodes.forEach(node => {
+ if (node.nodeName === 'IFRAME') processIframeElement(node);
+ if (node.querySelectorAll) {
+ node.querySelectorAll('iframe').forEach(processIframeElement);
+ }
+ });
+ }
+ });
+ });
+
+ _observer.observe(document.documentElement, {
+ childList: true,
+ subtree: true,
+ attributes: true,
+ attributeFilter: ['src']
+ });
+ """);
+ }
+ }
+
+ @override
+ Future<void> unloadPage() async {
+ loadingMonitorTimer?.cancel();
+ await webviewController
+ ?.loadUrl(urlRequest: URLRequest(url: WebUri("about:blank")));
+ }
+
+ @override
+ void dispose() {
+ loadingMonitorTimer?.cancel();
+ headlessWebView?.dispose();
+ headlessWebView = null;
+ webviewController = null;
+ }
+
+ Future<void> _setupProxy() async {
+ final setting = GStorage.setting;
+ final bool proxyEnable =
+ setting.get(SettingBoxKey.proxyEnable, defaultValue: false);
+ if (!proxyEnable) {
+ return;
+ }
+
+ final String proxyUrl =
+ setting.get(SettingBoxKey.proxyUrl, defaultValue: '');
+ final formattedProxy = ProxyUtils.getFormattedProxyUrl(proxyUrl);
+ if (formattedProxy == null) {
+ return;
+ }
+
+ try {
+ final proxyAvailable =
+ await android_webview.AndroidWebViewFeature.instance()
+ .isFeatureSupported(WebViewFeature.PROXY_OVERRIDE);
+ if (!proxyAvailable) {
+ KazumiLogger().w('WebView: 当前 Android 版本不支持代理');
+ return;
+ }
+
+ final proxyController = android_webview.AndroidProxyController.instance();
+ await proxyController.clearProxyOverride();
+ await proxyController.setProxyOverride(
+ settings: ProxySettings(
+ proxyRules: [
+ ProxyRule(url: formattedProxy),
+ ],
+ ),
+ );
+ KazumiLogger().i('WebView: 代理设置成功 $formattedProxy');
+ } catch (e) {
+ KazumiLogger().e('WebView: 设置代理失败 $e');
+ }
+ }
+}
diff --git a/lib/pages/webview/webview_controller_impel/webview_linux_controller_impel.dart b/lib/webview/webview_controller_impel/webview_linux_controller_impel.dart
similarity index 99%
rename from lib/pages/webview/webview_controller_impel/webview_linux_controller_impel.dart
rename to lib/webview/webview_controller_impel/webview_linux_controller_impel.dart
index 4a04f906..28fd63cf 100644
--- a/lib/pages/webview/webview_controller_impel/webview_linux_controller_impel.dart
+++ b/lib/webview/webview_controller_impel/webview_linux_controller_impel.dart
@@ -1,5 +1,5 @@
import 'dart:async';
-import 'package:kazumi/pages/webview/webview_controller.dart';
+import 'package:kazumi/webview/webview_controller.dart';
import 'package:kazumi/utils/utils.dart';
import 'package:kazumi/utils/storage.dart';
import 'package:kazumi/utils/proxy_utils.dart';
diff --git a/lib/pages/webview/webview_controller_impel/webview_windows_controller_impel.dart b/lib/webview/webview_controller_impel/webview_windows_controller_impel.dart
similarity index 73%
rename from lib/pages/webview/webview_controller_impel/webview_windows_controller_impel.dart
rename to lib/webview/webview_controller_impel/webview_windows_controller_impel.dart
index 2526b130..46dd573b 100644
--- a/lib/pages/webview/webview_controller_impel/webview_windows_controller_impel.dart
+++ b/lib/webview/webview_controller_impel/webview_windows_controller_impel.dart
@@ -1,6 +1,6 @@
import 'dart:async';
import 'package:webview_windows/webview_windows.dart';
-import 'package:kazumi/pages/webview/webview_controller.dart';
+import 'package:kazumi/webview/webview_controller.dart';
import 'package:kazumi/utils/storage.dart';
import 'package:kazumi/utils/proxy_utils.dart';
import 'package:kazumi/utils/logger.dart';
@@ -9,12 +9,14 @@ class WebviewWindowsItemControllerImpel
extends WebviewItemController<WebviewController> {
final List<StreamSubscription> subscriptions = [];
+ HeadlessWebview? headlessWebview;
+
@override
Future<void> init() async {
await _setupProxy();
- webviewController ??= WebviewController();
- await webviewController!.initialize();
- await webviewController!
+ headlessWebview ??= HeadlessWebview();
+ await headlessWebview!.run();
+ await headlessWebview!
.setPopupWindowPolicy(WebviewPopupWindowPolicy.deny);
initEventController.add(true);
}
@@ -53,7 +55,7 @@ class WebviewWindowsItemControllerImpel
isIframeLoaded = false;
isVideoSourceLoaded = false;
videoLoadingEventController.add(true);
- subscriptions.add(webviewController!.onM3USourceLoaded.listen((data) {
+ subscriptions.add(headlessWebview!.onM3USourceLoaded.listen((data) {
String url = data['url'] ?? '';
if (url.isEmpty) {
return;
@@ -65,7 +67,7 @@ class WebviewWindowsItemControllerImpel
logEventController.add('Loading m3u8 source: $url');
videoParserEventController.add((url, offset));
}));
- subscriptions.add(webviewController!.onVideoSourceLoaded.listen((data) {
+ subscriptions.add(headlessWebview!.onVideoSourceLoaded.listen((data) {
String url = data['url'] ?? '';
if (url.isEmpty) {
return;
@@ -77,7 +79,7 @@ class WebviewWindowsItemControllerImpel
logEventController.add('Loading video source: $url');
videoParserEventController.add((url, offset));
}));
- await webviewController!.loadUrl(url);
+ await headlessWebview!.loadUrl(url);
}
@override
@@ -97,15 +99,11 @@ class WebviewWindowsItemControllerImpel
s.cancel();
} catch (_) {}
});
- // It's a custom function to dispose the whole webview environment in Predidit's flutter-webview-windows fork.
- // which allow re-initialization webview environment with different proxy settings.
- // It's difficult to get a dispose finish callback from Microsoft Edge WebView2 SDK,
- // so don't call webviewController.dispose() when we call WebviewController.disposeEnvironment(), WebViewController.disposeEnvironment() already do any necessary clean up internally.
- // ohtherwise, app will crash due to resource conflict.
- if (webviewController != null) {
- WebviewController.disposeEnvironment();
- webviewController = null;
- }
+ // disposeEnvironment() 内部已通过 headless_instances_.clear() 销毁所有 headless 实例,
+ // 不要额外调用 headlessWebview.dispose(),否则两个异步方法通道调用可能产生竞争,
+ // 导致 disposeEnvironment 先到达原生侧清除实例后,disposeHeadless 找不到条目抛出异常。
+ headlessWebview = null;
+ WebviewController.disposeEnvironment();
}
// The webview_windows package does not have a method to unload the current page.
@@ -113,7 +111,7 @@ class WebviewWindowsItemControllerImpel
// Directly disposing of the webview controller would require reinitialization when switching episodes, which is costly.
// Therefore, this method is used to redirect to a blank page instead.
Future<void> redirect2Blank() async {
- await webviewController!.executeScript('''
+ await headlessWebview!.executeScript('''
window.location.href = 'about:blank';
''');
}
diff --git a/macos/Flutter/GeneratedPluginRegistrant.swift b/macos/Flutter/GeneratedPluginRegistrant.swift
index 6b4d70b0..abdf9b3f 100644
--- a/macos/Flutter/GeneratedPluginRegistrant.swift
+++ b/macos/Flutter/GeneratedPluginRegistrant.swift
@@ -19,7 +19,6 @@ import sqflite_darwin
import tray_manager
import url_launcher_macos
import wakelock_plus
-import webview_flutter_wkwebview
import window_manager
func RegisterGeneratedPlugins(registry: FlutterPluginRegistry) {
@@ -37,6 +36,5 @@ func RegisterGeneratedPlugins(registry: FlutterPluginRegistry) {
TrayManagerPlugin.register(with: registry.registrar(forPlugin: "TrayManagerPlugin"))
UrlLauncherPlugin.register(with: registry.registrar(forPlugin: "UrlLauncherPlugin"))
WakelockPlusMacosPlugin.register(with: registry.registrar(forPlugin: "WakelockPlusMacosPlugin"))
- WebViewFlutterPlugin.register(with: registry.registrar(forPlugin: "WebViewFlutterPlugin"))
WindowManagerPlugin.register(with: registry.registrar(forPlugin: "WindowManagerPlugin"))
}
diff --git a/pubspec.lock b/pubspec.lock
index db00bdef..b99272a8 100644
--- a/pubspec.lock
+++ b/pubspec.lock
@@ -1603,38 +1603,6 @@ packages:
url: "https://pub.dev"
source: hosted
version: "1.2.2"
- webview_flutter:
- dependency: "direct main"
- description:
- name: webview_flutter
- sha256: a3da219916aba44947d3a5478b1927876a09781174b5a2b67fa5be0555154bf9
- url: "https://pub.dev"
- source: hosted
- version: "4.13.1"
- webview_flutter_android:
- dependency: transitive
- description:
- name: webview_flutter_android
- sha256: "414174cacd339046a1a6dbf93cac62422194c676fed11119ccf228b81640e887"
- url: "https://pub.dev"
- source: hosted
- version: "4.9.1"
- webview_flutter_platform_interface:
- dependency: transitive
- description:
- name: webview_flutter_platform_interface
- sha256: "63d26ee3aca7256a83ccb576a50272edd7cfc80573a4305caa98985feb493ee0"
- url: "https://pub.dev"
- source: hosted
- version: "2.14.0"
- webview_flutter_wkwebview:
- dependency: transitive
- description:
- name: webview_flutter_wkwebview
- sha256: fb46db8216131a3e55bcf44040ca808423539bc6732e7ed34fb6d8044e3d512f
- url: "https://pub.dev"
- source: hosted
- version: "3.23.0"
webview_windows:
dependency: "direct main"
description:
diff --git a/pubspec.yaml b/pubspec.yaml
index 0f326ead..352fa86f 100644
--- a/pubspec.yaml
+++ b/pubspec.yaml
@@ -62,7 +62,7 @@ dependencies:
window_manager: ^0.5.1
xpath_selector: ^3.0.2
xpath_selector_html_parser: ^3.0.1
- webview_flutter: ^4.13.1
+
canvas_danmaku: ^0.3.1
webdav_client: ^1.2.2
tray_manager: ^0.5.0
diff --git a/test/m3u8_parser_test.dart b/test/m3u8_parser_test.dart
new file mode 100644
index 00000000..0ffcb0f4
--- /dev/null
+++ b/test/m3u8_parser_test.dart
@@ -0,0 +1,204 @@
+import 'dart:io';
+import 'package:kazumi/utils/m3u8_parser.dart';
+
+void main() {
+ print('=== M3U8 Parser 验证测试 ===\n');
+
+ // Test 1: Mux master playlist
+ testMasterPlaylist();
+
+ // Test 2: Mux media playlist (有 PLAYLIST-TYPE:VOD + ENDLIST)
+ testMuxMediaPlaylist();
+
+ // Test 3: Apple media playlist (有 PLAYLIST-TYPE:VOD, 无 ENDLIST)
+ testAppleMediaPlaylist();
+
+ // Test 4: 模拟无 PLAYLIST-TYPE:VOD 也无 ENDLIST 的 playlist
+ testNoVodNoEndlist();
+
+ // Test 5: EVENT 类型的 playlist
+ testEventPlaylist();
+
+ // Test 6: 显式 PLAYLIST-TYPE:VOD(无 ENDLIST)
+ testExplicitVodTag();
+
+ // Test 7: 嵌套 M3U8 展开
+ testNestedM3u8();
+
+ print('\n=== 所有测试完成 ===');
+}
+
+void testMasterPlaylist() {
+ print('--- Test 1: Mux Master Playlist ---');
+ final content = File('/tmp/mux_master.m3u8').readAsStringSync();
+ final type = M3u8Parser.detectType(content);
+ print('类型检测: ${type == M3u8Type.master ? "✓ master" : "✗ 预期 master, 实际 $type"}');
+
+ final master = M3u8Parser.parseMasterPlaylist(content, 'https://test-streams.mux.dev/x36xhzz/x36xhzz.m3u8');
+ print('变体数量: ${master.variants.length}');
+ final best = master.bestVariant;
+ print('最佳变体: ${best.resolution ?? "unknown"} @ ${best.bandwidth} bps');
+ print('最佳变体 URI: ${best.uri}');
+ print('');
+}
+
+void testMuxMediaPlaylist() {
+ print('--- Test 2: Mux Media Playlist (VOD + ENDLIST) ---');
+ final content = File('/tmp/mux_media.m3u8').readAsStringSync();
+ final type = M3u8Parser.detectType(content);
+ print('类型检测: ${type == M3u8Type.media ? "✓ media" : "✗ 预期 media, 实际 $type"}');
+
+ final playlist = M3u8Parser.parseMediaPlaylist(
+ content, 'https://test-streams.mux.dev/x36xhzz/url_0/193039199_mp4_h264_aac_hd_7.m3u8',
+ );
+ print('isVod: ${playlist.isVod ? "✓ true" : "✗ false (应为 true)"}');
+ print('targetDuration: ${playlist.targetDuration}');
+ print('分片数量: ${playlist.segments.length}');
+ print('首个分片 URI: ${playlist.segments.first.uri}');
+
+ // 检查是否有 PLAYLIST-TYPE:VOD 标签
+ final hasVodTag = content.contains('#EXT-X-PLAYLIST-TYPE:VOD');
+ final hasEndList = content.contains('#EXT-X-ENDLIST');
+ print('原始内容包含 PLAYLIST-TYPE:VOD: $hasVodTag');
+ print('原始内容包含 ENDLIST: $hasEndList');
+ print('');
+}
+
+void testAppleMediaPlaylist() {
+ print('--- Test 3: Apple Media Playlist (VOD, 检查 ENDLIST) ---');
+ final content = File('/tmp/apple_media.m3u8').readAsStringSync();
+ final playlist = M3u8Parser.parseMediaPlaylist(
+ content, 'https://devstreaming-cdn.apple.com/videos/streaming/examples/bipbop_adv_example_hevc/v5/prog_index.m3u8',
+ );
+
+ final hasVodTag = content.contains('#EXT-X-PLAYLIST-TYPE:VOD');
+ final hasEndList = content.contains('#EXT-X-ENDLIST');
+ print('原始内容包含 PLAYLIST-TYPE:VOD: $hasVodTag');
+ print('原始内容包含 ENDLIST: $hasEndList');
+ print('isVod: ${playlist.isVod ? "✓ true" : "✗ false (应为 true)"}');
+ print('分片数量: ${playlist.segments.length}');
+ print('');
+}
+
+void testNoVodNoEndlist() {
+ print('--- Test 4: 无 VOD 标签、无 ENDLIST(模拟野生源) ---');
+ const content = '''
+#EXTM3U
+#EXT-X-VERSION:3
+#EXT-X-TARGETDURATION:10
+#EXT-X-MEDIA-SEQUENCE:0
+#EXTINF:10.0,
+https://example.com/seg_00000.ts
+#EXTINF:10.0,
+https://example.com/seg_00001.ts
+#EXTINF:8.5,
+https://example.com/seg_00002.ts
+''';
+
+ final playlist = M3u8Parser.parseMediaPlaylist(content, 'https://example.com/playlist.m3u8');
+ // 当前逻辑: !isLiveEvent && segments.isNotEmpty → true
+ print('isVod: ${playlist.isVod} (当前逻辑: 兜底判定为 VOD)');
+ print('分片数量: ${playlist.segments.length}');
+ print('');
+}
+
+void testEventPlaylist() {
+ print('--- Test 5: EVENT 类型 Playlist ---');
+ const content = '''
+#EXTM3U
+#EXT-X-VERSION:3
+#EXT-X-PLAYLIST-TYPE:EVENT
+#EXT-X-TARGETDURATION:10
+#EXT-X-MEDIA-SEQUENCE:0
+#EXTINF:10.0,
+https://example.com/seg_00000.ts
+#EXTINF:10.0,
+https://example.com/seg_00001.ts
+''';
+
+ final playlist = M3u8Parser.parseMediaPlaylist(content, 'https://example.com/event.m3u8');
+ // EVENT 且无 ENDLIST → 应该判定为非 VOD(直播追赶流)
+ print('isVod: ${!playlist.isVod ? "✓ false (正确拒绝 EVENT 流)" : "✗ true (不应判定为 VOD)"}');
+ print('');
+}
+
+void testExplicitVodTag() {
+ print('--- Test 6: 显式 PLAYLIST-TYPE:VOD(无 ENDLIST) ---');
+ const content = '''
+#EXTM3U
+#EXT-X-VERSION:3
+#EXT-X-PLAYLIST-TYPE:VOD
+#EXT-X-TARGETDURATION:10
+#EXT-X-MEDIA-SEQUENCE:0
+#EXTINF:10.0,
+https://example.com/seg_00000.ts
+#EXTINF:10.0,
+https://example.com/seg_00001.ts
+''';
+
+ final playlist = M3u8Parser.parseMediaPlaylist(content, 'https://example.com/vod.m3u8');
+ print('isVod: ${playlist.isVod ? "✓ true (显式 VOD 标签生效)" : "✗ false (未识别 VOD 标签)"}');
+
+ // 边界情况: 有 VOD 标签但无分片(不应崩溃)
+ const emptyVod = '''
+#EXTM3U
+#EXT-X-VERSION:3
+#EXT-X-PLAYLIST-TYPE:VOD
+#EXT-X-TARGETDURATION:10
+''';
+ final emptyPlaylist = M3u8Parser.parseMediaPlaylist(emptyVod, 'https://example.com/empty.m3u8');
+ print('空分片 VOD: isVod=${emptyPlaylist.isVod ? "✓ true (仅靠 VOD 标签判定)" : "✗ false"}, segments=${emptyPlaylist.segments.length}');
+ print('');
+}
+
+void testNestedM3u8() async {
+ print('--- Test 7: 嵌套 M3U8 展开 ---');
+
+ // 模拟: 外层 playlist 中有一个 segment 指向另一个 m3u8
+ const outerContent = '''
+#EXTM3U
+#EXT-X-VERSION:3
+#EXT-X-TARGETDURATION:30
+#EXTINF:10.0,
+https://example.com/seg_00000.ts
+#EXTINF:30.0,
+https://example.com/nested.m3u8
+#EXTINF:10.0,
+https://example.com/seg_00002.ts
+#EXT-X-ENDLIST
+''';
+
+ const nestedContent = '''
+#EXTM3U
+#EXT-X-VERSION:3
+#EXT-X-TARGETDURATION:10
+#EXTINF:10.0,
+seg_a.ts
+#EXTINF:10.0,
+seg_b.ts
+#EXTINF:10.0,
+seg_c.ts
+#EXT-X-ENDLIST
+''';
+
+ final outer = M3u8Parser.parseMediaPlaylist(outerContent, 'https://example.com/main.m3u8');
+ print('展开前分片数: ${outer.segments.length}');
+ print('其中 m3u8 引用: ${outer.segments.where((s) => s.uri.endsWith(".m3u8")).length}');
+
+ final resolved = await M3u8Parser.resolveNestedSegments(
+ outer.segments,
+ (url) async {
+ if (url.contains('nested.m3u8')) return nestedContent;
+ throw Exception('Unknown URL: $url');
+ },
+ );
+
+ print('展开后分片数: ${resolved.length}');
+ print('展开后 URI 列表:');
+ for (final seg in resolved) {
+ print(' [group=${seg.discontinuityGroup}] ${seg.uri}');
+ }
+ final hasM3u8Ref = resolved.any((s) => s.uri.endsWith('.m3u8'));
+ print('展开后仍有 m3u8 引用: ${!hasM3u8Ref ? "✓ 无 (全部展开)" : "✗ 有 (未完全展开)"}');
+ print('');
+}