基于自定义规则的番剧采集APP,支持流媒体在线观看,支持弹幕,支持实时超分辨率。
feat(download): support android custom directories (#2647)
LiggMax2768c230407d
diff --git a/android/app/src/main/AndroidManifest.xml b/android/app/src/main/AndroidManifest.xmlindex 8dbe3c03..58bd9e9c 100644--- a/android/app/src/main/AndroidManifest.xml+++ b/android/app/src/main/AndroidManifest.xml@@ -3,6 +3,7 @@android:label="Kazumi"android:name="${applicationName}"android:usesCleartextTraffic="true"+ android:requestLegacyExternalStorage="true"android:icon="@mipmap/ic_launcher"android:extractNativeLibs="true"><meta-data@@ -72,6 +73,10 @@<uses-permission android:name="android.permission.FOREGROUND_SERVICE_MEDIA_PLAYBACK"/><uses-permission android:name="android.permission.POST_NOTIFICATIONS"/><uses-permission android:name="android.permission.REQUEST_INSTALL_PACKAGES" />+ <!-- Direct file access for optional custom download directories. -->+ <uses-permission android:name="android.permission.MANAGE_EXTERNAL_STORAGE" />+ <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" android:maxSdkVersion="32" />+ <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" android:maxSdkVersion="29" /><!-- Required to query activities that can process text, see:https://developer.android.com/training/package-visibility?hl=en andhttps://developer.android.com/reference/android/content/Intent#ACTION_PROCESS_TEXT.diff --git a/android/app/src/main/kotlin/com/example/kazumi/DownloadDirectoryHandler.kt b/android/app/src/main/kotlin/com/example/kazumi/DownloadDirectoryHandler.ktnew file mode 100644index 00000000..5debcf72--- /dev/null+++ b/android/app/src/main/kotlin/com/example/kazumi/DownloadDirectoryHandler.kt@@ -0,0 +1,209 @@+package com.example.kazumi++import android.Manifest+import android.app.Activity+import android.content.Intent+import android.content.pm.PackageManager+import android.net.Uri+import android.os.Build+import android.os.Environment+import android.os.storage.StorageManager+import android.provider.DocumentsContract+import android.provider.Settings+import androidx.core.content.ContextCompat+import io.flutter.plugin.common.MethodCall+import io.flutter.plugin.common.MethodChannel+import java.io.File++/**+ * Grants storage access and picks a local directory when the user changes the+ * download location. Downloads then use the plain filesystem path.+ */+class DownloadDirectoryHandler(private val activity: Activity) : MethodChannel.MethodCallHandler {+ companion object {+ const val CHANNEL = "com.predidit.kazumi/download_directory"+ private const val ACCESS_REQUEST = 53010+ private const val DIRECTORY_REQUEST = 53011+ private const val EXTERNAL_DOCUMENTS = "com.android.externalstorage.documents"+ }++ private var accessResult: MethodChannel.Result? = null+ private var directoryResult: MethodChannel.Result? = null++ override fun onMethodCall(call: MethodCall, result: MethodChannel.Result) {+ when (call.method) {+ "requestStorageAccess" -> requestStorageAccess(result)+ "pickDirectory" -> pickDirectory(call.argument<String>("initialDirectory"), result)+ else -> result.notImplemented()+ }+ }++ private fun isBusy(result: MethodChannel.Result): Boolean {+ if (accessResult == null && directoryResult == null) return false+ result.error("DIRECTORY_BUSY", "Another directory request is in progress", null)+ return true+ }++ private fun hasStorageAccess(): Boolean {+ return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {+ Environment.isExternalStorageManager()+ } else {+ ContextCompat.checkSelfPermission(activity, Manifest.permission.WRITE_EXTERNAL_STORAGE) ==+ PackageManager.PERMISSION_GRANTED+ }+ }++ @Suppress("DEPRECATION")+ private fun requestStorageAccess(result: MethodChannel.Result) {+ if (isBusy(result)) return+ if (hasStorageAccess()) {+ result.success(true)+ return+ }+ accessResult = result+ try {+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {+ val appSettings = Intent(+ Settings.ACTION_MANAGE_APP_ALL_FILES_ACCESS_PERMISSION,+ Uri.parse("package:${activity.packageName}")+ )+ try {+ activity.startActivityForResult(appSettings, ACCESS_REQUEST)+ } catch (_: android.content.ActivityNotFoundException) {+ activity.startActivityForResult(+ Intent(Settings.ACTION_MANAGE_ALL_FILES_ACCESS_PERMISSION), ACCESS_REQUEST+ )+ }+ } else {+ activity.requestPermissions(+ arrayOf(Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE),+ ACCESS_REQUEST+ )+ }+ } catch (e: Exception) {+ accessResult = null+ result.error("STORAGE_ACCESS_FAILED", "Failed to open storage access settings: ${e.message}", null)+ }+ }++ @Suppress("DEPRECATION")+ private fun pickDirectory(initialDirectory: String?, result: MethodChannel.Result) {+ if (isBusy(result)) return+ if (!hasStorageAccess()) {+ result.error("STORAGE_ACCESS_DENIED", "Storage access is not granted", null)+ return+ }+ directoryResult = result+ try {+ val intent = Intent(Intent.ACTION_OPEN_DOCUMENT_TREE).apply {+ putExtra(Intent.EXTRA_LOCAL_ONLY, true)+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O && initialDirectory != null) {+ initialUri(File(initialDirectory))?.let {+ putExtra(DocumentsContract.EXTRA_INITIAL_URI, it)+ }+ }+ }+ activity.startActivityForResult(intent, DIRECTORY_REQUEST)+ } catch (e: Exception) {+ directoryResult = null+ result.error("DIRECTORY_PICKER_FAILED", "Failed to open directory picker: ${e.message}", null)+ }+ }++ fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {+ when (requestCode) {+ ACCESS_REQUEST -> finishAccessRequest()+ DIRECTORY_REQUEST -> {+ val result = directoryResult ?: return+ directoryResult = null+ if (resultCode != Activity.RESULT_OK) {+ result.success(null)+ return+ }+ try {+ val uri = data?.data+ val directory = uri?.let { resolveDirectory(it) }+ if (directory == null) {+ result.error(+ "UNSUPPORTED_DIRECTORY",+ "Only directories on local storage volumes are supported",+ null+ )+ } else {+ result.success(directory.canonicalPath)+ }+ } catch (e: Exception) {+ result.error("INVALID_DIRECTORY", "Failed to resolve the selected directory: ${e.message}", null)+ }+ }+ }+ }++ fun onRequestPermissionsResult(requestCode: Int) {+ if (requestCode == ACCESS_REQUEST) finishAccessRequest()+ }++ private fun finishAccessRequest() {+ val result = accessResult ?: return+ accessResult = null+ // Settings activities commonly return RESULT_CANCELED even after a grant.+ result.success(hasStorageAccess())+ }++ @Suppress("DEPRECATION")+ private fun storageRoots(): List<Pair<String, File>> {+ val roots = mutableListOf("primary" to Environment.getExternalStorageDirectory())+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {+ val manager = activity.getSystemService(StorageManager::class.java)+ manager.storageVolumes.forEach { volume ->+ val id = volume.uuid+ val directory = volume.directory+ if (id != null && directory != null) roots.add(id to directory)+ }+ } else {+ // getExternalFilesDirs exposes mounted removable volumes on older APIs.+ activity.getExternalFilesDirs(null).filterNotNull().forEach { directory ->+ val rootPath = directory.absolutePath.substringBefore("/Android/data/")+ val root = File(rootPath)+ if (rootPath != directory.absolutePath && root.name != "0") {+ roots.add(root.name to root)+ }+ }+ }+ return roots+ }++ private fun resolveDirectory(uri: Uri): File? {+ // A document URI is not a filesystem path. Only resolve known local+ // storage volumes, never invent a path for cloud/virtual providers.+ if (uri.scheme != "content" || uri.authority != EXTERNAL_DOCUMENTS ||+ !DocumentsContract.isTreeUri(uri)) return null+ val documentId = DocumentsContract.getTreeDocumentId(uri)+ val separator = documentId.indexOf(':')+ if (separator < 0) return null+ val volumeId = documentId.substring(0, separator)+ val root = storageRoots().firstOrNull { it.first.equals(volumeId, ignoreCase = true) }?.second+ ?: return null+ val directory = File(root, documentId.substring(separator + 1))+ return if (contains(root, directory)) directory else null+ }++ private fun initialUri(directory: File): Uri? {+ val entry = storageRoots().firstOrNull { contains(it.second, directory) } ?: return null+ val relative = directory.canonicalFile.relativeTo(entry.second.canonicalFile).path+ return DocumentsContract.buildDocumentUri(EXTERNAL_DOCUMENTS, "${entry.first}:$relative")+ }++ private fun contains(root: File, directory: File): Boolean {+ val rootPath = root.canonicalPath+ val directoryPath = directory.canonicalPath+ return directoryPath == rootPath || directoryPath.startsWith(rootPath + File.separator)+ }++ fun dispose() {+ accessResult?.error("ACTIVITY_CLOSED", "Activity destroyed during storage access request", null)+ directoryResult?.error("ACTIVITY_CLOSED", "Activity destroyed during directory selection", null)+ accessResult = null+ directoryResult = null+ }+}diff --git a/android/app/src/main/kotlin/com/example/kazumi/MainActivity.kt b/android/app/src/main/kotlin/com/example/kazumi/MainActivity.ktindex e098691a..cf4f3d73 100644--- a/android/app/src/main/kotlin/com/example/kazumi/MainActivity.kt+++ b/android/app/src/main/kotlin/com/example/kazumi/MainActivity.kt@@ -36,6 +36,8 @@ class MainActivity: AudioServiceActivity() {private val PIP_CHANNEL = "com.predidit.kazumi/pip"private var intentChannel: MethodChannel? = nullprivate var pipChannel: MethodChannel? = null+ private var downloadDirectoryChannel: MethodChannel? = null+ private var downloadDirectoryHandler: DownloadDirectoryHandler? = nullprivate var pipIsPlaying = falseprivate var pipDanmakuEnabled = false@@ -74,6 +76,10 @@ class MainActivity: AudioServiceActivity() {}override fun onDestroy() {+ downloadDirectoryChannel?.setMethodCallHandler(null)+ downloadDirectoryChannel = null+ downloadDirectoryHandler?.dispose()+ downloadDirectoryHandler = nullunregisterPipActionReceiverIfNeeded()// audio_service stays bound for the whole activity lifetime, so its// own stopSelf() never destroys a service started for playback.@@ -101,6 +107,11 @@ class MainActivity: AudioServiceActivity() {override fun configureFlutterEngine(@NonNull flutterEngine: FlutterEngine) {super.configureFlutterEngine(flutterEngine)+ downloadDirectoryHandler = DownloadDirectoryHandler(this)+ downloadDirectoryChannel = MethodChannel(+ flutterEngine.dartExecutor.binaryMessenger, DownloadDirectoryHandler.CHANNEL+ )+ downloadDirectoryChannel?.setMethodCallHandler(downloadDirectoryHandler)intentChannel = MethodChannel(flutterEngine.dartExecutor.binaryMessenger, CHANNEL)intentChannel?.setMethodCallHandler { call, result ->if (call.method == "openWithMime") {@@ -176,6 +187,21 @@ class MainActivity: AudioServiceActivity() {startActivity(intent)}+ @Suppress("DEPRECATION")+ override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {+ super.onActivityResult(requestCode, resultCode, data)+ downloadDirectoryHandler?.onActivityResult(requestCode, resultCode, data)+ }++ override fun onRequestPermissionsResult(+ requestCode: Int,+ permissions: Array<out String>,+ grantResults: IntArray+ ) {+ super.onRequestPermissionsResult(requestCode, permissions, grantResults)+ downloadDirectoryHandler?.onRequestPermissionsResult(requestCode)+ }+private fun getAndroidSdkVersion(): Int {return Build.VERSION.SDK_INT}diff --git a/lib/main.dart b/lib/main.dartindex 0e2ebdf0..9562fa7d 100644--- a/lib/main.dart+++ b/lib/main.dart@@ -6,6 +6,7 @@ import 'package:flutter_modular/flutter_modular.dart';import 'package:kazumi/bean/settings/theme_provider.dart';import 'package:path_provider/path_provider.dart';import 'package:kazumi/services/storage/storage.dart';+import 'package:kazumi/services/download/download_directory_service.dart';import 'package:hive_ce_flutter/hive_flutter.dart';import 'package:kazumi/services/network/metered_network_service.dart';import 'package:kazumi/services/network/ech_http_licenses.dart';@@ -68,6 +69,7 @@ void main() async {}));return;}+ await DownloadDirectoryService().restoreAccess();final showWindowButton = DesktopWindowConfig.showWindowButton;if (isDesktop()) {await windowManager.ensureInitialized();diff --git a/lib/pages/download/download_controller.dart b/lib/pages/download/download_controller.dartindex 9df68f18..cd8cad31 100644--- a/lib/pages/download/download_controller.dart+++ b/lib/pages/download/download_controller.dart@@ -875,61 +875,63 @@ abstract class _DownloadController with Store {}}- Future<void> cancelDownload(- int bangumiId, String pluginName, int episodeNumber) async {- final recordKey = '${pluginName}_$bangumiId';- final episode =- _repository.getEpisode(bangumiId, pluginName, episodeNumber);- _downloadManager.cancel(recordKey, episodeNumber);- _cancelResolve(recordKey, episodeNumber);- await _downloadManager.deleteEpisodeFiles(- bangumiId,- pluginName,- episodeNumber,- episode: episode,- );- await _repository.deleteEpisode(recordKey, episodeNumber);- _refreshRecord(recordKey);- _queueBackgroundNotificationUpdate();- }-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);- _speeds.remove('${recordKey}_$ep');- }- }+ final episodes = <int, DownloadEpisode>{...?record?.episodes};_cancelResolveRecord(recordKey);- await _downloadManager.deleteRecordFiles(- bangumiId,- pluginName,- record: record,- );- await _repository.deleteRecord(recordKey);- _refreshRecord(recordKey);- _queueBackgroundNotificationUpdate();+ await _stopEpisodes(recordKey, episodes);+ try {+ await _downloadManager.deleteRecordFiles(+ bangumiId,+ pluginName,+ record: record,+ );+ await _repository.deleteRecord(recordKey);+ } finally {+ _refreshRecord(recordKey);+ _queueBackgroundNotificationUpdate();+ }}Future<void> deleteEpisode(int bangumiId, String pluginName, int episodeNumber) async {final recordKey = '${pluginName}_$bangumiId';- _downloadManager.cancel(recordKey, episodeNumber);- _speeds.remove('${recordKey}_$episodeNumber');- _cancelResolve(recordKey, episodeNumber);final episode =_repository.getEpisode(bangumiId, pluginName, episodeNumber);- await _downloadManager.deleteEpisodeFiles(- bangumiId,- pluginName,- episodeNumber,- episode: episode,- );- await _repository.deleteEpisode(recordKey, episodeNumber);- _refreshRecord(recordKey);- _queueBackgroundNotificationUpdate();+ _cancelResolve(recordKey, episodeNumber);+ await _stopEpisodes(recordKey, {episodeNumber: ?episode});+ try {+ await _downloadManager.deleteEpisodeFiles(+ bangumiId,+ pluginName,+ episodeNumber,+ episode: episode,+ );+ await _repository.deleteEpisode(recordKey, episodeNumber);+ } finally {+ _refreshRecord(recordKey);+ _queueBackgroundNotificationUpdate();+ }+ }++ /// Stops downloads before their files are deleted. Active episodes are+ /// persisted as paused first, so a failed deletion leaves them resumable.+ Future<void> _stopEpisodes(+ String recordKey, Map<int, DownloadEpisode> episodes) async {+ for (final episodeNumber in episodes.keys) {+ _downloadManager.cancel(recordKey, episodeNumber);+ _speeds.remove('${recordKey}_$episodeNumber');+ }+ for (final entry in episodes.entries) {+ final episode = entry.value;+ if (episode.status == DownloadStatus.downloading ||+ episode.status == DownloadStatus.resolving ||+ episode.status == DownloadStatus.pending) {+ episode.status = DownloadStatus.paused;+ await _repository.updateEpisode(recordKey, entry.key, episode);+ }+ }}Future<void> priorityDownload({diff --git a/lib/pages/download/download_page.dart b/lib/pages/download/download_page.dartindex dac68321..14aa506b 100644--- a/lib/pages/download/download_page.dart+++ b/lib/pages/download/download_page.dart@@ -9,6 +9,7 @@ import 'package:kazumi/modules/bangumi/bangumi_item.dart';import 'package:kazumi/pages/download/download_controller.dart';import 'package:kazumi/pages/download/download_widgets.dart';import 'package:kazumi/pages/video/video_playback_args.dart';+import 'package:kazumi/services/logging/logger.dart';import 'package:kazumi/utils/format.dart';class DownloadPage extends StatefulWidget {@@ -294,13 +295,15 @@ class _DownloadPageState extends State<DownloadPage> {),),TextButton(- onPressed: () {- downloadController.deleteEpisode(- record.bangumiId,- record.pluginName,- episode.episodeNumber,- );+ onPressed: () async {KazumiDialog.dismiss();+ await _deleteDownload(+ () => downloadController.deleteEpisode(+ record.bangumiId,+ record.pluginName,+ episode.episodeNumber,+ ),+ );},child: Text('删除',@@ -326,12 +329,14 @@ class _DownloadPageState extends State<DownloadPage> {),),TextButton(- onPressed: () {- downloadController.deleteRecord(- record.bangumiId,- record.pluginName,- );+ onPressed: () async {KazumiDialog.dismiss();+ await _deleteDownload(+ () => downloadController.deleteRecord(+ record.bangumiId,+ record.pluginName,+ ),+ );},child: Text('删除',@@ -342,4 +347,26 @@ class _DownloadPageState extends State<DownloadPage> {),);}++ Future<void> _deleteDownload(Future<void> Function() delete) async {+ try {+ await delete();+ } catch (e) {+ KazumiLogger().w('DownloadPage: failed to delete download', error: e);+ if (!mounted) return;+ KazumiDialog.show(+ context: context,+ builder: (context) => AlertDialog(+ title: const Text('删除失败'),+ content: const Text('删除下载文件失败,请稍后重试'),+ actions: [+ TextButton(+ onPressed: () => KazumiDialog.dismiss(context: context),+ child: const Text('确定'),+ ),+ ],+ ),+ );+ }+ }}diff --git a/lib/pages/settings/download_settings.dart b/lib/pages/settings/download_settings.dartindex 78a23dd4..2e26fff4 100644--- a/lib/pages/settings/download_settings.dart+++ b/lib/pages/settings/download_settings.dart@@ -1,13 +1,12 @@import 'dart:io';-import 'package:file_picker/file_picker.dart';import 'package:flutter/material.dart';import 'package:kazumi/bean/dialog/dialog_helper.dart';import 'package:kazumi/bean/settings/settings_detail_scaffold.dart';import 'package:kazumi/bean/settings/settings_list.dart';import 'package:kazumi/bean/widget/loading_indicator.dart';-import 'package:kazumi/services/platform/secure_bookmark_service.dart';+import 'package:kazumi/services/download/download_directory_service.dart';import 'package:kazumi/services/storage/storage.dart';import 'package:kazumi/utils/file_system.dart';@@ -19,6 +18,7 @@ class DownloadSettingsPage extends StatefulWidget {}class _DownloadSettingsPageState extends State<DownloadSettingsPage> {+ final _directoryService = DownloadDirectoryService();late int parallelEpisodes;late int parallelSegments;late bool downloadDanmaku;@@ -34,15 +34,11 @@ class _DownloadSettingsPageState extends State<DownloadSettingsPage> {parallelSegments =GStorage.getSetting(SettingsKeys.downloadParallelSegments);downloadDanmaku = GStorage.getSetting(SettingsKeys.downloadDanmaku);- downloadDirectory =- GStorage.getSetting(SettingsKeys.downloadDirectory).trim();+ downloadDirectory = _directoryService.customDirectory;_loadDefaultDownloadDirectory();}- bool get _canPickDirectory => supportsCustomDownloadDirectory;-- bool get _hasCustomDirectory =>- _canPickDirectory && downloadDirectory.isNotEmpty;+ bool get _hasCustomDirectory => downloadDirectory.isNotEmpty;String get _effectiveDownloadDirectory =>_hasCustomDirectory ? downloadDirectory : defaultDownloadDirectory;@@ -56,38 +52,18 @@ class _DownloadSettingsPageState extends State<DownloadSettingsPage> {}Future<void> _selectDownloadDirectory() async {- if (!_canPickDirectory) {- KazumiDialog.showToast(message: '当前平台不支持手动选择目录');- return;- }if (isSelectingDirectory) return;setState(() => isSelectingDirectory = true);try {- final effectiveDirectory = _effectiveDownloadDirectory;- final initialDirectory = effectiveDirectory.isNotEmpty &&- await Directory(effectiveDirectory).exists()- ? effectiveDirectory- : null;- final selectedPath = await FilePicker.platform.getDirectoryPath(- dialogTitle: '选择下载位置',- initialDirectory: initialDirectory,- );- if (selectedPath == null || selectedPath.isEmpty) return;-- await ensureDirectoryWritable(selectedPath);- if (!await SecureBookmarkService.persist(selectedPath)) {- KazumiDialog.showToast(message: '无法获得该目录的持久访问权限,请更换目录');- return;- }- await GStorage.putSetting(- SettingsKeys.downloadDirectory,- selectedPath,- );+ final selectedPath = await _directoryService.selectDirectory();+ if (selectedPath == null) return;if (mounted) {setState(() => downloadDirectory = selectedPath);}KazumiDialog.showToast(message: '下载位置已更新,仅对新下载生效');+ } on DownloadDirectoryException catch (e) {+ KazumiDialog.showToast(message: e.message);} on FileSystemException catch (e) {KazumiDialog.showToast(message: '无法写入该目录: ${e.message}');} catch (e) {@@ -100,8 +76,7 @@ class _DownloadSettingsPageState extends State<DownloadSettingsPage> {}Future<void> _resetDownloadDirectory() async {- await SecureBookmarkService.clear();- await GStorage.putSetting(SettingsKeys.downloadDirectory, '');+ await _directoryService.resetDirectory();if (mounted) {setState(() => downloadDirectory = '');}diff --git a/lib/services/download/download_directory_service.dart b/lib/services/download/download_directory_service.dartnew file mode 100644index 00000000..289fab88--- /dev/null+++ b/lib/services/download/download_directory_service.dart@@ -0,0 +1,150 @@+import 'dart:io';++import 'package:file_picker/file_picker.dart';+import 'package:flutter/services.dart';+import 'package:kazumi/services/logging/logger.dart';+import 'package:kazumi/services/storage/storage.dart';+import 'package:kazumi/utils/file_system.dart';+import 'package:macos_secure_bookmarks/macos_secure_bookmarks.dart';+import 'package:path/path.dart' as path;++class DownloadDirectoryException implements Exception {+ const DownloadDirectoryException(this.message);++ final String message;++ @override+ String toString() => message;+}++/// Owns where downloads are stored. Access is settled when the directory is+/// picked and, on macOS, restored once per launch, so downloads, playback and+/// deletion all work with plain filesystem paths.+class DownloadDirectoryService {+ static final DownloadDirectoryService _instance =+ DownloadDirectoryService._internal();+ factory DownloadDirectoryService() => _instance;+ DownloadDirectoryService._internal();++ static const _androidChannel = MethodChannel(+ 'com.predidit.kazumi/download_directory',+ );+ final _bookmarks = SecureBookmarks();+ bool _accessLost = false;++ bool get supportsCustomDirectory =>+ Platform.isAndroid || Platform.isMacOS || Platform.isWindows;++ /// Empty while the default directory is in use.+ String get customDirectory => supportsCustomDirectory+ ? GStorage.getSetting(SettingsKeys.downloadDirectory).trim()+ : '';++ /// Restores sandbox access to the custom directory before anything reads or+ /// writes downloads. Other platforms keep the access granted when picking.+ Future<void> restoreAccess() async {+ final directory = customDirectory;+ if (!Platform.isMacOS || directory.isEmpty) return;+ try {+ final restored = await _bookmarks.resolveBookmark(+ GStorage.getSetting(SettingsKeys.downloadDirectoryBookmark),+ isDirectory: true,+ );+ _accessLost =+ !await _bookmarks.startAccessingSecurityScopedResource(restored);+ // The bookmark follows the directory when the user moves it.+ if (!_accessLost && !path.equals(restored.path, directory)) {+ await GStorage.putSetting(+ SettingsKeys.downloadDirectory,+ restored.path,+ );+ }+ } catch (e) {+ _accessLost = true;+ KazumiLogger().e(+ 'DownloadDirectoryService: failed to restore access to $directory',+ error: e,+ );+ }+ }++ /// Root for new downloads. A custom directory whose access could not be+ /// restored fails instead of silently redirecting downloads elsewhere.+ Future<String> getDownloadDirectory() async {+ final directory = customDirectory;+ if (directory.isEmpty) return getDefaultDownloadDirectory();+ if (_accessLost) {+ throw const DownloadDirectoryException('下载目录访问权限已失效,请在下载设置中重新选择该目录');+ }+ return directory;+ }++ /// Returns null when the user cancels. The directory is saved only after+ /// it proves writable and its access is persisted.+ Future<String?> selectDirectory() async {+ if (!supportsCustomDirectory) {+ throw const DownloadDirectoryException('当前平台不支持手动选择目录');+ }+ final current = customDirectory.isEmpty+ ? await getDefaultDownloadDirectory()+ : customDirectory;+ final selected = await _pickDirectory(+ await Directory(current).exists() ? current : null,+ );+ if (selected == null || selected.isEmpty) return null;+ await ensureDirectoryWritable(selected);+ await _persistAccess(selected);+ await GStorage.putSetting(SettingsKeys.downloadDirectory, selected);+ // The picker grant covers the rest of this session.+ _accessLost = false;+ return selected;+ }++ Future<void> resetDirectory() async {+ await GStorage.putSetting(SettingsKeys.downloadDirectoryBookmark, '');+ await GStorage.putSetting(SettingsKeys.downloadDirectory, '');+ _accessLost = false;+ }++ Future<String?> _pickDirectory(String? initialDirectory) async {+ if (!Platform.isAndroid) {+ return FilePicker.platform.getDirectoryPath(+ dialogTitle: '选择下载位置',+ initialDirectory: initialDirectory,+ );+ }+ try {+ // A document tree grant alone does not allow direct file paths.+ final granted =+ await _androidChannel.invokeMethod<bool>('requestStorageAccess') ??+ false;+ if (!granted) {+ throw const DownloadDirectoryException('未授予存储访问权限,下载位置未修改');+ }+ return await _androidChannel.invokeMethod<String>('pickDirectory', {+ 'initialDirectory': initialDirectory,+ });+ } on PlatformException catch (e) {+ throw DownloadDirectoryException(+ e.code == 'UNSUPPORTED_DIRECTORY'+ ? '请选择内部存储或 SD 卡中的本地文件夹'+ : '选择下载位置失败,请重试',+ );+ }+ }++ Future<void> _persistAccess(String directory) async {+ if (!Platform.isMacOS) return;+ final String bookmark;+ try {+ bookmark = await _bookmarks.bookmark(Directory(directory));+ } catch (e) {+ KazumiLogger().e(+ 'DownloadDirectoryService: failed to bookmark $directory',+ error: e,+ );+ throw const DownloadDirectoryException('无法获得该目录的持久访问权限,请更换目录');+ }+ await GStorage.putSetting(SettingsKeys.downloadDirectoryBookmark, bookmark);+ }+}diff --git a/lib/services/download/download_manager.dart b/lib/services/download/download_manager.dartindex 37c461f6..356035e6 100644--- a/lib/services/download/download_manager.dart+++ b/lib/services/download/download_manager.dart@@ -10,7 +10,7 @@ import 'package:kazumi/utils/m3u8_ad_filter.dart';import 'package:kazumi/utils/format.dart' as fmt;import 'package:kazumi/utils/file_system.dart';import 'package:kazumi/services/logging/logger.dart';-import 'package:kazumi/services/platform/secure_bookmark_service.dart';+import 'package:kazumi/services/download/download_directory_service.dart';import 'package:kazumi/services/storage/storage.dart';import 'package:path/path.dart' as path;@@ -138,6 +138,7 @@ class DownloadManager implements IDownloadManager {}final DownloadHttpClient _http = DownloadHttpClient.instance;+ final DownloadDirectoryService _directoryService = DownloadDirectoryService();final Map<String, DownloadTask> _activeTasks = {};final List<DownloadRequest> _queue = [];@@ -215,22 +216,6 @@ class DownloadManager implements IDownloadManager {bool isDownloading(String recordKey, int episodeNumber) =>_activeTasks.containsKey(_taskKey(recordKey, episodeNumber));- Future<String> get _downloadBaseDir async {- if (supportsCustomDownloadDirectory) {- final customDir =- GStorage.getSetting(SettingsKeys.downloadDirectory).trim();- if (customDir.isNotEmpty) {- // On macOS this re-establishes sandbox access after a restart;- // elsewhere it returns the path unchanged.- final usable = await SecureBookmarkService.restore(customDir);- if (usable != null) return usable;- KazumiLogger().w(- 'DownloadManager: custom download directory unavailable, falling back to default');- }- }- return getDefaultDownloadDirectory();- }-String _getEpisodeDir(String downloadBase, int bangumiId, String pluginName,int episodeNumber) {return path.join(@@ -248,8 +233,8 @@ class DownloadManager implements IDownloadManager {final storedDir = episode.downloadDirectory.trim();final episodeDir = storedDir.isNotEmpty? storedDir- : _getEpisodeDir(- await _downloadBaseDir, bangumiId, pluginName, episodeNumber);+ : _getEpisodeDir(await _directoryService.getDownloadDirectory(),+ bangumiId, pluginName, episodeNumber);await ensureDirectoryWritable(episodeDir);episode.downloadDirectory = episodeDir;await _checkStorageSpace(episodeDir);@@ -371,6 +356,8 @@ class DownloadManager implements IDownloadManager {final key = _taskKey(recordKey, episodeNumber);final task = _activeTasks[key];if (task != null) {+ // The unwinding worker then leaves its episode paused, never active.+ task.isPaused = true;task.cancelToken.cancel('cancelled');_activeTasks.remove(key);_queue.removeWhere(@@ -420,7 +407,7 @@ class DownloadManager implements IDownloadManager {episode.status = DownloadStatus.downloading;episode.networkM3u8Url = m3u8Url;- _notifyProgress(task.recordKey, task.episodeNumber, episode);+ _notifyProgress(task, episode);String m3u8Content;try {@@ -470,14 +457,14 @@ class DownloadManager implements IDownloadManager {if (!resolvedPlaylist.isVod) {episode.status = DownloadStatus.failed;episode.errorMessage = '不支持下载直播流 (无有效分片)';- _notifyProgress(task.recordKey, task.episodeNumber, episode);+ _notifyProgress(task, episode);return;}if (resolvedPlaylist.segments.isEmpty) {episode.status = DownloadStatus.failed;episode.errorMessage = 'M3U8 中未找到可下载的分片';- _notifyProgress(task.recordKey, task.episodeNumber, episode);+ _notifyProgress(task, episode);return;}@@ -504,7 +491,7 @@ class DownloadManager implements IDownloadManager {episode.totalSegments = segments.length;episode.downloadedSegments = 0;- _notifyProgress(task.recordKey, task.episodeNumber, episode);+ _notifyProgress(task, episode);final episodeDirObj = Directory(episodeDir);if (await episodeDirObj.exists()) {await for (final entity in episodeDirObj.list()) {@@ -533,7 +520,7 @@ class DownloadManager implements IDownloadManager {episode.progressPercent = episode.totalSegments > 0? episode.downloadedSegments / episode.totalSegments: 0.0;- _notifyProgress(task.recordKey, task.episodeNumber, episode);+ _notifyProgress(task, episode);final pendingIndices = <int>[];for (int i = 0; i < segments.length; i++) {@@ -573,7 +560,7 @@ class DownloadManager implements IDownloadManager {episode.progressPercent =episode.downloadedSegments / episode.totalSegments;_speedTrackers[key]?.update(sessionBytes);- _notifyProgress(task.recordKey, task.episodeNumber, episode);+ _notifyProgress(task, episode);completedCount++;semaphore.release();if (completedCount + failedCount == pendingIndices.length) {@@ -599,14 +586,14 @@ class DownloadManager implements IDownloadManager {if (task.isPaused) {episode.status = DownloadStatus.paused;}- _notifyProgress(task.recordKey, task.episodeNumber, episode);+ _notifyProgress(task, episode);return;}if (failedCount > 0) {episode.status = DownloadStatus.failed;episode.errorMessage = '$failedCount 个分片下载失败';- _notifyProgress(task.recordKey, task.episodeNumber, episode);+ _notifyProgress(task, episode);return;}@@ -628,7 +615,7 @@ class DownloadManager implements IDownloadManager {episode.completedAt = DateTime.now();episode.totalBytes =finalVideoBytes > 0 ? finalVideoBytes : existingBytes + sessionBytes;- _notifyProgress(task.recordKey, task.episodeNumber, episode);+ _notifyProgress(task, episode);KazumiLogger().i('DownloadManager: episode ${task.episodeNumber} completed. '@@ -638,12 +625,12 @@ class DownloadManager implements IDownloadManager {episode.status = DownloadStatus.failed;episode.errorMessage ='存储空间不足 (可用: ${fmt.formatBytes(e.availableBytes)})';- _notifyProgress(task.recordKey, task.episodeNumber, episode);+ _notifyProgress(task, episode);KazumiLogger().w('DownloadManager: insufficient storage space', error: e);} on FileSystemException catch (e) {episode.status = DownloadStatus.failed;episode.errorMessage = _getStorageErrorMessage(e);- _notifyProgress(task.recordKey, task.episodeNumber, episode);+ _notifyProgress(task, episode);KazumiLogger().e('DownloadManager: file system error', error: e);} on NetworkException catch (e) {if (e.type == NetworkExceptionType.cancel) {@@ -654,14 +641,14 @@ class DownloadManager implements IDownloadManager {episode.status = DownloadStatus.failed;episode.errorMessage = e.message;}- _notifyProgress(task.recordKey, task.episodeNumber, episode);+ _notifyProgress(task, episode);} catch (e) {episode.status = DownloadStatus.failed;episode.errorMessage = e.toString();- _notifyProgress(task.recordKey, task.episodeNumber, episode);+ _notifyProgress(task, episode);KazumiLogger().e('DownloadManager: episode download failed', error: e);} finally {- _onTaskComplete(key);+ _onTaskComplete(task);}}@@ -689,7 +676,7 @@ class DownloadManager implements IDownloadManager {episode.totalSegments = 1;episode.downloadedSegments = 0;- _notifyProgress(task.recordKey, task.episodeNumber, episode);+ _notifyProgress(task, episode);final requestHeaders = Map<String, String>.from(httpHeaders);bool useRange = existingBytes > 0;@@ -751,7 +738,7 @@ class DownloadManager implements IDownloadManager {episode.progressPercent = totalSize > 0 ? received / totalSize : 0;// Update speed tracker_speedTrackers[key]?.update(received);- _notifyProgress(task.recordKey, task.episodeNumber, episode);+ _notifyProgress(task, episode);}} finally {await raf.close();@@ -761,7 +748,7 @@ class DownloadManager implements IDownloadManager {if (task.isPaused) {episode.status = DownloadStatus.paused;}- _notifyProgress(task.recordKey, task.episodeNumber, episode);+ _notifyProgress(task, episode);return;}@@ -773,7 +760,7 @@ class DownloadManager implements IDownloadManager {episode.progressPercent = 1.0;episode.completedAt = DateTime.now();episode.totalBytes = await File(filePath).length();- _notifyProgress(task.recordKey, task.episodeNumber, episode);+ _notifyProgress(task, episode);KazumiLogger().i('DownloadManager: episode ${task.episodeNumber} completed (direct download). '@@ -783,12 +770,12 @@ class DownloadManager implements IDownloadManager {episode.status = DownloadStatus.failed;episode.errorMessage ='存储空间不足 (可用: ${fmt.formatBytes(e.availableBytes)})';- _notifyProgress(task.recordKey, task.episodeNumber, episode);+ _notifyProgress(task, episode);KazumiLogger().w('DownloadManager: insufficient storage space', error: e);} on FileSystemException catch (e) {episode.status = DownloadStatus.failed;episode.errorMessage = _getStorageErrorMessage(e);- _notifyProgress(task.recordKey, task.episodeNumber, episode);+ _notifyProgress(task, episode);KazumiLogger().e('DownloadManager: file system error', error: e);} on NetworkException catch (e) {if (e.type == NetworkExceptionType.cancel) {@@ -799,28 +786,33 @@ class DownloadManager implements IDownloadManager {episode.status = DownloadStatus.failed;episode.errorMessage = e.message;}- _notifyProgress(task.recordKey, task.episodeNumber, episode);+ _notifyProgress(task, episode);} catch (e) {episode.status = DownloadStatus.failed;episode.errorMessage = e.toString();- _notifyProgress(task.recordKey, task.episodeNumber, episode);+ _notifyProgress(task, episode);KazumiLogger().e('DownloadManager: direct file download failed', error: e);}}- void _onTaskComplete(String key) {- _activeTasks.remove(key);- _speedTrackers.remove(key);+ void _onTaskComplete(DownloadTask task) {+ final key = _taskKey(task.recordKey, task.episodeNumber);+ // A retry may already own this key while the cancelled task is unwinding.+ if (_activeTasks[key] == null || identical(_activeTasks[key], task)) {+ _activeTasks.remove(key);+ _speedTrackers.remove(key);+ }_runningCount--;_processQueue();}- void _notifyProgress(- String recordKey, int episodeNumber, DownloadEpisode episode) {- final key = _taskKey(recordKey, episodeNumber);+ void _notifyProgress(DownloadTask task, DownloadEpisode episode) {+ final key = _taskKey(task.recordKey, task.episodeNumber);+ // Cancelled or superseded tasks no longer own the episode.+ if (!identical(_activeTasks[key], task)) return;final speed = _speedTrackers[key]?.currentSpeed ?? 0.0;- onProgress?.call(recordKey, episodeNumber, episode, speed);+ onProgress?.call(task.recordKey, task.episodeNumber, episode, speed);}Future<String> _fetchM3u8(diff --git a/lib/services/platform/secure_bookmark_service.dart b/lib/services/platform/secure_bookmark_service.dartdeleted file mode 100644index 042642d3..00000000--- a/lib/services/platform/secure_bookmark_service.dart+++ /dev/null@@ -1,60 +0,0 @@-import 'dart:io';--import 'package:kazumi/services/logging/logger.dart';-import 'package:kazumi/services/storage/storage.dart';-import 'package:macos_secure_bookmarks/macos_secure_bookmarks.dart';--/// Keeps the user-picked download directory writable across app restarts on-/// sandboxed macOS via security-scoped bookmarks. No-op on other platforms.-class SecureBookmarkService {- SecureBookmarkService._();-- static final _bookmarks = SecureBookmarks();- static String _accessedPath = '';-- /// Persist a bookmark for [path] just picked by the user. Returns false if- /// the bookmark cannot be created, in which case the path must not be used.- static Future<bool> persist(String path) async {- if (!Platform.isMacOS) return true;- try {- final bookmark = await _bookmarks.bookmark(Directory(path));- await GStorage.putSetting(- SettingsKeys.downloadDirectoryBookmark, bookmark);- // The picker grant already covers this session.- _accessedPath = path;- return true;- } catch (e) {- KazumiLogger()- .e('SecureBookmarkService: failed to bookmark $path', error: e);- return false;- }- }-- /// Restore write access to the custom directory [path]. Returns the usable- /// path (which may differ from [path] if the directory was moved), or null- /// when access cannot be restored.- static Future<String?> restore(String path) async {- if (!Platform.isMacOS) return path;- if (_accessedPath == path) return path;- final String bookmark =- GStorage.getSetting(SettingsKeys.downloadDirectoryBookmark);- if (bookmark.isEmpty) return null;- try {- final entity = await _bookmarks.resolveBookmark(bookmark);- await _bookmarks.startAccessingSecurityScopedResource(entity);- _accessedPath = entity.path;- return entity.path;- } catch (e) {- KazumiLogger().e(- 'SecureBookmarkService: failed to restore access to $path',- error: e);- return null;- }- }-- static Future<void> clear() async {- if (!Platform.isMacOS) return;- await GStorage.putSetting(SettingsKeys.downloadDirectoryBookmark, '');- _accessedPath = '';- }-}diff --git a/lib/utils/file_system.dart b/lib/utils/file_system.dartindex 56b698e1..ba9d47bd 100644--- a/lib/utils/file_system.dart+++ b/lib/utils/file_system.dart@@ -3,12 +3,6 @@ import 'dart:io';import 'package:path/path.dart' as path;import 'package:path_provider/path_provider.dart';-/// Custom download directories are supported on desktop platforms where the-/// user can grant persistent access to an arbitrary directory. On macOS this-/// additionally requires a security-scoped bookmark (SecureBookmarkService).-bool get supportsCustomDownloadDirectory =>- Platform.isWindows || Platform.isMacOS;-Future<String> getDefaultDownloadDirectory() async {final appSupport = await getApplicationSupportDirectory();return path.join(appSupport.path, 'downloads');diff --git a/test/download_path_migration_test.dart b/test/download_path_migration_test.dartindex 7061af29..42e95965 100644--- a/test/download_path_migration_test.dart+++ b/test/download_path_migration_test.dart@@ -1,354 +1,69 @@-import 'dart:async';-import 'dart:io';-import 'package:flutter_test/flutter_test.dart';import 'package:hive_ce/hive.dart';import 'package:kazumi/modules/download/download_module.dart';-import 'package:kazumi/services/download/download_manager.dart';import 'package:kazumi/services/download/download_path_migration.dart';-import 'package:kazumi/services/storage/storage.dart';import 'package:logger/logger.dart';import 'package:path/path.dart' as path;-import 'package:path_provider_platform_interface/path_provider_platform_interface.dart';void main() {- late Directory temporaryDirectory;- late PathProviderPlatform originalPaths;+ setUpAll(() => Logger.level = Level.off);++ test('rebases recorded paths under the current download root', () async {+ String oldDirectory(int episode) =>+ path.join('old', 'downloads', '123_source', '$episode');+ String newDirectory(int episode) =>+ path.join('new', 'downloads', '123_source', '$episode');+ final record = _record({+ 1: _episode(oldDirectory(1), path.join(oldDirectory(1), 'playlist.m3u8')),+ 2: _episode(oldDirectory(2), ''),+ 3: _episode('', ''),+ // Older records can hold a video path without a recorded directory.+ 4: _episode('', path.join(oldDirectory(4), 'video.mp4')),+ });+ final downloads = _MemoryDownloads({record.key: record});- setUpAll(() async {- Logger.level = Level.off;- temporaryDirectory = await Directory.systemTemp.createTemp(- 'kazumi_download_paths_',+ await rebaseIosDownloadPaths(+ downloads,+ downloadDirectory: () async => path.join('new', 'downloads'),);- originalPaths = PathProviderPlatform.instance;- PathProviderPlatform.instance = _TestPaths(temporaryDirectory.path);- Hive.init(path.join(temporaryDirectory.path, 'hive'));- await GStorage.init();- });- setUp(() async {- PathProviderPlatform.instance = _TestPaths(temporaryDirectory.path);- await GStorage.downloads.clear();- });-- tearDownAll(() async {- await Hive.close();- PathProviderPlatform.instance = originalPaths;- expect(- path.isWithin(Directory.systemTemp.path, temporaryDirectory.path),- isTrue,- );+ final episodes = downloads.get(record.key)!.episodes;+ expect(episodes[1]!.downloadDirectory, newDirectory(1));expect(- path.basename(temporaryDirectory.path),- startsWith('kazumi_download_paths_'),+ episodes[1]!.localM3u8Path,+ path.join(newDirectory(1), 'playlist.m3u8'),);- await temporaryDirectory.delete(recursive: true);+ expect(episodes[2]!.downloadDirectory, newDirectory(2));+ expect(episodes[2]!.localM3u8Path, isEmpty);+ expect(episodes[3]!.downloadDirectory, isEmpty);+ expect(episodes[3]!.localM3u8Path, isEmpty);+ expect(episodes[4]!.localM3u8Path, path.join(newDirectory(4), 'video.mp4'));+ expect(downloads.saved, {record.key});});- for (final filename in ['playlist.m3u8', 'video.mp4']) {- test(- 'relocated $filename can be played and deleted after reopening Hive',- () async {- final oldContainer = Directory(- path.join(temporaryDirectory.path, filename, 'old-container'),- );- final newContainer = Directory(- path.join(temporaryDirectory.path, filename, 'new-container'),- );- String base(Directory container) => path.join(- container.path,- 'Library',- 'Application Support',- 'downloads',- );- final oldEpisodeDirectory = path.join(- base(oldContainer),- '123_source',- '1',- );- await Directory(oldEpisodeDirectory).create(recursive: true);- final oldVideo = File(path.join(oldEpisodeDirectory, filename));- await oldVideo.writeAsString('downloaded video');- await File(- path.join(oldEpisodeDirectory, 'seg_00000.ts'),- ).writeAsString('segment');- await File(- path.join(oldEpisodeDirectory, 'danmaku.json'),- ).writeAsString('[]');- final episode = _episode(- directory: oldEpisodeDirectory,- videoPath: oldVideo.path,- );- final record = _record({1: episode});- await GStorage.downloads.put(record.key, record);- final manager = DownloadManager();- expect(manager.getLocalVideoPath(episode), oldVideo.path);-- expect(- path.isWithin(temporaryDirectory.path, oldContainer.path),- isTrue,- );- expect(- path.isWithin(temporaryDirectory.path, newContainer.path),- isTrue,- );- await oldContainer.rename(newContainer.path);- expect(manager.getLocalVideoPath(episode), isNull);-- PathProviderPlatform.instance = _TestPaths(- path.join(newContainer.path, 'Library', 'Application Support'),- );- await rebaseIosDownloadPaths(GStorage.downloads);- await GStorage.downloads.close();- GStorage.downloads = await Hive.openBox<DownloadRecord>('downloads');- final restoredRecord = GStorage.downloads.get(record.key)!;- final restoredEpisode = restoredRecord.episodes[1]!;- final newEpisodeDirectory = path.join(- base(newContainer),- '123_source',- '1',- );- expect(restoredEpisode.downloadDirectory, newEpisodeDirectory);- expect(- manager.getLocalVideoPath(restoredEpisode),- path.join(newEpisodeDirectory, filename),- );- expect(- File(path.join(newEpisodeDirectory, 'danmaku.json')).existsSync(),- isTrue,- );- expect(restoredEpisode.status, DownloadStatus.completed);- expect(restoredEpisode.totalBytes, 42);-- // A second startup must leave already restored paths unchanged.- await rebaseIosDownloadPaths(GStorage.downloads);- expect(- GStorage.downloads.get(record.key)!.episodes[1]!.localM3u8Path,- path.join(newEpisodeDirectory, filename),- );-- if (filename == 'playlist.m3u8') {- await manager.deleteEpisodeFiles(- 123,- 'source',- 1,- episode: restoredEpisode,- );- } else {- await manager.deleteRecordFiles(- 123,- 'source',- record: restoredRecord,- );- }- expect(Directory(newEpisodeDirectory).existsSync(), isFalse);- },- );- }-- test(- 'partial downloads keep their files and unstarted episodes stay empty',- () async {- final oldDirectory = path.join(- temporaryDirectory.path,- 'stale',- '123_source',- '2',- );- final currentBase = path.join(- temporaryDirectory.path,- 'current',- 'downloads',- );- final currentDirectory = path.join(currentBase, '123_source', '2');- await Directory(currentDirectory).create(recursive: true);- final segment = File(path.join(currentDirectory, 'seg_00000.ts'));- await segment.writeAsString('partial download');- final partial = _episode(directory: oldDirectory, videoPath: '')- ..episodeNumber = 2- ..status = DownloadStatus.paused;- final unstarted = _episode(directory: '', videoPath: '')- ..episodeNumber = 3- ..status = DownloadStatus.pending;- // Older records can contain a local file path without a recorded directory.- final legacy = _episode(- directory: '',- videoPath: path.join(oldDirectory, 'video.mp4'),- )..episodeNumber = 4;- await GStorage.downloads.put(- 'source_123',- _record({2: partial, 3: unstarted, 4: legacy}),- );-- await rebaseIosDownloadPaths(- GStorage.downloads,- downloadDirectory: () async => currentBase,- );-- final restored = GStorage.downloads.get('source_123')!;- expect(restored.episodes[2]!.downloadDirectory, currentDirectory);- expect(restored.episodes[2]!.localM3u8Path, isEmpty);- expect(restored.episodes[2]!.status, DownloadStatus.paused);- expect(await segment.readAsString(), 'partial download');- expect(restored.episodes[3]!.downloadDirectory, isEmpty);- expect(restored.episodes[3]!.localM3u8Path, isEmpty);- expect(- restored.episodes[4]!.localM3u8Path,- path.join(currentBase, '123_source', '4', 'video.mp4'),- );- expect(DownloadManager().getLocalVideoPath(restored.episodes[4]), isNull);- },- );+ test('a failed directory lookup leaves records untouched', () async {+ final directory = path.join('old', 'downloads', '123_source', '1');+ final record = _record({1: _episode(directory, '')});+ final downloads = _MemoryDownloads({record.key: record});- test('resuming a relocated download reuses its existing segments', () async {- final currentBase = path.join(- temporaryDirectory.path,- 'resume',- 'downloads',- );- final currentDirectory = path.join(currentBase, '123_source', '1');- await Directory(currentDirectory).create(recursive: true);- final existingSegment = File(path.join(currentDirectory, 'seg_00000.ts'));- await existingSegment.writeAsString('already downloaded');- final partial = _episode(- directory: '/old-container/downloads/123_source/1',- videoPath: '',- )..status = DownloadStatus.paused;- await GStorage.downloads.put('source_123', _record({1: partial}));- await rebaseIosDownloadPaths(- GStorage.downloads,- downloadDirectory: () async => currentBase,- );- final restored = GStorage.downloads.get('source_123')!.episodes[1]!;-- final server = await HttpServer.bind(InternetAddress.loopbackIPv4, 0);- final requests = <String>[];- server.listen((request) async {- requests.add(request.uri.path);- switch (request.uri.path) {- case '/playlist.m3u8':- request.response.write(- '#EXTM3U\n#EXT-X-TARGETDURATION:10\n'- '#EXTINF:10,\nfirst.ts\n#EXTINF:10,\nsecond.ts\n#EXT-X-ENDLIST\n',- );- case '/second.ts':- request.response.write('new segment');- default:- request.response.statusCode = HttpStatus.notFound;- }- await request.response.close();- });- final finished = Completer<void>();- final manager = DownloadManager()- ..onProgress = (_, _, episode, _) {- if (finished.isCompleted) return;- if (episode.status == DownloadStatus.completed) finished.complete();- if (episode.status == DownloadStatus.failed) {- finished.completeError(StateError(episode.errorMessage));- }- };- try {- await manager.resume(- DownloadRequest(- recordKey: 'source_123',- bangumiId: 123,- pluginName: 'source',- episodeNumber: 1,- m3u8Url: 'http://127.0.0.1:${server.port}/playlist.m3u8',- httpHeaders: const {},- adBlockerEnabled: false,- episode: restored,- ),- );- await finished.future.timeout(const Duration(seconds: 15));- expect(await existingSegment.readAsString(), 'already downloaded');- expect(- await File(path.join(currentDirectory, 'seg_00001.ts')).readAsString(),- 'new segment',- );- expect(requests, ['/playlist.m3u8', '/second.ts']);- expect(- manager.getLocalVideoPath(restored),- path.join(currentDirectory, 'playlist.m3u8'),- );- } finally {- manager.cancel('source_123', 1);- await server.close(force: true);- }- });-- test('directory lookup failure leaves existing downloads usable', () async {- final original = _record({- 1: _episode(directory: '/old/downloads/123_source/1', videoPath: ''),- });- await GStorage.downloads.put(original.key, original);await expectLater(rebaseIosDownloadPaths(- GStorage.downloads,- downloadDirectory: () async => throw FileSystemException('unavailable'),+ downloads,+ downloadDirectory: () async => throw StateError('unavailable'),),completes,);expect(- GStorage.downloads.get(original.key)!.episodes[1]!.downloadDirectory,- '/old/downloads/123_source/1',+ downloads.get(record.key)!.episodes[1]!.downloadDirectory,+ directory,);});-- for (final failOnFlush in [false, true]) {- test(- 'migration tolerates ${failOnFlush ? 'flush' : 'write'} failure and retries',- () async {- final original = _record({- 1: _episode(directory: '/old/downloads/123_source/1', videoPath: ''),- });- await GStorage.downloads.put(original.key, original);- final currentBase = path.join(- temporaryDirectory.path,- 'retry',- 'downloads',- );- await expectLater(- rebaseIosDownloadPaths(- _FailingDownloads(GStorage.downloads, failOnFlush: failOnFlush),- downloadDirectory: () async => currentBase,- ),- completes,- );- await GStorage.downloads.close();- GStorage.downloads = await Hive.openBox<DownloadRecord>('downloads');- if (!failOnFlush) {- expect(- GStorage.downloads- .get(original.key)!- .episodes[1]!- .downloadDirectory,- '/old/downloads/123_source/1',- );- }-- await rebaseIosDownloadPaths(- GStorage.downloads,- downloadDirectory: () async => currentBase,- );- await GStorage.downloads.close();- GStorage.downloads = await Hive.openBox<DownloadRecord>('downloads');- expect(- GStorage.downloads.get(original.key)!.episodes[1]!.downloadDirectory,- path.join(currentBase, '123_source', '1'),- );- },- );- }}DownloadRecord _record(Map<int, DownloadEpisode> episodes) =>DownloadRecord(123, 'anime', '', 'source', episodes, DateTime(2026));-DownloadEpisode _episode({- required String directory,- required String videoPath,-}) => DownloadEpisode(+DownloadEpisode _episode(String directory, String videoPath) => DownloadEpisode(1,'episode',0,@@ -365,36 +80,27 @@ DownloadEpisode _episode({'',);-class _TestPaths extends PathProviderPlatform {- _TestPaths(this.directory);-- final String directory;-- @override- Future<String?> getApplicationSupportPath() async => directory;-}--class _FailingDownloads implements Box<DownloadRecord> {- _FailingDownloads(this.delegate, {required this.failOnFlush});+class _MemoryDownloads implements Box<DownloadRecord> {+ _MemoryDownloads(this._records);- final Box<DownloadRecord> delegate;- final bool failOnFlush;+ final Map<String, DownloadRecord> _records;+ final saved = <dynamic>{};@override- Iterable<dynamic> get keys => delegate.keys;+ Iterable<dynamic> get keys => _records.keys;@overrideDownloadRecord? get(dynamic key, {DownloadRecord? defaultValue}) =>- delegate.get(key, defaultValue: defaultValue);+ _records[key] ?? defaultValue;@overrideFuture<void> put(dynamic key, DownloadRecord value) async {- if (!failOnFlush) throw FileSystemException('No space left on device');- await delegate.put(key, value);+ _records[key as String] = value;+ saved.add(key);}@override- Future<void> flush() async => throw FileSystemException('flush failed');+ Future<void> flush() async {}@overridedynamic noSuchMethod(Invocation invocation) => super.noSuchMethod(invocation);