Skip to content

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

feat(rules): unify XPath and API rule runtime (#2303)

Predidit82bc184e0ead
diff --git a/lib/pages/info/source_sheet.dart b/lib/pages/info/source_sheet.dart
index f5bdfcc0..dcd8090c 100644
--- a/lib/pages/info/source_sheet.dart
+++ b/lib/pages/info/source_sheet.dart
@@ -373,8 +373,8 @@ class _SourceSheetState extends State<SourceSheet>
TextButton(
style: TextButton.styleFrom(
minimumSize: Size.zero,
- padding:
- const EdgeInsets.symmetric(horizontal: 8, vertical: 10),
+ padding: const EdgeInsets.symmetric(
+ horizontal: 8, vertical: 10),
tapTargetSize: MaterialTapTargetSize.shrinkWrap,
visualDensity: VisualDensity.compact,
textStyle: Theme.of(context).textTheme.bodySmall,
@@ -385,8 +385,8 @@ class _SourceSheetState extends State<SourceSheet>
TextButton(
style: TextButton.styleFrom(
minimumSize: Size.zero,
- padding:
- const EdgeInsets.symmetric(horizontal: 8, vertical: 10),
+ padding: const EdgeInsets.symmetric(
+ horizontal: 8, vertical: 10),
tapTargetSize: MaterialTapTargetSize.shrinkWrap,
visualDensity: VisualDensity.compact,
textStyle: Theme.of(context).textTheme.bodySmall,
@@ -535,11 +535,16 @@ class _SourceSheetState extends State<SourceSheet>
IconButton(
onPressed: () {
int currentIndex = widget.tabController.index;
+ final currentPlugin =
+ pluginsController.pluginList[currentIndex];
+ final targetUrl = currentPlugin.usesApiSearch
+ ? currentPlugin.baseUrl
+ : currentPlugin.searchURL.replaceFirst(
+ '@keyword',
+ Uri.encodeQueryComponent(keyword),
+ );
launchUrl(
- Uri.parse(pluginsController
- .pluginList[currentIndex].searchURL
- .replaceFirst(
- '@keyword', Uri.encodeQueryComponent(keyword))),
+ Uri.parse(targetUrl),
mode: LaunchMode.externalApplication,
);
},
diff --git a/lib/pages/plugin_editor/plugin_editor_page.dart b/lib/pages/plugin_editor/plugin_editor_page.dart
index 90b4655e..ccfff0ce 100644
--- a/lib/pages/plugin_editor/plugin_editor_page.dart
+++ b/lib/pages/plugin_editor/plugin_editor_page.dart
@@ -1,11 +1,82 @@
+import 'dart:convert';
+
import 'package:card_settings_ui/card_settings_ui.dart';
import 'package:card_settings_ui/tile/settings_tile_info.dart';
import 'package:flutter/material.dart';
import 'package:flutter_modular/flutter_modular.dart';
import 'package:kazumi/plugins/plugins.dart';
+import 'package:kazumi/plugins/api_rule_config.dart';
import 'package:kazumi/plugins/anti_crawler_config.dart';
import 'package:kazumi/plugins/plugins_controller.dart';
import 'package:kazumi/bean/appbar/sys_app_bar.dart';
+import 'package:kazumi/request/config/api_endpoints.dart';
+import 'package:kazumi/services/plugin/api_rule_engine.dart';
+
+abstract final class _RuleEditorText {
+ static const ruleName = '规则名称';
+ static const ruleVersion = '规则版本';
+ static const baseUrl = '基础地址(URL)';
+ static const searchRuleType = '搜索规则类型';
+ static const chapterRuleType = '选集规则类型';
+
+ static const searchUrl = '搜索地址(URL)';
+ static const searchListXPath = '搜索结果列表(XPath)';
+ static const itemNameXPath = '条目名称(XPath)';
+ static const itemLinkXPath = '条目链接(XPath)';
+ static const roadListXPath = '播放线路列表(XPath)';
+ static const episodeListXPath = '剧集列表(XPath)';
+
+ static const searchMethod = '搜索请求方法';
+ static const searchRequestUrl = '搜索请求地址(URL)';
+ static const searchHeaders = '搜索请求头(JSON)';
+ static const searchQuery = '搜索查询参数(JSON)';
+ static const searchBodyType = '搜索请求体类型';
+ static const searchBody = '搜索请求体(JSON)';
+ static const searchListPath = '搜索结果列表路径(JSONPath)';
+ static const itemNamePath = '条目名称路径(JSONPath,相对条目)';
+ static const itemSourcePath = '条目来源路径(JSONPath,相对条目)';
+
+ static const chapterMethod = '选集请求方法';
+ static const chapterRequestUrl = '选集请求地址(URL)';
+ static const chapterHeaders = '选集请求头(JSON)';
+ static const chapterQuery = '选集查询参数(JSON)';
+ static const chapterBodyType = '选集请求体类型';
+ static const chapterBody = '选集请求体(JSON)';
+ static const chapterResponseFormat = '选集响应格式';
+ static const roadListPath = '播放线路列表路径(JSONPath,留空表示单线路)';
+ static const roadNamePath = '线路名称路径(JSONPath,相对线路)';
+ static const episodeListPath = '剧集列表路径(JSONPath,相对线路)';
+ static const episodeNamePath = '剧集名称路径(JSONPath,相对剧集)';
+ static const playbackEntryPath = '播放入口地址路径(JSONPath,使用播放页地址模板时可留空)';
+ static const playbackEntryPathHelper = '从剧集对象读取交给 WebView 的地址,可以是播放页面或媒体直链。';
+ static const roadNamesPath = '线路名称串路径(JSONPath)';
+ static const roadEpisodesPath = '线路剧集串路径(JSONPath)';
+ static const roadSeparator = '线路分隔符';
+ static const episodeSeparator = '剧集分隔符';
+ static const fieldSeparator = '名称与地址分隔符';
+ static const responseVariables = '响应变量(JSON:变量名 → JSONPath)';
+ static const playPageUrl = '播放页地址模板(URL,可选)';
+ static const playPageQuery = '播放页查询参数(JSON)';
+
+ static const userAgent = '用户代理(User-Agent)';
+ static const userAgentHelper = '仅用于播放器和下载器。';
+ static const referer = '播放请求来源(Referer)';
+ static const refererHelper = '仅用于播放器和下载器。';
+
+ static const captchaDetectValue = '验证页检测值';
+ static const captchaDetectValueHelper = '留空时使用验证码图片或验证按钮的 XPath 进行检测。';
+ static const captchaImage = '验证码图片(XPath)';
+ static const captchaImageHelper = '填写验证码图片元素的 XPath。';
+ static const captchaInput = '验证码输入框(XPath)';
+ static const captchaInputHelper = '填写验证码输入框元素的 XPath。';
+ static const captchaSubmitButton = '验证提交按钮(XPath)';
+ static const captchaSubmitButtonHelper = '填写提交验证码按钮元素的 XPath。';
+ static const verifyButton = '验证按钮(XPath)';
+ static const verifyButtonHelper = '填写验证按钮元素的 XPath,检测到后将自动点击。';
+ static const captchaScript = '验证脚本(JavaScript)';
+ static const captchaScriptHelper =
+ '可调用 KazumiCaptcha.log、clicked、done 和 fail。';
+}
class PluginEditorPage extends StatefulWidget {
const PluginEditorPage({
@@ -31,9 +102,62 @@ class _PluginEditorPageState extends State<PluginEditorPage> {
final TextEditingController chapterRoadsController = TextEditingController();
final TextEditingController chapterResultController = TextEditingController();
final TextEditingController refererController = TextEditingController();
- bool muliSources = true;
- bool useWebview = true;
- bool useNativePlayer = true;
+ final TextEditingController searchApiURLController = TextEditingController();
+ final TextEditingController searchApiHeadersController =
+ TextEditingController();
+ final TextEditingController searchApiQueryController =
+ TextEditingController();
+ final TextEditingController searchApiBodyController = TextEditingController();
+ final TextEditingController searchApiListPathController =
+ TextEditingController();
+ final TextEditingController searchApiNamePathController =
+ TextEditingController();
+ final TextEditingController searchApiSourcePathController =
+ TextEditingController();
+ final TextEditingController chapterApiURLController = TextEditingController();
+ final TextEditingController chapterApiHeadersController =
+ TextEditingController();
+ final TextEditingController chapterApiQueryController =
+ TextEditingController();
+ final TextEditingController chapterApiBodyController =
+ TextEditingController();
+ final TextEditingController chapterApiRoadsPathController =
+ TextEditingController();
+ final TextEditingController chapterApiRoadNamePathController =
+ TextEditingController();
+ final TextEditingController chapterApiEpisodesPathController =
+ TextEditingController();
+ final TextEditingController chapterApiEpisodeNamePathController =
+ TextEditingController();
+ final TextEditingController chapterApiEpisodeURLPathController =
+ TextEditingController();
+ final TextEditingController chapterApiRoadNamesPathController =
+ TextEditingController();
+ final TextEditingController chapterApiRoadEpisodesPathController =
+ TextEditingController();
+ final TextEditingController chapterApiRoadSeparatorController =
+ TextEditingController();
+ final TextEditingController chapterApiEpisodeSeparatorController =
+ TextEditingController();
+ final TextEditingController chapterApiFieldSeparatorController =
+ TextEditingController();
+ final TextEditingController chapterApiVariablesController =
+ TextEditingController();
+ final TextEditingController chapterApiPageURLController =
+ TextEditingController();
+ final TextEditingController chapterApiPageQueryController =
+ TextEditingController();
+ String searchMode = RuleMode.xpath;
+ String chapterMode = RuleMode.xpath;
+ String searchApiMethod = 'GET';
+ String searchApiBodyType = ApiBodyType.none;
+ String chapterApiMethod = 'GET';
+ String chapterApiBodyType = ApiBodyType.none;
+ String chapterApiFormat = ApiChapterFormat.nested;
+ // Legacy schema values retained on save but no longer exposed as settings.
+ late bool _muliSources;
+ late bool _useWebview;
+ late bool _useNativePlayer;
bool usePost = false;
bool useLegacyParser = false;
bool adBlocker = false;
@@ -54,7 +178,7 @@ class _PluginEditorPageState extends State<PluginEditorPage> {
static const Map<int, String> _captchaTypeMap = {
CaptchaType.imageCaptcha: '图片验证码',
CaptchaType.autoClickButton: '自动点击按钮',
- CaptchaType.customJavaScript: '自定义 JS 验证',
+ CaptchaType.customJavaScript: '自定义 JavaScript 验证',
};
static const Map<int, String> _captchaDetectTypeMap = {
@@ -80,9 +204,58 @@ class _PluginEditorPageState extends State<PluginEditorPage> {
chapterRoadsController.text = plugin.chapterRoads;
chapterResultController.text = plugin.chapterResult;
refererController.text = plugin.referer;
- muliSources = plugin.muliSources;
- useWebview = plugin.useWebview;
- useNativePlayer = plugin.useNativePlayer;
+ searchMode = plugin.searchMode;
+ chapterMode = plugin.chapterMode;
+ searchApiMethod = plugin.searchApiConfig.request.method;
+ searchApiBodyType = plugin.searchApiConfig.request.bodyType;
+ searchApiURLController.text = plugin.searchApiConfig.request.url;
+ searchApiHeadersController.text =
+ _prettyJson(plugin.searchApiConfig.request.headers);
+ searchApiQueryController.text =
+ _prettyJson(plugin.searchApiConfig.request.query);
+ searchApiBodyController.text =
+ _prettyJson(plugin.searchApiConfig.request.body);
+ searchApiListPathController.text = plugin.searchApiConfig.listPath;
+ searchApiNamePathController.text = plugin.searchApiConfig.namePath;
+ searchApiSourcePathController.text = plugin.searchApiConfig.sourcePath;
+ chapterApiMethod = plugin.chapterApiConfig.request.method;
+ chapterApiBodyType = plugin.chapterApiConfig.request.bodyType;
+ chapterApiFormat = plugin.chapterApiConfig.format;
+ chapterApiURLController.text = plugin.chapterApiConfig.request.url;
+ chapterApiHeadersController.text =
+ _prettyJson(plugin.chapterApiConfig.request.headers);
+ chapterApiQueryController.text =
+ _prettyJson(plugin.chapterApiConfig.request.query);
+ chapterApiBodyController.text =
+ _prettyJson(plugin.chapterApiConfig.request.body);
+ chapterApiRoadsPathController.text = plugin.chapterApiConfig.roadsPath;
+ chapterApiRoadNamePathController.text =
+ plugin.chapterApiConfig.roadNamePath;
+ chapterApiEpisodesPathController.text =
+ plugin.chapterApiConfig.episodesPath;
+ chapterApiEpisodeNamePathController.text =
+ plugin.chapterApiConfig.episodeNamePath;
+ chapterApiEpisodeURLPathController.text =
+ plugin.chapterApiConfig.episodeUrlPath;
+ chapterApiRoadNamesPathController.text =
+ plugin.chapterApiConfig.roadNamesPath;
+ chapterApiRoadEpisodesPathController.text =
+ plugin.chapterApiConfig.roadEpisodesPath;
+ chapterApiRoadSeparatorController.text =
+ plugin.chapterApiConfig.roadSeparator;
+ chapterApiEpisodeSeparatorController.text =
+ plugin.chapterApiConfig.episodeSeparator;
+ chapterApiFieldSeparatorController.text =
+ plugin.chapterApiConfig.fieldSeparator;
+ chapterApiVariablesController.text =
+ _prettyJson(plugin.chapterApiConfig.variables);
+ chapterApiPageURLController.text =
+ plugin.chapterApiConfig.episodePage?.url ?? '';
+ chapterApiPageQueryController.text =
+ _prettyJson(plugin.chapterApiConfig.episodePage?.query);
+ _muliSources = plugin.muliSources;
+ _useWebview = plugin.useWebview;
+ _useNativePlayer = plugin.useNativePlayer;
usePost = plugin.usePost;
useLegacyParser = plugin.useLegacyParser;
adBlocker = plugin.adBlocker;
@@ -112,6 +285,30 @@ class _PluginEditorPageState extends State<PluginEditorPage> {
chapterRoadsController.dispose();
chapterResultController.dispose();
refererController.dispose();
+ searchApiURLController.dispose();
+ searchApiHeadersController.dispose();
+ searchApiQueryController.dispose();
+ searchApiBodyController.dispose();
+ searchApiListPathController.dispose();
+ searchApiNamePathController.dispose();
+ searchApiSourcePathController.dispose();
+ chapterApiURLController.dispose();
+ chapterApiHeadersController.dispose();
+ chapterApiQueryController.dispose();
+ chapterApiBodyController.dispose();
+ chapterApiRoadsPathController.dispose();
+ chapterApiRoadNamePathController.dispose();
+ chapterApiEpisodesPathController.dispose();
+ chapterApiEpisodeNamePathController.dispose();
+ chapterApiEpisodeURLPathController.dispose();
+ chapterApiRoadNamesPathController.dispose();
+ chapterApiRoadEpisodesPathController.dispose();
+ chapterApiRoadSeparatorController.dispose();
+ chapterApiEpisodeSeparatorController.dispose();
+ chapterApiFieldSeparatorController.dispose();
+ chapterApiVariablesController.dispose();
+ chapterApiPageURLController.dispose();
+ chapterApiPageQueryController.dispose();
captchaImageController.dispose();
captchaInputController.dispose();
captchaButtonController.dispose();
@@ -120,9 +317,14 @@ class _PluginEditorPageState extends State<PluginEditorPage> {
super.dispose();
}
+ static String _prettyJson(Object? value) {
+ if (value == null) return '';
+ if (value is Map && value.isEmpty) return '{}';
+ return const JsonEncoder.withIndent(' ').convert(value);
+ }
+
@override
Widget build(BuildContext context) {
- final Plugin plugin = Modular.args.data as Plugin;
final fontFamily = Theme.of(context).textTheme.bodyMedium?.fontFamily;
return Scaffold(
@@ -139,57 +341,62 @@ class _PluginEditorPageState extends State<PluginEditorPage> {
TextField(
controller: nameController,
decoration: const InputDecoration(
- labelText: 'Name', border: OutlineInputBorder()),
+ labelText: _RuleEditorText.ruleName,
+ border: OutlineInputBorder()),
),
const SizedBox(height: 20),
TextField(
controller: versionController,
decoration: const InputDecoration(
- labelText: 'Version', border: OutlineInputBorder()),
+ labelText: _RuleEditorText.ruleVersion,
+ border: OutlineInputBorder()),
),
const SizedBox(height: 20),
TextField(
controller: baseURLController,
decoration: const InputDecoration(
- labelText: 'BaseURL', border: OutlineInputBorder()),
- ),
- const SizedBox(height: 20),
- TextField(
- controller: searchURLController,
- decoration: const InputDecoration(
- labelText: 'SearchURL', border: OutlineInputBorder()),
- ),
- const SizedBox(height: 20),
- TextField(
- controller: searchListController,
- decoration: const InputDecoration(
- labelText: 'SearchList', border: OutlineInputBorder()),
- ),
- const SizedBox(height: 20),
- TextField(
- controller: searchNameController,
- decoration: const InputDecoration(
- labelText: 'SearchName', border: OutlineInputBorder()),
- ),
- const SizedBox(height: 20),
- TextField(
- controller: searchResultController,
- decoration: const InputDecoration(
- labelText: 'SearchResult', border: OutlineInputBorder()),
+ labelText: _RuleEditorText.baseUrl,
+ border: OutlineInputBorder()),
),
const SizedBox(height: 20),
- TextField(
- controller: chapterRoadsController,
+ DropdownButtonFormField<String>(
+ initialValue: searchMode,
decoration: const InputDecoration(
- labelText: 'ChapterRoads', border: OutlineInputBorder()),
+ labelText: _RuleEditorText.searchRuleType,
+ border: OutlineInputBorder(),
+ ),
+ items: const [
+ DropdownMenuItem(
+ value: RuleMode.xpath, child: Text('XPath')),
+ DropdownMenuItem(value: RuleMode.api, child: Text('API')),
+ ],
+ onChanged: (value) =>
+ setState(() => searchMode = value ?? RuleMode.xpath),
),
const SizedBox(height: 20),
- TextField(
- controller: chapterResultController,
+ if (searchMode == RuleMode.xpath)
+ ..._buildXPathSearchFields()
+ else
+ ..._buildApiSearchFields(),
+ DropdownButtonFormField<String>(
+ initialValue: chapterMode,
decoration: const InputDecoration(
- labelText: 'ChapterResult', border: OutlineInputBorder()),
+ labelText: _RuleEditorText.chapterRuleType,
+ border: OutlineInputBorder(),
+ ),
+ items: const [
+ DropdownMenuItem(
+ value: RuleMode.xpath, child: Text('XPath')),
+ DropdownMenuItem(value: RuleMode.api, child: Text('API')),
+ ],
+ onChanged: (value) =>
+ setState(() => chapterMode = value ?? RuleMode.xpath),
),
const SizedBox(height: 20),
+ if (chapterMode == RuleMode.xpath)
+ ..._buildXPathChapterFields()
+ else
+ ..._buildApiChapterFields(),
ExpansionTile(
title: const Text('高级选项'),
shape: const RoundedRectangleBorder(
@@ -208,24 +415,6 @@ class _PluginEditorPageState extends State<PluginEditorPage> {
onToggle: (v) => setState(
() => useLegacyParser = v ?? !useLegacyParser),
),
- SettingsTile.switchTile(
- title: Text('POST',
- style: TextStyle(fontFamily: fontFamily)),
- description: Text('使用 POST 而不是 GET 进行检索',
- style: TextStyle(fontFamily: fontFamily)),
- initialValue: usePost,
- onToggle: (v) =>
- setState(() => usePost = v ?? !usePost),
- ),
- SettingsTile.switchTile(
- title: Text('内置播放器',
- style: TextStyle(fontFamily: fontFamily)),
- description: Text('使用内置播放器播放视频',
- style: TextStyle(fontFamily: fontFamily)),
- initialValue: useNativePlayer,
- onToggle: (v) => setState(
- () => useNativePlayer = v ?? !useNativePlayer),
- ),
SettingsTile.switchTile(
title: Text('广告过滤',
style: TextStyle(fontFamily: fontFamily)),
@@ -246,7 +435,8 @@ class _PluginEditorPageState extends State<PluginEditorPage> {
context,
info,
controller: userAgentController,
- label: 'UserAgent',
+ label: _RuleEditorText.userAgent,
+ helper: _RuleEditorText.userAgentHelper,
),
),
CustomSettingsTile(
@@ -254,202 +444,208 @@ class _PluginEditorPageState extends State<PluginEditorPage> {
context,
info,
controller: refererController,
- label: 'Referer',
+ label: _RuleEditorText.referer,
+ helper: _RuleEditorText.refererHelper,
),
),
],
),
- SettingsSection(
- title: Text('反反爬虫配置',
- style: TextStyle(fontFamily: fontFamily)),
- tiles: [
- SettingsTile.switchTile(
- title: Text('启用反反爬虫',
- style: TextStyle(fontFamily: fontFamily)),
- description: Text('检索失败时显示验证码验证按钮而非重试',
- style: TextStyle(fontFamily: fontFamily)),
- initialValue: antiCrawlerEnabled,
- onToggle: (v) => setState(() =>
- antiCrawlerEnabled = v ?? !antiCrawlerEnabled),
- ),
- if (antiCrawlerEnabled) ...[
- SettingsTile.navigation(
- onPressed: (_) {
- if (captchaTypeMenuController.isOpen) {
- captchaTypeMenuController.close();
- } else {
- captchaTypeMenuController.open();
- }
- },
- title: Text('验证类型',
+ if (searchMode == RuleMode.xpath)
+ SettingsSection(
+ title: Text('反反爬虫配置',
+ style: TextStyle(fontFamily: fontFamily)),
+ tiles: [
+ SettingsTile.switchTile(
+ title: Text('启用反反爬虫',
style: TextStyle(fontFamily: fontFamily)),
- description: Text(
- switch (captchaType) {
- CaptchaType.imageCaptcha =>
- '图片验证码(展示验证码图片,用户手动输入)',
- CaptchaType.autoClickButton =>
- '自动点击验证按钮(检测到按钮后自动模拟点击)',
- CaptchaType.customJavaScript =>
- '自定义 JS 验证(加载页面后执行规则脚本)',
- _ => '未知验证类型',
+ description: Text('检索失败时显示验证码验证按钮而非重试',
+ style: TextStyle(fontFamily: fontFamily)),
+ initialValue: antiCrawlerEnabled,
+ onToggle: (v) => setState(() =>
+ antiCrawlerEnabled = v ?? !antiCrawlerEnabled),
+ ),
+ if (antiCrawlerEnabled) ...[
+ SettingsTile.navigation(
+ onPressed: (_) {
+ if (captchaTypeMenuController.isOpen) {
+ captchaTypeMenuController.close();
+ } else {
+ captchaTypeMenuController.open();
+ }
},
- style: TextStyle(fontFamily: fontFamily),
- ),
- value: MenuAnchor(
- consumeOutsideTap: true,
- controller: captchaTypeMenuController,
- builder: (_, __, ___) => Text(
- _captchaTypeMap[captchaType] ?? '未知',
+ title: Text('验证类型',
+ style: TextStyle(fontFamily: fontFamily)),
+ description: Text(
+ switch (captchaType) {
+ CaptchaType.imageCaptcha =>
+ '图片验证码(展示验证码图片,用户手动输入)',
+ CaptchaType.autoClickButton =>
+ '自动点击验证按钮(检测到按钮后自动模拟点击)',
+ CaptchaType.customJavaScript =>
+ '自定义 JavaScript 验证(加载页面后执行规则脚本)',
+ _ => '未知验证类型',
+ },
style: TextStyle(fontFamily: fontFamily),
),
- menuChildren: [
- for (final entry in _captchaTypeMap.entries)
- MenuItemButton(
- requestFocusOnHover: false,
- onPressed: () =>
- setState(() => captchaType = entry.key),
- child: Container(
- height: 48,
- constraints:
- const BoxConstraints(minWidth: 160),
- child: Align(
- alignment: Alignment.centerLeft,
- child: Text(
- entry.value,
- style: TextStyle(
- color: entry.key == captchaType
- ? Theme.of(context)
- .colorScheme
- .primary
- : null,
- fontFamily: fontFamily,
+ value: MenuAnchor(
+ consumeOutsideTap: true,
+ controller: captchaTypeMenuController,
+ builder: (_, __, ___) => Text(
+ _captchaTypeMap[captchaType] ?? '未知',
+ style: TextStyle(fontFamily: fontFamily),
+ ),
+ menuChildren: [
+ for (final entry in _captchaTypeMap.entries)
+ MenuItemButton(
+ requestFocusOnHover: false,
+ onPressed: () => setState(
+ () => captchaType = entry.key),
+ child: Container(
+ height: 48,
+ constraints:
+ const BoxConstraints(minWidth: 160),
+ child: Align(
+ alignment: Alignment.centerLeft,
+ child: Text(
+ entry.value,
+ style: TextStyle(
+ color: entry.key == captchaType
+ ? Theme.of(context)
+ .colorScheme
+ .primary
+ : null,
+ fontFamily: fontFamily,
+ ),
),
),
),
),
- ),
- ],
- ),
- ),
- SettingsTile.navigation(
- onPressed: (_) {
- if (captchaDetectTypeMenuController.isOpen) {
- captchaDetectTypeMenuController.close();
- } else {
- captchaDetectTypeMenuController.open();
- }
- },
- title: Text('验证页检测方式',
- style: TextStyle(fontFamily: fontFamily)),
- description: Text('优先使用该标记判断搜索响应是否为验证页',
- style: TextStyle(fontFamily: fontFamily)),
- value: MenuAnchor(
- consumeOutsideTap: true,
- controller: captchaDetectTypeMenuController,
- builder: (_, __, ___) => Text(
- _captchaDetectTypeMap[captchaDetectType] ??
- '未知',
- style: TextStyle(fontFamily: fontFamily),
+ ],
),
- menuChildren: [
- for (final entry
- in _captchaDetectTypeMap.entries)
- MenuItemButton(
- requestFocusOnHover: false,
- onPressed: () => setState(
- () => captchaDetectType = entry.key),
- child: Container(
- height: 48,
- constraints:
- const BoxConstraints(minWidth: 160),
- child: Align(
- alignment: Alignment.centerLeft,
- child: Text(
- entry.value,
- style: TextStyle(
- color:
- entry.key == captchaDetectType
- ? Theme.of(context)
- .colorScheme
- .primary
- : null,
- fontFamily: fontFamily,
+ ),
+ SettingsTile.navigation(
+ onPressed: (_) {
+ if (captchaDetectTypeMenuController.isOpen) {
+ captchaDetectTypeMenuController.close();
+ } else {
+ captchaDetectTypeMenuController.open();
+ }
+ },
+ title: Text('验证页检测方式',
+ style: TextStyle(fontFamily: fontFamily)),
+ description: Text('优先使用该标记判断搜索响应是否为验证页',
+ style: TextStyle(fontFamily: fontFamily)),
+ value: MenuAnchor(
+ consumeOutsideTap: true,
+ controller: captchaDetectTypeMenuController,
+ builder: (_, __, ___) => Text(
+ _captchaDetectTypeMap[captchaDetectType] ??
+ '未知',
+ style: TextStyle(fontFamily: fontFamily),
+ ),
+ menuChildren: [
+ for (final entry
+ in _captchaDetectTypeMap.entries)
+ MenuItemButton(
+ requestFocusOnHover: false,
+ onPressed: () => setState(
+ () => captchaDetectType = entry.key),
+ child: Container(
+ height: 48,
+ constraints:
+ const BoxConstraints(minWidth: 160),
+ child: Align(
+ alignment: Alignment.centerLeft,
+ child: Text(
+ entry.value,
+ style: TextStyle(
+ color:
+ entry.key == captchaDetectType
+ ? Theme.of(context)
+ .colorScheme
+ .primary
+ : null,
+ fontFamily: fontFamily,
+ ),
),
),
),
),
- ),
- ],
- ),
- ),
- CustomSettingsTile(
- child: (info) => _buildTextFieldTile(
- context,
- info,
- controller: captchaDetectValueController,
- label: 'CaptchaDetectValue',
- hint: captchaDetectType == CaptchaDetectType.text
- ? '身份验证'
- : captchaDetectType == CaptchaDetectType.regex
- ? '身份验证|smart_verify'
- : '//button[@id="verify"]',
- helper: '留空时回退到旧的图片/按钮 XPath 检测',
- ),
- ),
- if (captchaType == CaptchaType.imageCaptcha) ...[
- CustomSettingsTile(
- child: (info) => _buildTextFieldTile(
- context,
- info,
- controller: captchaImageController,
- label: 'CaptchaImage (XPath)',
- hint: '//img[@class="captcha"]',
- helper: '验证码图片元素的 XPath',
- ),
- ),
- CustomSettingsTile(
- child: (info) => _buildTextFieldTile(
- context,
- info,
- controller: captchaInputController,
- label: 'CaptchaInput (XPath)',
- hint: '//input[@name="captcha"]',
- helper: '验证码输入框元素的 XPath',
- ),
- ),
- ],
- if (captchaType != CaptchaType.customJavaScript)
- CustomSettingsTile(
- child: (info) => _buildTextFieldTile(
- context,
- info,
- controller: captchaButtonController,
- label: captchaType == CaptchaType.imageCaptcha
- ? 'CaptchaButton (XPath)'
- : 'VerifyButton (XPath)',
- hint: '//button[@type="submit"]',
- helper: captchaType == CaptchaType.imageCaptcha
- ? '验证提交按钮元素的 XPath'
- : '验证按钮元素的 XPath,检测到后自动点击',
+ ],
),
),
- if (captchaType == CaptchaType.customJavaScript)
CustomSettingsTile(
child: (info) => _buildTextFieldTile(
context,
info,
- controller: captchaScriptController,
- label: 'CaptchaScript (JavaScript)',
+ controller: captchaDetectValueController,
+ label: _RuleEditorText.captchaDetectValue,
hint:
- 'KazumiCaptcha.log("ready"); KazumiCaptcha.done();',
+ captchaDetectType == CaptchaDetectType.text
+ ? '身份验证'
+ : captchaDetectType ==
+ CaptchaDetectType.regex
+ ? '身份验证|smart_verify'
+ : '//button[@id="verify"]',
helper:
- '可调用 KazumiCaptcha.log/clicked/done/fail',
- maxLines: 8,
+ _RuleEditorText.captchaDetectValueHelper,
),
),
+ if (captchaType == CaptchaType.imageCaptcha) ...[
+ CustomSettingsTile(
+ child: (info) => _buildTextFieldTile(
+ context,
+ info,
+ controller: captchaImageController,
+ label: _RuleEditorText.captchaImage,
+ hint: '//img[@class="captcha"]',
+ helper: _RuleEditorText.captchaImageHelper,
+ ),
+ ),
+ CustomSettingsTile(
+ child: (info) => _buildTextFieldTile(
+ context,
+ info,
+ controller: captchaInputController,
+ label: _RuleEditorText.captchaInput,
+ hint: '//input[@name="captcha"]',
+ helper: _RuleEditorText.captchaInputHelper,
+ ),
+ ),
+ ],
+ if (captchaType != CaptchaType.customJavaScript)
+ CustomSettingsTile(
+ child: (info) => _buildTextFieldTile(
+ context,
+ info,
+ controller: captchaButtonController,
+ label: captchaType == CaptchaType.imageCaptcha
+ ? _RuleEditorText.captchaSubmitButton
+ : _RuleEditorText.verifyButton,
+ hint: '//button[@type="submit"]',
+ helper:
+ captchaType == CaptchaType.imageCaptcha
+ ? _RuleEditorText
+ .captchaSubmitButtonHelper
+ : _RuleEditorText.verifyButtonHelper,
+ ),
+ ),
+ if (captchaType == CaptchaType.customJavaScript)
+ CustomSettingsTile(
+ child: (info) => _buildTextFieldTile(
+ context,
+ info,
+ controller: captchaScriptController,
+ label: _RuleEditorText.captchaScript,
+ hint:
+ 'KazumiCaptcha.log("ready"); KazumiCaptcha.done();',
+ helper: _RuleEditorText.captchaScriptHelper,
+ maxLines: 8,
+ ),
+ ),
+ ],
],
- ],
- ),
+ ),
],
),
],
@@ -464,38 +660,13 @@ class _PluginEditorPageState extends State<PluginEditorPage> {
heroTag: null,
child: const Icon(Icons.bug_report),
onPressed: () async {
- Plugin pluginText = Plugin(
- api: apiController.text,
- type: typeController.text,
- name: nameController.text,
- version: versionController.text,
- muliSources: muliSources,
- useWebview: useWebview,
- useNativePlayer: useNativePlayer,
- usePost: usePost,
- useLegacyParser: useLegacyParser,
- adBlocker: adBlocker,
- userAgent: userAgentController.text,
- baseUrl: baseURLController.text,
- searchURL: searchURLController.text,
- searchList: searchListController.text,
- searchName: searchNameController.text,
- searchResult: searchResultController.text,
- chapterRoads: chapterRoadsController.text,
- chapterResult: chapterResultController.text,
- referer: refererController.text,
- antiCrawlerConfig: AntiCrawlerConfig(
- enabled: antiCrawlerEnabled,
- captchaType: captchaType,
- captchaImage: captchaImageController.text,
- captchaInput: captchaInputController.text,
- captchaButton: captchaButtonController.text,
- captchaDetectType: captchaDetectType,
- captchaDetectValue: captchaDetectValueController.text,
- captchaScript: captchaScriptController.text,
- ));
- Modular.to
- .pushNamed('/settings/plugin/test', arguments: pluginText);
+ try {
+ final pluginText = _buildEditedPlugin();
+ Modular.to
+ .pushNamed('/settings/plugin/test', arguments: pluginText);
+ } catch (error) {
+ _showEditorError(error);
+ }
},
),
SizedBox(width: 15),
@@ -503,37 +674,13 @@ class _PluginEditorPageState extends State<PluginEditorPage> {
heroTag: null,
child: const Icon(Icons.save),
onPressed: () async {
- plugin.api = apiController.text;
- plugin.type = typeController.text;
- plugin.name = nameController.text;
- plugin.version = versionController.text;
- plugin.userAgent = userAgentController.text;
- plugin.baseUrl = baseURLController.text;
- plugin.searchURL = searchURLController.text;
- plugin.searchList = searchListController.text;
- plugin.searchName = searchNameController.text;
- plugin.searchResult = searchResultController.text;
- plugin.chapterRoads = chapterRoadsController.text;
- plugin.chapterResult = chapterResultController.text;
- plugin.muliSources = muliSources;
- plugin.useWebview = useWebview;
- plugin.useNativePlayer = useNativePlayer;
- plugin.usePost = usePost;
- plugin.useLegacyParser = useLegacyParser;
- plugin.adBlocker = adBlocker;
- plugin.referer = refererController.text;
- plugin.antiCrawlerConfig = AntiCrawlerConfig(
- enabled: antiCrawlerEnabled,
- captchaType: captchaType,
- captchaImage: captchaImageController.text,
- captchaInput: captchaInputController.text,
- captchaButton: captchaButtonController.text,
- captchaDetectType: captchaDetectType,
- captchaDetectValue: captchaDetectValueController.text,
- captchaScript: captchaScriptController.text,
- );
- pluginsController.updatePlugin(plugin);
- Navigator.of(context).pop();
+ try {
+ final editedPlugin = _buildEditedPlugin();
+ pluginsController.updatePlugin(editedPlugin);
+ Navigator.of(context).pop();
+ } catch (error) {
+ _showEditorError(error);
+ }
},
),
],
@@ -541,6 +688,441 @@ class _PluginEditorPageState extends State<PluginEditorPage> {
);
}
+ List<Widget> _buildXPathSearchFields() => [
+ _requestMethodField(
+ label: _RuleEditorText.searchMethod,
+ value: usePost ? 'POST' : 'GET',
+ onChanged: (value) => setState(() => usePost = value == 'POST'),
+ ),
+ const SizedBox(height: 20),
+ _editorField(searchURLController, _RuleEditorText.searchUrl),
+ _editorField(searchListController, _RuleEditorText.searchListXPath),
+ _editorField(searchNameController, _RuleEditorText.itemNameXPath),
+ _editorField(searchResultController, _RuleEditorText.itemLinkXPath),
+ ];
+
+ List<Widget> _buildXPathChapterFields() => [
+ _editorField(chapterRoadsController, _RuleEditorText.roadListXPath),
+ _editorField(chapterResultController, _RuleEditorText.episodeListXPath),
+ ];
+
+ List<Widget> _buildApiSearchFields() => [
+ _requestMethodField(
+ label: _RuleEditorText.searchMethod,
+ value: searchApiMethod,
+ onChanged: (value) => setState(() => searchApiMethod = value),
+ ),
+ const SizedBox(height: 20),
+ _editorField(
+ searchApiURLController,
+ _RuleEditorText.searchRequestUrl,
+ ),
+ _editorField(
+ searchApiHeadersController,
+ _RuleEditorText.searchHeaders,
+ maxLines: 4,
+ ),
+ _editorField(
+ searchApiQueryController,
+ _RuleEditorText.searchQuery,
+ maxLines: 4,
+ ),
+ DropdownButtonFormField<String>(
+ initialValue: searchApiBodyType,
+ decoration: const InputDecoration(
+ labelText: _RuleEditorText.searchBodyType,
+ border: OutlineInputBorder(),
+ ),
+ items: const [
+ DropdownMenuItem(value: ApiBodyType.none, child: Text('无')),
+ DropdownMenuItem(value: ApiBodyType.json, child: Text('JSON')),
+ DropdownMenuItem(value: ApiBodyType.form, child: Text('表单')),
+ ],
+ onChanged: (value) => setState(
+ () => searchApiBodyType = value ?? ApiBodyType.none,
+ ),
+ ),
+ const SizedBox(height: 20),
+ if (searchApiBodyType != ApiBodyType.none)
+ _editorField(
+ searchApiBodyController,
+ _RuleEditorText.searchBody,
+ maxLines: 5,
+ ),
+ _editorField(
+ searchApiListPathController,
+ _RuleEditorText.searchListPath,
+ ),
+ _editorField(
+ searchApiNamePathController,
+ _RuleEditorText.itemNamePath,
+ ),
+ _editorField(
+ searchApiSourcePathController,
+ _RuleEditorText.itemSourcePath,
+ ),
+ ];
+
+ List<Widget> _buildApiChapterFields() => [
+ _requestMethodField(
+ label: _RuleEditorText.chapterMethod,
+ value: chapterApiMethod,
+ onChanged: (value) => setState(() => chapterApiMethod = value),
+ ),
+ const SizedBox(height: 20),
+ _editorField(
+ chapterApiURLController,
+ _RuleEditorText.chapterRequestUrl,
+ ),
+ _editorField(
+ chapterApiHeadersController,
+ _RuleEditorText.chapterHeaders,
+ maxLines: 4,
+ ),
+ _editorField(
+ chapterApiQueryController,
+ _RuleEditorText.chapterQuery,
+ maxLines: 4,
+ ),
+ DropdownButtonFormField<String>(
+ initialValue: chapterApiBodyType,
+ decoration: const InputDecoration(
+ labelText: _RuleEditorText.chapterBodyType,
+ border: OutlineInputBorder(),
+ ),
+ items: const [
+ DropdownMenuItem(value: ApiBodyType.none, child: Text('无')),
+ DropdownMenuItem(value: ApiBodyType.json, child: Text('JSON')),
+ DropdownMenuItem(value: ApiBodyType.form, child: Text('表单')),
+ ],
+ onChanged: (value) => setState(
+ () => chapterApiBodyType = value ?? ApiBodyType.none,
+ ),
+ ),
+ const SizedBox(height: 20),
+ if (chapterApiBodyType != ApiBodyType.none)
+ _editorField(
+ chapterApiBodyController,
+ _RuleEditorText.chapterBody,
+ maxLines: 5,
+ ),
+ DropdownButtonFormField<String>(
+ initialValue: chapterApiFormat,
+ decoration: const InputDecoration(
+ labelText: _RuleEditorText.chapterResponseFormat,
+ border: OutlineInputBorder(),
+ ),
+ items: const [
+ DropdownMenuItem(
+ value: ApiChapterFormat.nested,
+ child: Text('嵌套 JSON'),
+ ),
+ DropdownMenuItem(
+ value: ApiChapterFormat.delimited,
+ child: Text('分隔字符串'),
+ ),
+ ],
+ onChanged: (value) => setState(
+ () => chapterApiFormat = value ?? ApiChapterFormat.nested,
+ ),
+ ),
+ const SizedBox(height: 20),
+ if (chapterApiFormat == ApiChapterFormat.nested) ...[
+ _editorField(
+ chapterApiRoadsPathController,
+ _RuleEditorText.roadListPath,
+ ),
+ _editorField(
+ chapterApiRoadNamePathController,
+ _RuleEditorText.roadNamePath,
+ ),
+ _editorField(
+ chapterApiEpisodesPathController,
+ _RuleEditorText.episodeListPath,
+ ),
+ _editorField(
+ chapterApiEpisodeNamePathController,
+ _RuleEditorText.episodeNamePath,
+ ),
+ _editorField(
+ chapterApiEpisodeURLPathController,
+ _RuleEditorText.playbackEntryPath,
+ helper: _RuleEditorText.playbackEntryPathHelper,
+ ),
+ ] else ...[
+ _editorField(
+ chapterApiRoadNamesPathController,
+ _RuleEditorText.roadNamesPath,
+ ),
+ _editorField(
+ chapterApiRoadEpisodesPathController,
+ _RuleEditorText.roadEpisodesPath,
+ ),
+ _editorField(
+ chapterApiRoadSeparatorController,
+ _RuleEditorText.roadSeparator,
+ ),
+ _editorField(
+ chapterApiEpisodeSeparatorController,
+ _RuleEditorText.episodeSeparator,
+ ),
+ _editorField(
+ chapterApiFieldSeparatorController,
+ _RuleEditorText.fieldSeparator,
+ ),
+ ],
+ _editorField(
+ chapterApiVariablesController,
+ _RuleEditorText.responseVariables,
+ maxLines: 5,
+ ),
+ _editorField(
+ chapterApiPageURLController,
+ _RuleEditorText.playPageUrl,
+ ),
+ _editorField(
+ chapterApiPageQueryController,
+ _RuleEditorText.playPageQuery,
+ maxLines: 5,
+ ),
+ ];
+
+ Widget _requestMethodField({
+ required String label,
+ required String value,
+ required ValueChanged<String> onChanged,
+ }) {
+ return DropdownButtonFormField<String>(
+ initialValue: value,
+ decoration: InputDecoration(
+ labelText: label,
+ border: const OutlineInputBorder(),
+ ),
+ items: const [
+ DropdownMenuItem(value: 'GET', child: Text('GET')),
+ DropdownMenuItem(value: 'POST', child: Text('POST')),
+ ],
+ onChanged: (value) {
+ if (value != null) onChanged(value);
+ },
+ );
+ }
+
+ Widget _editorField(
+ TextEditingController controller,
+ String label, {
+ String? helper,
+ int maxLines = 1,
+ }) {
+ return Padding(
+ padding: const EdgeInsets.only(bottom: 20),
+ child: TextField(
+ controller: controller,
+ maxLines: maxLines,
+ decoration: InputDecoration(
+ labelText: label,
+ helperText: helper,
+ border: const OutlineInputBorder(),
+ ),
+ ),
+ );
+ }
+
+ Plugin _buildEditedPlugin() {
+ final searchConfig = _buildSearchApiConfig();
+ final chapterConfig = _buildChapterApiConfig();
+ return Plugin(
+ api: searchMode == RuleMode.api || chapterMode == RuleMode.api
+ ? ApiEndpoints.apiLevel.toString()
+ : apiController.text,
+ type: typeController.text,
+ name: nameController.text,
+ version: versionController.text,
+ muliSources: _muliSources,
+ useWebview: _useWebview,
+ useNativePlayer: _useNativePlayer,
+ usePost: usePost,
+ useLegacyParser: useLegacyParser,
+ adBlocker: adBlocker,
+ userAgent: userAgentController.text,
+ baseUrl: baseURLController.text,
+ searchURL: searchURLController.text,
+ searchList: searchListController.text,
+ searchName: searchNameController.text,
+ searchResult: searchResultController.text,
+ chapterRoads: chapterRoadsController.text,
+ chapterResult: chapterResultController.text,
+ referer: refererController.text,
+ searchMode: searchMode,
+ chapterMode: chapterMode,
+ searchApiConfig: searchConfig,
+ chapterApiConfig: chapterConfig,
+ antiCrawlerConfig: AntiCrawlerConfig(
+ enabled: antiCrawlerEnabled,
+ captchaType: captchaType,
+ captchaImage: captchaImageController.text,
+ captchaInput: captchaInputController.text,
+ captchaButton: captchaButtonController.text,
+ captchaDetectType: captchaDetectType,
+ captchaDetectValue: captchaDetectValueController.text,
+ captchaScript: captchaScriptController.text,
+ ),
+ );
+ }
+
+ ApiSearchConfig _buildSearchApiConfig() {
+ final shouldValidate = searchMode == RuleMode.api;
+ String valueOf(TextEditingController controller) =>
+ shouldValidate ? controller.text.trim() : controller.text;
+ final config = ApiSearchConfig(
+ request: ApiRequestConfig(
+ method: searchApiMethod,
+ url: valueOf(searchApiURLController),
+ headers: _parseJsonMap(searchApiHeadersController, '搜索请求头'),
+ query: _parseJsonMap(searchApiQueryController, '搜索查询参数'),
+ bodyType: searchApiBodyType,
+ body: _parseBody(
+ searchApiBodyController,
+ searchApiBodyType,
+ '搜索请求体',
+ ),
+ ),
+ listPath: valueOf(searchApiListPathController),
+ namePath: valueOf(searchApiNamePathController),
+ sourcePath: valueOf(searchApiSourcePathController),
+ );
+ if (!shouldValidate) return config;
+ if (config.request.url.isEmpty) {
+ throw const FormatException('搜索请求地址不能为空');
+ }
+ const ApiRuleStrategy().prepareRequest(
+ config.request,
+ const {'keyword': 'test'},
+ );
+ RestrictedJsonPath.validate(config.listPath);
+ RestrictedJsonPath.validate(config.namePath);
+ RestrictedJsonPath.validate(config.sourcePath);
+ return config;
+ }
+
+ ApiChapterConfig _buildChapterApiConfig() {
+ final pageUrl = chapterApiPageURLController.text.trim();
+ final variablesRaw = _parseJsonMap(
+ chapterApiVariablesController,
+ '选集响应变量',
+ );
+ final config = ApiChapterConfig(
+ request: ApiRequestConfig(
+ method: chapterApiMethod,
+ url: chapterApiURLController.text.trim(),
+ headers: _parseJsonMap(chapterApiHeadersController, '选集请求头'),
+ query: _parseJsonMap(chapterApiQueryController, '选集查询参数'),
+ bodyType: chapterApiBodyType,
+ body: _parseBody(
+ chapterApiBodyController,
+ chapterApiBodyType,
+ '选集请求体',
+ ),
+ ),
+ format: chapterApiFormat,
+ roadsPath: chapterApiRoadsPathController.text.trim(),
+ roadNamePath: chapterApiRoadNamePathController.text.trim(),
+ episodesPath: chapterApiEpisodesPathController.text.trim(),
+ episodeNamePath: chapterApiEpisodeNamePathController.text.trim(),
+ episodeUrlPath: chapterApiEpisodeURLPathController.text.trim(),
+ roadNamesPath: chapterApiRoadNamesPathController.text.trim(),
+ roadEpisodesPath: chapterApiRoadEpisodesPathController.text.trim(),
+ roadSeparator: chapterApiRoadSeparatorController.text,
+ episodeSeparator: chapterApiEpisodeSeparatorController.text,
+ fieldSeparator: chapterApiFieldSeparatorController.text,
+ variables: variablesRaw.map(
+ (key, value) => MapEntry(key, value.toString()),
+ ),
+ episodePage: pageUrl.isEmpty
+ ? null
+ : ApiEpisodePageConfig(
+ url: pageUrl,
+ query: _parseJsonMap(
+ chapterApiPageQueryController,
+ '播放页查询参数',
+ ),
+ ),
+ );
+ if (chapterMode != RuleMode.api) return config;
+ if (config.request.url.isEmpty) {
+ throw const FormatException('选集请求地址不能为空');
+ }
+ const ApiRuleStrategy().prepareRequest(
+ config.request,
+ const {'source': 'test'},
+ );
+ for (final path in config.variables.values) {
+ RestrictedJsonPath.validate(path);
+ }
+ if (config.format == ApiChapterFormat.nested) {
+ if (config.roadsPath.isNotEmpty) {
+ RestrictedJsonPath.validate(config.roadsPath);
+ }
+ if (config.roadNamePath.isNotEmpty) {
+ RestrictedJsonPath.validate(config.roadNamePath);
+ }
+ RestrictedJsonPath.validate(config.episodesPath);
+ RestrictedJsonPath.validate(config.episodeNamePath);
+ if (config.episodeUrlPath.isNotEmpty) {
+ RestrictedJsonPath.validate(config.episodeUrlPath);
+ } else if (config.episodePage == null) {
+ throw const FormatException('必须配置播放入口地址路径或播放页地址模板');
+ }
+ } else {
+ RestrictedJsonPath.validate(config.roadNamesPath);
+ RestrictedJsonPath.validate(config.roadEpisodesPath);
+ if (config.roadSeparator.isEmpty ||
+ config.episodeSeparator.isEmpty ||
+ config.fieldSeparator.isEmpty) {
+ throw const FormatException('章节分隔符不能为空');
+ }
+ }
+ return config;
+ }
+
+ Map<String, dynamic> _parseJsonMap(
+ TextEditingController controller,
+ String label,
+ ) {
+ final text = controller.text.trim();
+ if (text.isEmpty) return <String, dynamic>{};
+ final value = jsonDecode(text);
+ if (value is! Map) throw FormatException('$label 必须是 JSON 对象');
+ return value.map((key, value) => MapEntry(key.toString(), value));
+ }
+
+ dynamic _parseBody(
+ TextEditingController controller,
+ String bodyType,
+ String label,
+ ) {
+ if (bodyType == ApiBodyType.none) return null;
+ final text = controller.text.trim();
+ if (text.isEmpty) return <String, dynamic>{};
+ final dynamic value;
+ try {
+ value = jsonDecode(text);
+ } on FormatException catch (error) {
+ throw FormatException('$label 不是有效 JSON:${error.message}');
+ }
+ if (bodyType == ApiBodyType.form && value is! Map) {
+ throw FormatException('$label 在表单模式下必须是 JSON 对象');
+ }
+ return value;
+ }
+
+ void _showEditorError(Object error) {
+ if (!mounted) return;
+ ScaffoldMessenger.of(context).showSnackBar(
+ SnackBar(content: Text(error.toString())),
+ );
+ }
+
Widget _buildTextFieldTile(
BuildContext context,
SettingsTileInfo info, {
diff --git a/lib/pages/plugin_editor/plugin_shop_page.dart b/lib/pages/plugin_editor/plugin_shop_page.dart
index 14bc8bd1..ee001912 100644
--- a/lib/pages/plugin_editor/plugin_shop_page.dart
+++ b/lib/pages/plugin_editor/plugin_shop_page.dart
@@ -111,22 +111,6 @@ class _PluginShopPageState extends State<PluginShopPage> {
color: Theme.of(context).colorScheme.surface),
),
),
- const SizedBox(width: 5),
- Container(
- padding: const EdgeInsets.symmetric(
- horizontal: 8.0, vertical: 1.0),
- decoration: BoxDecoration(
- color: Theme.of(context).colorScheme.primary,
- borderRadius: BorderRadius.circular(16.0),
- ),
- child: Text(
- sortedList[index].useNativePlayer
- ? "native"
- : "webview",
- style: TextStyle(
- color: Theme.of(context).colorScheme.surface),
- ),
- ),
if (sortedList[index].antiCrawlerEnabled) ...[
const SizedBox(width: 5),
Container(
diff --git a/lib/pages/plugin_editor/plugin_test_page.dart b/lib/pages/plugin_editor/plugin_test_page.dart
index 831a2c61..5dd32dca 100644
--- a/lib/pages/plugin_editor/plugin_test_page.dart
+++ b/lib/pages/plugin_editor/plugin_test_page.dart
@@ -1,16 +1,15 @@
+import 'dart:convert';
+
import 'package:dio/dio.dart';
-import 'package:flutter/material.dart' hide Element;
+import 'package:flutter/material.dart';
import 'package:flutter_modular/flutter_modular.dart';
import 'package:kazumi/bean/dialog/dialog_helper.dart';
import 'package:kazumi/bean/appbar/sys_app_bar.dart';
import 'package:kazumi/modules/search/plugin_search_module.dart';
-import 'package:kazumi/pages/video/video_controller.dart';
import 'package:kazumi/services/logging/logger.dart';
-import 'package:html/dom.dart' show Element;
-import 'package:html/parser.dart' show parse;
-import 'package:xpath_selector_html_parser/xpath_selector_html_parser.dart';
import '../../modules/roads/road_module.dart';
+import '../../plugins/api_rule_config.dart';
import '../../plugins/plugins.dart';
const _h8 = SizedBox(height: 8.0);
@@ -41,28 +40,28 @@ class PluginTestPage extends StatefulWidget {
class _PluginTestPageState extends State<PluginTestPage> {
late final Plugin plugin;
- final VideoPageController videoPageController =
- Modular.get<VideoPageController>();
final testKeywordController = TextEditingController();
- final htmlScrollController = ScrollController();
+ final searchRawScrollController = ScrollController();
final chapterScrollController = ScrollController();
- final itemHtmlScrollController = ScrollController();
+ final fragmentScrollController = ScrollController();
- String searchHtml = "";
+ String searchRaw = "";
+ String chapterRaw = "";
PluginSearchResponse? searchRes;
List<Road>? chapters;
bool isTesting = false;
String errorMsg = "";
- final Map<int, String> _itemHtmlMap = {};
- int? _showItemHtmlIdx;
+ final Map<int, String> _itemFragmentMap = {};
+ int? _shownFragmentIndex;
- bool get _hasSearchHtml => searchHtml.isNotEmpty;
+ bool get _hasSearchRaw => searchRaw.isNotEmpty;
bool get _hasSearchData => searchRes?.data.isNotEmpty ?? false;
bool get _hasChapters => chapters?.isNotEmpty ?? false;
- bool get _needChapterParse => plugin.chapterRoads.isNotEmpty;
+ bool get _needChapterParse =>
+ plugin.chapterMode == RuleMode.api || plugin.chapterRoads.isNotEmpty;
CancelToken? _testSearchRequestCancelToken;
CancelToken? _testRoadsCancelToken;
@@ -80,76 +79,68 @@ class _PluginTestPageState extends State<PluginTestPage> {
_testSearchRequestCancelToken?.cancel();
_testRoadsCancelToken?.cancel();
testKeywordController.dispose();
- htmlScrollController.dispose();
+ searchRawScrollController.dispose();
chapterScrollController.dispose();
- itemHtmlScrollController.dispose();
+ fragmentScrollController.dispose();
super.dispose();
}
- void onBackPressed() =>
+ void _onBackPressed() =>
KazumiDialog.observer.hasKazumiDialog ? KazumiDialog.dismiss() : null;
- void resetState() => setState(() {
+ void _resetState() => setState(() {
_testSearchRequestCancelToken?.cancel();
_testSearchRequestCancelToken = null;
_testRoadsCancelToken?.cancel();
_testRoadsCancelToken = null;
- searchHtml = "";
+ searchRaw = "";
+ chapterRaw = "";
searchRes = null;
chapters = null;
errorMsg = "";
- _itemHtmlMap.clear();
- _showItemHtmlIdx = null;
+ _itemFragmentMap.clear();
+ _shownFragmentIndex = null;
});
- String _parseItemHtml(int index) {
- if (_itemHtmlMap.containsKey(index)) return _itemHtmlMap[index]!;
- try {
- final node = (parse(searchHtml)
- .documentElement!
- .queryXPath(plugin.searchList)
- .nodes[index]
- .node as Element);
- return _itemHtmlMap[index] = node.outerHtml;
- } catch (e) {
- KazumiLogger()
- .e('PluginTest: failed to parse HTML item ${index + 1}', error: e);
- return "解析失败:$e";
+ void _toggleFragment(int index) {
+ if (_shownFragmentIndex == index) {
+ return setState(() => _shownFragmentIndex = null);
}
- }
-
- void _toggleItemHtml(int index) {
- if (_showItemHtmlIdx == index)
- return setState(() => _showItemHtmlIdx = null);
- setState(() => isTesting = true);
- _parseItemHtml(index);
- setState(() {
- _showItemHtmlIdx = index;
- isTesting = false;
- });
+ setState(() => _shownFragmentIndex = index);
}
Future<void> startTest() async {
final keyword = testKeywordController.text.trim();
- resetState();
+ _resetState();
setState(() => isTesting = true);
try {
_testSearchRequestCancelToken?.cancel();
_testSearchRequestCancelToken = CancelToken();
- searchHtml = await plugin.testSearchRequest(keyword,
- shouldRethrow: true, cancelToken: _testSearchRequestCancelToken);
- searchRes = plugin.testQueryBangumi(searchHtml);
+ final searchTrace = await plugin.traceSearch(
+ keyword,
+ cancelToken: _testSearchRequestCancelToken,
+ );
+ searchRaw = searchTrace.rawResponse;
+ searchRes = searchTrace.response;
+ _itemFragmentMap.addAll(searchTrace.matchedFragments.asMap());
if (_hasSearchData && _needChapterParse) {
final firstItem = searchRes!.data.first;
if (firstItem.src.isNotEmpty) {
_testRoadsCancelToken?.cancel();
_testRoadsCancelToken = CancelToken();
- chapters = await plugin.querychapterRoads(firstItem.src,
- cancelToken: _testRoadsCancelToken);
+ final chapterTrace = await plugin.traceChapters(
+ firstItem.src,
+ cancelToken: _testRoadsCancelToken,
+ );
+ chapterRaw = chapterTrace.rawResponse;
+ chapters = chapterTrace.roads;
}
}
} catch (e, stack) {
KazumiLogger().e("PluginTest: test failed", error: e, stackTrace: stack);
+ if (mounted) {
+ setState(() => errorMsg = e.toString());
+ }
} finally {
if (mounted) setState(() => isTesting = false);
}
@@ -160,7 +151,7 @@ class _PluginTestPageState extends State<PluginTestPage> {
final theme = Theme.of(context);
return PopScope(
canPop: true,
- onPopInvokedWithResult: (didPop, _) => !didPop ? onBackPressed() : null,
+ onPopInvokedWithResult: (didPop, _) => !didPop ? _onBackPressed() : null,
child: Scaffold(
appBar: SysAppBar(
title: Text('${plugin.name} 测试'),
@@ -171,7 +162,7 @@ class _PluginTestPageState extends State<PluginTestPage> {
tooltip: '开始测试',
),
IconButton(
- onPressed: resetState,
+ onPressed: _resetState,
icon: const Icon(Icons.refresh),
tooltip: '重置',
),
@@ -317,8 +308,8 @@ class _PluginTestPageState extends State<PluginTestPage> {
String _getSearchSubtitle() {
if (isTesting) return '测试中...';
- if (!_hasSearchHtml) return '未执行测试';
- return 'HTML长度:${searchHtml.length} 字符';
+ if (!_hasSearchRaw) return '未执行测试';
+ return '${plugin.searchMode == RuleMode.api ? 'JSON' : 'HTML'}长度:${searchRaw.length} 字符';
}
// 简化副标题颜色逻辑:仅三类
@@ -338,7 +329,7 @@ class _PluginTestPageState extends State<PluginTestPage> {
Widget _buildSearchContent(ThemeData theme) {
if (isTesting) return _buildLoading(theme);
- if (!_hasSearchHtml) return _buildEmpty('点击顶部「开始测试」按钮执行', theme);
+ if (!_hasSearchRaw) return _buildEmpty('点击顶部「开始测试」按钮执行', theme);
return Container(
margin: const EdgeInsets.only(bottom: 8.0),
padding: const EdgeInsets.all(8.0),
@@ -349,10 +340,10 @@ class _PluginTestPageState extends State<PluginTestPage> {
),
height: 250,
child: SingleChildScrollView(
- controller: htmlScrollController,
+ controller: searchRawScrollController,
physics: const ClampingScrollPhysics(),
child: SelectableText(
- searchHtml,
+ _formattedRaw(searchRaw, isJson: plugin.searchMode == RuleMode.api),
style: theme.textTheme.bodySmall?.copyWith(fontFamily: 'monospace'),
),
),
@@ -360,15 +351,15 @@ class _PluginTestPageState extends State<PluginTestPage> {
}
String _getParseSubtitle() {
- if (isTesting && _showItemHtmlIdx == null) return '解析中...';
- if (!_hasSearchHtml) return '未执行解析';
+ if (isTesting && _shownFragmentIndex == null) return '解析中...';
+ if (!_hasSearchRaw) return '未执行解析';
if (!_hasSearchData) return '未解析到结果';
return '解析到 ${searchRes?.data.length ?? 0} 条结果';
}
Widget _buildParseContent(ThemeData theme) {
- if (isTesting && _showItemHtmlIdx == null) return _buildLoading(theme);
- if (!_hasSearchHtml) return _buildEmpty('请先完成搜索请求测试', theme);
+ if (isTesting && _shownFragmentIndex == null) return _buildLoading(theme);
+ if (!_hasSearchRaw) return _buildEmpty('请先完成搜索请求测试', theme);
if (!_hasSearchData) return _buildEmpty('未解析到搜索结果', theme, isError: true);
return Column(children: [
@@ -384,8 +375,8 @@ class _PluginTestPageState extends State<PluginTestPage> {
}
Widget _buildSearchItemCard(SearchItem item, int i, ThemeData theme) {
- final isShowHtml = _showItemHtmlIdx == i;
- final itemHtml = _itemHtmlMap[i] ?? '加载中...';
+ final isShowingFragment = _shownFragmentIndex == i;
+ final fragment = _itemFragmentMap[i] ?? '无匹配片段';
return Column(children: [
Card(
@@ -406,13 +397,13 @@ class _PluginTestPageState extends State<PluginTestPage> {
),
),
IconButton(
- onPressed: isTesting ? null : () => _toggleItemHtml(i),
+ onPressed: isTesting ? null : () => _toggleFragment(i),
icon: Icon(
- isShowHtml ? Icons.keyboard_arrow_up : Icons.code,
+ isShowingFragment ? Icons.keyboard_arrow_up : Icons.code,
size: 18,
color: theme.getCoreColor(CoreColorType.success),
),
- tooltip: isShowHtml ? '隐藏HTML' : '查看HTML',
+ tooltip: isShowingFragment ? '隐藏匹配片段' : '查看匹配片段',
),
]),
_h8,
@@ -422,7 +413,7 @@ class _PluginTestPageState extends State<PluginTestPage> {
]),
),
),
- if (isShowHtml)
+ if (isShowingFragment)
Container(
margin: const EdgeInsets.only(bottom: 8.0),
padding: const EdgeInsets.all(8.0),
@@ -434,10 +425,10 @@ class _PluginTestPageState extends State<PluginTestPage> {
),
height: 250,
child: SingleChildScrollView(
- controller: itemHtmlScrollController,
+ controller: fragmentScrollController,
physics: const ClampingScrollPhysics(),
child: SelectableText(
- itemHtml,
+ fragment,
style:
theme.textTheme.bodySmall?.copyWith(fontFamily: 'monospace'),
),
@@ -461,17 +452,52 @@ class _PluginTestPageState extends State<PluginTestPage> {
if (chapters == null) return _buildEmpty('未获取章节数据', theme, isError: true);
if (!_hasChapters) return _buildEmpty('无可用章节', theme, isError: true);
- return Container(
- padding: const EdgeInsets.all(8.0),
- height: 280,
- child: ListView.builder(
- controller: chapterScrollController,
- itemCount: chapters?.length ?? 0,
- itemBuilder: (_, i) => _buildChapterCard(chapters![i], i, theme),
- ),
+ return Column(
+ children: [
+ if (chapterRaw.isNotEmpty)
+ Container(
+ margin: const EdgeInsets.only(bottom: 8),
+ padding: const EdgeInsets.all(8),
+ constraints: const BoxConstraints(maxHeight: 220),
+ width: double.infinity,
+ decoration: BoxDecoration(
+ borderRadius: BorderRadius.circular(8),
+ border:
+ Border.all(color: theme.getCoreColor(CoreColorType.waiting)),
+ ),
+ child: SingleChildScrollView(
+ child: SelectableText(
+ _formattedRaw(
+ chapterRaw,
+ isJson: plugin.chapterMode == RuleMode.api,
+ ),
+ style: theme.textTheme.bodySmall
+ ?.copyWith(fontFamily: 'monospace'),
+ ),
+ ),
+ ),
+ Container(
+ padding: const EdgeInsets.all(8.0),
+ height: 280,
+ child: ListView.builder(
+ controller: chapterScrollController,
+ itemCount: chapters?.length ?? 0,
+ itemBuilder: (_, i) => _buildChapterCard(chapters![i], i, theme),
+ ),
+ ),
+ ],
);
}
+ String _formattedRaw(String raw, {required bool isJson}) {
+ if (!isJson) return raw;
+ try {
+ return const JsonEncoder.withIndent(' ').convert(jsonDecode(raw));
+ } catch (_) {
+ return raw;
+ }
+ }
+
Widget _buildChapterCard(Road road, int i, ThemeData theme) => Card(
margin: const EdgeInsets.only(bottom: 8.0),
elevation: 1,
@@ -498,10 +524,16 @@ class _PluginTestPageState extends State<PluginTestPage> {
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
- ...road.identifier.asMap().entries.map((e) => Text(
- '${e.key + 1}. ${e.value}',
- style: theme.textTheme.bodySmall,
- )),
+ ...road.identifier.asMap().entries.map(
+ (e) => Padding(
+ padding: const EdgeInsets.only(bottom: 6),
+ child: SelectableText(
+ '${e.key + 1}. ${e.value}\n'
+ '${e.key < road.data.length ? road.data[e.key] : ''}',
+ style: theme.textTheme.bodySmall,
+ ),
+ ),
+ ),
]),
),
),
diff --git a/lib/pages/video/video_controller.dart b/lib/pages/video/video_controller.dart
index 3fc4e2c2..d5540242 100644
--- a/lib/pages/video/video_controller.dart
+++ b/lib/pages/video/video_controller.dart
@@ -747,13 +747,17 @@ abstract class _VideoPageController with Store {
for (Plugin plugin in pluginsController.pluginList) {
if (plugin.name == pluginName) {
roadList.addAll(
- await plugin.querychapterRoads(url, cancelToken: cancelToken));
+ await plugin.queryChapterRoads(url, cancelToken: cancelToken));
}
}
KazumiLogger()
.i('VideoPageController: road list length ${roadList.length}');
+ if (roadList.isEmpty) {
+ throw ChapterErrorException(pluginName);
+ }
KazumiLogger().i(
- 'VideoPageController: first road episode count ${roadList[0].data.length}');
+ 'VideoPageController: first road episode count ${roadList.first.data.length}',
+ );
}
void toggleSortOrder() {
diff --git a/lib/plugins/anti_crawler_config.dart b/lib/plugins/anti_crawler_config.dart
index d240b8e1..54164a82 100644
--- a/lib/plugins/anti_crawler_config.dart
+++ b/lib/plugins/anti_crawler_config.dart
@@ -20,8 +20,8 @@ class CaptchaDetectType {
/// 反反爬虫配置
///
-/// 当网站对搜索请求返回验证码时,使用 WebView 加载搜索页,
-/// 根据 [captchaType] 采用不同策略完成验证,之后保存 Cookie 用于后续请求。
+/// 仅当 XPath 搜索响应为验证页时,使用 WebView 加载搜索页,
+/// 根据 [captchaType] 完成验证并保存 Cookie,随后重试 XPath 搜索。
class AntiCrawlerConfig {
/// 是否启用反反爬虫功能
bool enabled;
diff --git a/lib/plugins/api_rule_config.dart b/lib/plugins/api_rule_config.dart
new file mode 100644
index 00000000..4213d32a
--- /dev/null
+++ b/lib/plugins/api_rule_config.dart
@@ -0,0 +1,220 @@
+class RuleMode {
+ static const String xpath = 'xpath';
+ static const String api = 'api';
+
+ static String normalize(Object? value) {
+ return value == api ? api : xpath;
+ }
+}
+
+class ApiBodyType {
+ static const String none = 'none';
+ static const String json = 'json';
+ static const String form = 'form';
+
+ static String normalize(Object? value) {
+ return switch (value) {
+ json => json,
+ form => form,
+ _ => none,
+ };
+ }
+}
+
+class ApiChapterFormat {
+ static const String nested = 'nested';
+ static const String delimited = 'delimited';
+
+ static String normalize(Object? value) {
+ return value == delimited ? delimited : nested;
+ }
+}
+
+class ApiRequestConfig {
+ String method;
+ String url;
+ Map<String, dynamic> headers;
+ Map<String, dynamic> query;
+ String bodyType;
+ dynamic body;
+
+ ApiRequestConfig({
+ this.method = 'GET',
+ this.url = '',
+ Map<String, dynamic>? headers,
+ Map<String, dynamic>? query,
+ this.bodyType = ApiBodyType.none,
+ this.body,
+ }) : headers = headers ?? <String, dynamic>{},
+ query = query ?? <String, dynamic>{};
+
+ factory ApiRequestConfig.fromJson(Map<String, dynamic> json) {
+ return ApiRequestConfig(
+ method: (json['method'] as String? ?? 'GET').toUpperCase(),
+ url: json['url'] as String? ?? '',
+ headers: _asStringMap(json['headers']),
+ query: _asStringMap(json['query']),
+ bodyType: ApiBodyType.normalize(json['bodyType']),
+ body: json['body'],
+ );
+ }
+
+ Map<String, dynamic> toJson() => {
+ 'method': method.toUpperCase(),
+ 'url': url,
+ 'headers': headers,
+ 'query': query,
+ 'bodyType': bodyType,
+ if (bodyType != ApiBodyType.none && body != null) 'body': body,
+ };
+}
+
+class ApiSearchConfig {
+ ApiRequestConfig request;
+ String listPath;
+ String namePath;
+ String sourcePath;
+
+ ApiSearchConfig({
+ ApiRequestConfig? request,
+ this.listPath = r'$.data[*]',
+ this.namePath = r'$.name',
+ this.sourcePath = r'$.url',
+ }) : request = request ?? ApiRequestConfig();
+
+ factory ApiSearchConfig.fromJson(Map<String, dynamic> json) {
+ return ApiSearchConfig(
+ request: ApiRequestConfig.fromJson(_asStringMap(json['request'])),
+ listPath: json['listPath'] as String? ?? r'$.data[*]',
+ namePath: json['namePath'] as String? ?? r'$.name',
+ sourcePath: json['sourcePath'] as String? ?? r'$.url',
+ );
+ }
+
+ Map<String, dynamic> toJson() => {
+ 'request': request.toJson(),
+ 'listPath': listPath,
+ 'namePath': namePath,
+ 'sourcePath': sourcePath,
+ };
+}
+
+class ApiEpisodePageConfig {
+ /// Template for the final playback page URL.
+ String url;
+
+ /// Query parameters rendered with response and episode index variables.
+ Map<String, dynamic> query;
+
+ ApiEpisodePageConfig({
+ this.url = '',
+ Map<String, dynamic>? query,
+ }) : query = query ?? <String, dynamic>{};
+
+ factory ApiEpisodePageConfig.fromJson(Map<String, dynamic> json) {
+ return ApiEpisodePageConfig(
+ url: json['url'] as String? ?? '',
+ query: _asStringMap(json['query']),
+ );
+ }
+
+ Map<String, dynamic> toJson() => {
+ 'url': url,
+ 'query': query,
+ };
+}
+
+class ApiChapterConfig {
+ ApiRequestConfig request;
+ String format;
+
+ // Nested JSON response mapping.
+ String roadsPath;
+ String roadNamePath;
+ String episodesPath;
+ String episodeNamePath;
+
+ /// JSONPath for a playback entry URL (page URL or direct media URL).
+ /// May be empty when [episodePage] constructs the final playback page URL.
+ String episodeUrlPath;
+
+ // Delimited string response mapping.
+ String roadNamesPath;
+ String roadEpisodesPath;
+ String roadSeparator;
+ String episodeSeparator;
+ String fieldSeparator;
+
+ String defaultRoadName;
+ Map<String, String> variables;
+
+ /// Optional final playback page template used instead of a response URL.
+ ApiEpisodePageConfig? episodePage;
+
+ ApiChapterConfig({
+ ApiRequestConfig? request,
+ this.format = ApiChapterFormat.nested,
+ this.roadsPath = r'$.data.roads[*]',
+ this.roadNamePath = r'$.name',
+ this.episodesPath = r'$.episodes[*]',
+ this.episodeNamePath = r'$.name',
+ this.episodeUrlPath = r'$.url',
+ this.roadNamesPath = '',
+ this.roadEpisodesPath = '',
+ this.roadSeparator = r'$$$',
+ this.episodeSeparator = '#',
+ this.fieldSeparator = r'$',
+ this.defaultRoadName = '播放线路',
+ Map<String, String>? variables,
+ this.episodePage,
+ }) : request = request ?? ApiRequestConfig(),
+ variables = variables ?? <String, String>{};
+
+ factory ApiChapterConfig.fromJson(Map<String, dynamic> json) {
+ final rawVariables = _asStringMap(json['variables']);
+ return ApiChapterConfig(
+ request: ApiRequestConfig.fromJson(_asStringMap(json['request'])),
+ format: ApiChapterFormat.normalize(json['format']),
+ roadsPath: json['roadsPath'] as String? ?? r'$.data.roads[*]',
+ roadNamePath: json['roadNamePath'] as String? ?? r'$.name',
+ episodesPath: json['episodesPath'] as String? ?? r'$.episodes[*]',
+ episodeNamePath: json['episodeNamePath'] as String? ?? r'$.name',
+ episodeUrlPath: json['episodeUrlPath'] as String? ?? r'$.url',
+ roadNamesPath: json['roadNamesPath'] as String? ?? '',
+ roadEpisodesPath: json['roadEpisodesPath'] as String? ?? '',
+ roadSeparator: json['roadSeparator'] as String? ?? r'$$$',
+ episodeSeparator: json['episodeSeparator'] as String? ?? '#',
+ fieldSeparator: json['fieldSeparator'] as String? ?? r'$',
+ defaultRoadName: json['defaultRoadName'] as String? ?? '播放线路',
+ variables: rawVariables.map(
+ (key, value) => MapEntry(key, value.toString()),
+ ),
+ episodePage: json['episodePage'] is Map
+ ? ApiEpisodePageConfig.fromJson(_asStringMap(json['episodePage']))
+ : null,
+ );
+ }
+
+ Map<String, dynamic> toJson() => {
+ 'request': request.toJson(),
+ 'format': format,
+ 'roadsPath': roadsPath,
+ 'roadNamePath': roadNamePath,
+ 'episodesPath': episodesPath,
+ 'episodeNamePath': episodeNamePath,
+ 'episodeUrlPath': episodeUrlPath,
+ 'roadNamesPath': roadNamesPath,
+ 'roadEpisodesPath': roadEpisodesPath,
+ 'roadSeparator': roadSeparator,
+ 'episodeSeparator': episodeSeparator,
+ 'fieldSeparator': fieldSeparator,
+ 'defaultRoadName': defaultRoadName,
+ 'variables': variables,
+ if (episodePage != null) 'episodePage': episodePage!.toJson(),
+ };
+}
+
+Map<String, dynamic> _asStringMap(Object? value) {
+ if (value is! Map) return <String, dynamic>{};
+ return value.map((key, value) => MapEntry(key.toString(), value));
+}
diff --git a/lib/plugins/plugins.dart b/lib/plugins/plugins.dart
index a538fb15..1fcf2ad7 100644
--- a/lib/plugins/plugins.dart
+++ b/lib/plugins/plugins.dart
@@ -1,60 +1,33 @@
-import 'package:dio/dio.dart';
-import 'package:kazumi/modules/search/plugin_search_module.dart';
import 'package:kazumi/modules/roads/road_module.dart';
-import 'package:kazumi/request/clients/plugin_site_client.dart';
-import 'package:html/dom.dart' show Element;
-import 'package:html/parser.dart';
-import 'package:kazumi/request/config/api_endpoints.dart';
-import 'package:kazumi/services/logging/logger.dart';
-import 'package:xpath_selector_html_parser/xpath_selector_html_parser.dart';
+import 'package:kazumi/modules/search/plugin_search_module.dart';
import 'package:kazumi/plugins/anti_crawler_config.dart';
-import 'package:kazumi/services/plugin/plugin_cookie_manager.dart';
+import 'package:kazumi/plugins/api_rule_config.dart';
+import 'package:kazumi/request/config/api_endpoints.dart';
+import 'package:kazumi/services/plugin/api_rule_engine.dart';
import 'package:kazumi/utils/episode_url.dart';
import 'package:kazumi/utils/http_headers.dart';
-/// Thrown by [Plugin.queryBangumi] when the response contains a CAPTCHA challenge
-/// (i.e. the [AntiCrawlerConfig.captchaImage] XPath selector matches something
-/// in the returned HTML).
-class CaptchaRequiredException implements Exception {
- final String pluginName;
- const CaptchaRequiredException(this.pluginName);
- @override
- String toString() =>
- 'CaptchaRequiredException: $pluginName requires captcha verification';
-}
-
-/// Thrown by [Plugin.queryBangumi] when the search request succeeds but the
-/// XPath selectors return no results.
-class NoResultException implements Exception {
- final String pluginName;
- const NoResultException(this.pluginName);
- @override
- String toString() =>
- 'NoResultException: $pluginName returned no search results';
-}
-
-/// Thrown by [Plugin.queryBangumi] when the HTTP request or HTML parsing
-/// fails for reasons other than a captcha challenge.
-class SearchErrorException implements Exception {
- final String pluginName;
- final Object? cause;
- const SearchErrorException(this.pluginName, {this.cause});
- @override
- String toString() =>
- 'SearchErrorException: $pluginName search failed${cause != null ? ' ($cause)' : ''}';
-}
+export 'package:kazumi/services/plugin/rule_engine_models.dart'
+ show
+ CaptchaRequiredException,
+ NoResultException,
+ SearchErrorException,
+ ChapterErrorException,
+ RuleFailureKind;
class Plugin {
- static final PluginSiteClient _siteClient = PluginSiteClient.instance;
+ static final RuleEngine _ruleEngine = RuleEngine();
String api;
String type;
String name;
String version;
bool muliSources;
+
+ /// Legacy schema field retained for rule import/export compatibility.
bool useWebview;
- /// Deprecated (always true)
+ /// Legacy schema field retained for rule import/export compatibility.
bool useNativePlayer;
bool usePost;
bool useLegacyParser;
@@ -68,6 +41,10 @@ class Plugin {
String chapterRoads;
String chapterResult;
String referer;
+ String searchMode;
+ String chapterMode;
+ ApiSearchConfig searchApiConfig;
+ ApiChapterConfig chapterApiConfig;
AntiCrawlerConfig antiCrawlerConfig;
Plugin({
@@ -90,327 +67,196 @@ class Plugin {
required this.chapterRoads,
required this.chapterResult,
required this.referer,
+ this.searchMode = RuleMode.xpath,
+ this.chapterMode = RuleMode.xpath,
+ ApiSearchConfig? searchApiConfig,
+ ApiChapterConfig? chapterApiConfig,
AntiCrawlerConfig? antiCrawlerConfig,
- }) : antiCrawlerConfig = antiCrawlerConfig ?? AntiCrawlerConfig.empty();
+ }) : searchApiConfig = searchApiConfig ?? ApiSearchConfig(),
+ chapterApiConfig = chapterApiConfig ?? ApiChapterConfig(),
+ antiCrawlerConfig = antiCrawlerConfig ?? AntiCrawlerConfig.empty();
factory Plugin.fromJson(Map<String, dynamic> json) {
return Plugin(
- api: json['api'],
- type: json['type'],
- name: json['name'],
- version: json['version'],
- muliSources: json['muliSources'],
- useWebview: json['useWebview'],
- useNativePlayer: json['useNativePlayer'],
- usePost: json['usePost'] ?? false,
- useLegacyParser: json['useLegacyParser'] ?? false,
- adBlocker: json['adBlocker'] ?? false,
- userAgent: json['userAgent'],
- baseUrl: json['baseURL'],
- searchURL: json['searchURL'],
- searchList: json['searchList'],
- searchName: json['searchName'],
- searchResult: json['searchResult'],
- chapterRoads: json['chapterRoads'],
- chapterResult: json['chapterResult'],
- referer: json['referer'] ?? '',
- antiCrawlerConfig: json['antiCrawlerConfig'] != null
- ? AntiCrawlerConfig.fromJson(
- Map<String, dynamic>.from(json['antiCrawlerConfig']))
- : AntiCrawlerConfig.empty());
+ api: json['api']?.toString() ?? '1',
+ type: json['type'] as String? ?? 'anime',
+ name: json['name'] as String? ?? '',
+ version: json['version']?.toString() ?? '',
+ muliSources: json['muliSources'] as bool? ?? true,
+ useWebview: json['useWebview'] as bool? ?? true,
+ useNativePlayer: json['useNativePlayer'] as bool? ?? true,
+ usePost: json['usePost'] ?? false,
+ useLegacyParser: json['useLegacyParser'] ?? false,
+ adBlocker: json['adBlocker'] ?? false,
+ userAgent: json['userAgent'] as String? ?? '',
+ baseUrl: json['baseURL'] as String? ?? '',
+ searchURL: json['searchURL'] as String? ?? '',
+ searchList: json['searchList'] as String? ?? '',
+ searchName: json['searchName'] as String? ?? '',
+ searchResult: json['searchResult'] as String? ?? '',
+ chapterRoads: json['chapterRoads'] as String? ?? '',
+ chapterResult: json['chapterResult'] as String? ?? '',
+ referer: json['referer'] ?? '',
+ searchMode: RuleMode.normalize(json['searchMode']),
+ chapterMode: RuleMode.normalize(json['chapterMode']),
+ searchApiConfig: json['searchApiConfig'] is Map
+ ? ApiSearchConfig.fromJson(
+ Map<String, dynamic>.from(json['searchApiConfig']),
+ )
+ : ApiSearchConfig(),
+ chapterApiConfig: json['chapterApiConfig'] is Map
+ ? ApiChapterConfig.fromJson(
+ Map<String, dynamic>.from(json['chapterApiConfig']),
+ )
+ : ApiChapterConfig(),
+ antiCrawlerConfig: json['antiCrawlerConfig'] != null
+ ? AntiCrawlerConfig.fromJson(
+ Map<String, dynamic>.from(json['antiCrawlerConfig']),
+ )
+ : AntiCrawlerConfig.empty(),
+ );
}
factory Plugin.fromTemplate() {
return Plugin(
- api: ApiEndpoints.apiLevel.toString(),
- type: 'anime',
- name: '',
- version: '',
- muliSources: true,
- useWebview: true,
- useNativePlayer: true,
- usePost: false,
- useLegacyParser: false,
- adBlocker: false,
- userAgent: '',
- baseUrl: '',
- searchURL: '',
- searchList: '',
- searchName: '',
- searchResult: '',
- chapterRoads: '',
- chapterResult: '',
- referer: '',
- antiCrawlerConfig: AntiCrawlerConfig.empty());
+ api: ApiEndpoints.apiLevel.toString(),
+ type: 'anime',
+ name: '',
+ version: '',
+ muliSources: true,
+ useWebview: true,
+ useNativePlayer: true,
+ usePost: false,
+ useLegacyParser: false,
+ adBlocker: false,
+ userAgent: '',
+ baseUrl: '',
+ searchURL: '',
+ searchList: '',
+ searchName: '',
+ searchResult: '',
+ chapterRoads: '',
+ chapterResult: '',
+ referer: '',
+ searchMode: RuleMode.xpath,
+ chapterMode: RuleMode.xpath,
+ searchApiConfig: ApiSearchConfig(),
+ chapterApiConfig: ApiChapterConfig(),
+ antiCrawlerConfig: AntiCrawlerConfig.empty(),
+ );
}
Map<String, dynamic> toJson() {
- final Map<String, dynamic> data = <String, dynamic>{};
- data['api'] = api;
- data['type'] = type;
- data['name'] = name;
- data['version'] = version;
- data['muliSources'] = muliSources;
- data['useWebview'] = useWebview;
- data['useNativePlayer'] = useNativePlayer;
- data['usePost'] = usePost;
- data['useLegacyParser'] = useLegacyParser;
- data['adBlocker'] = adBlocker;
- data['userAgent'] = userAgent;
- data['baseURL'] = baseUrl;
- data['searchURL'] = searchURL;
- data['searchList'] = searchList;
- data['searchName'] = searchName;
- data['searchResult'] = searchResult;
- data['chapterRoads'] = chapterRoads;
- data['chapterResult'] = chapterResult;
- data['referer'] = referer;
- data['antiCrawlerConfig'] = antiCrawlerConfig.toJson();
- return data;
+ return <String, dynamic>{
+ 'api': api,
+ 'type': type,
+ 'name': name,
+ 'version': version,
+ 'muliSources': muliSources,
+ 'useWebview': useWebview,
+ 'useNativePlayer': useNativePlayer,
+ 'usePost': usePost,
+ 'useLegacyParser': useLegacyParser,
+ 'adBlocker': adBlocker,
+ 'userAgent': userAgent,
+ 'baseURL': baseUrl,
+ 'searchURL': searchURL,
+ 'searchList': searchList,
+ 'searchName': searchName,
+ 'searchResult': searchResult,
+ 'chapterRoads': chapterRoads,
+ 'chapterResult': chapterResult,
+ 'referer': referer,
+ 'searchMode': searchMode,
+ 'chapterMode': chapterMode,
+ 'searchApiConfig': searchApiConfig.toJson(),
+ 'chapterApiConfig': chapterApiConfig.toJson(),
+ 'antiCrawlerConfig': antiCrawlerConfig.toJson(),
+ };
}
- Future<PluginSearchResponse> queryBangumi(String keyword,
- {bool shouldRethrow = false}) async {
- try {
- String queryURL =
- searchURL.replaceAll('@keyword', Uri.encodeQueryComponent(keyword));
- String htmlString;
- List<SearchItem> searchItems = [];
- final String cookieHeader = await _cookieHeaderFor(queryURL);
- if (usePost) {
- Uri uri = Uri.parse(queryURL);
- Map<String, String> queryParams = uri.queryParameters;
- Uri postUri = Uri(
- scheme: uri.scheme,
- host: uri.host,
- path: uri.path,
- );
- var httpHeaders = {
- 'referer': '$baseUrl/',
- 'Content-Type': 'application/x-www-form-urlencoded',
- 'Accept-Language': getRandomAcceptedLanguage(),
- 'Connection': 'keep-alive',
- if (cookieHeader.isNotEmpty) 'Cookie': cookieHeader,
- };
- htmlString = await _siteClient.postFormText(
- postUri.toString(),
- headers: httpHeaders,
- data: queryParams,
- );
- } else {
- var httpHeaders = {
- 'referer': '$baseUrl/',
- 'Accept-Language': getRandomAcceptedLanguage(),
- 'Connection': 'keep-alive',
- if (cookieHeader.isNotEmpty) 'Cookie': cookieHeader,
- };
- htmlString = await _siteClient.getText(
- queryURL,
- headers: httpHeaders,
- );
- }
+ bool get usesApiSearch => searchMode == RuleMode.api;
- var htmlElement = parse(htmlString).documentElement!;
+ RuleExecutionConfig get _executionConfig => RuleExecutionConfig(
+ pluginName: name,
+ baseUrl: baseUrl,
+ usePost: usePost,
+ searchMode: searchMode,
+ chapterMode: chapterMode,
+ searchUrl: searchURL,
+ searchList: searchList,
+ searchName: searchName,
+ searchResult: searchResult,
+ chapterRoads: chapterRoads,
+ chapterResult: chapterResult,
+ searchApiConfig: searchApiConfig,
+ chapterApiConfig: chapterApiConfig,
+ antiCrawlerConfig: antiCrawlerConfig,
+ );
+
+ Future<RuleSearchTrace> traceSearch(
+ String keyword, {
+ RuleCancelToken? cancelToken,
+ }) {
+ return _ruleEngine.search(
+ _executionConfig,
+ keyword,
+ cancelToken: cancelToken,
+ );
+ }
- if (detectsCaptchaChallenge(htmlString, htmlElement: htmlElement)) {
- KazumiLogger()
- .w('Plugin: $name detected captcha challenge in search response');
- throw CaptchaRequiredException(name);
- }
+ Future<RuleChapterTrace> traceChapters(
+ String source, {
+ RuleCancelToken? cancelToken,
+ }) {
+ return _ruleEngine.queryChapters(
+ _executionConfig,
+ source,
+ cancelToken: cancelToken,
+ );
+ }
- htmlElement.queryXPath(searchList).nodes.forEach((element) {
- try {
- SearchItem searchItem = SearchItem(
- name: element.queryXPath(searchName).node!.text?.trim() ?? '',
- src:
- element.queryXPath(searchResult).node!.attributes['href'] ?? '',
- );
- searchItems.add(searchItem);
- KazumiLogger().i(
- 'Plugin: $name ${element.queryXPath(searchName).node!.text ?? ''} $baseUrl${element.queryXPath(searchResult).node!.attributes['href'] ?? ''}');
- } catch (_) {}
- });
- if (searchItems.isEmpty) throw NoResultException(name);
- return PluginSearchResponse(pluginName: name, data: searchItems);
+ Future<PluginSearchResponse> queryBangumi(
+ String keyword, {
+ bool shouldRethrow = false,
+ RuleCancelToken? cancelToken,
+ }) async {
+ try {
+ return (await traceSearch(keyword, cancelToken: cancelToken)).response;
} on CaptchaRequiredException {
rethrow;
} on NoResultException {
rethrow;
- } catch (e, st) {
- KazumiLogger().w('Plugin: $name search failed', error: e, stackTrace: st);
- if (shouldRethrow) throw SearchErrorException(name, cause: e);
- return PluginSearchResponse(pluginName: name, data: []);
+ } on SearchErrorException {
+ if (shouldRethrow) rethrow;
+ return PluginSearchResponse(pluginName: name, data: <SearchItem>[]);
}
}
- Future<List<Road>> querychapterRoads(String url,
- {CancelToken? cancelToken}) async {
- List<Road> roadList = [];
- if (!url.contains('https')) {
- url = url.replaceAll('http', 'https');
- }
- String queryURL = '';
- if (url.contains(baseUrl)) {
- queryURL = url;
- } else {
- queryURL = baseUrl + url;
- }
- var httpHeaders = {
- 'referer': '$baseUrl/',
- 'Accept-Language': getRandomAcceptedLanguage(),
- 'Connection': 'keep-alive',
- };
- try {
- final htmlString = await _siteClient.getText(
- queryURL,
- headers: httpHeaders,
- cancelToken: cancelToken,
- );
- var htmlElement = parse(htmlString).documentElement!;
- int count = 1;
- htmlElement.queryXPath(chapterRoads).nodes.forEach((element) {
- try {
- List<String> chapterUrlList = [];
- List<String> chapterNameList = [];
- element.queryXPath(chapterResult).nodes.forEach((item) {
- String itemUrl = item.node.attributes['href'] ?? '';
- String itemName = item.node.text ?? '';
- chapterUrlList.add(normalizeEpisodeUrl(baseUrl, itemUrl));
- chapterNameList.add(itemName.replaceAll(RegExp(r'\s+'), ''));
- });
- if (chapterUrlList.isNotEmpty && chapterNameList.isNotEmpty) {
- Road road = Road(
- name: '播放线路$count',
- data: chapterUrlList,
- identifier: chapterNameList);
- roadList.add(road);
- count++;
- }
- } catch (_) {}
- });
- } catch (_) {}
- return roadList;
+ Future<List<Road>> queryChapterRoads(
+ String source, {
+ RuleCancelToken? cancelToken,
+ }) async {
+ return (await traceChapters(source, cancelToken: cancelToken)).roads;
}
- Future<String> testSearchRequest(String keyword,
- {bool shouldRethrow = false, CancelToken? cancelToken}) async {
- String queryURL =
- searchURL.replaceAll('@keyword', Uri.encodeQueryComponent(keyword));
- String htmlString;
- if (usePost) {
- Uri uri = Uri.parse(queryURL);
- Map<String, String> queryParams = uri.queryParameters;
- Uri postUri = Uri(
- scheme: uri.scheme,
- host: uri.host,
- path: uri.path,
- );
- var httpHeaders = {
- 'referer': '$baseUrl/',
- 'Content-Type': 'application/x-www-form-urlencoded',
- 'Accept-Language': getRandomAcceptedLanguage(),
- 'Connection': 'keep-alive',
- };
- htmlString = await _siteClient.postFormText(
- postUri.toString(),
- headers: httpHeaders,
- data: queryParams,
- cancelToken: cancelToken,
- );
- } else {
- var httpHeaders = {
- 'referer': '$baseUrl/',
- 'Accept-Language': getRandomAcceptedLanguage(),
- 'Connection': 'keep-alive',
- };
- htmlString = await _siteClient.getText(
- queryURL,
- headers: httpHeaders,
- cancelToken: cancelToken,
- );
- }
-
- return htmlString;
- }
-
- Future<String> _cookieHeaderFor(String url) async {
- if (!PluginCookieManager.instance.hasCookies(name)) return '';
- final uri = Uri.tryParse(url);
- if (uri == null) return '';
- try {
- final cookies =
- await PluginCookieManager.instance.getJar(name).loadForRequest(uri);
- if (cookies.isEmpty) return '';
- return cookies.map((c) => '${c.name}=${c.value}').join('; ');
- } catch (_) {
- return '';
- }
- }
-
- bool detectsCaptchaChallenge(String htmlString, {Element? htmlElement}) {
- if (!antiCrawlerConfig.enabled) return false;
-
- final detectValue = antiCrawlerConfig.captchaDetectValue.trim();
- if (detectValue.isNotEmpty) {
- switch (antiCrawlerConfig.captchaDetectType) {
- case CaptchaDetectType.text:
- return htmlString.contains(detectValue);
- case CaptchaDetectType.regex:
- try {
- return RegExp(detectValue, caseSensitive: false, dotAll: true)
- .hasMatch(htmlString);
- } catch (e) {
- KazumiLogger()
- .w('Plugin: $name invalid captcha detect regex: $detectValue');
- return false;
- }
- case CaptchaDetectType.xpath:
- default:
- final element = htmlElement ?? parse(htmlString).documentElement!;
- return element.queryXPath(detectValue).node != null;
- }
- }
-
- final element = htmlElement ?? parse(htmlString).documentElement!;
- final List<String> detectionXpaths = [
- antiCrawlerConfig.captchaImage,
- antiCrawlerConfig.captchaButton,
- ].where((x) => x.isNotEmpty).toList();
- return detectionXpaths
- .any((xpath) => element.queryXPath(xpath).node != null);
+ @Deprecated('Use queryChapterRoads instead.')
+ Future<List<Road>> querychapterRoads(
+ String source, {
+ RuleCancelToken? cancelToken,
+ }) {
+ return queryChapterRoads(source, cancelToken: cancelToken);
}
String buildFullUrl(String urlItem) {
- if (urlItem.contains(baseUrl) ||
- urlItem.contains(baseUrl.replaceAll('https', 'http'))) {
- return urlItem;
- }
- return baseUrl + urlItem;
+ return normalizeEpisodeUrl(baseUrl, urlItem);
}
+ /// Headers used when resolving or downloading the final media resource.
Map<String, String> buildHttpHeaders() {
return {
'user-agent': userAgent.isEmpty ? getRandomUA() : userAgent,
if (referer.isNotEmpty) 'referer': referer,
};
}
-
- PluginSearchResponse testQueryBangumi(String htmlString) {
- List<SearchItem> searchItems = [];
- var htmlElement = parse(htmlString).documentElement!;
- htmlElement.queryXPath(searchList).nodes.forEach((element) {
- try {
- SearchItem searchItem = SearchItem(
- name: element.queryXPath(searchName).node!.text?.trim() ?? '',
- src: element.queryXPath(searchResult).node!.attributes['href'] ?? '',
- );
- searchItems.add(searchItem);
- KazumiLogger().i(
- 'Plugin: $name ${element.queryXPath(searchName).node!.text ?? ''} $baseUrl${element.queryXPath(searchResult).node!.attributes['href'] ?? ''}');
- } catch (_) {}
- });
- PluginSearchResponse pluginSearchResponse =
- PluginSearchResponse(pluginName: name, data: searchItems);
- return pluginSearchResponse;
- }
}
diff --git a/lib/request/clients/plugin_site_client.dart b/lib/request/clients/plugin_site_client.dart
index 04a66afd..be037830 100644
--- a/lib/request/clients/plugin_site_client.dart
+++ b/lib/request/clients/plugin_site_client.dart
@@ -8,42 +8,23 @@ class PluginSiteClient {
static final PluginSiteClient instance = PluginSiteClient._();
- Future<String> getText(
+ Future<String> requestText(
String url, {
+ required String method,
Map<String, dynamic> headers = const {},
- CancelToken? cancelToken,
- }) async {
- try {
- final response = await DioFactory.pluginDio.get<String>(
- url,
- options: Options(
- responseType: ResponseType.plain,
- headers: _headers(headers),
- ),
- cancelToken: cancelToken,
- );
- return response.data ?? '';
- } on DioException catch (e) {
- throw await NetworkErrorMapper.mapException(e);
- }
- }
-
- Future<String> postFormText(
- String url, {
+ Map<String, dynamic> queryParameters = const {},
Object? data,
- Map<String, dynamic> headers = const {},
CancelToken? cancelToken,
}) async {
try {
- final response = await DioFactory.pluginDio.post<String>(
+ final response = await DioFactory.pluginDio.request<String>(
url,
+ queryParameters: queryParameters,
data: data,
options: Options(
+ method: method,
responseType: ResponseType.plain,
- headers: _headers({
- 'Content-Type': 'application/x-www-form-urlencoded',
- ...headers,
- }),
+ headers: _headers(headers),
),
cancelToken: cancelToken,
);
diff --git a/lib/request/config/api_endpoints.dart b/lib/request/config/api_endpoints.dart
index b0a111ce..b2d2bb1b 100644
--- a/lib/request/config/api_endpoints.dart
+++ b/lib/request/config/api_endpoints.dart
@@ -3,7 +3,7 @@ class ApiEndpoints {
static const String version = '2.1.8';
/// 规则API级别
- static const int apiLevel = 7;
+ static const int apiLevel = 8;
/// 项目主页
static const String projectUrl = "https://kazumi.app/";
diff --git a/lib/services/plugin/api_rule_engine.dart b/lib/services/plugin/api_rule_engine.dart
new file mode 100644
index 00000000..c007bc26
--- /dev/null
+++ b/lib/services/plugin/api_rule_engine.dart
@@ -0,0 +1,3 @@
+export 'api_rule_strategy.dart';
+export 'rule_engine.dart';
+export 'rule_engine_models.dart';
diff --git a/lib/services/plugin/api_rule_strategy.dart b/lib/services/plugin/api_rule_strategy.dart
new file mode 100644
index 00000000..d0f0e8d6
--- /dev/null
+++ b/lib/services/plugin/api_rule_strategy.dart
@@ -0,0 +1,539 @@
+import 'dart:convert';
+
+import 'package:json_path/json_path.dart';
+import 'package:kazumi/modules/roads/road_module.dart';
+import 'package:kazumi/modules/search/plugin_search_module.dart';
+import 'package:kazumi/plugins/api_rule_config.dart';
+import 'package:kazumi/services/plugin/rule_engine_models.dart';
+import 'package:kazumi/utils/episode_url.dart';
+
+class ApiRuleFormatException implements Exception {
+ const ApiRuleFormatException(this.message);
+
+ final String message;
+
+ @override
+ String toString() => 'ApiRuleFormatException: $message';
+}
+
+class RestrictedJsonPath {
+ const RestrictedJsonPath._();
+
+ static void validate(String expression) {
+ if (expression.isEmpty || !expression.startsWith(r'$')) {
+ throw ApiRuleFormatException('JSONPath 必须以 \$ 开头: $expression');
+ }
+ var index = 1;
+ while (index < expression.length) {
+ final char = expression[index];
+ if (char == '.') {
+ index++;
+ final start = index;
+ while (index < expression.length &&
+ RegExp(r'[A-Za-z0-9_$-]').hasMatch(expression[index])) {
+ index++;
+ }
+ if (index == start) {
+ throw ApiRuleFormatException('不支持的 JSONPath: $expression');
+ }
+ continue;
+ }
+ if (char == '[') {
+ final end = _findBracketEnd(expression, index);
+ final content = expression.substring(index + 1, end).trim();
+ final isIndex = RegExp(r'^\d+$').hasMatch(content);
+ final isWildcard = content == '*';
+ final isQuoted = content.length >= 2 &&
+ ((content.startsWith("'") && content.endsWith("'")) ||
+ (content.startsWith('"') && content.endsWith('"')));
+ if (!isIndex && !isWildcard && !isQuoted) {
+ throw ApiRuleFormatException('不支持的 JSONPath 片段: [$content]');
+ }
+ index = end + 1;
+ continue;
+ }
+ throw ApiRuleFormatException('不支持的 JSONPath: $expression');
+ }
+ }
+
+ static int _findBracketEnd(String expression, int start) {
+ String? quote;
+ var escaped = false;
+ for (var i = start + 1; i < expression.length; i++) {
+ final char = expression[i];
+ if (escaped) {
+ escaped = false;
+ continue;
+ }
+ if (char == '\\') {
+ escaped = true;
+ continue;
+ }
+ if (quote != null) {
+ if (char == quote) quote = null;
+ continue;
+ }
+ if (char == "'" || char == '"') {
+ quote = char;
+ continue;
+ }
+ if (char == ']') return i;
+ }
+ throw ApiRuleFormatException('JSONPath 缺少 ]: $expression');
+ }
+
+ static List<Object?> read(dynamic document, String expression) {
+ validate(expression);
+ try {
+ return JsonPath(expression).readValues(document).toList();
+ } catch (error) {
+ throw ApiRuleFormatException('JSONPath 解析失败 $expression: $error');
+ }
+ }
+
+ static Object? readFirst(dynamic document, String expression) {
+ final values = read(document, expression);
+ return values.isEmpty ? null : values.first;
+ }
+}
+
+/// Executes API request templates and parses supported JSON response shapes.
+class ApiRuleStrategy {
+ const ApiRuleStrategy();
+
+ dynamic decodeResponse(String raw) {
+ try {
+ return jsonDecode(raw);
+ } on FormatException catch (error) {
+ throw ApiRuleFormatException('API 响应不是有效 JSON: ${error.message}');
+ }
+ }
+
+ PreparedRuleRequest prepareRequest(
+ ApiRequestConfig config,
+ Map<String, Object?> variables,
+ ) {
+ final method = config.method.toUpperCase();
+ if (method != 'GET' && method != 'POST') {
+ throw ApiRuleFormatException('仅支持 GET/POST,当前为 $method');
+ }
+ if (config.url.trim().isEmpty) {
+ throw const ApiRuleFormatException('API 请求 URL 不能为空');
+ }
+ final url = _renderTemplate(config.url.trim(), variables, encode: true);
+ final uri = Uri.tryParse(url);
+ if (uri == null || !uri.hasScheme || uri.host.isEmpty) {
+ throw ApiRuleFormatException('API 请求 URL 无效: $url');
+ }
+ final hasBody = method == 'POST' && config.bodyType != ApiBodyType.none;
+ return PreparedRuleRequest(
+ method: method,
+ url: url,
+ headers: _renderMap(config.headers, variables),
+ query: _renderMap(config.query, variables),
+ bodyType: config.bodyType,
+ body: hasBody ? _renderValue(config.body, variables) : null,
+ includeCookies: true,
+ );
+ }
+
+ RuleSearchParseResult parseSearch(String raw, ApiSearchConfig config) {
+ RestrictedJsonPath.validate(config.listPath);
+ RestrictedJsonPath.validate(config.namePath);
+ RestrictedJsonPath.validate(config.sourcePath);
+ final document = decodeResponse(raw);
+ final nodes = RestrictedJsonPath.read(document, config.listPath);
+ final results = <SearchItem>[];
+ final fragments = <String>[];
+ final diagnostics = <String>[];
+ for (var index = 0; index < nodes.length; index++) {
+ final node = nodes[index];
+ try {
+ final name = _stringValue(
+ RestrictedJsonPath.readFirst(node, config.namePath),
+ );
+ final source = _stringValue(
+ RestrictedJsonPath.readFirst(node, config.sourcePath),
+ );
+ if (name.isEmpty || source.isEmpty) {
+ diagnostics.add('搜索节点 $index 缺少名称或来源,已跳过');
+ continue;
+ }
+ results.add(SearchItem(name: name, src: source));
+ fragments.add(jsonEncode(node));
+ } on ApiRuleFormatException {
+ rethrow;
+ } catch (error) {
+ diagnostics.add('搜索节点 $index 解析失败: $error');
+ }
+ }
+ return RuleSearchParseResult(
+ items: results,
+ matchedFragments: fragments,
+ diagnostics: diagnostics,
+ );
+ }
+
+ RuleChapterParseResult parseChapters(
+ String raw,
+ ApiChapterConfig config, {
+ required String source,
+ required String baseUrl,
+ }) {
+ _validateChapterConfig(config);
+ final document = decodeResponse(raw);
+ final rootVariables = <String, Object?>{'source': source};
+ for (final entry in config.variables.entries) {
+ final value = RestrictedJsonPath.readFirst(document, entry.value);
+ if (value == null) {
+ throw ApiRuleFormatException(
+ '章节响应变量 ${entry.key} 未匹配到值: ${entry.value}',
+ );
+ }
+ rootVariables[entry.key] = value;
+ }
+ final diagnostics = <String>[];
+ final roads = config.format == ApiChapterFormat.delimited
+ ? _parseDelimited(
+ document,
+ config,
+ rootVariables,
+ baseUrl,
+ diagnostics,
+ )
+ : _parseNested(
+ document,
+ config,
+ rootVariables,
+ baseUrl,
+ diagnostics,
+ );
+ final fragments = config.format == ApiChapterFormat.delimited
+ ? <String>[raw]
+ : _chapterFragments(document, config);
+ return RuleChapterParseResult(
+ roads: roads,
+ matchedFragments: fragments,
+ diagnostics: diagnostics,
+ );
+ }
+
+ List<String> _chapterFragments(
+ dynamic document,
+ ApiChapterConfig config,
+ ) {
+ if (config.roadsPath.trim().isEmpty) return <String>[jsonEncode(document)];
+ return RestrictedJsonPath.read(document, config.roadsPath)
+ .map(jsonEncode)
+ .toList();
+ }
+
+ List<Road> _parseNested(
+ dynamic document,
+ ApiChapterConfig config,
+ Map<String, Object?> rootVariables,
+ String baseUrl,
+ List<String> diagnostics,
+ ) {
+ final hasRoads = config.roadsPath.trim().isNotEmpty;
+ final roadNodes = hasRoads
+ ? RestrictedJsonPath.read(document, config.roadsPath)
+ : <Object?>[document];
+ final roads = <Road>[];
+ for (var roadIndex = 0; roadIndex < roadNodes.length; roadIndex++) {
+ final roadNode = roadNodes[roadIndex];
+ try {
+ final roadName = hasRoads && config.roadNamePath.trim().isNotEmpty
+ ? _stringValue(
+ RestrictedJsonPath.readFirst(roadNode, config.roadNamePath),
+ )
+ : '';
+ final episodeNodes = RestrictedJsonPath.read(
+ roadNode,
+ config.episodesPath,
+ );
+ final urls = <String>[];
+ final names = <String>[];
+ for (var episodeIndex = 0;
+ episodeIndex < episodeNodes.length;
+ episodeIndex++) {
+ try {
+ final episodeNode = episodeNodes[episodeIndex];
+ final episodeName = _stringValue(
+ RestrictedJsonPath.readFirst(
+ episodeNode,
+ config.episodeNamePath,
+ ),
+ );
+ final rawUrl = config.episodeUrlPath.trim().isEmpty
+ ? ''
+ : _stringValue(
+ RestrictedJsonPath.readFirst(
+ episodeNode,
+ config.episodeUrlPath,
+ ),
+ );
+ final pageUrl = _resolveEpisodeUrl(
+ config,
+ rootVariables,
+ rawUrl: rawUrl,
+ roadIndex: roadIndex,
+ episodeIndex: episodeIndex,
+ baseUrl: baseUrl,
+ );
+ if (pageUrl.isEmpty) {
+ diagnostics.add(
+ '线路 $roadIndex 的剧集节点 $episodeIndex 缺少 URL,已跳过',
+ );
+ continue;
+ }
+ urls.add(pageUrl);
+ names.add(
+ episodeName.isEmpty ? '第${episodeIndex + 1}集' : episodeName,
+ );
+ } on ApiRuleFormatException {
+ rethrow;
+ } catch (error) {
+ diagnostics.add(
+ '线路 $roadIndex 的剧集节点 $episodeIndex 解析失败: $error',
+ );
+ }
+ }
+ if (urls.isEmpty) {
+ diagnostics.add('线路节点 $roadIndex 没有有效剧集,已跳过');
+ continue;
+ }
+ roads.add(
+ Road(
+ name: roadName.isEmpty
+ ? '${config.defaultRoadName}${roads.length + 1}'
+ : roadName,
+ data: urls,
+ identifier: names,
+ ),
+ );
+ } on ApiRuleFormatException {
+ rethrow;
+ } catch (error) {
+ diagnostics.add('线路节点 $roadIndex 解析失败: $error');
+ }
+ }
+ return roads;
+ }
+
+ List<Road> _parseDelimited(
+ dynamic document,
+ ApiChapterConfig config,
+ Map<String, Object?> rootVariables,
+ String baseUrl,
+ List<String> diagnostics,
+ ) {
+ final namesValue = _stringValue(
+ RestrictedJsonPath.readFirst(document, config.roadNamesPath),
+ );
+ final episodesValue = _stringValue(
+ RestrictedJsonPath.readFirst(document, config.roadEpisodesPath),
+ );
+ if (episodesValue.isEmpty) return <Road>[];
+ final roadNames = namesValue.split(config.roadSeparator);
+ final roadGroups = episodesValue.split(config.roadSeparator);
+ final roads = <Road>[];
+ for (var roadIndex = 0; roadIndex < roadGroups.length; roadIndex++) {
+ final urls = <String>[];
+ final names = <String>[];
+ final entries = roadGroups[roadIndex].split(config.episodeSeparator);
+ for (var episodeIndex = 0;
+ episodeIndex < entries.length;
+ episodeIndex++) {
+ final entry = entries[episodeIndex].trim();
+ if (entry.isEmpty) continue;
+ final separatorIndex = entry.indexOf(config.fieldSeparator);
+ if (separatorIndex < 0) {
+ diagnostics.add(
+ '线路 $roadIndex 的剧集条目 $episodeIndex 缺少字段分隔符,已跳过',
+ );
+ continue;
+ }
+ final name = entry.substring(0, separatorIndex).trim();
+ final rawUrl = entry
+ .substring(separatorIndex + config.fieldSeparator.length)
+ .trim();
+ try {
+ final pageUrl = _resolveEpisodeUrl(
+ config,
+ rootVariables,
+ rawUrl: rawUrl,
+ roadIndex: roadIndex,
+ episodeIndex: episodeIndex,
+ baseUrl: baseUrl,
+ );
+ if (pageUrl.isEmpty) {
+ diagnostics.add(
+ '线路 $roadIndex 的剧集条目 $episodeIndex 缺少 URL,已跳过',
+ );
+ continue;
+ }
+ urls.add(pageUrl);
+ names.add(name.isEmpty ? '第${episodeIndex + 1}集' : name);
+ } on ApiRuleFormatException {
+ rethrow;
+ } catch (error) {
+ diagnostics.add(
+ '线路 $roadIndex 的剧集条目 $episodeIndex 解析失败: $error',
+ );
+ }
+ }
+ if (urls.isEmpty) {
+ diagnostics.add('线路 $roadIndex 没有有效剧集,已跳过');
+ continue;
+ }
+ final configuredName =
+ roadIndex < roadNames.length ? roadNames[roadIndex].trim() : '';
+ roads.add(
+ Road(
+ name: configuredName.isEmpty
+ ? '${config.defaultRoadName}${roads.length + 1}'
+ : configuredName,
+ data: urls,
+ identifier: names,
+ ),
+ );
+ }
+ return roads;
+ }
+
+ String _resolveEpisodeUrl(
+ ApiChapterConfig config,
+ Map<String, Object?> rootVariables, {
+ required String rawUrl,
+ required int roadIndex,
+ required int episodeIndex,
+ required String baseUrl,
+ }) {
+ final page = config.episodePage;
+ if (page == null) return normalizeEpisodeUrl(baseUrl, rawUrl);
+ if (page.url.trim().isEmpty) {
+ throw const ApiRuleFormatException('播放页地址模板不能为空');
+ }
+ final variables = <String, Object?>{
+ ...rootVariables,
+ 'episodeUrl': rawUrl,
+ 'roadIndex': roadIndex,
+ 'roadNumber': roadIndex + 1,
+ 'episodeIndex': episodeIndex,
+ 'episodeNumber': episodeIndex + 1,
+ };
+ final path = _renderTemplate(page.url, variables, encode: true);
+ final uri = Uri.tryParse(path);
+ if (uri == null) {
+ throw ApiRuleFormatException('剧集页面 URL 无效: $path');
+ }
+ final renderedQuery = _renderMap(page.query, variables).map(
+ (key, value) => MapEntry(key, value.toString()),
+ );
+ final mergedQuery = <String, String>{
+ ...uri.queryParameters,
+ ...renderedQuery,
+ };
+ return normalizeEpisodeUrl(
+ baseUrl,
+ uri.replace(queryParameters: mergedQuery).toString(),
+ );
+ }
+
+ void _validateChapterConfig(ApiChapterConfig config) {
+ for (final path in config.variables.values) {
+ RestrictedJsonPath.validate(path);
+ }
+ if (config.format == ApiChapterFormat.delimited) {
+ RestrictedJsonPath.validate(config.roadNamesPath);
+ RestrictedJsonPath.validate(config.roadEpisodesPath);
+ if (config.roadSeparator.isEmpty ||
+ config.episodeSeparator.isEmpty ||
+ config.fieldSeparator.isEmpty) {
+ throw const ApiRuleFormatException('章节分隔符不能为空');
+ }
+ return;
+ }
+
+ if (config.roadsPath.trim().isNotEmpty) {
+ RestrictedJsonPath.validate(config.roadsPath);
+ }
+ if (config.roadNamePath.trim().isNotEmpty) {
+ RestrictedJsonPath.validate(config.roadNamePath);
+ }
+ RestrictedJsonPath.validate(config.episodesPath);
+ RestrictedJsonPath.validate(config.episodeNamePath);
+ if (config.episodeUrlPath.trim().isNotEmpty) {
+ RestrictedJsonPath.validate(config.episodeUrlPath);
+ } else if (config.episodePage == null) {
+ throw const ApiRuleFormatException(
+ '必须配置播放入口地址路径或播放页地址模板',
+ );
+ }
+ if (config.episodePage != null && config.episodePage!.url.trim().isEmpty) {
+ throw const ApiRuleFormatException('播放页地址模板不能为空');
+ }
+ }
+
+ Map<String, dynamic> _renderMap(
+ Map<String, dynamic> input,
+ Map<String, Object?> variables,
+ ) {
+ return input.map(
+ (key, value) => MapEntry(
+ _renderTemplate(key, variables),
+ _renderValue(value, variables),
+ ),
+ );
+ }
+
+ dynamic _renderValue(dynamic value, Map<String, Object?> variables) {
+ if (value is String) {
+ final exact = RegExp(r'^@([A-Za-z_][A-Za-z0-9_]*)$').firstMatch(value);
+ if (exact != null) {
+ final name = exact.group(1)!;
+ if (!variables.containsKey(name)) {
+ throw ApiRuleFormatException('缺少模板变量 @$name');
+ }
+ return variables[name];
+ }
+ return _renderTemplate(value, variables);
+ }
+ if (value is List) {
+ return value.map((item) => _renderValue(item, variables)).toList();
+ }
+ if (value is Map) {
+ return value.map(
+ (key, item) => MapEntry(
+ key.toString(),
+ _renderValue(item, variables),
+ ),
+ );
+ }
+ return value;
+ }
+
+ String _renderTemplate(
+ String template,
+ Map<String, Object?> variables, {
+ bool encode = false,
+ }) {
+ return template.replaceAllMapped(
+ RegExp(r'(?<![A-Za-z0-9_])@([A-Za-z_][A-Za-z0-9_]*)'),
+ (match) {
+ final name = match.group(1)!;
+ if (!variables.containsKey(name)) {
+ throw ApiRuleFormatException('缺少模板变量 @$name');
+ }
+ final value = variables[name]?.toString() ?? '';
+ return encode ? Uri.encodeComponent(value) : value;
+ },
+ );
+ }
+
+ String _stringValue(Object? value) {
+ if (value == null) return '';
+ return value is String ? value.trim() : value.toString();
+ }
+}
diff --git a/lib/services/plugin/captcha_verification_service.dart b/lib/services/plugin/captcha_verification_service.dart
index a0fb9f83..bc3f9f6f 100644
--- a/lib/services/plugin/captcha_verification_service.dart
+++ b/lib/services/plugin/captcha_verification_service.dart
@@ -10,21 +10,21 @@ import 'package:kazumi/webview/captcha/captcha_webview_controller.dart';
///
/// **类型1:图片验证码**([loadForCaptcha] + [submitCaptcha])
/// 1. 初始化 WebView
-/// 2. 加载搜索页面,注入 JS 脚本监听验证码图片
+/// 2. 加载 XPath 搜索页面并监听验证码图片
/// 3. 通过 [onCaptchaImageUrl] 流将验证码图片 URL 暴露给 UI
/// 4. UI 将用户输入的验证码传给 [submitCaptcha]
-/// 5. 页面通过 AJAX 提交验证码
+/// 5. 在页面中填写验证码并点击提交按钮
/// 6. 验证码图片消失后,获取页面 Cookie 并保存到 [PluginCookieManager]
/// 7. UI 发起重新检索
///
/// **类型2:自动点击验证按钮**([loadForButtonClick])
/// 1. 初始化 WebView
-/// 2. 加载搜索页面,注入 JS 脚本轮询验证按钮
+/// 2. 加载 XPath 搜索页面并监听验证按钮
/// 3. 检测到按钮后自动模拟点击
/// 4. 按钮消失或页面跳转时,获取页面 Cookie 并保存到 [PluginCookieManager]
/// 5. 通过 [onVerified] 回调通知 UI 发起重新检索
///
-/// **类型3:自定义 JS 验证**([loadForCustomScript])
+/// **类型3:自定义 JavaScript 验证**([loadForCustomScript])
/// 1. 初始化 WebView
/// 2. 加载搜索页面,注入规则中配置的 JS 验证脚本
/// 3. 脚本调用 KazumiCaptcha.clicked/done 或返回 true 后完成验证
@@ -233,8 +233,6 @@ class CaptchaVerificationService {
await controller.unloadPage();
}
- Stream<String>? get onLog => _controller?.onLog;
-
void dispose() {
if (_disposed) return;
_disposed = true;
diff --git a/lib/services/plugin/plugin_cookie_manager.dart b/lib/services/plugin/plugin_cookie_manager.dart
index 33b10c25..5c16de60 100644
--- a/lib/services/plugin/plugin_cookie_manager.dart
+++ b/lib/services/plugin/plugin_cookie_manager.dart
@@ -5,7 +5,7 @@ import 'package:kazumi/services/logging/logger.dart';
///
/// 为每条规则维护一个独立的内存 [CookieJar],
/// 通过 [saveFromWebView] 将 WebView 捕获的 document.cookie 字符串
-/// 解析后存入对应规则的 jar,用于后续 HTTP 请求的 CookieManager 拦截器。
+/// 解析后存入对应规则的 jar。规则请求执行器按需读取并组装 Cookie 请求头。
/// Cookie 仅在当前 App 会话内有效,重启后需重新验证。
class PluginCookieManager {
PluginCookieManager._();
@@ -13,7 +13,7 @@ class PluginCookieManager {
final Map<String, CookieJar> _jars = {};
- CookieJar getJar(String pluginName) {
+ CookieJar _getJar(String pluginName) {
return _jars.putIfAbsent(pluginName, () => CookieJar());
}
@@ -23,7 +23,7 @@ class PluginCookieManager {
final uri = Uri.tryParse(pageUrl);
if (uri == null) return;
- final jar = getJar(pluginName);
+ final jar = _getJar(pluginName);
final cookies = _parseCookieString(cookieString, uri);
if (cookies.isEmpty) return;
@@ -52,11 +52,12 @@ class PluginCookieManager {
return cookies;
}
- void clearCookies(String pluginName) {
- _jars.remove(pluginName);
- }
-
- bool hasCookies(String pluginName) {
- return _jars.containsKey(pluginName);
+ Future<List<Cookie>> loadForRequest(
+ String pluginName,
+ Uri uri,
+ ) async {
+ final jar = _jars[pluginName];
+ if (jar == null) return <Cookie>[];
+ return jar.loadForRequest(uri);
}
}
diff --git a/lib/services/plugin/plugin_search_service.dart b/lib/services/plugin/plugin_search_service.dart
index 2a44386d..0f9c74b8 100644
--- a/lib/services/plugin/plugin_search_service.dart
+++ b/lib/services/plugin/plugin_search_service.dart
@@ -1,8 +1,6 @@
-import 'dart:async';
-import 'package:kazumi/modules/search/plugin_search_module.dart';
-import 'package:kazumi/plugins/plugins.dart';
import 'package:flutter_modular/flutter_modular.dart';
import 'package:kazumi/pages/info/info_controller.dart';
+import 'package:kazumi/plugins/plugins.dart';
import 'package:kazumi/plugins/plugins_controller.dart';
import 'package:kazumi/services/logging/logger.dart';
@@ -13,110 +11,75 @@ class PluginSearchService {
final InfoController infoController;
final PluginsController pluginsController = Modular.get<PluginsController>();
- StreamController? _controller;
bool _isCancelled = false;
Future<void> querySource(String keyword, String pluginName) async {
- for (PluginSearchResponse pluginSearchResponse
- in infoController.pluginSearchResponseList) {
- if (pluginSearchResponse.pluginName == pluginName) {
- infoController.pluginSearchResponseList.remove(pluginSearchResponse);
- break;
- }
- }
+ infoController.pluginSearchResponseList.removeWhere(
+ (response) => response.pluginName == pluginName,
+ );
if (infoController.pluginSearchStatus.containsKey(pluginName)) {
infoController.pluginSearchStatus[pluginName] = 'pending';
}
- for (Plugin plugin in pluginsController.pluginList) {
+ for (final plugin in pluginsController.pluginList) {
if (plugin.name == pluginName) {
- plugin.queryBangumi(keyword, shouldRethrow: true).then((result) {
- if (_isCancelled) {
- return;
- }
-
- infoController.pluginSearchStatus[plugin.name] = 'success';
- if (result.data.isNotEmpty) {
- pluginsController.validityTracker.markSearchValid(plugin.name);
- }
- infoController.pluginSearchResponseList.add(result);
- }).catchError((error) {
- if (_isCancelled) {
- return;
- }
-
- if (error is CaptchaRequiredException) {
- KazumiLogger().w(
- 'PluginSearchService: captcha required for ${error.pluginName}');
- infoController.pluginSearchStatus[error.pluginName] = 'captcha';
- } else if (error is NoResultException) {
- KazumiLogger()
- .i('PluginSearchService: no results for ${error.pluginName}');
- infoController.pluginSearchStatus[error.pluginName] = 'noResult';
- } else {
- final name =
- error is SearchErrorException ? error.pluginName : plugin.name;
- KazumiLogger().w('PluginSearchService: search error for $name');
- infoController.pluginSearchStatus[name] = 'error';
- }
- });
+ await _queryPlugin(plugin, keyword);
+ return;
}
}
}
Future<void> queryAllSource(String keyword) async {
- _controller = StreamController();
infoController.pluginSearchResponseList.clear();
- for (Plugin plugin in pluginsController.pluginList) {
+ final plugins = List<Plugin>.of(pluginsController.pluginList);
+ for (final plugin in plugins) {
infoController.pluginSearchStatus[plugin.name] = 'pending';
}
+ await Future.wait(
+ plugins.map((plugin) => _queryPlugin(plugin, keyword)),
+ );
+ }
- for (Plugin plugin in pluginsController.pluginList) {
+ Future<void> _queryPlugin(Plugin plugin, String keyword) async {
+ if (_isCancelled) return;
+ try {
+ final result = await plugin.queryBangumi(
+ keyword,
+ shouldRethrow: true,
+ );
if (_isCancelled) return;
-
- plugin.queryBangumi(keyword, shouldRethrow: true).then((result) {
- if (_isCancelled) {
- return;
- }
-
- infoController.pluginSearchStatus[plugin.name] = 'success';
- if (result.data.isNotEmpty) {
- pluginsController.validityTracker.markSearchValid(plugin.name);
- }
- _controller?.add(result);
- }).catchError((error) {
- if (_isCancelled) {
- return;
- }
-
- if (error is CaptchaRequiredException) {
- KazumiLogger().w(
- 'PluginSearchService: captcha required for ${error.pluginName}');
- infoController.pluginSearchStatus[error.pluginName] = 'captcha';
- } else if (error is NoResultException) {
- KazumiLogger()
- .i('PluginSearchService: no results for ${error.pluginName}');
- infoController.pluginSearchStatus[error.pluginName] = 'noResult';
- } else {
- final name =
- error is SearchErrorException ? error.pluginName : plugin.name;
- KazumiLogger().w('PluginSearchService: search error for $name');
- infoController.pluginSearchStatus[name] = 'error';
- }
- });
+ infoController.pluginSearchStatus[plugin.name] = 'success';
+ if (result.data.isNotEmpty) {
+ pluginsController.validityTracker.markSearchValid(plugin.name);
+ }
+ infoController.pluginSearchResponseList.add(result);
+ } catch (error) {
+ if (_isCancelled) return;
+ _handleSearchError(plugin, error);
}
+ }
- await for (var result in _controller!.stream) {
- if (_isCancelled) break;
-
- infoController.pluginSearchResponseList.add(result);
+ void _handleSearchError(Plugin plugin, Object error) {
+ if (error is CaptchaRequiredException) {
+ KazumiLogger().i(
+ 'PluginSearchService: captcha required for ${error.pluginName}',
+ );
+ infoController.pluginSearchStatus[error.pluginName] = 'captcha';
+ return;
}
+ if (error is NoResultException) {
+ KazumiLogger().i(
+ 'PluginSearchService: no results for ${error.pluginName}',
+ );
+ infoController.pluginSearchStatus[error.pluginName] = 'noResult';
+ return;
+ }
+ final name = error is SearchErrorException ? error.pluginName : plugin.name;
+ KazumiLogger().w('PluginSearchService: search error for $name');
+ infoController.pluginSearchStatus[name] = 'error';
}
void cancel() {
_isCancelled = true;
- if (_controller != null && !_controller!.isClosed) {
- _controller!.close();
- }
}
}
diff --git a/lib/services/plugin/rule_engine.dart b/lib/services/plugin/rule_engine.dart
new file mode 100644
index 00000000..c92c43d7
--- /dev/null
+++ b/lib/services/plugin/rule_engine.dart
@@ -0,0 +1,258 @@
+import 'package:dio/dio.dart';
+import 'package:kazumi/modules/search/plugin_search_module.dart';
+import 'package:kazumi/plugins/api_rule_config.dart';
+import 'package:kazumi/request/clients/plugin_site_client.dart';
+import 'package:kazumi/request/core/network_exception.dart';
+import 'package:kazumi/services/logging/logger.dart';
+import 'package:kazumi/services/plugin/api_rule_strategy.dart';
+import 'package:kazumi/services/plugin/plugin_cookie_manager.dart';
+import 'package:kazumi/services/plugin/rule_engine_models.dart';
+import 'package:kazumi/services/plugin/xpath_rule_strategy.dart';
+
+abstract interface class RuleRequestExecutor {
+ Future<String> execute(
+ PreparedRuleRequest request,
+ RuleExecutionConfig config, {
+ CancelToken? cancelToken,
+ });
+}
+
+class RuleEngine {
+ RuleEngine({
+ RuleRequestExecutor? requestExecutor,
+ ApiRuleStrategy apiStrategy = const ApiRuleStrategy(),
+ XPathRuleStrategy xpathStrategy = const XPathRuleStrategy(),
+ bool logFailures = true,
+ }) : _requestExecutor = requestExecutor ?? _DefaultRuleRequestExecutor(),
+ _apiStrategy = apiStrategy,
+ _xpathStrategy = xpathStrategy,
+ _logFailures = logFailures;
+
+ final RuleRequestExecutor _requestExecutor;
+ final ApiRuleStrategy _apiStrategy;
+ final XPathRuleStrategy _xpathStrategy;
+ final bool _logFailures;
+
+ Future<RuleSearchTrace> search(
+ RuleExecutionConfig config,
+ String keyword, {
+ CancelToken? cancelToken,
+ }) async {
+ late final PreparedRuleRequest request;
+ try {
+ request = config.searchMode == RuleMode.api
+ ? _apiStrategy.prepareRequest(
+ config.searchApiConfig.request,
+ <String, Object?>{'keyword': keyword},
+ )
+ : _xpathStrategy.prepareSearchRequest(config, keyword);
+ } catch (error, stackTrace) {
+ _logFailure(config, 'search request preparation', error, stackTrace);
+ throw SearchErrorException(
+ config.pluginName,
+ cause: error,
+ kind: RuleFailureKind.parse,
+ );
+ }
+
+ final raw = await _executeRequest(
+ request,
+ config,
+ phase: 'search request',
+ wrapError: (error) => SearchErrorException(
+ config.pluginName,
+ cause: error,
+ kind: RuleFailureKind.request,
+ ),
+ cancelToken: cancelToken,
+ );
+ try {
+ final parsed = config.searchMode == RuleMode.api
+ ? _apiStrategy.parseSearch(raw, config.searchApiConfig)
+ : _xpathStrategy.parseSearch(raw, config);
+ if (parsed.items.isEmpty) {
+ throw NoResultException(config.pluginName);
+ }
+ return RuleSearchTrace(
+ rawResponse: raw,
+ response: PluginSearchResponse(
+ pluginName: config.pluginName,
+ data: parsed.items,
+ ),
+ matchedFragments: parsed.matchedFragments,
+ diagnostics: parsed.diagnostics,
+ );
+ } on CaptchaRequiredException {
+ rethrow;
+ } on NoResultException {
+ rethrow;
+ } catch (error, stackTrace) {
+ if (_isCancellation(error)) rethrow;
+ _logFailure(config, 'search response parsing', error, stackTrace);
+ throw SearchErrorException(
+ config.pluginName,
+ cause: error,
+ kind: RuleFailureKind.parse,
+ );
+ }
+ }
+
+ Future<RuleChapterTrace> queryChapters(
+ RuleExecutionConfig config,
+ String source, {
+ CancelToken? cancelToken,
+ }) async {
+ late final PreparedRuleRequest request;
+ try {
+ request = config.chapterMode == RuleMode.api
+ ? _apiStrategy.prepareRequest(
+ config.chapterApiConfig.request,
+ <String, Object?>{'source': source},
+ )
+ : _xpathStrategy.prepareChapterRequest(config, source);
+ } catch (error, stackTrace) {
+ _logFailure(config, 'chapter request preparation', error, stackTrace);
+ throw ChapterErrorException(
+ config.pluginName,
+ cause: error,
+ kind: RuleFailureKind.parse,
+ );
+ }
+
+ final raw = await _executeRequest(
+ request,
+ config,
+ phase: 'chapter request',
+ wrapError: (error) => ChapterErrorException(
+ config.pluginName,
+ cause: error,
+ kind: RuleFailureKind.request,
+ ),
+ cancelToken: cancelToken,
+ );
+ try {
+ final parsed = config.chapterMode == RuleMode.api
+ ? _apiStrategy.parseChapters(
+ raw,
+ config.chapterApiConfig,
+ source: source,
+ baseUrl: config.baseUrl,
+ )
+ : _xpathStrategy.parseChapters(raw, config);
+ if (parsed.roads.isEmpty) {
+ throw ChapterErrorException(
+ config.pluginName,
+ kind: RuleFailureKind.noResult,
+ );
+ }
+ return RuleChapterTrace(
+ rawResponse: raw,
+ roads: parsed.roads,
+ matchedFragments: parsed.matchedFragments,
+ diagnostics: parsed.diagnostics,
+ );
+ } on ChapterErrorException {
+ rethrow;
+ } catch (error, stackTrace) {
+ if (_isCancellation(error)) rethrow;
+ _logFailure(config, 'chapter response parsing', error, stackTrace);
+ throw ChapterErrorException(
+ config.pluginName,
+ cause: error,
+ kind: RuleFailureKind.parse,
+ );
+ }
+ }
+
+ Future<String> _executeRequest(
+ PreparedRuleRequest request,
+ RuleExecutionConfig config, {
+ required String phase,
+ required Object Function(Object error) wrapError,
+ CancelToken? cancelToken,
+ }) async {
+ try {
+ return await _requestExecutor.execute(
+ request,
+ config,
+ cancelToken: cancelToken,
+ );
+ } catch (error, stackTrace) {
+ if (_isCancellation(error)) rethrow;
+ _logFailure(config, phase, error, stackTrace);
+ throw wrapError(error);
+ }
+ }
+
+ bool _isCancellation(Object error) {
+ return error is NetworkException &&
+ error.type == NetworkExceptionType.cancel;
+ }
+
+ void _logFailure(
+ RuleExecutionConfig config,
+ String phase,
+ Object error,
+ StackTrace stackTrace,
+ ) {
+ if (!_logFailures) return;
+ KazumiLogger().w(
+ 'Plugin: ${config.pluginName} $phase failed',
+ error: error,
+ stackTrace: stackTrace,
+ );
+ }
+}
+
+class _DefaultRuleRequestExecutor implements RuleRequestExecutor {
+ @override
+ Future<String> execute(
+ PreparedRuleRequest request,
+ RuleExecutionConfig config, {
+ CancelToken? cancelToken,
+ }) async {
+ final cookieHeader = request.includeCookies
+ ? await _cookieHeaderFor(config.pluginName, request.url)
+ : '';
+ final headers = <String, dynamic>{
+ 'referer': '${config.baseUrl}/',
+ if (cookieHeader.isNotEmpty) 'Cookie': cookieHeader,
+ ...request.headers,
+ };
+ if (request.method == 'POST') {
+ switch (request.bodyType) {
+ case ApiBodyType.json:
+ headers.putIfAbsent('Content-Type', () => 'application/json');
+ break;
+ case ApiBodyType.form:
+ headers.putIfAbsent(
+ 'Content-Type',
+ () => 'application/x-www-form-urlencoded',
+ );
+ break;
+ }
+ }
+ return PluginSiteClient.instance.requestText(
+ request.url,
+ method: request.method,
+ headers: headers,
+ queryParameters: request.query,
+ data: request.method == 'POST' ? request.body : null,
+ cancelToken: cancelToken,
+ );
+ }
+
+ Future<String> _cookieHeaderFor(String pluginName, String url) async {
+ final uri = Uri.tryParse(url);
+ if (uri == null) return '';
+ try {
+ final cookies =
+ await PluginCookieManager.instance.loadForRequest(pluginName, uri);
+ return cookies
+ .map((cookie) => '${cookie.name}=${cookie.value}')
+ .join('; ');
+ } catch (_) {
+ return '';
+ }
+ }
+}
diff --git a/lib/services/plugin/rule_engine_models.dart b/lib/services/plugin/rule_engine_models.dart
new file mode 100644
index 00000000..6ca2366f
--- /dev/null
+++ b/lib/services/plugin/rule_engine_models.dart
@@ -0,0 +1,175 @@
+import 'package:dio/dio.dart';
+import 'package:kazumi/modules/roads/road_module.dart';
+import 'package:kazumi/modules/search/plugin_search_module.dart';
+import 'package:kazumi/plugins/anti_crawler_config.dart';
+import 'package:kazumi/plugins/api_rule_config.dart';
+
+typedef RuleCancelToken = CancelToken;
+
+enum RuleFailureKind {
+ request,
+ parse,
+ noResult,
+}
+
+class CaptchaRequiredException implements Exception {
+ const CaptchaRequiredException(this.pluginName);
+
+ final String pluginName;
+
+ @override
+ String toString() =>
+ 'CaptchaRequiredException: $pluginName requires captcha verification';
+}
+
+class NoResultException implements Exception {
+ const NoResultException(this.pluginName);
+
+ final String pluginName;
+
+ @override
+ String toString() =>
+ 'NoResultException: $pluginName returned no search results';
+}
+
+class SearchErrorException implements Exception {
+ const SearchErrorException(
+ this.pluginName, {
+ this.cause,
+ this.kind = RuleFailureKind.parse,
+ });
+
+ final String pluginName;
+ final Object? cause;
+ final RuleFailureKind kind;
+
+ @override
+ String toString() =>
+ 'SearchErrorException: $pluginName search failed${cause != null ? ' ($cause)' : ''}';
+}
+
+class ChapterErrorException implements Exception {
+ const ChapterErrorException(
+ this.pluginName, {
+ this.cause,
+ this.kind = RuleFailureKind.parse,
+ });
+
+ final String pluginName;
+ final Object? cause;
+ final RuleFailureKind kind;
+
+ @override
+ String toString() => 'ChapterErrorException: $pluginName chapter query failed'
+ '${cause != null ? ' ($cause)' : ''}';
+}
+
+/// Immutable runtime snapshot built from a plugin rule.
+///
+/// Playback-only headers such as the rule's User-Agent and Referer are
+/// deliberately excluded. API requests can provide their own static headers.
+class RuleExecutionConfig {
+ const RuleExecutionConfig({
+ required this.pluginName,
+ required this.baseUrl,
+ required this.usePost,
+ required this.searchMode,
+ required this.chapterMode,
+ required this.searchUrl,
+ required this.searchList,
+ required this.searchName,
+ required this.searchResult,
+ required this.chapterRoads,
+ required this.chapterResult,
+ required this.searchApiConfig,
+ required this.chapterApiConfig,
+ required this.antiCrawlerConfig,
+ });
+
+ final String pluginName;
+ final String baseUrl;
+ final bool usePost;
+ final String searchMode;
+ final String chapterMode;
+ final String searchUrl;
+ final String searchList;
+ final String searchName;
+ final String searchResult;
+ final String chapterRoads;
+ final String chapterResult;
+ final ApiSearchConfig searchApiConfig;
+ final ApiChapterConfig chapterApiConfig;
+ final AntiCrawlerConfig antiCrawlerConfig;
+}
+
+class PreparedRuleRequest {
+ const PreparedRuleRequest({
+ required this.method,
+ required this.url,
+ this.headers = const <String, dynamic>{},
+ this.query = const <String, dynamic>{},
+ this.bodyType = ApiBodyType.none,
+ this.body,
+ this.includeCookies = false,
+ });
+
+ final String method;
+ final String url;
+ final Map<String, dynamic> headers;
+ final Map<String, dynamic> query;
+ final String bodyType;
+ final Object? body;
+ final bool includeCookies;
+}
+
+class RuleSearchParseResult {
+ const RuleSearchParseResult({
+ required this.items,
+ this.matchedFragments = const <String>[],
+ this.diagnostics = const <String>[],
+ });
+
+ final List<SearchItem> items;
+ final List<String> matchedFragments;
+ final List<String> diagnostics;
+}
+
+class RuleChapterParseResult {
+ const RuleChapterParseResult({
+ required this.roads,
+ this.matchedFragments = const <String>[],
+ this.diagnostics = const <String>[],
+ });
+
+ final List<Road> roads;
+ final List<String> matchedFragments;
+ final List<String> diagnostics;
+}
+
+class RuleSearchTrace {
+ const RuleSearchTrace({
+ required this.rawResponse,
+ required this.response,
+ required this.matchedFragments,
+ required this.diagnostics,
+ });
+
+ final String rawResponse;
+ final PluginSearchResponse response;
+ final List<String> matchedFragments;
+ final List<String> diagnostics;
+}
+
+class RuleChapterTrace {
+ const RuleChapterTrace({
+ required this.rawResponse,
+ required this.roads,
+ required this.matchedFragments,
+ required this.diagnostics,
+ });
+
+ final String rawResponse;
+ final List<Road> roads;
+ final List<String> matchedFragments;
+ final List<String> diagnostics;
+}
diff --git a/lib/services/plugin/xpath_rule_strategy.dart b/lib/services/plugin/xpath_rule_strategy.dart
new file mode 100644
index 00000000..54618096
--- /dev/null
+++ b/lib/services/plugin/xpath_rule_strategy.dart
@@ -0,0 +1,334 @@
+import 'package:html/dom.dart';
+import 'package:html/parser.dart';
+import 'package:kazumi/modules/roads/road_module.dart';
+import 'package:kazumi/modules/search/plugin_search_module.dart';
+import 'package:kazumi/plugins/anti_crawler_config.dart';
+import 'package:kazumi/services/plugin/rule_engine_models.dart';
+import 'package:kazumi/utils/episode_url.dart';
+import 'package:xpath_selector_html_parser/xpath_selector_html_parser.dart';
+
+enum XPathRuleFormatKind {
+ invalidUrl,
+ invalidDocument,
+ invalidSelector,
+}
+
+enum XPathRuleField {
+ searchList,
+ searchName,
+ searchResult,
+ chapterRoads,
+ chapterResult,
+ captchaDetectValue,
+ captchaImage,
+ captchaButton,
+}
+
+class XPathRuleFormatException implements Exception {
+ const XPathRuleFormatException(
+ this.message, {
+ required this.kind,
+ this.field,
+ this.expression,
+ this.cause,
+ });
+
+ final String message;
+ final XPathRuleFormatKind kind;
+ final XPathRuleField? field;
+ final String? expression;
+ final Object? cause;
+
+ @override
+ String toString() => 'XPathRuleFormatException.${kind.name}: $message'
+ '${cause == null ? '' : ' ($cause)'}';
+}
+
+class XPathRuleStrategy {
+ const XPathRuleStrategy();
+
+ PreparedRuleRequest prepareSearchRequest(
+ RuleExecutionConfig config,
+ String keyword,
+ ) {
+ final queryUrl = config.searchUrl.replaceAll(
+ '@keyword',
+ Uri.encodeQueryComponent(keyword),
+ );
+ final uri = Uri.tryParse(queryUrl);
+ if (uri == null || !uri.hasScheme || uri.host.isEmpty) {
+ throw XPathRuleFormatException(
+ '搜索 URL 无效: $queryUrl',
+ kind: XPathRuleFormatKind.invalidUrl,
+ );
+ }
+ if (!config.usePost) {
+ return PreparedRuleRequest(
+ method: 'GET',
+ url: queryUrl,
+ includeCookies: true,
+ );
+ }
+ return PreparedRuleRequest(
+ method: 'POST',
+ url: uri.replace(query: null).toString(),
+ bodyType: 'form',
+ body: uri.queryParameters,
+ includeCookies: true,
+ );
+ }
+
+ PreparedRuleRequest prepareChapterRequest(
+ RuleExecutionConfig config,
+ String source,
+ ) {
+ final url = normalizeEpisodeUrl(config.baseUrl, source);
+ final uri = Uri.tryParse(url);
+ if (uri == null || !uri.hasScheme || uri.host.isEmpty) {
+ throw XPathRuleFormatException(
+ '章节 URL 无效: $url',
+ kind: XPathRuleFormatKind.invalidUrl,
+ );
+ }
+ return PreparedRuleRequest(method: 'GET', url: url);
+ }
+
+ RuleSearchParseResult parseSearch(
+ String raw,
+ RuleExecutionConfig config,
+ ) {
+ final root = _documentElement(raw);
+ if (detectsCaptchaChallenge(
+ raw,
+ config.antiCrawlerConfig,
+ htmlElement: root,
+ )) {
+ throw CaptchaRequiredException(config.pluginName);
+ }
+
+ final items = <SearchItem>[];
+ final fragments = <String>[];
+ final diagnostics = <String>[];
+ final nodes = _runSelector(
+ XPathRuleField.searchList,
+ config.searchList,
+ () => root.queryXPath(config.searchList).nodes,
+ );
+ for (var index = 0; index < nodes.length; index++) {
+ final node = nodes[index];
+ try {
+ final name = _runSelector(
+ XPathRuleField.searchName,
+ config.searchName,
+ () => node.queryXPath(config.searchName).node,
+ )?.text?.trim() ??
+ '';
+ final source = _runSelector(
+ XPathRuleField.searchResult,
+ config.searchResult,
+ () => node.queryXPath(config.searchResult).node,
+ )?.attributes['href']?.trim() ??
+ '';
+ if (name.isEmpty || source.isEmpty) {
+ diagnostics.add('搜索节点 $index 缺少名称或来源,已跳过');
+ continue;
+ }
+ items.add(SearchItem(name: name, src: source));
+ fragments.add(_fragment(node.node));
+ } on XPathRuleFormatException {
+ rethrow;
+ } catch (error) {
+ diagnostics.add('搜索节点 $index 解析失败: $error');
+ }
+ }
+ return RuleSearchParseResult(
+ items: items,
+ matchedFragments: fragments,
+ diagnostics: diagnostics,
+ );
+ }
+
+ RuleChapterParseResult parseChapters(
+ String raw,
+ RuleExecutionConfig config,
+ ) {
+ final root = _documentElement(raw);
+ final roads = <Road>[];
+ final fragments = <String>[];
+ final diagnostics = <String>[];
+ final roadNodes = _runSelector(
+ XPathRuleField.chapterRoads,
+ config.chapterRoads,
+ () => root.queryXPath(config.chapterRoads).nodes,
+ );
+ for (var roadIndex = 0; roadIndex < roadNodes.length; roadIndex++) {
+ final roadNode = roadNodes[roadIndex];
+ fragments.add(_fragment(roadNode.node));
+ try {
+ final urls = <String>[];
+ final names = <String>[];
+ final episodeNodes = _runSelector(
+ XPathRuleField.chapterResult,
+ config.chapterResult,
+ () => roadNode.queryXPath(config.chapterResult).nodes,
+ );
+ for (var episodeIndex = 0;
+ episodeIndex < episodeNodes.length;
+ episodeIndex++) {
+ try {
+ final episode = episodeNodes[episodeIndex].node;
+ final source = episode.attributes['href']?.trim() ?? '';
+ if (source.isEmpty) {
+ diagnostics.add(
+ '线路 $roadIndex 的剧集节点 $episodeIndex 缺少 URL,已跳过',
+ );
+ continue;
+ }
+ final name = (episode.text ?? '').replaceAll(RegExp(r'\s+'), '');
+ urls.add(normalizeEpisodeUrl(config.baseUrl, source));
+ names.add(name.isEmpty ? '第${episodeIndex + 1}集' : name);
+ } catch (error) {
+ diagnostics.add(
+ '线路 $roadIndex 的剧集节点 $episodeIndex 解析失败: $error',
+ );
+ }
+ }
+ if (urls.isEmpty) {
+ diagnostics.add('线路 $roadIndex 没有有效剧集,已跳过');
+ continue;
+ }
+ roads.add(
+ Road(
+ name: '播放线路${roads.length + 1}',
+ data: urls,
+ identifier: names,
+ ),
+ );
+ } on XPathRuleFormatException {
+ rethrow;
+ } catch (error) {
+ diagnostics.add('线路节点 $roadIndex 解析失败: $error');
+ }
+ }
+ return RuleChapterParseResult(
+ roads: roads,
+ matchedFragments: fragments,
+ diagnostics: diagnostics,
+ );
+ }
+
+ bool detectsCaptchaChallenge(
+ String raw,
+ AntiCrawlerConfig config, {
+ Element? htmlElement,
+ }) {
+ if (!config.enabled) return false;
+ final detectValue = config.captchaDetectValue.trim();
+ if (detectValue.isNotEmpty) {
+ switch (config.captchaDetectType) {
+ case CaptchaDetectType.text:
+ return raw.contains(detectValue);
+ case CaptchaDetectType.regex:
+ try {
+ return RegExp(
+ detectValue,
+ caseSensitive: false,
+ dotAll: true,
+ ).hasMatch(raw);
+ } on FormatException {
+ return false;
+ }
+ case CaptchaDetectType.xpath:
+ default:
+ final root = htmlElement ?? _documentElement(raw);
+ return _runSelector(
+ XPathRuleField.captchaDetectValue,
+ detectValue,
+ () => root.queryXPath(detectValue).node,
+ ) !=
+ null;
+ }
+ }
+
+ final root = htmlElement ?? _documentElement(raw);
+ final fallbackSelectors = <(XPathRuleField, String)>[
+ (XPathRuleField.captchaImage, config.captchaImage),
+ (XPathRuleField.captchaButton, config.captchaButton),
+ ];
+ for (final (field, expression) in fallbackSelectors) {
+ if (expression.trim().isEmpty) continue;
+ final node = _runSelector(
+ field,
+ expression,
+ () => root.queryXPath(expression).node,
+ );
+ if (node != null) return true;
+ }
+ return false;
+ }
+
+ Element _documentElement(String raw) {
+ try {
+ final element = parse(raw).documentElement;
+ if (element == null) {
+ throw const XPathRuleFormatException(
+ 'HTML 响应没有根节点',
+ kind: XPathRuleFormatKind.invalidDocument,
+ );
+ }
+ return element;
+ } on XPathRuleFormatException {
+ rethrow;
+ } catch (error) {
+ throw XPathRuleFormatException(
+ 'HTML 响应解析失败',
+ kind: XPathRuleFormatKind.invalidDocument,
+ cause: error,
+ );
+ }
+ }
+
+ T _runSelector<T>(
+ XPathRuleField field,
+ String expression,
+ T Function() query,
+ ) {
+ final label = _fieldLabel(field);
+ if (expression.trim().isEmpty) {
+ throw XPathRuleFormatException(
+ '$label XPath 不能为空',
+ kind: XPathRuleFormatKind.invalidSelector,
+ field: field,
+ expression: expression,
+ );
+ }
+ try {
+ return query();
+ } catch (error) {
+ throw XPathRuleFormatException(
+ '$label XPath 无效: $expression',
+ kind: XPathRuleFormatKind.invalidSelector,
+ field: field,
+ expression: expression,
+ cause: error,
+ );
+ }
+ }
+
+ String _fieldLabel(XPathRuleField field) {
+ return switch (field) {
+ XPathRuleField.searchList => '搜索结果列表',
+ XPathRuleField.searchName => '条目名称',
+ XPathRuleField.searchResult => '条目链接',
+ XPathRuleField.chapterRoads => '播放线路列表',
+ XPathRuleField.chapterResult => '剧集列表',
+ XPathRuleField.captchaDetectValue => '验证页检测',
+ XPathRuleField.captchaImage => '验证码图片',
+ XPathRuleField.captchaButton => '验证按钮',
+ };
+ }
+
+ String _fragment(Node node) {
+ return node is Element ? node.outerHtml : node.text ?? '';
+ }
+}
diff --git a/pubspec.lock b/pubspec.lock
index df73ee44..c78800f9 100644
--- a/pubspec.lock
+++ b/pubspec.lock
@@ -816,6 +816,14 @@ packages:
url: "https://pub.dev"
source: hosted
version: "1.0.5"
+ iregexp:
+ dependency: transitive
+ description:
+ name: iregexp
+ sha256: c79119931b7ae9c0b6327adaa4495811813fcae7e6236ac68c15f45ca857d38b
+ url: "https://pub.dev"
+ source: hosted
+ version: "0.2.0"
isolate_channel:
dependency: transitive
description:
@@ -856,6 +864,14 @@ packages:
url: "https://pub.dev"
source: hosted
version: "4.12.0"
+ json_path:
+ dependency: "direct main"
+ description:
+ name: json_path
+ sha256: "99cef94ca7b604ad85b9442bc8852e55396f559c08c0ab961d10b90b730c326f"
+ url: "https://pub.dev"
+ source: hosted
+ version: "0.9.0"
leak_tracker:
dependency: transitive
description:
@@ -920,6 +936,14 @@ packages:
url: "https://pub.dev"
source: hosted
version: "0.13.0"
+ maybe_just_nothing:
+ dependency: transitive
+ description:
+ name: maybe_just_nothing
+ sha256: "57af3cacbbe57d5889a4479983755b76551db3c8862aa6335f57f50657945054"
+ url: "https://pub.dev"
+ source: hosted
+ version: "0.6.0"
media_kit:
dependency: "direct main"
description:
@@ -1297,6 +1321,14 @@ packages:
url: "https://pub.dev"
source: hosted
version: "2.2.0"
+ rfc_6901:
+ dependency: transitive
+ description:
+ name: rfc_6901
+ sha256: "6a43b1858dca2febaf93e15639aa6b0c49ccdfd7647775f15a499f872b018154"
+ url: "https://pub.dev"
+ source: hosted
+ version: "0.2.1"
rxdart:
dependency: transitive
description:
diff --git a/pubspec.yaml b/pubspec.yaml
index c5ca9145..8ab05098 100644
--- a/pubspec.yaml
+++ b/pubspec.yaml
@@ -77,6 +77,7 @@ dependencies:
window_manager: ^0.5.1
xpath_selector: ^3.0.2
xpath_selector_html_parser: ^3.0.1
+ json_path: ^0.9.0
canvas_danmaku: ^0.3.1
webdav_client: ^1.2.2
diff --git a/test/api_rule_engine_test.dart b/test/api_rule_engine_test.dart
new file mode 100644
index 00000000..8d8df01f
--- /dev/null
+++ b/test/api_rule_engine_test.dart
@@ -0,0 +1,257 @@
+import 'dart:convert';
+
+import 'package:flutter_test/flutter_test.dart';
+import 'package:kazumi/plugins/api_rule_config.dart';
+import 'package:kazumi/services/plugin/api_rule_engine.dart';
+
+void main() {
+ const engine = ApiRuleStrategy();
+
+ group('RestrictedJsonPath', () {
+ test('allows fields, quoted fields, indexes and wildcards', () {
+ for (final path in [
+ r'$',
+ r'$.data.videos[*]',
+ r"$['data']['play-sources'][0]",
+ ]) {
+ expect(() => RestrictedJsonPath.validate(path), returnsNormally);
+ }
+ });
+
+ test('rejects filters, recursive descent and expressions', () {
+ for (final path in [
+ r'$..videos',
+ r'$.videos[?(@.enabled)]',
+ r'$.videos[0:2]',
+ r'$.videos.length()',
+ ]) {
+ expect(
+ () => RestrictedJsonPath.validate(path),
+ throwsA(isA<ApiRuleFormatException>()),
+ );
+ }
+ });
+ });
+
+ test('prepares typed request placeholders', () {
+ final request = engine.prepareRequest(
+ ApiRequestConfig(
+ method: 'post',
+ url: 'https://example.com/videos/@source',
+ headers: {'X-Keyword': '@keyword'},
+ query: {'q': '@keyword', 'page': 1},
+ bodyType: ApiBodyType.json,
+ body: {
+ 'source': '@source',
+ 'label': 'video-@source',
+ },
+ ),
+ {'source': 'a/b', 'keyword': '测试'},
+ );
+
+ expect(request.method, 'POST');
+ expect(request.url, 'https://example.com/videos/a%2Fb');
+ expect(request.headers['X-Keyword'], '测试');
+ expect(request.query, {'q': '测试', 'page': 1});
+ expect(request.body, {'source': 'a/b', 'label': 'video-a/b'});
+ });
+
+ test('ignores inactive request bodies for GET requests', () {
+ final request = engine.prepareRequest(
+ ApiRequestConfig(
+ method: 'GET',
+ url: 'https://example.com/search',
+ bodyType: ApiBodyType.json,
+ body: {'unused': '@missing'},
+ ),
+ const <String, Object?>{},
+ );
+
+ expect(request.body, isNull);
+ });
+
+ test('parses Liangzi search and delimited chapters', () {
+ const searchRaw = '''
+{
+ "code": 1,
+ "list": [
+ {"vod_id": 22639, "vod_name": "吞噬星空"}
+ ]
+}
+''';
+ final searchConfig = ApiSearchConfig(
+ listPath: r'$.list[*]',
+ namePath: r'$.vod_name',
+ sourcePath: r'$.vod_id',
+ );
+ final search = engine.parseSearch(searchRaw, searchConfig);
+ expect(search.items.single.name, '吞噬星空');
+ expect(search.items.single.src, '22639');
+
+ const chapterRaw = r'''
+{
+ "list": [{
+ "vod_play_from": "线路A$$$线路B",
+ "vod_play_url": "第01集$https://cdn-a.test/1.m3u8#第02集$https://cdn-a.test/2.m3u8$$$正片$https://cdn-b.test/main.m3u8"
+ }]
+}
+''';
+ final chapterConfig = ApiChapterConfig(
+ format: ApiChapterFormat.delimited,
+ roadNamesPath: r'$.list[0].vod_play_from',
+ roadEpisodesPath: r'$.list[0].vod_play_url',
+ );
+ final roads = engine.parseChapters(
+ chapterRaw,
+ chapterConfig,
+ source: '22639',
+ baseUrl: 'https://lzizy.net/',
+ );
+ expect(roads.roads, hasLength(2));
+ expect(roads.roads[0].name, '线路A');
+ expect(roads.roads[0].identifier, ['第01集', '第02集']);
+ expect(roads.roads[0].data[0], 'https://cdn-a.test/1.m3u8');
+ expect(roads.roads[1].name, '线路B');
+ expect(roads.roads[1].data.single, 'https://cdn-b.test/main.m3u8');
+ });
+
+ test('parses TvTFun chapters and constructs playback page URLs', () {
+ final raw = jsonEncode({
+ 'data': {
+ 'slug': '28431',
+ 'playSources': [
+ {
+ 'name': '线路C',
+ 'episodes': [
+ {'name': '第01集', 'url': 'protected'},
+ {'name': '第02集', 'url': 'protected'},
+ ],
+ },
+ {
+ 'name': '线路D',
+ 'episodes': [
+ {'name': '第01集', 'url': 'protected'},
+ ],
+ },
+ ],
+ },
+ });
+ final config = ApiChapterConfig(
+ roadsPath: r'$.data.playSources[*]',
+ roadNamePath: r'$.name',
+ episodesPath: r'$.episodes[*]',
+ episodeNamePath: r'$.name',
+ episodeUrlPath: '',
+ variables: {'slug': r'$.data.slug'},
+ episodePage: ApiEpisodePageConfig(
+ url: 'https://www.tvtfun.net/video/@slug/play',
+ query: {
+ 'source': '@roadIndex',
+ 'episode': '@episodeIndex',
+ },
+ ),
+ );
+ final roads = engine.parseChapters(
+ raw,
+ config,
+ source: 'cmp2x3ot91k1qi9m8zglverqd',
+ baseUrl: 'https://www.tvtfun.net/',
+ );
+
+ expect(roads.roads, hasLength(2));
+ expect(
+ roads.roads[0].data[1],
+ 'https://www.tvtfun.net/video/28431/play?source=0&episode=1',
+ );
+ expect(
+ roads.roads[1].data.single,
+ 'https://www.tvtfun.net/video/28431/play?source=1&episode=0',
+ );
+ });
+
+ test('skips malformed delimited episode entries', () {
+ const raw = r'''
+{"names":"线路","episodes":"损坏条目#第02集$https://cdn.test/2.m3u8"}
+''';
+ final roads = engine.parseChapters(
+ raw,
+ ApiChapterConfig(
+ format: ApiChapterFormat.delimited,
+ roadNamesPath: r'$.names',
+ roadEpisodesPath: r'$.episodes',
+ ),
+ source: 'id',
+ baseUrl: 'https://example.com/',
+ );
+ expect(roads.roads.single.identifier, ['第02集']);
+ expect(roads.diagnostics, hasLength(1));
+ });
+
+ test('keeps default nested road names gapless without changing source index',
+ () {
+ final raw = jsonEncode({
+ 'data': {
+ 'roads': [
+ {'episodes': <Object>[]},
+ {
+ 'episodes': [
+ {'name': '第01集'},
+ ],
+ },
+ ],
+ },
+ });
+ final result = engine.parseChapters(
+ raw,
+ ApiChapterConfig(
+ roadNamePath: '',
+ episodeUrlPath: '',
+ episodePage: ApiEpisodePageConfig(
+ url: '/play',
+ query: {'source': '@roadIndex'},
+ ),
+ ),
+ source: 'id',
+ baseUrl: 'https://example.com/',
+ );
+
+ expect(result.roads.single.name, '播放线路1');
+ expect(
+ result.roads.single.data.single,
+ 'https://example.com/play?source=1',
+ );
+ });
+
+ test('keeps default delimited road names gapless', () {
+ const raw = r'''
+{"names":"$$$","episodes":"损坏条目$$$第01集$https://cdn.test/1.m3u8"}
+''';
+ final result = engine.parseChapters(
+ raw,
+ ApiChapterConfig(
+ format: ApiChapterFormat.delimited,
+ roadNamesPath: r'$.names',
+ roadEpisodesPath: r'$.episodes',
+ ),
+ source: 'id',
+ baseUrl: 'https://example.com/',
+ );
+
+ expect(result.roads.single.name, '播放线路1');
+ expect(result.roads.single.data.single, 'https://cdn.test/1.m3u8');
+ });
+
+ test('rejects invalid relative search paths before mapping entries', () {
+ expect(
+ () => engine.parseSearch(
+ '{"data":[{"name":"item","id":"1"}]}',
+ ApiSearchConfig(
+ listPath: r'$.data[*]',
+ namePath: r'$..name',
+ sourcePath: r'$.id',
+ ),
+ ),
+ throwsA(isA<ApiRuleFormatException>()),
+ );
+ });
+}
diff --git a/test/plugin_api_config_test.dart b/test/plugin_api_config_test.dart
new file mode 100644
index 00000000..549443a2
--- /dev/null
+++ b/test/plugin_api_config_test.dart
@@ -0,0 +1,137 @@
+import 'dart:convert';
+
+import 'package:flutter_test/flutter_test.dart';
+import 'package:kazumi/plugins/api_rule_config.dart';
+import 'package:kazumi/plugins/plugins.dart';
+import 'package:kazumi/utils/encoding.dart';
+
+void main() {
+ test('legacy plugin defaults to XPath modes', () {
+ final plugin = Plugin.fromJson(_legacyRule);
+ expect(plugin.searchMode, RuleMode.xpath);
+ expect(plugin.chapterMode, RuleMode.xpath);
+ });
+
+ test('legacy XPath POST setting survives JSON round trip', () {
+ final plugin = Plugin.fromJson({..._legacyRule, 'usePost': true});
+ final restored = Plugin.fromJson(plugin.toJson());
+
+ expect(plugin.usePost, isTrue);
+ expect(restored.usePost, isTrue);
+ expect(restored.searchMode, RuleMode.xpath);
+ });
+
+ test('API configuration survives JSON round trip', () {
+ final plugin = Plugin.fromJson({
+ ..._legacyRule,
+ 'searchMode': 'api',
+ 'chapterMode': 'api',
+ 'searchApiConfig': {
+ 'request': {
+ 'method': 'GET',
+ 'url': 'https://example.com/search',
+ 'query': {'q': '@keyword'},
+ },
+ 'listPath': r'$.data[*]',
+ 'namePath': r'$.name',
+ 'sourcePath': r'$.id',
+ },
+ 'chapterApiConfig': {
+ 'request': {
+ 'method': 'GET',
+ 'url': 'https://example.com/videos/@source',
+ },
+ 'format': 'nested',
+ 'roadsPath': r'$.data.roads[*]',
+ 'roadNamePath': r'$.name',
+ 'episodesPath': r'$.episodes[*]',
+ 'episodeNamePath': r'$.name',
+ 'episodeUrlPath': r'$.url',
+ },
+ });
+ final restored = Plugin.fromJson(plugin.toJson());
+
+ expect(restored.searchMode, RuleMode.api);
+ expect(restored.chapterMode, RuleMode.api);
+ expect(restored.searchApiConfig.request.query['q'], '@keyword');
+ expect(
+ restored.chapterApiConfig.request.url,
+ 'https://example.com/videos/@source',
+ );
+ });
+
+ test('API-only rule may omit legacy XPath fields', () {
+ final plugin = Plugin.fromJson({
+ 'api': '8',
+ 'name': 'api-only',
+ 'version': '1',
+ 'searchMode': RuleMode.api,
+ 'chapterMode': RuleMode.api,
+ 'searchApiConfig': {
+ 'request': {'url': 'https://example.com/search'},
+ },
+ 'chapterApiConfig': {
+ 'request': {'url': 'https://example.com/detail/@source'},
+ },
+ });
+
+ expect(plugin.searchURL, isEmpty);
+ expect(plugin.chapterRoads, isEmpty);
+ expect(plugin.searchMode, RuleMode.api);
+ });
+
+ test('kazumi link import and export preserves API rule configuration', () {
+ final plugin = Plugin.fromJson({
+ ..._legacyRule,
+ 'api': '8',
+ 'searchMode': RuleMode.api,
+ 'chapterMode': RuleMode.api,
+ 'searchApiConfig': {
+ 'request': {
+ 'method': 'GET',
+ 'url': 'https://example.com/search',
+ 'query': {'q': '@keyword'},
+ },
+ 'listPath': r'$.data[*]',
+ 'namePath': r'$.name',
+ 'sourcePath': r'$.id',
+ },
+ 'chapterApiConfig': {
+ 'request': {
+ 'method': 'GET',
+ 'url': 'https://example.com/detail/@source',
+ },
+ },
+ });
+
+ final link = jsonToKazumiBase64(jsonEncode(plugin.toJson()));
+ final restored = Plugin.fromJson(
+ jsonDecode(kazumiBase64ToJson(link)) as Map<String, dynamic>,
+ );
+
+ expect(restored.toJson(), plugin.toJson());
+ expect(restored.chapterApiConfig.request.method, 'GET');
+ });
+}
+
+final Map<String, dynamic> _legacyRule = {
+ 'api': '7',
+ 'type': 'anime',
+ 'name': 'legacy',
+ 'version': '1.0',
+ 'muliSources': true,
+ 'useWebview': true,
+ 'useNativePlayer': true,
+ 'usePost': false,
+ 'useLegacyParser': false,
+ 'adBlocker': false,
+ 'userAgent': '',
+ 'baseURL': 'https://example.com/',
+ 'searchURL': 'https://example.com/search?q=@keyword',
+ 'searchList': '//li',
+ 'searchName': '//a',
+ 'searchResult': '//a',
+ 'chapterRoads': '//ul',
+ 'chapterResult': '//a',
+ 'referer': '',
+};
diff --git a/test/rule_engine_test.dart b/test/rule_engine_test.dart
new file mode 100644
index 00000000..53d01d4a
--- /dev/null
+++ b/test/rule_engine_test.dart
@@ -0,0 +1,303 @@
+import 'dart:convert';
+
+import 'package:dio/dio.dart';
+import 'package:flutter_test/flutter_test.dart';
+import 'package:kazumi/plugins/anti_crawler_config.dart';
+import 'package:kazumi/plugins/api_rule_config.dart';
+import 'package:kazumi/request/core/network_exception.dart';
+import 'package:kazumi/services/plugin/rule_engine.dart';
+import 'package:kazumi/services/plugin/rule_engine_models.dart';
+import 'package:kazumi/services/plugin/xpath_rule_strategy.dart';
+
+void main() {
+ TestWidgetsFlutterBinding.ensureInitialized();
+
+ const xpathResponse = '''
+<html>
+ <article class="result"><h2><a href="/video/alpha">Alpha</a></h2></article>
+ <div class="road"><a href="/play/alpha-1">第1集</a></div>
+</html>
+''';
+ final apiSearchFixture = jsonEncode({
+ 'data': [
+ {'name': 'API result', 'id': 'api-id'},
+ ],
+ });
+ final apiChapterFixture = jsonEncode({
+ 'data': {
+ 'roads': [
+ {
+ 'name': 'API road',
+ 'episodes': [
+ {'name': 'Episode 1', 'url': '/api-play/1'},
+ ],
+ },
+ ],
+ },
+ });
+
+ for (final searchMode in [RuleMode.xpath, RuleMode.api]) {
+ for (final chapterMode in [RuleMode.xpath, RuleMode.api]) {
+ test('supports $searchMode search with $chapterMode chapters', () async {
+ final executor = _FakeExecutor([
+ searchMode == RuleMode.api ? apiSearchFixture : xpathResponse,
+ chapterMode == RuleMode.api ? apiChapterFixture : xpathResponse,
+ ]);
+ final engine = RuleEngine(
+ requestExecutor: executor,
+ logFailures: false,
+ );
+ final config = _config(
+ searchMode: searchMode,
+ chapterMode: chapterMode,
+ );
+
+ final search = await engine.search(config, 'test keyword');
+ final chapters = await engine.queryChapters(
+ config,
+ search.response.data.first.src,
+ );
+
+ expect(search.rawResponse, isNotEmpty);
+ expect(search.matchedFragments, isNotEmpty);
+ expect(search.diagnostics, isEmpty);
+ expect(chapters.rawResponse, isNotEmpty);
+ expect(chapters.matchedFragments, isNotEmpty);
+ expect(chapters.diagnostics, isEmpty);
+ expect(chapters.roads, isNotEmpty);
+ expect(executor.requests, hasLength(2));
+ });
+ }
+ }
+
+ test('API search never turns a non-JSON captcha page into captcha flow',
+ () async {
+ final engine = RuleEngine(
+ requestExecutor: _FakeExecutor(['<html>captcha</html>']),
+ logFailures: false,
+ );
+
+ await expectLater(
+ engine.search(
+ _config(
+ searchMode: RuleMode.api,
+ chapterMode: RuleMode.xpath,
+ antiCrawler: _antiCrawler(),
+ ),
+ 'keyword',
+ ),
+ throwsA(
+ isA<SearchErrorException>()
+ .having((error) => error.kind, 'kind', RuleFailureKind.parse),
+ ),
+ );
+ });
+
+ test('maps an empty relative search XPath to a typed parse error', () async {
+ final engine = RuleEngine(
+ requestExecutor: _FakeExecutor([xpathResponse]),
+ logFailures: false,
+ );
+
+ await expectLater(
+ engine.search(
+ _config(
+ searchMode: RuleMode.xpath,
+ chapterMode: RuleMode.xpath,
+ searchName: '',
+ ),
+ 'keyword',
+ ),
+ throwsA(
+ isA<SearchErrorException>()
+ .having((error) => error.kind, 'kind', RuleFailureKind.parse)
+ .having(
+ (error) => error.cause,
+ 'cause',
+ isA<XPathRuleFormatException>()
+ .having(
+ (error) => error.kind,
+ 'kind',
+ XPathRuleFormatKind.invalidSelector,
+ )
+ .having(
+ (error) => error.field,
+ 'field',
+ XPathRuleField.searchName,
+ ),
+ ),
+ ),
+ );
+ });
+
+ test('maps an empty chapter XPath to a typed parse error', () async {
+ final engine = RuleEngine(
+ requestExecutor: _FakeExecutor([xpathResponse]),
+ logFailures: false,
+ );
+
+ await expectLater(
+ engine.queryChapters(
+ _config(
+ searchMode: RuleMode.xpath,
+ chapterMode: RuleMode.xpath,
+ chapterResult: '',
+ ),
+ '/video/1',
+ ),
+ throwsA(
+ isA<ChapterErrorException>()
+ .having((error) => error.kind, 'kind', RuleFailureKind.parse)
+ .having(
+ (error) => error.cause,
+ 'cause',
+ isA<XPathRuleFormatException>()
+ .having(
+ (error) => error.kind,
+ 'kind',
+ XPathRuleFormatKind.invalidSelector,
+ )
+ .having(
+ (error) => error.field,
+ 'field',
+ XPathRuleField.chapterResult,
+ ),
+ ),
+ ),
+ );
+ });
+
+ test('chapter parsing never triggers the search captcha flow', () async {
+ final engine = RuleEngine(
+ requestExecutor: _FakeExecutor(['<html>captcha</html>']),
+ logFailures: false,
+ );
+
+ await expectLater(
+ engine.queryChapters(
+ _config(
+ searchMode: RuleMode.xpath,
+ chapterMode: RuleMode.xpath,
+ antiCrawler: _antiCrawler(),
+ ),
+ '/video/1',
+ ),
+ throwsA(isA<ChapterErrorException>()),
+ );
+ });
+
+ test('maps request failures to a typed request reason', () async {
+ final engine = RuleEngine(
+ requestExecutor: _FakeExecutor(
+ const [],
+ error: StateError('offline'),
+ ),
+ logFailures: false,
+ );
+
+ await expectLater(
+ engine.search(
+ _config(searchMode: RuleMode.api, chapterMode: RuleMode.api),
+ 'keyword',
+ ),
+ throwsA(
+ isA<SearchErrorException>()
+ .having((error) => error.kind, 'kind', RuleFailureKind.request),
+ ),
+ );
+ });
+
+ test('propagates cancellation without wrapping it', () async {
+ const cancellation = NetworkException(
+ type: NetworkExceptionType.cancel,
+ message: 'cancelled',
+ );
+ final engine = RuleEngine(
+ requestExecutor: _FakeExecutor(const [], error: cancellation),
+ logFailures: false,
+ );
+
+ await expectLater(
+ engine.search(
+ _config(searchMode: RuleMode.api, chapterMode: RuleMode.api),
+ 'keyword',
+ cancelToken: CancelToken(),
+ ),
+ throwsA(same(cancellation)),
+ );
+ });
+}
+
+class _FakeExecutor implements RuleRequestExecutor {
+ _FakeExecutor(List<String> responses, {this.error})
+ : _responses = List<String>.of(responses);
+
+ final List<String> _responses;
+ final Object? error;
+ final List<PreparedRuleRequest> requests = [];
+
+ @override
+ Future<String> execute(
+ PreparedRuleRequest request,
+ RuleExecutionConfig config, {
+ CancelToken? cancelToken,
+ }) async {
+ requests.add(request);
+ if (error != null) throw error!;
+ return _responses.removeAt(0);
+ }
+}
+
+RuleExecutionConfig _config({
+ required String searchMode,
+ required String chapterMode,
+ AntiCrawlerConfig? antiCrawler,
+ String searchName = '//h2/a',
+ String chapterResult = '//a',
+}) {
+ return RuleExecutionConfig(
+ pluginName: 'runtime-test',
+ baseUrl: 'https://example.com/',
+ usePost: false,
+ searchMode: searchMode,
+ chapterMode: chapterMode,
+ searchUrl: 'https://example.com/search?q=@keyword',
+ searchList: '//article[@class="result"]',
+ searchName: searchName,
+ searchResult: '//h2/a',
+ chapterRoads: '//div[@class="road"]',
+ chapterResult: chapterResult,
+ searchApiConfig: ApiSearchConfig(
+ request: ApiRequestConfig(
+ url: 'https://example.com/api/search',
+ query: {'q': '@keyword'},
+ ),
+ listPath: r'$.data[*]',
+ namePath: r'$.name',
+ sourcePath: r'$.id',
+ ),
+ chapterApiConfig: ApiChapterConfig(
+ request: ApiRequestConfig(
+ url: 'https://example.com/api/videos/@source',
+ ),
+ roadsPath: r'$.data.roads[*]',
+ roadNamePath: r'$.name',
+ episodesPath: r'$.episodes[*]',
+ episodeNamePath: r'$.name',
+ episodeUrlPath: r'$.url',
+ ),
+ antiCrawlerConfig: antiCrawler ?? AntiCrawlerConfig.empty(),
+ );
+}
+
+AntiCrawlerConfig _antiCrawler() {
+ return AntiCrawlerConfig(
+ enabled: true,
+ captchaType: CaptchaType.imageCaptcha,
+ captchaImage: '',
+ captchaInput: '',
+ captchaButton: '',
+ captchaDetectType: CaptchaDetectType.text,
+ captchaDetectValue: 'captcha',
+ );
+}