Skip to content

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

feat: captcha (#1853)

Prediditee71a865531a
diff --git a/lib/bean/dialog/dialog_helper.dart b/lib/bean/dialog/dialog_helper.dart
index 295659a3..eed8c937 100644
--- a/lib/bean/dialog/dialog_helper.dart
+++ b/lib/bean/dialog/dialog_helper.dart
@@ -1,3 +1,4 @@
+import 'dart:async';
import 'package:flutter/material.dart';
import 'package:kazumi/utils/constants.dart';
@@ -194,6 +195,80 @@ class KazumiDialog {
debugPrint('Kazumi Dialog Debug: No active KazumiDialog to dismiss');
}
}
+
+ /// Shows a non-dismissible timed success dialog with a linear progress
+ /// countdown, then auto-dismisses when the countdown completes.
+ ///
+ /// The caller is responsible for dismissing any currently-open dialog
+ /// BEFORE calling this method.
+ ///
+ /// [onComplete] is invoked inside [onDismiss] after the countdown finishes
+ /// (or if the dialog is dismissed for any other reason), ensuring it runs
+ /// exactly once and resources are always cleaned up.
+ static void showTimedSuccessDialog({
+ required String title,
+ required String message,
+ required VoidCallback onComplete,
+ Duration duration = const Duration(seconds: 3),
+ }) {
+ final progressNotifier = ValueNotifier<double>(0.0);
+ Timer? countdownTimer;
+ final totalMs = duration.inMilliseconds;
+ final stopwatch = Stopwatch()..start();
+ countdownTimer = Timer.periodic(const Duration(milliseconds: 16), (t) {
+ final elapsed = stopwatch.elapsedMilliseconds;
+ progressNotifier.value = (elapsed / totalMs).clamp(0.0, 1.0);
+ if (elapsed >= totalMs) {
+ t.cancel();
+ KazumiDialog.dismiss();
+ }
+ });
+ KazumiDialog.show(
+ clickMaskDismiss: false,
+ onDismiss: () {
+ countdownTimer?.cancel();
+ progressNotifier.dispose();
+ onComplete();
+ },
+ builder: (context) => Dialog(
+ clipBehavior: Clip.antiAlias,
+ child: Padding(
+ padding: const EdgeInsets.symmetric(horizontal: 32, vertical: 28),
+ child: SizedBox(
+ width: 320,
+ child: Column(
+ mainAxisSize: MainAxisSize.min,
+ children: [
+ Icon(
+ Icons.check_circle_rounded,
+ size: 52,
+ color: Theme.of(context).colorScheme.primary,
+ ),
+ const SizedBox(height: 16),
+ Text(
+ title,
+ style: Theme.of(context).textTheme.titleLarge,
+ ),
+ const SizedBox(height: 6),
+ Text(
+ message,
+ style: Theme.of(context).textTheme.bodyMedium,
+ ),
+ const SizedBox(height: 24),
+ ValueListenableBuilder<double>(
+ valueListenable: progressNotifier,
+ builder: (context, value, _) => LinearProgressIndicator(
+ value: value,
+ borderRadius: BorderRadius.circular(4),
+ ),
+ ),
+ ],
+ ),
+ ),
+ ),
+ ),
+ );
+ }
}
/// Navigator observer to track contexts and dialog routes
diff --git a/lib/modules/plugin/plugin_http_module.dart b/lib/modules/plugin/plugin_http_module.dart
index bdb8cb34..68ca49b9 100644
--- a/lib/modules/plugin/plugin_http_module.dart
+++ b/lib/modules/plugin/plugin_http_module.dart
@@ -4,6 +4,7 @@ class PluginHTTPItem {
bool useNativePlayer;
String author;
int lastUpdate;
+ bool antiCrawlerEnabled;
PluginHTTPItem({
required this.name,
@@ -11,15 +12,21 @@ class PluginHTTPItem {
required this.useNativePlayer,
required this.author,
required this.lastUpdate,
+ this.antiCrawlerEnabled = false,
});
factory PluginHTTPItem.fromJson(Map<String, dynamic> json) {
+ final dynamic rawConfig = json['antiCrawlerConfig'];
+ final bool antiCrawlerEnabled = rawConfig is Map<String, dynamic>
+ ? (rawConfig['enabled'] as bool? ?? false)
+ : false;
return PluginHTTPItem(
name: json['name'],
version: json['version'],
useNativePlayer: json['useNativePlayer'],
author: json['author'],
lastUpdate: json['lastUpdate'] ?? 0,
+ antiCrawlerEnabled: antiCrawlerEnabled,
);
}
}
diff --git a/lib/pages/download/download_controller.dart b/lib/pages/download/download_controller.dart
index 0f28a2fa..3f71b748 100644
--- a/lib/pages/download/download_controller.dart
+++ b/lib/pages/download/download_controller.dart
@@ -12,7 +12,7 @@ import 'package:kazumi/utils/download_manager.dart';
import 'package:kazumi/utils/format_utils.dart';
import 'package:kazumi/utils/logger.dart';
import 'package:kazumi/utils/storage.dart';
-import 'package:kazumi/providers/providers.dart';
+import 'package:kazumi/providers/video/providers.dart';
import 'package:kazumi/request/damaku.dart';
import 'package:mobx/mobx.dart';
diff --git a/lib/pages/info/source_sheet.dart b/lib/pages/info/source_sheet.dart
index e6b4dab0..585ebde4 100644
--- a/lib/pages/info/source_sheet.dart
+++ b/lib/pages/info/source_sheet.dart
@@ -6,11 +6,16 @@ import 'package:kazumi/pages/info/info_controller.dart';
import 'package:kazumi/utils/logger.dart';
import 'package:kazumi/bean/dialog/dialog_helper.dart';
import 'package:kazumi/plugins/plugins_controller.dart';
+import 'package:kazumi/plugins/plugins.dart';
import 'package:kazumi/pages/video/video_controller.dart';
import 'package:url_launcher/url_launcher.dart';
import 'package:kazumi/request/query_manager.dart';
import 'package:kazumi/pages/collect/collect_controller.dart';
import 'package:kazumi/bean/widget/error_widget.dart';
+import 'dart:async';
+import 'dart:convert';
+import 'package:kazumi/providers/captcha/captcha_provider.dart';
+import 'package:kazumi/plugins/anti_crawler_config.dart';
class SourceSheet extends StatefulWidget {
const SourceSheet({
@@ -37,6 +42,12 @@ class _SourceSheetState extends State<SourceSheet>
/// Concurrent query manager
QueryManager? queryManager;
+ /// Captcha solving provider (created on demand)
+ CaptchaProvider? _captchaProvider;
+
+ /// Timeout timer waiting for captcha verification result
+ Timer? _captchaVerifyTimer;
+
@override
void initState() {
keyword = widget.infoController.bangumiItem.nameCn == ''
@@ -51,9 +62,361 @@ class _SourceSheetState extends State<SourceSheet>
void dispose() {
queryManager?.cancel();
queryManager = null;
+ _captchaProvider?.dispose();
+ _captchaProvider = null;
+ _captchaVerifyTimer?.cancel();
+ _captchaVerifyTimer = null;
super.dispose();
}
+ /// 根据插件的验证类型分发到对应的验证对话框
+ void showAntiCrawlerDialog(Plugin plugin) {
+ switch (plugin.antiCrawlerConfig.captchaType) {
+ case CaptchaType.autoClickButton:
+ showButtonClickDialog(plugin);
+ break;
+ default:
+ showCaptchaDialog(plugin);
+ }
+ }
+
+ void showCaptchaDialog(Plugin plugin) {
+ final captchaImageNotifier = ValueNotifier<String?>(null);
+ final submittingNotifier = ValueNotifier<bool>(false);
+ final TextEditingController codeController = TextEditingController();
+
+ /// flag whether verification has passed, used to distinguish normal dismissal from cancellation in onDismiss
+ bool verified = false;
+
+ _captchaProvider?.dispose();
+ _captchaProvider = CaptchaProvider();
+
+ final searchUrl = plugin.searchURL.replaceAll('@keyword', keyword);
+
+ _captchaProvider!.loadForCaptcha(
+ searchUrl,
+ plugin.antiCrawlerConfig.captchaImage,
+ inputXpath: plugin.antiCrawlerConfig.captchaInput,
+ );
+
+ final imageSub = _captchaProvider!.onCaptchaImageUrl.listen((url) {
+ if (url != null) captchaImageNotifier.value = url;
+ });
+
+ Future<void> doSubmit() async {
+ if (submittingNotifier.value) return;
+ if (codeController.text.trim().isEmpty) {
+ KazumiDialog.showToast(message: '请输入验证码');
+ return;
+ }
+ submittingNotifier.value = true;
+ await _captchaProvider?.submitCaptcha(
+ captchaCode: codeController.text.trim(),
+ inputXpath: plugin.antiCrawlerConfig.captchaInput,
+ buttonXpath: plugin.antiCrawlerConfig.captchaButton,
+ pluginName: plugin.name,
+ onVerified: () {
+ _captchaVerifyTimer?.cancel();
+ _captchaVerifyTimer = null;
+ 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: () => queryManager?.querySource(keyword, plugin.name),
+ );
+ },
+ );
+ // 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) {
+ _captchaVerifyTimer?.cancel();
+ _captchaVerifyTimer = Timer(const Duration(seconds: 8), () {
+ if (!verified) {
+ KazumiDialog.dismiss();
+ }
+ });
+ }
+ }
+
+ KazumiDialog.show(
+ onDismiss: () async {
+ _captchaVerifyTimer?.cancel();
+ _captchaVerifyTimer = null;
+ // Cancel the image subscription before disposing the notifier to
+ // prevent late stream events writing to an already-disposed notifier.
+ imageSub.cancel();
+ codeController.dispose();
+ captchaImageNotifier.dispose();
+ submittingNotifier.dispose();
+ // Capture the current provider instance locally NOW, before any await.
+ // Without this, an async gap could allow _captchaProvider to be
+ // replaced (or nulled by _SourceSheetState.dispose()), causing the
+ // closure to dispose the wrong/already-disposed instance.
+ final provider = _captchaProvider;
+ _captchaProvider = null;
+ if (!verified) {
+ await provider?.saveAndUnload(plugin.name);
+ provider?.dispose();
+ queryManager?.querySource(keyword, plugin.name);
+ } else {
+ provider?.dispose();
+ }
+ },
+ builder: (context) {
+ return Dialog(
+ clipBehavior: Clip.antiAlias,
+ child: Padding(
+ padding: const EdgeInsets.all(24),
+ child: SizedBox(
+ width: 400,
+ child: Column(
+ mainAxisSize: MainAxisSize.min,
+ crossAxisAlignment: CrossAxisAlignment.center,
+ children: [
+ Text(
+ '验证码验证',
+ style: Theme.of(context).textTheme.titleLarge,
+ ),
+ const SizedBox(height: 4),
+ Text(
+ '${plugin.name} 需要验证码验证',
+ style: Theme.of(context).textTheme.bodySmall,
+ ),
+ const SizedBox(height: 20),
+ ValueListenableBuilder<String?>(
+ valueListenable: captchaImageNotifier,
+ builder: (context, imageUrl, _) {
+ if (imageUrl == null) {
+ return const Column(
+ children: [
+ CircularProgressIndicator(),
+ SizedBox(height: 12),
+ Text('正在加载验证码图片...'),
+ ],
+ );
+ }
+ return ValueListenableBuilder<bool>(
+ valueListenable: submittingNotifier,
+ builder: (context, isSubmitting, _) {
+ return Column(
+ children: [
+ ClipRRect(
+ borderRadius: BorderRadius.circular(8),
+ child: Image.memory(
+ base64Decode(imageUrl.split(',').last),
+ height: 80,
+ fit: BoxFit.contain,
+ errorBuilder: (context, error, _) =>
+ const Text('图片解码失败'),
+ ),
+ ),
+ const SizedBox(height: 16),
+ TextField(
+ controller: codeController,
+ autofocus: true,
+ enabled: !isSubmitting,
+ decoration: const InputDecoration(
+ labelText: '请输入验证码',
+ border: OutlineInputBorder(),
+ ),
+ onSubmitted:
+ isSubmitting ? null : (_) => doSubmit(),
+ ),
+ ],
+ );
+ },
+ );
+ },
+ ),
+ const SizedBox(height: 20),
+ ListenableBuilder(
+ listenable: Listenable.merge(
+ [captchaImageNotifier, submittingNotifier]),
+ builder: (context, _) {
+ final isImageLoading = captchaImageNotifier.value == null;
+ final isSubmitting = submittingNotifier.value;
+ final isDisabled = isImageLoading || isSubmitting;
+ return Row(
+ mainAxisAlignment: MainAxisAlignment.end,
+ children: [
+ TextButton(
+ onPressed: () => KazumiDialog.dismiss(),
+ child: Text(
+ '取消',
+ style: TextStyle(
+ color: Theme.of(context).colorScheme.outline),
+ ),
+ ),
+ const SizedBox(width: 8),
+ FilledButton(
+ onPressed: isDisabled ? null : doSubmit,
+ child: isSubmitting
+ ? const SizedBox(
+ width: 18,
+ height: 18,
+ child: CircularProgressIndicator(
+ strokeWidth: 2,
+ ),
+ )
+ : const Text('提交'),
+ ),
+ ],
+ );
+ },
+ ),
+ ],
+ ),
+ ),
+ ),
+ );
+ },
+ );
+ }
+
+ void showButtonClickDialog(Plugin plugin) {
+ /// flag whether onVerified was fired by the auto-click flow (cookies already saved + page unloaded)
+ bool autoVerified = false;
+
+ _captchaProvider?.dispose();
+ _captchaProvider = CaptchaProvider();
+
+ final searchUrl = plugin.searchURL.replaceAll('@keyword', keyword);
+
+ void onVerified() {
+ if (autoVerified) return;
+ autoVerified = true;
+ KazumiDialog.dismiss();
+ // show a 3s countdown progress dialog before re-querying
+ KazumiDialog.showTimedSuccessDialog(
+ title: '验证成功',
+ message: '正在重新检索,请稍候…',
+ onComplete: () => queryManager?.querySource(keyword, plugin.name),
+ );
+ }
+
+ _captchaProvider!.loadForButtonClick(
+ url: searchUrl,
+ buttonXpath: plugin.antiCrawlerConfig.captchaButton,
+ pluginName: plugin.name,
+ onVerified: onVerified,
+ );
+
+ KazumiDialog.show(
+ onDismiss: () async {
+ // Capture the current provider instance locally before any await.
+ final provider = _captchaProvider;
+ _captchaProvider = null;
+ if (autoVerified) {
+ // auto-verify already saved cookies and unloaded the page
+ provider?.dispose();
+ } else {
+ // save whatever cookies are present and unload the page
+ await provider?.saveAndUnload(plugin.name);
+ provider?.dispose();
+ queryManager?.querySource(keyword, plugin.name);
+ }
+ },
+ builder: (context) => Dialog(
+ clipBehavior: Clip.antiAlias,
+ child: Padding(
+ padding: const EdgeInsets.all(24),
+ child: SizedBox(
+ width: 400,
+ child: Column(
+ mainAxisSize: MainAxisSize.min,
+ crossAxisAlignment: CrossAxisAlignment.center,
+ children: [
+ Text(
+ '自动验证中',
+ style: Theme.of(context).textTheme.titleLarge,
+ ),
+ const SizedBox(height: 4),
+ Text(
+ '${plugin.name} 正在自动完成验证,请稍候',
+ style: Theme.of(context).textTheme.bodySmall,
+ ),
+ const SizedBox(height: 24),
+ const CircularProgressIndicator(),
+ const SizedBox(height: 12),
+ Text(
+ '已检测到验证按钮并模拟点击,等待验证通过…',
+ style: Theme.of(context).textTheme.bodyMedium,
+ textAlign: TextAlign.center,
+ ),
+ const SizedBox(height: 20),
+ Align(
+ alignment: Alignment.centerRight,
+ child: TextButton(
+ onPressed: () => KazumiDialog.dismiss(),
+ child: Text(
+ '取消',
+ style: TextStyle(
+ color: Theme.of(context).colorScheme.outline),
+ ),
+ ),
+ ),
+ ],
+ ),
+ ),
+ ),
+ ),
+ );
+ }
+
+ Widget buildPluginView(Plugin plugin, List<Widget> cardList) {
+ final status =
+ widget.infoController.pluginSearchStatus[plugin.name];
+ if (status == 'pending') {
+ return const Center(child: CircularProgressIndicator());
+ }
+ if (status == 'captcha') {
+ return GeneralErrorWidget(
+ errMsg: '${plugin.name} 需要验证码验证 完成验证后重新检索',
+ actions: [
+ GeneralErrorButton(
+ onPressed: () => showAntiCrawlerDialog(plugin),
+ text: '进行验证',
+ ),
+ GeneralErrorButton(
+ onPressed: () => queryManager?.querySource(keyword, plugin.name),
+ text: '重试',
+ ),
+ ],
+ );
+ }
+ if (status == 'noResult') {
+ return GeneralErrorWidget(
+ errMsg: '${plugin.name} 无结果 使用别名或左右滑动以切换到其他视频来源',
+ actions: [
+ GeneralErrorButton(
+ onPressed: () => showAliasSearchDialog(plugin.name),
+ text: '别名检索',
+ ),
+ GeneralErrorButton(
+ onPressed: () => showCustomSearchDialog(plugin.name),
+ text: '手动检索',
+ ),
+ ],
+ );
+ }
+ if (status == 'error') {
+ return GeneralErrorWidget(
+ errMsg: '${plugin.name} 检索失败 重试或左右滑动以切换到其他视频来源',
+ actions: [
+ GeneralErrorButton(
+ onPressed: () => queryManager?.querySource(keyword, plugin.name),
+ text: '重试',
+ ),
+ ],
+ );
+ }
+ return ListView(children: cardList);
+ }
+
void showAliasSearchDialog(String pluginName) {
if (widget.infoController.bangumiItem.alias.isEmpty) {
KazumiDialog.showToast(message: '无可用别名,试试手动检索');
@@ -198,23 +561,6 @@ class _SourceSheetState extends State<SourceSheet>
.map(
(plugin) => Observer(
builder: (context) {
- bool isSuccessButEmpty = false;
- if (widget.infoController
- .pluginSearchStatus[plugin.name] ==
- 'success') {
- bool hasContent = false;
- for (var searchResponse in widget
- .infoController.pluginSearchResponseList) {
- if (searchResponse.pluginName ==
- plugin.name &&
- searchResponse.data.isNotEmpty) {
- hasContent = true;
- break;
- }
- }
- isSuccessButEmpty = !hasContent;
- }
-
return Tab(
child: Row(
children: [
@@ -235,19 +581,14 @@ class _SourceSheetState extends State<SourceSheet>
width: 8.0,
height: 8.0,
decoration: BoxDecoration(
- color: isSuccessButEmpty
- ? Colors.orange
- : (widget.infoController
- .pluginSearchStatus[
- plugin.name] ==
- 'success'
- ? Colors.green
- : (widget.infoController
- .pluginSearchStatus[
- plugin.name] ==
- 'pending')
- ? Colors.grey
- : Colors.red),
+ color: switch (widget.infoController
+ .pluginSearchStatus[plugin.name]) {
+ 'success' => Colors.green,
+ 'noResult' => Colors.orange,
+ 'captcha' => Colors.blue,
+ 'error' => Colors.red,
+ _ => Colors.grey,
+ },
shape: BoxShape.circle,
),
),
@@ -314,8 +655,8 @@ class _SourceSheetState extends State<SourceSheet>
KazumiDialog.dismiss();
Modular.to.pushNamed('/video/');
} catch (_) {
- KazumiLogger()
- .w("QueryManager: failed to query video playlist");
+ KazumiLogger().w(
+ "QueryManager: failed to query video playlist");
KazumiDialog.dismiss();
}
},
@@ -329,49 +670,7 @@ class _SourceSheetState extends State<SourceSheet>
}
}
}
- return widget.infoController
- .pluginSearchStatus[plugin.name] ==
- 'pending'
- ? const Center(child: CircularProgressIndicator())
- : (widget.infoController
- .pluginSearchStatus[plugin.name] ==
- 'error'
- ? GeneralErrorWidget(
- errMsg: '${plugin.name} 检索失败 重试或左右滑动以切换到其他视频来源',
- actions: [
- GeneralErrorButton(
- onPressed: () {
- queryManager?.querySource(
- keyword, plugin.name);
- },
- text: '重试',
- ),
- ],
- )
- : cardList.isEmpty
- ? GeneralErrorWidget(
- errMsg:
- '${plugin.name} 无结果 使用别名或左右滑动以切换到其他视频来源',
- actions: [
- GeneralErrorButton(
- onPressed: () {
- showAliasSearchDialog(
- plugin.name,
- );
- },
- text: '别名检索',
- ),
- GeneralErrorButton(
- onPressed: () {
- showCustomSearchDialog(
- plugin.name,
- );
- },
- text: '手动检索',
- ),
- ],
- )
- : ListView(children: cardList));
+ return buildPluginView(plugin, cardList);
}),
),
),
diff --git a/lib/pages/plugin_editor/plugin_editor_page.dart b/lib/pages/plugin_editor/plugin_editor_page.dart
index 0b8d29a1..94f1f26c 100644
--- a/lib/pages/plugin_editor/plugin_editor_page.dart
+++ b/lib/pages/plugin_editor/plugin_editor_page.dart
@@ -1,6 +1,9 @@
+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/anti_crawler_config.dart';
import 'package:kazumi/plugins/plugins_controller.dart';
import 'package:kazumi/bean/appbar/sys_app_bar.dart';
@@ -35,6 +38,19 @@ class _PluginEditorPageState extends State<PluginEditorPage> {
bool useLegacyParser = false;
bool adBlocker = false;
+ // AntiCrawler fields
+ final TextEditingController captchaImageController = TextEditingController();
+ final TextEditingController captchaInputController = TextEditingController();
+ final TextEditingController captchaButtonController = TextEditingController();
+ bool antiCrawlerEnabled = false;
+ int captchaType = CaptchaType.imageCaptcha;
+ final MenuController captchaTypeMenuController = MenuController();
+
+ static const Map<int, String> _captchaTypeMap = {
+ CaptchaType.imageCaptcha: '图片验证码',
+ CaptchaType.autoClickButton: '自动点击按钮',
+ };
+
@override
void initState() {
super.initState();
@@ -58,11 +74,17 @@ class _PluginEditorPageState extends State<PluginEditorPage> {
usePost = plugin.usePost;
useLegacyParser = plugin.useLegacyParser;
adBlocker = plugin.adBlocker;
+ antiCrawlerEnabled = plugin.antiCrawlerConfig.enabled;
+ captchaType = plugin.antiCrawlerConfig.captchaType;
+ captchaImageController.text = plugin.antiCrawlerConfig.captchaImage;
+ captchaInputController.text = plugin.antiCrawlerConfig.captchaInput;
+ captchaButtonController.text = plugin.antiCrawlerConfig.captchaButton;
}
@override
Widget build(BuildContext context) {
final Plugin plugin = Modular.args.data as Plugin;
+ final fontFamily = Theme.of(context).textTheme.bodyMedium?.fontFamily;
return Scaffold(
appBar: const SysAppBar(
@@ -133,57 +155,146 @@ class _PluginEditorPageState extends State<PluginEditorPage> {
title: const Text('高级选项'),
shape: const RoundedRectangleBorder(borderRadius: BorderRadius.zero),
children: [
- SwitchListTile(
- title: const Text('简易解析'),
- subtitle: const Text('使用简易解析器而不是现代解析器'),
- value: useLegacyParser,
- onChanged: (bool value) {
- setState(() {
- useLegacyParser = value;
- });
- },
- ),
- SwitchListTile(
- title: const Text('POST'),
- subtitle: const Text('使用POST而不是GET进行检索'),
- value: usePost,
- onChanged: (bool value) {
- setState(() {
- usePost = value;
- });
- },
- ),
- SwitchListTile(
- title: const Text('内置播放器'),
- subtitle: const Text('使用内置播放器播放视频'),
- value: useNativePlayer,
- onChanged: (bool value) {
- setState(() {
- useNativePlayer = value;
- });
- },
+ SettingsSection(
+ title: Text('行为设置', style: TextStyle(fontFamily: fontFamily)),
+ tiles: [
+ SettingsTile.switchTile(
+ title: Text('简易解析', style: TextStyle(fontFamily: fontFamily)),
+ description: Text('使用简易解析器而不是现代解析器', style: TextStyle(fontFamily: fontFamily)),
+ initialValue: useLegacyParser,
+ 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)),
+ description: Text('启用 HLS 广告过滤', style: TextStyle(fontFamily: fontFamily)),
+ initialValue: adBlocker,
+ onToggle: (v) => setState(() => adBlocker = v ?? !adBlocker),
+ ),
+ ],
),
- SwitchListTile(
- title: const Text('广告过滤'),
- subtitle: const Text('启用HLS广告过滤'),
- value: adBlocker,
- onChanged: (bool value) {
- setState(() {
- adBlocker = value;
- });
- },
+ SettingsSection(
+ title: Text('网络设置', style: TextStyle(fontFamily: fontFamily)),
+ tiles: [
+ CustomSettingsTile(
+ child: (info) => _buildTextFieldTile(
+ context, info,
+ controller: userAgentController,
+ label: 'UserAgent',
+ ),
+ ),
+ CustomSettingsTile(
+ child: (info) => _buildTextFieldTile(
+ context, info,
+ controller: refererController,
+ label: 'Referer',
+ ),
+ ),
+ ],
),
- const SizedBox(height: 20),
- TextField(
- controller: userAgentController,
- decoration: const InputDecoration(
- labelText: 'UserAgent', border: OutlineInputBorder()),
- ),
- const SizedBox(height: 20),
- TextField(
- controller: refererController,
- decoration: const InputDecoration(
- labelText: 'Referer', border: OutlineInputBorder()),
+ 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('验证类型', style: TextStyle(fontFamily: fontFamily)),
+ description: Text(
+ captchaType == CaptchaType.imageCaptcha
+ ? '图片验证码(展示验证码图片,用户手动输入)'
+ : '自动点击验证按钮(检测到按钮后自动模拟点击)',
+ style: TextStyle(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,
+ ),
+ ),
+ ),
+ ),
+ ),
+ ],
+ ),
+ ),
+ 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',
+ ),
+ ),
+ ],
+ 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,检测到后自动点击',
+ ),
+ ),
+ ],
+ ],
),
],
),
@@ -218,7 +329,14 @@ class _PluginEditorPageState extends State<PluginEditorPage> {
searchResult: searchResultController.text,
chapterRoads: chapterRoadsController.text,
chapterResult: chapterResultController.text,
- referer: refererController.text);
+ referer: refererController.text,
+ antiCrawlerConfig: AntiCrawlerConfig(
+ enabled: antiCrawlerEnabled,
+ captchaType: captchaType,
+ captchaImage: captchaImageController.text,
+ captchaInput: captchaInputController.text,
+ captchaButton: captchaButtonController.text,
+ ));
Modular.to.pushNamed('/settings/plugin/test', arguments: pluginText);
},
),
@@ -246,6 +364,13 @@ class _PluginEditorPageState extends State<PluginEditorPage> {
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,
+ );
pluginsController.updatePlugin(plugin);
Navigator.of(context).pop();
},
@@ -254,4 +379,43 @@ class _PluginEditorPageState extends State<PluginEditorPage> {
),
);
}
+
+ Widget _buildTextFieldTile(
+ BuildContext context,
+ SettingsTileInfo info, {
+ required TextEditingController controller,
+ required String label,
+ String? hint,
+ String? helper,
+ }) {
+ return Column(
+ mainAxisSize: MainAxisSize.min,
+ children: [
+ ClipRRect(
+ borderRadius: BorderRadius.vertical(
+ top: Radius.circular(info.isTopTile ? 20 : 3),
+ bottom: Radius.circular(info.isBottomTile ? 20 : 3),
+ ),
+ child: Material(
+ color: Theme.of(context).brightness == Brightness.light
+ ? Theme.of(context).colorScheme.surfaceContainerLowest
+ : Theme.of(context).colorScheme.surfaceContainerHigh,
+ child: Padding(
+ padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12),
+ child: TextField(
+ controller: controller,
+ decoration: InputDecoration(
+ labelText: label,
+ hintText: hint,
+ helperText: helper,
+ border: const OutlineInputBorder(),
+ ),
+ ),
+ ),
+ ),
+ ),
+ if (info.needDivider) const SizedBox(height: 2),
+ ],
+ );
+ }
}
diff --git a/lib/pages/plugin_editor/plugin_shop_page.dart b/lib/pages/plugin_editor/plugin_shop_page.dart
index 6b955dde..48e8b619 100644
--- a/lib/pages/plugin_editor/plugin_shop_page.dart
+++ b/lib/pages/plugin_editor/plugin_shop_page.dart
@@ -131,6 +131,24 @@ class _PluginShopPageState extends State<PluginShopPage> {
color: Theme.of(context).colorScheme.surface),
),
),
+ if (sortedList[index].antiCrawlerEnabled) ...[
+ const SizedBox(width: 5),
+ Container(
+ padding: const EdgeInsets.symmetric(
+ horizontal: 8.0, vertical: 1.0),
+ decoration: BoxDecoration(
+ color: Theme.of(context).colorScheme.tertiary,
+ borderRadius: BorderRadius.circular(16.0),
+ ),
+ child: Text(
+ 'captcha',
+ style: TextStyle(
+ color: Theme.of(context)
+ .colorScheme
+ .onTertiary),
+ ),
+ ),
+ ],
],
),
if (sortedList[index].lastUpdate > 0) ...[
diff --git a/lib/pages/video/video_controller.dart b/lib/pages/video/video_controller.dart
index 23934064..fe14213f 100644
--- a/lib/pages/video/video_controller.dart
+++ b/lib/pages/video/video_controller.dart
@@ -9,7 +9,7 @@ import 'package:kazumi/modules/bangumi/bangumi_item.dart';
import 'package:kazumi/modules/download/download_module.dart';
import 'package:kazumi/repositories/download_repository.dart';
import 'package:kazumi/utils/download_manager.dart';
-import 'package:kazumi/providers/providers.dart';
+import 'package:kazumi/providers/video/providers.dart';
import 'package:kazumi/bean/dialog/dialog_helper.dart';
import 'package:mobx/mobx.dart';
import 'package:kazumi/utils/utils.dart';
diff --git a/lib/plugins/anti_crawler_config.dart b/lib/plugins/anti_crawler_config.dart
new file mode 100644
index 00000000..461c4f7b
--- /dev/null
+++ b/lib/plugins/anti_crawler_config.dart
@@ -0,0 +1,93 @@
+/// 反反爬虫验证类型
+///
+/// - [imageCaptcha] (1): WebView 抓取验证码图片,引导用户手动输入后提交
+/// - [autoClickButton] (2): WebView 检测到验证按钮后自动点击,无需用户交互
+///
+/// 保留整数表示以便将来新增第三种及更多验证方式时向后兼容。
+class CaptchaType {
+ static const int imageCaptcha = 1;
+ static const int autoClickButton = 2;
+}
+
+/// 反反爬虫配置
+///
+/// 当网站对搜索请求返回验证码时,使用 WebView 加载搜索页,
+/// 根据 [captchaType] 采用不同策略完成验证,之后保存 Cookie 用于后续请求。
+class AntiCrawlerConfig {
+ /// 是否启用反反爬虫功能
+ bool enabled;
+
+ /// 验证类型,见 [CaptchaType] 中的常量
+ ///
+ /// - [CaptchaType.imageCaptcha] (1):图片验证码,需要用户手动输入
+ /// - [CaptchaType.autoClickButton] (2):自动点击验证按钮,无需用户交互
+ int captchaType;
+
+ /// 验证码图片元素的 XPath 选择器(仅 captchaType == 1 时使用)
+ /// 用于在 WebView 页面中定位验证码图片,通过 Canvas 抓取其像素
+ String captchaImage;
+
+ /// 验证码输入框元素的 XPath 选择器(仅 captchaType == 1 时使用)
+ /// 用于在 WebView 页面中定位供用户输入验证码的 input 元素
+ String captchaInput;
+
+ /// 验证按钮元素的 XPath 选择器
+ ///
+ /// - captchaType == 1:提交验证码的按钮,模拟点击提交
+ /// - captchaType == 2:目标验证按钮(如"我不是机器人"),检测到后自动点击
+ String captchaButton;
+
+ AntiCrawlerConfig({
+ required this.enabled,
+ required this.captchaType,
+ required this.captchaImage,
+ required this.captchaInput,
+ required this.captchaButton,
+ });
+
+ factory AntiCrawlerConfig.fromJson(Map<String, dynamic> json) {
+ return AntiCrawlerConfig(
+ enabled: json['enabled'] ?? false,
+ captchaType: json['captchaType'] ?? CaptchaType.imageCaptcha,
+ captchaImage: json['captchaImage'] ?? '',
+ captchaInput: json['captchaInput'] ?? '',
+ captchaButton: json['captchaButton'] ?? '',
+ );
+ }
+
+ factory AntiCrawlerConfig.empty() {
+ return AntiCrawlerConfig(
+ enabled: false,
+ captchaType: CaptchaType.imageCaptcha,
+ captchaImage: '',
+ captchaInput: '',
+ captchaButton: '',
+ );
+ }
+
+ Map<String, dynamic> toJson() {
+ return {
+ 'enabled': enabled,
+ 'captchaType': captchaType,
+ 'captchaImage': captchaImage,
+ 'captchaInput': captchaInput,
+ 'captchaButton': captchaButton,
+ };
+ }
+
+ AntiCrawlerConfig copyWith({
+ bool? enabled,
+ int? captchaType,
+ String? captchaImage,
+ String? captchaInput,
+ String? captchaButton,
+ }) {
+ return AntiCrawlerConfig(
+ enabled: enabled ?? this.enabled,
+ captchaType: captchaType ?? this.captchaType,
+ captchaImage: captchaImage ?? this.captchaImage,
+ captchaInput: captchaInput ?? this.captchaInput,
+ captchaButton: captchaButton ?? this.captchaButton,
+ );
+ }
+}
diff --git a/lib/plugins/plugin_cookie_manager.dart b/lib/plugins/plugin_cookie_manager.dart
new file mode 100644
index 00000000..12003ef2
--- /dev/null
+++ b/lib/plugins/plugin_cookie_manager.dart
@@ -0,0 +1,62 @@
+import 'package:cookie_jar/cookie_jar.dart';
+import 'package:kazumi/utils/logger.dart';
+
+/// 每条规则的 Cookie 管理器
+///
+/// 为每条规则维护一个独立的内存 [CookieJar],
+/// 通过 [saveFromWebView] 将 WebView 捕获的 document.cookie 字符串
+/// 解析后存入对应规则的 jar,用于后续 HTTP 请求的 CookieManager 拦截器。
+/// Cookie 仅在当前 App 会话内有效,重启后需重新验证。
+class PluginCookieManager {
+ PluginCookieManager._();
+ static final PluginCookieManager instance = PluginCookieManager._();
+
+ final Map<String, CookieJar> _jars = {};
+
+ CookieJar getJar(String pluginName) {
+ return _jars.putIfAbsent(pluginName, () => CookieJar());
+ }
+
+ Future<void> saveFromWebView(
+ String pluginName, String pageUrl, String cookieString) async {
+ if (cookieString.trim().isEmpty) return;
+ final uri = Uri.tryParse(pageUrl);
+ if (uri == null) return;
+
+ final jar = getJar(pluginName);
+ final cookies = _parseCookieString(cookieString, uri);
+ if (cookies.isEmpty) return;
+
+ await jar.saveFromResponse(uri, cookies);
+ KazumiLogger().i(
+ '[PluginCookieManager] Saved ${cookies.length} cookies for $pluginName');
+ }
+
+ /// 解析字符串为 [Cookie] 列表
+ List<Cookie> _parseCookieString(String raw, Uri uri) {
+ final cookies = <Cookie>[];
+ for (final part in raw.split(';')) {
+ final trimmed = part.trim();
+ if (trimmed.isEmpty) continue;
+ final eqIndex = trimmed.indexOf('=');
+ if (eqIndex <= 0) continue;
+ final name = trimmed.substring(0, eqIndex).trim();
+ final value = trimmed.substring(eqIndex + 1).trim();
+ try {
+ final cookie = Cookie(name, value)
+ ..domain = uri.host
+ ..path = '/';
+ cookies.add(cookie);
+ } catch (_) {}
+ }
+ return cookies;
+ }
+
+ void clearCookies(String pluginName) {
+ _jars.remove(pluginName);
+ }
+
+ bool hasCookies(String pluginName) {
+ return _jars.containsKey(pluginName);
+ }
+}
diff --git a/lib/plugins/plugins.dart b/lib/plugins/plugins.dart
index 731869a5..7bc34ce3 100644
--- a/lib/plugins/plugins.dart
+++ b/lib/plugins/plugins.dart
@@ -7,6 +7,37 @@ import 'package:kazumi/request/api.dart';
import 'package:kazumi/utils/logger.dart';
import 'package:xpath_selector_html_parser/xpath_selector_html_parser.dart';
import 'package:kazumi/utils/utils.dart';
+import 'package:kazumi/plugins/anti_crawler_config.dart';
+import 'package:kazumi/plugins/plugin_cookie_manager.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)' : ''}';
+}
class Plugin {
String api;
@@ -29,6 +60,7 @@ class Plugin {
String chapterRoads;
String chapterResult;
String referer;
+ AntiCrawlerConfig antiCrawlerConfig;
Plugin({
required this.api,
@@ -50,7 +82,8 @@ class Plugin {
required this.chapterRoads,
required this.chapterResult,
required this.referer,
- });
+ AntiCrawlerConfig? antiCrawlerConfig,
+ }) : antiCrawlerConfig = antiCrawlerConfig ?? AntiCrawlerConfig.empty();
factory Plugin.fromJson(Map<String, dynamic> json) {
return Plugin(
@@ -72,7 +105,11 @@ class Plugin {
searchResult: json['searchResult'],
chapterRoads: json['chapterRoads'],
chapterResult: json['chapterResult'],
- referer: json['referer'] ?? '');
+ referer: json['referer'] ?? '',
+ antiCrawlerConfig: json['antiCrawlerConfig'] != null
+ ? AntiCrawlerConfig.fromJson(
+ Map<String, dynamic>.from(json['antiCrawlerConfig']))
+ : AntiCrawlerConfig.empty());
}
factory Plugin.fromTemplate() {
@@ -95,7 +132,8 @@ class Plugin {
searchResult: '',
chapterRoads: '',
chapterResult: '',
- referer: '');
+ referer: '',
+ antiCrawlerConfig: AntiCrawlerConfig.empty());
}
Map<String, dynamic> toJson() {
@@ -119,14 +157,17 @@ class Plugin {
data['chapterRoads'] = chapterRoads;
data['chapterResult'] = chapterResult;
data['referer'] = referer;
+ data['antiCrawlerConfig'] = antiCrawlerConfig.toJson();
return data;
}
Future<PluginSearchResponse> queryBangumi(String keyword,
{bool shouldRethrow = false}) async {
+ try {
String queryURL = searchURL.replaceAll('@keyword', keyword);
dynamic resp;
List<SearchItem> searchItems = [];
+ final String cookieHeader = await _cookieHeaderFor(queryURL);
if (usePost) {
Uri uri = Uri.parse(queryURL);
Map<String, String> queryParams = uri.queryParameters;
@@ -140,6 +181,7 @@ class Plugin {
'Content-Type': 'application/x-www-form-urlencoded',
'Accept-Language': Utils.getRandomAcceptedLanguage(),
'Connection': 'keep-alive',
+ if (cookieHeader.isNotEmpty) 'Cookie': cookieHeader,
};
resp = await Request().post(postUri.toString(),
options: Options(headers: httpHeaders),
@@ -151,6 +193,7 @@ class Plugin {
'referer': '$baseUrl/',
'Accept-Language': Utils.getRandomAcceptedLanguage(),
'Connection': 'keep-alive',
+ if (cookieHeader.isNotEmpty) 'Cookie': cookieHeader,
};
resp = await Request().get(queryURL,
options: Options(headers: httpHeaders),
@@ -161,6 +204,22 @@ class Plugin {
var htmlString = resp.data.toString();
var htmlElement = parse(htmlString).documentElement!;
+ // Detect captcha challenge: if antiCrawlerConfig is enabled, check both
+ // captchaImage and captchaButton XPaths — if either matches, throw so
+ // callers can show the dedicated captcha UI instead of a generic error.
+ if (antiCrawlerConfig.enabled) {
+ final List<String> detectionXpaths = [
+ antiCrawlerConfig.captchaImage,
+ antiCrawlerConfig.captchaButton,
+ ].where((x) => x.isNotEmpty).toList();
+ final bool captchaDetected = detectionXpaths.any(
+ (xpath) => htmlElement.queryXPath(xpath).node != null);
+ if (captchaDetected) {
+ KazumiLogger().w('Plugin: $name detected captcha challenge in search response');
+ throw CaptchaRequiredException(name);
+ }
+ }
+
htmlElement.queryXPath(searchList).nodes.forEach((element) {
try {
SearchItem searchItem = SearchItem(
@@ -172,14 +231,21 @@ class Plugin {
'Plugin: $name ${element.queryXPath(searchName).node!.text ?? ''} $baseUrl${element.queryXPath(searchResult).node!.attributes['href'] ?? ''}');
} catch (_) {}
});
- PluginSearchResponse pluginSearchResponse =
- PluginSearchResponse(pluginName: name, data: searchItems);
- return pluginSearchResponse;
+ if (searchItems.isEmpty) throw NoResultException(name);
+ return PluginSearchResponse(pluginName: name, data: searchItems);
+ } 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: []);
+ }
}
Future<List<Road>> querychapterRoads(String url, {CancelToken? cancelToken}) async {
List<Road> roadList = [];
- // 预处理
if (!url.contains('https')) {
url = url.replaceAll('http', 'https');
}
@@ -225,7 +291,7 @@ class Plugin {
}
Future<String> testSearchRequest(String keyword,
- {bool shouldRethrow = false,CancelToken? cancelToken}) async {
+ {bool shouldRethrow = false, CancelToken? cancelToken}) async {
String queryURL = searchURL.replaceAll('@keyword', keyword);
dynamic resp;
if (usePost) {
@@ -255,7 +321,7 @@ class Plugin {
'Connection': 'keep-alive',
};
resp = await Request().get(queryURL,
- options: Options(headers: httpHeaders,),
+ options: Options(headers: httpHeaders),
shouldRethrow: shouldRethrow,
extra: {'customError': ''},
cancelToken: cancelToken);
@@ -264,6 +330,20 @@ class Plugin {
return resp.data.toString();
}
+ 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 '';
+ }
+ }
+
String buildFullUrl(String urlItem) {
if (urlItem.contains(baseUrl) ||
urlItem.contains(baseUrl.replaceAll('https', 'http'))) {
diff --git a/lib/providers/captcha/captcha_provider.dart b/lib/providers/captcha/captcha_provider.dart
new file mode 100644
index 00000000..b11de430
--- /dev/null
+++ b/lib/providers/captcha/captcha_provider.dart
@@ -0,0 +1,205 @@
+import 'dart:async';
+
+import 'package:kazumi/webview/captcha/captcha_webview_controller.dart';
+import 'package:kazumi/plugins/plugin_cookie_manager.dart';
+import 'package:kazumi/utils/logger.dart';
+
+/// 验证码解决 Provider
+///
+/// 支持两种独立的验证流程:
+///
+/// **类型1:图片验证码**([loadForCaptcha] + [submitCaptcha])
+/// 1. 初始化 WebView
+/// 2. 加载搜索页面,注入 JS 脚本监听验证码图片
+/// 3. 通过 [onCaptchaImageUrl] 流将验证码图片 URL 暴露给 UI
+/// 4. UI 将用户输入的验证码传给 [submitCaptcha]
+/// 5. 页面通过 AJAX 提交验证码
+/// 6. 验证码图片消失后,获取页面 Cookie 并保存到 [PluginCookieManager]
+/// 7. UI 发起重新检索
+///
+/// **类型2:自动点击验证按钮**([loadForButtonClick])
+/// 1. 初始化 WebView
+/// 2. 加载搜索页面,注入 JS 脚本轮询验证按钮
+/// 3. 检测到按钮后自动模拟点击
+/// 4. 按钮消失时,获取页面 Cookie 并保存到 [PluginCookieManager]
+/// 5. 通过 [onVerified] 回调通知 UI 发起重新检索
+class CaptchaProvider {
+ CaptchaWebviewController? _controller;
+
+ final StreamController<String?> _captchaImageStreamController =
+ StreamController<String?>.broadcast();
+
+ Stream<String?> get onCaptchaImageUrl => _captchaImageStreamController.stream;
+
+ StreamSubscription? _imageFoundSub;
+ StreamSubscription? _disappearedSub;
+ StreamSubscription? _logSub;
+
+ bool _isInitialized = false;
+ bool _disposed = false;
+ String _pageUrl = '';
+
+ Future<void> _ensureInitialized() async {
+ if (_isInitialized || _disposed) return;
+ _controller = CaptchaWebviewControllerFactory.getController();
+ final initializedFuture = _controller!.onInitialized.first
+ .timeout(const Duration(seconds: 10), onTimeout: () => false);
+
+ await _controller!.init();
+ if (_disposed) return;
+ await initializedFuture;
+ if (_disposed) return;
+
+ _logSub?.cancel();
+ _logSub = _controller!.onLog.listen((msg) => KazumiLogger().d(msg));
+
+ _isInitialized = true;
+ KazumiLogger().i('[CaptchaProvider] WebView initialized');
+ }
+
+ /// 加载指定页面并开始监听验证码图片
+ ///
+ /// [url] 要加载的页面地址
+ /// [captchaXpath] 验证码图片元素的 XPath
+ /// [inputXpath] 可选,验证码输入框的 XPath。如果提供,会在检测验证码前先触发输入框的 focus 事件
+ Future<void> loadForCaptcha(String url, String captchaXpath, {String? inputXpath}) async {
+ _pageUrl = url;
+ await _ensureInitialized();
+ if (_disposed || _controller == null) return;
+
+ _imageFoundSub?.cancel();
+ _imageFoundSub = _controller!.onCaptchaImageFound.listen((src) {
+ KazumiLogger().i('[CaptchaProvider] Captcha image found: $src');
+ if (!_captchaImageStreamController.isClosed) {
+ _captchaImageStreamController.add(src);
+ }
+ });
+
+ await _controller!.loadPage(url, captchaXpath, inputXpath: inputXpath);
+ KazumiLogger().i('[CaptchaProvider] Page loading: $url');
+ }
+
+ /// 提交验证码
+ ///
+ /// [captchaCode] 用户输入的验证码文本
+ /// [inputXpath] 验证码输入框元素的 XPath
+ /// [buttonXpath] 验证提交按钮元素的 XPath
+ /// [pluginName] 规则名(用于保存 Cookie)
+ /// [onVerified] 验证成功后的回调
+ Future<void> submitCaptcha({
+ required String captchaCode,
+ required String inputXpath,
+ required String buttonXpath,
+ required String pluginName,
+ required void Function() onVerified,
+ }) async {
+ if (_controller == null) {
+ KazumiLogger().w('[CaptchaProvider] submitCaptcha called before init');
+ return;
+ }
+
+ KazumiLogger().i('[CaptchaProvider] Submitting captcha code via interact');
+
+ bool _handled = false;
+
+ Future<void> onDisappeared() async {
+ if (_handled) return;
+ _handled = true;
+ _disappearedSub?.cancel();
+ final cookieString = await _controller!.getCookieString(_pageUrl);
+ KazumiLogger().i('[CaptchaProvider] Captured cookies: $cookieString');
+ if (cookieString.isNotEmpty) {
+ await PluginCookieManager.instance
+ .saveFromWebView(pluginName, _pageUrl, cookieString);
+ KazumiLogger()
+ .i('[CaptchaProvider] Cookies saved for plugin: $pluginName');
+ }
+ await _controller!.unloadPage();
+ onVerified();
+ }
+ _disappearedSub?.cancel();
+ _disappearedSub = _controller!.onCaptchaDisappeared.listen((_) {
+ onDisappeared();
+ });
+ await _controller!.submitCaptchaInteract(captchaCode, inputXpath, buttonXpath);
+ }
+
+ /// 加载页面并自动点击验证按钮
+ ///
+ /// [url] 要加载的页面地址
+ /// [buttonXpath] 验证按钮元素的 XPath,检测到后自动点击
+ /// [pluginName] 规则名(用于保存 Cookie)
+ /// [onVerified] 按钮消失(验证通过)后的回调
+ Future<void> loadForButtonClick({
+ required String url,
+ required String buttonXpath,
+ required String pluginName,
+ required void Function() 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 cookieString = await _controller!.getCookieString(_pageUrl);
+ KazumiLogger().i('[CaptchaProvider] (type2) Captured cookies: $cookieString');
+ if (cookieString.isNotEmpty) {
+ await PluginCookieManager.instance
+ .saveFromWebView(pluginName, _pageUrl, cookieString);
+ KazumiLogger()
+ .i('[CaptchaProvider] (type2) Cookies saved for plugin: $pluginName');
+ }
+ await _controller!.unloadPage();
+ onVerified();
+ }
+
+ _disappearedSub?.cancel();
+ _disappearedSub = _controller!.onCaptchaDisappeared.listen((_) {
+ onDisappeared();
+ });
+
+ await _controller!.loadPageForButtonClick(url, buttonXpath);
+ KazumiLogger().i('[CaptchaProvider] (type2) Page loading for button click: $url');
+ }
+
+ Future<void> saveAndUnload(String pluginName) async {
+ _disappearedSub?.cancel();
+ _disappearedSub = null;
+ // Capture locally before any await so dispose() nulling _controller
+ // between two awaits cannot cause a force-unwrap crash.
+ final controller = _controller;
+ if (controller == null || _pageUrl.isEmpty) return;
+ final cookieString = await controller.getCookieString(_pageUrl);
+ KazumiLogger()
+ .i('[CaptchaProvider] Captured cookies on cancel: $cookieString');
+ if (cookieString.isNotEmpty) {
+ await PluginCookieManager.instance
+ .saveFromWebView(pluginName, _pageUrl, cookieString);
+ KazumiLogger()
+ .i('[CaptchaProvider] Cookies saved on cancel for plugin: $pluginName');
+ }
+ await controller.unloadPage();
+ }
+
+ Stream<String>? get onLog => _controller?.onLog;
+
+ void dispose() {
+ if (_disposed) return;
+ _disposed = true;
+ _imageFoundSub?.cancel();
+ _disappearedSub?.cancel();
+ _logSub?.cancel();
+ if (!_captchaImageStreamController.isClosed) {
+ _captchaImageStreamController.close();
+ }
+ _controller?.dispose();
+ _controller = null;
+ _isInitialized = false;
+ KazumiLogger().i('[CaptchaProvider] Disposed');
+ }
+}
diff --git a/lib/providers/providers.dart b/lib/providers/video/providers.dart
similarity index 100%
rename from lib/providers/providers.dart
rename to lib/providers/video/providers.dart
diff --git a/lib/providers/video_source_provider.dart b/lib/providers/video/video_source_provider.dart
similarity index 100%
rename from lib/providers/video_source_provider.dart
rename to lib/providers/video/video_source_provider.dart
diff --git a/lib/providers/webview_video_source_provider.dart b/lib/providers/video/webview_video_source_provider.dart
similarity index 91%
rename from lib/providers/webview_video_source_provider.dart
rename to lib/providers/video/webview_video_source_provider.dart
index 5ee1d8ef..2fe5ca81 100644
--- a/lib/providers/webview_video_source_provider.dart
+++ b/lib/providers/video/webview_video_source_provider.dart
@@ -1,7 +1,7 @@
import 'dart:async';
-import 'package:kazumi/webview/webview_controller.dart';
-import 'package:kazumi/providers/video_source_provider.dart';
+import 'package:kazumi/webview/video/video_webview_controller.dart';
+import 'package:kazumi/providers/video/video_source_provider.dart';
/// WebView 视频源提供者
///
@@ -9,7 +9,7 @@ import 'package:kazumi/providers/video_source_provider.dart';
/// WebView 实例在 Provider 生命周期内复用,切换集数时调用 unloadPage 释放页面资源,
/// 仅在 [dispose] 时才真正销毁 WebView。
class WebViewVideoSourceProvider implements IVideoSourceProvider {
- WebviewItemController? _webview;
+ VideoWebviewController? _webview;
StreamSubscription? _logSubscription;
/// 单个 Provider 实例不能实现并发解析,单个 Provider 实例只能持有一个 Webview
@@ -32,7 +32,7 @@ class WebViewVideoSourceProvider implements IVideoSourceProvider {
final currentResolveId = _resolveId;
if (_webview == null) {
- _webview = WebviewItemControllerFactory.getController();
+ _webview = VideoWebviewControllerFactory.getController();
await _webview!.init();
_logSubscription = _webview!.onLog.listen((log) {
diff --git a/lib/request/api.dart b/lib/request/api.dart
index 639159de..167bbdad 100644
--- a/lib/request/api.dart
+++ b/lib/request/api.dart
@@ -2,7 +2,7 @@ class Api {
/// 当前版本
static const String version = '2.0.4';
/// 规则API级别
- static const int apiLevel = 5;
+ static const int apiLevel = 6;
/// 项目主页
static const String projectUrl = "https://kazumi.app/";
/// Github 项目主页
diff --git a/lib/request/query_manager.dart b/lib/request/query_manager.dart
index c99a23d3..0fdec035 100644
--- a/lib/request/query_manager.dart
+++ b/lib/request/query_manager.dart
@@ -4,6 +4,7 @@ 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_controller.dart';
+import 'package:kazumi/utils/logger.dart';
class QueryManager {
QueryManager({
@@ -43,7 +44,17 @@ class QueryManager {
return;
}
- infoController.pluginSearchStatus[plugin.name] = 'error';
+ if (error is CaptchaRequiredException) {
+ KazumiLogger().w('QueryManager: captcha required for ${error.pluginName}');
+ infoController.pluginSearchStatus[error.pluginName] = 'captcha';
+ } else if (error is NoResultException) {
+ KazumiLogger().i('QueryManager: no results for ${error.pluginName}');
+ infoController.pluginSearchStatus[error.pluginName] = 'noResult';
+ } else {
+ final name = error is SearchErrorException ? error.pluginName : plugin.name;
+ KazumiLogger().w('QueryManager: search error for $name');
+ infoController.pluginSearchStatus[name] = 'error';
+ }
});
}
}
@@ -75,7 +86,17 @@ class QueryManager {
return;
}
- infoController.pluginSearchStatus[plugin.name] = 'error';
+ if (error is CaptchaRequiredException) {
+ KazumiLogger().w('QueryManager: captcha required for ${error.pluginName}');
+ infoController.pluginSearchStatus[error.pluginName] = 'captcha';
+ } else if (error is NoResultException) {
+ KazumiLogger().i('QueryManager: no results for ${error.pluginName}');
+ infoController.pluginSearchStatus[error.pluginName] = 'noResult';
+ } else {
+ final name = error is SearchErrorException ? error.pluginName : plugin.name;
+ KazumiLogger().w('QueryManager: search error for $name');
+ infoController.pluginSearchStatus[name] = 'error';
+ }
});
}
diff --git a/lib/webview/captcha/captcha_webview_controller.dart b/lib/webview/captcha/captcha_webview_controller.dart
new file mode 100644
index 00000000..3cb4091a
--- /dev/null
+++ b/lib/webview/captcha/captcha_webview_controller.dart
@@ -0,0 +1,78 @@
+import 'dart:io';
+import 'dart:async';
+
+import 'package:kazumi/webview/captcha/impl/captcha_webview_inappwebview_impl.dart';
+import 'package:kazumi/webview/captcha/impl/captcha_webview_windows_impl.dart';
+import 'package:kazumi/webview/captcha/impl/captcha_webview_linux_impl.dart';
+
+abstract class CaptchaWebviewController {
+ final StreamController<String> captchaImageFoundController =
+ StreamController<String>.broadcast();
+ final StreamController<void> captchaDisappearedController =
+ StreamController<void>.broadcast();
+ final StreamController<bool> initEventController =
+ StreamController<bool>.broadcast();
+ final StreamController<String> logEventController =
+ StreamController<String>.broadcast();
+
+ /// WebView 初始化完成事件
+ Stream<bool> get onInitialized => initEventController.stream;
+
+ /// 验证码图片 src 找到时触发(携带图片绝对 URL)
+ Stream<String> get onCaptchaImageFound => captchaImageFoundController.stream;
+
+ /// 验证码图片从页面消失时触发
+ Stream<void> get onCaptchaDisappeared => captchaDisappearedController.stream;
+
+ /// 调试日志
+ Stream<String> get onLog => logEventController.stream;
+
+ /// 初始化 WebView
+ Future<void> init();
+
+ /// 加载指定 URL,并注入监听验证码图片的 JS 脚本(类型1:图片验证码)
+ ///
+ /// [url] 要加载的页面地址(一般为搜索 URL)
+ /// [captchaXpath] 验证码图片元素的 XPath 选择器
+ /// [inputXpath] 可选,验证码输入框的 XPath。如果提供,会在检测验证码前先触发输入框的 focus 事件(某些站点需要)
+ Future<void> loadPage(String url, String captchaXpath, {String? inputXpath});
+
+ /// 加载指定 URL,并注入监听验证按钮的 JS 脚本(类型2:自动点击验证按钮)
+ ///
+ /// 检测到 [buttonXpath] 元素后立即模拟点击;按钮消失时触发 [onCaptchaDisappeared]。
+ /// [url] 要加载的页面地址
+ /// [buttonXpath] 验证按钮元素的 XPath 选择器
+ Future<void> loadPageForButtonClick(String url, String buttonXpath);
+
+ /// 在 WebView 内通过 JS 模拟输入验证码并模拟点击提交按钮
+ ///
+ /// [captchaCode] 用户输入的验证码文本
+ /// [inputXpath] 验证码输入框元素的 XPath
+ /// [buttonXpath] 提交按钮元素的 XPath
+ Future<void> submitCaptchaInteract(
+ String captchaCode, String inputXpath, String buttonXpath);
+
+ /// 获取当前页面的 Cookie 字符串("key1=val1; key2=val2")
+ ///
+ /// [pageUrl] 当前加载的页面地址,部分平台用于精确过滤 Cookie
+ Future<String> getCookieString(String pageUrl);
+
+ /// 卸载当前页面(跳转到 about:blank)
+ Future<void> unloadPage();
+
+ /// 释放 WebView 资源
+ void dispose();
+}
+
+class CaptchaWebviewControllerFactory {
+ static CaptchaWebviewController getController() {
+ if (Platform.isWindows) {
+ return CaptchaWebviewWindowsImpl();
+ }
+ if (Platform.isLinux) {
+ return CaptchaWebviewLinuxImpl();
+ }
+ // Android, iOS, macOS
+ return CaptchaWebviewInAppWebviewImpl();
+ }
+}
diff --git a/lib/webview/captcha/impl/captcha_webview_inappwebview_impl.dart b/lib/webview/captcha/impl/captcha_webview_inappwebview_impl.dart
new file mode 100644
index 00000000..d5f65403
--- /dev/null
+++ b/lib/webview/captcha/impl/captcha_webview_inappwebview_impl.dart
@@ -0,0 +1,443 @@
+import 'dart:async';
+
+import 'package:kazumi/utils/utils.dart';
+import 'package:kazumi/utils/logger.dart';
+import 'package:kazumi/webview/captcha/captcha_webview_controller.dart';
+import 'package:flutter_inappwebview_platform_interface/flutter_inappwebview_platform_interface.dart';
+
+class CaptchaWebviewInAppWebviewImpl extends CaptchaWebviewController {
+ PlatformHeadlessInAppWebView? _headlessWebView;
+ PlatformInAppWebViewController? _webviewController;
+ bool _handlersRegistered = false;
+ String _currentCaptchaImageXpath = '';
+ String _currentInputXpath = '';
+ /// For type-1 (captcha image), whether a captcha image has been detected, used to determine if verification is successful after page navigation
+ bool _captchaWasFound = false;
+ /// For type-2 (auto-click button), we set this flag when the button click is triggered. Then on page navigation or DOM change, if this flag is set, we can confirm verification success without relying solely on captcha disappearance.
+ bool _buttonWasClicked = false;
+
+ @override
+ Future<void> init() async {
+ _headlessWebView ??= PlatformHeadlessInAppWebView(
+ PlatformHeadlessInAppWebViewCreationParams(
+ initialSettings: InAppWebViewSettings(
+ userAgent: Utils.getRandomUA(),
+ mediaPlaybackRequiresUserGesture: true,
+ cacheEnabled: true,
+ blockNetworkImage: false,
+ loadsImagesAutomatically: true,
+ upgradeKnownHostsToHTTPS: false,
+ safeBrowsingEnabled: false,
+ ),
+ onWebViewCreated: (controller) {
+ logEventController.add('[Captcha WebView] Created');
+ _webviewController = controller;
+ initEventController.add(true);
+ },
+ onLoadStart: (controller, url) {
+ logEventController.add('[Captcha WebView] Load start: $url');
+ },
+ onLoadStop: (controller, url) {
+ logEventController.add('[Captcha WebView] Load stop: $url');
+ if (_buttonWasClicked && !captchaDisappearedController.isClosed) {
+ KazumiLogger().i('[Captcha WebView] Button click → page navigated, verification done');
+ _buttonWasClicked = false;
+ captchaDisappearedController.add(null);
+ }
+ },
+ onReceivedError: (controller, request, error) {
+ logEventController
+ .add('[Captcha WebView] Error: ${error.description}');
+ },
+ ),
+ );
+ await _headlessWebView!.run();
+ }
+
+ void _registerHandlers() {
+ if (_handlersRegistered) return;
+
+ _webviewController?.addJavaScriptHandler(
+ handlerName: 'CaptchaImageBridge',
+ callback: (args) {
+ final src = args.isNotEmpty ? args[0].toString() : '';
+ logEventController.add('[Captcha WebView] Captcha image found: $src');
+ if (src.isNotEmpty && !captchaImageFoundController.isClosed) {
+ _captchaWasFound = true;
+ captchaImageFoundController.add(src);
+ }
+ },
+ );
+
+ _webviewController?.addJavaScriptHandler(
+ handlerName: 'CaptchaStatusBridge',
+ callback: (args) {
+ final status = args.isNotEmpty ? args[0].toString() : '';
+ logEventController.add('[Captcha WebView JS] Page captcha status: $status');
+ if (status == 'absent' && _captchaWasFound &&
+ !captchaDisappearedController.isClosed) {
+ KazumiLogger().i('[Captcha WebView] Captcha gone after navigation (StatusBridge)');
+ _captchaWasFound = false;
+ captchaDisappearedController.add(null);
+ }
+ },
+ );
+
+ _webviewController?.addJavaScriptHandler(
+ handlerName: 'CaptchaGoneBridge',
+ callback: (args) {
+ logEventController.add('[Captcha WebView] Captcha image disappeared');
+ _buttonWasClicked = false;
+ if (!captchaDisappearedController.isClosed) {
+ captchaDisappearedController.add(null);
+ }
+ },
+ );
+
+ _webviewController?.addJavaScriptHandler(
+ handlerName: 'ButtonClickedBridge',
+ callback: (args) {
+ logEventController.add('[Captcha WebView] Button clicked flag set');
+ _buttonWasClicked = true;
+ },
+ );
+
+ _webviewController?.addJavaScriptHandler(
+ handlerName: 'CaptchaLogBridge',
+ callback: (args) {
+ if (args.isNotEmpty) {
+ logEventController.add('[Captcha WebView JS] ${args[0]}');
+ }
+ },
+ );
+
+ _handlersRegistered = true;
+ logEventController.add('[Captcha WebView] JS handlers registered');
+ }
+
+ Future<void> _addCaptchaUserScript() async {
+ if (_currentCaptchaImageXpath.isEmpty) return;
+
+ final escapedXpath =
+ _currentCaptchaImageXpath.replaceAll('\\', '\\\\').replaceAll("'", "\\'");
+ final escapedInputXpath =
+ _currentInputXpath.replaceAll('\\', '\\\\').replaceAll("'", "\\'");
+
+ // Remove any previously injected captcha script before adding a fresh one.
+ await _webviewController?.removeAllUserScripts();
+
+ const String scriptTemplate = """
+window.flutter_inappwebview.callHandler('CaptchaLogBridge',
+ 'CaptchaScript loaded on: ' + window.location.href);
+
+var _captchaXpath = '{XPATH}';
+var _inputXpath = '{INPUT_XPATH}';
+var _captchaPoller = null;
+var _disappearObserver = null;
+
+function _evalXpath() {
+ try {
+ var result = document.evaluate(
+ _captchaXpath, document, null,
+ XPathResult.FIRST_ORDERED_NODE_TYPE, null);
+ return result.singleNodeValue;
+ } catch(e) { return null; }
+}
+
+function _startDisappearMonitor() {
+ if (_disappearObserver) return;
+ _disappearObserver = new MutationObserver(function() {
+ var node = _evalXpath();
+ if (!node) {
+ _disappearObserver.disconnect();
+ _disappearObserver = null;
+ try {
+ window.flutter_inappwebview.callHandler('CaptchaGoneBridge', '');
+ } catch(e) {}
+ }
+ });
+ _disappearObserver.observe(document.documentElement,
+ { childList: true, subtree: true, attributes: true });
+}
+
+function _captureAsBase64(imgNode, callback) {
+ function doCapture() {
+ try {
+ var canvas = document.createElement('canvas');
+ canvas.width = imgNode.naturalWidth || imgNode.width || 100;
+ canvas.height = imgNode.naturalHeight || imgNode.height || 40;
+ var ctx = canvas.getContext('2d');
+ ctx.drawImage(imgNode, 0, 0);
+ callback(canvas.toDataURL('image/png'));
+ } catch(e) { callback(null); }
+ }
+ if (imgNode.complete && imgNode.naturalWidth > 0) {
+ doCapture();
+ } else {
+ imgNode.addEventListener('load', doCapture);
+ imgNode.addEventListener('error', function() { callback(null); });
+ }
+}
+
+function _checkForCaptcha() {
+ var node = _evalXpath();
+ if (node) {
+ _captureAsBase64(node, function(dataUrl) {
+ if (dataUrl) {
+ try {
+ window.flutter_inappwebview.callHandler('CaptchaImageBridge', dataUrl);
+ } catch(e) {}
+ }
+ });
+ _startDisappearMonitor();
+ return true;
+ }
+ return false;
+}
+
+function _triggerInputFocus() {
+ if (!_inputXpath) return false;
+ try {
+ var inputResult = document.evaluate(_inputXpath, document, null,
+ XPathResult.FIRST_ORDERED_NODE_TYPE, null);
+ var inputEl = inputResult.singleNodeValue;
+ if (inputEl) {
+ if (typeof \$ !== 'undefined' && \$) {
+ \$(inputEl).trigger('focus');
+ return true;
+ } else if (typeof jQuery !== 'undefined' && jQuery) {
+ jQuery(inputEl).trigger('focus');
+ return true;
+ } else {
+ inputEl.focus();
+ return true;
+ }
+ }
+ } catch(e) {
+ try { window.flutter_inappwebview.callHandler('CaptchaLogBridge',
+ 'Failed to trigger input focus - ' + e.message); } catch(e2) {}
+ }
+ return false;
+}
+
+// Report captcha status to Dart at DOMContentLoaded so that after a full-page
+// navigation Dart can detect that verification succeeded (captcha is gone).
+// Also trigger input focus here since DOM is ready at this point.
+window.addEventListener('DOMContentLoaded', function() {
+ _triggerInputFocus();
+ var node = _evalXpath();
+ try {
+ window.flutter_inappwebview.callHandler('CaptchaStatusBridge', node ? 'present' : 'absent');
+ } catch(e) {}
+});
+
+if (!_checkForCaptcha()) {
+ _captchaPoller = setInterval(function() {
+ if (_checkForCaptcha()) {
+ clearInterval(_captchaPoller);
+ _captchaPoller = null;
+ }
+ }, 500);
+}
+""";
+
+ final script = scriptTemplate
+ .replaceAll('{XPATH}', escapedXpath)
+ .replaceAll('{INPUT_XPATH}', escapedInputXpath);
+ await _webviewController?.addUserScripts(
+ userScripts: [
+ UserScript(
+ source: script,
+ injectionTime: UserScriptInjectionTime.AT_DOCUMENT_START,
+ ),
+ ],
+ );
+ }
+
+ @override
+ Future<void> loadPage(String url, String captchaXpath, {String? inputXpath}) async {
+ _currentCaptchaImageXpath = captchaXpath;
+ _currentInputXpath = inputXpath ?? '';
+ _captchaWasFound = false;
+ _buttonWasClicked = false;
+ _registerHandlers();
+ await _addCaptchaUserScript();
+ try {
+ await PlatformCookieManager(const PlatformCookieManagerCreationParams())
+ .deleteAllCookies();
+ logEventController.add('[Captcha WebView] Cookies cleared before load');
+ } catch (_) {}
+ await _webviewController
+ ?.loadUrl(urlRequest: URLRequest(url: WebUri(url)));
+ }
+
+ @override
+ Future<void> loadPageForButtonClick(String url, String buttonXpath) async {
+ _currentCaptchaImageXpath = ''; // disable captcha-image script on navigation
+ _captchaWasFound = false;
+ _buttonWasClicked = false;
+ _registerHandlers();
+ await _addButtonClickUserScript(buttonXpath);
+ try {
+ await PlatformCookieManager(const PlatformCookieManagerCreationParams())
+ .deleteAllCookies();
+ logEventController.add('[Captcha WebView] Cookies cleared before load');
+ } catch (_) {}
+ await _webviewController
+ ?.loadUrl(urlRequest: URLRequest(url: WebUri(url)));
+ }
+
+ Future<void> _addButtonClickUserScript(String buttonXpath) async {
+ final escapedXpath =
+ buttonXpath.replaceAll('\\', '\\\\').replaceAll("'", "\\'");
+ await _webviewController?.removeAllUserScripts();
+
+ const String scriptTemplate = """
+try { window.flutter_inappwebview.callHandler('CaptchaLogBridge',
+ 'ButtonClickScript loaded on: ' + window.location.href); } catch(e) {}
+
+var _btnXpath = '{XPATH}';
+var _clicked = false;
+var _poller = null;
+var _disappearObserver = null;
+
+function _evalBtnXpath() {
+ try {
+ var result = document.evaluate(
+ _btnXpath, document, null,
+ XPathResult.FIRST_ORDERED_NODE_TYPE, null);
+ return result.singleNodeValue;
+ } catch(e) { return null; }
+}
+
+function _startDisappearMonitor() {
+ if (_disappearObserver) return;
+ _disappearObserver = new MutationObserver(function() {
+ if (!_evalBtnXpath()) {
+ _disappearObserver.disconnect();
+ _disappearObserver = null;
+ try { window.flutter_inappwebview.callHandler('CaptchaGoneBridge', ''); } catch(e) {}
+ }
+ });
+ _disappearObserver.observe(document.documentElement,
+ { childList: true, subtree: true, attributes: true });
+}
+
+function _checkAndClick() {
+ var btn = _evalBtnXpath();
+ if (btn && !_clicked) {
+ _clicked = true;
+ btn.click();
+ try { window.flutter_inappwebview.callHandler('ButtonClickedBridge', ''); } catch(e) {}
+ _startDisappearMonitor();
+ return true;
+ }
+ return false;
+}
+
+if (!_checkAndClick()) {
+ _poller = setInterval(function() {
+ if (_checkAndClick()) { clearInterval(_poller); _poller = null; }
+ }, 500);
+}
+""";
+
+ final script = scriptTemplate.replaceAll('{XPATH}', escapedXpath);
+ await _webviewController?.addUserScripts(
+ userScripts: [
+ UserScript(
+ source: script,
+ injectionTime: UserScriptInjectionTime.AT_DOCUMENT_END,
+ ),
+ ],
+ );
+ }
+
+ @override
+ Future<void> submitCaptchaInteract(
+ String captchaCode, String inputXpath, String buttonXpath) async {
+ logEventController
+ .add('[Captcha WebView] Filling input and clicking button');
+ final escapedCode =
+ captchaCode.replaceAll('\\', '\\\\').replaceAll("'", "\\'");
+ final escapedInput =
+ inputXpath.replaceAll('\\', '\\\\').replaceAll("'", "\\'");
+ final escapedButton =
+ buttonXpath.replaceAll('\\', '\\\\').replaceAll("'", "\\'");
+ final script = '''
+(function() {
+ function evalXpath(xpath) {
+ try {
+ var r = document.evaluate(xpath, document, null,
+ XPathResult.FIRST_ORDERED_NODE_TYPE, null);
+ return r.singleNodeValue;
+ } catch(e) { return null; }
+ }
+ var inputEl = evalXpath('$escapedInput');
+ if (inputEl) {
+ inputEl.focus();
+ var nativeInput = Object.getOwnPropertyDescriptor(
+ window.HTMLInputElement.prototype, 'value');
+ nativeInput.set.call(inputEl, '$escapedCode');
+ inputEl.dispatchEvent(new Event('input', { bubbles: true }));
+ inputEl.dispatchEvent(new Event('change', { bubbles: true }));
+ try { window.flutter_inappwebview.callHandler('CaptchaLogBridge', 'Input filled'); } catch(e) {}
+ } else {
+ try { window.flutter_inappwebview.callHandler('CaptchaLogBridge', 'Input element not found'); } catch(e) {}
+ }
+ var btnEl = evalXpath('$escapedButton');
+ if (btnEl) {
+ btnEl.click();
+ try { window.flutter_inappwebview.callHandler('CaptchaLogBridge', 'Button clicked'); } catch(e) {}
+ } else {
+ try { window.flutter_inappwebview.callHandler('CaptchaLogBridge', 'Button element not found'); } catch(e) {}
+ }
+})();
+''';
+ await _webviewController?.evaluateJavascript(source: script);
+ }
+
+ @override
+ Future<String> getCookieString(String pageUrl) async {
+ try {
+ final PlatformCookieManager cookieManager = PlatformCookieManager(
+ PlatformCookieManagerCreationParams(),
+ );
+ final cookies = await cookieManager.getCookies(url: WebUri(pageUrl));
+ return cookies.map((c) => '${c.name}=${c.value}').join('; ');
+ } catch (e) {
+ KazumiLogger().e('[Captcha WebView] getCookieString error: $e');
+ return '';
+ }
+ }
+
+ @override
+ Future<void> unloadPage() async {
+ try {
+ await _webviewController
+ ?.loadUrl(urlRequest: URLRequest(url: WebUri('about:blank')));
+ } catch (_) {}
+ }
+
+ @override
+ void dispose() {
+ _currentCaptchaImageXpath = '';
+ _currentInputXpath = '';
+ _captchaWasFound = false;
+ _buttonWasClicked = false;
+ _handlersRegistered = false;
+ try {
+ PlatformCookieManager(const PlatformCookieManagerCreationParams())
+ .deleteAllCookies();
+ } catch (_) {}
+ try {
+ captchaImageFoundController.close();
+ captchaDisappearedController.close();
+ initEventController.close();
+ logEventController.close();
+ } catch (_) {}
+ _headlessWebView?.dispose();
+ _headlessWebView = null;
+ _webviewController = null;
+ }
+}
diff --git a/lib/webview/captcha/impl/captcha_webview_linux_impl.dart b/lib/webview/captcha/impl/captcha_webview_linux_impl.dart
new file mode 100644
index 00000000..7ce11f29
--- /dev/null
+++ b/lib/webview/captcha/impl/captcha_webview_linux_impl.dart
@@ -0,0 +1,396 @@
+import 'dart:async';
+
+import 'package:flutter/foundation.dart';
+import 'package:desktop_webview_window/desktop_webview_window.dart';
+import 'package:kazumi/utils/logger.dart';
+import 'package:kazumi/utils/storage.dart';
+import 'package:kazumi/utils/proxy_utils.dart';
+import 'package:kazumi/webview/captcha/captcha_webview_controller.dart';
+
+class CaptchaWebviewLinuxImpl extends CaptchaWebviewController {
+ Webview? _webviewController;
+ VoidCallback? _navigationListener;
+ String _currentCaptchaImageXpath = '';
+ /// For type-1 (captcha image), whether a captcha image has been detected, used to determine if verification is successful after page navigation
+ bool _captchaWasFound = false;
+ String _buttonXpath = '';
+ /// For type-2 (auto-click button), we set this flag when the button click is triggered. Then on page navigation or DOM change, if this flag is set, we can confirm verification success without relying solely on captcha disappearance.
+ bool _buttonWasClicked = false;
+
+ @override
+ Future<void> init() async {
+ final proxyConfig = _getProxyConfiguration();
+ _webviewController ??= await WebviewWindow.create(
+ configuration: CreateConfiguration(
+ headless: true,
+ proxy: proxyConfig,
+ ),
+ );
+ _initMessageBridge();
+ _initNavigationListener();
+ initEventController.add(true);
+ }
+
+ ProxyConfiguration? _getProxyConfiguration() {
+ final setting = GStorage.setting;
+ final bool proxyEnable =
+ setting.get(SettingBoxKey.proxyEnable, defaultValue: false);
+ if (!proxyEnable) return null;
+
+ final String proxyUrl =
+ setting.get(SettingBoxKey.proxyUrl, defaultValue: '');
+ final parsed = ProxyUtils.parseProxyUrl(proxyUrl);
+ if (parsed == null) return null;
+
+ final (host, port) = parsed;
+ KazumiLogger().i('[Captcha WebView] 代理设置成功 $host:$port');
+ return ProxyConfiguration(host: host, port: port);
+ }
+
+ void _initMessageBridge() {
+ _webviewController?.addOnWebMessageReceivedCallback((message) async {
+ final msg = message.toString();
+ logEventController.add('[Captcha WebView] WM: $msg');
+ if (msg.startsWith('captchaImage:')) {
+ final src = msg.replaceFirst('captchaImage:', '');
+ if (src.isNotEmpty && !captchaImageFoundController.isClosed) {
+ _captchaWasFound = true;
+ captchaImageFoundController.add(src);
+ }
+ } else if (msg.startsWith('buttonClicked:')) {
+ _buttonWasClicked = true;
+ logEventController.add('[Captcha WebView] Button clicked flag set');
+ } else if (msg.startsWith('captchaGone:')) {
+ _buttonWasClicked = false;
+ if (!captchaDisappearedController.isClosed) {
+ captchaDisappearedController.add(null);
+ }
+ } else if (msg.startsWith('captchaLog:')) {
+ logEventController.add(
+ '[Captcha WebView JS] ${msg.replaceFirst('captchaLog:', '')}');
+ }
+ });
+ }
+
+ void _initNavigationListener() {
+ _navigationListener = () {
+ _onNavigationInject();
+ _onNavigationCompletion();
+ };
+ _webviewController?.isNavigating.addListener(_navigationListener!);
+ }
+
+ Future<void> _onNavigationInject() async {
+ if (_webviewController?.isNavigating.value == false) {
+ logEventController.add('[Captcha WebView] Navigation completed');
+ if (_currentCaptchaImageXpath.isNotEmpty) {
+ await _injectCaptchaScript();
+ } else if (_buttonXpath.isNotEmpty) {
+ await _injectButtonClickScript(_buttonXpath);
+ }
+ }
+ }
+
+ Future<void> _onNavigationCompletion() async {
+ if (_webviewController?.isNavigating.value == false) {
+ // Type-1: captcha image was seen; check if it has disappeared.
+ if (_captchaWasFound) {
+ final present = await _isCaptchaPresent();
+ if (!present && !captchaDisappearedController.isClosed) {
+ logEventController
+ .add('[Captcha WebView] Captcha gone after navigation');
+ _captchaWasFound = false;
+ captchaDisappearedController.add(null);
+ }
+ }
+ // Type-2: button was clicked; page navigation confirms verification.
+ if (_buttonWasClicked && !captchaDisappearedController.isClosed) {
+ logEventController.add(
+ '[Captcha WebView] Button click and page navigated, verification done');
+ _buttonWasClicked = false;
+ captchaDisappearedController.add(null);
+ }
+ }
+ }
+
+ Future<bool> _isCaptchaPresent() async {
+ if (_currentCaptchaImageXpath.isEmpty || _webviewController == null) return false;
+ final escaped =
+ _currentCaptchaImageXpath.replaceAll('\\', '\\\\').replaceAll("'", "\\'");
+ try {
+ final result = await _webviewController!.evaluateJavaScript('''
+(function() {
+ try {
+ var r = document.evaluate('$escaped', document, null,
+ XPathResult.FIRST_ORDERED_NODE_TYPE, null);
+ return r.singleNodeValue ? 'present' : 'absent';
+ } catch(e) { return 'absent'; }
+})();
+''');
+ return result?.contains('present') ?? false;
+ } catch (e) {
+ KazumiLogger().d('[Captcha WebView] _isCaptchaPresent error: $e');
+ return false;
+ }
+ }
+
+ Future<void> _injectCaptchaScript() async {
+ if (_currentCaptchaImageXpath.isEmpty) return;
+ final escapedXpath =
+ _currentCaptchaImageXpath.replaceAll('\\', '\\\\').replaceAll("'", "\\'");
+
+ final script = '''
+(function() {
+ window.webkit.messageHandlers.msgToNative.postMessage(
+ 'captchaLog:CaptchaScript injected on ' + window.location.href);
+
+ var _captchaXpath = '$escapedXpath';
+ var _captchaPoller = null;
+ var _disappearObserver = null;
+
+ function _resolveSrc(node) {
+ return node.getAttribute('src') || node.getAttribute('data-src') ||
+ node.src || '';
+ }
+
+ function _evalXpath() {
+ try {
+ var result = document.evaluate(
+ _captchaXpath, document, null,
+ XPathResult.FIRST_ORDERED_NODE_TYPE, null);
+ return result.singleNodeValue;
+ } catch(e) { return null; }
+ }
+
+ function _startDisappearMonitor() {
+ if (_disappearObserver) return;
+ _disappearObserver = new MutationObserver(function() {
+ if (!_evalXpath()) {
+ _disappearObserver.disconnect();
+ _disappearObserver = null;
+ window.webkit.messageHandlers.msgToNative.postMessage('captchaGone:');
+ }
+ });
+ _disappearObserver.observe(document.documentElement,
+ { childList: true, subtree: true, attributes: true });
+ }
+
+ function _captureAsBase64(imgNode, callback) {
+ function doCapture() {
+ try {
+ var canvas = document.createElement('canvas');
+ canvas.width = imgNode.naturalWidth || imgNode.width || 100;
+ canvas.height = imgNode.naturalHeight || imgNode.height || 40;
+ var ctx = canvas.getContext('2d');
+ ctx.drawImage(imgNode, 0, 0);
+ callback(canvas.toDataURL('image/png'));
+ } catch(e) { callback(null); }
+ }
+ if (imgNode.complete && imgNode.naturalWidth > 0) {
+ doCapture();
+ } else {
+ imgNode.addEventListener('load', doCapture);
+ imgNode.addEventListener('error', function() { callback(null); });
+ }
+ }
+
+ function _checkForCaptcha() {
+ var node = _evalXpath();
+ if (node) {
+ _captureAsBase64(node, function(dataUrl) {
+ if (dataUrl) {
+ window.webkit.messageHandlers.msgToNative.postMessage('captchaImage:' + dataUrl);
+ }
+ });
+ _startDisappearMonitor();
+ return true;
+ }
+ return false;
+ }
+
+ if (!_checkForCaptcha()) {
+ _captchaPoller = setInterval(function() {
+ if (_checkForCaptcha()) {
+ clearInterval(_captchaPoller);
+ _captchaPoller = null;
+ }
+ }, 500);
+ }
+})();
+''';
+
+ try {
+ await _webviewController?.evaluateJavaScript(script);
+ } catch (e) {
+ KazumiLogger().e('[Captcha WebView] inject script error: $e');
+ }
+ }
+
+ @override
+ Future<void> loadPage(String url, String captchaXpath, {String? inputXpath}) async {
+ _currentCaptchaImageXpath = captchaXpath;
+ _buttonXpath = '';
+ _buttonWasClicked = false;
+ _captchaWasFound = false;
+ _webviewController?.launch(url);
+ }
+
+ @override
+ Future<void> loadPageForButtonClick(String url, String buttonXpath) async {
+ _currentCaptchaImageXpath = '';
+ _buttonXpath = buttonXpath;
+ _buttonWasClicked = false;
+ _captchaWasFound = false;
+ _webviewController?.launch(url);
+ }
+
+ Future<void> _injectButtonClickScript(String buttonXpath) async {
+ final escaped =
+ buttonXpath.replaceAll('\\', '\\\\').replaceAll("'", "\\'");
+ final script = '''
+(function() {
+ window.webkit.messageHandlers.msgToNative.postMessage(
+ 'captchaLog:ButtonClickScript injected on ' + window.location.href);
+
+ var _xpath = '$escaped';
+ var _clicked = false;
+ var _poller = null;
+ var _disappearObserver = null;
+
+ function evalXpath() {
+ try {
+ var r = document.evaluate(_xpath, document, null,
+ XPathResult.FIRST_ORDERED_NODE_TYPE, null);
+ return r.singleNodeValue;
+ } catch(e) { return null; }
+ }
+
+ function startDisappearMonitor() {
+ if (_disappearObserver) return;
+ _disappearObserver = new MutationObserver(function() {
+ if (!evalXpath()) {
+ _disappearObserver.disconnect();
+ _disappearObserver = null;
+ window.webkit.messageHandlers.msgToNative.postMessage('captchaGone:');
+ }
+ });
+ _disappearObserver.observe(document.documentElement,
+ { childList: true, subtree: true, attributes: true });
+ }
+
+ function checkAndClick() {
+ var btn = evalXpath();
+ if (btn && !_clicked) {
+ _clicked = true;
+ btn.click();
+ window.webkit.messageHandlers.msgToNative.postMessage('buttonClicked:');
+ startDisappearMonitor();
+ return true;
+ }
+ return false;
+ }
+
+ if (!checkAndClick()) {
+ _poller = setInterval(function() {
+ if (checkAndClick()) { clearInterval(_poller); _poller = null; }
+ }, 500);
+ }
+})();
+''';
+ try {
+ await _webviewController?.evaluateJavaScript(script);
+ } catch (e) {
+ KazumiLogger().e('[Captcha WebView] injectButtonClickScript error: $e');
+ }
+ }
+
+ @override
+ Future<void> submitCaptchaInteract(
+ String captchaCode, String inputXpath, String buttonXpath) async {
+ logEventController
+ .add('[Captcha WebView] Filling input and clicking button');
+ final escapedCode =
+ captchaCode.replaceAll('\\', '\\\\').replaceAll("'", "\\'");
+ final escapedInput =
+ inputXpath.replaceAll('\\', '\\\\').replaceAll("'", "\\'");
+ final escapedButton =
+ buttonXpath.replaceAll('\\', '\\\\').replaceAll("'", "\\'");
+ final script = '''
+(function() {
+ function evalXpath(xpath) {
+ try {
+ var r = document.evaluate(xpath, document, null,
+ XPathResult.FIRST_ORDERED_NODE_TYPE, null);
+ return r.singleNodeValue;
+ } catch(e) { return null; }
+ }
+ var inputEl = evalXpath('$escapedInput');
+ if (inputEl) {
+ inputEl.focus();
+ var nativeInput = Object.getOwnPropertyDescriptor(
+ window.HTMLInputElement.prototype, 'value');
+ nativeInput.set.call(inputEl, '$escapedCode');
+ inputEl.dispatchEvent(new Event('input', { bubbles: true }));
+ inputEl.dispatchEvent(new Event('change', { bubbles: true }));
+ window.webkit.messageHandlers.msgToNative.postMessage('captchaLog:Input filled');
+ } else {
+ window.webkit.messageHandlers.msgToNative.postMessage('captchaLog:Input element not found');
+ }
+ var btnEl = evalXpath('$escapedButton');
+ if (btnEl) {
+ btnEl.click();
+ window.webkit.messageHandlers.msgToNative.postMessage('captchaLog:Button clicked');
+ } else {
+ window.webkit.messageHandlers.msgToNative.postMessage('captchaLog:Button element not found');
+ }
+})();
+''';
+ try {
+ await _webviewController?.evaluateJavaScript(script);
+ } catch (e) {
+ KazumiLogger().e('[Captcha WebView] submitCaptchaInteract error: $e');
+ }
+ }
+
+ @override
+ Future<String> getCookieString(String pageUrl) async {
+ try {
+ final cookies = await _webviewController?.getAllCookies() ?? [];
+ final cookieString =
+ cookies.map((c) => '${c.name}=${c.value}').join('; ');
+ logEventController
+ .add('[Captcha WebView] Cookies: $cookieString');
+ return cookieString;
+ } catch (e) {
+ KazumiLogger().e('[Captcha WebView] getCookieString error: $e');
+ return '';
+ }
+ }
+
+ @override
+ Future<void> unloadPage() async {
+ _webviewController?.launch('about:blank');
+ }
+
+ @override
+ void dispose() {
+ _currentCaptchaImageXpath = '';
+ _buttonXpath = '';
+ _buttonWasClicked = false;
+ _captchaWasFound = false;
+ if (_navigationListener != null) {
+ try {
+ _webviewController?.isNavigating.removeListener(_navigationListener!);
+ } catch (_) {}
+ _navigationListener = null;
+ }
+ try {
+ captchaImageFoundController.close();
+ captchaDisappearedController.close();
+ initEventController.close();
+ logEventController.close();
+ } catch (_) {}
+ _webviewController?.close();
+ _webviewController = null;
+ }
+}
diff --git a/lib/webview/captcha/impl/captcha_webview_windows_impl.dart b/lib/webview/captcha/impl/captcha_webview_windows_impl.dart
new file mode 100644
index 00000000..45c24d73
--- /dev/null
+++ b/lib/webview/captcha/impl/captcha_webview_windows_impl.dart
@@ -0,0 +1,435 @@
+import 'dart:async';
+
+import 'package:webview_windows/webview_windows.dart';
+import 'package:kazumi/utils/logger.dart';
+import 'package:kazumi/utils/storage.dart';
+import 'package:kazumi/utils/proxy_utils.dart';
+import 'package:kazumi/webview/captcha/captcha_webview_controller.dart';
+
+class CaptchaWebviewWindowsImpl extends CaptchaWebviewController {
+ HeadlessWebview? _headlessWebview;
+ final List<StreamSubscription> _subscriptions = [];
+ String _currentCaptchaImageXpath = '';
+ String _currentInputXpath = '';
+ String _currentPageUrl = '';
+ /// For type-1 (captcha image), whether a captcha image has been detected, used to determine if verification is successful after page navigation
+ bool _captchaWasFound = false;
+ String _buttonXpath = '';
+ /// For type-2 (auto-click button), we set this flag when the button click is triggered. Then on page navigation or DOM change, if this flag is set, we can confirm verification success without relying solely on captcha disappearance.
+ bool _buttonWasClicked = false;
+
+ @override
+ Future<void> init() async {
+ await _setupProxy();
+ _headlessWebview ??= HeadlessWebview();
+ await _headlessWebview!.run();
+ await _headlessWebview!.setPopupWindowPolicy(WebviewPopupWindowPolicy.deny);
+
+ // Listen for messages from JavaScript via window.chrome.webview.postMessage
+ _subscriptions.add(
+ _headlessWebview!.webMessage.listen(_onWebMessage),
+ );
+
+ // Inject captcha or button-click script when navigation completes
+ _subscriptions.add(
+ _headlessWebview!.loadingState.listen((state) async {
+ if (state == LoadingState.navigationCompleted) {
+ logEventController
+ .add('[Captcha WebView] Navigation completed: $_currentPageUrl');
+ if (_currentCaptchaImageXpath.isNotEmpty) {
+ await _injectCaptchaScript();
+ } else if (_buttonXpath.isNotEmpty) {
+ await _injectButtonClickScript(_buttonXpath);
+ }
+ }
+ }),
+ );
+
+ // After a navigation, detect verification completion for both type-1
+ // (captcha image gone) and type-2 (button was clicked, page navigated).
+ _subscriptions.add(
+ _headlessWebview!.loadingState.listen((state) async {
+ if (state == LoadingState.navigationCompleted) {
+ if (_captchaWasFound) {
+ final present = await _isCaptchaPresent();
+ if (!present && !captchaDisappearedController.isClosed) {
+ logEventController
+ .add('[Captcha WebView] Captcha gone after navigation');
+ _captchaWasFound = false;
+ captchaDisappearedController.add(null);
+ }
+ }
+ if (_buttonWasClicked && !captchaDisappearedController.isClosed) {
+ logEventController
+ .add('[Captcha WebView] Button click → page navigated, verification done');
+ _buttonWasClicked = false;
+ captchaDisappearedController.add(null);
+ }
+ }
+ }),
+ );
+
+ initEventController.add(true);
+ }
+
+ void _onWebMessage(dynamic message) {
+ final msg = message.toString();
+ logEventController.add('[Captcha WebView] WM: $msg');
+ if (msg.startsWith('captchaImage:')) {
+ final src = msg.replaceFirst('captchaImage:', '');
+ if (src.isNotEmpty && !captchaImageFoundController.isClosed) {
+ _captchaWasFound = true;
+ captchaImageFoundController.add(src);
+ }
+ } else if (msg.startsWith('buttonClicked:')) {
+ _buttonWasClicked = true;
+ logEventController.add('[Captcha WebView] Button clicked flag set');
+ } else if (msg.startsWith('captchaGone:')) {
+ _buttonWasClicked = false;
+ if (!captchaDisappearedController.isClosed) {
+ captchaDisappearedController.add(null);
+ }
+ } else if (msg.startsWith('captchaLog:')) {
+ logEventController.add('[Captcha WebView JS] ${msg.replaceFirst('captchaLog:', '')}');
+ }
+ }
+
+ Future<bool> _isCaptchaPresent() async {
+ if (_currentCaptchaImageXpath.isEmpty || _headlessWebview == null) return false;
+ final escaped =
+ _currentCaptchaImageXpath.replaceAll('\\', '\\\\').replaceAll("'", "\\'");
+ try {
+ final result = await _headlessWebview!.executeScript('''
+(function() {
+ try {
+ var r = document.evaluate('$escaped', document, null,
+ XPathResult.FIRST_ORDERED_NODE_TYPE, null);
+ return r.singleNodeValue ? 'present' : 'absent';
+ } catch(e) { return 'absent'; }
+})();
+''');
+ return result?.toString().contains('present') ?? false;
+ } catch (e) {
+ KazumiLogger().d('[Captcha WebView] _isCaptchaPresent error: $e');
+ return false;
+ }
+ }
+
+ Future<void> _injectCaptchaScript() async {
+ if (_currentCaptchaImageXpath.isEmpty) return;
+ final escapedXpath =
+ _currentCaptchaImageXpath.replaceAll('\\', '\\\\').replaceAll("'", "\\'");
+ final escapedInputXpath =
+ _currentInputXpath.replaceAll('\\', '\\\\').replaceAll("'", "\\'");
+
+ final script = '''
+(function() {
+ window.chrome.webview.postMessage('captchaLog:CaptchaScript injected on ' + window.location.href);
+
+ var _captchaXpath = '$escapedXpath';
+ var _inputXpath = '$escapedInputXpath';
+ var _captchaPoller = null;
+ var _disappearObserver = null;
+
+ function _resolveSrc(node) {
+ return node.getAttribute('src') || node.getAttribute('data-src') ||
+ node.src || '';
+ }
+
+ function _evalXpath() {
+ try {
+ var result = document.evaluate(
+ _captchaXpath, document, null,
+ XPathResult.FIRST_ORDERED_NODE_TYPE, null);
+ return result.singleNodeValue;
+ } catch(e) { return null; }
+ }
+
+ function _startDisappearMonitor() {
+ if (_disappearObserver) return;
+ _disappearObserver = new MutationObserver(function() {
+ if (!_evalXpath()) {
+ _disappearObserver.disconnect();
+ _disappearObserver = null;
+ window.chrome.webview.postMessage('captchaGone:');
+ }
+ });
+ _disappearObserver.observe(document.documentElement,
+ { childList: true, subtree: true, attributes: true });
+ }
+
+ function _captureAsBase64(imgNode, callback) {
+ function doCapture() {
+ try {
+ var canvas = document.createElement('canvas');
+ canvas.width = imgNode.naturalWidth || imgNode.width || 100;
+ canvas.height = imgNode.naturalHeight || imgNode.height || 40;
+ var ctx = canvas.getContext('2d');
+ ctx.drawImage(imgNode, 0, 0);
+ callback(canvas.toDataURL('image/png'));
+ } catch(e) { callback(null); }
+ }
+ if (imgNode.complete && imgNode.naturalWidth > 0) {
+ doCapture();
+ } else {
+ imgNode.addEventListener('load', doCapture);
+ imgNode.addEventListener('error', function() { callback(null); });
+ }
+ }
+
+ function _checkForCaptcha() {
+ var node = _evalXpath();
+ if (node) {
+ _captureAsBase64(node, function(dataUrl) {
+ if (dataUrl) {
+ window.chrome.webview.postMessage('captchaImage:' + dataUrl);
+ }
+ });
+ _startDisappearMonitor();
+ return true;
+ }
+ return false;
+ }
+
+ function _triggerInputFocus() {
+ if (!_inputXpath) {
+ return false;
+ }
+
+ try {
+ var inputResult = document.evaluate(_inputXpath, document, null,
+ XPathResult.FIRST_ORDERED_NODE_TYPE, null);
+ var inputEl = inputResult.singleNodeValue;
+
+ if (inputEl) {
+ if (typeof \$ !== 'undefined' && \$) {
+ \$(inputEl).trigger('focus');
+ return true;
+ } else if (typeof jQuery !== 'undefined' && jQuery) {
+ jQuery(inputEl).trigger('focus');
+ return true;
+ } else {
+ inputEl.focus();
+ return true;
+ }
+ }
+ } catch(e) {
+ window.chrome.webview.postMessage('captchaLog:Failed to trigger input focus - ' + e.message);
+ }
+ return false;
+ }
+
+ // If inputXpath is provided, trigger focus to load captcha (some sites require this)
+ _triggerInputFocus();
+
+ if (!_checkForCaptcha()) {
+ _captchaPoller = setInterval(function() {
+ if (_checkForCaptcha()) {
+ clearInterval(_captchaPoller);
+ _captchaPoller = null;
+ }
+ }, 500);
+ }
+})();
+''';
+
+ try {
+ await _headlessWebview?.executeScript(script);
+ } catch (e) {
+ KazumiLogger().e('[Captcha WebView] inject script error: $e');
+ }
+ }
+
+ @override
+ Future<void> loadPage(String url, String captchaXpath, {String? inputXpath}) async {
+ _currentCaptchaImageXpath = captchaXpath;
+ _currentInputXpath = inputXpath ?? '';
+ _buttonXpath = '';
+ _buttonWasClicked = false;
+ _currentPageUrl = url;
+ _captchaWasFound = false;
+ await _headlessWebview?.loadUrl(url);
+ }
+
+ @override
+ Future<void> loadPageForButtonClick(String url, String buttonXpath) async {
+ _currentCaptchaImageXpath = '';
+ _buttonXpath = buttonXpath;
+ _buttonWasClicked = false;
+ _currentPageUrl = url;
+ _captchaWasFound = false;
+ await _headlessWebview?.loadUrl(url);
+ }
+
+ Future<void> _injectButtonClickScript(String buttonXpath) async {
+ final escaped =
+ buttonXpath.replaceAll('\\', '\\\\').replaceAll("'", "\\'");
+ final script = '''
+(function() {
+ window.chrome.webview.postMessage('captchaLog:ButtonClickScript injected on ' + window.location.href);
+
+ var _xpath = '$escaped';
+ var _clicked = false;
+ var _poller = null;
+ var _disappearObserver = null;
+
+ function evalXpath() {
+ try {
+ var r = document.evaluate(_xpath, document, null,
+ XPathResult.FIRST_ORDERED_NODE_TYPE, null);
+ return r.singleNodeValue;
+ } catch(e) { return null; }
+ }
+
+ function startDisappearMonitor() {
+ if (_disappearObserver) return;
+ _disappearObserver = new MutationObserver(function() {
+ if (!evalXpath()) {
+ _disappearObserver.disconnect();
+ _disappearObserver = null;
+ window.chrome.webview.postMessage('captchaGone:');
+ }
+ });
+ _disappearObserver.observe(document.documentElement,
+ { childList: true, subtree: true, attributes: true });
+ }
+
+ function checkAndClick() {
+ var btn = evalXpath();
+ if (btn && !_clicked) {
+ _clicked = true;
+ btn.click();
+ window.chrome.webview.postMessage('buttonClicked:');
+ startDisappearMonitor();
+ return true;
+ }
+ return false;
+ }
+
+ if (!checkAndClick()) {
+ _poller = setInterval(function() {
+ if (checkAndClick()) { clearInterval(_poller); _poller = null; }
+ }, 500);
+ }
+})();
+''';
+ try {
+ await _headlessWebview?.executeScript(script);
+ } catch (e) {
+ KazumiLogger().e('[Captcha WebView] injectButtonClickScript error: $e');
+ }
+ }
+
+ @override
+ Future<void> submitCaptchaInteract(
+ String captchaCode, String inputXpath, String buttonXpath) async {
+ logEventController
+ .add('[Captcha WebView] Filling input and clicking button');
+ final escapedCode =
+ captchaCode.replaceAll('\\', '\\\\').replaceAll("'", "\\'");
+ final escapedInput =
+ inputXpath.replaceAll('\\', '\\\\').replaceAll("'", "\\'");
+ final escapedButton =
+ buttonXpath.replaceAll('\\', '\\\\').replaceAll("'", "\\'");
+ final script = '''
+(function() {
+ function evalXpath(xpath) {
+ try {
+ var r = document.evaluate(xpath, document, null,
+ XPathResult.FIRST_ORDERED_NODE_TYPE, null);
+ return r.singleNodeValue;
+ } catch(e) { return null; }
+ }
+ var inputEl = evalXpath('$escapedInput');
+ if (inputEl) {
+ inputEl.focus();
+ var nativeInput = Object.getOwnPropertyDescriptor(
+ window.HTMLInputElement.prototype, 'value');
+ nativeInput.set.call(inputEl, '$escapedCode');
+ inputEl.dispatchEvent(new Event('input', { bubbles: true }));
+ inputEl.dispatchEvent(new Event('change', { bubbles: true }));
+ window.chrome.webview.postMessage('captchaLog:Input filled');
+ } else {
+ window.chrome.webview.postMessage('captchaLog:Input element not found');
+ }
+ var btnEl = evalXpath('$escapedButton');
+ if (btnEl) {
+ btnEl.click();
+ window.chrome.webview.postMessage('captchaLog:Button clicked');
+ } else {
+ window.chrome.webview.postMessage('captchaLog:Button element not found');
+ }
+})();
+''';
+ try {
+ await _headlessWebview?.executeScript(script);
+ } catch (e) {
+ KazumiLogger().e('[Captcha WebView] submitCaptchaInteract error: $e');
+ }
+ }
+
+ @override
+ Future<String> getCookieString(String pageUrl) async {
+ try {
+ final result = await _headlessWebview?.getCookies(pageUrl);
+ return result ?? '';
+ } catch (e) {
+ KazumiLogger().e('[Captcha WebView] getCookieString error: $e');
+ return '';
+ }
+ }
+
+ @override
+ Future<void> unloadPage() async {
+ try {
+ await _headlessWebview?.executeScript(
+ "window.location.href = 'about:blank';");
+ } catch (e) {
+ KazumiLogger().d('[Captcha WebView] unloadPage skipped: $e');
+ }
+ }
+
+ @override
+ void dispose() {
+ _currentCaptchaImageXpath = '';
+ _currentInputXpath = '';
+ _buttonXpath = '';
+ _buttonWasClicked = false;
+ _currentPageUrl = '';
+ for (final s in _subscriptions) {
+ try {
+ s.cancel();
+ } catch (_) {}
+ }
+ _subscriptions.clear();
+ try {
+ captchaImageFoundController.close();
+ captchaDisappearedController.close();
+ initEventController.close();
+ logEventController.close();
+ } catch (_) {}
+ _headlessWebview?.dispose();
+ _headlessWebview = null;
+ }
+
+ Future<void> _setupProxy() async {
+ final setting = GStorage.setting;
+ final bool proxyEnable =
+ setting.get(SettingBoxKey.proxyEnable, defaultValue: false);
+ if (!proxyEnable) return;
+
+ final String proxyUrl =
+ setting.get(SettingBoxKey.proxyUrl, defaultValue: '');
+ final formattedProxy = ProxyUtils.getFormattedProxyUrl(proxyUrl);
+ if (formattedProxy == null) return;
+
+ try {
+ await WebviewController.initializeEnvironment(
+ additionalArguments: '--proxy-server=$formattedProxy',
+ );
+ KazumiLogger().i('[Captcha WebView] 代理设置成功 $formattedProxy');
+ } catch (e) {
+ KazumiLogger().e('[Captcha WebView] 设置代理失败 $e');
+ }
+ }
+}
diff --git a/lib/webview/webview_controller_impel/webview_android_controller_impel.dart b/lib/webview/video/impl/video_webview_android_impl.dart
similarity index 98%
rename from lib/webview/webview_controller_impel/webview_android_controller_impel.dart
rename to lib/webview/video/impl/video_webview_android_impl.dart
index e3d61bec..c5933fed 100644
--- a/lib/webview/webview_controller_impel/webview_android_controller_impel.dart
+++ b/lib/webview/video/impl/video_webview_android_impl.dart
@@ -3,13 +3,13 @@ import 'package:kazumi/utils/utils.dart';
import 'package:kazumi/utils/storage.dart';
import 'package:kazumi/utils/proxy_utils.dart';
import 'package:kazumi/utils/logger.dart';
-import 'package:kazumi/webview/webview_controller.dart';
+import 'package:kazumi/webview/video/video_webview_controller.dart';
import 'package:flutter_inappwebview_platform_interface/flutter_inappwebview_platform_interface.dart';
import 'package:flutter_inappwebview_android/flutter_inappwebview_android.dart'
as android_webview;
-class WebviewAndroidItemControllerImpel
- extends WebviewItemController<PlatformInAppWebViewController> {
+class VideoWebviewAndroidImpl
+ extends VideoWebviewController<PlatformInAppWebViewController> {
PlatformHeadlessInAppWebView? headlessWebView;
bool hasInjectedScripts = false;
bool shouldInjectIframeRedirect = false;
diff --git a/lib/webview/webview_controller_impel/webview_apple_controller_impel.dart b/lib/webview/video/impl/video_webview_apple_impl.dart
similarity index 98%
rename from lib/webview/webview_controller_impel/webview_apple_controller_impel.dart
rename to lib/webview/video/impl/video_webview_apple_impl.dart
index 6c4d00d5..a78d0e82 100644
--- a/lib/webview/webview_controller_impel/webview_apple_controller_impel.dart
+++ b/lib/webview/video/impl/video_webview_apple_impl.dart
@@ -2,11 +2,11 @@ import 'dart:async';
import 'dart:collection';
import 'package:kazumi/utils/logger.dart';
import 'package:kazumi/utils/utils.dart';
-import 'package:kazumi/webview/webview_controller.dart';
+import 'package:kazumi/webview/video/video_webview_controller.dart';
import 'package:flutter_inappwebview_platform_interface/flutter_inappwebview_platform_interface.dart';
-class WebviewAppleItemControllerImpel
- extends WebviewItemController<PlatformInAppWebViewController> {
+class VideoWebviewAppleImpl
+ extends VideoWebviewController<PlatformInAppWebViewController> {
PlatformHeadlessInAppWebView? headlessWebView;
bool hasInjectedScripts = false;
diff --git a/lib/webview/webview_controller_impel/webview_controller_impel.dart b/lib/webview/video/impl/video_webview_impl.dart
similarity index 99%
rename from lib/webview/webview_controller_impel/webview_controller_impel.dart
rename to lib/webview/video/impl/video_webview_impl.dart
index 85720b1d..bb04ef08 100644
--- a/lib/webview/webview_controller_impel/webview_controller_impel.dart
+++ b/lib/webview/video/impl/video_webview_impl.dart
@@ -4,13 +4,13 @@ import 'package:kazumi/utils/utils.dart';
import 'package:kazumi/utils/storage.dart';
import 'package:kazumi/utils/proxy_utils.dart';
import 'package:kazumi/utils/logger.dart';
-import 'package:kazumi/webview/webview_controller.dart';
+import 'package:kazumi/webview/video/video_webview_controller.dart';
import 'package:flutter_inappwebview_platform_interface/flutter_inappwebview_platform_interface.dart';
import 'package:flutter_inappwebview_android/flutter_inappwebview_android.dart'
as android_webview;
-class WebviewItemControllerImpel
- extends WebviewItemController<PlatformInAppWebViewController> {
+class VideoWebviewImpl
+ extends VideoWebviewController<PlatformInAppWebViewController> {
PlatformHeadlessInAppWebView? headlessWebView;
bool hasRegisteredHandlers = false;
bool useLegacyParser = false;
diff --git a/lib/webview/webview_controller_impel/webview_linux_controller_impel.dart b/lib/webview/video/impl/video_webview_linux_impl.dart
similarity index 98%
rename from lib/webview/webview_controller_impel/webview_linux_controller_impel.dart
rename to lib/webview/video/impl/video_webview_linux_impl.dart
index 8f4b1f62..31f25cea 100644
--- a/lib/webview/webview_controller_impel/webview_linux_controller_impel.dart
+++ b/lib/webview/video/impl/video_webview_linux_impl.dart
@@ -1,12 +1,12 @@
import 'dart:async';
-import 'package:kazumi/webview/webview_controller.dart';
+import 'package:kazumi/webview/video/video_webview_controller.dart';
import 'package:kazumi/utils/utils.dart';
import 'package:kazumi/utils/storage.dart';
import 'package:kazumi/utils/proxy_utils.dart';
import 'package:kazumi/utils/logger.dart';
import 'package:desktop_webview_window/desktop_webview_window.dart';
-class WebviewLinuxItemControllerImpel extends WebviewItemController<Webview> {
+class VideoWebviewLinuxImpl extends VideoWebviewController<Webview> {
bool bridgeInited = false;
@override
diff --git a/lib/webview/webview_controller_impel/webview_windows_controller_impel.dart b/lib/webview/video/impl/video_webview_windows_impl.dart
similarity index 95%
rename from lib/webview/webview_controller_impel/webview_windows_controller_impel.dart
rename to lib/webview/video/impl/video_webview_windows_impl.dart
index 04ea8899..9804b951 100644
--- a/lib/webview/webview_controller_impel/webview_windows_controller_impel.dart
+++ b/lib/webview/video/impl/video_webview_windows_impl.dart
@@ -1,12 +1,12 @@
import 'dart:async';
import 'package:webview_windows/webview_windows.dart';
-import 'package:kazumi/webview/webview_controller.dart';
+import 'package:kazumi/webview/video/video_webview_controller.dart';
import 'package:kazumi/utils/storage.dart';
import 'package:kazumi/utils/proxy_utils.dart';
import 'package:kazumi/utils/logger.dart';
-class WebviewWindowsItemControllerImpel
- extends WebviewItemController<WebviewController> {
+class VideoWebviewWindowsImpl
+ extends VideoWebviewController<WebviewController> {
final List<StreamSubscription> subscriptions = [];
HeadlessWebview? headlessWebview;
diff --git a/lib/webview/webview_controller.dart b/lib/webview/video/video_webview_controller.dart
similarity index 68%
rename from lib/webview/webview_controller.dart
rename to lib/webview/video/video_webview_controller.dart
index 2d680c3d..8cb3f51b 100644
--- a/lib/webview/webview_controller.dart
+++ b/lib/webview/video/video_webview_controller.dart
@@ -1,14 +1,14 @@
import 'dart:io';
import 'dart:async';
-import 'package:kazumi/webview/webview_controller_impel/webview_android_controller_impel.dart';
-import 'package:kazumi/webview/webview_controller_impel/webview_controller_impel.dart';
-import 'package:kazumi/webview/webview_controller_impel/webview_windows_controller_impel.dart';
-import 'package:kazumi/webview/webview_controller_impel/webview_linux_controller_impel.dart';
-import 'package:kazumi/webview/webview_controller_impel/webview_apple_controller_impel.dart';
+import 'package:kazumi/webview/video/impl/video_webview_android_impl.dart';
+import 'package:kazumi/webview/video/impl/video_webview_impl.dart';
+import 'package:kazumi/webview/video/impl/video_webview_windows_impl.dart';
+import 'package:kazumi/webview/video/impl/video_webview_linux_impl.dart';
+import 'package:kazumi/webview/video/impl/video_webview_apple_impl.dart';
import 'package:kazumi/utils/utils.dart';
-abstract class WebviewItemController<T> {
+abstract class VideoWebviewController<T> {
// Webview controller
T? webviewController;
@@ -58,20 +58,20 @@ abstract class WebviewItemController<T> {
void dispose();
}
-class WebviewItemControllerFactory {
- static WebviewItemController getController() {
+class VideoWebviewControllerFactory {
+ static VideoWebviewController getController() {
if (Platform.isWindows) {
- return WebviewWindowsItemControllerImpel();
+ return VideoWebviewWindowsImpl();
}
if (Platform.isLinux) {
- return WebviewLinuxItemControllerImpel();
+ return VideoWebviewLinuxImpl();
}
if (Platform.isMacOS || Platform.isIOS) {
- return WebviewAppleItemControllerImpel();
+ return VideoWebviewAppleImpl();
}
if (Platform.isAndroid && Utils.isDocumentStartScriptSupported) {
- return WebviewAndroidItemControllerImpel();
+ return VideoWebviewAndroidImpl();
}
- return WebviewItemControllerImpel();
+ return VideoWebviewImpl();
}
}
diff --git a/pubspec.lock b/pubspec.lock
index 78ef99a2..899f0711 100644
--- a/pubspec.lock
+++ b/pubspec.lock
@@ -249,6 +249,14 @@ packages:
url: "https://pub.dev"
source: hosted
version: "3.1.2"
+ cookie_jar:
+ dependency: "direct main"
+ description:
+ name: cookie_jar
+ sha256: "963da02c1ef64cb5ac20de948c9e5940aa351f1e34a12b1d327c83d85b7e8fff"
+ url: "https://pub.dev"
+ source: hosted
+ version: "4.0.9"
crypto:
dependency: transitive
description:
@@ -1640,8 +1648,8 @@ packages:
dependency: "direct main"
description:
path: "."
- ref: "9b9aabb2452e53d8d32bf59d571520fdfbaa7c21"
- resolved-ref: "9b9aabb2452e53d8d32bf59d571520fdfbaa7c21"
+ ref: "1b9e83371356c04d8b0fb7ab1d20ebacf5cf9764"
+ resolved-ref: "1b9e83371356c04d8b0fb7ab1d20ebacf5cf9764"
url: "https://github.com/Predidit/flutter-webview-windows.git"
source: git
version: "0.4.0"
diff --git a/pubspec.yaml b/pubspec.yaml
index 1acfb5ee..0cfb3006 100644
--- a/pubspec.yaml
+++ b/pubspec.yaml
@@ -41,6 +41,7 @@ dependencies:
mobx: ^2.6.0
flutter_mobx: ^2.3.0
dio: ^5.0.0
+ cookie_jar: ^4.0.9
connectivity_plus: ^6.0.5
path_provider: ^2.1.5
@@ -93,7 +94,7 @@ dependencies:
webview_windows:
git:
url: https://github.com/Predidit/flutter-webview-windows.git
- ref: 9b9aabb2452e53d8d32bf59d571520fdfbaa7c21
+ ref: 1b9e83371356c04d8b0fb7ab1d20ebacf5cf9764
desktop_webview_window:
git:
url: https://github.com/Predidit/linux_webview_window.git