Skip to content

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

refactor(rules): rebuild plugin update pipeline with caching and rollback

Predidit9d4fbee95762
diff --git a/lib/pages/about/about_page.dart b/lib/pages/about/about_page.dart
index 8490e553..5322bffd 100644
--- a/lib/pages/about/about_page.dart
+++ b/lib/pages/about/about_page.dart
@@ -32,6 +32,7 @@ class _AboutPageState extends State<AboutPage> {
late dynamic defaultThemeColor;
late int exitBehavior = GStorage.getSetting(SettingsKeys.exitBehavior);
late bool autoUpdate;
+ late bool checkPluginUpdateOnStartup;
double _cacheSizeMB = -1;
MyController get myController => widget.controller;
final MenuController menuController = MenuController();
@@ -40,6 +41,8 @@ class _AboutPageState extends State<AboutPage> {
void initState() {
super.initState();
autoUpdate = GStorage.getSetting(SettingsKeys.autoUpdate);
+ checkPluginUpdateOnStartup =
+ GStorage.getSetting(SettingsKeys.checkPluginUpdateOnStartup);
_getCacheSize();
}
@@ -310,19 +313,40 @@ class _AboutPageState extends State<AboutPage> {
SettingsKeys.autoUpdate, autoUpdate);
setState(() {});
},
- title: Text('自动更新', style: TextStyle(fontFamily: fontFamily)),
+ title: Text('启动时检查应用更新',
+ style: TextStyle(fontFamily: fontFamily)),
initialValue: autoUpdate,
),
SettingsTile.navigation(
onPressed: (_) {
myController.checkUpdate();
},
- title: Text('检查更新', style: TextStyle(fontFamily: fontFamily)),
+ title:
+ Text('检查应用更新', style: TextStyle(fontFamily: fontFamily)),
value: Text('当前版本 ${ApiEndpoints.version}',
style: TextStyle(fontFamily: fontFamily)),
),
],
),
+ SettingsSection(
+ title: Text('规则更新', style: TextStyle(fontFamily: fontFamily)),
+ tiles: [
+ SettingsTile.switchTile(
+ onToggle: (value) async {
+ checkPluginUpdateOnStartup =
+ value ?? !checkPluginUpdateOnStartup;
+ await GStorage.putSetting(
+ SettingsKeys.checkPluginUpdateOnStartup,
+ checkPluginUpdateOnStartup,
+ );
+ setState(() {});
+ },
+ title: Text('启动时检查规则更新',
+ style: TextStyle(fontFamily: fontFamily)),
+ initialValue: checkPluginUpdateOnStartup,
+ ),
+ ],
+ ),
],
),
),
diff --git a/lib/pages/init_page.dart b/lib/pages/init_page.dart
index aa8e2cfa..41663692 100644
--- a/lib/pages/init_page.dart
+++ b/lib/pages/init_page.dart
@@ -13,6 +13,7 @@ import 'package:flutter/services.dart' show rootBundle;
import 'package:kazumi/services/logging/logger.dart';
import 'package:kazumi/services/shaders/shader_asset_service.dart';
import 'package:kazumi/pages/download/download_controller.dart';
+import 'package:kazumi/pages/plugin_editor/plugin_update_actions.dart';
import 'package:kazumi/services/download/background_download_service.dart';
import 'package:kazumi/services/platform/windows_shortcut.dart';
import 'package:kazumi/services/platform/platform_environment_service.dart';
@@ -278,8 +279,14 @@ class _InitPageState extends State<InitPage> {
await pluginsController.init();
statementsText =
await rootBundle.loadString("assets/statements/statements.txt");
- _pluginUpdate();
- } catch (_) {}
+ unawaited(_pluginUpdate());
+ } catch (error, stackTrace) {
+ KazumiLogger().e(
+ 'Plugin: failed to initialize rules',
+ error: error,
+ stackTrace: stackTrace,
+ );
+ }
if (pluginsController.pluginList.isEmpty) {
await KazumiDialog.show(
clickMaskDismiss: false,
@@ -305,7 +312,16 @@ class _InitPageState extends State<InitPage> {
onPressed: () async {
try {
await pluginsController.copyPluginsToExternalDirectory();
- } catch (_) {}
+ } catch (error, stackTrace) {
+ KazumiLogger().e(
+ 'Plugin: failed to install bundled rules',
+ error: error,
+ stackTrace: stackTrace,
+ );
+ KazumiDialog.dismiss();
+ KazumiDialog.showToast(message: '初始化规则失败');
+ return;
+ }
KazumiDialog.dismiss();
if (!Platform.isAndroid) {
return;
@@ -322,10 +338,8 @@ class _InitPageState extends State<InitPage> {
}
}
- // The function is not completed yet
- // We simply disable update when the user is using F-Droid mirror
- // We are trying to meet F-Droid requirement to submit the app
- // After the app is submitted, we will complete the function
+ // Selecting F-Droid delegates application updates to the store and disables
+ // Kazumi's in-app application update checks.
Future<void> _switchUpdateMirror() async {
await KazumiDialog.show(
clickMaskDismiss: false,
@@ -390,15 +404,27 @@ class _InitPageState extends State<InitPage> {
}
Future<void> _pluginUpdate() async {
- await pluginsController.queryPluginHTTPList();
- int count = 0;
- for (var plugin in pluginsController.pluginList) {
- if (pluginsController.pluginUpdateStatus(plugin) == 'updatable') {
- count++;
- }
+ final checkOnStartup =
+ GStorage.getSetting(SettingsKeys.checkPluginUpdateOnStartup);
+ late final int count;
+ try {
+ count = await pluginsController.checkPluginUpdatesOnStartup(
+ enabled: checkOnStartup,
+ );
+ } catch (_) {
+ return;
}
if (count != 0) {
- KazumiDialog.showToast(message: '检测到 $count 条规则可以更新');
+ KazumiDialog.showToast(
+ message: '检测到 $count 条规则可以更新',
+ showActionButton: true,
+ actionLabel: '全部更新',
+ onActionPressed: () => updateAllPluginsWithFeedback(
+ pluginsController,
+ ensureCatalog: false,
+ ),
+ duration: const Duration(seconds: 5),
+ );
}
}
diff --git a/lib/pages/plugin_editor/plugin_editor_page.dart b/lib/pages/plugin_editor/plugin_editor_page.dart
index 900cd228..3fa304ec 100644
--- a/lib/pages/plugin_editor/plugin_editor_page.dart
+++ b/lib/pages/plugin_editor/plugin_editor_page.dart
@@ -687,7 +687,8 @@ class _PluginEditorPageState extends State<PluginEditorPage> {
onPressed: () async {
try {
final editedPlugin = _buildEditedPlugin();
- pluginsController.updatePlugin(editedPlugin);
+ await pluginsController.updatePlugin(editedPlugin);
+ if (!context.mounted) return;
context.pop();
} catch (error) {
_showEditorError(error);
diff --git a/lib/pages/plugin_editor/plugin_shop_page.dart b/lib/pages/plugin_editor/plugin_shop_page.dart
index b2bc35f9..cec2feb2 100644
--- a/lib/pages/plugin_editor/plugin_shop_page.dart
+++ b/lib/pages/plugin_editor/plugin_shop_page.dart
@@ -1,9 +1,12 @@
+import 'dart:async';
+
import 'package:flutter/material.dart';
import 'package:flutter_mobx/flutter_mobx.dart';
import 'package:flutter_modular/flutter_modular.dart';
import 'package:kazumi/bean/dialog/dialog_helper.dart';
import 'package:kazumi/bean/widget/error_widget.dart';
import 'package:kazumi/plugins/plugins_controller.dart';
+import 'package:kazumi/pages/plugin_editor/plugin_update_actions.dart';
import 'package:kazumi/bean/appbar/sys_app_bar.dart';
import 'package:kazumi/services/storage/storage.dart';
@@ -20,8 +23,8 @@ class PluginShopPage extends StatefulWidget {
}
class _PluginShopPageState extends State<PluginShopPage> {
- bool timeout = false;
- bool loading = false;
+ bool loadFailed = false;
+ bool loading = true;
late bool enableGitProxy;
// 排序方式状态:false=按更新时间排序,true=按名称排序
@@ -39,29 +42,45 @@ class _PluginShopPageState extends State<PluginShopPage> {
void initState() {
super.initState();
enableGitProxy = GStorage.getSetting(SettingsKeys.enableGitProxy);
+ if (pluginsController.isPluginCatalogFresh) {
+ loading = false;
+ } else {
+ unawaited(_loadPluginCatalog());
+ }
}
- // 刷新规则列表
- void _handleRefresh() async {
- if (!loading) {
+ Future<void> _loadPluginCatalog({bool forceRefresh = false}) async {
+ try {
+ if (forceRefresh) {
+ await pluginsController.refreshPluginCatalog();
+ } else {
+ await pluginsController.ensurePluginCatalog();
+ }
+ if (!mounted) return;
setState(() {
- loading = true;
- timeout = false;
+ loading = false;
+ loadFailed = false;
});
- enableGitProxy = GStorage.getSetting(SettingsKeys.enableGitProxy);
- pluginsController.queryPluginHTTPList().then((_) {
- setState(() {
- loading = false;
- });
- if (pluginsController.pluginHTTPList.isEmpty) {
- setState(() {
- timeout = true;
- });
- }
+ } catch (_) {
+ if (!mounted) return;
+ setState(() {
+ loading = false;
+ loadFailed = true;
});
}
}
+ // 刷新规则列表
+ void _handleRefresh() {
+ if (loading) return;
+ setState(() {
+ loading = true;
+ loadFailed = false;
+ enableGitProxy = GStorage.getSetting(SettingsKeys.enableGitProxy);
+ });
+ unawaited(_loadPluginCatalog(forceRefresh: true));
+ }
+
// 切换排序方式
void _toggleSort() {
setState(() {
@@ -72,7 +91,7 @@ class _PluginShopPageState extends State<PluginShopPage> {
Widget get pluginHTTPListBody {
return Observer(builder: (context) {
// 创建列表副本用于排序
- var sortedList = List.from(pluginsController.pluginHTTPList);
+ final sortedList = pluginsController.pluginHTTPList.toList();
// 排序规则:
// 1. 按名称排序:忽略大小写的字母顺序
@@ -87,13 +106,15 @@ class _PluginShopPageState extends State<PluginShopPage> {
return ListView.builder(
itemCount: sortedList.length,
itemBuilder: (context, index) {
+ final item = sortedList[index];
+ final status = pluginsController.pluginStatus(item);
return Card(
margin: const EdgeInsets.fromLTRB(8, 0, 8, 8),
child: ListTile(
title: Row(
children: [
Text(
- sortedList[index].name,
+ item.name,
style: const TextStyle(fontWeight: FontWeight.bold),
),
],
@@ -111,12 +132,12 @@ class _PluginShopPageState extends State<PluginShopPage> {
borderRadius: BorderRadius.circular(16.0),
),
child: Text(
- sortedList[index].version,
+ item.version,
style: TextStyle(
color: Theme.of(context).colorScheme.surface),
),
),
- if (sortedList[index].antiCrawlerEnabled) ...[
+ if (item.antiCrawlerEnabled) ...[
const SizedBox(width: 5),
Container(
padding: const EdgeInsets.symmetric(
@@ -135,60 +156,36 @@ class _PluginShopPageState extends State<PluginShopPage> {
],
],
),
- if (sortedList[index].lastUpdate > 0) ...[
+ if (item.lastUpdate > 0) ...[
const SizedBox(height: 4),
Text(
- '更新时间: ${DateTime.fromMillisecondsSinceEpoch(sortedList[index].lastUpdate).toString().split('.')[0]}',
+ '更新时间: ${DateTime.fromMillisecondsSinceEpoch(item.lastUpdate).toString().split('.')[0]}',
style: const TextStyle(color: Colors.grey),
),
],
],
),
trailing: TextButton(
- onPressed: () async {
- if (pluginsController.pluginStatus(sortedList[index]) ==
- 'install') {
- KazumiDialog.showToast(message: '导入中');
- int res = await pluginsController
- .tryUpdatePluginByName(sortedList[index].name);
- if (res == 0) {
- KazumiDialog.showToast(message: '导入成功');
- setState(() {});
- } else if (res == 1) {
- KazumiDialog.showToast(
- message: '规则需要更高版本客户端',
- );
- } else if (res == 2) {
- KazumiDialog.showToast(message: '导入规则失败');
- }
- }
- if (pluginsController.pluginStatus(sortedList[index]) ==
- 'update') {
- KazumiDialog.showToast(message: '更新中');
- int res = await pluginsController
- .tryUpdatePluginByName(sortedList[index].name);
- if (res == 0) {
- KazumiDialog.showToast(message: '更新成功');
- setState(() {});
- } else if (res == 1) {
- KazumiDialog.showToast(
- message: '规则需要更高版本客户端',
- );
- } else if (res == 2) {
- KazumiDialog.showToast(message: '更新规则失败');
- } else if (res == 3) {
- KazumiDialog.showToast(message: '远程规则版本不高于本地, 已跳过更新');
- }
- }
- },
- child: Text(pluginsController
- .pluginStatus(sortedList[index]) ==
- 'install'
- ? '安装'
- : (pluginsController.pluginStatus(sortedList[index]) ==
- 'installed')
- ? '已安装'
- : '更新'),
+ onPressed: status == PluginCatalogItemStatus.installed
+ ? null
+ : () async {
+ final result = await updatePluginWithFeedback(
+ pluginsController,
+ item.name,
+ installing:
+ status == PluginCatalogItemStatus.install,
+ );
+ if (result == PluginUpdateResult.updated && mounted) {
+ setState(() {});
+ }
+ },
+ child: Text(
+ switch (status) {
+ PluginCatalogItemStatus.install => '安装',
+ PluginCatalogItemStatus.installed => '已安装',
+ PluginCatalogItemStatus.update => '更新',
+ },
+ ),
)),
);
},
@@ -196,7 +193,7 @@ class _PluginShopPageState extends State<PluginShopPage> {
});
}
- Widget get timeoutWidget {
+ Widget get loadErrorWidget {
return Center(
child: GeneralErrorWidget(
errMsg:
@@ -221,7 +218,6 @@ class _PluginShopPageState extends State<PluginShopPage> {
@override
Widget build(BuildContext context) {
- WidgetsBinding.instance.addPostFrameCallback((_) {});
return PopScope(
canPop: true,
onPopInvokedWithResult: (bool didPop, Object? result) {
@@ -248,10 +244,12 @@ class _PluginShopPageState extends State<PluginShopPage> {
],
),
body: loading
- ? (const Center(child: CircularProgressIndicator()))
- : (pluginsController.pluginHTTPList.isEmpty
- ? timeoutWidget
- : pluginHTTPListBody),
+ ? const Center(child: CircularProgressIndicator())
+ : loadFailed
+ ? loadErrorWidget
+ : pluginsController.pluginHTTPList.isEmpty
+ ? const Center(child: Text('规则仓库中暂无规则'))
+ : pluginHTTPListBody,
),
);
}
diff --git a/lib/pages/plugin_editor/plugin_update_actions.dart b/lib/pages/plugin_editor/plugin_update_actions.dart
new file mode 100644
index 00000000..d3dcf387
--- /dev/null
+++ b/lib/pages/plugin_editor/plugin_update_actions.dart
@@ -0,0 +1,65 @@
+import 'package:kazumi/bean/dialog/dialog_helper.dart';
+import 'package:kazumi/plugins/plugins_controller.dart';
+
+Future<void> updateAllPluginsWithFeedback(
+ PluginsController controller, {
+ required bool ensureCatalog,
+}) async {
+ KazumiDialog.showLoading(msg: '更新中');
+ try {
+ final result = await controller.tryUpdateAllPlugin(
+ ensureCatalog: ensureCatalog,
+ );
+ KazumiDialog.dismiss();
+ KazumiDialog.showToast(message: _batchUpdateMessage(result));
+ } catch (_) {
+ KazumiDialog.dismiss();
+ KazumiDialog.showToast(message: '更新规则失败');
+ }
+}
+
+Future<PluginUpdateResult> updatePluginWithFeedback(
+ PluginsController controller,
+ String name, {
+ required bool installing,
+}) async {
+ KazumiDialog.showToast(message: installing ? '导入中' : '更新中');
+ late final PluginUpdateResult result;
+ try {
+ result = await controller.tryUpdatePluginByName(name);
+ } catch (_) {
+ KazumiDialog.showToast(message: '保存规则失败');
+ return PluginUpdateResult.failed;
+ }
+ final message = switch (result) {
+ PluginUpdateResult.updated => installing ? '导入成功' : '更新成功',
+ PluginUpdateResult.requiresNewerClient => '规则需要更高版本客户端',
+ PluginUpdateResult.failed => installing ? '导入规则失败' : '更新规则失败',
+ PluginUpdateResult.notNewer => '远程规则版本不高于本地,已跳过更新',
+ };
+ KazumiDialog.showToast(message: message);
+ return result;
+}
+
+String _batchUpdateMessage(PluginBatchUpdateResult result) {
+ if (result.hasNoCandidates) {
+ return '没有可更新的规则';
+ }
+ if (result.failed == 0 &&
+ result.requiresNewerClient == 0 &&
+ result.notNewer == 0) {
+ return '更新成功 ${result.updated} 条';
+ }
+
+ final parts = <String>['成功 ${result.updated} 条'];
+ if (result.requiresNewerClient > 0) {
+ parts.add('不兼容 ${result.requiresNewerClient} 条');
+ }
+ if (result.notNewer > 0) {
+ parts.add('已跳过 ${result.notNewer} 条');
+ }
+ if (result.failed > 0) {
+ parts.add('失败 ${result.failed} 条');
+ }
+ return '更新完成:${parts.join(',')}';
+}
diff --git a/lib/pages/plugin_editor/plugin_view_page.dart b/lib/pages/plugin_editor/plugin_view_page.dart
index 87e1a4e7..94c35bb3 100644
--- a/lib/pages/plugin_editor/plugin_view_page.dart
+++ b/lib/pages/plugin_editor/plugin_view_page.dart
@@ -1,3 +1,4 @@
+import 'dart:async';
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
@@ -7,6 +8,7 @@ import 'package:kazumi/bean/dialog/dialog_helper.dart';
import 'package:kazumi/plugins/plugins.dart';
import 'package:kazumi/plugins/plugins_controller.dart';
import 'package:kazumi/bean/appbar/sys_app_bar.dart';
+import 'package:kazumi/pages/plugin_editor/plugin_update_actions.dart';
import 'package:kazumi/utils/encoding.dart';
class PluginViewPage extends StatefulWidget {
@@ -31,13 +33,20 @@ class _PluginViewPageState extends State<PluginViewPage> {
final Set<String> selectedNames = {};
Future<void> _handleUpdate() async {
- KazumiDialog.showLoading(msg: '更新中');
- int count = await pluginsController.tryUpdateAllPlugin();
- KazumiDialog.dismiss();
- if (count == 0) {
- KazumiDialog.showToast(message: '所有规则已是最新');
- } else {
- KazumiDialog.showToast(message: '更新成功 $count 条');
+ await updateAllPluginsWithFeedback(
+ pluginsController,
+ ensureCatalog: true,
+ );
+ if (mounted) {
+ setState(() {});
+ }
+ }
+
+ Future<void> _handleReorder(int oldIndex, int newIndex) async {
+ try {
+ await pluginsController.onReorder(oldIndex, newIndex);
+ } catch (_) {
+ KazumiDialog.showToast(message: '保存规则顺序失败');
}
}
@@ -117,7 +126,7 @@ class _PluginViewPageState extends State<PluginViewPage> {
);
return;
}
- pluginsController.updatePlugin(plugin);
+ await pluginsController.updatePlugin(plugin);
KazumiDialog.dismiss();
KazumiDialog.showToast(message: '导入成功');
} catch (e) {
@@ -144,11 +153,22 @@ class _PluginViewPageState extends State<PluginViewPage> {
@override
void initState() {
super.initState();
+ unawaited(_loadPluginUpdateStatus());
+ }
+
+ Future<void> _loadPluginUpdateStatus() async {
+ try {
+ await pluginsController.ensurePluginCatalog();
+ if (mounted) {
+ setState(() {});
+ }
+ } catch (_) {
+ KazumiDialog.showToast(message: '检查规则更新失败');
+ }
}
@override
Widget build(BuildContext context) {
- WidgetsBinding.instance.addPostFrameCallback((_) {});
return PopScope(
canPop: !isMultiSelectMode,
onPopInvokedWithResult: (bool didPop, Object? result) {
@@ -200,9 +220,15 @@ class _PluginViewPageState extends State<PluginViewPage> {
),
),
TextButton(
- onPressed: () {
- pluginsController
- .removePlugins(selectedNames);
+ onPressed: () async {
+ try {
+ await pluginsController
+ .removePlugins(selectedNames);
+ } catch (_) {
+ KazumiDialog.showToast(message: '删除规则失败');
+ return;
+ }
+ if (!mounted) return;
setState(() {
isMultiSelectMode = false;
selectedNames.clear();
@@ -251,16 +277,16 @@ class _PluginViewPageState extends State<PluginViewPage> {
);
},
onReorderItem: (int oldIndex, int newIndex) {
- pluginsController.onReorder(oldIndex, newIndex);
+ unawaited(_handleReorder(oldIndex, newIndex));
},
itemCount: pluginsController.pluginList.length,
itemBuilder: (context, index) {
var plugin = pluginsController.pluginList[index];
bool canUpdate =
pluginsController.pluginUpdateStatus(plugin) ==
- 'updatable';
+ PluginUpdateAvailability.updatable;
return Card(
- key: ValueKey(index),
+ key: ObjectKey(plugin),
margin: const EdgeInsets.fromLTRB(8, 0, 8, 8),
child: ListTile(
trailing: pluginCardTrailing(index),
@@ -414,24 +440,29 @@ class _PluginViewPageState extends State<PluginViewPage> {
MenuItemButton(
requestFocusOnHover: false,
onPressed: () async {
- var state = pluginsController.pluginUpdateStatus(plugin);
- if (state == "nonexistent") {
- KazumiDialog.showToast(message: '规则仓库中没有当前规则');
- } else if (state == "latest") {
- KazumiDialog.showToast(message: '规则已是最新');
- } else if (state == "updatable") {
- KazumiDialog.showLoading(msg: '更新中');
- int res = await pluginsController.tryUpdatePlugin(plugin);
- KazumiDialog.dismiss();
- if (res == 0) {
- KazumiDialog.showToast(message: '更新成功');
- } else if (res == 1) {
- KazumiDialog.showToast(message: 'kazumi版本过低, 此规则不兼容当前版本');
- } else if (res == 2) {
- KazumiDialog.showToast(message: '更新规则失败');
- } else if (res == 3) {
- KazumiDialog.showToast(message: '远程规则版本不高于本地, 已跳过更新');
+ try {
+ await pluginsController.ensurePluginCatalog();
+ if (mounted) {
+ setState(() {});
}
+ } catch (_) {
+ KazumiDialog.showToast(message: '检查规则更新失败');
+ return;
+ }
+ final state = pluginsController.pluginUpdateStatus(plugin);
+ switch (state) {
+ case PluginUpdateAvailability.unknown:
+ KazumiDialog.showToast(message: '尚未获取规则更新状态');
+ case PluginUpdateAvailability.notInCatalog:
+ KazumiDialog.showToast(message: '规则仓库中没有当前规则');
+ case PluginUpdateAvailability.latest:
+ KazumiDialog.showToast(message: '规则已是最新');
+ case PluginUpdateAvailability.updatable:
+ await updatePluginWithFeedback(
+ pluginsController,
+ plugin.name,
+ installing: false,
+ );
}
},
child: Container(
@@ -545,9 +576,11 @@ class _PluginViewPageState extends State<PluginViewPage> {
MenuItemButton(
requestFocusOnHover: false,
onPressed: () async {
- setState(() {
- pluginsController.removePlugin(plugin);
- });
+ try {
+ await pluginsController.removePlugin(plugin);
+ } catch (_) {
+ KazumiDialog.showToast(message: '删除规则失败');
+ }
},
child: Container(
height: 48,
diff --git a/lib/plugins/plugins_controller.dart b/lib/plugins/plugins_controller.dart
index 6c622c05..4756f124 100644
--- a/lib/plugins/plugins_controller.dart
+++ b/lib/plugins/plugins_controller.dart
@@ -9,6 +9,8 @@ import 'package:kazumi/services/plugin/plugin_install_time_tracker.dart';
import 'package:kazumi/request/apis/plugin_catalog_api.dart';
import 'package:kazumi/modules/plugin/plugin_http_module.dart';
import 'package:kazumi/services/logging/logger.dart';
+import 'package:kazumi/utils/async_serial_queue.dart';
+import 'package:kazumi/utils/async_single_flight.dart';
import 'package:kazumi/utils/version.dart';
part 'plugins_controller.g.dart';
@@ -18,7 +20,75 @@ part 'plugins_controller.g.dart';
class PluginsController = _PluginsController with _$PluginsController;
+enum PluginUpdateAvailability { unknown, notInCatalog, latest, updatable }
+
+enum PluginCatalogItemStatus { install, installed, update }
+
+enum PluginUpdateResult { updated, requiresNewerClient, failed, notNewer }
+
+class PluginBatchUpdateResult {
+ const PluginBatchUpdateResult({
+ required this.candidates,
+ required this.updated,
+ required this.requiresNewerClient,
+ required this.failed,
+ required this.notNewer,
+ });
+
+ final int candidates;
+ final int updated;
+ final int requiresNewerClient;
+ final int failed;
+ final int notNewer;
+
+ bool get hasNoCandidates => candidates == 0;
+}
+
+typedef PluginCatalogLoader = Future<List<PluginHTTPItem>> Function();
+typedef PluginLoader = Future<Plugin> Function(String name);
+typedef PluginJsonWriter = Future<void> Function(String jsonData);
+typedef PluginErrorReporter = void Function(
+ String message,
+ Object error,
+ StackTrace stackTrace,
+);
+typedef _PluginUpdateAttempt = ({PluginUpdateResult result, Plugin? plugin});
+
+void _defaultPluginErrorReporter(
+ String message,
+ Object error,
+ StackTrace stackTrace,
+) {
+ KazumiLogger().e(message, error: error, stackTrace: stackTrace);
+}
+
abstract class _PluginsController with Store {
+ _PluginsController({
+ PluginCatalogLoader? catalogLoader,
+ PluginLoader? pluginLoader,
+ PluginJsonWriter? pluginJsonWriter,
+ PluginErrorReporter? errorReporter,
+ }) : _catalogLoader = catalogLoader ?? PluginCatalogApi.getPluginList,
+ _pluginLoader = pluginLoader ?? PluginCatalogApi.getPlugin,
+ _pluginJsonWriter = pluginJsonWriter,
+ _errorReporter = errorReporter ?? _defaultPluginErrorReporter;
+
+ final PluginCatalogLoader _catalogLoader;
+ final PluginLoader _pluginLoader;
+ final PluginJsonWriter? _pluginJsonWriter;
+ final PluginErrorReporter _errorReporter;
+ final AsyncSingleFlight<List<PluginHTTPItem>> _catalogRefreshSingleFlight =
+ AsyncSingleFlight<List<PluginHTTPItem>>();
+ final AsyncSerialQueue _mutations = AsyncSerialQueue();
+ Map<String, PluginHTTPItem> _pluginCatalogByName = const {};
+ DateTime? _pluginCatalogRefreshedAt;
+ int _optimisticReorderRevision = 0;
+
+ // Reuse a recent catalog across startup, the rule list, and the rule shop.
+ // Explicit refresh actions always bypass this window.
+ static const _pluginCatalogMaxAge = Duration(minutes: 5);
+ static const _maxConcurrentRuleDownloads = 4;
+
@observable
ObservableList<Plugin> pluginList = ObservableList.of([]);
@@ -48,22 +118,22 @@ abstract class _PluginsController with Store {
if (!await newPluginDirectory!.exists()) {
await newPluginDirectory!.create(recursive: true);
}
- await loadAllPlugins();
+ await _loadAllPlugins();
}
// Loads all plugins from the directory, populates the plugin list, and saves to plugins.json if needed
- Future<void> loadAllPlugins() async {
+ Future<void> _loadAllPlugins() async {
pluginList.clear();
KazumiLogger().i('Plugins Directory: ${newPluginDirectory!.path}');
if (await newPluginDirectory!.exists()) {
final pluginsFile = File('${newPluginDirectory!.path}/$pluginsFileName');
if (await pluginsFile.exists()) {
final jsonString = await pluginsFile.readAsString();
- pluginList.addAll(getPluginListFromJson(jsonString));
+ pluginList.addAll(_getPluginListFromJson(jsonString));
KazumiLogger().i('Plugin: Current Plugin number: ${pluginList.length}');
} else {
// No plugins.json
- var jsonFiles = await getPluginFiles();
+ var jsonFiles = await _getPluginFiles();
for (var filePath in jsonFiles) {
final file = File(filePath);
final jsonString = await file.readAsString();
@@ -72,7 +142,7 @@ abstract class _PluginsController with Store {
pluginList.add(plugin);
await file.delete(recursive: true);
}
- savePlugins();
+ await _savePlugins();
}
} else {
KazumiLogger().w('Plugin: plugin directory does not exist');
@@ -80,7 +150,7 @@ abstract class _PluginsController with Store {
}
// Retrieves a list of JSON plugin file paths from the plugin directory
- Future<List<String>> getPluginFiles() async {
+ Future<List<String>> _getPluginFiles() async {
if (await oldPluginDirectory!.exists()) {
final jsonFiles = oldPluginDirectory!
.listSync()
@@ -105,12 +175,12 @@ abstract class _PluginsController with Store {
final plugin = Plugin.fromJson(jsonDecode(jsonString));
pluginList.add(plugin);
}
- await savePlugins();
+ await _savePlugins();
KazumiLogger().i(
'Plugin: ${jsonFiles.length} plugin files copied to ${newPluginDirectory!.path}');
}
- List<dynamic> pluginListToJson() {
+ List<dynamic> _pluginListToJson() {
final List<dynamic> json = [];
for (var plugin in pluginList) {
json.add(plugin.toJson());
@@ -119,7 +189,7 @@ abstract class _PluginsController with Store {
}
// Converts a JSON string into a list of Plugin objects.
- List<Plugin> getPluginListFromJson(String jsonString) {
+ List<Plugin> _getPluginListFromJson(String jsonString) {
List<dynamic> json = jsonDecode(jsonString);
List<Plugin> plugins = [];
for (var j in json) {
@@ -128,16 +198,25 @@ abstract class _PluginsController with Store {
return plugins;
}
- Future<void> removePlugin(Plugin plugin) async {
- pluginList.removeWhere((p) => p.name == plugin.name);
- await savePlugins();
+ Future<void> removePlugin(Plugin plugin) {
+ return _mutateAndPersist(
+ () => pluginList.removeWhere(
+ (candidate) => _catalogKey(candidate.name) == _catalogKey(plugin.name),
+ ),
+ errorMessage: 'Plugin: failed to persist rule removal',
+ );
}
- // Update or add plugin
- void updatePlugin(Plugin plugin) {
+ bool get isPluginCatalogFresh {
+ final refreshedAt = _pluginCatalogRefreshedAt;
+ return refreshedAt != null &&
+ DateTime.now().difference(refreshedAt) < _pluginCatalogMaxAge;
+ }
+
+ void _replacePlugin(Plugin plugin) {
bool flag = false;
for (int i = 0; i < pluginList.length; ++i) {
- if (pluginList[i].name == plugin.name) {
+ if (_catalogKey(pluginList[i].name) == _catalogKey(plugin.name)) {
pluginList.replaceRange(i, i + 1, [plugin]);
flag = true;
break;
@@ -146,34 +225,128 @@ abstract class _PluginsController with Store {
if (!flag) {
pluginList.add(plugin);
}
- savePlugins();
}
- void onReorder(int oldIndex, int newIndex) {
+ Future<T> _mutateAndPersist<T>(
+ T Function() mutate, {
+ required String errorMessage,
+ }) {
+ return _mutations.run(
+ () => _mutateAndPersistNow(
+ mutate,
+ errorMessage: errorMessage,
+ ),
+ );
+ }
+
+ Future<T> _mutateAndPersistNow<T>(
+ T Function() mutate, {
+ required String errorMessage,
+ }) async {
+ final previous = List<Plugin>.from(pluginList);
+ try {
+ final result = mutate();
+ await _savePlugins();
+ return result;
+ } catch (error, stackTrace) {
+ pluginList
+ ..clear()
+ ..addAll(previous);
+ _errorReporter(errorMessage, error, stackTrace);
+ rethrow;
+ }
+ }
+
+ Future<void> updatePlugin(Plugin plugin) {
+ return _mutateAndPersist(
+ () => _replacePlugin(plugin),
+ errorMessage: 'Plugin: failed to persist rule update',
+ );
+ }
+
+ Future<void> onReorder(int oldIndex, int newIndex) {
+ final previous = List<Plugin>.from(pluginList);
final plugin = pluginList.removeAt(oldIndex);
pluginList.insert(newIndex, plugin);
- savePlugins();
+ final jsonData = jsonEncode(_pluginListToJson());
+ final revision = ++_optimisticReorderRevision;
+ return _mutations.run(() async {
+ try {
+ await _writePluginsJson(jsonData);
+ } catch (error, stackTrace) {
+ if (revision == _optimisticReorderRevision) {
+ pluginList
+ ..clear()
+ ..addAll(previous);
+ }
+ _errorReporter(
+ 'Plugin: failed to persist rule order',
+ error,
+ stackTrace,
+ );
+ rethrow;
+ }
+ });
}
- Future<void> savePlugins() async {
- final jsonData = jsonEncode(pluginListToJson());
- final pluginsFile = File('${newPluginDirectory!.path}/$pluginsFileName');
- await pluginsFile.writeAsString(jsonData);
- KazumiLogger().i('Plugin: updated plugin file $pluginsFileName');
+ Future<void> _savePlugins() async {
+ final jsonData = jsonEncode(_pluginListToJson());
+ await _writePluginsJson(jsonData);
}
- Future<void> queryPluginHTTPList() async {
- pluginHTTPList.clear();
- var pluginHTTPListRes = await PluginCatalogApi.getPluginList();
- pluginHTTPList.addAll(pluginHTTPListRes);
+ Future<void> _writePluginsJson(String jsonData) async {
+ final writer = _pluginJsonWriter;
+ if (writer != null) {
+ await writer(jsonData);
+ } else {
+ final pluginsFile = File('${newPluginDirectory!.path}/$pluginsFileName');
+ await pluginsFile.writeAsString(jsonData);
+ KazumiLogger().i('Plugin: updated plugin file $pluginsFileName');
+ }
}
- Future<Plugin?> queryPluginHTTP(String name) async {
- Plugin? plugin;
- plugin = await PluginCatalogApi.getPlugin(name);
- return plugin;
+ Future<List<PluginHTTPItem>> refreshPluginCatalog() {
+ return _catalogRefreshSingleFlight.run(() async {
+ try {
+ final catalog = await _catalogLoader();
+ _pluginCatalogByName = {
+ for (final item in catalog) _catalogKey(item.name): item,
+ };
+ pluginHTTPList
+ ..clear()
+ ..addAll(catalog);
+ _pluginCatalogRefreshedAt = DateTime.now();
+ return List<PluginHTTPItem>.unmodifiable(catalog);
+ } catch (error, stackTrace) {
+ _errorReporter(
+ 'Plugin: failed to refresh rule catalog',
+ error,
+ stackTrace,
+ );
+ rethrow;
+ }
+ });
}
+ Future<List<PluginHTTPItem>> ensurePluginCatalog() {
+ if (isPluginCatalogFresh) {
+ return Future.value(
+ List<PluginHTTPItem>.unmodifiable(pluginHTTPList),
+ );
+ }
+ return refreshPluginCatalog();
+ }
+
+ Future<int> checkPluginUpdatesOnStartup({required bool enabled}) async {
+ if (!enabled) {
+ return 0;
+ }
+ await refreshPluginCatalog();
+ return _updatablePluginNames().length;
+ }
+
+ String _catalogKey(String name) => name.toLowerCase();
+
bool _remoteIsNewer(String localVersion, String remoteVersion) {
try {
return needUpdate(localVersion, remoteVersion);
@@ -182,14 +355,14 @@ abstract class _PluginsController with Store {
}
}
- String pluginStatus(PluginHTTPItem pluginHTTPItem) {
- String pluginStatus = 'install';
+ PluginCatalogItemStatus pluginStatus(PluginHTTPItem pluginHTTPItem) {
+ var pluginStatus = PluginCatalogItemStatus.install;
for (Plugin plugin in pluginList) {
- if (pluginHTTPItem.name == plugin.name) {
+ if (_catalogKey(pluginHTTPItem.name) == _catalogKey(plugin.name)) {
if (_remoteIsNewer(plugin.version, pluginHTTPItem.version)) {
- pluginStatus = 'update';
+ pluginStatus = PluginCatalogItemStatus.update;
} else {
- pluginStatus = 'installed';
+ pluginStatus = PluginCatalogItemStatus.installed;
}
break;
}
@@ -197,63 +370,191 @@ abstract class _PluginsController with Store {
return pluginStatus;
}
- String pluginUpdateStatus(Plugin plugin) {
- if (!pluginHTTPList.any((p) => p.name == plugin.name)) {
- return "nonexistent";
+ PluginUpdateAvailability pluginUpdateStatus(Plugin plugin) {
+ if (_pluginCatalogRefreshedAt == null) {
+ return PluginUpdateAvailability.unknown;
}
- PluginHTTPItem p = pluginHTTPList.firstWhere(
- (p) => p.name == plugin.name,
- );
- return _remoteIsNewer(plugin.version, p.version) ? "updatable" : "latest";
+ final remote = _pluginCatalogByName[_catalogKey(plugin.name)];
+ if (remote == null) {
+ return PluginUpdateAvailability.notInCatalog;
+ }
+ return _remoteIsNewer(plugin.version, remote.version)
+ ? PluginUpdateAvailability.updatable
+ : PluginUpdateAvailability.latest;
}
- Future<int> tryUpdatePlugin(Plugin plugin) async {
- return await tryUpdatePluginByName(plugin.name);
+ List<String> _updatablePluginNames() {
+ return [
+ for (final plugin in pluginList)
+ if (pluginUpdateStatus(plugin) == PluginUpdateAvailability.updatable)
+ _pluginCatalogByName[_catalogKey(plugin.name)]!.name,
+ ];
}
- Future<int> tryUpdatePluginByName(String name) async {
- var pluginHTTPItem = await queryPluginHTTP(name);
- if (pluginHTTPItem != null) {
- if (pluginHTTPItem.requiresNewerClient) {
- return 1;
+ Future<PluginUpdateResult> tryUpdatePluginByName(String name) {
+ return _mutations.run(() async {
+ final catalogName = _pluginCatalogByName[_catalogKey(name)]?.name ?? name;
+ final attempt = await _preparePluginUpdate(catalogName);
+ if (attempt.result == PluginUpdateResult.updated) {
+ await _mutateAndPersistNow(
+ () => _replacePlugin(attempt.plugin!),
+ errorMessage:
+ 'Plugin: failed to persist downloaded rule $catalogName',
+ );
}
- Plugin? local;
- for (final p in pluginList) {
- if (p.name == name) {
- local = p;
- break;
- }
+ return attempt.result;
+ });
+ }
+
+ Future<_PluginUpdateAttempt> _preparePluginUpdate(String name) async {
+ late final Plugin remotePlugin;
+ try {
+ remotePlugin = await _pluginLoader(name);
+ } catch (error, stackTrace) {
+ _errorReporter(
+ 'Plugin: failed to download rule $name',
+ error,
+ stackTrace,
+ );
+ return (result: PluginUpdateResult.failed, plugin: null);
+ }
+ // Validate at the injected loader boundary so production and test/custom
+ // loaders follow the same integrity rule. Preserve the catalog spelling.
+ if (remotePlugin.name.isEmpty ||
+ _catalogKey(remotePlugin.name) != _catalogKey(name)) {
+ final error = FormatException(
+ 'Downloaded rule name ${remotePlugin.name} does not match $name',
+ );
+ _errorReporter(
+ 'Plugin: rejected mismatched rule payload',
+ error,
+ StackTrace.current,
+ );
+ return (result: PluginUpdateResult.failed, plugin: null);
+ }
+ remotePlugin.name = name;
+ try {
+ if (remotePlugin.requiresNewerClient) {
+ return (
+ result: PluginUpdateResult.requiresNewerClient,
+ plugin: null,
+ );
}
- // Never downgrade an installed plugin; mirrors may lag behind upstream
- if (local != null &&
- !_remoteIsNewer(local.version, pluginHTTPItem.version)) {
- return 3;
+ } catch (error, stackTrace) {
+ _errorReporter(
+ 'Plugin: invalid API level in rule $name',
+ error,
+ stackTrace,
+ );
+ return (result: PluginUpdateResult.failed, plugin: null);
+ }
+ Plugin? local;
+ for (final plugin in pluginList) {
+ if (_catalogKey(plugin.name) == _catalogKey(name)) {
+ local = plugin;
+ break;
}
- updatePlugin(pluginHTTPItem);
- return 0;
}
- return 2;
+ // Never downgrade an installed plugin; mirrors may lag behind upstream.
+ if (local != null && !_remoteIsNewer(local.version, remotePlugin.version)) {
+ return (result: PluginUpdateResult.notNewer, plugin: null);
+ }
+ return (result: PluginUpdateResult.updated, plugin: remotePlugin);
}
- Future<int> tryUpdateAllPlugin() async {
- int count = 0;
- for (Plugin plugin in pluginList) {
- if (pluginUpdateStatus(plugin) == 'updatable') {
- if (await tryUpdatePlugin(plugin) == 0) {
- count++;
- }
+ Future<PluginBatchUpdateResult> tryUpdateAllPlugin({
+ bool ensureCatalog = true,
+ }) {
+ return _mutations.run(
+ () => _tryUpdateAllPlugin(ensureCatalog: ensureCatalog),
+ );
+ }
+
+ Future<PluginBatchUpdateResult> _tryUpdateAllPlugin({
+ required bool ensureCatalog,
+ }) async {
+ if (ensureCatalog) {
+ await ensurePluginCatalog();
+ } else if (_pluginCatalogRefreshedAt == null) {
+ throw StateError('Plugin catalog has not been loaded');
+ }
+
+ final candidates = _updatablePluginNames();
+ final attempts = await _preparePluginUpdates(candidates);
+ var updated = 0;
+ var requiresNewerClient = 0;
+ var failed = 0;
+ var notNewer = 0;
+
+ final updatedPlugins = <Plugin>[];
+ for (final attempt in attempts) {
+ switch (attempt.result) {
+ case PluginUpdateResult.updated:
+ updated++;
+ updatedPlugins.add(attempt.plugin!);
+ case PluginUpdateResult.requiresNewerClient:
+ requiresNewerClient++;
+ case PluginUpdateResult.failed:
+ failed++;
+ case PluginUpdateResult.notNewer:
+ notNewer++;
}
}
- return count;
+
+ if (updatedPlugins.isNotEmpty) {
+ await _mutateAndPersistNow(
+ () {
+ for (final plugin in updatedPlugins) {
+ _replacePlugin(plugin);
+ }
+ },
+ errorMessage: 'Plugin: failed to persist batch rule update',
+ );
+ }
+ return PluginBatchUpdateResult(
+ candidates: candidates.length,
+ updated: updated,
+ requiresNewerClient: requiresNewerClient,
+ failed: failed,
+ notNewer: notNewer,
+ );
}
- void removePlugins(Set<String> pluginNames) {
- for (int i = pluginList.length - 1; i >= 0; --i) {
- var name = pluginList[i].name;
- if (pluginNames.contains(name)) {
- pluginList.removeAt(i);
+ Future<List<_PluginUpdateAttempt>> _preparePluginUpdates(
+ List<String> names,
+ ) async {
+ if (names.isEmpty) {
+ return const [];
+ }
+ final results = List<_PluginUpdateAttempt?>.filled(names.length, null);
+ var nextIndex = 0;
+
+ Future<void> worker() async {
+ while (nextIndex < names.length) {
+ final index = nextIndex++;
+ results[index] = await _preparePluginUpdate(names[index]);
}
}
- savePlugins();
+
+ final workerCount = names.length < _maxConcurrentRuleDownloads
+ ? names.length
+ : _maxConcurrentRuleDownloads;
+ await Future.wait(List.generate(workerCount, (_) => worker()));
+ return results.cast<_PluginUpdateAttempt>();
+ }
+
+ Future<void> removePlugins(Set<String> pluginNames) {
+ final names = Set<String>.of(pluginNames);
+ return _mutateAndPersist(
+ () {
+ for (int i = pluginList.length - 1; i >= 0; --i) {
+ var name = pluginList[i].name;
+ if (names.contains(name)) {
+ pluginList.removeAt(i);
+ }
+ }
+ },
+ errorMessage: 'Plugin: failed to persist batch rule removal',
+ );
}
}
diff --git a/lib/request/apis/plugin_catalog_api.dart b/lib/request/apis/plugin_catalog_api.dart
index 9a50ea90..3980c58f 100644
--- a/lib/request/apis/plugin_catalog_api.dart
+++ b/lib/request/apis/plugin_catalog_api.dart
@@ -9,32 +9,66 @@ class PluginCatalogApi {
static final RulesRepoClient _client = RulesRepoClient.instance;
static Future<List<PluginHTTPItem>> getPluginList() async {
- List<PluginHTTPItem> pluginHTTPItemList = [];
- try {
- final raw = await _client.getText('${ApiEndpoints.pluginShop}index.json');
- final jsonData = json.decode(raw);
- for (dynamic pluginJsonItem in jsonData) {
- try {
- PluginHTTPItem pluginHTTPItem =
- PluginHTTPItem.fromJson(pluginJsonItem);
- pluginHTTPItemList.add(pluginHTTPItem);
- } catch (_) {}
+ final raw = await _client.getText('${ApiEndpoints.pluginShop}index.json');
+ final result = parsePluginList(raw);
+ if (result.skippedItems > 0) {
+ KazumiLogger().w(
+ 'Plugin: skipped ${result.skippedItems} invalid rule catalog item(s)',
+ );
+ }
+ return result.items;
+ }
+
+ static PluginCatalogParseResult parsePluginList(String raw) {
+ final jsonData = json.decode(raw);
+ if (jsonData is! List) {
+ throw const FormatException('Rule catalog root must be a JSON array');
+ }
+ final items = <PluginHTTPItem>[];
+ var skippedItems = 0;
+ for (var index = 0; index < jsonData.length; index++) {
+ try {
+ items.add(_parsePluginListItem(jsonData[index], index));
+ } on FormatException {
+ skippedItems++;
}
- } catch (e) {
- KazumiLogger().e('Plugin: getPluginList error: ${e.toString()}');
}
- return pluginHTTPItemList;
+ if (jsonData.isNotEmpty && items.isEmpty) {
+ throw const FormatException('Rule catalog contains no valid items');
+ }
+ return PluginCatalogParseResult(
+ items: List.unmodifiable(items),
+ skippedItems: skippedItems,
+ );
}
- static Future<Plugin?> getPlugin(String name) async {
- Plugin? plugin;
+ static PluginHTTPItem _parsePluginListItem(Object? value, int index) {
+ if (value is! Map) {
+ throw FormatException('Rule catalog item $index must be an object');
+ }
try {
- final raw = await _client.getText('${ApiEndpoints.pluginShop}$name.json');
- final jsonData = json.decode(raw);
- plugin = Plugin.fromJson(jsonData);
- } catch (e) {
- KazumiLogger().e('Plugin: getPlugin error: ${e.toString()}');
+ return PluginHTTPItem.fromJson(Map<String, dynamic>.from(value));
+ } catch (error) {
+ throw FormatException('Invalid rule catalog item $index: $error');
}
- return plugin;
}
+
+ static Future<Plugin> getPlugin(String name) async {
+ final raw = await _client.getText('${ApiEndpoints.pluginShop}$name.json');
+ final jsonData = json.decode(raw);
+ if (jsonData is! Map) {
+ throw FormatException('Rule $name must be a JSON object');
+ }
+ return Plugin.fromJson(Map<String, dynamic>.from(jsonData));
+ }
+}
+
+class PluginCatalogParseResult {
+ const PluginCatalogParseResult({
+ required this.items,
+ required this.skippedItems,
+ });
+
+ final List<PluginHTTPItem> items;
+ final int skippedItems;
}
diff --git a/lib/services/storage/settings_keys.dart b/lib/services/storage/settings_keys.dart
index 1c6d7225..2c8f57c7 100644
--- a/lib/services/storage/settings_keys.dart
+++ b/lib/services/storage/settings_keys.dart
@@ -60,6 +60,11 @@ class SettingsKeys {
true,
group: SettingGroup.update,
);
+ static const checkPluginUpdateOnStartup = SettingKey<bool>(
+ 'checkPluginUpdateOnStartup',
+ true,
+ group: SettingGroup.update,
+ );
static const alwaysOntop = SettingKey<bool>(
_SettingBoxKey.alwaysOntop,
false,
@@ -502,6 +507,7 @@ class SettingsKeys {
hardwareDecoder,
searchEnhanceEnable,
autoUpdate,
+ checkPluginUpdateOnStartup,
alwaysOntop,
defaultPlaySpeed,
defaultShortcutForwardPlaySpeed,