Skip to content

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

feat(plugin): support bulk rule imports (#2488)

misakaac39437a83b1
diff --git a/lib/pages/plugin_editor/plugin_view_page.dart b/lib/pages/plugin_editor/plugin_view_page.dart
index 20d76999..24ce25fc 100644
--- a/lib/pages/plugin_editor/plugin_view_page.dart
+++ b/lib/pages/plugin_editor/plugin_view_page.dart
@@ -1,5 +1,8 @@
import 'dart:async';
import 'dart:convert';
+import 'dart:io';
+
+import 'package:file_picker/file_picker.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_mobx/flutter_mobx.dart';
@@ -11,6 +14,7 @@ import 'package:kazumi/plugins/plugins_controller.dart';
import 'package:kazumi/bean/settings/settings_detail_scaffold.dart';
import 'package:kazumi/pages/plugin_editor/plugin_update_actions.dart';
import 'package:kazumi/services/logging/logger.dart';
+import 'package:kazumi/services/plugin/plugin_import_parser.dart';
import 'package:kazumi/utils/encoding.dart';
class PluginViewPage extends StatefulWidget {
@@ -80,9 +84,20 @@ class _PluginViewPageState extends State<PluginViewPage> {
const SizedBox(height: 10),
ListTile(
title: const Text('从剪贴板导入'),
+ onTap: () async {
+ KazumiDialog.dismiss();
+ final clipboard =
+ await Clipboard.getData(Clipboard.kTextPlain);
+ if (!mounted) return;
+ _showInputDialog(initialValue: clipboard?.text ?? '');
+ },
+ ),
+ const SizedBox(height: 10),
+ ListTile(
+ title: const Text('从文件导入'),
onTap: () {
KazumiDialog.dismiss();
- _showInputDialog();
+ _importFromFile();
},
),
],
@@ -92,18 +107,25 @@ class _PluginViewPageState extends State<PluginViewPage> {
});
}
- void _showInputDialog() {
- String pluginText = '';
+ void _showInputDialog({String initialValue = ''}) {
+ var pluginText = initialValue;
KazumiDialog.show(
builder: (context) {
return AlertDialog(
- title: const Text('导入规则'),
- content: StatefulBuilder(
- builder: (BuildContext context, StateSetter setState) {
- return TextField(
+ title: const Text('从剪贴板导入规则'),
+ content: SizedBox(
+ width: 520,
+ child: TextFormField(
+ initialValue: initialValue,
onChanged: (value) => pluginText = value,
- );
- }),
+ minLines: 4,
+ maxLines: 10,
+ decoration: const InputDecoration(
+ hintText: '可粘贴多条 kazumi:// 链接或 JSON 数组',
+ border: OutlineInputBorder(),
+ ),
+ ),
+ ),
actions: [
TextButton(
onPressed: () => KazumiDialog.dismiss(),
@@ -112,43 +134,74 @@ class _PluginViewPageState extends State<PluginViewPage> {
style: TextStyle(color: Theme.of(context).colorScheme.outline),
),
),
- StatefulBuilder(
- builder: (BuildContext context, StateSetter setState) {
- return TextButton(
- onPressed: () async {
- try {
- final plugin = Plugin.fromJson(
- json.decode(kazumiBase64ToJson(pluginText)),
- );
- if (plugin.requiresNewerClient) {
- KazumiDialog.dismiss();
- KazumiDialog.showToast(
- message: '规则需要更高版本客户端',
- );
- return;
- }
- await pluginsController.updatePlugin(plugin);
- KazumiDialog.dismiss();
- KazumiDialog.showToast(message: '导入成功');
- } catch (e, stackTrace) {
- KazumiLogger().e(
- 'Plugin: failed to import rule link',
- error: e,
- stackTrace: stackTrace,
- );
- KazumiDialog.dismiss();
- KazumiDialog.showToast(message: '导入失败 ${e.toString()}');
- }
- },
- child: const Text('导入'),
- );
- })
+ TextButton(
+ onPressed: () => _importFromText(
+ pluginText,
+ dismissDialog: true,
+ ),
+ child: const Text('导入'),
+ ),
],
);
},
);
}
+ Future<void> _importFromFile() async {
+ try {
+ final result = await FilePicker.platform.pickFiles(
+ type: FileType.custom,
+ allowedExtensions: const ['json'],
+ withData: true,
+ );
+ if (result == null) return;
+ final file = result.files.single;
+ final bytes = file.bytes ??
+ (file.path == null ? null : await File(file.path!).readAsBytes());
+ if (bytes == null) {
+ throw const FileSystemException('无法读取所选文件');
+ }
+ await _importFromText(utf8.decode(bytes));
+ } catch (error, stackTrace) {
+ KazumiLogger().e(
+ 'Plugin: failed to import rules from file',
+ error: error,
+ stackTrace: stackTrace,
+ );
+ KazumiDialog.showToast(message: '读取规则文件失败:$error');
+ }
+ }
+
+ Future<void> _importFromText(
+ String text, {
+ bool dismissDialog = false,
+ }) async {
+ final result = PluginImportParser.parse(text);
+ if (result.plugins.isEmpty) {
+ if (dismissDialog) KazumiDialog.dismiss();
+ KazumiDialog.showToast(
+ message: result.failures.isEmpty ? '没有可导入的规则' : result.failures.first,
+ );
+ return;
+ }
+
+ if (dismissDialog) KazumiDialog.dismiss();
+ try {
+ await pluginsController.updatePlugins(result.plugins);
+ KazumiDialog.showToast(
+ message: '导入完成:成功 ${result.plugins.length} 条,'
+ '跳过重复 ${result.duplicateCount} 条,失败 ${result.failureCount} 条',
+ );
+ } catch (error, stackTrace) {
+ KazumiLogger().e(
+ 'Plugin: failed to persist imported rules',
+ error: error,
+ stackTrace: stackTrace,
+ );
+ KazumiDialog.showToast(message: '保存导入规则失败:$error');
+ }
+ }
+
void onBackPressed(BuildContext context) {
if (KazumiDialog.observer.hasKazumiDialog) {
KazumiDialog.dismiss();
diff --git a/lib/plugins/plugins.dart b/lib/plugins/plugins.dart
index df096c62..1fe17292 100644
--- a/lib/plugins/plugins.dart
+++ b/lib/plugins/plugins.dart
@@ -14,6 +14,8 @@ export 'package:kazumi/services/plugin/rule_engine_models.dart'
SearchErrorException,
ChapterErrorException;
+String pluginNameKey(String name) => name.toLowerCase();
+
class Plugin {
static final RuleEngine _ruleEngine = RuleEngine();
diff --git a/lib/plugins/plugins_controller.dart b/lib/plugins/plugins_controller.dart
index 4756f124..5ed69efe 100644
--- a/lib/plugins/plugins_controller.dart
+++ b/lib/plugins/plugins_controller.dart
@@ -201,7 +201,8 @@ abstract class _PluginsController with Store {
Future<void> removePlugin(Plugin plugin) {
return _mutateAndPersist(
() => pluginList.removeWhere(
- (candidate) => _catalogKey(candidate.name) == _catalogKey(plugin.name),
+ (candidate) =>
+ pluginNameKey(candidate.name) == pluginNameKey(plugin.name),
),
errorMessage: 'Plugin: failed to persist rule removal',
);
@@ -216,7 +217,7 @@ abstract class _PluginsController with Store {
void _replacePlugin(Plugin plugin) {
bool flag = false;
for (int i = 0; i < pluginList.length; ++i) {
- if (_catalogKey(pluginList[i].name) == _catalogKey(plugin.name)) {
+ if (pluginNameKey(pluginList[i].name) == pluginNameKey(plugin.name)) {
pluginList.replaceRange(i, i + 1, [plugin]);
flag = true;
break;
@@ -264,6 +265,17 @@ abstract class _PluginsController with Store {
);
}
+ Future<void> updatePlugins(Iterable<Plugin> plugins) {
+ return _mutateAndPersist(
+ () {
+ for (final plugin in plugins) {
+ _replacePlugin(plugin);
+ }
+ },
+ errorMessage: 'Plugin: failed to persist imported rules',
+ );
+ }
+
Future<void> onReorder(int oldIndex, int newIndex) {
final previous = List<Plugin>.from(pluginList);
final plugin = pluginList.removeAt(oldIndex);
@@ -310,7 +322,7 @@ abstract class _PluginsController with Store {
try {
final catalog = await _catalogLoader();
_pluginCatalogByName = {
- for (final item in catalog) _catalogKey(item.name): item,
+ for (final item in catalog) pluginNameKey(item.name): item,
};
pluginHTTPList
..clear()
@@ -345,8 +357,6 @@ abstract class _PluginsController with Store {
return _updatablePluginNames().length;
}
- String _catalogKey(String name) => name.toLowerCase();
-
bool _remoteIsNewer(String localVersion, String remoteVersion) {
try {
return needUpdate(localVersion, remoteVersion);
@@ -358,7 +368,7 @@ abstract class _PluginsController with Store {
PluginCatalogItemStatus pluginStatus(PluginHTTPItem pluginHTTPItem) {
var pluginStatus = PluginCatalogItemStatus.install;
for (Plugin plugin in pluginList) {
- if (_catalogKey(pluginHTTPItem.name) == _catalogKey(plugin.name)) {
+ if (pluginNameKey(pluginHTTPItem.name) == pluginNameKey(plugin.name)) {
if (_remoteIsNewer(plugin.version, pluginHTTPItem.version)) {
pluginStatus = PluginCatalogItemStatus.update;
} else {
@@ -374,7 +384,7 @@ abstract class _PluginsController with Store {
if (_pluginCatalogRefreshedAt == null) {
return PluginUpdateAvailability.unknown;
}
- final remote = _pluginCatalogByName[_catalogKey(plugin.name)];
+ final remote = _pluginCatalogByName[pluginNameKey(plugin.name)];
if (remote == null) {
return PluginUpdateAvailability.notInCatalog;
}
@@ -387,13 +397,14 @@ abstract class _PluginsController with Store {
return [
for (final plugin in pluginList)
if (pluginUpdateStatus(plugin) == PluginUpdateAvailability.updatable)
- _pluginCatalogByName[_catalogKey(plugin.name)]!.name,
+ _pluginCatalogByName[pluginNameKey(plugin.name)]!.name,
];
}
Future<PluginUpdateResult> tryUpdatePluginByName(String name) {
return _mutations.run(() async {
- final catalogName = _pluginCatalogByName[_catalogKey(name)]?.name ?? name;
+ final catalogName =
+ _pluginCatalogByName[pluginNameKey(name)]?.name ?? name;
final attempt = await _preparePluginUpdate(catalogName);
if (attempt.result == PluginUpdateResult.updated) {
await _mutateAndPersistNow(
@@ -421,7 +432,7 @@ abstract class _PluginsController with Store {
// 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)) {
+ pluginNameKey(remotePlugin.name) != pluginNameKey(name)) {
final error = FormatException(
'Downloaded rule name ${remotePlugin.name} does not match $name',
);
@@ -450,7 +461,7 @@ abstract class _PluginsController with Store {
}
Plugin? local;
for (final plugin in pluginList) {
- if (_catalogKey(plugin.name) == _catalogKey(name)) {
+ if (pluginNameKey(plugin.name) == pluginNameKey(name)) {
local = plugin;
break;
}
diff --git a/lib/services/plugin/plugin_import_parser.dart b/lib/services/plugin/plugin_import_parser.dart
new file mode 100644
index 00000000..835268d3
--- /dev/null
+++ b/lib/services/plugin/plugin_import_parser.dart
@@ -0,0 +1,176 @@
+import 'dart:convert';
+
+import 'package:kazumi/plugins/plugins.dart';
+import 'package:kazumi/utils/encoding.dart';
+
+class PluginImportParseResult {
+ const PluginImportParseResult({
+ required this.plugins,
+ required this.failures,
+ required this.duplicateCount,
+ });
+
+ final List<Plugin> plugins;
+ final List<String> failures;
+ final int duplicateCount;
+
+ int get failureCount => failures.length;
+}
+
+class PluginImportParser {
+ const PluginImportParser._();
+
+ static final RegExp _ruleLinkPayloadPrefixPattern = RegExp(
+ r'^[A-Za-z0-9+/_=%\-\s]+',
+ );
+ static final RegExp _whitespacePattern = RegExp(r'\s+');
+
+ static PluginImportParseResult parse(String input) {
+ final value = input.trim();
+ if (value.isEmpty) {
+ return const PluginImportParseResult(
+ plugins: [],
+ failures: ['导入内容为空'],
+ duplicateCount: 0,
+ );
+ }
+
+ final parsed = <Plugin>[];
+ final failures = <String>[];
+ Object? jsonValue;
+ var decodedAsJson = false;
+ try {
+ jsonValue = json.decode(value);
+ decodedAsJson = true;
+ } on FormatException {
+ // Share links and text files are parsed below.
+ }
+
+ if (decodedAsJson) {
+ if (jsonValue is List) {
+ for (var index = 0; index < jsonValue.length; index++) {
+ _parseEntry(jsonValue[index], index + 1, parsed, failures);
+ }
+ } else {
+ _parseEntry(jsonValue, 1, parsed, failures);
+ }
+ } else {
+ final segments = findKazumiRuleLinkSegments(value).toList();
+ if (segments.isEmpty) {
+ failures.add('未找到有效的 JSON 或 kazumi:// 规则链接');
+ } else {
+ for (var index = 0; index < segments.length; index++) {
+ final segment = segments[index];
+ _parseRuleLinkSegment(
+ segment.scheme,
+ segment.rawPayload,
+ index + 1,
+ parsed,
+ failures,
+ );
+ }
+ }
+ }
+
+ final uniquePlugins = <String, Plugin>{};
+ var duplicateCount = 0;
+ for (final plugin in parsed) {
+ final key = pluginNameKey(plugin.name);
+ if (uniquePlugins.containsKey(key)) {
+ duplicateCount++;
+ }
+ uniquePlugins[key] = plugin;
+ }
+
+ return PluginImportParseResult(
+ plugins: List.unmodifiable(uniquePlugins.values),
+ failures: List.unmodifiable(failures),
+ duplicateCount: duplicateCount,
+ );
+ }
+
+ static void _parseRuleLinkSegment(
+ String scheme,
+ String rawPayload,
+ int index,
+ List<Plugin> plugins,
+ List<String> failures,
+ ) {
+ try {
+ final entry = _decodeRuleEntry(scheme, rawPayload);
+ _parseEntry(entry, index, plugins, failures);
+ } catch (error) {
+ failures.add('第 $index 条:$error');
+ }
+ }
+
+ static Map<String, dynamic> _decodeRuleEntry(
+ String scheme,
+ String rawPayload,
+ ) {
+ final payload = _ruleLinkPayloadPrefixPattern
+ .firstMatch(rawPayload)
+ ?.group(0)
+ ?.trimRight();
+ if (payload == null || payload.isEmpty) {
+ throw const FormatException('Missing payload in Kazumi rule link');
+ }
+
+ final candidates = <String>[payload];
+ final whitespaceMatches = _whitespacePattern.allMatches(payload).toList();
+ for (final whitespaceMatch in whitespaceMatches.reversed) {
+ final candidate = payload.substring(0, whitespaceMatch.start).trimRight();
+ if (candidate.isNotEmpty && candidate != candidates.last) {
+ candidates.add(candidate);
+ }
+ }
+
+ FormatException? firstError;
+ for (final candidate in candidates) {
+ try {
+ final decoded = json.decode(kazumiBase64ToJson('$scheme$candidate'));
+ if (decoded is Map) {
+ return Map<String, dynamic>.from(decoded);
+ }
+ firstError ??=
+ const FormatException('规则链接内容必须是 JSON object');
+ } on FormatException catch (error) {
+ firstError ??= error;
+ // Try a shorter prefix in case prose follows the rule link.
+ }
+ }
+ throw firstError ?? const FormatException('Invalid Kazumi rule link');
+ }
+
+ static void _parseEntry(
+ Object? entry,
+ int index,
+ List<Plugin> plugins,
+ List<String> failures,
+ ) {
+ try {
+ late final Plugin plugin;
+ if (entry is Map) {
+ plugin = Plugin.fromJson(Map<String, dynamic>.from(entry));
+ } else if (entry is String) {
+ final decoded = json.decode(kazumiBase64ToJson(entry));
+ if (decoded is! Map) {
+ throw const FormatException('规则链接内容必须是 JSON object');
+ }
+ plugin = Plugin.fromJson(Map<String, dynamic>.from(decoded));
+ } else {
+ throw const FormatException('规则必须是 JSON object 或 kazumi:// 链接');
+ }
+
+ if (plugin.name.trim().isEmpty) {
+ throw const FormatException('规则名称不能为空');
+ }
+ if (plugin.requiresNewerClient) {
+ throw const FormatException('规则需要更高版本客户端');
+ }
+ plugins.add(plugin);
+ } catch (error) {
+ failures.add('第 $index 条:$error');
+ }
+ }
+}
diff --git a/lib/utils/encoding.dart b/lib/utils/encoding.dart
index 46faefcb..3bfaf25d 100644
--- a/lib/utils/encoding.dart
+++ b/lib/utils/encoding.dart
@@ -1,5 +1,26 @@
import 'dart:convert';
+final RegExp _kazumiRuleLinkSchemePattern = RegExp(
+ r'kazumi:(?://)?',
+ caseSensitive: false,
+);
+
+Iterable<({String scheme, String rawPayload})> findKazumiRuleLinkSegments(
+ String input,
+) sync* {
+ final matches = _kazumiRuleLinkSchemePattern.allMatches(input).toList();
+ for (var index = 0; index < matches.length; index++) {
+ final match = matches[index];
+ final end = index + 1 < matches.length
+ ? matches[index + 1].start
+ : input.length;
+ yield (
+ scheme: match.group(0)!,
+ rawPayload: input.substring(match.end, end),
+ );
+ }
+}
+
String jsonToKazumiBase64(String jsonStr) {
final base64Str = base64Encode(utf8.encode(jsonStr));
return 'kazumi://$base64Str';
@@ -7,10 +28,7 @@ String jsonToKazumiBase64(String jsonStr) {
String kazumiBase64ToJson(String kazumiBase64Str) {
final input = kazumiBase64Str.trim();
- final schemeMatch = RegExp(
- r'^kazumi:(?://)?',
- caseSensitive: false,
- ).firstMatch(input);
+ final schemeMatch = _kazumiRuleLinkSchemePattern.matchAsPrefix(input);
if (schemeMatch == null) {
throw const FormatException('Invalid Kazumi rule link');
}
@@ -20,6 +38,8 @@ String kazumiBase64ToJson(String kazumiBase64Str) {
payload = Uri.decodeComponent(payload);
} on FormatException {
throw const FormatException('Invalid encoding in Kazumi rule link');
+ } on ArgumentError {
+ throw const FormatException('Invalid encoding in Kazumi rule link');
}
payload = payload.replaceAll(RegExp(r'\s'), '');
if (payload.isEmpty) {
diff --git a/test/plugin_api_config_test.dart b/test/plugin_api_config_test.dart
index 4c97866f..add3ad35 100644
--- a/test/plugin_api_config_test.dart
+++ b/test/plugin_api_config_test.dart
@@ -204,6 +204,10 @@ void main() {
() => kazumiBase64ToJson('kazumi://not-base64!'),
throwsA(isA<FormatException>()),
);
+ expect(
+ () => kazumiBase64ToJson('kazumi://%zz'),
+ throwsA(isA<FormatException>()),
+ );
});
}
diff --git a/test/plugin_import_parser_test.dart b/test/plugin_import_parser_test.dart
new file mode 100644
index 00000000..c58f0ccf
--- /dev/null
+++ b/test/plugin_import_parser_test.dart
@@ -0,0 +1,224 @@
+import 'dart:convert';
+
+import 'package:flutter_test/flutter_test.dart';
+import 'package:kazumi/plugins/plugins.dart';
+import 'package:kazumi/plugins/plugins_controller.dart';
+import 'package:kazumi/services/plugin/plugin_import_parser.dart';
+import 'package:kazumi/utils/encoding.dart';
+
+void main() {
+ Plugin plugin(String name) {
+ return Plugin.fromTemplate()
+ ..name = name
+ ..version = '1.0';
+ }
+
+ String linkFor(Plugin value) {
+ return jsonToKazumiBase64(jsonEncode(value.toJson()));
+ }
+
+ group('PluginImportParser', () {
+ test('keeps single-link import backward compatible', () {
+ final result = PluginImportParser.parse(linkFor(plugin('single')));
+
+ expect(result.plugins.single.name, 'single');
+ expect(result.failureCount, 0);
+ });
+
+ test('imports multiple Kazumi links from text', () {
+ final result = PluginImportParser.parse(
+ '${linkFor(plugin('one'))}\n${linkFor(plugin('two'))}',
+ );
+
+ expect(result.plugins.map((item) => item.name), ['one', 'two']);
+ expect(result.failureCount, 0);
+ expect(result.duplicateCount, 0);
+ });
+
+ test('imports a link with an uppercase scheme', () {
+ final link = linkFor(plugin('uppercase'))
+ .replaceFirst('kazumi://', 'KAZUMI://');
+
+ final result = PluginImportParser.parse(link);
+
+ expect(result.plugins.single.name, 'uppercase');
+ expect(result.failureCount, 0);
+ });
+
+ test('imports a rule link wrapped across lines', () {
+ final link = linkFor(plugin('wrapped'));
+ final splitAt = link.length ~/ 2;
+ final wrapped = '${link.substring(0, splitAt)}\n'
+ ' ${link.substring(splitAt)}';
+
+ final result = PluginImportParser.parse(wrapped);
+
+ expect(result.plugins.single.name, 'wrapped');
+ expect(result.failureCount, 0);
+ });
+
+ test('does not merge adjacent wrapped rule links', () {
+ String wrap(String link) {
+ final splitAt = link.length ~/ 2;
+ return '${link.substring(0, splitAt)}\n${link.substring(splitAt)}';
+ }
+
+ final result = PluginImportParser.parse(
+ '${wrap(linkFor(plugin('one')))}\n'
+ '${wrap(linkFor(plugin('two')))}',
+ );
+
+ expect(result.plugins.map((item) => item.name), ['one', 'two']);
+ expect(result.failureCount, 0);
+ });
+
+ test('ignores prose after a rule link', () {
+ final link = linkFor(plugin('shared'));
+
+ final chineseResult = PluginImportParser.parse('$link 谢谢分享');
+ final englishResult = PluginImportParser.parse('$link thanks');
+
+ expect(chineseResult.plugins.single.name, 'shared');
+ expect(chineseResult.failureCount, 0);
+ expect(englishResult.plugins.single.name, 'shared');
+ expect(englishResult.failureCount, 0);
+ });
+
+ test('imports a percent-encoded link followed by prose', () {
+ final link = linkFor(plugin('encoded'));
+ final payload = link.substring('kazumi://'.length);
+ final firstByte = payload.codeUnitAt(0)
+ .toRadixString(16)
+ .padLeft(2, '0')
+ .toUpperCase();
+ final encodedPayload = '%$firstByte${payload.substring(1)}';
+
+ expect(encodedPayload, isNot(payload));
+
+ final result = PluginImportParser.parse(
+ 'kazumi:$encodedPayload thanks',
+ );
+
+ expect(result.plugins.single.name, 'encoded');
+ expect(result.failureCount, 0);
+ });
+
+ test('imports links separated by punctuation', () {
+ final result = PluginImportParser.parse(
+ '${linkFor(plugin('one'))}、${linkFor(plugin('two'))}',
+ );
+
+ expect(result.plugins.map((item) => item.name), ['one', 'two']);
+ expect(result.failureCount, 0);
+ });
+
+ test('imports a JSON array of rules', () {
+ final result = PluginImportParser.parse(
+ jsonEncode([plugin('one').toJson(), plugin('two').toJson()]),
+ );
+
+ expect(result.plugins.map((item) => item.name), ['one', 'two']);
+ expect(result.failureCount, 0);
+ });
+
+ test('keeps valid links when another link is invalid', () {
+ final result = PluginImportParser.parse(
+ '${linkFor(plugin('valid'))}\nkazumi://not-base64!',
+ );
+
+ expect(result.plugins.single.name, 'valid');
+ expect(result.failureCount, 1);
+ });
+
+ test('keeps valid links when a decoded link is not an object', () {
+ final result = PluginImportParser.parse(
+ '${jsonToKazumiBase64(jsonEncode([42]))}\n'
+ '${linkFor(plugin('valid'))}',
+ );
+
+ expect(result.plugins.single.name, 'valid');
+ expect(result.failureCount, 1);
+ });
+
+ test('keeps valid links after malformed percent encoding', () {
+ final result = PluginImportParser.parse(
+ 'kazumi://%zz\n${linkFor(plugin('valid'))}',
+ );
+
+ expect(result.plugins.single.name, 'valid');
+ expect(result.failureCount, 1);
+ });
+
+ test('keeps the last duplicate rule', () {
+ final first = plugin('same')..version = '1.0';
+ final second = plugin('SAME')..version = '2.0';
+ final result = PluginImportParser.parse(
+ '${linkFor(first)}\n${linkFor(second)}',
+ );
+
+ expect(result.plugins.single.version, '2.0');
+ expect(result.duplicateCount, 1);
+ });
+
+ test('rejects unsupported JSON values', () {
+ final result = PluginImportParser.parse('[42, null]');
+
+ expect(result.plugins, isEmpty);
+ expect(result.failureCount, 2);
+ });
+ });
+
+ group('PluginsController.updatePlugins', () {
+ test('imports all parsed rules with one persistence write', () async {
+ var writeCount = 0;
+ late String persistedJson;
+ final controller = PluginsController(
+ pluginJsonWriter: (jsonData) async {
+ writeCount++;
+ persistedJson = jsonData;
+ },
+ );
+
+ await controller.updatePlugins([plugin('one'), plugin('two')]);
+
+ expect(writeCount, 1);
+ expect(controller.pluginList.map((item) => item.name), ['one', 'two']);
+ expect(
+ (jsonDecode(persistedJson) as List)
+ .map((item) => (item as Map<String, dynamic>)['name']),
+ ['one', 'two'],
+ );
+ });
+
+ test('batch update replaces an installed rule case-insensitively',
+ () async {
+ var writeCount = 0;
+ final controller = PluginsController(
+ pluginJsonWriter: (_) async => writeCount++,
+ );
+ controller.pluginList.add(plugin('same')..version = '1.0');
+
+ await controller.updatePlugins([plugin('SAME')..version = '2.0']);
+
+ expect(writeCount, 1);
+ expect(controller.pluginList, hasLength(1));
+ expect(controller.pluginList.single.name, 'SAME');
+ expect(controller.pluginList.single.version, '2.0');
+ });
+
+ test('batch update rolls back all rules when persistence fails', () async {
+ final controller = PluginsController(
+ pluginJsonWriter: (_) async => throw StateError('write failed'),
+ errorReporter: (_, __, ___) {},
+ );
+ controller.pluginList.add(plugin('installed'));
+
+ await expectLater(
+ controller.updatePlugins([plugin('one'), plugin('two')]),
+ throwsStateError,
+ );
+
+ expect(controller.pluginList.map((item) => item.name), ['installed']);
+ });
+ });
+}