Skip to content

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

feat(plugin): support custom rule repositories (#2487)

misaka85c5106ffba9
diff --git a/lib/pages/plugin_editor/plugin_catalog_view.dart b/lib/pages/plugin_editor/plugin_catalog_view.dart
index 4df73c5a..927908ea 100644
--- a/lib/pages/plugin_editor/plugin_catalog_view.dart
+++ b/lib/pages/plugin_editor/plugin_catalog_view.dart
@@ -243,18 +243,23 @@ class _PluginCatalogViewState extends State<PluginCatalogView> {
child: Center(child: LoadingIndicator()));
}
if (_loadFailed && _controller.pluginHTTPList.isEmpty) {
+ // Mirrors only apply to the official repository.
+ final customRepository = _controller.ruleRepository.isNotEmpty;
return GeneralErrorWidget(
title: '无法访问规则仓库',
- errMsg: '请检查网络连接,或调整加速设置后重试。\n规则仓库加速:${RulesMirror.current.label}',
+ errMsg: customRepository
+ ? '请检查自定义仓库地址和网络连接后重试。'
+ : '请检查网络连接,或调整加速设置后重试。\n规则仓库加速:${RulesMirror.current.label}',
icon: Icons.cloud_off_rounded,
onRetry: _refresh,
retryText: '重新加载',
actions: [
- StateActionButton.tonal(
- onPressed: _selectMirrorAndRefresh,
- icon: Icons.tune_rounded,
- text: '切换加速',
- ),
+ if (!customRepository)
+ StateActionButton.tonal(
+ onPressed: _selectMirrorAndRefresh,
+ icon: Icons.tune_rounded,
+ text: '切换加速',
+ ),
],
);
}
diff --git a/lib/pages/plugin_editor/plugin_shop_page.dart b/lib/pages/plugin_editor/plugin_shop_page.dart
index a09c0901..da73d650 100644
--- a/lib/pages/plugin_editor/plugin_shop_page.dart
+++ b/lib/pages/plugin_editor/plugin_shop_page.dart
@@ -1,22 +1,44 @@
import 'package:flutter/material.dart';
import 'package:kazumi/bean/settings/settings_detail_scaffold.dart';
import 'package:kazumi/pages/plugin_editor/plugin_catalog_view.dart';
+import 'package:kazumi/pages/plugin_editor/rule_dialogs.dart';
import 'package:kazumi/plugins/plugins_controller.dart';
-class PluginShopPage extends StatelessWidget {
+class PluginShopPage extends StatefulWidget {
const PluginShopPage({super.key, required this.controller});
final PluginsController controller;
+ @override
+ State<PluginShopPage> createState() => _PluginShopPageState();
+}
+
+class _PluginShopPageState extends State<PluginShopPage> {
+ Future<void> _editRepository() async {
+ await showRuleRepositoryDialog(context, widget.controller);
+ // A changed repository remounts the catalog through its key.
+ if (mounted) setState(() {});
+ }
+
@override
Widget build(BuildContext context) => SettingsDetailScaffold(
title: const Text('规则仓库'),
+ actions: [
+ IconButton(
+ onPressed: _editRepository,
+ tooltip: '规则仓库地址',
+ icon: const Icon(Icons.link_rounded),
+ ),
+ ],
body: SafeArea(
top: false,
child: Align(
alignment: Alignment.topCenter,
child: ConstrainedBox(
constraints: const BoxConstraints(maxWidth: 1000),
- child: PluginCatalogView(controller: controller),
+ child: PluginCatalogView(
+ key: ValueKey(widget.controller.ruleRepository),
+ controller: widget.controller,
+ ),
),
),
),
diff --git a/lib/pages/plugin_editor/rule_dialogs.dart b/lib/pages/plugin_editor/rule_dialogs.dart
index 9d42c566..0aa7f942 100644
--- a/lib/pages/plugin_editor/rule_dialogs.dart
+++ b/lib/pages/plugin_editor/rule_dialogs.dart
@@ -7,6 +7,7 @@ import 'package:kazumi/bean/widget/loading_indicator.dart';
import 'package:kazumi/pages/plugin_editor/rule_management_widgets.dart';
import 'package:kazumi/plugins/plugins.dart';
import 'package:kazumi/plugins/plugins_controller.dart';
+import 'package:kazumi/request/config/api_endpoints.dart';
import 'package:kazumi/services/plugin/plugin_import_parser.dart';
import 'package:kazumi/utils/encoding.dart';
@@ -280,6 +281,90 @@ class _RuleImportDialogState extends State<_RuleImportDialog> {
);
}
+Future<void> showRuleRepositoryDialog(
+ BuildContext context, PluginsController controller) =>
+ KazumiDialog.show<void>(
+ context: context,
+ builder: (context) => _RuleRepositoryDialog(controller: controller),
+ );
+
+class _RuleRepositoryDialog extends StatefulWidget {
+ const _RuleRepositoryDialog({required this.controller});
+ final PluginsController controller;
+
+ @override
+ State<_RuleRepositoryDialog> createState() => _RuleRepositoryDialogState();
+}
+
+class _RuleRepositoryDialogState extends State<_RuleRepositoryDialog> {
+ late final _text =
+ TextEditingController(text: widget.controller.ruleRepository);
+ String? _error;
+
+ @override
+ void dispose() {
+ _text.dispose();
+ super.dispose();
+ }
+
+ Future<void> _save() async {
+ late final bool changed;
+ try {
+ changed = await widget.controller.setRuleRepository(_text.text);
+ } on FormatException catch (error) {
+ if (mounted) setState(() => _error = error.message);
+ return;
+ } catch (_) {
+ if (mounted) setState(() => _error = '保存失败,请重试。');
+ return;
+ }
+ if (!mounted) return;
+ KazumiDialog.dismiss(context: context);
+ if (changed) {
+ KazumiDialog.showToast(
+ message: widget.controller.ruleRepository.isEmpty
+ ? '已恢复官方规则仓库'
+ : '已切换规则仓库');
+ }
+ }
+
+ @override
+ Widget build(BuildContext context) => _RuleDialog(
+ title: '规则仓库地址',
+ icon: Icons.link_rounded,
+ content: Column(
+ mainAxisSize: MainAxisSize.min,
+ crossAxisAlignment: CrossAxisAlignment.stretch,
+ children: [
+ const Text('仅添加信任的仓库,第三方规则可以访问任意网站并执行脚本。'),
+ const SizedBox(height: 20),
+ TextField(
+ controller: _text,
+ autofocus: true,
+ keyboardType: TextInputType.url,
+ onChanged: (_) {
+ if (_error != null) setState(() => _error = null);
+ },
+ onSubmitted: (_) => _save(),
+ decoration: ruleInputDecoration(context,
+ label: '仓库地址', hint: ApiEndpoints.pluginShop)
+ .copyWith(
+ helperText: '填写 index.json 所在目录,留空使用官方仓库',
+ errorText: _error,
+ errorMaxLines: 2),
+ ),
+ ],
+ ),
+ actions: [
+ TextButton(
+ onPressed: () => Navigator.of(context).pop(),
+ child: const Text('取消'),
+ ),
+ FilledButton(onPressed: _save, child: const Text('保存')),
+ ],
+ );
+}
+
class _RuleDialog extends StatelessWidget {
const _RuleDialog({
required this.title,
diff --git a/lib/plugins/plugins_controller.dart b/lib/plugins/plugins_controller.dart
index f34b962c..f10d47de 100644
--- a/lib/plugins/plugins_controller.dart
+++ b/lib/plugins/plugins_controller.dart
@@ -5,8 +5,10 @@ import 'package:path_provider/path_provider.dart';
import 'package:kazumi/plugins/plugins.dart';
import 'package:kazumi/services/plugin/plugin_validity_tracker.dart';
import 'package:kazumi/request/apis/plugin_catalog_api.dart';
+import 'package:kazumi/request/config/rules_repository_config.dart';
import 'package:kazumi/modules/plugin/plugin_http_module.dart';
import 'package:kazumi/services/logging/logger.dart';
+import 'package:kazumi/services/storage/storage.dart';
import 'package:kazumi/utils/async_serial_queue.dart';
import 'package:kazumi/utils/async_single_flight.dart';
import 'package:kazumi/utils/version.dart';
@@ -39,8 +41,10 @@ class PluginBatchUpdateResult {
bool get hasNoCandidates => candidates == 0;
}
-typedef PluginCatalogLoader = Future<List<PluginHTTPItem>> Function();
-typedef PluginLoader = Future<Plugin> Function(String name);
+typedef PluginCatalogLoader = Future<List<PluginHTTPItem>> Function(
+ String repository,
+);
+typedef PluginLoader = Future<Plugin> Function(String repository, String name);
typedef PluginJsonWriter = Future<void> Function(String jsonData);
typedef PluginErrorReporter = void Function(
String message,
@@ -72,7 +76,7 @@ abstract class _PluginsController with Store {
final PluginLoader _pluginLoader;
final PluginJsonWriter? _pluginJsonWriter;
final PluginErrorReporter _errorReporter;
- final AsyncSingleFlight<List<PluginHTTPItem>> _catalogRefreshSingleFlight =
+ AsyncSingleFlight<List<PluginHTTPItem>> _catalogRefreshSingleFlight =
AsyncSingleFlight<List<PluginHTTPItem>>();
final AsyncSerialQueue _mutations = AsyncSerialQueue();
Map<String, PluginHTTPItem> _pluginCatalogByName = const {};
@@ -145,6 +149,25 @@ abstract class _PluginsController with Store {
DateTime.now().difference(refreshedAt) < _pluginCatalogMaxAge;
}
+ /// Empty means the official repository.
+ String get ruleRepository =>
+ GStorage.getSetting(SettingsKeys.ruleRepositoryUrl);
+
+ /// Returns whether the repository changed. Throws [FormatException].
+ Future<bool> setRuleRepository(String input) async {
+ final repository = RulesRepositoryConfig.normalizeForStorage(input);
+ if (repository == ruleRepository) {
+ return false;
+ }
+ await GStorage.putSetting(SettingsKeys.ruleRepositoryUrl, repository);
+ // Later refreshes must not join a request for the previous repository.
+ _catalogRefreshSingleFlight = AsyncSingleFlight();
+ _pluginCatalogByName = const {};
+ _pluginCatalogRefreshedAt = null;
+ pluginHTTPList.clear();
+ return true;
+ }
+
void _replacePlugin(Plugin plugin) {
bool flag = false;
for (int i = 0; i < pluginList.length; ++i) {
@@ -249,15 +272,19 @@ abstract class _PluginsController with Store {
Future<List<PluginHTTPItem>> refreshPluginCatalog() {
return _catalogRefreshSingleFlight.run(() async {
+ final repository = ruleRepository;
try {
- final catalog = await _catalogLoader();
- _pluginCatalogByName = {
- for (final item in catalog) pluginNameKey(item.name): item,
- };
- pluginHTTPList
- ..clear()
- ..addAll(catalog);
- _pluginCatalogRefreshedAt = DateTime.now();
+ final catalog = await _catalogLoader(repository);
+ // The repository may have been switched while loading.
+ if (repository == ruleRepository) {
+ _pluginCatalogByName = {
+ for (final item in catalog) pluginNameKey(item.name): item,
+ };
+ pluginHTTPList
+ ..clear()
+ ..addAll(catalog);
+ _pluginCatalogRefreshedAt = DateTime.now();
+ }
return List<PluginHTTPItem>.unmodifiable(catalog);
} catch (error, stackTrace) {
_errorReporter(
@@ -332,10 +359,11 @@ abstract class _PluginsController with Store {
}
Future<PluginUpdateResult> tryUpdatePluginByName(String name) {
+ // Captured before queueing so a later switch can't redirect this request.
+ final repository = ruleRepository;
+ final catalogName = _pluginCatalogByName[pluginNameKey(name)]?.name ?? name;
return _mutations.run(() async {
- final catalogName =
- _pluginCatalogByName[pluginNameKey(name)]?.name ?? name;
- final attempt = await _preparePluginUpdate(catalogName);
+ final attempt = await _preparePluginUpdate(repository, catalogName);
if (attempt.result == PluginUpdateResult.updated) {
await _mutateAndPersistNow(
() => _replacePlugin(attempt.plugin!),
@@ -347,10 +375,13 @@ abstract class _PluginsController with Store {
});
}
- Future<_PluginUpdateAttempt> _preparePluginUpdate(String name) async {
+ Future<_PluginUpdateAttempt> _preparePluginUpdate(
+ String repository,
+ String name,
+ ) async {
late final Plugin remotePlugin;
try {
- remotePlugin = await _pluginLoader(name);
+ remotePlugin = await _pluginLoader(repository, name);
} catch (error, stackTrace) {
_errorReporter(
'Plugin: failed to download rule $name',
@@ -420,8 +451,9 @@ abstract class _PluginsController with Store {
throw StateError('Plugin catalog has not been loaded');
}
+ final repository = ruleRepository;
final candidates = _updatablePluginNames();
- final attempts = await _preparePluginUpdates(candidates);
+ final attempts = await _preparePluginUpdates(repository, candidates);
var updated = 0;
var requiresNewerClient = 0;
var failed = 0;
@@ -462,6 +494,7 @@ abstract class _PluginsController with Store {
}
Future<List<_PluginUpdateAttempt>> _preparePluginUpdates(
+ String repository,
List<String> names,
) async {
if (names.isEmpty) {
@@ -473,7 +506,7 @@ abstract class _PluginsController with Store {
Future<void> worker() async {
while (nextIndex < names.length) {
final index = nextIndex++;
- results[index] = await _preparePluginUpdate(names[index]);
+ results[index] = await _preparePluginUpdate(repository, names[index]);
}
}
diff --git a/lib/request/apis/plugin_catalog_api.dart b/lib/request/apis/plugin_catalog_api.dart
index 3980c58f..1b58d3b3 100644
--- a/lib/request/apis/plugin_catalog_api.dart
+++ b/lib/request/apis/plugin_catalog_api.dart
@@ -1,6 +1,6 @@
import 'dart:convert';
import 'package:kazumi/services/logging/logger.dart';
-import 'package:kazumi/request/config/api_endpoints.dart';
+import 'package:kazumi/request/config/rules_repository_config.dart';
import 'package:kazumi/request/clients/rules_repo_client.dart';
import 'package:kazumi/plugins/plugins.dart';
import 'package:kazumi/modules/plugin/plugin_http_module.dart';
@@ -8,8 +8,9 @@ import 'package:kazumi/modules/plugin/plugin_http_module.dart';
class PluginCatalogApi {
static final RulesRepoClient _client = RulesRepoClient.instance;
- static Future<List<PluginHTTPItem>> getPluginList() async {
- final raw = await _client.getText('${ApiEndpoints.pluginShop}index.json');
+ static Future<List<PluginHTTPItem>> getPluginList(String repository) async {
+ final raw = await _client
+ .getText(RulesRepositoryConfig.catalogUri(repository).toString());
final result = parsePluginList(raw);
if (result.skippedItems > 0) {
KazumiLogger().w(
@@ -53,8 +54,9 @@ class PluginCatalogApi {
}
}
- static Future<Plugin> getPlugin(String name) async {
- final raw = await _client.getText('${ApiEndpoints.pluginShop}$name.json');
+ static Future<Plugin> getPlugin(String repository, String name) async {
+ final raw = await _client
+ .getText(RulesRepositoryConfig.ruleUri(repository, name).toString());
final jsonData = json.decode(raw);
if (jsonData is! Map) {
throw FormatException('Rule $name must be a JSON object');
diff --git a/lib/request/config/rules_repository_config.dart b/lib/request/config/rules_repository_config.dart
new file mode 100644
index 00000000..06867c93
--- /dev/null
+++ b/lib/request/config/rules_repository_config.dart
@@ -0,0 +1,66 @@
+import 'package:kazumi/request/config/api_endpoints.dart';
+
+class RulesRepositoryConfig {
+ const RulesRepositoryConfig._();
+
+ static String normalizeForStorage(String input) {
+ if (input.trim().isEmpty) {
+ return '';
+ }
+ final normalized = _baseUri(input).toString();
+ return normalized == ApiEndpoints.pluginShop ? '' : normalized;
+ }
+
+ static Uri catalogUri(String repository) {
+ return _baseUri(repository).resolve('index.json');
+ }
+
+ static Uri ruleUri(String repository, String ruleName) {
+ return _baseUri(
+ repository,
+ ).resolveUri(Uri(pathSegments: ['$ruleName.json']));
+ }
+
+ static Uri _baseUri(String repository) {
+ final value = repository.trim();
+ if (value.isEmpty) {
+ return Uri.parse(ApiEndpoints.pluginShop);
+ }
+
+ final uri = Uri.tryParse(value);
+ if (uri == null ||
+ (uri.scheme != 'http' && uri.scheme != 'https') ||
+ !uri.hasAuthority ||
+ uri.host.isEmpty) {
+ throw const FormatException('规则仓库地址必须是有效的 HTTP 或 HTTPS URL');
+ }
+ if (uri.userInfo.isNotEmpty) {
+ throw const FormatException('规则仓库地址不能包含用户名或密码');
+ }
+ if (uri.hasQuery || uri.hasFragment) {
+ throw const FormatException('规则仓库地址不能包含查询参数或片段');
+ }
+ if (uri.host == 'github.com') {
+ throw const FormatException('请使用 raw 文件地址,不要使用 GitHub 仓库网页地址');
+ }
+
+ // Keep inner empty segments, e.g. in proxy prefixes like `/https://...`.
+ final segments = [...uri.pathSegments];
+ while (segments.isNotEmpty && segments.last.isEmpty) {
+ segments.removeLast();
+ }
+ final last = segments.isEmpty ? null : segments.last;
+ if (last?.toLowerCase() == 'index.json') {
+ segments.removeLast();
+ } else if (last != null && last.contains('.') && !uri.path.endsWith('/')) {
+ throw const FormatException('规则仓库地址必须是目录或以 index.json 结尾');
+ }
+
+ return Uri(
+ scheme: uri.scheme,
+ host: uri.host,
+ port: uri.hasPort ? uri.port : null,
+ pathSegments: [...segments, ''],
+ );
+ }
+}
diff --git a/lib/services/storage/settings_keys.dart b/lib/services/storage/settings_keys.dart
index b32aedb9..2c71bb6c 100644
--- a/lib/services/storage/settings_keys.dart
+++ b/lib/services/storage/settings_keys.dart
@@ -266,6 +266,11 @@ class SettingsKeys {
true,
group: SettingGroup.proxy,
);
+ static const ruleRepositoryUrl = SettingKey<String>(
+ 'ruleRepositoryUrl',
+ '',
+ group: SettingGroup.proxy,
+ );
static const enableBangumiProxy = SettingKey<bool>(
_SettingBoxKey.enableBangumiProxy,
true,
@@ -621,6 +626,7 @@ class SettingsKeys {
oledEnhance,
displayMode,
enableGitProxy,
+ ruleRepositoryUrl,
enableBangumiProxy,
imageAcceleration,
bangumiAcceleration,
diff --git a/test/rules_repository_config_test.dart b/test/rules_repository_config_test.dart
new file mode 100644
index 00000000..d6c2c355
--- /dev/null
+++ b/test/rules_repository_config_test.dart
@@ -0,0 +1,144 @@
+import 'package:flutter_test/flutter_test.dart';
+import 'package:kazumi/request/config/api_endpoints.dart';
+import 'package:kazumi/request/config/rules_repository_config.dart';
+
+void main() {
+ group('RulesRepositoryConfig', () {
+ test('uses the official repository when the setting is blank', () {
+ expect(
+ RulesRepositoryConfig.catalogUri(' ').toString(),
+ '${ApiEndpoints.pluginShop}index.json',
+ );
+ });
+
+ test('normalizes a repository directory URL', () {
+ expect(
+ RulesRepositoryConfig.normalizeForStorage('https://example.com/rules'),
+ 'https://example.com/rules/',
+ );
+ });
+
+ test('accepts a case-insensitive direct index URL', () {
+ expect(
+ RulesRepositoryConfig.normalizeForStorage(
+ 'https://example.com/rules/INDEX.JSON',
+ ),
+ 'https://example.com/rules/',
+ );
+ });
+
+ test('normalizes trailing and encoded index URL variants', () {
+ expect(
+ RulesRepositoryConfig.normalizeForStorage(
+ 'https://example.com/rules/index.json/',
+ ),
+ 'https://example.com/rules/',
+ );
+ expect(
+ RulesRepositoryConfig.normalizeForStorage(
+ 'https://example.com/rules/%69ndex.json',
+ ),
+ 'https://example.com/rules/',
+ );
+ });
+
+ test(
+ 'accepts explicit directory URLs whose last segment contains dots',
+ () {
+ expect(
+ RulesRepositoryConfig.normalizeForStorage(
+ 'https://example.com/rules/v1.2/',
+ ),
+ 'https://example.com/rules/v1.2/',
+ );
+ expect(
+ RulesRepositoryConfig.normalizeForStorage(
+ 'https://example.com/rules.d/',
+ ),
+ 'https://example.com/rules.d/',
+ );
+ },
+ );
+
+ test('normalizes official repository URLs back to the default setting', () {
+ expect(
+ RulesRepositoryConfig.normalizeForStorage(ApiEndpoints.pluginShop),
+ isEmpty,
+ );
+ expect(
+ RulesRepositoryConfig.normalizeForStorage(
+ '${ApiEndpoints.pluginShop}index.json',
+ ),
+ isEmpty,
+ );
+ });
+
+ test('resolves catalog and rule URLs from the same repository', () {
+ const repository = 'https://example.com/rules/';
+ expect(
+ RulesRepositoryConfig.catalogUri(repository).toString(),
+ 'https://example.com/rules/index.json',
+ );
+ expect(
+ RulesRepositoryConfig.ruleUri(repository, 'demo').toString(),
+ 'https://example.com/rules/demo.json',
+ );
+ });
+
+ test('rejects non-HTTP repository URLs', () {
+ expect(
+ () => RulesRepositoryConfig.normalizeForStorage('file:///tmp/rules/'),
+ throwsFormatException,
+ );
+ expect(
+ () => RulesRepositoryConfig.normalizeForStorage('example.com/rules'),
+ throwsFormatException,
+ );
+ });
+
+ test('rejects URLs with credentials, query parameters or fragments', () {
+ expect(
+ () => RulesRepositoryConfig.normalizeForStorage(
+ 'https://user:[email protected]/rules/',
+ ),
+ throwsFormatException,
+ );
+ expect(
+ () => RulesRepositoryConfig.normalizeForStorage(
+ 'https://example.com/rules/index.json?cache=1',
+ ),
+ throwsFormatException,
+ );
+ expect(
+ () => RulesRepositoryConfig.normalizeForStorage(
+ 'https://example.com/rules/#catalog',
+ ),
+ throwsFormatException,
+ );
+ });
+
+ test('rejects GitHub HTML index pages', () {
+ expect(
+ () => RulesRepositoryConfig.normalizeForStorage(
+ 'https://github.com/example/rules/blob/main/index.json',
+ ),
+ throwsFormatException,
+ );
+ });
+
+ test('rejects file URLs and GitHub repository pages', () {
+ expect(
+ () => RulesRepositoryConfig.normalizeForStorage(
+ 'https://example.com/rules/catalog.json',
+ ),
+ throwsFormatException,
+ );
+ expect(
+ () => RulesRepositoryConfig.normalizeForStorage(
+ 'https://github.com/example/rules',
+ ),
+ throwsFormatException,
+ );
+ });
+ });
+}