Skip to content

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

refactor(rules): surface parse diagnostics and trim speculative API rule

Prediditbf8235d44017
diff --git a/lib/pages/plugin_editor/plugin_editor_page.dart b/lib/pages/plugin_editor/plugin_editor_page.dart
index 284405a1..900cd228 100644
--- a/lib/pages/plugin_editor/plugin_editor_page.dart
+++ b/lib/pages/plugin_editor/plugin_editor_page.dart
@@ -56,7 +56,11 @@ abstract final class _RuleEditorText {
static const fieldSeparator = '名称与地址分隔符';
static const responseVariables = '响应变量(JSON:变量名 → JSONPath)';
static const playPageUrl = '播放页地址模板(URL,可选)';
+ static const playPageUrlHelper = '可用变量:@source、@episodeUrl、'
+ '@roadIndex/@episodeIndex(从 0 起)、@roadNumber/@episodeNumber(从 1 起)'
+ '及响应变量。';
static const playPageQuery = '播放页查询参数(JSON)';
+ static const playPageQueryHelper = '与地址模板可用变量相同,合并进最终 URL 的查询参数。';
static const userAgent = '用户代理(User-Agent)';
static const userAgentHelper = '仅用于播放器和下载器。';
@@ -886,10 +890,12 @@ class _PluginEditorPageState extends State<PluginEditorPage> {
_editorField(
chapterApiPageURLController,
_RuleEditorText.playPageUrl,
+ helper: _RuleEditorText.playPageUrlHelper,
),
_editorField(
chapterApiPageQueryController,
_RuleEditorText.playPageQuery,
+ helper: _RuleEditorText.playPageQueryHelper,
maxLines: 5,
),
];
@@ -1002,13 +1008,9 @@ class _PluginEditorPageState extends State<PluginEditorPage> {
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);
+ const ApiRuleStrategy()
+ ..prepareRequest(config.request, const {'keyword': 'test'})
+ ..validateSearchConfig(config);
return config;
}
@@ -1059,36 +1061,9 @@ class _PluginEditorPageState extends State<PluginEditorPage> {
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('章节分隔符不能为空');
- }
- }
+ const ApiRuleStrategy()
+ ..prepareRequest(config.request, const {'source': 'test'})
+ ..validateChapterConfig(config);
return config;
}
diff --git a/lib/pages/plugin_editor/plugin_test_page.dart b/lib/pages/plugin_editor/plugin_test_page.dart
index 9c9e23c2..eb5d012b 100644
--- a/lib/pages/plugin_editor/plugin_test_page.dart
+++ b/lib/pages/plugin_editor/plugin_test_page.dart
@@ -55,6 +55,8 @@ class _PluginTestPageState extends State<PluginTestPage> {
List<Road>? chapters;
bool isTesting = false;
String errorMsg = "";
+ List<String> searchDiagnostics = [];
+ List<String> chapterDiagnostics = [];
final Map<int, String> _itemFragmentMap = {};
int? _shownFragmentIndex;
@@ -102,6 +104,8 @@ class _PluginTestPageState extends State<PluginTestPage> {
searchRes = null;
chapters = null;
errorMsg = "";
+ searchDiagnostics = [];
+ chapterDiagnostics = [];
_itemFragmentMap.clear();
_shownFragmentIndex = null;
});
@@ -126,6 +130,7 @@ class _PluginTestPageState extends State<PluginTestPage> {
);
searchRaw = searchTrace.rawResponse;
searchRes = searchTrace.response;
+ searchDiagnostics = searchTrace.diagnostics;
_itemFragmentMap.addAll(searchTrace.matchedFragments.asMap());
if (_hasSearchData && _needChapterParse) {
final firstItem = searchRes!.data.first;
@@ -138,6 +143,7 @@ class _PluginTestPageState extends State<PluginTestPage> {
);
chapterRaw = chapterTrace.rawResponse;
chapters = chapterTrace.roads;
+ chapterDiagnostics = chapterTrace.diagnostics;
}
}
} catch (e, stack) {
@@ -325,7 +331,8 @@ class _PluginTestPageState extends State<PluginTestPage> {
}
if (subtitle.contains('失败') ||
subtitle.contains('无可用') ||
- subtitle.contains('无有效')) {
+ subtitle.contains('无有效') ||
+ subtitle.contains('跳过')) {
return theme.getCoreColor(CoreColorType.error);
}
return theme.getCoreColor(CoreColorType.success);
@@ -358,7 +365,9 @@ class _PluginTestPageState extends State<PluginTestPage> {
if (isTesting && _shownFragmentIndex == null) return '解析中...';
if (!_hasSearchRaw) return '未执行解析';
if (!_hasSearchData) return '未解析到结果';
- return '解析到 ${searchRes?.data.length ?? 0} 条结果';
+ final skipped =
+ searchDiagnostics.isEmpty ? '' : ',跳过 ${searchDiagnostics.length} 条';
+ return '解析到 ${searchRes?.data.length ?? 0} 条结果$skipped';
}
Widget _buildParseContent(ThemeData theme) {
@@ -367,6 +376,7 @@ class _PluginTestPageState extends State<PluginTestPage> {
if (!_hasSearchData) return _buildEmpty('未解析到搜索结果', theme, isError: true);
return Column(children: [
+ _buildDiagnosticsWidget(searchDiagnostics, theme),
ListView.builder(
shrinkWrap: true,
physics: const NeverScrollableScrollPhysics(),
@@ -378,6 +388,44 @@ class _PluginTestPageState extends State<PluginTestPage> {
]);
}
+ /// Nodes the rule skipped during parsing; empty when every node matched.
+ Widget _buildDiagnosticsWidget(List<String> diagnostics, ThemeData theme) {
+ if (diagnostics.isEmpty) return const SizedBox.shrink();
+ return Container(
+ width: double.infinity,
+ margin: const EdgeInsets.only(bottom: 8.0),
+ padding: const EdgeInsets.all(12.0),
+ decoration: BoxDecoration(
+ color: theme.colorScheme.errorContainer,
+ border: Border.all(color: theme.getCoreColor(CoreColorType.error)),
+ borderRadius: BorderRadius.circular(8),
+ ),
+ child: Column(
+ crossAxisAlignment: CrossAxisAlignment.start,
+ children: [
+ Row(children: [
+ Icon(Icons.warning_amber_outlined,
+ color: theme.getCoreColor(CoreColorType.error), size: 20),
+ const SizedBox(width: 8.0),
+ Text('部分节点被跳过(${diagnostics.length})',
+ style: theme.textTheme.bodyMedium?.copyWith(
+ color: theme.colorScheme.onErrorContainer,
+ fontWeight: FontWeight.w500)),
+ ]),
+ _h8,
+ ...diagnostics.map(
+ (message) => Padding(
+ padding: const EdgeInsets.only(bottom: 4.0),
+ child: SelectableText(message,
+ style: theme.textTheme.bodySmall?.copyWith(
+ color: theme.colorScheme.onErrorContainer)),
+ ),
+ ),
+ ],
+ ),
+ );
+ }
+
Widget _buildSearchItemCard(SearchItem item, int i, ThemeData theme) {
final isShowingFragment = _shownFragmentIndex == i;
final fragment = _itemFragmentMap[i] ?? '无匹配片段';
@@ -446,7 +494,9 @@ class _PluginTestPageState extends State<PluginTestPage> {
if (!_hasSearchData) return '无有效搜索结果';
if (!_needChapterParse) return '无需解析章节';
if (chapters == null) return '未获取章节数据';
- return '获取到 ${chapters?.length ?? 0} 个播放线路';
+ final skipped =
+ chapterDiagnostics.isEmpty ? '' : ',跳过 ${chapterDiagnostics.length} 条';
+ return '获取到 ${chapters?.length ?? 0} 个播放线路$skipped';
}
Widget _buildChapterContent(ThemeData theme) {
@@ -458,6 +508,7 @@ class _PluginTestPageState extends State<PluginTestPage> {
return Column(
children: [
+ _buildDiagnosticsWidget(chapterDiagnostics, theme),
if (chapterRaw.isNotEmpty)
Container(
margin: const EdgeInsets.only(bottom: 8),
diff --git a/lib/plugins/api_rule_config.dart b/lib/plugins/api_rule_config.dart
index 4213d32a..4267ae86 100644
--- a/lib/plugins/api_rule_config.dart
+++ b/lib/plugins/api_rule_config.dart
@@ -62,9 +62,9 @@ class ApiRequestConfig {
Map<String, dynamic> toJson() => {
'method': method.toUpperCase(),
'url': url,
- 'headers': headers,
- 'query': query,
- 'bodyType': bodyType,
+ if (headers.isNotEmpty) 'headers': headers,
+ if (query.isNotEmpty) 'query': query,
+ if (bodyType != ApiBodyType.none) 'bodyType': bodyType,
if (bodyType != ApiBodyType.none && body != null) 'body': body,
};
}
@@ -145,7 +145,8 @@ class ApiChapterConfig {
String episodeSeparator;
String fieldSeparator;
- String defaultRoadName;
+ /// Named JSONPath captures over the chapter response, exposed as template
+ /// variables to [episodePage].
Map<String, String> variables;
/// Optional final playback page template used instead of a response URL.
@@ -164,7 +165,6 @@ class ApiChapterConfig {
this.roadSeparator = r'$$$',
this.episodeSeparator = '#',
this.fieldSeparator = r'$',
- this.defaultRoadName = '播放线路',
Map<String, String>? variables,
this.episodePage,
}) : request = request ?? ApiRequestConfig(),
@@ -185,7 +185,6 @@ class ApiChapterConfig {
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()),
),
@@ -195,21 +194,39 @@ class ApiChapterConfig {
);
}
+ /// Whether any nested-format field deviates from its default. Persisting
+ /// re-serializes every plugin, so a customized inactive side must survive
+ /// even while [format] points at the other one.
+ bool get _hasNestedConfig =>
+ roadsPath != r'$.data.roads[*]' ||
+ roadNamePath != r'$.name' ||
+ episodesPath != r'$.episodes[*]' ||
+ episodeNamePath != r'$.name' ||
+ episodeUrlPath != r'$.url';
+
+ bool get _hasDelimitedConfig =>
+ roadNamesPath.isNotEmpty || roadEpisodesPath.isNotEmpty;
+
+ /// Serializes the active [format]'s fields, plus the inactive format's
+ /// fields when they carry non-default configuration.
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 (format == ApiChapterFormat.nested || _hasNestedConfig) ...{
+ 'roadsPath': roadsPath,
+ 'roadNamePath': roadNamePath,
+ 'episodesPath': episodesPath,
+ 'episodeNamePath': episodeNamePath,
+ 'episodeUrlPath': episodeUrlPath,
+ },
+ if (format == ApiChapterFormat.delimited || _hasDelimitedConfig) ...{
+ 'roadNamesPath': roadNamesPath,
+ 'roadEpisodesPath': roadEpisodesPath,
+ 'roadSeparator': roadSeparator,
+ 'episodeSeparator': episodeSeparator,
+ 'fieldSeparator': fieldSeparator,
+ },
+ if (variables.isNotEmpty) 'variables': variables,
if (episodePage != null) 'episodePage': episodePage!.toJson(),
};
}
diff --git a/lib/plugins/plugins.dart b/lib/plugins/plugins.dart
index ff45c885..e52973a3 100644
--- a/lib/plugins/plugins.dart
+++ b/lib/plugins/plugins.dart
@@ -12,8 +12,7 @@ export 'package:kazumi/services/plugin/rule_engine_models.dart'
CaptchaRequiredException,
NoResultException,
SearchErrorException,
- ChapterErrorException,
- RuleFailureKind;
+ ChapterErrorException;
class Plugin {
static final RuleEngine _ruleEngine = RuleEngine();
@@ -169,8 +168,13 @@ class Plugin {
'referer': referer,
'searchMode': searchMode,
'chapterMode': chapterMode,
- 'searchApiConfig': searchApiConfig.toJson(),
- 'chapterApiConfig': chapterApiConfig.toJson(),
+ // Persisting re-serializes the whole plugin list, so a configured API
+ // rule must survive even while the mode points at XPath.
+ if (searchMode == RuleMode.api || searchApiConfig.request.url.isNotEmpty)
+ 'searchApiConfig': searchApiConfig.toJson(),
+ if (chapterMode == RuleMode.api ||
+ chapterApiConfig.request.url.isNotEmpty)
+ 'chapterApiConfig': chapterApiConfig.toJson(),
'antiCrawlerConfig': antiCrawlerConfig.toJson(),
};
}
@@ -242,14 +246,6 @@ class Plugin {
return (await traceChapters(source, cancelToken: cancelToken)).roads;
}
- @Deprecated('Use queryChapterRoads instead.')
- Future<List<Road>> querychapterRoads(
- String source, {
- RuleCancelToken? cancelToken,
- }) {
- return queryChapterRoads(source, cancelToken: cancelToken);
- }
-
String buildFullUrl(String urlItem) {
return normalizeEpisodeUrl(baseUrl, urlItem);
}
diff --git a/lib/services/plugin/api_rule_strategy.dart b/lib/services/plugin/api_rule_strategy.dart
index d0f0e8d6..123df626 100644
--- a/lib/services/plugin/api_rule_strategy.dart
+++ b/lib/services/plugin/api_rule_strategy.dart
@@ -137,10 +137,16 @@ class ApiRuleStrategy {
);
}
- RuleSearchParseResult parseSearch(String raw, ApiSearchConfig config) {
+ /// Validates all JSONPath expressions in a search rule. Also used by the
+ /// plugin editor to reject invalid rules before saving.
+ void validateSearchConfig(ApiSearchConfig config) {
RestrictedJsonPath.validate(config.listPath);
RestrictedJsonPath.validate(config.namePath);
RestrictedJsonPath.validate(config.sourcePath);
+ }
+
+ RuleSearchParseResult parseSearch(String raw, ApiSearchConfig config) {
+ validateSearchConfig(config);
final document = decodeResponse(raw);
final nodes = RestrictedJsonPath.read(document, config.listPath);
final results = <SearchItem>[];
@@ -180,7 +186,7 @@ class ApiRuleStrategy {
required String source,
required String baseUrl,
}) {
- _validateChapterConfig(config);
+ validateChapterConfig(config);
final document = decodeResponse(raw);
final rootVariables = <String, Object?>{'source': source};
for (final entry in config.variables.entries) {
@@ -208,26 +214,12 @@ class ApiRuleStrategy {
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,
@@ -306,7 +298,7 @@ class ApiRuleStrategy {
roads.add(
Road(
name: roadName.isEmpty
- ? '${config.defaultRoadName}${roads.length + 1}'
+ ? '播放线路${roads.length + 1}'
: roadName,
data: urls,
identifier: names,
@@ -392,7 +384,7 @@ class ApiRuleStrategy {
roads.add(
Road(
name: configuredName.isEmpty
- ? '${config.defaultRoadName}${roads.length + 1}'
+ ? '播放线路${roads.length + 1}'
: configuredName,
data: urls,
identifier: names,
@@ -415,6 +407,9 @@ class ApiRuleStrategy {
if (page.url.trim().isEmpty) {
throw const ApiRuleFormatException('播放页地址模板不能为空');
}
+ // The template language has no arithmetic, so both 0-based and 1-based
+ // indices must be provided; @episodeUrl carries the raw value extracted
+ // by episodeUrlPath and has no substitute.
final variables = <String, Object?>{
...rootVariables,
'episodeUrl': rawUrl,
@@ -441,7 +436,10 @@ class ApiRuleStrategy {
);
}
- void _validateChapterConfig(ApiChapterConfig config) {
+ /// Validates the JSONPath expressions and format-specific invariants of a
+ /// chapter rule. Also used by the plugin editor to reject invalid rules
+ /// before saving.
+ void validateChapterConfig(ApiChapterConfig config) {
for (final path in config.variables.values) {
RestrictedJsonPath.validate(path);
}
diff --git a/lib/services/plugin/rule_engine.dart b/lib/services/plugin/rule_engine.dart
index c92c43d7..01230179 100644
--- a/lib/services/plugin/rule_engine.dart
+++ b/lib/services/plugin/rule_engine.dart
@@ -48,22 +48,15 @@ class RuleEngine {
: _xpathStrategy.prepareSearchRequest(config, keyword);
} catch (error, stackTrace) {
_logFailure(config, 'search request preparation', error, stackTrace);
- throw SearchErrorException(
- config.pluginName,
- cause: error,
- kind: RuleFailureKind.parse,
- );
+ throw SearchErrorException(config.pluginName, cause: error);
}
final raw = await _executeRequest(
request,
config,
phase: 'search request',
- wrapError: (error) => SearchErrorException(
- config.pluginName,
- cause: error,
- kind: RuleFailureKind.request,
- ),
+ wrapError: (error) =>
+ SearchErrorException(config.pluginName, cause: error),
cancelToken: cancelToken,
);
try {
@@ -73,6 +66,7 @@ class RuleEngine {
if (parsed.items.isEmpty) {
throw NoResultException(config.pluginName);
}
+ _logDiagnostics(config, 'search', parsed.diagnostics);
return RuleSearchTrace(
rawResponse: raw,
response: PluginSearchResponse(
@@ -89,11 +83,7 @@ class RuleEngine {
} catch (error, stackTrace) {
if (_isCancellation(error)) rethrow;
_logFailure(config, 'search response parsing', error, stackTrace);
- throw SearchErrorException(
- config.pluginName,
- cause: error,
- kind: RuleFailureKind.parse,
- );
+ throw SearchErrorException(config.pluginName, cause: error);
}
}
@@ -112,22 +102,15 @@ class RuleEngine {
: _xpathStrategy.prepareChapterRequest(config, source);
} catch (error, stackTrace) {
_logFailure(config, 'chapter request preparation', error, stackTrace);
- throw ChapterErrorException(
- config.pluginName,
- cause: error,
- kind: RuleFailureKind.parse,
- );
+ throw ChapterErrorException(config.pluginName, cause: error);
}
final raw = await _executeRequest(
request,
config,
phase: 'chapter request',
- wrapError: (error) => ChapterErrorException(
- config.pluginName,
- cause: error,
- kind: RuleFailureKind.request,
- ),
+ wrapError: (error) =>
+ ChapterErrorException(config.pluginName, cause: error),
cancelToken: cancelToken,
);
try {
@@ -140,15 +123,12 @@ class RuleEngine {
)
: _xpathStrategy.parseChapters(raw, config);
if (parsed.roads.isEmpty) {
- throw ChapterErrorException(
- config.pluginName,
- kind: RuleFailureKind.noResult,
- );
+ throw ChapterErrorException(config.pluginName);
}
+ _logDiagnostics(config, 'chapter', parsed.diagnostics);
return RuleChapterTrace(
rawResponse: raw,
roads: parsed.roads,
- matchedFragments: parsed.matchedFragments,
diagnostics: parsed.diagnostics,
);
} on ChapterErrorException {
@@ -156,11 +136,7 @@ class RuleEngine {
} catch (error, stackTrace) {
if (_isCancellation(error)) rethrow;
_logFailure(config, 'chapter response parsing', error, stackTrace);
- throw ChapterErrorException(
- config.pluginName,
- cause: error,
- kind: RuleFailureKind.parse,
- );
+ throw ChapterErrorException(config.pluginName, cause: error);
}
}
@@ -189,6 +165,21 @@ class RuleEngine {
error.type == NetworkExceptionType.cancel;
}
+ /// Surfaces partially-skipped nodes so incomplete results are traceable
+ /// from logs even when the rule succeeds overall.
+ void _logDiagnostics(
+ RuleExecutionConfig config,
+ String phase,
+ List<String> diagnostics,
+ ) {
+ if (!_logFailures || diagnostics.isEmpty) return;
+ final preview = diagnostics.take(3).join('; ');
+ KazumiLogger().w(
+ 'Plugin: ${config.pluginName} $phase skipped ${diagnostics.length} '
+ 'node(s): $preview',
+ );
+ }
+
void _logFailure(
RuleExecutionConfig config,
String phase,
diff --git a/lib/services/plugin/rule_engine_models.dart b/lib/services/plugin/rule_engine_models.dart
index 6ca2366f..5769607e 100644
--- a/lib/services/plugin/rule_engine_models.dart
+++ b/lib/services/plugin/rule_engine_models.dart
@@ -6,12 +6,6 @@ import 'package:kazumi/plugins/api_rule_config.dart';
typedef RuleCancelToken = CancelToken;
-enum RuleFailureKind {
- request,
- parse,
- noResult,
-}
-
class CaptchaRequiredException implements Exception {
const CaptchaRequiredException(this.pluginName);
@@ -33,15 +27,10 @@ class NoResultException implements Exception {
}
class SearchErrorException implements Exception {
- const SearchErrorException(
- this.pluginName, {
- this.cause,
- this.kind = RuleFailureKind.parse,
- });
+ const SearchErrorException(this.pluginName, {this.cause});
final String pluginName;
final Object? cause;
- final RuleFailureKind kind;
@override
String toString() =>
@@ -49,15 +38,10 @@ class SearchErrorException implements Exception {
}
class ChapterErrorException implements Exception {
- const ChapterErrorException(
- this.pluginName, {
- this.cause,
- this.kind = RuleFailureKind.parse,
- });
+ const ChapterErrorException(this.pluginName, {this.cause});
final String pluginName;
final Object? cause;
- final RuleFailureKind kind;
@override
String toString() => 'ChapterErrorException: $pluginName chapter query failed'
@@ -119,6 +103,9 @@ class PreparedRuleRequest {
final Map<String, dynamic> query;
final String bodyType;
final Object? body;
+
+ /// Whether stored plugin cookies are attached to the request. Historically
+ /// only search and API requests send cookies; XPath chapter requests do not.
final bool includeCookies;
}
@@ -137,12 +124,10 @@ class RuleSearchParseResult {
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;
}
@@ -164,12 +149,10 @@ 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
index 54618096..a320e085 100644
--- a/lib/services/plugin/xpath_rule_strategy.dart
+++ b/lib/services/plugin/xpath_rule_strategy.dart
@@ -90,6 +90,8 @@ class XPathRuleStrategy {
kind: XPathRuleFormatKind.invalidUrl,
);
}
+ // XPath chapter requests historically go out without stored cookies;
+ // only search requests attach them.
return PreparedRuleRequest(method: 'GET', url: url);
}
@@ -154,7 +156,6 @@ class XPathRuleStrategy {
) {
final root = _documentElement(raw);
final roads = <Road>[];
- final fragments = <String>[];
final diagnostics = <String>[];
final roadNodes = _runSelector(
XPathRuleField.chapterRoads,
@@ -163,7 +164,6 @@ class XPathRuleStrategy {
);
for (var roadIndex = 0; roadIndex < roadNodes.length; roadIndex++) {
final roadNode = roadNodes[roadIndex];
- fragments.add(_fragment(roadNode.node));
try {
final urls = <String>[];
final names = <String>[];
@@ -212,7 +212,6 @@ class XPathRuleStrategy {
}
return RuleChapterParseResult(
roads: roads,
- matchedFragments: fragments,
diagnostics: diagnostics,
);
}
diff --git a/test/api_rule_engine_test.dart b/test/api_rule_engine_test.dart
index 8d8df01f..d1d6d67f 100644
--- a/test/api_rule_engine_test.dart
+++ b/test/api_rule_engine_test.dart
@@ -169,6 +169,45 @@ void main() {
);
});
+ test('renders every documented episode page template variable', () {
+ final raw = jsonEncode({
+ 'data': {
+ 'slug': 'abc',
+ 'roads': [
+ {
+ 'name': '线路',
+ 'episodes': [
+ {'name': '第01集', 'url': 'ep-token'},
+ ],
+ },
+ ],
+ },
+ });
+ final roads = engine.parseChapters(
+ raw,
+ ApiChapterConfig(
+ variables: {'slug': r'$.data.slug'},
+ episodePage: ApiEpisodePageConfig(
+ url: 'https://example.com/@slug/@episodeUrl',
+ query: {
+ 'ri': '@roadIndex',
+ 'rn': '@roadNumber',
+ 'ei': '@episodeIndex',
+ 'en': '@episodeNumber',
+ 'src': '@source',
+ },
+ ),
+ ),
+ source: 'vid-1',
+ baseUrl: 'https://example.com/',
+ );
+
+ expect(
+ roads.roads.single.data.single,
+ 'https://example.com/abc/ep-token?ri=0&rn=1&ei=0&en=1&src=vid-1',
+ );
+ });
+
test('skips malformed delimited episode entries', () {
const raw = r'''
{"names":"线路","episodes":"损坏条目#第02集$https://cdn.test/2.m3u8"}
diff --git a/test/plugin_api_config_test.dart b/test/plugin_api_config_test.dart
index 97b85cf4..64381409 100644
--- a/test/plugin_api_config_test.dart
+++ b/test/plugin_api_config_test.dart
@@ -95,6 +95,56 @@ void main() {
expect(plugin.searchMode, RuleMode.api);
});
+ test('configured API rule survives serialization while mode is XPath', () {
+ final plugin = Plugin.fromJson({
+ ..._legacyRule,
+ 'searchMode': RuleMode.xpath,
+ 'chapterMode': RuleMode.xpath,
+ 'searchApiConfig': {
+ 'request': {'url': 'https://example.com/search'},
+ 'listPath': r'$.list[*]',
+ },
+ 'chapterApiConfig': {
+ 'request': {'url': 'https://example.com/detail/@source'},
+ 'format': 'delimited',
+ 'roadNamesPath': r'$.from',
+ 'roadEpisodesPath': r'$.urls',
+ },
+ });
+ final restored = Plugin.fromJson(plugin.toJson());
+
+ expect(restored.searchApiConfig.request.url, 'https://example.com/search');
+ expect(restored.searchApiConfig.listPath, r'$.list[*]');
+ expect(restored.chapterApiConfig.roadNamesPath, r'$.from');
+ expect(restored.chapterApiConfig.roadEpisodesPath, r'$.urls');
+ });
+
+ test('customized inactive chapter format survives serialization', () {
+ final config = ApiChapterConfig.fromJson({
+ 'format': 'delimited',
+ 'roadNamesPath': r'$.from',
+ 'roadEpisodesPath': r'$.urls',
+ 'roadsPath': r'$.custom[*]',
+ });
+ final restored = ApiChapterConfig.fromJson(config.toJson());
+
+ expect(restored.format, ApiChapterFormat.delimited);
+ expect(restored.roadsPath, r'$.custom[*]');
+ });
+
+ test('pristine rules omit inactive-mode and inactive-format fields', () {
+ final xpathRule = Plugin.fromJson(_legacyRule);
+ expect(xpathRule.toJson().containsKey('searchApiConfig'), isFalse);
+ expect(xpathRule.toJson().containsKey('chapterApiConfig'), isFalse);
+
+ final nestedChapter = ApiChapterConfig.fromJson({
+ 'request': {'url': 'https://example.com/detail/@source'},
+ }).toJson();
+ expect(nestedChapter.containsKey('roadSeparator'), isFalse);
+ expect(nestedChapter.containsKey('roadNamesPath'), isFalse);
+ expect(nestedChapter['roadsPath'], r'$.data.roads[*]');
+ });
+
test('kazumi link import and export preserves API rule configuration', () {
final plugin = Plugin.fromJson({
..._legacyRule,
diff --git a/test/rule_engine_test.dart b/test/rule_engine_test.dart
index 53d01d4a..9c9a49a8 100644
--- a/test/rule_engine_test.dart
+++ b/test/rule_engine_test.dart
@@ -62,7 +62,6 @@ void main() {
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));
@@ -86,10 +85,7 @@ void main() {
),
'keyword',
),
- throwsA(
- isA<SearchErrorException>()
- .having((error) => error.kind, 'kind', RuleFailureKind.parse),
- ),
+ throwsA(isA<SearchErrorException>()),
);
});
@@ -109,9 +105,7 @@ void main() {
'keyword',
),
throwsA(
- isA<SearchErrorException>()
- .having((error) => error.kind, 'kind', RuleFailureKind.parse)
- .having(
+ isA<SearchErrorException>().having(
(error) => error.cause,
'cause',
isA<XPathRuleFormatException>()
@@ -146,9 +140,7 @@ void main() {
'/video/1',
),
throwsA(
- isA<ChapterErrorException>()
- .having((error) => error.kind, 'kind', RuleFailureKind.parse)
- .having(
+ isA<ChapterErrorException>().having(
(error) => error.cause,
'cause',
isA<XPathRuleFormatException>()
@@ -186,7 +178,7 @@ void main() {
);
});
- test('maps request failures to a typed request reason', () async {
+ test('wraps request failures in a search error', () async {
final engine = RuleEngine(
requestExecutor: _FakeExecutor(
const [],
@@ -202,7 +194,7 @@ void main() {
),
throwsA(
isA<SearchErrorException>()
- .having((error) => error.kind, 'kind', RuleFailureKind.request),
+ .having((error) => error.cause, 'cause', isA<StateError>()),
),
);
});