基于自定义规则的番剧采集APP,支持流媒体在线观看,支持弹幕,支持实时超分辨率。
feat(android): background download (#1700)
林晨1fb1dd220e84
diff --git a/android/app/src/main/AndroidManifest.xml b/android/app/src/main/AndroidManifest.xmlindex 1cfd903a..0efed673 100644--- a/android/app/src/main/AndroidManifest.xml+++ b/android/app/src/main/AndroidManifest.xml@@ -35,12 +35,19 @@<meta-dataandroid:name="flutterEmbedding"android:value="2" />+ <!-- flutter_foreground_task service -->+ <service+ android:name="com.pravera.flutter_foreground_task.service.ForegroundService"+ android:foregroundServiceType="dataSync"+ android:exported="false" /></application><uses-permission android:name="android.permission.INTERNET" /><uses-permission android:name="android.permission.ACCESS_WIFI_STATE" /><uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /><uses-permission android:name="android.permission.WAKE_LOCK"/><uses-permission android:name="android.permission.FOREGROUND_SERVICE"/>+ <uses-permission android:name="android.permission.FOREGROUND_SERVICE_DATA_SYNC"/>+ <uses-permission android:name="android.permission.POST_NOTIFICATIONS"/><uses-permission android:name="android.permission.REQUEST_INSTALL_PACKAGES" /><!-- Required to query activities that can process text, see:https://developer.android.com/training/package-visibility?hl=en anddiff --git a/android/app/src/main/kotlin/com/example/kazumi/MainActivity.kt b/android/app/src/main/kotlin/com/example/kazumi/MainActivity.ktindex 5c87a816..6f114b7d 100644--- a/android/app/src/main/kotlin/com/example/kazumi/MainActivity.kt+++ b/android/app/src/main/kotlin/com/example/kazumi/MainActivity.kt@@ -1,7 +1,8 @@package com.example.kazumiimport android.content.Intent-import android.os.Build;+import android.os.Build+import android.os.StatFsimport android.net.Uriimport android.os.Bundleimport androidx.annotation.NonNull@@ -11,6 +12,7 @@ import io.flutter.embedding.android.FlutterActivityclass MainActivity: FlutterActivity() {private val CHANNEL = "com.predidit.kazumi/intent"+ private val STORAGE_CHANNEL = "com.predidit.kazumi/storage"override fun configureFlutterEngine(@NonNull flutterEngine: FlutterEngine) {super.configureFlutterEngine(flutterEngine)@@ -34,6 +36,16 @@ class MainActivity: FlutterActivity() {result.notImplemented()}}++ MethodChannel(flutterEngine.dartExecutor.binaryMessenger, STORAGE_CHANNEL).setMethodCallHandler { call, result ->+ if (call.method == "getAvailableStorage") {+ val path = call.argument<String>("path") ?: filesDir.absolutePath+ val availableBytes = getAvailableStorage(path)+ result.success(availableBytes)+ } else {+ result.notImplemented()+ }+ }}private fun openWithMime(url: String, mimeType: String) {@@ -54,4 +66,13 @@ class MainActivity: FlutterActivity() {private fun getAndroidSdkVersion(): Int {return Build.VERSION.SDK_INT}++ private fun getAvailableStorage(path: String): Long {+ return try {+ val stat = StatFs(path)+ stat.availableBlocksLong * stat.blockSizeLong+ } catch (e: Exception) {+ -1L+ }+ }}diff --git a/ios/Runner/AppDelegate.swift b/ios/Runner/AppDelegate.swiftindex e3c90457..3e9e4e80 100644--- a/ios/Runner/AppDelegate.swift+++ b/ios/Runner/AppDelegate.swift@@ -32,6 +32,29 @@ import AVKitresult(FlutterMethodNotImplemented)}}++ let storageChannel = FlutterMethodChannel(+ name: "com.predidit.kazumi/storage",+ binaryMessenger: engineBridge.applicationRegistrar.messenger()+ )+ storageChannel.setMethodCallHandler { (call: FlutterMethodCall, result: @escaping FlutterResult) in+ if call.method == "getAvailableStorage" {+ do {+ let attrs = try FileManager.default.attributesOfFileSystem(+ forPath: NSHomeDirectory()+ )+ if let freeSize = attrs[.systemFreeSize] as? Int64 {+ result(freeSize)+ } else {+ result(-1)+ }+ } catch {+ result(-1)+ }+ } else {+ result(FlutterMethodNotImplemented)+ }+ }}// TODO: ADD VLC SUPPORTdiff --git a/lib/pages/download/download_controller.dart b/lib/pages/download/download_controller.dartindex d2168a91..465f37a5 100644--- a/lib/pages/download/download_controller.dart+++ b/lib/pages/download/download_controller.dart@@ -6,7 +6,9 @@ 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/background_download_service.dart';import 'package:kazumi/utils/download_manager.dart';+import 'package:kazumi/utils/format_utils.dart';import 'package:kazumi/utils/logger.dart';import 'package:kazumi/utils/storage.dart';import 'package:kazumi/providers/providers.dart';@@ -20,13 +22,14 @@ class DownloadController = _DownloadController with _$DownloadController;abstract class _DownloadController with Store {final _repository = Modular.get<IDownloadRepository>();final _downloadManager = Modular.get<IDownloadManager>();+ final _backgroundService = BackgroundDownloadService();@observableObservableList<DownloadRecord> records = ObservableList<DownloadRecord>();- /// Queue for episodes waiting to be resolved via WebView (one at a time)final List<_ResolveRequest> _resolveQueue = [];bool _isResolving = false;+ bool _isBackgroundServiceInitialized = false;void init() {final temp = _repository.getAllRecords();@@ -51,10 +54,33 @@ abstract class _DownloadController with Store {}_downloadManager.onProgress = _onDownloadProgress;+ _initBackgroundService();+ }++ Future<void> _initBackgroundService() async {+ if (!_backgroundService.isSupported) return;+ if (_isBackgroundServiceInitialized) return;++ await _backgroundService.init();+ _backgroundService.onPauseAll = pauseAllDownloads;+ _backgroundService.addTaskDataCallback(_onTaskData);+ _isBackgroundServiceInitialized = true;+ }++ void _onTaskData(Object data) {+ if (data is Map) {+ final action = data['action'];+ if (action == 'button_pressed') {+ _backgroundService.handleNotificationAction(data['id'] as String);+ } else if (action == 'navigate_to_download') {+ _backgroundService.handleNavigateToDownload();+ }+ }}- /// Speed data (in-memory, not persisted)final Map<String, double> _speeds = {};+ DateTime _lastUiUpdateTime = DateTime.now();+ static const _uiUpdateInterval = Duration(milliseconds: 500);void _onDownloadProgress(String recordKey, int episodeNumber,DownloadEpisode episode, double speed) {@@ -63,26 +89,88 @@ abstract class _DownloadController with Store {return;}_repository.updateEpisode(recordKey, episodeNumber, episode);- // Store speed in memory+final key = '${recordKey}_$episodeNumber';_speeds[key] = speed;- refreshRecords();++ final isFinalState = episode.status == DownloadStatus.completed ||+ episode.status == DownloadStatus.failed ||+ episode.status == DownloadStatus.paused;++ final now = DateTime.now();+ if (isFinalState || now.difference(_lastUiUpdateTime) >= _uiUpdateInterval) {+ _lastUiUpdateTime = now;+ refreshRecords();+ _updateBackgroundNotification();+ }+ }++ Future<void> _updateBackgroundNotification() async {+ if (!_backgroundService.isRunning) return;++ final stats = _getDownloadStats();+ if (stats.activeCount == 0 && stats.pendingCount == 0) {+ await _backgroundService.stopService();+ return;+ }++ double totalSpeed = 0;+ for (final entry in _speeds.entries) {+ totalSpeed += entry.value;+ }++ await _backgroundService.updateProgress(+ activeCount: stats.activeCount,+ totalCount: stats.totalCount,+ overallProgress: stats.overallProgress,+ speedText: formatSpeed(totalSpeed),+ );+ }++ Future<void> _startBackgroundServiceIfNeeded() async {+ if (!_backgroundService.isSupported || _backgroundService.isRunning) return;++ final started = await _backgroundService.startService();+ if (started) {+ KazumiLogger().i('DownloadController: background service started');+ }+ }++ ({int activeCount, int pendingCount, int totalCount, double overallProgress}) _getDownloadStats() {+ int activeCount = 0;+ int pendingCount = 0;+ int totalCount = 0;+ double totalProgress = 0;++ for (final record in records) {+ for (final episode in record.episodes.values) {+ if (episode.status == DownloadStatus.downloading) {+ activeCount++;+ totalCount++;+ totalProgress += episode.progressPercent;+ } else if (episode.status == DownloadStatus.resolving ||+ episode.status == DownloadStatus.pending) {+ pendingCount++;+ totalCount++;+ }+ }+ }++ final overallProgress = totalCount > 0 ? totalProgress / totalCount : 0.0;+ return (+ activeCount: activeCount,+ pendingCount: pendingCount,+ totalCount: totalCount,+ overallProgress: overallProgress,+ );}- /// 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';- }+@actionvoid refreshRecords() {@@ -124,8 +212,6 @@ abstract class _DownloadController with Store {return _repository.getCompletedEpisodes(bangumiId, pluginName);}- /// 获取缓存的弹幕数据- /// 返回 null 表示没有缓存List<Danmaku>? getCachedDanmakus(int bangumiId, String pluginName, int episodeNumber) {final episode =@@ -143,7 +229,6 @@ abstract class _DownloadController with Store {}}- /// 更新缓存的弹幕数据(用于离线播放时在线获取后保存)Future<void> updateCachedDanmakus(int bangumiId,String pluginName,@@ -192,7 +277,6 @@ abstract class _DownloadController with Store {DateTime.now(),);- // 检查是否已有相同 URL 的下载(防止列表重排序后重复下载)if (episodePageUrl.isNotEmpty) {for (final entry in record.episodes.entries) {if (entry.value.episodePageUrl == episodePageUrl) {@@ -213,7 +297,7 @@ abstract class _DownloadController with Store {0,'','',- '', // networkM3u8Url - will be filled after WebView resolves+ '',null,'',0,@@ -224,7 +308,6 @@ abstract class _DownloadController with Store {await _repository.putRecord(record);refreshRecords();- // Queue for WebView resolution_resolveQueue.add(_ResolveRequest(recordKey: recordKey,bangumiId: bangumiId,@@ -235,7 +318,6 @@ abstract class _DownloadController with Store {_processResolveQueue();}- /// Process the resolve queue one at a time (sequential WebView resolution)Future<void> _processResolveQueue() async {if (_isResolving || _resolveQueue.isEmpty) return;_isResolving = true;@@ -248,7 +330,6 @@ abstract class _DownloadController with Store {_isResolving = false;}- /// Resolve a single episode's M3U8 URL via headless WebView, then enqueue downloadFuture<void> _resolveAndEnqueue(_ResolveRequest request) async {final plugin = _findPlugin(request.pluginName);if (plugin == null) {@@ -262,7 +343,6 @@ abstract class _DownloadController with Store {final episode = record.episodes[request.episodeNumber];if (episode == null) return;- // Skip if already cancelled/deletedif (episode.status != DownloadStatus.resolving) return;final fullUrl = plugin.buildFullUrl(request.episodePageUrl);@@ -304,7 +384,6 @@ abstract class _DownloadController with Store {final freshEpisode = freshRecord.episodes[request.episodeNumber];if (freshEpisode == null) return;- // Check if user cancelled during resolutionif (freshEpisode.status != DownloadStatus.resolving) return;freshEpisode.networkM3u8Url = m3u8Url;@@ -313,7 +392,8 @@ abstract class _DownloadController with Store {request.recordKey, request.episodeNumber, freshEpisode);refreshRecords();- // Now enqueue the actual download+ await _startBackgroundServiceIfNeeded();+final httpHeaders = plugin.buildHttpHeaders();bool adBlockerEnabled = _repository.getForceAdBlocker() || plugin.adBlocker;@@ -328,12 +408,10 @@ abstract class _DownloadController with Store {episode: freshEpisode,));- // 检查是否启用弹幕缓存(并行获取,不阻塞视频下载)final Box setting = GStorage.setting;final bool downloadDanmaku =setting.get(SettingBoxKey.downloadDanmaku, defaultValue: true);if (downloadDanmaku) {- // 异步获取弹幕,不等待完成_fetchAndCacheDanmakuAsync(request.recordKey,request.bangumiId,@@ -342,10 +420,8 @@ abstract class _DownloadController with Store {}}- /// 异步获取并缓存弹幕数据(不阻塞视频下载)void _fetchAndCacheDanmakuAsync(String recordKey, int bangumiId, int episodeNumber) {- // 使用 Future 在后台执行,不阻塞调用者Future(() async {try {KazumiLogger().i(@@ -411,7 +487,6 @@ abstract class _DownloadController with Store {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);@@ -422,8 +497,33 @@ abstract class _DownloadController with Store {episode.status = DownloadStatus.paused;await _repository.updateEpisode(recordKey, episodeNumber, episode);refreshRecords();+ _updateBackgroundNotification();+ }+ }+ }++ Future<void> pauseAllDownloads() async {+ KazumiLogger().i('DownloadController: pausing all downloads');++ _resolveQueue.clear();++ for (final record in records) {+ for (final entry in record.episodes.entries) {+ final episode = entry.value;+ if (episode.status == DownloadStatus.downloading ||+ episode.status == DownloadStatus.resolving ||+ episode.status == DownloadStatus.pending) {+ final recordKey = '${record.pluginName}_${record.bangumiId}';+ _downloadManager.pause(recordKey, entry.key);+ episode.status = DownloadStatus.paused;+ await _repository.updateEpisode(recordKey, entry.key, episode);+ }}}++ refreshRecords();++ await _backgroundService.stopService();}Future<void> retryDownload({@@ -452,6 +552,8 @@ abstract class _DownloadController with Store {await _repository.updateEpisode(recordKey, episodeNumber, episode);refreshRecords();+ await _startBackgroundServiceIfNeeded();+final httpHeaders = plugin.buildHttpHeaders();bool adBlockerEnabled =_repository.getForceAdBlocker() || plugin.adBlocker;@@ -467,7 +569,6 @@ abstract class _DownloadController with Store {episode: episode,));} else {- // Need to re-resolve via WebViewepisode.status = DownloadStatus.resolving;episode.errorMessage = '';episode.progressPercent = 0.0;@@ -496,6 +597,7 @@ abstract class _DownloadController with Store {bangumiId, pluginName, episodeNumber);await _repository.deleteEpisode(recordKey, episodeNumber);refreshRecords();+ _updateBackgroundNotification();}Future<void> deleteRecord(int bangumiId, String pluginName) async {@@ -511,6 +613,7 @@ abstract class _DownloadController with Store {await _downloadManager.deleteRecordFiles(bangumiId, pluginName);await _repository.deleteRecord(recordKey);refreshRecords();+ _updateBackgroundNotification();}Future<void> deleteEpisode(@@ -524,9 +627,9 @@ abstract class _DownloadController with Store {bangumiId, pluginName, episodeNumber);await _repository.deleteEpisode(recordKey, episodeNumber);refreshRecords();+ _updateBackgroundNotification();}- /// Priority download - skip the queue and start immediatelyFuture<void> priorityDownload({required int bangumiId,required String pluginName,@@ -544,7 +647,6 @@ abstract class _DownloadController with Store {return;}- // Remove from resolve queue if waiting_resolveQueue.removeWhere((r) => r.recordKey == recordKey && r.episodeNumber == episodeNumber);@@ -554,6 +656,8 @@ abstract class _DownloadController with Store {await _repository.updateEpisode(recordKey, episodeNumber, episode);refreshRecords();+ await _startBackgroundServiceIfNeeded();+final httpHeaders = plugin.buildHttpHeaders();bool adBlockerEnabled =_repository.getForceAdBlocker() || plugin.adBlocker;@@ -569,7 +673,6 @@ abstract class _DownloadController with Store {episode: episode,));} else {- // Need to resolve first - add to front of resolve queueepisode.status = DownloadStatus.resolving;episode.errorMessage = '';await _repository.updateEpisode(recordKey, episodeNumber, episode);@@ -588,7 +691,6 @@ abstract class _DownloadController with Store {}}- /// Resume all incomplete downloads for a recordFuture<void> resumeAllDownloads(int bangumiId, String pluginName) async {final recordKey = '${pluginName}_$bangumiId';final record = _repository.getRecord(recordKey);@@ -623,14 +725,6 @@ abstract class _DownloadController with Store {.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 {diff --git a/lib/pages/download/download_page.dart b/lib/pages/download/download_page.dartindex 31e65e51..61d1cdb1 100644--- a/lib/pages/download/download_page.dart+++ b/lib/pages/download/download_page.dart@@ -7,6 +7,7 @@ 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';+import 'package:kazumi/utils/format_utils.dart';class DownloadPage extends StatefulWidget {const DownloadPage({super.key});@@ -206,14 +207,14 @@ class _DownloadPageState extends State<DownloadPage> {String _getStatusText(DownloadRecord record, DownloadEpisode episode) {switch (episode.status) {case DownloadStatus.completed:- return '已完成 ${downloadController.formatBytes(episode.totalBytes)}';+ return '已完成 ${formatBytes(episode.totalBytes)}';case DownloadStatus.downloading:final speed = downloadController.getSpeed(record.bangumiId,record.pluginName,episode.episodeNumber,);- final speedText = speed > 0 ? ' · ${downloadController.formatSpeed(speed)}' : '';+ final speedText = speed > 0 ? ' · ${formatSpeed(speed)}' : '';return '${(episode.progressPercent * 100).toStringAsFixed(0)}% ''${episode.downloadedSegments}/${episode.totalSegments}$speedText';case DownloadStatus.failed:diff --git a/lib/pages/init_page.dart b/lib/pages/init_page.dartindex c86b523f..3cf47278 100644--- a/lib/pages/init_page.dart+++ b/lib/pages/init_page.dart@@ -15,6 +15,7 @@ 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';+import 'package:kazumi/utils/background_download_service.dart';class InitPage extends StatefulWidget {const InitPage({super.key});@@ -46,6 +47,7 @@ class _InitPageState extends State<InitPage> {_webDavInit();try {downloadController.init();+ _setupBackgroundDownloadNavigation();} catch (e) {KazumiLogger().e('InitPage: downloadController.init() failed', error: e);}@@ -57,6 +59,50 @@ class _InitPageState extends State<InitPage> {_update();}+ void _setupBackgroundDownloadNavigation() {+ final backgroundService = BackgroundDownloadService();++ backgroundService.onNavigateToDownloadRequested = () {+ Future.delayed(const Duration(milliseconds: 300), () {+ try {+ if (Modular.to.path.contains('/download')) return;+ Modular.to.pushNamed('/settings/download/');+ } catch (e) {+ KazumiLogger().w('InitPage: failed to navigate to download page', error: e);+ }+ });+ };++ backgroundService.onNotificationPermissionRequired = () async {+ final result = await KazumiDialog.show<bool>(+ clickMaskDismiss: false,+ builder: (context) {+ return AlertDialog(+ title: const Text('需要通知权限'),+ content: const Text(+ '开启通知权限后,可以在后台下载时显示进度,并防止系统终止下载任务。\n\n'+ '如果拒绝,下载功能仍可使用,但在后台时可能被系统中断。',+ ),+ actions: [+ TextButton(+ onPressed: () => KazumiDialog.dismiss(popWith: false),+ child: Text(+ '稍后再说',+ style: TextStyle(color: Theme.of(context).colorScheme.outline),+ ),+ ),+ TextButton(+ onPressed: () => KazumiDialog.dismiss(popWith: true),+ child: const Text('允许'),+ ),+ ],+ );+ },+ );+ return result ?? false;+ };+ }+void _navigateToHome() {// Workaround for dynamic_color. dynamic_color need PlatformChannel to get color, it takes time.// setDynamic here to avoid white screen flash when themeMode is dark.diff --git a/lib/utils/background_download_service.dart b/lib/utils/background_download_service.dartnew file mode 100644index 00000000..691f0482--- /dev/null+++ b/lib/utils/background_download_service.dart@@ -0,0 +1,254 @@+import 'dart:io';+import 'package:flutter/foundation.dart';+import 'package:flutter_foreground_task/flutter_foreground_task.dart';+import 'package:kazumi/utils/logger.dart';++/// Android 后台下载服务+///+/// 使用 Foreground Service 保持 app 进程存活,防止系统在后台时杀死下载进程。+/// 下载逻辑仍在主 Isolate 运行,此服务仅负责:+/// 1. 显示通知栏进度+/// 2. 保持进程存活+/// 3. 提供通知栏交互(暂停/取消)+class BackgroundDownloadService {+ static final BackgroundDownloadService _instance = BackgroundDownloadService._internal();+ factory BackgroundDownloadService() => _instance;+ BackgroundDownloadService._internal();++ bool _isInitialized = false;+ bool _isRunning = false;++ void Function()? onPauseAll;+ void Function()? onCancelAll;+ void Function()? onNavigateToDownloadRequested;++ /// 返回 true 表示用户同意请求权限,false 表示用户拒绝+ Future<bool> Function()? onNotificationPermissionRequired;++ bool get isSupported => Platform.isAndroid;+ bool get isRunning => _isRunning;+ Future<void> init() async {+ if (!isSupported || _isInitialized) return;++ FlutterForegroundTask.init(+ androidNotificationOptions: AndroidNotificationOptions(+ channelId: 'kazumi_download_channel',+ channelName: '下载服务',+ channelDescription: '视频下载后台服务',+ channelImportance: NotificationChannelImportance.LOW,+ priority: NotificationPriority.LOW,+ onlyAlertOnce: true,+ ),+ iosNotificationOptions: const IOSNotificationOptions(+ showNotification: false,+ ),+ foregroundTaskOptions: ForegroundTaskOptions(+ eventAction: ForegroundTaskEventAction.nothing(),+ autoRunOnBoot: false,+ autoRunOnMyPackageReplaced: false,+ allowWakeLock: true,+ allowWifiLock: true,+ ),+ );++ FlutterForegroundTask.initCommunicationPort();++ _isInitialized = true;+ KazumiLogger().i('BackgroundDownloadService: initialized');+ }++ Future<bool> needsNotificationPermission() async {+ if (!isSupported) return false;+ final permission = await FlutterForegroundTask.checkNotificationPermission();+ return permission != NotificationPermission.granted;+ }++ Future<bool> requestNotificationPermission() async {+ if (!isSupported) return true;+ final result = await FlutterForegroundTask.requestNotificationPermission();+ return result == NotificationPermission.granted;+ }++ Future<bool> startService() async {+ if (!isSupported) return false;+ if (_isRunning) return true;++ if (!_isInitialized) {+ await init();+ }++ final needsPermission = await needsNotificationPermission();+ if (needsPermission) {+ if (onNotificationPermissionRequired != null) {+ final userAgreed = await onNotificationPermissionRequired!();+ if (userAgreed) {+ final granted = await requestNotificationPermission();+ if (!granted) {+ KazumiLogger().w('BackgroundDownloadService: notification permission denied by user');+ }+ } else {+ KazumiLogger().i('BackgroundDownloadService: user declined permission dialog');+ }+ } else {+ // 没有设置回调,直接请求权限(兼容旧行为)+ final granted = await requestNotificationPermission();+ if (!granted) {+ KazumiLogger().w('BackgroundDownloadService: notification permission denied');+ }+ }+ }++ try {+ final result = await FlutterForegroundTask.startService(+ notificationTitle: '正在下载',+ notificationText: '准备中...',+ notificationButtons: [+ const NotificationButton(id: 'pause_all', text: '暂停全部'),+ ],+ callback: _backgroundCallback,+ );++ _isRunning = result is ServiceRequestSuccess;++ if (_isRunning) {+ KazumiLogger().i('BackgroundDownloadService: service started');+ } else {+ KazumiLogger().w('BackgroundDownloadService: service start returned non-success: $result');+ }+ return _isRunning;+ } catch (e) {+ KazumiLogger().e('BackgroundDownloadService: failed to start service', error: e);+ return false;+ }+ }++ Future<void> stopService() async {+ if (!isSupported || !_isRunning) return;++ try {+ await FlutterForegroundTask.stopService();+ _isRunning = false;+ KazumiLogger().i('BackgroundDownloadService: service stopped');+ } catch (e) {+ KazumiLogger().e('BackgroundDownloadService: failed to stop service', error: e);+ }+ }++ Future<void> updateNotification({+ required String title,+ required String text,+ }) async {+ if (!isSupported || !_isRunning) return;++ try {+ await FlutterForegroundTask.updateService(+ notificationTitle: title,+ notificationText: text,+ );+ } catch (e) {+ // 忽略更新失败,不影响下载+ }+ }++ Future<void> updateProgress({+ required int activeCount,+ required int totalCount,+ required double overallProgress,+ required String speedText,+ }) async {+ if (!isSupported || !_isRunning) return;++ String title;+ String text;++ if (activeCount == 0) {+ title = '下载已暂停';+ text = '共 $totalCount 个任务';+ } else {+ final percent = (overallProgress * 100).toInt();+ title = '正在下载 ($activeCount/$totalCount)';+ text = '$percent% · $speedText';+ }++ await updateNotification(title: title, text: text);+ }++ Future<void> showCompletedNotification({+ required int completedCount,+ }) async {+ if (!isSupported) return;+ await stopService();+ // TODO: 显示普通通知告知用户下载完成(需要额外的通知插件)+ }++ void handleNotificationAction(String buttonId) {+ switch (buttonId) {+ case 'pause_all':+ onPauseAll?.call();+ break;+ case 'cancel_all':+ onCancelAll?.call();+ break;+ }+ }++ void handleNavigateToDownload() {+ onNavigateToDownloadRequested?.call();+ }++ void addTaskDataCallback(void Function(Object) callback) {+ FlutterForegroundTask.addTaskDataCallback(callback);+ }++ void removeTaskDataCallback(void Function(Object) callback) {+ FlutterForegroundTask.removeTaskDataCallback(callback);+ }+}++/// 后台任务回调(在独立 Isolate 中运行)+///+/// 注意:此回调主要用于保持服务存活和处理通知交互。+/// 实际下载逻辑在主 Isolate 中运行。+@pragma('vm:entry-point')+void _backgroundCallback() {+ FlutterForegroundTask.setTaskHandler(_DownloadTaskHandler());+}++class _DownloadTaskHandler extends TaskHandler {+ @override+ Future<void> onStart(DateTime timestamp, TaskStarter starter) async {+ debugPrint('BackgroundDownloadService: task handler started');+ }++ @override+ void onRepeatEvent(DateTime timestamp) {+ // eventAction 配置为 nothing,不会触发+ }++ @override+ void onNotificationButtonPressed(String id) {+ debugPrint('BackgroundDownloadService: notification button pressed: $id');+ FlutterForegroundTask.sendDataToMain({'action': 'button_pressed', 'id': id});+ }++ @override+ void onNotificationPressed() {+ FlutterForegroundTask.sendDataToMain({'action': 'navigate_to_download'});+ FlutterForegroundTask.launchApp();+ }++ @override+ void onNotificationDismissed() {+ // 前台服务通知通常不可划掉+ }++ @override+ Future<void> onDestroy(DateTime timestamp, bool isTimeout) async {+ debugPrint('BackgroundDownloadService: task handler destroyed (isTimeout: $isTimeout)');+ }++ @override+ void onReceiveData(Object data) {+ debugPrint('BackgroundDownloadService: received data: $data');+ }+}diff --git a/lib/utils/download_manager.dart b/lib/utils/download_manager.dartindex 54228a7b..d682df4b 100644--- a/lib/utils/download_manager.dart+++ b/lib/utils/download_manager.dart@@ -1,9 +1,11 @@import 'dart:async';import 'dart:io';import 'package:dio/dio.dart';+import 'package:flutter/services.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/format_utils.dart' as fmt;import 'package:kazumi/utils/logger.dart';import 'package:kazumi/utils/storage.dart';import 'package:path_provider/path_provider.dart';@@ -15,6 +17,14 @@ class _NotM3u8Exception implements Exception {String toString() => message;}+class _InsufficientStorageException implements Exception {+ final int availableBytes;+ final int requiredBytes;+ _InsufficientStorageException(this.availableBytes, this.requiredBytes);+ @override+ String toString() => '存储空间不足';+}+class DownloadTask {final String recordKey;final int episodeNumber;@@ -69,7 +79,6 @@ abstract class IDownloadManager {double getSpeed(String recordKey, int episodeNumber);}-/// Tracks download speed for a single episodeclass _SpeedTracker {int _lastBytes = 0;DateTime _lastTime = DateTime.now();@@ -79,7 +88,6 @@ class _SpeedTracker {final now = DateTime.now();final elapsed = now.difference(_lastTime).inMilliseconds;if (elapsed > 500) {- // Update speed every 500msfinal bytesDownloaded = totalBytes - _lastBytes;currentSpeed = bytesDownloaded / (elapsed / 1000);_lastBytes = totalBytes;@@ -114,6 +122,9 @@ class DownloadManager implements IDownloadManager {@overrideProgressCallback? onProgress;+ static const _minRequiredSpace = 100 * 1024 * 1024; // 100MB minimum+ static const _storageChannel = MethodChannel('com.predidit.kazumi/storage');+void _loadSettings() {final setting = GStorage.setting;maxParallelEpisodes = setting.get(@@ -126,6 +137,48 @@ class DownloadManager implements IDownloadManager {);}+ /// Returns available bytes, or -1 if unable to determine+ Future<int> _getAvailableStorage(String path) async {+ try {+ final result = await _storageChannel.invokeMethod<int>(+ 'getAvailableStorage',+ {'path': path},+ );+ return result ?? -1;+ } on MissingPluginException {+ return -1;+ } catch (e) {+ KazumiLogger().w('DownloadManager: failed to get storage info', error: e);+ return -1;+ }+ }++ Future<void> _checkStorageSpace(String downloadDir, {int requiredBytes = 0}) async {+ final available = await _getAvailableStorage(downloadDir);+ if (available == -1) return; // Skip check if unable to determine++ final required = requiredBytes > 0 ? requiredBytes : _minRequiredSpace;+ if (available < required) {+ throw _InsufficientStorageException(available, required);+ }+ }++ String _getStorageErrorMessage(FileSystemException e) {+ // POSIX error code 28 = ENOSPC (No space left on device)+ if (e.osError?.errorCode == 28) {+ return '存储空间不足,请清理后重试';+ }+ // POSIX error code 13 = EACCES (Permission denied)+ if (e.osError?.errorCode == 13) {+ return '存储权限被拒绝';+ }+ // POSIX error code 30 = EROFS (Read-only file system)+ if (e.osError?.errorCode == 30) {+ return '存储为只读,无法写入';+ }+ return '存储错误: ${e.message}';+ }+@overridedouble getSpeed(String recordKey, int episodeNumber) {final key = _taskKey(recordKey, episodeNumber);@@ -181,7 +234,6 @@ class DownloadManager implements IDownloadManager {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,);@@ -290,7 +342,6 @@ class DownloadManager implements IDownloadManager {}) async {final key = _taskKey(task.recordKey, task.episodeNumber);try {- // Step 1: Fetch M3U8 contentepisode.status = DownloadStatus.downloading;episode.networkM3u8Url = m3u8Url;_notifyProgress(task.recordKey, task.episodeNumber, episode);@@ -299,7 +350,6 @@ class DownloadManager implements IDownloadManager {try {m3u8Content = await _fetchM3u8(m3u8Url, httpHeaders, task.cancelToken);} on _NotM3u8Exception {- // URL is not an M3U8 playlist, fall back to direct file downloadKazumiLogger().i('DownloadManager: URL is not M3U8, falling back to direct file download ''for episode ${task.episodeNumber}',@@ -315,7 +365,6 @@ class DownloadManager implements IDownloadManager {return;}- // Step 2: Parse M3U8final type = M3u8Parser.detectType(m3u8Content);String mediaM3u8Content = m3u8Content;String mediaM3u8Url = m3u8Url;@@ -356,19 +405,16 @@ class DownloadManager implements IDownloadManager {return;}- // Step 3: Ad filteringList<M3u8Segment> segments = resolvedPlaylist.segments;if (adBlockerEnabled) {segments = M3u8AdFilter.filterAds(segments);}- // Step 4: Create download directoryfinal 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+ await _checkStorageSpace(base);final keys = M3u8Parser.extractUniqueKeys(M3u8MediaPlaylist(segments: segments,@@ -384,12 +430,9 @@ class DownloadManager implements IDownloadManager {keyUriToLocal[keys[i].uri] = keyFile;}- // Step 6: Download TS segmentsepisode.totalSegments = segments.length;episode.downloadedSegments = 0;_notifyProgress(task.recordKey, task.episodeNumber, episode);-- // Clean up .tmp files from previous incomplete downloadsfinal episodeDirObj = Directory(episodeDir);if (await episodeDirObj.exists()) {await for (final entity in episodeDirObj.list()) {@@ -401,7 +444,6 @@ class DownloadManager implements IDownloadManager {}}- // 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');@@ -411,7 +453,6 @@ class DownloadManager implements IDownloadManager {}}- // Download remaining segments with concurrency controlfinal pendingIndices = <int>[];for (int i = 0; i < segments.length; i++) {if (!existingSegments.contains(i)) {@@ -425,11 +466,9 @@ class DownloadManager implements IDownloadManager {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;@@ -451,7 +490,6 @@ class DownloadManager implements IDownloadManager {episode.totalBytes = totalBytes;episode.progressPercent =episode.downloadedSegments / episode.totalSegments;- // Update speed tracker_speedTrackers[key]?.update(totalBytes);_notifyProgress(task.recordKey, task.episodeNumber, episode);completedCount++;@@ -490,7 +528,6 @@ class DownloadManager implements IDownloadManager {return;}- // Step 7: Write local M3U8final targetDuration = adBlockerEnabled? M3u8AdFilter.calculateTargetDuration(segments): resolvedPlaylist.targetDuration;@@ -502,7 +539,6 @@ class DownloadManager implements IDownloadManager {final m3u8Path = '$episodeDir/playlist.m3u8';await File(m3u8Path).writeAsString(localM3u8);- // Step 8: Mark completedepisode.status = DownloadStatus.completed;episode.localM3u8Path = m3u8Path;episode.progressPercent = 1.0;@@ -513,6 +549,16 @@ class DownloadManager implements IDownloadManager {'DownloadManager: episode ${task.episodeNumber} completed. ''${segments.length} segments, ${(totalBytes / 1024 / 1024).toStringAsFixed(1)} MB',);+ } on _InsufficientStorageException catch (e) {+ episode.status = DownloadStatus.failed;+ episode.errorMessage = '存储空间不足 (可用: ${fmt.formatBytes(e.availableBytes)})';+ _notifyProgress(task.recordKey, task.episodeNumber, 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);+ KazumiLogger().e('DownloadManager: file system error', error: e);} on DioException catch (e) {if (e.type == DioExceptionType.cancel) {if (task.isPaused) {@@ -533,7 +579,6 @@ class DownloadManager implements IDownloadManager {}}- /// Download a direct video file (non-M3U8) with resume supportFuture<void> _runDirectFileDownload({required DownloadTask task,required int bangumiId,@@ -548,12 +593,11 @@ class DownloadManager implements IDownloadManager {final episodeDir = getEpisodeDir(base, bangumiId, pluginName, task.episodeNumber);await Directory(episodeDir).create(recursive: true);episode.downloadDirectory = episodeDir;+ await _checkStorageSpace(base);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 resumedint existingBytes = 0;final tmpFile = File(tmpPath);if (await tmpFile.exists()) {@@ -564,7 +608,6 @@ class DownloadManager implements IDownloadManager {episode.downloadedSegments = 0;_notifyProgress(task.recordKey, task.episodeNumber, episode);- // Use stream response for resume supportfinal requestHeaders = Map<String, String>.from(httpHeaders);bool useRange = existingBytes > 0;if (useRange) {@@ -583,7 +626,6 @@ class DownloadManager implements IDownloadManager {cancelToken: task.cancelToken,);} on DioException catch (e) {- // Handle 416 Range Not Satisfiable - delete local file and retry without Rangeif (e.response?.statusCode == 416 && useRange) {KazumiLogger().w('DownloadManager: 416 Range Not Satisfiable, deleting tmp file and retrying',@@ -605,13 +647,11 @@ class DownloadManager implements IDownloadManager {}}- // Parse total size from Content-Range or Content-Lengthfinal 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 {@@ -622,7 +662,6 @@ class DownloadManager implements IDownloadManager {mode: existingBytes > 0 ? FileMode.append : FileMode.write);int received = existingBytes;- // Initialize speed tracker for direct file download_speedTrackers[key] = _SpeedTracker();try {@@ -649,10 +688,8 @@ class DownloadManager implements IDownloadManager {return;}- // Rename .tmp to final pathawait File(tmpPath).rename(filePath);- // Mark completedepisode.status = DownloadStatus.completed;episode.localM3u8Path = filePath;episode.downloadedSegments = 1;@@ -665,6 +702,16 @@ class DownloadManager implements IDownloadManager {'DownloadManager: episode ${task.episodeNumber} completed (direct download). ''${(episode.totalBytes / 1024 / 1024).toStringAsFixed(1)} MB',);+ } on _InsufficientStorageException catch (e) {+ episode.status = DownloadStatus.failed;+ episode.errorMessage = '存储空间不足 (可用: ${fmt.formatBytes(e.availableBytes)})';+ _notifyProgress(task.recordKey, task.episodeNumber, 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);+ KazumiLogger().e('DownloadManager: file system error', error: e);} on DioException catch (e) {if (e.type == DioExceptionType.cancel) {if (task.isPaused) {@@ -701,11 +748,8 @@ class DownloadManager implements IDownloadManager {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 taskfinal fetchToken = CancelToken();- // Forward cancellation from the task's main tokenif (cancelToken.isCancelled) {throw DioException(type: DioExceptionType.cancel,@@ -723,12 +767,10 @@ class DownloadManager implements IDownloadManager {),cancelToken: fetchToken,onReceiveProgress: (received, total) {- // Check if parent task was cancelledif (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');}@@ -737,7 +779,6 @@ class DownloadManager implements IDownloadManager {final content = response.data!;- // Validate M3U8 contentfinal trimmed = content.trimLeft();if (!trimmed.startsWith('#EXTM3U')) {throw _NotM3u8Exception('URL 不是 M3U8 播放列表');@@ -745,9 +786,7 @@ class DownloadManager implements IDownloadManager {return content;} on DioException catch (e) {- // Re-throw if the main task was cancelled/pausedif (cancelToken.isCancelled) rethrow;- // fetchToken cancelled due to too-large responseif (e.type == DioExceptionType.cancel) {throw _NotM3u8Exception('响应过大,非 M3U8 播放列表');}@@ -785,7 +824,6 @@ class DownloadManager implements IDownloadManager {await File(tmpPath).rename(savePath);return await File(savePath).length();} catch (e) {- // Clean up incomplete .tmp file on failuretry {final tmpFile = File(tmpPath);if (await tmpFile.exists()) await tmpFile.delete();diff --git a/lib/utils/format_utils.dart b/lib/utils/format_utils.dartnew file mode 100644index 00000000..40a7c0ad--- /dev/null+++ b/lib/utils/format_utils.dart@@ -0,0 +1,16 @@+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';+}++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';+}diff --git a/linux/my_application.cc b/linux/my_application.ccindex 424c205a..2379b642 100644--- a/linux/my_application.cc+++ b/linux/my_application.cc@@ -1,6 +1,7 @@#include "my_application.h"#include <flutter_linux/flutter_linux.h>+#include <sys/statvfs.h>#ifdef GDK_WINDOWING_X11#include <gdk/gdkx.h>#endif@@ -11,6 +12,7 @@ struct _MyApplication {GtkApplication parent_instance;char** dart_entrypoint_arguments;FlMethodChannel* intent_method_channel;+ FlMethodChannel* storage_method_channel;};G_DEFINE_TYPE(MyApplication, my_application, GTK_TYPE_APPLICATION)@@ -22,6 +24,39 @@ static FlMethodResponse* is_running_on_x11() {return FL_METHOD_RESPONSE(fl_method_success_response_new(result));}+static void storage_method_call_handler(FlMethodChannel* channel,+ FlMethodCall* method_call,+ gpointer user_data) {+ g_autoptr(FlMethodResponse) response = nullptr;+ if (strcmp(fl_method_call_get_name(method_call), "getAvailableStorage") == 0) {+ const gchar* path = "/";+ FlValue* args = fl_method_call_get_args(method_call);+ if (fl_value_get_type(args) == FL_VALUE_TYPE_MAP) {+ FlValue* path_value = fl_value_lookup_string(args, "path");+ if (path_value != nullptr && fl_value_get_type(path_value) == FL_VALUE_TYPE_STRING) {+ path = fl_value_get_string(path_value);+ }+ }++ struct statvfs stat;+ if (statvfs(path, &stat) == 0) {+ gint64 available = (gint64)stat.f_bavail * (gint64)stat.f_frsize;+ g_autoptr(FlValue) result = fl_value_new_int(available);+ response = FL_METHOD_RESPONSE(fl_method_success_response_new(result));+ } else {+ g_autoptr(FlValue) result = fl_value_new_int(-1);+ response = FL_METHOD_RESPONSE(fl_method_success_response_new(result));+ }+ } else {+ response = FL_METHOD_RESPONSE(fl_method_not_implemented_response_new());+ }++ g_autoptr(GError) error = nullptr;+ if (!fl_method_call_respond(method_call, response, &error)) {+ g_warning("Failed to send response: %s", error->message);+ }+}+static void intent_method_call_handler(FlMethodChannel* channel,FlMethodCall* method_call,gpointer user_data) {@@ -89,6 +124,11 @@ static void my_application_activate(GApplication* application) {fl_method_channel_set_method_call_handler(self->intent_method_channel, intent_method_call_handler, self, nullptr);+ self->storage_method_channel = fl_method_channel_new(+ fl_engine_get_binary_messenger(fl_view_get_engine(view)), "com.predidit.kazumi/storage", FL_METHOD_CODEC(codec));+ fl_method_channel_set_method_call_handler(+ self->storage_method_channel, storage_method_call_handler, self, nullptr);+gtk_widget_grab_focus(GTK_WIDGET(view));}@@ -134,6 +174,7 @@ static void my_application_dispose(GObject* object) {MyApplication* self = MY_APPLICATION(object);g_clear_pointer(&self->dart_entrypoint_arguments, g_strfreev);g_clear_object(&self->intent_method_channel);+ g_clear_object(&self->storage_method_channel);G_OBJECT_CLASS(my_application_parent_class)->dispose(object);}diff --git a/macos/Runner/AppDelegate.swift b/macos/Runner/AppDelegate.swiftindex ab6a64d7..e89cc74e 100644--- a/macos/Runner/AppDelegate.swift+++ b/macos/Runner/AppDelegate.swift@@ -39,6 +39,27 @@ class AppDelegate: FlutterAppDelegate {result(FlutterMethodNotImplemented)}});++ let storageChannel = FlutterMethodChannel.init(name: "com.predidit.kazumi/storage", binaryMessenger: controller.engine.binaryMessenger)+ storageChannel.setMethodCallHandler({+ (call: FlutterMethodCall, result: @escaping FlutterResult) -> Void in+ if call.method == "getAvailableStorage" {+ do {+ let attrs = try FileManager.default.attributesOfFileSystem(+ forPath: NSHomeDirectory()+ )+ if let freeSize = attrs[.systemFreeSize] as? Int64 {+ result(freeSize)+ } else {+ result(-1)+ }+ } catch {+ result(-1)+ }+ } else {+ result(FlutterMethodNotImplemented)+ }+ });self.menuChannel?.setMethodCallHandler({call,result inswitch call.method {case "setMenuEnabled":diff --git a/pubspec.lock b/pubspec.lockindex 3a56f859..12ba81b1 100644--- a/pubspec.lock+++ b/pubspec.lock@@ -407,6 +407,14 @@ packages:url: "https://pub.dev"source: hostedversion: "0.6.0"+ flutter_foreground_task:+ dependency: "direct main"+ description:+ name: flutter_foreground_task+ sha256: "48ea45056155a99fb30b15f14f4039a044d925bc85f381ed0b2d3b00a60b99de"+ url: "https://pub.dev"+ source: hosted+ version: "9.2.0"flutter_inappwebview_android:dependency: "direct main"description:diff --git a/pubspec.yaml b/pubspec.yamlindex 1b84bb59..fff01842 100644--- a/pubspec.yaml+++ b/pubspec.yaml@@ -78,6 +78,7 @@ dependencies:flutter_svg: ^2.2.3antlr4: ^4.13.2fl_chart: ^1.1.1+ flutter_foreground_task: ^9.0.0skeletonizer: ^2.1.2flutter_inappwebview_platform_interface: ^1.3.0+1flutter_inappwebview_ios: ^1.1.2diff --git a/windows/runner/flutter_window.cpp b/windows/runner/flutter_window.cppindex bcc23164..c2ef7ef9 100644--- a/windows/runner/flutter_window.cpp+++ b/windows/runner/flutter_window.cpp@@ -47,6 +47,9 @@ bool FlutterWindow::OnCreate() {// Register Intent MethodChannelRegisterIntentChannel();+ // Register Storage MethodChannel+ RegisterStorageChannel();+return true;}@@ -114,3 +117,37 @@ void FlutterWindow::RegisterIntentChannel() {}});}++// Storage MethodChannel setup+void FlutterWindow::RegisterStorageChannel() {+ auto storage_channel =+ std::make_unique<flutter::MethodChannel<flutter::EncodableValue>>(+ flutter_controller_->engine()->messenger(), "com.predidit.kazumi/storage",+ &flutter::StandardMethodCodec::GetInstance());++ storage_channel->SetMethodCallHandler([](const auto& call, auto result) {+ if (call.method_name().compare("getAvailableStorage") == 0) {+ std::wstring path = L"C:\\";+ const auto* arguments = std::get_if<flutter::EncodableMap>(call.arguments());+ if (arguments) {+ auto path_it = arguments->find(flutter::EncodableValue("path"));+ if (path_it != arguments->end()) {+ const std::string& path_str = std::get<std::string>(path_it->second);+ // Extract drive root from path (e.g. "C:\Users\..." -> "C:\")+ if (path_str.length() >= 2 && path_str[1] == ':') {+ path = std::wstring(1, static_cast<wchar_t>(path_str[0])) + L":\\";+ }+ }+ }++ ULARGE_INTEGER free_bytes_available;+ if (GetDiskFreeSpaceExW(path.c_str(), &free_bytes_available, nullptr, nullptr)) {+ result->Success(flutter::EncodableValue(static_cast<int64_t>(free_bytes_available.QuadPart)));+ } else {+ result->Success(flutter::EncodableValue(static_cast<int64_t>(-1)));+ }+ } else {+ result->NotImplemented();+ }+ });+}diff --git a/windows/runner/flutter_window.h b/windows/runner/flutter_window.hindex 071da165..81a932c9 100644--- a/windows/runner/flutter_window.h+++ b/windows/runner/flutter_window.h@@ -31,6 +31,9 @@ class FlutterWindow : public Win32Window {// Register Intent MethodChannelvoid RegisterIntentChannel();++ // Register Storage MethodChannel+ void RegisterStorageChannel();};#endif // RUNNER_FLUTTER_WINDOW_H_