Skip to content

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

feat: image search (#2000)

LiggMaxa65b433b2870
diff --git a/README.md b/README.md
index d7629273..402ee371 100644
--- a/README.md
+++ b/README.md
@@ -183,6 +183,8 @@ A: 本项目编译需要良好的网络环境, 除了由 Google 托管的 Flutte
特别感谢 [SyncPlay](https://github.com/Syncplay/syncplay) 本项目使用 SyncPlay 协议并通过 SyncPlay 公共服务器实现一起看功能。
+特别感谢 [trace.moe](https://trace.moe) 本项目使用了 trace.moe 提供的图片识别番剧功能。
+
感谢 [media-kit](https://github.com/media-kit/media-kit) 本项目跨平台媒体播放能力来自 media-kit。
感谢 [avbuild](https://github.com/wang-bin/avbuild) 本项目使用了来自 avbuild 的树外补丁实现非标准视频流播放。
@@ -191,4 +193,3 @@ A: 本项目编译需要良好的网络环境, 除了由 Google 托管的 Flutte
-
diff --git a/lib/modules/search/image_search_module.dart b/lib/modules/search/image_search_module.dart
new file mode 100644
index 00000000..c146fa61
--- /dev/null
+++ b/lib/modules/search/image_search_module.dart
@@ -0,0 +1,410 @@
+import 'dart:convert';
+
+class ImageSearchItem {
+ final int? frameCount;
+ final String? error;
+ final List<ResultItem>? result;
+
+ ImageSearchItem({this.frameCount, this.error, this.result});
+
+ factory ImageSearchItem.fromJson(Map<String, dynamic> json) {
+ return ImageSearchItem(
+ frameCount: json['frameCount'] as int?,
+ error: json['error'] as String?,
+ result: json['result'] == null
+ ? null
+ : (json['result'] as List)
+ .map((e) => ResultItem.fromJson(e as Map<String, dynamic>))
+ .toList(),
+ );
+ }
+
+ Map<String, dynamic> toJson() => {
+ 'frameCount': frameCount,
+ 'error': error,
+ 'result': result?.map((e) => e.toJson()).toList(),
+ };
+
+ @override
+ String toString() => jsonEncode(toJson());
+}
+
+class ResultItem {
+ final Anilist? anilist;
+ final String? filename;
+ final dynamic episode; // num, List<num> or null
+ final double? from;
+ final double? at;
+ final double? to;
+ final double? duration;
+ final double? similarity;
+ final String? video;
+ final String? image;
+
+ ResultItem({
+ this.anilist,
+ this.filename,
+ this.episode,
+ this.from,
+ this.at,
+ this.to,
+ this.duration,
+ this.similarity,
+ this.video,
+ this.image,
+ });
+
+ factory ResultItem.fromJson(Map<String, dynamic> json) {
+ dynamic ep = json['episode'];
+ if (ep is List) {
+ ep = ep.whereType<num>().toList();
+ } else if (ep is! num) {
+ ep = null;
+ }
+
+ return ResultItem(
+ anilist: json['anilist'] == null
+ ? null
+ : Anilist.fromJson(json['anilist'] as Map<String, dynamic>),
+ filename: json['filename'] as String?,
+ episode: ep,
+ from: (json['from'] as num?)?.toDouble(),
+ at: (json['at'] as num?)?.toDouble(),
+ to: (json['to'] as num?)?.toDouble(),
+ duration: (json['duration'] as num?)?.toDouble(),
+ similarity: (json['similarity'] as num?)?.toDouble(),
+ video: json['video'] as String?,
+ image: json['image'] as String?,
+ );
+ }
+
+ Map<String, dynamic> toJson() => {
+ 'anilist': anilist?.toJson(),
+ 'filename': filename,
+ 'episode': episode,
+ 'from': from,
+ 'at': at,
+ 'to': to,
+ 'duration': duration,
+ 'similarity': similarity,
+ 'video': video,
+ 'image': image,
+ };
+}
+
+class Anilist {
+ final int? id;
+ final String? type;
+ final int? idMal;
+ final AnilistTitle? title;
+ final String? format;
+ final List<String>? genres;
+ final String? season;
+ final String? source;
+ final String? status;
+ final DateInfo? endDate;
+ final DateInfo? startDate;
+ final bool? isAdult;
+ final String? siteUrl;
+ final Studios? studios;
+ final int? duration;
+ final int? episodes;
+ final List<String>? synonyms;
+ final Relations? relations;
+ final int? seasonInt;
+ final CoverImage? coverImage;
+ final int? popularity;
+ final int? seasonYear;
+ final String? bannerImage;
+ final List<ExternalLink>? externalLinks;
+ final String? countryOfOrigin;
+ final List<String>? synonymsChinese;
+
+ Anilist({
+ this.id,
+ this.type,
+ this.idMal,
+ this.title,
+ this.format,
+ this.genres,
+ this.season,
+ this.source,
+ this.status,
+ this.endDate,
+ this.startDate,
+ this.isAdult,
+ this.siteUrl,
+ this.studios,
+ this.duration,
+ this.episodes,
+ this.synonyms,
+ this.relations,
+ this.seasonInt,
+ this.coverImage,
+ this.popularity,
+ this.seasonYear,
+ this.bannerImage,
+ this.externalLinks,
+ this.countryOfOrigin,
+ this.synonymsChinese,
+ });
+
+ factory Anilist.fromJson(Map<String, dynamic> json) {
+ return Anilist(
+ id: json['id'] as int?,
+ type: json['type'] as String?,
+ idMal: json['idMal'] as int?,
+ title: json['title'] == null
+ ? null
+ : AnilistTitle.fromJson(json['title'] as Map<String, dynamic>),
+ format: json['format'] as String?,
+ genres: json['genres'] == null
+ ? null
+ : List<String>.from(json['genres'] as List),
+ season: json['season'] as String?,
+ source: json['source'] as String?,
+ status: json['status'] as String?,
+ endDate: json['endDate'] == null
+ ? null
+ : DateInfo.fromJson(json['endDate'] as Map<String, dynamic>),
+ startDate: json['startDate'] == null
+ ? null
+ : DateInfo.fromJson(json['startDate'] as Map<String, dynamic>),
+ isAdult: json['isAdult'] as bool?,
+ siteUrl: json['siteUrl'] as String?,
+ studios: json['studios'] == null
+ ? null
+ : Studios.fromJson(json['studios'] as Map<String, dynamic>),
+ duration: json['duration'] as int?,
+ episodes: json['episodes'] as int?,
+ synonyms: json['synonyms'] == null
+ ? null
+ : List<String>.from(json['synonyms'] as List),
+ relations: json['relations'] == null
+ ? null
+ : Relations.fromJson(json['relations'] as Map<String, dynamic>),
+ seasonInt: json['seasonInt'] as int?,
+ coverImage: json['coverImage'] == null
+ ? null
+ : CoverImage.fromJson(json['coverImage'] as Map<String, dynamic>),
+ popularity: json['popularity'] as int?,
+ seasonYear: json['seasonYear'] as int?,
+ bannerImage: json['bannerImage'] as String?,
+ externalLinks: json['externalLinks'] == null
+ ? null
+ : (json['externalLinks'] as List)
+ .map((e) => ExternalLink.fromJson(e as Map<String, dynamic>))
+ .toList(),
+ countryOfOrigin: json['countryOfOrigin'] as String?,
+ synonymsChinese: json['synonyms_chinese'] == null
+ ? null
+ : List<String>.from(json['synonyms_chinese'] as List),
+ );
+ }
+
+ Map<String, dynamic> toJson() => {
+ 'id': id,
+ 'type': type,
+ 'idMal': idMal,
+ 'title': title?.toJson(),
+ 'format': format,
+ 'genres': genres,
+ 'season': season,
+ 'source': source,
+ 'status': status,
+ 'endDate': endDate?.toJson(),
+ 'startDate': startDate?.toJson(),
+ 'isAdult': isAdult,
+ 'siteUrl': siteUrl,
+ 'studios': studios?.toJson(),
+ 'duration': duration,
+ 'episodes': episodes,
+ 'synonyms': synonyms,
+ 'relations': relations?.toJson(),
+ 'seasonInt': seasonInt,
+ 'coverImage': coverImage?.toJson(),
+ 'popularity': popularity,
+ 'seasonYear': seasonYear,
+ 'bannerImage': bannerImage,
+ 'externalLinks': externalLinks?.map((e) => e.toJson()).toList(),
+ 'countryOfOrigin': countryOfOrigin,
+ 'synonyms_chinese': synonymsChinese,
+ };
+}
+
+class AnilistTitle {
+ final String? native;
+ final String? romaji;
+ final String? chinese;
+ final String? english;
+
+ AnilistTitle({this.native, this.romaji, this.chinese, this.english});
+
+ factory AnilistTitle.fromJson(Map<String, dynamic> json) => AnilistTitle(
+ native: json['native'] as String?,
+ romaji: json['romaji'] as String?,
+ chinese: json['chinese'] as String?,
+ english: json['english'] as String?,
+ );
+
+ Map<String, dynamic> toJson() => {
+ 'native': native,
+ 'romaji': romaji,
+ 'chinese': chinese,
+ 'english': english,
+ };
+}
+
+class DateInfo {
+ final int? day;
+ final int? year;
+ final int? month;
+
+ DateInfo({this.day, this.year, this.month});
+
+ factory DateInfo.fromJson(Map<String, dynamic> json) => DateInfo(
+ day: json['day'] as int?,
+ year: json['year'] as int?,
+ month: json['month'] as int?,
+ );
+
+ Map<String, dynamic> toJson() => {'day': day, 'year': year, 'month': month};
+}
+
+class CoverImage {
+ final String? color;
+ final String? large;
+ final String? medium;
+ final String? extraLarge;
+
+ CoverImage({this.color, this.large, this.medium, this.extraLarge});
+
+ factory CoverImage.fromJson(Map<String, dynamic> json) => CoverImage(
+ color: json['color'] as String?,
+ large: json['large'] as String?,
+ medium: json['medium'] as String?,
+ extraLarge: json['extraLarge'] as String?,
+ );
+
+ Map<String, dynamic> toJson() => {
+ 'color': color,
+ 'large': large,
+ 'medium': medium,
+ 'extraLarge': extraLarge
+ };
+}
+
+class Studios {
+ final List<StudioEdge>? edges;
+
+ Studios({this.edges});
+
+ factory Studios.fromJson(Map<String, dynamic> json) => Studios(
+ edges: json['edges'] == null
+ ? null
+ : (json['edges'] as List)
+ .map((e) => StudioEdge.fromJson(e as Map<String, dynamic>))
+ .toList(),
+ );
+
+ Map<String, dynamic> toJson() =>
+ {'edges': edges?.map((e) => e.toJson()).toList()};
+}
+
+class StudioEdge {
+ final StudioNode? node;
+ final bool? isMain;
+
+ StudioEdge({this.node, this.isMain});
+
+ factory StudioEdge.fromJson(Map<String, dynamic> json) => StudioEdge(
+ node: json['node'] == null
+ ? null
+ : StudioNode.fromJson(json['node'] as Map<String, dynamic>),
+ isMain: json['isMain'] as bool?,
+ );
+
+ Map<String, dynamic> toJson() => {'node': node?.toJson(), 'isMain': isMain};
+}
+
+class StudioNode {
+ final int? id;
+ final String? name;
+ final String? siteUrl;
+
+ StudioNode({this.id, this.name, this.siteUrl});
+
+ factory StudioNode.fromJson(Map<String, dynamic> json) => StudioNode(
+ id: json['id'] as int?,
+ name: json['name'] as String?,
+ siteUrl: json['siteUrl'] as String?,
+ );
+
+ Map<String, dynamic> toJson() => {'id': id, 'name': name, 'siteUrl': siteUrl};
+}
+
+class Relations {
+ final List<RelationEdge>? edges;
+
+ Relations({this.edges});
+
+ factory Relations.fromJson(Map<String, dynamic> json) => Relations(
+ edges: json['edges'] == null
+ ? null
+ : (json['edges'] as List)
+ .map((e) => RelationEdge.fromJson(e as Map<String, dynamic>))
+ .toList(),
+ );
+
+ Map<String, dynamic> toJson() =>
+ {'edges': edges?.map((e) => e.toJson()).toList()};
+}
+
+class RelationEdge {
+ final RelationNode? node;
+ final String? relationType;
+
+ RelationEdge({this.node, this.relationType});
+
+ factory RelationEdge.fromJson(Map<String, dynamic> json) => RelationEdge(
+ node: json['node'] == null
+ ? null
+ : RelationNode.fromJson(json['node'] as Map<String, dynamic>),
+ relationType: json['relationType'] as String?,
+ );
+
+ Map<String, dynamic> toJson() =>
+ {'node': node?.toJson(), 'relationType': relationType};
+}
+
+class RelationNode {
+ final int? id;
+ final AnilistTitle? title;
+
+ RelationNode({this.id, this.title});
+
+ factory RelationNode.fromJson(Map<String, dynamic> json) => RelationNode(
+ id: json['id'] as int?,
+ title: json['title'] == null
+ ? null
+ : AnilistTitle.fromJson(json['title'] as Map<String, dynamic>),
+ );
+
+ Map<String, dynamic> toJson() => {'id': id, 'title': title?.toJson()};
+}
+
+class ExternalLink {
+ final int? id;
+ final String? url;
+ final String? site;
+
+ ExternalLink({this.id, this.url, this.site});
+
+ factory ExternalLink.fromJson(Map<String, dynamic> json) => ExternalLink(
+ id: json['id'] as int?,
+ url: json['url'] as String?,
+ site: json['site'] as String?,
+ );
+
+ Map<String, dynamic> toJson() => {'id': id, 'url': url, 'site': site};
+}
diff --git a/lib/pages/about/about_page.dart b/lib/pages/about/about_page.dart
index eccc1cd5..927f7a9c 100644
--- a/lib/pages/about/about_page.dart
+++ b/lib/pages/about/about_page.dart
@@ -187,6 +187,14 @@ class _AboutPageState extends State<AboutPage> {
title: Text('番剧索引', style: TextStyle(fontFamily: fontFamily)),
value: Text('Bangumi', style: TextStyle(fontFamily: fontFamily)),
),
+ SettingsTile.navigation(
+ onPressed: (_) {
+ launchUrl(Uri.parse('https://trace.moe'),
+ mode: LaunchMode.externalApplication);
+ },
+ title: Text('以图搜番', style: TextStyle(fontFamily: fontFamily)),
+ value: Text('trace.moe', style: TextStyle(fontFamily: fontFamily)),
+ ),
SettingsTile.navigation(
onPressed: (_) {
launchUrl(Uri.parse(Api.dandanIndex),
diff --git a/lib/pages/search/image_search_page.dart b/lib/pages/search/image_search_page.dart
new file mode 100644
index 00000000..4c8101ae
--- /dev/null
+++ b/lib/pages/search/image_search_page.dart
@@ -0,0 +1,799 @@
+import 'dart:async';
+import 'dart:io';
+
+import 'package:flutter/material.dart';
+import 'package:flutter_mobx/flutter_mobx.dart';
+import 'package:image_picker/image_picker.dart';
+import 'package:kazumi/bean/appbar/sys_app_bar.dart';
+import 'package:kazumi/bean/card/network_img_layer.dart';
+import 'package:kazumi/bean/dialog/dialog_helper.dart';
+import 'package:kazumi/modules/search/image_search_module.dart';
+import 'package:kazumi/pages/search/search_controller.dart';
+import 'package:kazumi/utils/constants.dart';
+import 'package:kazumi/utils/utils.dart';
+import 'package:url_launcher/url_launcher.dart';
+
+class ImageSearchPage extends StatefulWidget {
+ const ImageSearchPage({super.key});
+
+ @override
+ State<ImageSearchPage> createState() => _ImageSearchPageState();
+}
+
+class _ImageSearchPageState extends State<ImageSearchPage> {
+ final TextEditingController _urlController = TextEditingController();
+ final SearchPageController _searchPageController = SearchPageController();
+ final ImagePicker _picker = ImagePicker();
+ bool _isUrlMode = false;
+ String _previewUrl = '';
+ Timer? _debounceTimer;
+ File? _selectedImageFile;
+ String? _selectedImageName;
+
+ @override
+ void initState() {
+ super.initState();
+ _urlController.addListener(_onUrlChanged);
+ }
+
+
+ @override
+ void dispose() {
+ _debounceTimer?.cancel();
+ _urlController.removeListener(_onUrlChanged);
+ _urlController.dispose();
+ super.dispose();
+ }
+
+ void _onUrlChanged() {
+ _debounceTimer?.cancel();
+ final text = _urlController.text.trim();
+ if (text.isEmpty) {
+ setState(() => _previewUrl = '');
+ return;
+ }
+ _debounceTimer = Timer(const Duration(milliseconds: 500), () {
+ if (!mounted) {
+ return;
+ }
+ setState(() {
+ _searchPageController.clearImageSearchState();
+ _previewUrl = text;
+ } );
+ });
+ }
+
+ Future<void> _pickImageFile() async {
+ final XFile? image = await _picker.pickImage(source: ImageSource.gallery);
+ if (image == null) return;
+ const int maxImageBytes = 25 * 1024 * 1024;
+ final imageFile = File(image.path);
+ final imageBytes = await imageFile.length();
+ if (imageBytes > maxImageBytes) {
+ if (!mounted) return;
+ ScaffoldMessenger.of(context).showSnackBar(
+ const SnackBar(content: Text('图片大小不能超过 25MB')),
+ );
+ return;
+ }
+
+ if (!mounted) return;
+ setState(() {
+ _searchPageController.clearImageSearchState();
+ _selectedImageFile = imageFile;
+ _selectedImageName = image.name;
+ });
+ }
+
+ Future<void> _startSearch() async {
+ if (_isUrlMode) {
+ final imageUrl = _urlController.text.trim();
+ final uri = Uri.tryParse(imageUrl);
+ if (imageUrl.isEmpty || uri == null || !uri.hasScheme) {
+ KazumiDialog.showToast(message: '请输入有效的图片链接');
+ return;
+ }
+ await _searchPageController.searchImageByUrl(imageUrl);
+ } else {
+ final imageFile = _selectedImageFile;
+ if (imageFile == null) {
+ KazumiDialog.showToast(message: '请先选择图片文件');
+ return;
+ }
+ await _searchPageController.searchImageByFile(imageFile);
+ }
+
+ if (!mounted) {
+ return;
+ }
+
+ if (_searchPageController.imageSearchError.isNotEmpty &&
+ _searchPageController.imageSearchResults.isEmpty) {
+ KazumiDialog.showToast(message: _searchPageController.imageSearchError);
+ }
+ }
+
+ void _switchMode() {
+ setState(() {
+ _isUrlMode = !_isUrlMode;
+ });
+ }
+
+ static String _formatTraceResultTitle(ResultItem result) {
+ final title = result.anilist?.title;
+ return title?.chinese ??
+ title?.native ??
+ title?.romaji ??
+ title?.english ??
+ result.filename ??
+ '未知番剧';
+ }
+
+
+ static String _formatTraceEpisode(dynamic episode) {
+ String formatEpisodeValue(num value) {
+ return value % 1 == 0 ? value.toInt().toString() : value.toString();
+ }
+
+ if (episode is num) {
+ return '第 ${formatEpisodeValue(episode)} 集';
+ }
+ if (episode is List && episode.isNotEmpty) {
+ final episodes = episode.whereType<num>().map(formatEpisodeValue);
+ if (episodes.isNotEmpty) {
+ return '剧集: ${episodes.join(' / ')}';
+ }
+ }
+ return '剧集未知';
+ }
+
+ int _resolveCrossAxisCount(double width) {
+ if (width < LayoutBreakpoint.compact['width']!) {
+ return 1;
+ }
+ if (width < LayoutBreakpoint.medium['width']!) {
+ return 2;
+ }
+ if (width < 1180) {
+ return 3;
+ }
+ return 4;
+ }
+
+ @override
+ Widget build(BuildContext context) {
+ final colorScheme = Theme.of(context).colorScheme;
+ final textTheme = Theme.of(context).textTheme;
+
+ return Scaffold(
+ appBar: SysAppBar(
+ backgroundColor: Colors.transparent,
+ title: const Text('图片搜索'),
+ ),
+ body: SingleChildScrollView(
+ padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 24),
+ child: Center(
+ child: ConstrainedBox(
+ constraints: const BoxConstraints(maxWidth: 1400),
+ child: Column(
+ crossAxisAlignment: CrossAxisAlignment.start,
+ spacing: 25,
+ children: [
+ AnimatedSwitcher(
+ duration: const Duration(milliseconds: 200),
+ child: _isUrlMode
+ ? _buildUrlInput(colorScheme, textTheme)
+ : _buildUploadArea(colorScheme, textTheme),
+ ),
+ Center(
+ child: TextButton.icon(
+ onPressed: _switchMode,
+ icon: Icon(
+ _isUrlMode ? Icons.upload_file : Icons.link,
+ size: 18,
+ ),
+ label: Text(_isUrlMode ? '改为上传图片文件' : '改为输入图片 URL'),
+ ),
+ ),
+ Observer(
+ builder: (context) => SizedBox(
+ width: double.infinity,
+ height: 52,
+ child: FilledButton.icon(
+ onPressed: _searchPageController.isImageSearching
+ ? null
+ : _startSearch,
+ icon: _searchPageController.isImageSearching
+ ? SizedBox(
+ width: 18,
+ height: 18,
+ child: CircularProgressIndicator(
+ strokeWidth: 2.2,
+ color: colorScheme.onPrimary,
+ ),
+ )
+ : const Icon(Icons.image_search_rounded),
+ label: Text(
+ _searchPageController.isImageSearching
+ ? '搜索中...'
+ : '开始搜索',
+ style: const TextStyle(fontSize: 16),
+ ),
+ ),
+ ),
+ ),
+ _buildResultSection(colorScheme, textTheme),
+ _buildTips(colorScheme, textTheme),
+ ],
+ ),
+ ),
+ ),
+ ),
+ );
+ }
+
+ Widget _buildUploadArea(ColorScheme colorScheme, TextTheme textTheme) {
+ return GestureDetector(
+ onTap: _pickImageFile,
+ child: Container(
+ width: double.infinity,
+ height: 240,
+ decoration: BoxDecoration(
+ color: colorScheme.surfaceContainerHighest.withValues(alpha: 0.5),
+ borderRadius: BorderRadius.circular(16),
+ border: Border.all(
+ color: colorScheme.outline.withValues(alpha: 0.4),
+ width: 1.5,
+ strokeAlign: BorderSide.strokeAlignOutside,
+ ),
+ ),
+ clipBehavior: Clip.antiAlias,
+ child: _selectedImageFile == null
+ ? Column(
+ mainAxisAlignment: MainAxisAlignment.center,
+ children: [
+ Container(
+ width: 64,
+ height: 64,
+ decoration: BoxDecoration(
+ color: colorScheme.primaryContainer,
+ shape: BoxShape.circle,
+ ),
+ child: Icon(
+ Icons.add_photo_alternate_outlined,
+ size: 32,
+ color: colorScheme.onPrimaryContainer,
+ ),
+ ),
+ const SizedBox(height: 16),
+ Text(
+ '点击选择图片',
+ style: textTheme.titleMedium?.copyWith(
+ fontWeight: FontWeight.w600,
+ ),
+ ),
+ const SizedBox(height: 6),
+ Text(
+ '支持 JPG、PNG、WEBP 格式',
+ style: textTheme.bodySmall?.copyWith(
+ color: colorScheme.onSurfaceVariant,
+ ),
+ ),
+ ],
+ )
+ : Stack(
+ fit: StackFit.expand,
+ children: [
+ Image.file(
+ _selectedImageFile!,
+ fit: BoxFit.cover,
+ errorBuilder: (context, error, stackTrace) => Center(
+ child: Text(
+ '图片预览失败',
+ style: textTheme.bodyMedium?.copyWith(
+ color: colorScheme.error,
+ ),
+ ),
+ ),
+ ),
+ DecoratedBox(
+ decoration: BoxDecoration(
+ gradient: LinearGradient(
+ begin: Alignment.topCenter,
+ end: Alignment.bottomCenter,
+ colors: [
+ Colors.black.withValues(alpha: 0.05),
+ Colors.black.withValues(alpha: 0.55),
+ ],
+ ),
+ ),
+ ),
+ Positioned(
+ left: 16,
+ right: 16,
+ bottom: 16,
+ child: Row(
+ children: [
+ Expanded(
+ child: Column(
+ crossAxisAlignment: CrossAxisAlignment.start,
+ mainAxisSize: MainAxisSize.min,
+ children: [
+ Text(
+ _selectedImageName ?? '已选择图片',
+ maxLines: 1,
+ overflow: TextOverflow.ellipsis,
+ style: textTheme.titleMedium?.copyWith(
+ color: Colors.white,
+ fontWeight: FontWeight.w600,
+ ),
+ ),
+ const SizedBox(height: 4),
+ Text(
+ '点击可重新选择图片',
+ style: textTheme.bodySmall?.copyWith(
+ color: Colors.white.withValues(alpha: 0.78),
+ ),
+ ),
+ ],
+ ),
+ ),
+ IconButton.filledTonal(
+ onPressed: _pickImageFile,
+ icon: const Icon(Icons.edit_outlined),
+ tooltip: '重新选择',
+ ),
+ ],
+ ),
+ ),
+ ],
+ ),
+ ),
+ );
+ }
+
+ Widget _buildUrlInput(ColorScheme colorScheme, TextTheme textTheme) {
+ return Column(
+ key: const ValueKey('url-input'),
+ crossAxisAlignment: CrossAxisAlignment.start,
+ spacing: 12,
+ children: [
+ TextField(
+ controller: _urlController,
+ decoration: InputDecoration(
+ hintText: '请输入图片链接',
+ hintStyle: TextStyle(
+ color: colorScheme.onSurfaceVariant.withValues(alpha: 0.6),
+ fontSize: 13,
+ ),
+ prefixIcon: const Icon(Icons.link),
+ suffixIcon: IconButton(
+ icon: const Icon(Icons.clear),
+ onPressed: _urlController.clear,
+ tooltip: '清除',
+ ),
+ filled: true,
+ fillColor:
+ colorScheme.surfaceContainerHighest.withValues(alpha: 0.5),
+ border: OutlineInputBorder(
+ borderRadius: BorderRadius.circular(12),
+ borderSide: BorderSide.none,
+ ),
+ focusedBorder: OutlineInputBorder(
+ borderRadius: BorderRadius.circular(12),
+ borderSide: BorderSide(color: colorScheme.primary, width: 1.5),
+ ),
+ contentPadding:
+ const EdgeInsets.symmetric(horizontal: 16, vertical: 16),
+ ),
+ keyboardType: TextInputType.url,
+ textInputAction: TextInputAction.search,
+ onSubmitted: (_) => _startSearch(),
+ ),
+ _buildUrlPreview(colorScheme, textTheme),
+ ],
+ );
+ }
+
+ Widget _buildUrlPreview(ColorScheme colorScheme, TextTheme textTheme) {
+ return AnimatedContainer(
+ duration: const Duration(milliseconds: 250),
+ width: double.infinity,
+ constraints: BoxConstraints(
+ minHeight: 170,
+ maxHeight: _previewUrl.isNotEmpty ? 300 : 170,
+ ),
+ decoration: BoxDecoration(
+ color: colorScheme.surfaceContainerHighest.withValues(alpha: 0.3),
+ borderRadius: BorderRadius.circular(16),
+ border: Border.all(
+ color: colorScheme.outline.withValues(alpha: 0.4),
+ width: 1.5,
+ strokeAlign: BorderSide.strokeAlignOutside,
+ ),
+ ),
+ clipBehavior: Clip.antiAlias,
+ child: _previewUrl.isEmpty
+ ? Center(
+ child: Column(
+ mainAxisAlignment: MainAxisAlignment.center,
+ children: [
+ Icon(
+ Icons.image_outlined,
+ size: 36,
+ color: colorScheme.onSurfaceVariant.withValues(alpha: 0.4),
+ ),
+ const SizedBox(height: 8),
+ Text(
+ '输入图片链接后预览',
+ style: textTheme.bodySmall?.copyWith(
+ color:
+ colorScheme.onSurfaceVariant.withValues(alpha: 0.4),
+ ),
+ ),
+ ],
+ ),
+ )
+ : Image.network(
+ _previewUrl,
+ fit: BoxFit.contain,
+ loadingBuilder: (context, child, loadingProgress) {
+ if (loadingProgress == null) {
+ return child;
+ }
+ final total = loadingProgress.expectedTotalBytes;
+ final loaded = loadingProgress.cumulativeBytesLoaded;
+ return Center(
+ child: Column(
+ mainAxisAlignment: MainAxisAlignment.center,
+ children: [
+ CircularProgressIndicator(
+ value: total != null ? loaded / total : null,
+ strokeWidth: 2.5,
+ ),
+ const SizedBox(height: 12),
+ Text(
+ '加载中...',
+ style: textTheme.bodySmall?.copyWith(
+ color: colorScheme.onSurfaceVariant,
+ ),
+ ),
+ ],
+ ),
+ );
+ },
+ errorBuilder: (context, error, stackTrace) => Center(
+ child: Column(
+ mainAxisAlignment: MainAxisAlignment.center,
+ children: [
+ Icon(
+ Icons.broken_image_outlined,
+ size: 36,
+ color: colorScheme.error.withValues(alpha: 0.7),
+ ),
+ const SizedBox(height: 8),
+ Text(
+ '图片加载失败',
+ style: textTheme.bodySmall?.copyWith(
+ color: colorScheme.error,
+ ),
+ ),
+ const SizedBox(height: 4),
+ Text(
+ '请检查链接是否有效',
+ style: textTheme.bodySmall?.copyWith(
+ color: colorScheme.onSurfaceVariant,
+ ),
+ ),
+ ],
+ ),
+ ),
+ ),
+ );
+ }
+
+ Widget _buildResultSection(ColorScheme colorScheme, TextTheme textTheme) {
+ return Observer(
+ builder: (context) {
+ final results = _searchPageController.imageSearchResults;
+ final errorMessage = _searchPageController.imageSearchError;
+
+ if (_searchPageController.isImageSearching) {
+ return _buildStateCard(
+ colorScheme: colorScheme,
+ textTheme: textTheme,
+ icon: const SizedBox(
+ width: 28,
+ height: 28,
+ child: CircularProgressIndicator(strokeWidth: 2.4),
+ ),
+ title: '正在识别图片',
+ description: '请稍候,正在从截图中匹配番剧信息',
+ );
+ }
+
+ if (results.isEmpty) {
+ return _buildStateCard(
+ colorScheme: colorScheme,
+ textTheme: textTheme,
+ icon: Icon(
+ errorMessage.isEmpty
+ ? Icons.grid_view_rounded
+ : Icons.error_outline,
+ size: 30,
+ color: errorMessage.isEmpty
+ ? colorScheme.primary
+ : colorScheme.error,
+ ),
+ title: errorMessage.isEmpty ? '搜索结果将在这里展示' : '未获取到搜索结果',
+ description:
+ errorMessage.isEmpty ? '选择图片文件或输入图片链接后开始搜索' : errorMessage,
+ );
+ }
+
+ return Column(
+ crossAxisAlignment: CrossAxisAlignment.start,
+ children: [
+ Text(
+ '识别结果',
+ style: textTheme.titleLarge?.copyWith(
+ fontWeight: FontWeight.w700,
+ ),
+ ),
+ const SizedBox(height: 16),
+ LayoutBuilder(
+ builder: (context, constraints) {
+ final crossAxisCount = _resolveCrossAxisCount(
+ constraints.maxWidth,
+ );
+ return GridView.builder(
+ shrinkWrap: true,
+ physics: const NeverScrollableScrollPhysics(),
+ itemCount: results.length,
+ gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
+ crossAxisCount: crossAxisCount,
+ crossAxisSpacing: 16,
+ mainAxisSpacing: 16,
+ mainAxisExtent: 152,
+ ),
+ itemBuilder: (context, index) {
+ final result = results[index];
+ return InkWell(
+ onTap: () {
+ final title = _formatTraceResultTitle(result);
+ Navigator.of(context).pop(title);
+ },
+ child: _buildResultCard(
+ context,
+ colorScheme,
+ textTheme,
+ result,
+ ),
+ );
+ },
+ );
+ },
+ ),
+ ],
+ );
+ },
+ );
+ }
+
+ Widget _buildStateCard({
+ required ColorScheme colorScheme,
+ required TextTheme textTheme,
+ required Widget icon,
+ required String title,
+ required String description,
+ }) {
+ return Container(
+ width: double.infinity,
+ padding: const EdgeInsets.all(24),
+ decoration: BoxDecoration(
+ color: colorScheme.surfaceContainerHighest.withValues(alpha: 0.35),
+ borderRadius: BorderRadius.circular(18),
+ ),
+ child: Column(
+ children: [
+ icon,
+ const SizedBox(height: 14),
+ Text(
+ title,
+ style: textTheme.titleMedium?.copyWith(
+ fontWeight: FontWeight.w700,
+ ),
+ ),
+ const SizedBox(height: 8),
+ Text(
+ description,
+ textAlign: TextAlign.center,
+ style: textTheme.bodyMedium?.copyWith(
+ color: colorScheme.onSurfaceVariant,
+ height: 1.5,
+ ),
+ ),
+ ],
+ ),
+ );
+ }
+
+ Widget _buildResultCard(
+ BuildContext context,
+ ColorScheme colorScheme,
+ TextTheme textTheme,
+ ResultItem result,
+ ) {
+ final coverUrl = result.image ??
+ result.anilist?.coverImage?.large ??
+ result.anilist?.coverImage?.medium;
+
+ return Container(
+ padding: const EdgeInsets.symmetric(horizontal: 14, vertical: 12),
+ decoration: BoxDecoration(
+ color: colorScheme.surfaceContainerHighest.withValues(alpha: 0.3),
+ borderRadius: BorderRadius.circular(16),
+ border: Border.all(
+ color: colorScheme.outline.withValues(alpha: 0.16),
+ ),
+ ),
+ child: Column(
+ crossAxisAlignment: CrossAxisAlignment.start,
+ children: [
+ Text(
+ _formatTraceResultTitle(result),
+ maxLines: 1,
+ overflow: TextOverflow.ellipsis,
+ style: textTheme.titleMedium?.copyWith(
+ fontWeight: FontWeight.w700,
+ ),
+ ),
+ const SizedBox(height: 10),
+ Expanded(
+ child: Row(
+ crossAxisAlignment: CrossAxisAlignment.start,
+ spacing: 5,
+ children: [
+ SizedBox(
+ child: AspectRatio(
+ aspectRatio: 16 / 9,
+ child: NetworkImgLayer(
+ src: coverUrl,
+ width: 132,
+ height: 74.25,
+ ),
+ ),
+ ),
+ Expanded(
+ child: Column(
+ mainAxisAlignment: MainAxisAlignment.center,
+ crossAxisAlignment: CrossAxisAlignment.start,
+ children: [
+ _buildInfoLine(
+ textTheme,
+ colorScheme,
+ _formatTraceEpisode(result.episode),
+ ),
+ _buildInfoLine(
+ textTheme,
+ colorScheme,
+ '相似度: ${Utils.formatTraceSimilarity(result.similarity)}',
+ ),
+ _buildInfoLine(
+ textTheme,
+ colorScheme,
+ '时间: ${Utils.durationToString(Duration(seconds: (result.from ?? 0).floor()))} - ${Utils.durationToString(Duration(seconds: (result.to ?? 0).floor()))}',
+ ),
+ ],
+ ),
+ ),
+ ],
+ ),
+ ),
+ ],
+ ),
+ );
+ }
+
+ Widget _buildInfoLine(
+ TextTheme textTheme,
+ ColorScheme colorScheme,
+ String value,
+ ) {
+ return Text(
+ value,
+ maxLines: 1,
+ overflow: TextOverflow.ellipsis,
+ style: textTheme.bodyMedium?.copyWith(
+ color: colorScheme.onSurfaceVariant,
+ fontWeight: FontWeight.w600,
+ ),
+ );
+ }
+
+
+ Widget _buildTips(ColorScheme colorScheme, TextTheme textTheme) {
+ final baseStyle = textTheme.bodySmall?.copyWith(
+ color: colorScheme.onSurfaceVariant,
+ height: 1.5,
+ );
+ final linkStyle = baseStyle?.copyWith(
+ color: colorScheme.primary,
+ decoration: TextDecoration.underline,
+ decorationColor: colorScheme.primary,
+ );
+ final dotColor = colorScheme.onSurfaceVariant.withValues(alpha: 0.6);
+
+ final tips = <Widget>[
+ Text('仅支持使用原始比例番剧截图搜索结果', style: baseStyle),
+ Text('截图应清晰,避免过度压缩或添加水印', style: baseStyle),
+ RichText(
+ text: TextSpan(
+ style: baseStyle,
+ children: [
+ const TextSpan(text: '搜索引擎由 '),
+ WidgetSpan(
+ alignment: PlaceholderAlignment.baseline,
+ baseline: TextBaseline.alphabetic,
+ child: GestureDetector(
+ onTap: () => launchUrl(
+ Uri.parse('https://trace.moe'),
+ mode: LaunchMode.externalApplication,
+ ),
+ child: Text('trace.moe', style: linkStyle),
+ ),
+ ),
+ const TextSpan(text: ' 提供支持'),
+ ],
+ ),
+ ),
+ ];
+
+ return Column(
+ crossAxisAlignment: CrossAxisAlignment.start,
+ children: [
+ Row(
+ children: [
+ Icon(
+ Icons.info_outline,
+ size: 16,
+ color: colorScheme.onSurfaceVariant,
+ ),
+ const SizedBox(width: 6),
+ Text(
+ '以图搜番',
+ style: textTheme.labelLarge?.copyWith(
+ color: colorScheme.onSurfaceVariant,
+ fontWeight: FontWeight.w600,
+ ),
+ ),
+ ],
+ ),
+ const SizedBox(height: 10),
+ ...tips.map(
+ (tipWidget) => Padding(
+ padding: const EdgeInsets.only(bottom: 6),
+ child: Row(
+ crossAxisAlignment: CrossAxisAlignment.start,
+ children: [
+ Padding(
+ padding: const EdgeInsets.only(top: 5),
+ child: Container(
+ width: 4,
+ height: 4,
+ decoration: BoxDecoration(
+ color: dotColor,
+ shape: BoxShape.circle,
+ ),
+ ),
+ ),
+ const SizedBox(width: 8),
+ Expanded(child: tipWidget),
+ ],
+ ),
+ ),
+ ),
+ ],
+ );
+ }
+}
diff --git a/lib/pages/search/search_controller.dart b/lib/pages/search/search_controller.dart
index 5400db8e..cb9552cc 100644
--- a/lib/pages/search/search_controller.dart
+++ b/lib/pages/search/search_controller.dart
@@ -1,12 +1,16 @@
+import 'dart:io';
+
import 'package:flutter_modular/flutter_modular.dart';
import 'package:mobx/mobx.dart';
import 'package:kazumi/modules/bangumi/bangumi_item.dart';
-import 'package:kazumi/request/bangumi.dart';
-import 'package:kazumi/utils/search_parser.dart';
+import 'package:kazumi/modules/collect/collect_type.dart';
+import 'package:kazumi/modules/search/image_search_module.dart';
import 'package:kazumi/modules/search/search_history_module.dart';
import 'package:kazumi/repositories/collect_repository.dart';
import 'package:kazumi/repositories/search_history_repository.dart';
-import 'package:kazumi/modules/collect/collect_type.dart';
+import 'package:kazumi/request/bangumi.dart';
+import 'package:kazumi/request/trace.dart';
+import 'package:kazumi/utils/search_parser.dart';
part 'search_controller.g.dart';
@@ -34,6 +38,15 @@ abstract class _SearchPageController with Store {
@observable
ObservableList<SearchHistory> searchHistories = ObservableList.of([]);
+ @observable
+ bool isImageSearching = false;
+
+ @observable
+ String imageSearchError = '';
+
+ @observable
+ ObservableList<ResultItem> imageSearchResults = ObservableList.of([]);
+
@action
void loadSearchHistories() {
final histories = _searchHistoryRepository.getAllHistories();
@@ -108,6 +121,53 @@ abstract class _SearchPageController with Store {
loadSearchHistories();
}
+ @action
+ void clearImageSearchState() {
+ isImageSearching = false;
+ imageSearchError = '';
+ imageSearchResults.clear();
+ }
+
+ @action
+ Future<void> searchImageByFile(File imageFile) async {
+ isImageSearching = true;
+ imageSearchError = '';
+ imageSearchResults.clear();
+ try {
+ final result = await Trace.searchAnimeByImageFile(imageFile);
+ imageSearchResults.addAll(result.result ?? []);
+ if (result.error != null && result.error!.isNotEmpty) {
+ imageSearchError = result.error!;
+ } else if (imageSearchResults.isEmpty) {
+ imageSearchError = '未找到匹配结果';
+ }
+ } catch (e) {
+ imageSearchError = '图片搜索失败,请稍后重试';
+ } finally {
+ isImageSearching = false;
+ }
+ }
+
+ @action
+ Future<void> searchImageByUrl(String imageUrl) async {
+ isImageSearching = true;
+ imageSearchError = '';
+ imageSearchResults.clear();
+ try {
+ final result = await Trace.searchAnimeByImageUrl(imageUrl);
+ imageSearchResults.addAll(result.result ?? []);
+ if (result.error != null && result.error!.isNotEmpty) {
+ imageSearchError = result.error!;
+ } else if (imageSearchResults.isEmpty) {
+ imageSearchError = '未找到匹配结果';
+ }
+ } catch (e) {
+ imageSearchError = '图片搜索失败,请检查图片地址或稍后重试';
+ } finally {
+ isImageSearching = false;
+ }
+ }
+
@action
Future<void> setNotShowWatchedBangumis(bool value) async {
notShowWatchedBangumis = value;
diff --git a/lib/pages/search/search_controller.g.dart b/lib/pages/search/search_controller.g.dart
index a5043434..3ec762e8 100644
--- a/lib/pages/search/search_controller.g.dart
+++ b/lib/pages/search/search_controller.g.dart
@@ -119,6 +119,54 @@ mixin _$SearchPageController on _SearchPageController, Store {
});
}
+ late final _$isImageSearchingAtom =
+ Atom(name: '_SearchPageController.isImageSearching', context: context);
+
+ @override
+ bool get isImageSearching {
+ _$isImageSearchingAtom.reportRead();
+ return super.isImageSearching;
+ }
+
+ @override
+ set isImageSearching(bool value) {
+ _$isImageSearchingAtom.reportWrite(value, super.isImageSearching, () {
+ super.isImageSearching = value;
+ });
+ }
+
+ late final _$imageSearchErrorAtom =
+ Atom(name: '_SearchPageController.imageSearchError', context: context);
+
+ @override
+ String get imageSearchError {
+ _$imageSearchErrorAtom.reportRead();
+ return super.imageSearchError;
+ }
+
+ @override
+ set imageSearchError(String value) {
+ _$imageSearchErrorAtom.reportWrite(value, super.imageSearchError, () {
+ super.imageSearchError = value;
+ });
+ }
+
+ late final _$imageSearchResultsAtom =
+ Atom(name: '_SearchPageController.imageSearchResults', context: context);
+
+ @override
+ ObservableList<ResultItem> get imageSearchResults {
+ _$imageSearchResultsAtom.reportRead();
+ return super.imageSearchResults;
+ }
+
+ @override
+ set imageSearchResults(ObservableList<ResultItem> value) {
+ _$imageSearchResultsAtom.reportWrite(value, super.imageSearchResults, () {
+ super.imageSearchResults = value;
+ });
+ }
+
late final _$searchBangumiAsyncAction =
AsyncAction('_SearchPageController.searchBangumi', context: context);
@@ -147,6 +195,24 @@ mixin _$SearchPageController on _SearchPageController, Store {
.run(() => super.clearSearchHistory());
}
+ late final _$searchImageByFileAsyncAction =
+ AsyncAction('_SearchPageController.searchImageByFile', context: context);
+
+ @override
+ Future<void> searchImageByFile(File imageFile) {
+ return _$searchImageByFileAsyncAction
+ .run(() => super.searchImageByFile(imageFile));
+ }
+
+ late final _$searchImageByUrlAsyncAction =
+ AsyncAction('_SearchPageController.searchImageByUrl', context: context);
+
+ @override
+ Future<void> searchImageByUrl(String imageUrl) {
+ return _$searchImageByUrlAsyncAction
+ .run(() => super.searchImageByUrl(imageUrl));
+ }
+
late final _$setNotShowWatchedBangumisAsyncAction = AsyncAction(
'_SearchPageController.setNotShowWatchedBangumis',
context: context);
@@ -181,6 +247,17 @@ mixin _$SearchPageController on _SearchPageController, Store {
}
}
+ @override
+ void clearImageSearchState() {
+ final _$actionInfo = _$_SearchPageControllerActionController.startAction(
+ name: '_SearchPageController.clearImageSearchState');
+ try {
+ return super.clearImageSearchState();
+ } finally {
+ _$_SearchPageControllerActionController.endAction(_$actionInfo);
+ }
+ }
+
@override
String toString() {
return '''
@@ -189,7 +266,10 @@ isTimeOut: ${isTimeOut},
notShowWatchedBangumis: ${notShowWatchedBangumis},
notShowAbandonedBangumis: ${notShowAbandonedBangumis},
bangumiList: ${bangumiList},
-searchHistories: ${searchHistories}
+searchHistories: ${searchHistories},
+isImageSearching: ${isImageSearching},
+imageSearchError: ${imageSearchError},
+imageSearchResults: ${imageSearchResults}
''';
}
}
diff --git a/lib/pages/search/search_module.dart b/lib/pages/search/search_module.dart
index e73f1469..b6fd3ce7 100644
--- a/lib/pages/search/search_module.dart
+++ b/lib/pages/search/search_module.dart
@@ -1,5 +1,6 @@
import 'package:flutter_modular/flutter_modular.dart';
import 'package:kazumi/pages/search/search_page.dart';
+import 'package:kazumi/pages/search/image_search_page.dart';
class SearchModule extends Module {
@override
@@ -7,6 +8,7 @@ class SearchModule extends Module {
@override
void routes(r) {
+ r.child("/image", child: (_) => const ImageSearchPage());
r.child("/:tag", child: (_) {
return SearchPage(inputTag: r.args.params['tag']);
});
diff --git a/lib/pages/search/search_page.dart b/lib/pages/search/search_page.dart
index 73cb1303..cf9957ac 100644
--- a/lib/pages/search/search_page.dart
+++ b/lib/pages/search/search_page.dart
@@ -7,6 +7,7 @@ import 'package:kazumi/pages/search/search_controller.dart';
import 'package:kazumi/bean/appbar/sys_app_bar.dart';
import 'package:kazumi/modules/bangumi/bangumi_item.dart';
import 'package:kazumi/utils/logger.dart';
+import 'package:flutter_modular/flutter_modular.dart';
class SearchPage extends StatefulWidget {
const SearchPage({super.key, this.inputTag = ''});
@@ -218,6 +219,20 @@ class _SearchPageState extends State<SearchPage> {
},
icon: Icon(Icons.arrow_back),
),
+ barTrailing: [
+ IconButton(
+ onPressed: () async {
+ final result =
+ await Modular.to.pushNamed('/search/image');
+ if (result is String && result.isNotEmpty) {
+ searchController.text = result;
+ searchPageController.searchBangumi(result,
+ type: 'init');
+ }
+ },
+ icon: const Icon(Icons.image_search_rounded),
+ ),
+ ],
isFullScreen: MediaQuery.sizeOf(context).width <
LayoutBreakpoint.compact['width']!,
suggestionsBuilder: (context, controller) => [
@@ -293,7 +308,6 @@ class _SearchPageState extends State<SearchPage> {
);
}
-
if (searchPageController.isLoading &&
searchPageController.bangumiList.isEmpty) {
return Center(child: CircularProgressIndicator());
@@ -307,17 +321,20 @@ class _SearchPageState extends State<SearchPage> {
LayoutBreakpoint.medium['width']!) {
crossCount = 6;
}
- List<BangumiItem> filteredList = searchPageController.bangumiList.toList();
+ List<BangumiItem> filteredList =
+ searchPageController.bangumiList.toList();
if (searchPageController.notShowWatchedBangumis) {
- final watchedBangumiIds = searchPageController.loadWatchedBangumiIds();
+ final watchedBangumiIds =
+ searchPageController.loadWatchedBangumiIds();
filteredList = filteredList
.where((item) => !watchedBangumiIds.contains(item.id))
.toList();
}
if (searchPageController.notShowAbandonedBangumis) {
- final abandonedBangumiIds = searchPageController.loadAbandonedBangumiIds();
+ final abandonedBangumiIds =
+ searchPageController.loadAbandonedBangumiIds();
filteredList = filteredList
.where((item) => !abandonedBangumiIds.contains(item.id))
.toList();
diff --git a/lib/request/api.dart b/lib/request/api.dart
index 36cbe01a..cc541d07 100644
--- a/lib/request/api.dart
+++ b/lib/request/api.dart
@@ -62,6 +62,9 @@ class Api {
/// 获取弹弹番剧元数据(通过BGM番剧ID)
static const String dandanAPIInfoByBgmBangumiId = "/api/v2/bangumi/bgmtv/{0}";
+ /// 图片识别番剧
+ static const String traceApi = 'https://api.trace.moe/search';
+
static String formatUrl(String url, List<dynamic> params) {
for (int i = 0; i < params.length; i++) {
url = url.replaceAll('{$i}', params[i].toString());
diff --git a/lib/request/trace.dart b/lib/request/trace.dart
new file mode 100644
index 00000000..f9d767dd
--- /dev/null
+++ b/lib/request/trace.dart
@@ -0,0 +1,38 @@
+import 'dart:io';
+
+import 'package:dio/dio.dart';
+import 'package:kazumi/modules/search/image_search_module.dart';
+import 'package:kazumi/request/api.dart';
+
+import 'request.dart';
+
+class Trace {
+ ///根据图片搜索番剧信息
+ static Future<ImageSearchItem> searchAnimeByImageFile(File imageFile,
+ {int anilistInfo = 2}) async {
+ final bytes = await imageFile.readAsBytes();
+
+ return await Request()
+ .post(Api.traceApi,
+ queryParameters: {
+ 'anilistInfo': anilistInfo,
+ },
+ data: bytes,
+ options: Options(headers: {'Content-Type': 'image/jpeg'}))
+ .then((onValue) =>
+ ImageSearchItem.fromJson(onValue.data as Map<String, dynamic>));
+ }
+
+ ///根据图片URL搜索番剧信息
+ static Future<ImageSearchItem> searchAnimeByImageUrl(String imageUrl,
+ {int anilistInfo = 2}) async {
+ return await Request()
+ .post(Api.traceApi,
+ queryParameters: {
+ 'anilistInfo': anilistInfo,
+ 'url': imageUrl,
+ })
+ .then((onValue) =>
+ ImageSearchItem.fromJson(onValue.data as Map<String, dynamic>));
+ }
+}
diff --git a/lib/utils/utils.dart b/lib/utils/utils.dart
index 1fdd4773..4b09ed3b 100644
--- a/lib/utils/utils.dart
+++ b/lib/utils/utils.dart
@@ -266,6 +266,16 @@ class Utils {
}
}
+ /// 格式化相似度为百分比字符串,默认为1位小数,空值时返回 `--`
+ static String formatTraceSimilarity(double? similarity,
+ {int fractionDigits = 1, String empty = '--'}) {
+ if (similarity == null) {
+ return empty;
+ }
+ return '${(similarity * 100).toStringAsFixed(fractionDigits)}%';
+ }
+
+
static Future<String> latest() async {
try {
var resp = await Dio().get<Map<String, dynamic>>(Api.latestApp);
diff --git a/linux/flutter/generated_plugin_registrant.cc b/linux/flutter/generated_plugin_registrant.cc
index 43268c18..847c7993 100644
--- a/linux/flutter/generated_plugin_registrant.cc
+++ b/linux/flutter/generated_plugin_registrant.cc
@@ -8,6 +8,7 @@
#include <desktop_webview_window/desktop_webview_window_plugin.h>
#include <dynamic_color/dynamic_color_plugin.h>
+#include <file_selector_linux/file_selector_plugin.h>
#include <flutter_volume_controller/flutter_volume_controller_plugin.h>
#include <media_kit_libs_linux/media_kit_libs_linux_plugin.h>
#include <media_kit_video/media_kit_video_plugin.h>
@@ -23,6 +24,9 @@ void fl_register_plugins(FlPluginRegistry* registry) {
g_autoptr(FlPluginRegistrar) dynamic_color_registrar =
fl_plugin_registry_get_registrar_for_plugin(registry, "DynamicColorPlugin");
dynamic_color_plugin_register_with_registrar(dynamic_color_registrar);
+ g_autoptr(FlPluginRegistrar) file_selector_linux_registrar =
+ fl_plugin_registry_get_registrar_for_plugin(registry, "FileSelectorPlugin");
+ file_selector_plugin_register_with_registrar(file_selector_linux_registrar);
g_autoptr(FlPluginRegistrar) flutter_volume_controller_registrar =
fl_plugin_registry_get_registrar_for_plugin(registry, "FlutterVolumeControllerPlugin");
flutter_volume_controller_plugin_register_with_registrar(flutter_volume_controller_registrar);
diff --git a/linux/flutter/generated_plugins.cmake b/linux/flutter/generated_plugins.cmake
index 74766b5b..87b90ed4 100644
--- a/linux/flutter/generated_plugins.cmake
+++ b/linux/flutter/generated_plugins.cmake
@@ -5,6 +5,7 @@
list(APPEND FLUTTER_PLUGIN_LIST
desktop_webview_window
dynamic_color
+ file_selector_linux
flutter_volume_controller
media_kit_libs_linux
media_kit_video
@@ -15,6 +16,7 @@ list(APPEND FLUTTER_PLUGIN_LIST
)
list(APPEND FLUTTER_FFI_PLUGIN_LIST
+ jni
)
set(PLUGIN_BUNDLED_LIBRARIES)
diff --git a/macos/Flutter/GeneratedPluginRegistrant.swift b/macos/Flutter/GeneratedPluginRegistrant.swift
index f155e34d..74657048 100644
--- a/macos/Flutter/GeneratedPluginRegistrant.swift
+++ b/macos/Flutter/GeneratedPluginRegistrant.swift
@@ -9,6 +9,7 @@ import audio_service
import audio_session
import connectivity_plus
import dynamic_color
+import file_selector_macos
import flutter_inappwebview_macos
import flutter_volume_controller
import media_kit_libs_macos_video
@@ -27,6 +28,7 @@ func RegisterGeneratedPlugins(registry: FlutterPluginRegistry) {
AudioSessionPlugin.register(with: registry.registrar(forPlugin: "AudioSessionPlugin"))
ConnectivityPlusPlugin.register(with: registry.registrar(forPlugin: "ConnectivityPlusPlugin"))
DynamicColorPlugin.register(with: registry.registrar(forPlugin: "DynamicColorPlugin"))
+ FileSelectorPlugin.register(with: registry.registrar(forPlugin: "FileSelectorPlugin"))
InAppWebViewFlutterPlugin.register(with: registry.registrar(forPlugin: "InAppWebViewFlutterPlugin"))
FlutterVolumeControllerPlugin.register(with: registry.registrar(forPlugin: "FlutterVolumeControllerPlugin"))
MediaKitLibsMacosVideoPlugin.register(with: registry.registrar(forPlugin: "MediaKitLibsMacosVideoPlugin"))
diff --git a/pubspec.yaml b/pubspec.yaml
index abb92eee..111592b0 100644
--- a/pubspec.yaml
+++ b/pubspec.yaml
@@ -100,6 +100,7 @@ dependencies:
material_color_utilities: any
path: any
photo_view: ^0.15.0
+ image_picker: ^1.2.1
webview_windows:
git:
url: https://github.com/Predidit/flutter-webview-windows.git
diff --git a/windows/flutter/generated_plugin_registrant.cc b/windows/flutter/generated_plugin_registrant.cc
index 0815a0c1..48020b00 100644
--- a/windows/flutter/generated_plugin_registrant.cc
+++ b/windows/flutter/generated_plugin_registrant.cc
@@ -9,6 +9,7 @@
#include <audio_service_win/audio_service_win_plugin_c_api.h>
#include <connectivity_plus/connectivity_plus_windows_plugin.h>
#include <dynamic_color/dynamic_color_plugin_c_api.h>
+#include <file_selector_windows/file_selector_windows.h>
#include <flutter_volume_controller/flutter_volume_controller_plugin_c_api.h>
#include <media_kit_libs_windows_video/media_kit_libs_windows_video_plugin_c_api.h>
#include <media_kit_video/media_kit_video_plugin_c_api.h>
@@ -25,6 +26,8 @@ void RegisterPlugins(flutter::PluginRegistry* registry) {
registry->GetRegistrarForPlugin("ConnectivityPlusWindowsPlugin"));
DynamicColorPluginCApiRegisterWithRegistrar(
registry->GetRegistrarForPlugin("DynamicColorPluginCApi"));
+ FileSelectorWindowsRegisterWithRegistrar(
+ registry->GetRegistrarForPlugin("FileSelectorWindows"));
FlutterVolumeControllerPluginCApiRegisterWithRegistrar(
registry->GetRegistrarForPlugin("FlutterVolumeControllerPluginCApi"));
MediaKitLibsWindowsVideoPluginCApiRegisterWithRegistrar(
diff --git a/windows/flutter/generated_plugins.cmake b/windows/flutter/generated_plugins.cmake
index ae6eff72..8ae9fbbe 100644
--- a/windows/flutter/generated_plugins.cmake
+++ b/windows/flutter/generated_plugins.cmake
@@ -6,6 +6,7 @@ list(APPEND FLUTTER_PLUGIN_LIST
audio_service_win
connectivity_plus
dynamic_color
+ file_selector_windows
flutter_volume_controller
media_kit_libs_windows_video
media_kit_video
@@ -17,6 +18,7 @@ list(APPEND FLUTTER_PLUGIN_LIST
)
list(APPEND FLUTTER_FFI_PLUGIN_LIST
+ jni
)
set(PLUGIN_BUNDLED_LIBRARIES)