Skip to content

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

feat(ui): redesign source selection cards

Predidit1eab03f3c276
diff --git a/lib/bean/settings/settings_list.dart b/lib/bean/settings/settings_list.dart
index fc2db5f9..87baad35 100644
--- a/lib/bean/settings/settings_list.dart
+++ b/lib/bean/settings/settings_list.dart
@@ -1,11 +1,8 @@
import 'package:flutter/material.dart';
+import 'package:kazumi/bean/widget/split_list_row.dart';
enum _TileKind { plain, toggle, radio }
-const double _outerRadius = 24;
-const double _innerRadius = 4;
-const double _rowGap = 4;
-
class SettingsList extends StatelessWidget {
const SettingsList({super.key, required this.sections, this.maxWidth = 1000});
@@ -84,7 +81,7 @@ class SettingsSplitGroup extends StatelessWidget {
const SettingsSplitGroup({
super.key,
required this.children,
- this.outerRadius = _outerRadius,
+ this.outerRadius = splitListOuterRadius,
});
final List<Widget> children;
@@ -94,25 +91,18 @@ class SettingsSplitGroup extends StatelessWidget {
/// smaller scale passes theirs so the group sits level with them.
final double outerRadius;
- /// Hand to a row's [InkWell.onHighlightChanged] to drive the morph. Null
- /// outside a group, which leaves the row's shape static.
- static ValueChanged<bool>? pressReporterOf(BuildContext context) {
- return context
- .dependOnInheritedWidgetOfExactType<_SplitRowScope>()
- ?.onPressChanged;
- }
-
@override
Widget build(BuildContext context) {
return Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
for (int i = 0; i < children.length; i++) ...[
- if (i > 0) const SizedBox(height: _rowGap),
- _SplitRow(
- first: i == 0,
- last: i == children.length - 1,
- outerRadius: outerRadius,
+ if (i > 0) const SizedBox(height: splitListRowGap),
+ SplitListRow(
+ topRadius: i == 0 ? outerRadius : splitListInnerRadius,
+ bottomRadius:
+ i == children.length - 1 ? outerRadius : splitListInnerRadius,
+ pressedRadius: outerRadius,
child: children[i],
),
],
@@ -121,60 +111,6 @@ class SettingsSplitGroup extends StatelessWidget {
}
}
-class _SplitRow extends StatefulWidget {
- const _SplitRow({
- required this.first,
- required this.last,
- required this.outerRadius,
- required this.child,
- });
-
- final bool first;
- final bool last;
- final double outerRadius;
- final Widget child;
-
- @override
- State<_SplitRow> createState() => _SplitRowState();
-}
-
-class _SplitRowState extends State<_SplitRow> {
- bool _pressed = false;
-
- @override
- Widget build(BuildContext context) {
- final outer = widget.outerRadius;
- final top = widget.first || _pressed ? outer : _innerRadius;
- final bottom = widget.last || _pressed ? outer : _innerRadius;
- return Material(
- // Material animates its own shape, so the morph needs no controller.
- color: Theme.of(context).colorScheme.surfaceContainerLow,
- shape: RoundedRectangleBorder(
- borderRadius: BorderRadius.vertical(
- top: Radius.circular(top),
- bottom: Radius.circular(bottom),
- ),
- ),
- clipBehavior: Clip.antiAlias,
- child: _SplitRowScope(
- onPressChanged: (pressed) => setState(() => _pressed = pressed),
- child: widget.child,
- ),
- );
- }
-}
-
-class _SplitRowScope extends InheritedWidget {
- const _SplitRowScope({required this.onPressChanged, required super.child});
-
- final ValueChanged<bool> onPressChanged;
-
- // The callback always reaches the same state, so a rebuilt scope never
- // obsoletes the one a row already holds.
- @override
- bool updateShouldNotify(_SplitRowScope oldWidget) => false;
-}
-
/// A [SettingsSection] whose tiles form a single radio group, so arrow keys
/// traverse the options and screen readers announce them as one set.
class SettingsRadioSection<T> extends StatelessWidget {
@@ -279,7 +215,7 @@ class SettingsCategoryTile extends StatelessWidget {
final textTheme = Theme.of(context).textTheme;
return InkWell(
onTap: onTap,
- onHighlightChanged: SettingsSplitGroup.pressReporterOf(context),
+ onHighlightChanged: SplitListRow.pressReporterOf(context),
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12),
child: Row(
@@ -493,7 +429,7 @@ class SettingsTile<T> extends StatelessWidget {
return InkWell(
onTap: _tapHandler(context),
- onHighlightChanged: SettingsSplitGroup.pressReporterOf(context),
+ onHighlightChanged: SplitListRow.pressReporterOf(context),
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12),
child: ConstrainedBox(
diff --git a/lib/bean/widget/split_list_row.dart b/lib/bean/widget/split_list_row.dart
new file mode 100644
index 00000000..ae2e04f5
--- /dev/null
+++ b/lib/bean/widget/split_list_row.dart
@@ -0,0 +1,96 @@
+import 'package:flutter/material.dart';
+
+/// The M3 Expressive split-list vocabulary: large corners at a group's ends,
+/// small ones between rows, and a gap in place of a divider.
+const double splitListOuterRadius = 24;
+const double splitListInnerRadius = 4;
+const double splitListRowGap = 4;
+
+const Duration splitListMotionDuration = Duration(milliseconds: 250);
+const Curve splitListMotionCurve = Curves.easeInOutCubic;
+
+/// One row of a split list, morphing to [pressedRadius] while held.
+///
+/// The press is driven by [onTap] here, or, when the row's content owns its
+/// own [InkWell], by handing [pressReporterOf] to that
+/// [InkWell.onHighlightChanged].
+class SplitListRow extends StatefulWidget {
+ const SplitListRow({
+ super.key,
+ required this.child,
+ this.color,
+ this.topRadius = splitListInnerRadius,
+ this.bottomRadius = splitListInnerRadius,
+ this.pressedRadius = splitListOuterRadius,
+ this.onTap,
+ });
+
+ final Widget child;
+
+ /// Defaults to `surfaceContainerLow`.
+ final Color? color;
+
+ final double topRadius;
+ final double bottomRadius;
+ final double pressedRadius;
+ final VoidCallback? onTap;
+
+ /// Null outside a row, which leaves that row's shape static.
+ static ValueChanged<bool>? pressReporterOf(BuildContext context) {
+ return context
+ .dependOnInheritedWidgetOfExactType<_SplitRowScope>()
+ ?.onPressChanged;
+ }
+
+ @override
+ State<SplitListRow> createState() => _SplitListRowState();
+}
+
+class _SplitListRowState extends State<SplitListRow> {
+ bool _pressed = false;
+
+ void _reportPress(bool pressed) => setState(() => _pressed = pressed);
+
+ @override
+ Widget build(BuildContext context) {
+ final child = widget.onTap == null
+ ? widget.child
+ : InkWell(
+ onTap: widget.onTap,
+ onHighlightChanged: _reportPress,
+ child: widget.child,
+ );
+ // An AnimatedContainer rather than Material's implicit animation:
+ // Material tweens its shape but snaps its colour.
+ return AnimatedContainer(
+ duration: splitListMotionDuration,
+ curve: splitListMotionCurve,
+ clipBehavior: Clip.antiAlias,
+ decoration: BoxDecoration(
+ color:
+ widget.color ?? Theme.of(context).colorScheme.surfaceContainerLow,
+ borderRadius: BorderRadius.vertical(
+ top: Radius.circular(
+ _pressed ? widget.pressedRadius : widget.topRadius),
+ bottom: Radius.circular(
+ _pressed ? widget.pressedRadius : widget.bottomRadius),
+ ),
+ ),
+ child: Material(
+ type: MaterialType.transparency,
+ child: _SplitRowScope(onPressChanged: _reportPress, child: child),
+ ),
+ );
+ }
+}
+
+class _SplitRowScope extends InheritedWidget {
+ const _SplitRowScope({required this.onPressChanged, required super.child});
+
+ final ValueChanged<bool> onPressChanged;
+
+ // The callback always reaches the same state, so a rebuilt scope never
+ // obsoletes the one a row already holds.
+ @override
+ bool updateShouldNotify(_SplitRowScope oldWidget) => false;
+}
diff --git a/lib/pages/info/source_alias_dialog.dart b/lib/pages/info/source_alias_dialog.dart
new file mode 100644
index 00000000..f9bb8d7e
--- /dev/null
+++ b/lib/pages/info/source_alias_dialog.dart
@@ -0,0 +1,138 @@
+import 'package:flutter/material.dart';
+import 'package:kazumi/bean/dialog/dialog_helper.dart';
+
+/// Deletions edit [aliases] in place and then fire [onAliasesChanged], so the
+/// caller can persist the list it passed in.
+void showAliasPickerDialog({
+ required List<String> aliases,
+ required ValueChanged<String> onAliasSelected,
+ required VoidCallback onAliasesChanged,
+}) {
+ KazumiDialog.show(
+ builder: (context) => _AliasPickerDialog(
+ aliases: aliases,
+ onAliasSelected: onAliasSelected,
+ onAliasesChanged: onAliasesChanged,
+ ),
+ );
+}
+
+/// [onSubmit] never sees a blank keyword.
+void showCustomKeywordDialog({required ValueChanged<String> onSubmit}) {
+ String keyword = '';
+
+ void submit(String value) {
+ final trimmed = value.trim();
+ if (trimmed.isEmpty) return;
+ KazumiDialog.dismiss();
+ onSubmit(trimmed);
+ }
+
+ KazumiDialog.show(
+ builder: (context) => AlertDialog(
+ title: const Text('输入别名'),
+ content: TextField(
+ onChanged: (value) => keyword = value,
+ onSubmitted: submit,
+ ),
+ actions: [
+ TextButton(
+ onPressed: KazumiDialog.dismiss,
+ child: Text(
+ '取消',
+ style: TextStyle(color: Theme.of(context).colorScheme.outline),
+ ),
+ ),
+ TextButton(
+ onPressed: () => submit(keyword),
+ child: const Text('确认'),
+ ),
+ ],
+ ),
+ );
+}
+
+class _AliasPickerDialog extends StatefulWidget {
+ const _AliasPickerDialog({
+ required this.aliases,
+ required this.onAliasSelected,
+ required this.onAliasesChanged,
+ });
+
+ final List<String> aliases;
+ final ValueChanged<String> onAliasSelected;
+ final VoidCallback onAliasesChanged;
+
+ @override
+ State<_AliasPickerDialog> createState() => _AliasPickerDialogState();
+}
+
+class _AliasPickerDialogState extends State<_AliasPickerDialog> {
+ late final ValueNotifier<List<String>> _aliasNotifier =
+ ValueNotifier<List<String>>(List.from(widget.aliases));
+
+ @override
+ void dispose() {
+ _aliasNotifier.dispose();
+ super.dispose();
+ }
+
+ void _confirmDelete(int index) {
+ KazumiDialog.show(
+ builder: (context) => AlertDialog(
+ title: const Text('删除确认'),
+ content: const Text('删除后无法恢复,确认要永久删除这个别名吗?'),
+ actions: [
+ TextButton(
+ onPressed: KazumiDialog.dismiss,
+ child: Text(
+ '取消',
+ style: TextStyle(color: Theme.of(context).colorScheme.outline),
+ ),
+ ),
+ TextButton(
+ onPressed: () {
+ KazumiDialog.dismiss();
+ widget.aliases.removeAt(index);
+ _aliasNotifier.value = List.from(widget.aliases);
+ widget.onAliasesChanged();
+ if (widget.aliases.isEmpty) {
+ Navigator.of(this.context).pop();
+ }
+ },
+ child: const Text('确认'),
+ ),
+ ],
+ ),
+ );
+ }
+
+ @override
+ Widget build(BuildContext context) {
+ return Dialog(
+ clipBehavior: Clip.antiAlias,
+ child: SizedBox(
+ width: 560,
+ child: ValueListenableBuilder<List<String>>(
+ valueListenable: _aliasNotifier,
+ builder: (context, aliasList, child) {
+ return ListView(
+ shrinkWrap: true,
+ children: [
+ for (var index = 0; index < aliasList.length; index++)
+ ListTile(
+ title: Text(aliasList[index]),
+ trailing: IconButton(
+ onPressed: () => _confirmDelete(index),
+ icon: const Icon(Icons.delete),
+ ),
+ onTap: () => widget.onAliasSelected(aliasList[index]),
+ ),
+ ],
+ );
+ },
+ ),
+ ),
+ );
+ }
+}
diff --git a/lib/pages/info/source_captcha_flow.dart b/lib/pages/info/source_captcha_flow.dart
new file mode 100644
index 00000000..6b81a98a
--- /dev/null
+++ b/lib/pages/info/source_captcha_flow.dart
@@ -0,0 +1,398 @@
+import 'dart:async';
+import 'dart:convert';
+
+import 'package:flutter/material.dart';
+import 'package:kazumi/bean/dialog/dialog_helper.dart';
+import 'package:kazumi/plugins/anti_crawler_config.dart';
+import 'package:kazumi/plugins/plugins.dart';
+import 'package:kazumi/services/plugin/captcha_verification_service.dart';
+
+/// Runs one plugin's anti-crawler verification end to end, owning the webview
+/// service, its dialog and the timeout that closes it.
+class SourceCaptchaFlow {
+ SourceCaptchaFlow({required this.onVerified, required this.onCancelled});
+
+ final void Function(Plugin plugin, String pageHtml) onVerified;
+
+ /// Dismissed before verification landed, so the source is still unresolved.
+ final void Function(Plugin plugin) onCancelled;
+
+ CaptchaVerificationService? _service;
+ Timer? _timer;
+
+ void start(Plugin plugin, String keyword) {
+ final searchUrl = plugin.searchURL
+ .replaceAll('@keyword', Uri.encodeQueryComponent(keyword));
+ switch (plugin.antiCrawlerConfig.captchaType) {
+ case CaptchaType.customJavaScript:
+ _startAutomated(
+ plugin,
+ searchUrl,
+ statusText: '${plugin.name} 正在执行验证脚本,请稍候',
+ detailText: '已加载验证页面并执行自定义脚本,等待验证通过…',
+ startVerification: (service, url, onVerified) =>
+ service.loadForCustomScript(
+ url: url,
+ script: plugin.antiCrawlerConfig.captchaScript,
+ pluginName: plugin.name,
+ onVerified: onVerified,
+ ),
+ );
+ case CaptchaType.autoClickButton:
+ _startAutomated(
+ plugin,
+ searchUrl,
+ statusText: '${plugin.name} 正在自动完成验证,请稍候',
+ detailText: '已检测到验证按钮并模拟点击,等待验证通过…',
+ startVerification: (service, url, onVerified) =>
+ service.loadForButtonClick(
+ url: url,
+ buttonXpath: plugin.antiCrawlerConfig.captchaButton,
+ pluginName: plugin.name,
+ onVerified: onVerified,
+ ),
+ );
+ default:
+ _startCaptchaInput(plugin, searchUrl);
+ }
+ }
+
+ void dispose() {
+ _service?.dispose();
+ _service = null;
+ _timer?.cancel();
+ _timer = null;
+ }
+
+ void _startCaptchaInput(Plugin plugin, String searchUrl) {
+ bool verified = false;
+
+ // Set once the webview reports the captcha gone. The timeout only guards
+ // "verification was never detected", so it keys off this rather than
+ // `verified`, which lands seconds later when the harvest finishes.
+ bool finalizing = false;
+
+ _service?.dispose();
+ final service = _service = CaptchaVerificationService();
+
+ service.loadForCaptcha(
+ searchUrl,
+ plugin.antiCrawlerConfig.captchaImage,
+ inputXpath: plugin.antiCrawlerConfig.captchaInput,
+ );
+
+ Future<void> submitCaptcha(String captchaCode) async {
+ await _service?.submitCaptcha(
+ captchaCode: captchaCode.trim(),
+ inputXpath: plugin.antiCrawlerConfig.captchaInput,
+ buttonXpath: plugin.antiCrawlerConfig.captchaButton,
+ pluginName: plugin.name,
+ // Verification is already confirmed here; the harvest that follows
+ // takes seconds, so retire the timeout now rather than in onVerified.
+ onFinalizing: () {
+ finalizing = true;
+ _timer?.cancel();
+ _timer = null;
+ },
+ onVerified: (pageHtml) {
+ verified = true;
+ KazumiDialog.dismiss();
+ onVerified(plugin, pageHtml);
+ },
+ );
+ // submitCaptcha completes once the JS button click is fired; only now
+ // does the wait for the captcha to disappear begin.
+ if (!finalizing) {
+ _timer?.cancel();
+ _timer = Timer(const Duration(seconds: 8), () {
+ if (!finalizing) {
+ KazumiDialog.dismiss();
+ }
+ });
+ }
+ }
+
+ KazumiDialog.show(
+ onDismiss: () async {
+ _timer?.cancel();
+ _timer = null;
+ // Capture before the await: an async gap could otherwise let
+ // [_service] be replaced or cleared, leaving this closure to dispose
+ // the wrong one.
+ final captchaService = _service;
+ _service = null;
+ if (verified) {
+ captchaService?.dispose();
+ } else {
+ // Saving the earned cookies needs the webview, so it has to
+ // happen before the service goes.
+ await captchaService?.cancelAndSave(plugin.name);
+ captchaService?.dispose();
+ onCancelled(plugin);
+ }
+ },
+ builder: (context) => _CaptchaDialog(
+ pluginName: plugin.name,
+ captchaImageStream: service.onCaptchaImageUrl,
+ onSubmit: submitCaptcha,
+ ),
+ );
+ }
+
+ void _startAutomated(
+ Plugin plugin,
+ String searchUrl, {
+ required String statusText,
+ required String detailText,
+ required Future<void> Function(
+ CaptchaVerificationService service,
+ String searchUrl,
+ void Function(String pageHtml) onVerified,
+ ) startVerification,
+ }) {
+ bool verified = false;
+
+ _service?.dispose();
+ final service = _service = CaptchaVerificationService();
+
+ unawaited(startVerification(service, searchUrl, (pageHtml) {
+ verified = true;
+ KazumiDialog.dismiss();
+ onVerified(plugin, pageHtml);
+ }));
+
+ KazumiDialog.show(
+ onDismiss: () async {
+ final captchaService = _service;
+ _service = null;
+ if (verified) {
+ captchaService?.dispose();
+ } else {
+ await captchaService?.cancelAndSave(plugin.name);
+ captchaService?.dispose();
+ onCancelled(plugin);
+ }
+ },
+ builder: (context) => _AutomatedVerifyDialog(
+ statusText: statusText,
+ detailText: detailText,
+ ),
+ );
+ }
+}
+
+class _VerifyDialogFrame extends StatelessWidget {
+ const _VerifyDialogFrame({
+ required this.title,
+ required this.statusText,
+ required this.children,
+ });
+
+ final String title;
+ final String statusText;
+ final List<Widget> children;
+
+ @override
+ Widget build(BuildContext context) {
+ final theme = Theme.of(context);
+ return Dialog(
+ clipBehavior: Clip.antiAlias,
+ child: Padding(
+ padding: const EdgeInsets.all(24),
+ child: SizedBox(
+ width: 400,
+ child: Column(
+ mainAxisSize: MainAxisSize.min,
+ children: [
+ Text(title, style: theme.textTheme.titleLarge),
+ const SizedBox(height: 4),
+ Text(statusText, style: theme.textTheme.bodySmall),
+ ...children,
+ ],
+ ),
+ ),
+ ),
+ );
+ }
+}
+
+class _CaptchaDialog extends StatefulWidget {
+ const _CaptchaDialog({
+ required this.pluginName,
+ required this.captchaImageStream,
+ required this.onSubmit,
+ });
+
+ final String pluginName;
+ final Stream<String?> captchaImageStream;
+ final Future<void> Function(String captchaCode) onSubmit;
+
+ @override
+ State<_CaptchaDialog> createState() => _CaptchaDialogState();
+}
+
+class _CaptchaDialogState extends State<_CaptchaDialog> {
+ final ValueNotifier<String?> _captchaImageNotifier =
+ ValueNotifier<String?>(null);
+ final ValueNotifier<bool> _submittingNotifier = ValueNotifier<bool>(false);
+ late final StreamSubscription<String?> _imageSub;
+ String _captchaCode = '';
+
+ @override
+ void initState() {
+ super.initState();
+ _imageSub = widget.captchaImageStream.listen((url) {
+ if (!mounted || url == null) return;
+ _captchaImageNotifier.value = url;
+ });
+ }
+
+ @override
+ void dispose() {
+ _imageSub.cancel();
+ _captchaImageNotifier.dispose();
+ _submittingNotifier.dispose();
+ super.dispose();
+ }
+
+ Future<void> _submit() async {
+ if (_submittingNotifier.value) return;
+ final captchaCode = _captchaCode.trim();
+ if (captchaCode.isEmpty) {
+ KazumiDialog.showToast(message: '请输入验证码');
+ return;
+ }
+ _submittingNotifier.value = true;
+ await widget.onSubmit(captchaCode);
+ }
+
+ @override
+ Widget build(BuildContext context) {
+ return _VerifyDialogFrame(
+ title: '验证码验证',
+ statusText: '${widget.pluginName} 需要验证码验证',
+ children: [
+ 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(
+ autofocus: true,
+ enabled: !isSubmitting,
+ onChanged: (value) => _captchaCode = value,
+ decoration: const InputDecoration(
+ labelText: '请输入验证码',
+ border: OutlineInputBorder(),
+ ),
+ onSubmitted: isSubmitting ? null : (_) => _submit(),
+ ),
+ ],
+ );
+ },
+ );
+ },
+ ),
+ const SizedBox(height: 20),
+ ListenableBuilder(
+ listenable: Listenable.merge([
+ _captchaImageNotifier,
+ _submittingNotifier,
+ ]),
+ builder: (context, _) {
+ final isSubmitting = _submittingNotifier.value;
+ final isDisabled =
+ _captchaImageNotifier.value == null || 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 : _submit,
+ child: isSubmitting
+ ? const SizedBox.square(
+ dimension: 18,
+ child: CircularProgressIndicator(strokeWidth: 2),
+ )
+ : const Text('提交'),
+ ),
+ ],
+ );
+ },
+ ),
+ ],
+ );
+ }
+}
+
+class _AutomatedVerifyDialog extends StatelessWidget {
+ const _AutomatedVerifyDialog({
+ required this.statusText,
+ required this.detailText,
+ });
+
+ final String statusText;
+ final String detailText;
+
+ @override
+ Widget build(BuildContext context) {
+ return _VerifyDialogFrame(
+ title: '自动验证中',
+ statusText: statusText,
+ children: [
+ const SizedBox(height: 24),
+ const CircularProgressIndicator(),
+ const SizedBox(height: 12),
+ Text(
+ detailText,
+ 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),
+ ),
+ ),
+ ),
+ ],
+ );
+ }
+}
diff --git a/lib/pages/info/source_sheet.dart b/lib/pages/info/source_sheet.dart
index 16d05374..0cc2b694 100644
--- a/lib/pages/info/source_sheet.dart
+++ b/lib/pages/info/source_sheet.dart
@@ -1,14 +1,14 @@
import 'package:flutter/material.dart';
import 'package:flutter_mobx/flutter_mobx.dart';
import 'package:flutter_modular/flutter_modular.dart';
-// Only the reaction API: mobx also exports a Listenable, which collides with
-// the Flutter one used further down this file.
import 'package:mobx/mobx.dart' show reaction, ReactionDisposer;
import 'package:kazumi/pages/info/info_controller.dart';
+import 'package:kazumi/pages/info/source_alias_dialog.dart';
+import 'package:kazumi/pages/info/source_captcha_flow.dart';
import 'package:kazumi/services/logging/logger.dart';
import 'package:kazumi/bean/dialog/dialog_helper.dart';
import 'package:kazumi/bean/dialog/material_bottom_sheet.dart';
-import 'package:kazumi/bean/settings/settings_list.dart';
+import 'package:kazumi/bean/widget/split_list_row.dart';
import 'package:kazumi/plugins/plugins_controller.dart';
import 'package:kazumi/plugins/plugins.dart';
import 'package:kazumi/modules/search/plugin_search_module.dart';
@@ -18,10 +18,6 @@ import 'package:kazumi/services/plugin/rule_engine_models.dart'
import 'package:url_launcher/url_launcher.dart';
import 'package:kazumi/services/plugin/plugin_search_service.dart';
import 'package:kazumi/pages/collect/collect_controller.dart';
-import 'dart:async';
-import 'dart:convert';
-import 'package:kazumi/services/plugin/captcha_verification_service.dart';
-import 'package:kazumi/plugins/anti_crawler_config.dart';
import 'package:kazumi/utils/device.dart';
class SourceSheet extends StatefulWidget {
@@ -37,298 +33,81 @@ class SourceSheet extends StatefulWidget {
}
class _SourceSheetState extends State<SourceSheet> {
- final CollectController collectController = inject<CollectController>();
- final PluginsController pluginsController = inject<PluginsController>();
- late String keyword;
+ final CollectController _collectController = inject<CollectController>();
+ final PluginsController _pluginsController = inject<PluginsController>();
- /// Plugin name whose results are expanded, or null for none.
- String? expandedSource;
- ReactionDisposer? autoExpandDisposer;
+ late final String _keyword;
+ late final PluginSearchService _searchService;
+ late final SourceCaptchaFlow _captchaFlow;
- /// Concurrent plugin search service.
- PluginSearchService? pluginSearchService;
-
- /// Captcha verification service (created on demand)
- CaptchaVerificationService? _captchaVerificationService;
-
- /// Timeout timer waiting for captcha verification result
- Timer? _captchaVerifyTimer;
+ String? _expandedSource;
+ ReactionDisposer? _autoExpandDisposer;
@override
void initState() {
- keyword = widget.infoController.bangumiItem.nameCn == ''
+ super.initState();
+ _keyword = widget.infoController.bangumiItem.nameCn == ''
? widget.infoController.bangumiItem.name
: widget.infoController.bangumiItem.nameCn;
- pluginSearchService = PluginSearchService(
+ _searchService = PluginSearchService(
infoController: widget.infoController,
- pluginsController: pluginsController,
+ pluginsController: _pluginsController,
+ );
+ _searchService.queryAllSource(_keyword);
+ _captchaFlow = SourceCaptchaFlow(
+ onVerified: _showVerifiedResult,
+ onCancelled: (plugin) => _querySource(_keyword, plugin.name),
);
- pluginSearchService?.queryAllSource(keyword);
// One shot: whichever source reports results first opens, and from then on
// the open card only moves when tapped.
- autoExpandDisposer = reaction<String?>(
- (_) => firstSourceWithResults(),
+ _autoExpandDisposer = reaction<String?>(
+ (_) => _firstSourceWithResults(),
(name) {
- if (name == null || expandedSource != null) return;
- setState(() => expandedSource = name);
- stopAutoExpand();
+ if (name == null) return;
+ setState(() => _expandedSource = name);
+ _stopAutoExpand();
},
);
- super.initState();
- }
-
- void stopAutoExpand() {
- autoExpandDisposer?.call();
- autoExpandDisposer = null;
}
@override
void dispose() {
- stopAutoExpand();
- pluginSearchService?.cancel();
- pluginSearchService = null;
- _captchaVerificationService?.dispose();
- _captchaVerificationService = null;
- _captchaVerifyTimer?.cancel();
- _captchaVerifyTimer = null;
+ _stopAutoExpand();
+ _searchService.cancel();
+ _captchaFlow.dispose();
super.dispose();
}
- /// After verification the webview already shows the real result page;
- /// prefer publishing the harvested HTML directly and only fall back to a
- /// delayed re-search when it does not parse.
+ void _stopAutoExpand() {
+ _autoExpandDisposer?.call();
+ _autoExpandDisposer = null;
+ }
+
+ /// Callbacks can outlive the sheet — a countdown ending after it closes, a
+ /// dialog dismissed behind it — and a cancelled service still clears the
+ /// page's results on its way to doing nothing.
+ void _querySource(String keyword, String pluginName) {
+ if (!mounted) return;
+ _searchService.querySource(keyword, pluginName);
+ }
+
void _showVerifiedResult(Plugin plugin, String pageHtml) {
- final harvested = pluginSearchService?.applyHarvestedSearchResult(
- plugin.name,
- pageHtml,
- ) ??
- false;
- if (harvested) {
+ if (_searchService.applyHarvestedSearchResult(plugin.name, pageHtml)) {
KazumiDialog.showToast(message: '验证成功');
return;
}
- // show a 3s countdown progress dialog before re-querying,
- // to avoid triggering rate limits immediately after verification.
+ // Counting down before re-querying keeps the retry from tripping the rate
+ // limit the verification just cleared.
KazumiDialog.showTimedSuccessDialog(
title: '验证成功',
message: '即将重新检索',
- onComplete: () => pluginSearchService?.querySource(keyword, plugin.name),
- );
- }
-
- void showAntiCrawlerDialog(Plugin plugin) {
- switch (plugin.antiCrawlerConfig.captchaType) {
- case CaptchaType.customJavaScript:
- showCustomScriptDialog(plugin);
- break;
- case CaptchaType.autoClickButton:
- showButtonClickDialog(plugin);
- break;
- default:
- showCaptchaDialog(plugin);
- }
- }
-
- void showCaptchaDialog(Plugin plugin) {
- /// flag whether verification has passed, used to distinguish normal dismissal from cancellation in onDismiss
- bool verified = false;
-
- /// Set once the webview reports the captcha gone. The timeout below only
- /// guards "verification was never detected", so it keys off this rather
- /// than [verified], which lands seconds later when the harvest finishes.
- bool finalizing = false;
-
- _captchaVerificationService?.dispose();
- _captchaVerificationService = CaptchaVerificationService();
-
- final searchUrl = plugin.searchURL
- .replaceAll('@keyword', Uri.encodeQueryComponent(keyword));
-
- _captchaVerificationService!.loadForCaptcha(
- searchUrl,
- plugin.antiCrawlerConfig.captchaImage,
- inputXpath: plugin.antiCrawlerConfig.captchaInput,
- );
-
- Future<void> submitCaptcha(String captchaCode) async {
- await _captchaVerificationService?.submitCaptcha(
- captchaCode: captchaCode.trim(),
- inputXpath: plugin.antiCrawlerConfig.captchaInput,
- buttonXpath: plugin.antiCrawlerConfig.captchaButton,
- pluginName: plugin.name,
- // Verification is already confirmed here; the harvest that follows
- // takes seconds, so retire the timeout now rather than in onVerified.
- onFinalizing: () {
- finalizing = true;
- _captchaVerifyTimer?.cancel();
- _captchaVerifyTimer = null;
- },
- onVerified: (pageHtml) {
- verified = true;
- KazumiDialog.dismiss();
- _showVerifiedResult(plugin, pageHtml);
- },
- );
- // submitCaptcha completes after the JS button click is fired.
- // Start the 8-second timeout only NOW, waiting for the webview to
- // detect the captcha disappearing.
- if (!finalizing) {
- _captchaVerifyTimer?.cancel();
- _captchaVerifyTimer = Timer(const Duration(seconds: 8), () {
- if (!finalizing) {
- KazumiDialog.dismiss();
- }
- });
- }
- }
-
- KazumiDialog.show(
- onDismiss: () async {
- _captchaVerifyTimer?.cancel();
- _captchaVerifyTimer = null;
- // Capture the current service instance locally before any await.
- // Without this, an async gap could allow _captchaVerificationService to be
- // replaced (or nulled by _SourceSheetState.dispose()), causing the
- // closure to dispose the wrong/already-disposed instance.
- final captchaService = _captchaVerificationService;
- _captchaVerificationService = null;
- if (!verified) {
- await captchaService?.cancelAndSave(plugin.name);
- captchaService?.dispose();
- pluginSearchService?.querySource(keyword, plugin.name);
- } else {
- captchaService?.dispose();
- }
- },
- builder: (context) => _CaptchaDialog(
- pluginName: plugin.name,
- captchaImageStream: _captchaVerificationService!.onCaptchaImageUrl,
- onSubmit: submitCaptcha,
- ),
- );
- }
-
- void showButtonClickDialog(Plugin plugin) {
- showAutomatedVerifyDialog(
- plugin,
- statusText: '${plugin.name} 正在自动完成验证,请稍候',
- detailText: '已检测到验证按钮并模拟点击,等待验证通过…',
- startVerification: (captchaService, searchUrl, onVerified) {
- return captchaService.loadForButtonClick(
- url: searchUrl,
- buttonXpath: plugin.antiCrawlerConfig.captchaButton,
- pluginName: plugin.name,
- onVerified: onVerified,
- );
- },
- );
- }
-
- void showCustomScriptDialog(Plugin plugin) {
- showAutomatedVerifyDialog(
- plugin,
- statusText: '${plugin.name} 正在执行验证脚本,请稍候',
- detailText: '已加载验证页面并执行自定义脚本,等待验证通过…',
- startVerification: (captchaService, searchUrl, onVerified) {
- return captchaService.loadForCustomScript(
- url: searchUrl,
- script: plugin.antiCrawlerConfig.captchaScript,
- pluginName: plugin.name,
- onVerified: onVerified,
- );
- },
- );
- }
-
- void showAutomatedVerifyDialog(
- Plugin plugin, {
- required String statusText,
- required String detailText,
- required Future<void> Function(
- CaptchaVerificationService captchaService,
- String searchUrl,
- void Function(String pageHtml) onVerified,
- ) startVerification,
- }) {
- bool verified = false;
-
- _captchaVerificationService?.dispose();
- _captchaVerificationService = CaptchaVerificationService();
-
- final captchaService = _captchaVerificationService!;
- final searchUrl = plugin.searchURL
- .replaceAll('@keyword', Uri.encodeQueryComponent(keyword));
-
- void onVerified(String pageHtml) {
- verified = true;
- KazumiDialog.dismiss();
- _showVerifiedResult(plugin, pageHtml);
- }
-
- unawaited(startVerification(captchaService, searchUrl, onVerified));
-
- KazumiDialog.show(
- onDismiss: () async {
- final captchaService = _captchaVerificationService;
- _captchaVerificationService = null;
- if (verified) {
- captchaService?.dispose();
- } else {
- await captchaService?.cancelAndSave(plugin.name);
- captchaService?.dispose();
- pluginSearchService?.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(
- statusText,
- style: Theme.of(context).textTheme.bodySmall,
- ),
- const SizedBox(height: 24),
- const CircularProgressIndicator(),
- const SizedBox(height: 12),
- Text(
- detailText,
- 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),
- ),
- ),
- ),
- ],
- ),
- ),
- ),
- ),
+ onComplete: () => _querySource(_keyword, plugin.name),
);
}
/// A plugin can publish more than one response: an alias search adds to what
/// the first pass found.
- List<SearchItem> resultsFor(String pluginName) {
+ List<SearchItem> _resultsFor(String pluginName) {
final results = <SearchItem>[];
for (final response in widget.infoController.pluginSearchResponseList) {
if (response.pluginName == pluginName) {
@@ -338,17 +117,31 @@ class _SourceSheetState extends State<SourceSheet> {
return results;
}
- void openInBrowser(Plugin plugin) {
+ String? _firstSourceWithResults() {
+ for (final plugin in _pluginsController.pluginList) {
+ if (_resultsFor(plugin.name).isNotEmpty) return plugin.name;
+ }
+ return null;
+ }
+
+ void _toggleSource(String pluginName) {
+ setState(() {
+ _expandedSource = _expandedSource == pluginName ? null : pluginName;
+ });
+ _stopAutoExpand();
+ }
+
+ void _openInBrowser(Plugin plugin) {
final targetUrl = plugin.usesApiSearch
? plugin.baseUrl
: plugin.searchURL.replaceFirst(
'@keyword',
- Uri.encodeQueryComponent(keyword),
+ Uri.encodeQueryComponent(_keyword),
);
launchUrl(Uri.parse(targetUrl), mode: LaunchMode.externalApplication);
}
- Future<void> openSearchItem(Plugin plugin, SearchItem searchItem) async {
+ Future<void> _openSearchItem(Plugin plugin, SearchItem searchItem) async {
final cancelToken = RuleCancelToken();
KazumiDialog.showLoading(
msg: '获取中',
@@ -376,34 +169,90 @@ class _SourceSheetState extends State<SourceSheet> {
),
);
} catch (_) {
- KazumiLogger()
- .w("PluginSearchService: failed to query video playlist");
+ KazumiLogger().w("PluginSearchService: failed to query video playlist");
KazumiDialog.dismiss();
}
}
- /// One source, collapsed to a row until opened. The row is both the picker
- /// and its own heading, so no separate strip of source buttons is needed.
- /// A source that came back empty opens onto its recovery actions instead of
- /// results, and only one source is open at a time.
- Widget buildSourceCard(Plugin plugin, List<SearchItem> results, bool open) {
+ /// Searching under an alias also saves it for the next visit.
+ void _searchAlias(String pluginName, String alias) {
+ if (!widget.infoController.bangumiItem.alias.contains(alias)) {
+ widget.infoController.bangumiItem.alias.add(alias);
+ _collectController.updateLocalCollect(widget.infoController.bangumiItem);
+ }
+ _querySource(alias, pluginName);
+ }
+
+ void _showAliasPicker(String pluginName) {
+ if (widget.infoController.bangumiItem.alias.isEmpty) {
+ KazumiDialog.showToast(message: '无可用别名,试试手动检索');
+ return;
+ }
+ showAliasPickerDialog(
+ aliases: widget.infoController.bangumiItem.alias,
+ onAliasSelected: (alias) {
+ KazumiDialog.dismiss();
+ _querySource(alias, pluginName);
+ },
+ onAliasesChanged: () => _collectController
+ .updateLocalCollect(widget.infoController.bangumiItem),
+ );
+ }
+
+ void _showCustomKeyword(String pluginName) => showCustomKeywordDialog(
+ onSubmit: (keyword) => _searchAlias(pluginName, keyword),
+ );
+
+ /// One source, collapsed to a row until opened. The header sits a surface
+ /// step above its result rows — and shifts to `secondaryContainer` while
+ /// open — so a rule never reads as one of the titles it returned.
+ Widget _buildSourceCard(Plugin plugin, List<SearchItem> results, bool open) {
final searching = widget.infoController.pluginSearchStatus[plugin.name] ==
PluginSearchStatus.pending;
+ final colorScheme = Theme.of(context).colorScheme;
+
+ final body = <({Widget child, VoidCallback? onTap})>[];
+ if (open && !searching) {
+ if (results.isEmpty) {
+ body.add((child: _buildActionsRow(plugin), onTap: null));
+ } else {
+ for (final result in results) {
+ body.add((
+ child: _buildResultRow(result),
+ onTap: () => _openSearchItem(plugin, result),
+ ));
+ }
+ }
+ }
+
return Padding(
- padding: const EdgeInsets.only(bottom: 8),
+ padding: const EdgeInsets.only(bottom: 12),
child: AnimatedSize(
- duration: const Duration(milliseconds: 250),
- curve: Curves.easeInOutCubic,
+ duration: splitListMotionDuration,
+ curve: splitListMotionCurve,
alignment: Alignment.topCenter,
- child: SettingsSplitGroup(
+ child: Column(
+ crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
- buildSourceRow(plugin, results, searching, open),
- if (open && !searching) ...[
- for (final searchItem in results)
- buildResultRow(plugin, searchItem),
- // Buttons under a result list get hit by thumbs reaching for the
- // last row, so with results they live in the header menu.
- if (results.isEmpty) buildActionsRow(plugin),
+ SplitListRow(
+ color: open
+ ? colorScheme.secondaryContainer
+ : colorScheme.surfaceContainer,
+ topRadius: splitListOuterRadius,
+ bottomRadius:
+ body.isEmpty ? splitListOuterRadius : splitListInnerRadius,
+ onTap: () => _toggleSource(plugin.name),
+ child: _buildSourceHeader(plugin, results, searching, open),
+ ),
+ for (var i = 0; i < body.length; i++) ...[
+ const SizedBox(height: splitListRowGap),
+ SplitListRow(
+ bottomRadius: i == body.length - 1
+ ? splitListOuterRadius
+ : splitListInnerRadius,
+ onTap: body[i].onTap,
+ child: body[i].child,
+ ),
],
],
),
@@ -411,10 +260,9 @@ class _SourceSheetState extends State<SourceSheet> {
);
}
- /// How many titles a source found, or why it found none. Status rides in
- /// this trailing text rather than a leading icon: rows whose siblings lack
- /// one end up with misaligned names.
- ({String text, Color? color}) sourceSummary(
+ /// Status rides in trailing text rather than a leading icon: rows whose
+ /// siblings lack one end up with misaligned names.
+ ({String text, Color? color}) _sourceSummary(
Plugin plugin, List<SearchItem> results, bool searching) {
if (searching) return (text: '检索中', color: null);
if (results.isNotEmpty) return (text: '${results.length} 条', color: null);
@@ -426,142 +274,120 @@ class _SourceSheetState extends State<SourceSheet> {
};
}
- /// The open source's row is inert: exactly one source is open at a time, so
- /// tapping the open one has nothing to do, and a no-op there means a thumb
- /// overshooting the first result cannot throw the whole list away.
- Widget buildSourceRow(
+ Widget _buildSourceHeader(
Plugin plugin, List<SearchItem> results, bool searching, bool open) {
- // A Builder so the row's context sits below the group's press scope.
- return Builder(
- builder: (context) {
- final theme = Theme.of(context);
- final summary = sourceSummary(plugin, results, searching);
- final hasMenu = open && results.isNotEmpty;
- final row = Padding(
- // Both branches land on 56dp, matching a result row: the menu's
- // IconButton is 48dp on its own.
- padding: hasMenu
- ? const EdgeInsets.fromLTRB(18, 4, 4, 4)
- : const EdgeInsets.fromLTRB(18, 18, 18, 18),
- child: Row(
- children: [
- Expanded(
- child: Text(
- plugin.name,
- style: theme.textTheme.titleSmall,
- ),
- ),
- Text(
- summary.text,
- style: theme.textTheme.labelMedium?.copyWith(
- color: summary.color ?? theme.colorScheme.onSurfaceVariant,
- ),
- ),
- if (searching) ...[
- const SizedBox(width: 10),
- const SizedBox.square(
- dimension: 16,
- child: CircularProgressIndicator(strokeWidth: 2),
- ),
- ] else if (hasMenu)
- PopupMenuButton<VoidCallback>(
- tooltip: '${plugin.name} 的更多操作',
- icon: const Icon(Icons.more_vert_rounded, size: 20),
- onSelected: (action) => action(),
- itemBuilder: (context) => [
- PopupMenuItem(
- value: () => showAliasSearchDialog(plugin.name),
- child: const Text('别名检索'),
- ),
- PopupMenuItem(
- value: () => showCustomSearchDialog(plugin.name),
- child: const Text('手动检索'),
- ),
- PopupMenuItem(
- value: () => openInBrowser(plugin),
- child: const Text('在浏览器中打开'),
- ),
- ],
- )
- else if (!open) ...[
- const SizedBox(width: 10),
- Icon(
- Icons.expand_more_rounded,
- size: 20,
- color: theme.colorScheme.onSurfaceVariant,
- ),
- ],
- ],
+ final theme = Theme.of(context);
+ final colorScheme = theme.colorScheme;
+ final summary = _sourceSummary(plugin, results, searching);
+ final onColor = open ? colorScheme.onSecondaryContainer : null;
+ // Buttons under a result list get hit by thumbs reaching for the last row,
+ // so a source with results keeps its actions up here instead.
+ final hasMenu = open && !searching && results.isNotEmpty;
+ return Padding(
+ // Both branches land on 56dp, matching a result row: the menu's
+ // IconButton is 48dp on its own.
+ padding: hasMenu
+ ? const EdgeInsets.fromLTRB(18, 4, 14, 4)
+ : const EdgeInsets.fromLTRB(18, 18, 18, 18),
+ child: Row(
+ children: [
+ Expanded(
+ child: Text(
+ plugin.name,
+ style: theme.textTheme.titleSmall?.copyWith(color: onColor),
+ ),
),
- );
- if (open || searching) return row;
- return InkWell(
- onTap: () => setState(() {
- expandedSource = plugin.name;
- stopAutoExpand();
- }),
- onHighlightChanged: SettingsSplitGroup.pressReporterOf(context),
- child: row,
- );
- },
+ Text(
+ summary.text,
+ style: theme.textTheme.labelMedium?.copyWith(
+ color: summary.color ?? onColor ?? colorScheme.onSurfaceVariant,
+ ),
+ ),
+ if (searching) ...[
+ const SizedBox(width: 10),
+ const SizedBox.square(
+ dimension: 16,
+ child: CircularProgressIndicator(strokeWidth: 2),
+ ),
+ ] else ...[
+ if (hasMenu)
+ PopupMenuButton<VoidCallback>(
+ tooltip: '${plugin.name} 的更多操作',
+ icon: Icon(Icons.more_vert_rounded, size: 20, color: onColor),
+ onSelected: (action) => action(),
+ itemBuilder: (context) => [
+ PopupMenuItem(
+ value: () => _showAliasPicker(plugin.name),
+ child: const Text('别名检索'),
+ ),
+ PopupMenuItem(
+ value: () => _showCustomKeyword(plugin.name),
+ child: const Text('手动检索'),
+ ),
+ PopupMenuItem(
+ value: () => _openInBrowser(plugin),
+ child: const Text('在浏览器中打开'),
+ ),
+ ],
+ )
+ else
+ const SizedBox(width: 10),
+ AnimatedRotation(
+ turns: open ? 0.5 : 0,
+ duration: splitListMotionDuration,
+ curve: splitListMotionCurve,
+ child: Icon(
+ Icons.expand_more_rounded,
+ size: 20,
+ color: onColor ?? colorScheme.onSurfaceVariant,
+ ),
+ ),
+ ],
+ ],
+ ),
);
}
- Widget buildResultRow(Plugin plugin, SearchItem searchItem) {
- return Builder(
- builder: (context) => InkWell(
- onTap: () => openSearchItem(plugin, searchItem),
- onHighlightChanged: SettingsSplitGroup.pressReporterOf(context),
- child: Padding(
- padding: const EdgeInsets.fromLTRB(18, 18, 16, 18),
- child: Row(
- children: [
- Expanded(
- child: Text(
- searchItem.name,
- style: Theme.of(context).textTheme.bodyMedium,
- ),
- ),
- const SizedBox(width: 8),
- Icon(
- Icons.play_arrow_rounded,
- size: 20,
- color: Theme.of(context).colorScheme.primary,
- ),
- ],
+ Widget _buildResultRow(SearchItem searchItem) {
+ final theme = Theme.of(context);
+ return Padding(
+ padding: const EdgeInsets.fromLTRB(18, 18, 16, 18),
+ child: Row(
+ children: [
+ Expanded(
+ child: Text(searchItem.name, style: theme.textTheme.bodyMedium),
),
- ),
+ const SizedBox(width: 8),
+ Icon(
+ Icons.play_arrow_rounded,
+ size: 20,
+ color: theme.colorScheme.primary,
+ ),
+ ],
),
);
}
- /// Recovery actions for a source that found nothing. Buttons keep their full
- /// Material size so they hold the 48dp tap target, and wrap rather than
- /// shrink when the row runs out of width.
- Widget buildActionsRow(Plugin plugin) {
+ Widget _buildActionsRow(Plugin plugin) {
final theme = Theme.of(context);
- final status = widget.infoController.pluginSearchStatus[plugin.name];
-
final actions = <Widget>[];
final String hint;
- if (status == PluginSearchStatus.captcha) {
- hint = '这个源要求先完成验证';
- actions
- .add(buildPrimaryAction('进行验证', () => showAntiCrawlerDialog(plugin)));
- actions.add(buildAction(
- '重试', () => pluginSearchService?.querySource(keyword, plugin.name)));
- } else if (status == PluginSearchStatus.error) {
- hint = '这个源没能返回结果';
- actions.add(buildPrimaryAction(
- '重试', () => pluginSearchService?.querySource(keyword, plugin.name)));
- } else {
- hint = '换个关键词再试试';
- actions.add(
- buildPrimaryAction('别名检索', () => showAliasSearchDialog(plugin.name)));
- actions
- .add(buildAction('手动检索', () => showCustomSearchDialog(plugin.name)));
+ switch (widget.infoController.pluginSearchStatus[plugin.name]) {
+ case PluginSearchStatus.captcha:
+ hint = '这个源要求先完成验证';
+ actions.add(
+ _primaryAction('进行验证', () => _captchaFlow.start(plugin, _keyword)));
+ actions.add(_action('重试', () => _retry(plugin)));
+ case PluginSearchStatus.error:
+ hint = '这个源没能返回结果';
+ actions.add(_primaryAction('重试', () => _retry(plugin)));
+ default:
+ hint = '换个关键词再试试';
+ actions
+ .add(_primaryAction('别名检索', () => _showAliasPicker(plugin.name)));
+ actions.add(_action('手动检索', () => _showCustomKeyword(plugin.name)));
}
- actions.add(buildAction('浏览器打开', () => openInBrowser(plugin)));
+ actions.add(_action('浏览器打开', () => _openInBrowser(plugin)));
return Padding(
padding: const EdgeInsets.fromLTRB(14, 10, 14, 12),
@@ -583,119 +409,44 @@ class _SourceSheetState extends State<SourceSheet> {
);
}
- Widget buildPrimaryAction(String label, VoidCallback onPressed) {
- return FilledButton.tonal(onPressed: onPressed, child: Text(label));
- }
+ void _retry(Plugin plugin) => _querySource(_keyword, plugin.name);
- Widget buildAction(String label, VoidCallback onPressed) {
- return TextButton(onPressed: onPressed, child: Text(label));
- }
+ Widget _primaryAction(String label, VoidCallback onPressed) =>
+ FilledButton.tonal(onPressed: onPressed, child: Text(label));
- void showAliasSearchDialog(String pluginName) {
- if (widget.infoController.bangumiItem.alias.isEmpty) {
- KazumiDialog.showToast(message: '无可用别名,试试手动检索');
- return;
- }
- KazumiDialog.show(
- builder: (context) {
- return _AliasDialog(
- aliases: widget.infoController.bangumiItem.alias,
- onAliasSelected: (alias) {
- KazumiDialog.dismiss();
- pluginSearchService?.querySource(alias, pluginName);
- },
- onAliasesChanged: () {
- collectController
- .updateLocalCollect(widget.infoController.bangumiItem);
- },
- );
- },
- );
- }
-
- void showCustomSearchDialog(String pluginName) {
- String customKeyword = '';
-
- void submit(String value) {
- final alias = value.trim();
- if (alias.isEmpty) {
- return;
- }
- widget.infoController.bangumiItem.alias.add(alias);
- collectController.updateLocalCollect(widget.infoController.bangumiItem);
- KazumiDialog.dismiss();
- pluginSearchService?.querySource(alias, pluginName);
- }
-
- KazumiDialog.show(
- builder: (context) {
- return AlertDialog(
- title: const Text('输入别名'),
- content: TextField(
- onChanged: (value) => customKeyword = value,
- onSubmitted: (keyword) {
- submit(keyword);
- },
- ),
- actions: [
- TextButton(
- onPressed: () {
- KazumiDialog.dismiss();
- },
- child: Text(
- '取消',
- style: TextStyle(color: Theme.of(context).colorScheme.outline),
- ),
- ),
- TextButton(
- onPressed: () {
- submit(customKeyword);
- },
- child: const Text('确认'),
- ),
- ],
- );
- },
- );
- }
+ Widget _action(String label, VoidCallback onPressed) =>
+ TextButton(onPressed: onPressed, child: Text(label));
- /// Always plugin order, never ranked by what came back. A source can fill up
- /// long after the search settles — a captcha source does exactly that once
- /// verified — and ranking would slide the card someone just acted on out
- /// from under them. [expandedSource] is what leads to something playable.
- List<Widget> buildSourceCards() {
+ /// Always plugin order, never ranked by what came back: a source can fill
+ /// up long after the search settles — a captcha source does once verified
+ /// — and ranking would slide the card someone just acted on out from
+ /// under them.
+ List<Widget> _buildSourceCards() {
final cards = <Widget>[];
- for (final plugin in pluginsController.pluginList) {
- cards.add(buildSourceCard(
+ for (final plugin in _pluginsController.pluginList) {
+ cards.add(_buildSourceCard(
plugin,
- resultsFor(plugin.name),
- expandedSource == plugin.name,
+ _resultsFor(plugin.name),
+ _expandedSource == plugin.name,
));
}
cards.add(const SafeArea(top: false, child: SizedBox(height: 12)));
return cards;
}
- String? firstSourceWithResults() {
- for (final plugin in pluginsController.pluginList) {
- if (resultsFor(plugin.name).isNotEmpty) return plugin.name;
- }
- return null;
- }
-
- String buildProgressDescription() {
- final plugins = pluginsController.pluginList;
+ String _progressDescription() {
+ final plugins = _pluginsController.pluginList;
final done = plugins
.where((plugin) =>
widget.infoController.pluginSearchStatus[plugin.name] !=
PluginSearchStatus.pending)
.length;
final found = plugins.fold<int>(
- 0, (sum, plugin) => sum + resultsFor(plugin.name).length);
+ 0, (sum, plugin) => sum + _resultsFor(plugin.name).length);
if (done < plugins.length) {
- return '「$keyword」· 检索中 $done/${plugins.length}';
+ return '「$_keyword」· 检索中 $done/${plugins.length}';
}
- return '「$keyword」· $found 条结果';
+ return '「$_keyword」· $found 条结果';
}
@override
@@ -706,12 +457,12 @@ class _SourceSheetState extends State<SourceSheet> {
builder: (context) {
// Must be read here, not behind a nested Builder: mobx only tracks
// reads made while the Observer's own builder runs.
- final cards = buildSourceCards();
+ final cards = _buildSourceCards();
return Column(
children: [
MaterialBottomSheetHeader(
title: '选择播放源',
- description: buildProgressDescription(),
+ description: _progressDescription(),
onClose: () => Navigator.of(context).pop(),
),
Expanded(
@@ -728,258 +479,3 @@ class _SourceSheetState extends State<SourceSheet> {
);
}
}
-
-class _CaptchaDialog extends StatefulWidget {
- const _CaptchaDialog({
- required this.pluginName,
- required this.captchaImageStream,
- required this.onSubmit,
- });
-
- final String pluginName;
- final Stream<String?> captchaImageStream;
- final Future<void> Function(String captchaCode) onSubmit;
-
- @override
- State<_CaptchaDialog> createState() => _CaptchaDialogState();
-}
-
-class _CaptchaDialogState extends State<_CaptchaDialog> {
- final ValueNotifier<String?> _captchaImageNotifier =
- ValueNotifier<String?>(null);
- final ValueNotifier<bool> _submittingNotifier = ValueNotifier<bool>(false);
- late final StreamSubscription<String?> _imageSub;
- String _captchaCode = '';
-
- @override
- void initState() {
- super.initState();
- _imageSub = widget.captchaImageStream.listen((url) {
- if (!mounted || url == null) return;
- _captchaImageNotifier.value = url;
- });
- }
-
- @override
- void dispose() {
- _imageSub.cancel();
- _captchaImageNotifier.dispose();
- _submittingNotifier.dispose();
- super.dispose();
- }
-
- Future<void> _submit() async {
- if (_submittingNotifier.value) return;
- final captchaCode = _captchaCode.trim();
- if (captchaCode.isEmpty) {
- KazumiDialog.showToast(message: '请输入验证码');
- return;
- }
- _submittingNotifier.value = true;
- await widget.onSubmit(captchaCode);
- }
-
- @override
- Widget build(BuildContext 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(
- '${widget.pluginName} 需要验证码验证',
- 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(
- autofocus: true,
- enabled: !isSubmitting,
- onChanged: (value) => _captchaCode = value,
- decoration: const InputDecoration(
- labelText: '请输入验证码',
- border: OutlineInputBorder(),
- ),
- onSubmitted: isSubmitting ? null : (_) => _submit(),
- ),
- ],
- );
- },
- );
- },
- ),
- 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 : _submit,
- child: isSubmitting
- ? const SizedBox(
- width: 18,
- height: 18,
- child: CircularProgressIndicator(
- strokeWidth: 2,
- ),
- )
- : const Text('提交'),
- ),
- ],
- );
- },
- ),
- ],
- ),
- ),
- ),
- );
- }
-}
-
-class _AliasDialog extends StatefulWidget {
- const _AliasDialog({
- required this.aliases,
- required this.onAliasSelected,
- required this.onAliasesChanged,
- });
-
- final List<String> aliases;
- final ValueChanged<String> onAliasSelected;
- final VoidCallback onAliasesChanged;
-
- @override
- State<_AliasDialog> createState() => _AliasDialogState();
-}
-
-class _AliasDialogState extends State<_AliasDialog> {
- late final ValueNotifier<List<String>> aliasNotifier =
- ValueNotifier<List<String>>(List.from(widget.aliases));
-
- @override
- void dispose() {
- aliasNotifier.dispose();
- super.dispose();
- }
-
- @override
- Widget build(BuildContext context) {
- return Dialog(
- clipBehavior: Clip.antiAlias,
- child: SizedBox(
- width: 560,
- child: ValueListenableBuilder<List<String>>(
- valueListenable: aliasNotifier,
- builder: (context, aliasList, child) {
- return ListView(
- shrinkWrap: true,
- children: aliasList.asMap().entries.map((entry) {
- final index = entry.key;
- final alias = entry.value;
- return ListTile(
- title: Text(alias),
- trailing: IconButton(
- onPressed: () {
- KazumiDialog.show(
- builder: (context) {
- return AlertDialog(
- title: const Text('删除确认'),
- content: const Text('删除后无法恢复,确认要永久删除这个别名吗?'),
- actions: [
- TextButton(
- onPressed: () {
- KazumiDialog.dismiss();
- },
- child: Text(
- '取消',
- style: TextStyle(
- color: Theme.of(context)
- .colorScheme
- .outline),
- ),
- ),
- TextButton(
- onPressed: () {
- KazumiDialog.dismiss();
- widget.aliases.removeAt(index);
- aliasNotifier.value =
- List.from(widget.aliases);
- widget.onAliasesChanged();
- if (widget.aliases.isEmpty) {
- Navigator.of(this.context).pop();
- }
- },
- child: const Text('确认'),
- ),
- ],
- );
- },
- );
- },
- icon: Icon(Icons.delete),
- ),
- onTap: () => widget.onAliasSelected(alias),
- );
- }).toList(),
- );
- },
- ),
- ),
- );
- }
-}