Skip to content

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

feat: captcha enhance (#2406)

Prediditb37320a05de7
diff --git a/lib/bean/dialog/dialog_helper.dart b/lib/bean/dialog/dialog_helper.dart
index 85fe2509..d3a261aa 100644
--- a/lib/bean/dialog/dialog_helper.dart
+++ b/lib/bean/dialog/dialog_helper.dart
@@ -1,4 +1,3 @@
-import 'dart:async';
import 'package:flutter/material.dart';
import 'package:kazumi/navigation.dart';
import 'package:kazumi/utils/constants.dart';
@@ -257,7 +256,7 @@ class KazumiDialog {
}
}
-class _TimedSuccessDialog extends StatefulWidget {
+class _TimedSuccessDialog extends StatelessWidget {
const _TimedSuccessDialog({
required this.title,
required this.message,
@@ -268,68 +267,53 @@ class _TimedSuccessDialog extends StatefulWidget {
final String message;
final Duration duration;
- @override
- State<_TimedSuccessDialog> createState() => _TimedSuccessDialogState();
-}
-
-class _TimedSuccessDialogState extends State<_TimedSuccessDialog> {
- Timer? _countdownTimer;
- late final Stopwatch _stopwatch = Stopwatch()..start();
- double _progress = 0.0;
-
- @override
- void initState() {
- super.initState();
- _countdownTimer = Timer.periodic(const Duration(milliseconds: 16), (_) {
- final totalMs = widget.duration.inMilliseconds.clamp(1, 1 << 31);
- final elapsed = _stopwatch.elapsedMilliseconds;
- final nextProgress = (elapsed / totalMs).clamp(0.0, 1.0).toDouble();
- if (!mounted) return;
- setState(() {
- _progress = nextProgress;
- });
- if (elapsed >= totalMs) {
- _countdownTimer?.cancel();
- _countdownTimer = null;
- KazumiDialog.dismiss(popWith: true);
- }
- });
- }
-
- @override
- void dispose() {
- _countdownTimer?.cancel();
- super.dispose();
- }
-
@override
Widget build(BuildContext context) {
+ final colorScheme = Theme.of(context).colorScheme;
+ final textTheme = Theme.of(context).textTheme;
return Dialog(
clipBehavior: Clip.antiAlias,
child: Padding(
- padding: const EdgeInsets.symmetric(horizontal: 32, vertical: 28),
+ padding: const EdgeInsets.all(24),
child: SizedBox(
- width: 320,
+ width: 300,
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
- Icon(
- Icons.check_circle_rounded,
- size: 52,
- color: Theme.of(context).colorScheme.primary,
+ Container(
+ width: 64,
+ height: 64,
+ decoration: BoxDecoration(
+ color: colorScheme.secondaryContainer,
+ shape: BoxShape.circle,
+ ),
+ child: Icon(
+ Icons.check_rounded,
+ size: 32,
+ color: colorScheme.onSecondaryContainer,
+ ),
),
const SizedBox(height: 16),
Text(
- widget.title,
- style: Theme.of(context).textTheme.titleLarge,
+ title,
+ style: textTheme.headlineSmall,
+ textAlign: TextAlign.center,
),
- const SizedBox(height: 6),
+ const SizedBox(height: 8),
Text(
- widget.message,
- style: Theme.of(context).textTheme.bodyMedium,
+ message,
+ style: textTheme.bodyMedium
+ ?.copyWith(color: colorScheme.onSurfaceVariant),
+ textAlign: TextAlign.center,
),
const SizedBox(height: 24),
- LinearProgressIndicator(value: _progress),
+ TweenAnimationBuilder<double>(
+ tween: Tween(begin: 0.0, end: 1.0),
+ duration: duration,
+ onEnd: () => KazumiDialog.dismiss(popWith: true),
+ builder: (context, value, _) =>
+ LinearProgressIndicator(value: value),
+ ),
],
),
),
diff --git a/lib/pages/info/source_sheet.dart b/lib/pages/info/source_sheet.dart
index 3a64ea61..768bb0c2 100644
--- a/lib/pages/info/source_sheet.dart
+++ b/lib/pages/info/source_sheet.dart
@@ -74,6 +74,28 @@ class _SourceSheetState extends State<SourceSheet>
super.dispose();
}
+ /// After verification the webview already shows the real result page;
+ /// prefer publishing the harvested HTML directly and only fall back to a
+ /// delayed re-search when it does not parse.
+ void _showVerifiedResult(Plugin plugin, String pageHtml) {
+ final harvested = pluginSearchService?.applyHarvestedSearchResult(
+ plugin.name,
+ pageHtml,
+ ) ??
+ false;
+ if (harvested) {
+ KazumiDialog.showToast(message: '验证成功');
+ return;
+ }
+ // show a 3s countdown progress dialog before re-querying,
+ // to avoid triggering rate limits immediately after verification.
+ KazumiDialog.showTimedSuccessDialog(
+ title: '验证成功',
+ message: '即将重新检索',
+ onComplete: () => pluginSearchService?.querySource(keyword, plugin.name),
+ );
+ }
+
void showAntiCrawlerDialog(Plugin plugin) {
switch (plugin.antiCrawlerConfig.captchaType) {
case CaptchaType.customJavaScript:
@@ -91,6 +113,11 @@ class _SourceSheetState extends State<SourceSheet>
/// flag whether verification has passed, used to distinguish normal dismissal from cancellation in onDismiss
bool verified = false;
+ /// Set once the webview reports the captcha gone. The timeout below only
+ /// guards "verification was never detected", so it keys off this rather
+ /// than [verified], which lands seconds later when the harvest finishes.
+ bool finalizing = false;
+
_captchaVerificationService?.dispose();
_captchaVerificationService = CaptchaVerificationService();
@@ -109,28 +136,26 @@ class _SourceSheetState extends State<SourceSheet>
inputXpath: plugin.antiCrawlerConfig.captchaInput,
buttonXpath: plugin.antiCrawlerConfig.captchaButton,
pluginName: plugin.name,
- onVerified: () {
+ // Verification is already confirmed here; the harvest that follows
+ // takes seconds, so retire the timeout now rather than in onVerified.
+ onFinalizing: () {
+ finalizing = true;
_captchaVerifyTimer?.cancel();
_captchaVerifyTimer = null;
+ },
+ onVerified: (pageHtml) {
verified = true;
KazumiDialog.dismiss();
- // show a 3s countdown progress dialog before re-querying,
- // to avoid triggering rate limits immediately after verification.
- KazumiDialog.showTimedSuccessDialog(
- title: '验证成功',
- message: '正在重新检索,请稍候…',
- onComplete: () =>
- pluginSearchService?.querySource(keyword, plugin.name),
- );
+ _showVerifiedResult(plugin, pageHtml);
},
);
// submitCaptcha completes after the JS button click is fired.
// Start the 8-second timeout only NOW, waiting for the webview to
- // detect the captcha disappearing and call onVerified.
- if (!verified) {
+ // detect the captcha disappearing.
+ if (!finalizing) {
_captchaVerifyTimer?.cancel();
_captchaVerifyTimer = Timer(const Duration(seconds: 8), () {
- if (!verified) {
+ if (!finalizing) {
KazumiDialog.dismiss();
}
});
@@ -148,7 +173,7 @@ class _SourceSheetState extends State<SourceSheet>
final captchaService = _captchaVerificationService;
_captchaVerificationService = null;
if (!verified) {
- await captchaService?.saveAndUnload(plugin.name);
+ await captchaService?.cancelAndSave(plugin.name);
captchaService?.dispose();
pluginSearchService?.querySource(keyword, plugin.name);
} else {
@@ -202,7 +227,7 @@ class _SourceSheetState extends State<SourceSheet>
required Future<void> Function(
CaptchaVerificationService captchaService,
String searchUrl,
- void Function() onVerified,
+ void Function(String pageHtml) onVerified,
) startVerification,
}) {
bool verified = false;
@@ -214,16 +239,10 @@ class _SourceSheetState extends State<SourceSheet>
final searchUrl = plugin.searchURL
.replaceAll('@keyword', Uri.encodeQueryComponent(keyword));
- void onVerified() {
- if (verified) return;
+ void onVerified(String pageHtml) {
verified = true;
KazumiDialog.dismiss();
- KazumiDialog.showTimedSuccessDialog(
- title: '验证成功',
- message: '正在重新检索,请稍候…',
- onComplete: () =>
- pluginSearchService?.querySource(keyword, plugin.name),
- );
+ _showVerifiedResult(plugin, pageHtml);
}
unawaited(startVerification(captchaService, searchUrl, onVerified));
@@ -235,7 +254,7 @@ class _SourceSheetState extends State<SourceSheet>
if (verified) {
captchaService?.dispose();
} else {
- await captchaService?.saveAndUnload(plugin.name);
+ await captchaService?.cancelAndSave(plugin.name);
captchaService?.dispose();
pluginSearchService?.querySource(keyword, plugin.name);
}
diff --git a/lib/plugins/plugins.dart b/lib/plugins/plugins.dart
index e52973a3..df096c62 100644
--- a/lib/plugins/plugins.dart
+++ b/lib/plugins/plugins.dart
@@ -222,6 +222,13 @@ class Plugin {
);
}
+ /// Parses HTML harvested from the captcha webview as a search result;
+ /// returns null when not applicable, letting callers fall back to
+ /// [queryBangumi].
+ PluginSearchResponse? parseHarvestedSearch(String html) {
+ return _ruleEngine.tryParseHarvestedSearch(_executionConfig, html);
+ }
+
Future<PluginSearchResponse> queryBangumi(
String keyword, {
bool shouldRethrow = false,
diff --git a/lib/services/plugin/captcha_verification_service.dart b/lib/services/plugin/captcha_verification_service.dart
index bc3f9f6f..29c61e06 100644
--- a/lib/services/plugin/captcha_verification_service.dart
+++ b/lib/services/plugin/captcha_verification_service.dart
@@ -2,33 +2,24 @@ import 'dart:async';
import 'package:kazumi/services/plugin/plugin_cookie_manager.dart';
import 'package:kazumi/services/logging/logger.dart';
+import 'package:kazumi/utils/async_single_flight.dart';
import 'package:kazumi/webview/captcha/captcha_webview_controller.dart';
/// 验证码验证服务
///
-/// 支持三种独立的验证流程:
+/// 三种验证流程各自加载搜索页并等待验证通过:
///
-/// **类型1:图片验证码**([loadForCaptcha] + [submitCaptcha])
-/// 1. 初始化 WebView
-/// 2. 加载 XPath 搜索页面并监听验证码图片
-/// 3. 通过 [onCaptchaImageUrl] 流将验证码图片 URL 暴露给 UI
-/// 4. UI 将用户输入的验证码传给 [submitCaptcha]
-/// 5. 在页面中填写验证码并点击提交按钮
-/// 6. 验证码图片消失后,获取页面 Cookie 并保存到 [PluginCookieManager]
-/// 7. UI 发起重新检索
+/// - **类型1:图片验证码**([loadForCaptcha] + [submitCaptcha])
+/// 监听验证码图片并经 [onCaptchaImageUrl] 交给 UI,UI 回传用户输入后
+/// 在页面内填写并提交,验证码图片消失即视为通过。
+/// - **类型2:自动点击验证按钮**([loadForButtonClick])
+/// 检测到按钮后自动点击,按钮消失或页面跳转即视为通过。
+/// - **类型3:自定义 JavaScript 验证**([loadForCustomScript])
+/// 注入规则提供的脚本,脚本调用 KazumiCaptcha.done 或返回 true 即通过。
///
-/// **类型2:自动点击验证按钮**([loadForButtonClick])
-/// 1. 初始化 WebView
-/// 2. 加载 XPath 搜索页面并监听验证按钮
-/// 3. 检测到按钮后自动模拟点击
-/// 4. 按钮消失或页面跳转时,获取页面 Cookie 并保存到 [PluginCookieManager]
-/// 5. 通过 [onVerified] 回调通知 UI 发起重新检索
-///
-/// **类型3:自定义 JavaScript 验证**([loadForCustomScript])
-/// 1. 初始化 WebView
-/// 2. 加载搜索页面,注入规则中配置的 JS 验证脚本
-/// 3. 脚本调用 KazumiCaptcha.clicked/done 或返回 true 后完成验证
-/// 4. 获取页面 Cookie 并保存到 [PluginCookieManager]
+/// 验证通过后统一收尾:收割验证后页面的 HTML,保存 Cookie 与 User-Agent 到
+/// [PluginCookieManager],再将 HTML 交给 onVerified。UI 能解析该 HTML 时直接
+/// 展示结果,否则回落到重新检索。
class CaptchaVerificationService {
CaptchaWebviewController? _controller;
@@ -45,6 +36,56 @@ class CaptchaVerificationService {
bool _disposed = false;
String _pageUrl = '';
+ /// 共享收尾任务。收割页面需要数秒,期间用户仍可取消,两条路径便会同时
+ /// 对同一个 WebView 卸载页面和读取内容。汇合到同一次收尾以避免并发访问,
+ /// 也使 [cancelAndSave] 的 await 覆盖住调用方随后的 dispose。
+ final AsyncSingleFlight<String> _finalize = AsyncSingleFlight<String>();
+
+ bool _outcomeClaimed = false;
+
+ /// 认领向 UI 提交结果的权利。
+ ///
+ /// 收尾任务的归属与结果的归属可以不同:成功路径先启动收尾,用户随后取消,
+ /// 此时应由取消提交结果。故在共享收尾之外单独仲裁——取消在 [cancelAndSave]
+ /// 入口同步认领,成功路径在收尾结束后认领,后到者放弃提交。
+ bool _claimOutcome() {
+ if (_outcomeClaimed) return false;
+ _outcomeClaimed = true;
+ return true;
+ }
+
+ /// 订阅验证通过事件:收尾后把收割到的 HTML 交给 [onVerified]。
+ ///
+ /// [onFinalizing] 在观察到验证通过、开始收尾之前触发。收尾需要数秒,
+ /// 调用方若对验证设有超时,必须以此为准而非 [onVerified],
+ /// 否则超时会在收尾途中把已经成功的验证判成失败。
+ void _listenForVerification(
+ String pluginName,
+ void Function(String pageHtml) onVerified, {
+ String logPrefix = '',
+ void Function()? onFinalizing,
+ }) {
+ final controller = _controller;
+ if (controller == null) return;
+
+ Future<void> onDisappeared() async {
+ _disappearedSub?.cancel();
+ // 重新读取:订阅到事件之间可能已被 dispose 置空。
+ final current = _controller;
+ if (current == null) return;
+ onFinalizing?.call();
+ final pageHtml = await _finalize.run(() =>
+ _saveCookiesAndUnload(current, pluginName, logPrefix: logPrefix));
+ if (_disposed || !_claimOutcome()) return;
+ onVerified(pageHtml);
+ }
+
+ _disappearedSub?.cancel();
+ _disappearedSub = controller.onCaptchaDisappeared.listen((_) {
+ onDisappeared();
+ });
+ }
+
Future<void> _ensureInitialized() async {
if (_isInitialized || _disposed) return;
_controller = CaptchaWebviewControllerFactory.getController();
@@ -87,19 +128,16 @@ class CaptchaVerificationService {
KazumiLogger().i('[CaptchaVerificationService] Page loading: $url');
}
- /// 提交验证码
+ /// 在页面中填写 [captchaCode] 并点击 [buttonXpath] 提交
///
- /// [captchaCode] 用户输入的验证码文本
- /// [inputXpath] 验证码输入框元素的 XPath
- /// [buttonXpath] 验证提交按钮元素的 XPath
- /// [pluginName] 规则名(用于保存 Cookie)
- /// [onVerified] 验证成功后的回调
+ /// [onFinalizing] 在验证通过、开始收尾时触发,早于 [onVerified] 数秒。
Future<void> submitCaptcha({
required String captchaCode,
required String inputXpath,
required String buttonXpath,
required String pluginName,
- required void Function() onVerified,
+ required void Function(String pageHtml) onVerified,
+ void Function()? onFinalizing,
}) async {
if (_controller == null) {
KazumiLogger()
@@ -110,127 +148,122 @@ class CaptchaVerificationService {
KazumiLogger()
.i('[CaptchaVerificationService] Submitting captcha code via interact');
- bool handled = false;
-
- Future<void> onDisappeared() async {
- if (handled) return;
- handled = true;
- _disappearedSub?.cancel();
- final controller = _controller;
- if (controller == null) return;
- await _saveCookiesAndUnload(controller, pluginName);
- onVerified();
- }
-
- _disappearedSub?.cancel();
- _disappearedSub = _controller!.onCaptchaDisappeared.listen((_) {
- onDisappeared();
- });
+ _listenForVerification(pluginName, onVerified, onFinalizing: onFinalizing);
await _controller!
.submitCaptchaInteract(captchaCode, inputXpath, buttonXpath);
}
- /// 加载页面并自动点击验证按钮
- ///
- /// [url] 要加载的页面地址
- /// [buttonXpath] 验证按钮元素的 XPath,检测到后自动点击
- /// [pluginName] 规则名(用于保存 Cookie)
- /// [onVerified] 验证通过后的回调
+ /// 加载 [url] 并在检测到 [buttonXpath] 后自动点击
Future<void> loadForButtonClick({
required String url,
required String buttonXpath,
required String pluginName,
- required void Function() onVerified,
+ required void Function(String pageHtml) onVerified,
}) async {
_pageUrl = url;
await _ensureInitialized();
if (_disposed || _controller == null) return;
- bool handled = false;
-
- Future<void> onDisappeared() async {
- if (handled) return;
- handled = true;
- _disappearedSub?.cancel();
- final controller = _controller;
- if (controller == null) return;
- await _saveCookiesAndUnload(controller, pluginName,
- logPrefix: '(type2) ');
- onVerified();
- }
-
- _disappearedSub?.cancel();
- _disappearedSub = _controller!.onCaptchaDisappeared.listen((_) {
- onDisappeared();
- });
-
+ _listenForVerification(pluginName, onVerified, logPrefix: '(type2) ');
await _controller!.loadPageForButtonClick(url, buttonXpath);
KazumiLogger().i(
'[CaptchaVerificationService] (type2) Page loading for button click: $url');
}
+ /// 加载 [url] 并注入规则提供的验证脚本 [script]
Future<void> loadForCustomScript({
required String url,
required String script,
required String pluginName,
- required void Function() onVerified,
+ required void Function(String pageHtml) onVerified,
}) async {
_pageUrl = url;
await _ensureInitialized();
if (_disposed || _controller == null) return;
- bool handled = false;
-
- Future<void> onDisappeared() async {
- if (handled) return;
- handled = true;
- _disappearedSub?.cancel();
- final controller = _controller;
- if (controller == null) return;
- await _saveCookiesAndUnload(controller, pluginName,
- logPrefix: '(type3) ');
- onVerified();
- }
-
- _disappearedSub?.cancel();
- _disappearedSub = _controller!.onCaptchaDisappeared.listen((_) {
- onDisappeared();
- });
-
+ _listenForVerification(pluginName, onVerified, logPrefix: '(type3) ');
await _controller!.loadPageForCustomScript(url, script);
KazumiLogger().i(
'[CaptchaVerificationService] (type3) Page loading for custom script: $url');
}
- Future<void> saveAndUnload(String pluginName) async {
+ /// 用户取消验证:认领结果提交权并保存已有 Cookie。
+ ///
+ /// 认领必须发生在任何 await 之前,这样即使验证恰好在此刻通过,
+ /// 其 onVerified 也不会再提交结果,由调用方按取消语义收尾。
+ Future<void> cancelAndSave(String pluginName) async {
+ _claimOutcome();
_disappearedSub?.cancel();
_disappearedSub = null;
- // Capture locally before any await so dispose() nulling _controller
- // between two awaits cannot cause a force-unwrap crash.
+ // 先取到本地:dispose 可能在两次 await 之间把 _controller 置空。
final controller = _controller;
if (controller == null || _pageUrl.isEmpty) return;
- await _saveCookiesAndUnload(
- controller,
- pluginName,
- logPrefix: 'on cancel ',
- );
+ // 若验证成功路径已在收尾,这里会汇合到那一次并等它把 Cookie 存完。
+ await _finalize.run(() => _saveCookiesAndUnload(
+ controller,
+ pluginName,
+ logPrefix: 'on cancel ',
+ harvestHtml: false,
+ ));
}
- Future<void> _saveCookiesAndUnload(
+ /// 保存 Cookie 与 User-Agent 并卸载页面。
+ ///
+ /// [harvestHtml] 为 true 时先收割验证后页面的 HTML 并返回,
+ /// 供上层直接解析检索结果;取消路径不收割。
+ ///
+ /// 按契约不抛异常:成功与取消两条路径共享这一个 Future,任何异常都会同时
+ /// 打断两边——成功路径的 onVerified 不再触发,取消路径 onDismiss 里的
+ /// dispose 与回落检索也会被跳过。故内部兜住异常,尽力返回已取到的内容。
+ Future<String> _saveCookiesAndUnload(
CaptchaWebviewController controller,
String pluginName, {
String logPrefix = '',
+ bool harvestHtml = true,
}) async {
- final cookieString = await controller.getCookieString(_pageUrl);
- KazumiLogger().i(
- '[CaptchaVerificationService] ${logPrefix}Captured cookies: $cookieString');
- if (cookieString.isNotEmpty) {
- await PluginCookieManager.instance
- .saveFromWebView(pluginName, _pageUrl, cookieString);
+ String pageHtml = '';
+ try {
+ // 先收割:等待结果页稳定的同时,也让 JS 写入的 Cookie 落地后再读取。
+ if (harvestHtml) {
+ pageHtml = await _waitForPageHtml(controller);
+ KazumiLogger().i(
+ '[CaptchaVerificationService] ${logPrefix}Harvested page html length: ${pageHtml.length}');
+ }
+ final cookieString = await controller.getCookieString(_pageUrl);
+ final userAgent = await controller.getUserAgent();
KazumiLogger().i(
- '[CaptchaVerificationService] ${logPrefix}Cookies saved for plugin: $pluginName');
+ '[CaptchaVerificationService] ${logPrefix}Captured cookies: $cookieString');
+ if (cookieString.isNotEmpty) {
+ await PluginCookieManager.instance.saveFromWebView(
+ pluginName, _pageUrl, cookieString,
+ userAgent: userAgent);
+ KazumiLogger().i(
+ '[CaptchaVerificationService] ${logPrefix}Cookies saved for plugin: $pluginName');
+ }
+ await controller.unloadPage();
+ } catch (error, stackTrace) {
+ KazumiLogger().w(
+ '[CaptchaVerificationService] ${logPrefix}Finalize failed',
+ error: error,
+ stackTrace: stackTrace,
+ );
+ }
+ return pageHtml;
+ }
+
+ /// 等待验证后的页面加载完成并返回其 HTML。
+ /// 验证消失事件可能早于结果页加载完成,因此短暂轮询;
+ /// 超时返回空字符串,由上层回落到重新检索。
+ Future<String> _waitForPageHtml(CaptchaWebviewController controller) async {
+ const maxAttempts = 10;
+ const interval = Duration(milliseconds: 300);
+ for (var attempt = 0; attempt < maxAttempts; attempt++) {
+ if (_disposed) return '';
+ final html = await controller.getPageHtml();
+ if (html.trim().isNotEmpty) return html;
+ await Future.delayed(interval);
}
- await controller.unloadPage();
+ return '';
}
void dispose() {
diff --git a/lib/services/plugin/plugin_cookie_manager.dart b/lib/services/plugin/plugin_cookie_manager.dart
index 5c16de60..52cad30a 100644
--- a/lib/services/plugin/plugin_cookie_manager.dart
+++ b/lib/services/plugin/plugin_cookie_manager.dart
@@ -6,19 +6,26 @@ import 'package:kazumi/services/logging/logger.dart';
/// 为每条规则维护一个独立的内存 [CookieJar],
/// 通过 [saveFromWebView] 将 WebView 捕获的 document.cookie 字符串
/// 解析后存入对应规则的 jar。规则请求执行器按需读取并组装 Cookie 请求头。
+/// 验证 Cookie 通常与 User-Agent 绑定,故同时记录 WebView 的 UA,
+/// 供后续 dio 请求对齐指纹。
/// Cookie 仅在当前 App 会话内有效,重启后需重新验证。
class PluginCookieManager {
PluginCookieManager._();
static final PluginCookieManager instance = PluginCookieManager._();
final Map<String, CookieJar> _jars = {};
+ final Map<String, String> _userAgents = {};
CookieJar _getJar(String pluginName) {
return _jars.putIfAbsent(pluginName, () => CookieJar());
}
Future<void> saveFromWebView(
- String pluginName, String pageUrl, String cookieString) async {
+ String pluginName, String pageUrl, String cookieString,
+ {String? userAgent}) async {
+ if (userAgent != null && userAgent.trim().isNotEmpty) {
+ _userAgents[pluginName] = userAgent.trim();
+ }
if (cookieString.trim().isEmpty) return;
final uri = Uri.tryParse(pageUrl);
if (uri == null) return;
@@ -60,4 +67,7 @@ class PluginCookieManager {
if (jar == null) return <Cookie>[];
return jar.loadForRequest(uri);
}
+
+ /// 验证时 WebView 使用的 User-Agent;未验证过的规则返回 null
+ String? userAgentFor(String pluginName) => _userAgents[pluginName];
}
diff --git a/lib/services/plugin/plugin_search_service.dart b/lib/services/plugin/plugin_search_service.dart
index e54232b4..67e606ae 100644
--- a/lib/services/plugin/plugin_search_service.dart
+++ b/lib/services/plugin/plugin_search_service.dart
@@ -35,6 +35,27 @@ class PluginSearchService {
}
}
+ /// Publishes the result page harvested by the captcha webview, skipping
+ /// one network round trip. Returns false when the HTML does not parse
+ /// into results; callers should fall back to [querySource].
+ bool applyHarvestedSearchResult(String pluginName, String html) {
+ if (_isCancelled) return false;
+ for (final plugin in pluginsController.pluginList) {
+ if (plugin.name != pluginName) continue;
+ final result = plugin.parseHarvestedSearch(html);
+ if (result == null) return false;
+ infoController.pluginSearchResponseList.removeWhere(
+ (response) => response.pluginName == pluginName,
+ );
+ infoController.pluginSearchStatus[pluginName] =
+ PluginSearchStatus.success;
+ pluginsController.validityTracker.markSearchValid(pluginName);
+ infoController.pluginSearchResponseList.add(result);
+ return true;
+ }
+ return false;
+ }
+
Future<void> queryAllSource(String keyword) async {
infoController.pluginSearchResponseList.clear();
infoController.pluginSearchStatus.clear();
diff --git a/lib/services/plugin/rule_engine.dart b/lib/services/plugin/rule_engine.dart
index 01230179..41e6235f 100644
--- a/lib/services/plugin/rule_engine.dart
+++ b/lib/services/plugin/rule_engine.dart
@@ -87,6 +87,38 @@ class RuleEngine {
}
}
+ /// Parses HTML harvested from the captcha webview as a search result,
+ /// skipping one network round trip after verification. Returns null when
+ /// not applicable (API/POST rules) or when the page does not parse into
+ /// results (still a challenge page, redirect page, or empty list) — the
+ /// caller then falls back to a regular re-search.
+ PluginSearchResponse? tryParseHarvestedSearch(
+ RuleExecutionConfig config,
+ String raw,
+ ) {
+ if (raw.trim().isEmpty) return null;
+ // The webview loads the search URL with GET; API-mode and POST-mode
+ // rules may render a different page than the real search response.
+ if (config.searchMode == RuleMode.api || config.usePost) return null;
+ try {
+ final parsed = _xpathStrategy.parseSearch(raw, config);
+ if (parsed.items.isEmpty) return null;
+ _logDiagnostics(config, 'harvested search', parsed.diagnostics);
+ return PluginSearchResponse(
+ pluginName: config.pluginName,
+ data: parsed.items,
+ );
+ } catch (error) {
+ if (_logFailures) {
+ KazumiLogger().i(
+ 'Plugin: ${config.pluginName} harvested page not parseable, '
+ 'falling back to re-search ($error)',
+ );
+ }
+ return null;
+ }
+ }
+
Future<RuleChapterTrace> queryChapters(
RuleExecutionConfig config,
String source, {
@@ -205,19 +237,29 @@ class _DefaultRuleRequestExecutor implements RuleRequestExecutor {
final cookieHeader = request.includeCookies
? await _cookieHeaderFor(config.pluginName, request.url)
: '';
+ final verifiedUserAgent = cookieHeader.isNotEmpty
+ ? PluginCookieManager.instance.userAgentFor(config.pluginName)
+ : null;
+ // Header names are lowercased so a rule-supplied 'User-Agent' collides
+ // with ours instead of being sent as a second, conflicting header.
final headers = <String, dynamic>{
'referer': '${config.baseUrl}/',
- if (cookieHeader.isNotEmpty) 'Cookie': cookieHeader,
- ...request.headers,
+ if (cookieHeader.isNotEmpty) 'cookie': cookieHeader,
+ for (final entry in request.headers.entries)
+ entry.key.toLowerCase(): entry.value,
+ // Clearance cookies are bound to the User-Agent they were issued to,
+ // so the verified UA overrides the rule's own; sending a different one
+ // would make the site serve the challenge page again.
+ if (verifiedUserAgent != null) 'user-agent': verifiedUserAgent,
};
if (request.method == 'POST') {
switch (request.bodyType) {
case ApiBodyType.json:
- headers.putIfAbsent('Content-Type', () => 'application/json');
+ headers.putIfAbsent('content-type', () => 'application/json');
break;
case ApiBodyType.form:
headers.putIfAbsent(
- 'Content-Type',
+ 'content-type',
() => 'application/x-www-form-urlencoded',
);
break;
diff --git a/lib/webview/captcha/captcha_webview_controller.dart b/lib/webview/captcha/captcha_webview_controller.dart
index fcd99e5f..3109b570 100644
--- a/lib/webview/captcha/captcha_webview_controller.dart
+++ b/lib/webview/captcha/captcha_webview_controller.dart
@@ -74,6 +74,15 @@ abstract class CaptchaWebviewController<T> {
/// [pageUrl] 当前加载的页面地址,部分平台用于精确过滤 Cookie
Future<String> getCookieString(String pageUrl);
+ /// 获取当前页面的完整 HTML(document.documentElement.outerHTML)
+ ///
+ /// 页面仍在加载(document.readyState === 'loading')时返回空字符串,
+ /// 由调用方决定是否重试。
+ Future<String> getPageHtml();
+
+ /// 获取 WebView 实际使用的 User-Agent(navigator.userAgent)
+ Future<String> getUserAgent();
+
/// 卸载当前页面(跳转到 about:blank)
Future<void> unloadPage();
diff --git a/lib/webview/captcha/impl/captcha_webview_inappwebview_impl.dart b/lib/webview/captcha/impl/captcha_webview_inappwebview_impl.dart
index 01c8fc4e..c2d85806 100644
--- a/lib/webview/captcha/impl/captcha_webview_inappwebview_impl.dart
+++ b/lib/webview/captcha/impl/captcha_webview_inappwebview_impl.dart
@@ -475,6 +475,31 @@ if (!_checkAndClick()) {
}
}
+ @override
+ Future<String> getPageHtml() async {
+ try {
+ final result = await webviewController?.evaluateJavascript(
+ source:
+ "document.readyState === 'loading' ? '' : document.documentElement.outerHTML;");
+ return result is String ? result : '';
+ } catch (e) {
+ KazumiLogger().d('[Captcha WebView] getPageHtml error: $e');
+ return '';
+ }
+ }
+
+ @override
+ Future<String> getUserAgent() async {
+ try {
+ final result = await webviewController?.evaluateJavascript(
+ source: 'navigator.userAgent;');
+ return result is String ? result : '';
+ } catch (e) {
+ KazumiLogger().d('[Captcha WebView] getUserAgent error: $e');
+ return '';
+ }
+ }
+
@override
Future<void> unloadPage() async {
try {
diff --git a/lib/webview/captcha/impl/captcha_webview_linux_impl.dart b/lib/webview/captcha/impl/captcha_webview_linux_impl.dart
index 25106976..f87a668e 100644
--- a/lib/webview/captcha/impl/captcha_webview_linux_impl.dart
+++ b/lib/webview/captcha/impl/captcha_webview_linux_impl.dart
@@ -1,4 +1,5 @@
import 'dart:async';
+import 'dart:convert';
import 'package:flutter/foundation.dart';
import 'package:desktop_webview_window/desktop_webview_window.dart';
@@ -125,7 +126,7 @@ class CaptchaWebviewLinuxImpl extends CaptchaWebviewController<Webview> {
} catch(e) { return 'absent'; }
})();
''');
- return result?.contains('present') ?? false;
+ return _decodeJsString(result) == 'present';
} catch (e) {
KazumiLogger().d('[Captcha WebView] _isCaptchaPresent error: $e');
return false;
@@ -418,6 +419,48 @@ $script
}
}
+ @override
+ Future<String> getPageHtml() async {
+ try {
+ final result = await webviewController?.evaluateJavaScript('''
+(function() {
+ try {
+ return document.readyState === 'loading' ? '' : document.documentElement.outerHTML;
+ } catch(e) { return ''; }
+})();
+''');
+ return _decodeJsString(result);
+ } catch (e) {
+ KazumiLogger().d('[Captcha WebView] getPageHtml error: $e');
+ return '';
+ }
+ }
+
+ @override
+ Future<String> getUserAgent() async {
+ try {
+ final result = await webviewController?.evaluateJavaScript(
+ '(function() { return navigator.userAgent; })();');
+ return _decodeJsString(result);
+ } catch (e) {
+ KazumiLogger().d('[Captcha WebView] getUserAgent error: $e');
+ return '';
+ }
+ }
+
+ /// WebKitGTK 通过 jsc_value_to_json 返回结果,字符串会带外围双引号且内容
+ /// 被转义,必须解码后才能当作 HTML 或 UA 使用。旧 WebKit 若返回裸字符串,
+ /// 解码失败则按原值回落。
+ String _decodeJsString(String? raw) {
+ if (raw == null || raw.isEmpty) return '';
+ try {
+ final decoded = jsonDecode(raw);
+ return decoded is String ? decoded : '';
+ } catch (_) {
+ return raw;
+ }
+ }
+
@override
Future<void> unloadPage() async {
webviewController?.launch('about:blank');
diff --git a/lib/webview/captcha/impl/captcha_webview_windows_impl.dart b/lib/webview/captcha/impl/captcha_webview_windows_impl.dart
index 5c755701..64a683aa 100644
--- a/lib/webview/captcha/impl/captcha_webview_windows_impl.dart
+++ b/lib/webview/captcha/impl/captcha_webview_windows_impl.dart
@@ -439,6 +439,30 @@ $script
}
}
+ @override
+ Future<String> getPageHtml() async {
+ try {
+ final result = await _headlessWebview?.executeScript(
+ "document.readyState === 'loading' ? '' : document.documentElement.outerHTML;");
+ return result is String ? result : '';
+ } catch (e) {
+ KazumiLogger().d('[Captcha WebView] getPageHtml error: $e');
+ return '';
+ }
+ }
+
+ @override
+ Future<String> getUserAgent() async {
+ try {
+ final result =
+ await _headlessWebview?.executeScript('navigator.userAgent;');
+ return result is String ? result : '';
+ } catch (e) {
+ KazumiLogger().d('[Captcha WebView] getUserAgent error: $e');
+ return '';
+ }
+ }
+
@override
Future<void> unloadPage() async {
try {