commit
9c5fef1a4d
412 files changed
+94582
No files matched your search
@@ -0,0 +1,11 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_riverpod/flutter_riverpod.dart';
|
||||
|
||||
import 'src/app.dart';
|
||||
import 'src/core/push_notifications.dart';
|
||||
|
||||
Future<void> main() async {
|
||||
WidgetsFlutterBinding.ensureInitialized();
|
||||
await PushNotifications.initialize();
|
||||
runApp(const ProviderScope(child: SakuraMobileApp()));
|
||||
}
|
||||
@@ -0,0 +1,117 @@
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
import 'core/push_notifications.dart';
|
||||
import 'pages/home_page.dart';
|
||||
|
||||
class SakuraScrollBehavior extends MaterialScrollBehavior {
|
||||
const SakuraScrollBehavior();
|
||||
|
||||
@override
|
||||
Widget buildOverscrollIndicator(
|
||||
BuildContext context,
|
||||
Widget child,
|
||||
ScrollableDetails details,
|
||||
) {
|
||||
return child;
|
||||
}
|
||||
|
||||
@override
|
||||
ScrollPhysics getScrollPhysics(BuildContext context) {
|
||||
return const ClampingScrollPhysics();
|
||||
}
|
||||
}
|
||||
|
||||
class SakuraMobileApp extends StatelessWidget {
|
||||
const SakuraMobileApp({super.key});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final colorScheme = ColorScheme.fromSeed(
|
||||
seedColor: const Color(0xFFE98AA6),
|
||||
primary: const Color(0xFFD95A83),
|
||||
secondary: const Color(0xFFF3A6B8),
|
||||
surface: const Color(0xFFFFFBFD),
|
||||
);
|
||||
return MaterialApp(
|
||||
navigatorKey: PushNotifications.navigatorKey,
|
||||
scrollBehavior: const SakuraScrollBehavior(),
|
||||
title: '樱云同步',
|
||||
debugShowCheckedModeBanner: false,
|
||||
theme: ThemeData(
|
||||
colorScheme: colorScheme,
|
||||
useMaterial3: true,
|
||||
fontFamily: 'Microsoft YaHei UI',
|
||||
scaffoldBackgroundColor: const Color(0xFFFFF5F8),
|
||||
cardTheme: CardThemeData(
|
||||
color: Colors.white,
|
||||
elevation: 0,
|
||||
shape:
|
||||
RoundedRectangleBorder(borderRadius: BorderRadius.circular(24)),
|
||||
surfaceTintColor: Colors.white,
|
||||
),
|
||||
appBarTheme: const AppBarTheme(
|
||||
backgroundColor: Color(0xFFFFF5F8),
|
||||
surfaceTintColor: Colors.transparent,
|
||||
elevation: 0,
|
||||
),
|
||||
navigationBarTheme: NavigationBarThemeData(
|
||||
backgroundColor: Colors.white.withValues(alpha: 0.94),
|
||||
indicatorColor: const Color(0xFFFFDDE7),
|
||||
iconTheme: WidgetStateProperty.resolveWith((states) {
|
||||
final selected = states.contains(WidgetState.selected);
|
||||
return IconThemeData(
|
||||
color: selected
|
||||
? const Color(0xFFD95A83)
|
||||
: const Color(0xFF8A6A74));
|
||||
}),
|
||||
labelTextStyle: WidgetStateProperty.resolveWith((states) {
|
||||
final selected = states.contains(WidgetState.selected);
|
||||
return TextStyle(
|
||||
fontSize: 12,
|
||||
fontWeight: selected ? FontWeight.w800 : FontWeight.w600,
|
||||
color:
|
||||
selected ? const Color(0xFFD95A83) : const Color(0xFF8A6A74),
|
||||
);
|
||||
}),
|
||||
),
|
||||
inputDecorationTheme: InputDecorationTheme(
|
||||
filled: true,
|
||||
fillColor: Colors.white,
|
||||
contentPadding:
|
||||
const EdgeInsets.symmetric(horizontal: 16, vertical: 18),
|
||||
border: OutlineInputBorder(
|
||||
borderRadius: BorderRadius.circular(18),
|
||||
borderSide: const BorderSide(color: Color(0xFFF1CAD7)),
|
||||
),
|
||||
enabledBorder: OutlineInputBorder(
|
||||
borderRadius: BorderRadius.circular(18),
|
||||
borderSide: const BorderSide(color: Color(0xFFF1CAD7)),
|
||||
),
|
||||
focusedBorder: OutlineInputBorder(
|
||||
borderRadius: BorderRadius.circular(18),
|
||||
borderSide: const BorderSide(color: Color(0xFFD95A83), width: 1.4),
|
||||
),
|
||||
),
|
||||
filledButtonTheme: FilledButtonThemeData(
|
||||
style: FilledButton.styleFrom(
|
||||
minimumSize: const Size.fromHeight(54),
|
||||
shape:
|
||||
RoundedRectangleBorder(borderRadius: BorderRadius.circular(18)),
|
||||
backgroundColor: const Color(0xFFD95A83),
|
||||
foregroundColor: Colors.white,
|
||||
textStyle:
|
||||
const TextStyle(fontSize: 16, fontWeight: FontWeight.w700),
|
||||
),
|
||||
),
|
||||
outlinedButtonTheme: OutlinedButtonThemeData(
|
||||
style: OutlinedButton.styleFrom(
|
||||
shape:
|
||||
RoundedRectangleBorder(borderRadius: BorderRadius.circular(18)),
|
||||
side: const BorderSide(color: Color(0xFFF1CAD7)),
|
||||
),
|
||||
),
|
||||
),
|
||||
home: const HomePage(),
|
||||
);
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,131 @@
|
||||
import 'dart:convert';
|
||||
|
||||
import 'package:flutter_js/flutter_js.dart';
|
||||
|
||||
class LegadoJsRunner {
|
||||
static const timeout = Duration(seconds: 3);
|
||||
static const stackLimitBytes = 1024 * 1024;
|
||||
|
||||
String run({
|
||||
required String script,
|
||||
required String result,
|
||||
required String rawHtml,
|
||||
required String baseUrl,
|
||||
required Map<String, String> context,
|
||||
}) {
|
||||
final resultExpression = _resultExpression(script, result);
|
||||
final runtime = QuickJsRuntime2(
|
||||
timeout: timeout.inMilliseconds,
|
||||
stackSize: stackLimitBytes,
|
||||
);
|
||||
try {
|
||||
final bootstrap = '''
|
||||
var result = $resultExpression;
|
||||
var rawHtml = ${jsonEncode(rawHtml)};
|
||||
var baseUrl = ${jsonEncode(baseUrl)};
|
||||
var __context = ${jsonEncode(context)};
|
||||
var src = rawHtml;
|
||||
var key = __context.key || '';
|
||||
var page = Number(__context.page || 1);
|
||||
var source = Object.freeze({
|
||||
key: __context.sourceUrl || baseUrl,
|
||||
bookSourceUrl: __context.sourceUrl || baseUrl,
|
||||
bookSourceName: __context.sourceName || '',
|
||||
getKey: function() { return this.key; },
|
||||
getVariable: function() { return __context.sourceVariable || ''; }
|
||||
});
|
||||
function __decodeBase64(value) {
|
||||
var chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';
|
||||
var input = String(value || '').replace(new RegExp('[^A-Za-z0-9+/=]', 'g'), '');
|
||||
var output = '';
|
||||
for (var i = 0; i < input.length;) {
|
||||
var e1 = chars.indexOf(input.charAt(i++));
|
||||
var e2 = chars.indexOf(input.charAt(i++));
|
||||
var e3 = chars.indexOf(input.charAt(i++));
|
||||
var e4 = chars.indexOf(input.charAt(i++));
|
||||
output += String.fromCharCode((e1 << 2) | (e2 >> 4));
|
||||
if (e3 !== 64 && e3 !== -1) {
|
||||
output += String.fromCharCode(((e2 & 15) << 4) | (e3 >> 2));
|
||||
}
|
||||
if (e4 !== 64 && e4 !== -1) {
|
||||
output += String.fromCharCode(((e3 & 3) << 6) | e4);
|
||||
}
|
||||
}
|
||||
try { return decodeURIComponent(escape(output)); } catch (_) { return output; }
|
||||
}
|
||||
var java = Object.freeze({
|
||||
get: function(key) { return __context[String(key)] || ''; },
|
||||
put: function(key, value) {
|
||||
__context[String(key)] = value == null ? '' : String(value);
|
||||
return value;
|
||||
},
|
||||
base64Decode: function(value) {
|
||||
return __decodeBase64(value);
|
||||
},
|
||||
encodeURI: function(value) { return encodeURIComponent(String(value)); },
|
||||
ajax: function() {
|
||||
throw new Error('Network access is disabled in Legado JS rules');
|
||||
},
|
||||
getElements: function() {
|
||||
throw new Error('DOM bridge is unavailable in the secure sandbox');
|
||||
},
|
||||
log: function() {}
|
||||
});
|
||||
var fetch = undefined;
|
||||
var XMLHttpRequest = undefined;
|
||||
var WebSocket = undefined;
|
||||
var localStorage = undefined;
|
||||
''';
|
||||
final init = runtime.evaluate(bootstrap);
|
||||
if (init.isError) throw FormatException(init.stringResult);
|
||||
|
||||
final evaluated = runtime.evaluate(script, sourceUrl: 'legado-rule.js');
|
||||
if (evaluated.isError) throw FormatException(evaluated.stringResult);
|
||||
final contextResult = runtime.evaluate('JSON.stringify(__context)');
|
||||
if (!contextResult.isError) {
|
||||
try {
|
||||
final decoded = jsonDecode(contextResult.stringResult);
|
||||
if (decoded is Map) {
|
||||
for (final entry in decoded.entries) {
|
||||
context[entry.key.toString()] = entry.value?.toString() ?? '';
|
||||
}
|
||||
}
|
||||
} on FormatException {
|
||||
// A malformed context must not discard a successful rule result.
|
||||
}
|
||||
}
|
||||
return _normalizeResult(evaluated);
|
||||
} finally {
|
||||
runtime.dispose();
|
||||
}
|
||||
}
|
||||
|
||||
String _resultExpression(String script, String result) {
|
||||
final value = result.trim();
|
||||
final accessesObject =
|
||||
RegExp(r'\bresult\s*\.[A-Za-z_$]').hasMatch(script) &&
|
||||
!RegExp(r'JSON\s*\.\s*parse\s*\(\s*result\s*\)').hasMatch(script);
|
||||
if (accessesObject &&
|
||||
((value.startsWith('{') && value.endsWith('}')) ||
|
||||
(value.startsWith('[') && value.endsWith(']')))) {
|
||||
try {
|
||||
jsonDecode(value);
|
||||
return value;
|
||||
} on FormatException {
|
||||
// Fall back to a string when the fragment only resembles JSON.
|
||||
}
|
||||
}
|
||||
return jsonEncode(result);
|
||||
}
|
||||
|
||||
String _normalizeResult(JsEvalResult value) {
|
||||
final raw = value.rawResult;
|
||||
if (raw == null) return value.stringResult;
|
||||
if (raw is String) return raw;
|
||||
if (raw is Iterable) return raw.join('\n');
|
||||
if (raw is Map) return jsonEncode(raw);
|
||||
final text = value.stringResult;
|
||||
if (text == 'undefined' || text == 'null') return '';
|
||||
return text;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,631 @@
|
||||
import 'dart:convert';
|
||||
|
||||
import 'manga_image.dart';
|
||||
|
||||
class SourceRepo {
|
||||
const SourceRepo({
|
||||
required this.name,
|
||||
required this.url,
|
||||
required this.description,
|
||||
required this.category,
|
||||
this.expectedCount,
|
||||
this.isSubscription = false,
|
||||
});
|
||||
|
||||
final String name;
|
||||
final String url;
|
||||
final String description;
|
||||
final String category;
|
||||
final int? expectedCount;
|
||||
final bool isSubscription;
|
||||
}
|
||||
|
||||
class LegadoSource {
|
||||
const LegadoSource({
|
||||
required this.id,
|
||||
required this.name,
|
||||
required this.url,
|
||||
required this.type,
|
||||
required this.enabled,
|
||||
this.userAgent,
|
||||
this.headers = const <String, String>{},
|
||||
this.searchUrl,
|
||||
this.searchListRule,
|
||||
this.searchNameRule,
|
||||
this.searchAuthorRule,
|
||||
this.searchCoverRule,
|
||||
this.searchDetailRule,
|
||||
this.searchMethod,
|
||||
this.searchBody,
|
||||
this.ruleKind,
|
||||
this.charset,
|
||||
this.urlEncoding,
|
||||
this.bookInfoUrl,
|
||||
this.bookInfoNameRule,
|
||||
this.bookInfoAuthorRule,
|
||||
this.bookInfoCoverRule,
|
||||
this.bookInfoIntroRule,
|
||||
this.bookInfoTocRule,
|
||||
this.tocUrl,
|
||||
this.tocListRule,
|
||||
this.tocNameRule,
|
||||
this.tocUrlRule,
|
||||
this.tocNextPageRule,
|
||||
this.contentRule,
|
||||
this.contentNextRule,
|
||||
this.contentPrevRule,
|
||||
});
|
||||
|
||||
final String id;
|
||||
final String name;
|
||||
final String url;
|
||||
final int type;
|
||||
final bool enabled;
|
||||
final String? userAgent;
|
||||
final Map<String, String> headers;
|
||||
final String? searchUrl;
|
||||
final String? searchListRule;
|
||||
final String? searchNameRule;
|
||||
final String? searchAuthorRule;
|
||||
final String? searchCoverRule;
|
||||
final String? searchDetailRule;
|
||||
final String? searchMethod;
|
||||
final String? searchBody;
|
||||
final String? ruleKind;
|
||||
final String? charset;
|
||||
final String? urlEncoding;
|
||||
final String? bookInfoUrl;
|
||||
final String? bookInfoNameRule;
|
||||
final String? bookInfoAuthorRule;
|
||||
final String? bookInfoCoverRule;
|
||||
final String? bookInfoIntroRule;
|
||||
final String? bookInfoTocRule;
|
||||
final String? tocUrl;
|
||||
final String? tocListRule;
|
||||
final String? tocNameRule;
|
||||
final String? tocUrlRule;
|
||||
final String? tocNextPageRule;
|
||||
final String? contentRule;
|
||||
final String? contentNextRule;
|
||||
final String? contentPrevRule;
|
||||
|
||||
bool get isNovel => type == 0;
|
||||
bool get isManga => type == 2;
|
||||
|
||||
LegadoSource copyWith({bool? enabled}) {
|
||||
return LegadoSource(
|
||||
id: id,
|
||||
name: name,
|
||||
url: url,
|
||||
type: type,
|
||||
enabled: enabled ?? this.enabled,
|
||||
userAgent: userAgent,
|
||||
headers: headers,
|
||||
searchUrl: searchUrl,
|
||||
searchListRule: searchListRule,
|
||||
searchNameRule: searchNameRule,
|
||||
searchAuthorRule: searchAuthorRule,
|
||||
searchCoverRule: searchCoverRule,
|
||||
searchDetailRule: searchDetailRule,
|
||||
searchMethod: searchMethod,
|
||||
searchBody: searchBody,
|
||||
ruleKind: ruleKind,
|
||||
charset: charset,
|
||||
urlEncoding: urlEncoding,
|
||||
bookInfoUrl: bookInfoUrl,
|
||||
bookInfoNameRule: bookInfoNameRule,
|
||||
bookInfoAuthorRule: bookInfoAuthorRule,
|
||||
bookInfoCoverRule: bookInfoCoverRule,
|
||||
bookInfoIntroRule: bookInfoIntroRule,
|
||||
bookInfoTocRule: bookInfoTocRule,
|
||||
tocUrl: tocUrl,
|
||||
tocListRule: tocListRule,
|
||||
tocNameRule: tocNameRule,
|
||||
tocUrlRule: tocUrlRule,
|
||||
tocNextPageRule: tocNextPageRule,
|
||||
contentRule: contentRule,
|
||||
contentNextRule: contentNextRule,
|
||||
contentPrevRule: contentPrevRule,
|
||||
);
|
||||
}
|
||||
|
||||
factory LegadoSource.fromJson(Map<String, dynamic> json) {
|
||||
final name = _string(json['bookSourceName']) ??
|
||||
_string(json['sourceName']) ??
|
||||
_string(json['name']) ??
|
||||
'未命名的书源';
|
||||
final url = _string(json['bookSourceUrl']) ??
|
||||
_string(json['sourceUrl']) ??
|
||||
_string(json['url']) ??
|
||||
'';
|
||||
final search = _map(json['ruleSearch']);
|
||||
final bookInfo = _map(json['ruleBookInfo']);
|
||||
final toc = _map(json['ruleToc']);
|
||||
final content = _map(json['ruleContent']);
|
||||
final type = _sourceType(
|
||||
json['bookSourceType'] ?? json['sourceType'] ?? json['type'],
|
||||
json: json,
|
||||
search: search,
|
||||
content: content,
|
||||
);
|
||||
final headers = _headers(json['header'] ?? json['headers']);
|
||||
final cookie = _string(json['cookie'] ?? json['cookies']);
|
||||
final mergedHeaders = {
|
||||
...headers,
|
||||
if (cookie != null &&
|
||||
!headers.keys.any((key) => key.toLowerCase() == 'cookie'))
|
||||
'Cookie': cookie,
|
||||
};
|
||||
return LegadoSource(
|
||||
id: _sourceId(name, url),
|
||||
name: name,
|
||||
url: url,
|
||||
type: type,
|
||||
enabled: json['enabled'] == true,
|
||||
userAgent: _string(json['httpUserAgent']),
|
||||
headers: mergedHeaders,
|
||||
searchUrl: _firstString([
|
||||
search['url'],
|
||||
search['searchUrl'],
|
||||
search['bookUrlPattern'],
|
||||
search['comicUrlPattern'],
|
||||
json['searchUrl'],
|
||||
]),
|
||||
searchListRule: _firstString([
|
||||
search['bookList'],
|
||||
search['comicList'],
|
||||
search['list'],
|
||||
search['result'],
|
||||
search['items'],
|
||||
search['data'],
|
||||
search['results'],
|
||||
]),
|
||||
searchNameRule: _firstString([
|
||||
search['name'],
|
||||
search['bookName'],
|
||||
search['comicName'],
|
||||
search['title'],
|
||||
]),
|
||||
searchAuthorRule: _firstString([
|
||||
search['author'],
|
||||
search['bookAuthor'],
|
||||
search['comicAuthor'],
|
||||
search['writer'],
|
||||
]),
|
||||
searchCoverRule: _firstString([
|
||||
search['coverUrl'],
|
||||
search['cover'],
|
||||
search['bookCover'],
|
||||
search['comicCover'],
|
||||
search['poster'],
|
||||
search['img'],
|
||||
search['image'],
|
||||
]),
|
||||
searchDetailRule: _firstString([
|
||||
search['detailUrl'],
|
||||
search['bookUrl'],
|
||||
search['comicUrl'],
|
||||
search['chapterUrl'],
|
||||
search['tocUrl'],
|
||||
search['url'],
|
||||
search['href'],
|
||||
search['link'],
|
||||
]),
|
||||
searchMethod: _firstString([
|
||||
search['method'],
|
||||
search['httpMethod'],
|
||||
search['requestMethod'],
|
||||
]),
|
||||
searchBody: _firstString([
|
||||
search['body'],
|
||||
search['data'],
|
||||
search['payload'],
|
||||
search['postBody'],
|
||||
]),
|
||||
ruleKind: _string(search['kind']) ?? _string(search['type']),
|
||||
charset: _string(json['charset']) ??
|
||||
_string(json['encoding']) ??
|
||||
_string(json['bookSourceCharset']),
|
||||
urlEncoding: _string(json['urlEncoding']) ??
|
||||
_string(json['searchEncoding']) ??
|
||||
_string(json['bookSourceEncoding']),
|
||||
bookInfoUrl: _firstString([bookInfo['url'], bookInfo['bookUrl']]),
|
||||
bookInfoNameRule: _firstString([bookInfo['name'], bookInfo['bookName']]),
|
||||
bookInfoAuthorRule:
|
||||
_firstString([bookInfo['author'], bookInfo['bookAuthor']]),
|
||||
bookInfoCoverRule:
|
||||
_firstString([bookInfo['coverUrl'], bookInfo['cover']]),
|
||||
bookInfoIntroRule: _firstString(
|
||||
[bookInfo['intro'], bookInfo['introduce'], bookInfo['desc']]),
|
||||
bookInfoTocRule: _firstString([
|
||||
bookInfo['tocUrl'],
|
||||
bookInfo['chapterUrl'],
|
||||
bookInfo['catalogUrl'],
|
||||
bookInfo['directoryUrl'],
|
||||
]),
|
||||
tocUrl: _firstString([toc['url'], toc['tocUrl']]),
|
||||
tocListRule:
|
||||
_firstString([toc['chapterList'], toc['chapters'], toc['list']]),
|
||||
tocNameRule:
|
||||
_firstString([toc['chapterName'], toc['name'], toc['title']]),
|
||||
tocUrlRule: _firstString([toc['chapterUrl'], toc['url'], toc['href']]),
|
||||
tocNextPageRule: _firstString([
|
||||
toc['tocNextPageRule'],
|
||||
toc['nextTocUrl'],
|
||||
toc['nextUrl'],
|
||||
toc['nextPage'],
|
||||
toc['tocNextPage'],
|
||||
toc['nextPageUrl'],
|
||||
json['tocNextPageRule'],
|
||||
]),
|
||||
contentRule:
|
||||
_firstString([content['content'], content['text'], content['body']]),
|
||||
contentNextRule: _firstString([
|
||||
content['nextChapterUrl'],
|
||||
content['nextContentUrl'],
|
||||
content['next'],
|
||||
content['nextPage'],
|
||||
]),
|
||||
contentPrevRule: _firstString([
|
||||
content['prevChapterUrl'],
|
||||
content['prevContentUrl'],
|
||||
content['prev'],
|
||||
content['prevPage'],
|
||||
]),
|
||||
);
|
||||
}
|
||||
|
||||
Map<String, dynamic> toJson() {
|
||||
return {
|
||||
'bookSourceName': name,
|
||||
'bookSourceUrl': url,
|
||||
'bookSourceType': type,
|
||||
'enabled': enabled,
|
||||
if (userAgent != null) 'httpUserAgent': userAgent,
|
||||
if (charset != null) 'charset': charset,
|
||||
if (urlEncoding != null) 'urlEncoding': urlEncoding,
|
||||
if (headers.isNotEmpty) 'headers': headers,
|
||||
'ruleSearch': {
|
||||
if (searchUrl != null) 'url': searchUrl,
|
||||
if (searchListRule != null) 'bookList': searchListRule,
|
||||
if (searchNameRule != null) 'name': searchNameRule,
|
||||
if (searchAuthorRule != null) 'author': searchAuthorRule,
|
||||
if (searchCoverRule != null) 'coverUrl': searchCoverRule,
|
||||
if (searchDetailRule != null) 'detailUrl': searchDetailRule,
|
||||
if (searchMethod != null) 'method': searchMethod,
|
||||
if (searchBody != null) 'body': searchBody,
|
||||
if (ruleKind != null) 'kind': ruleKind,
|
||||
},
|
||||
'ruleBookInfo': {
|
||||
if (bookInfoUrl != null) 'url': bookInfoUrl,
|
||||
if (bookInfoNameRule != null) 'name': bookInfoNameRule,
|
||||
if (bookInfoAuthorRule != null) 'author': bookInfoAuthorRule,
|
||||
if (bookInfoCoverRule != null) 'coverUrl': bookInfoCoverRule,
|
||||
if (bookInfoIntroRule != null) 'intro': bookInfoIntroRule,
|
||||
if (bookInfoTocRule != null) 'tocUrl': bookInfoTocRule,
|
||||
},
|
||||
'ruleToc': {
|
||||
if (tocUrl != null) 'url': tocUrl,
|
||||
if (tocListRule != null) 'chapterList': tocListRule,
|
||||
if (tocNameRule != null) 'chapterName': tocNameRule,
|
||||
if (tocUrlRule != null) 'chapterUrl': tocUrlRule,
|
||||
if (tocNextPageRule != null) 'nextTocUrl': tocNextPageRule,
|
||||
},
|
||||
'ruleContent': {
|
||||
if (contentRule != null) 'content': contentRule,
|
||||
if (contentNextRule != null) 'nextChapterUrl': contentNextRule,
|
||||
if (contentPrevRule != null) 'prevChapterUrl': contentPrevRule,
|
||||
},
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
class OnlineBookInfo {
|
||||
const OnlineBookInfo({
|
||||
required this.title,
|
||||
required this.tocUrl,
|
||||
required this.sourceName,
|
||||
this.author,
|
||||
this.coverUrl,
|
||||
this.intro,
|
||||
});
|
||||
|
||||
final String title;
|
||||
final String? author;
|
||||
final String? coverUrl;
|
||||
final String? intro;
|
||||
final String tocUrl;
|
||||
final String sourceName;
|
||||
}
|
||||
|
||||
class OnlineChapter {
|
||||
const OnlineChapter({
|
||||
required this.title,
|
||||
required this.url,
|
||||
required this.index,
|
||||
});
|
||||
|
||||
final String title;
|
||||
final String url;
|
||||
final int index;
|
||||
}
|
||||
|
||||
class OnlineChapterContent {
|
||||
const OnlineChapterContent({
|
||||
required this.title,
|
||||
this.textContent,
|
||||
this.imageUrls = const <String>[],
|
||||
this.pageImages = const <PageImage>[],
|
||||
this.nextChapterUrl,
|
||||
this.prevChapterUrl,
|
||||
});
|
||||
|
||||
final String title;
|
||||
final String? textContent;
|
||||
final List<String> imageUrls;
|
||||
final List<PageImage> pageImages;
|
||||
final String? nextChapterUrl;
|
||||
final String? prevChapterUrl;
|
||||
}
|
||||
|
||||
class OnlineReadingRecord {
|
||||
const OnlineReadingRecord({
|
||||
required this.sourceId,
|
||||
required this.sourceName,
|
||||
required this.bookTitle,
|
||||
required this.detailUrl,
|
||||
required this.chapterUrl,
|
||||
required this.chapterTitle,
|
||||
required this.chapterIndex,
|
||||
required this.totalChapters,
|
||||
required this.lastReadTime,
|
||||
});
|
||||
|
||||
final String sourceId;
|
||||
final String sourceName;
|
||||
final String bookTitle;
|
||||
final String detailUrl;
|
||||
final String chapterUrl;
|
||||
final String chapterTitle;
|
||||
final int chapterIndex;
|
||||
final int totalChapters;
|
||||
final DateTime lastReadTime;
|
||||
|
||||
factory OnlineReadingRecord.fromJson(Map<String, dynamic> json) =>
|
||||
OnlineReadingRecord(
|
||||
sourceId: json['sourceId']?.toString() ?? '',
|
||||
sourceName: json['sourceName']?.toString() ?? '',
|
||||
bookTitle: json['bookTitle']?.toString() ?? '',
|
||||
detailUrl: json['detailUrl']?.toString() ?? '',
|
||||
chapterUrl: json['chapterUrl']?.toString() ?? '',
|
||||
chapterTitle: json['chapterTitle']?.toString() ?? '',
|
||||
chapterIndex: _int(json['chapterIndex']) ?? 0,
|
||||
totalChapters: _int(json['totalChapters']) ?? 0,
|
||||
lastReadTime:
|
||||
DateTime.tryParse(json['lastReadTime']?.toString() ?? '') ??
|
||||
DateTime.fromMillisecondsSinceEpoch(0),
|
||||
);
|
||||
|
||||
Map<String, dynamic> toJson() => {
|
||||
'sourceId': sourceId,
|
||||
'sourceName': sourceName,
|
||||
'bookTitle': bookTitle,
|
||||
'detailUrl': detailUrl,
|
||||
'chapterUrl': chapterUrl,
|
||||
'chapterTitle': chapterTitle,
|
||||
'chapterIndex': chapterIndex,
|
||||
'totalChapters': totalChapters,
|
||||
'lastReadTime': lastReadTime.toIso8601String(),
|
||||
};
|
||||
}
|
||||
|
||||
enum LoadFailureReason {
|
||||
network,
|
||||
httpError,
|
||||
ruleNotSupported,
|
||||
ruleParseEmpty,
|
||||
encoding,
|
||||
unknown,
|
||||
}
|
||||
|
||||
class LegadoLoadException implements Exception {
|
||||
const LegadoLoadException(this.reason, this.message, {this.cause});
|
||||
|
||||
final LoadFailureReason reason;
|
||||
final String message;
|
||||
final Object? cause;
|
||||
|
||||
@override
|
||||
String toString() => message;
|
||||
}
|
||||
|
||||
enum SourceCompatLevel {
|
||||
full,
|
||||
partial,
|
||||
needsJs,
|
||||
needsPost,
|
||||
needsHeaders,
|
||||
broken,
|
||||
unknown,
|
||||
}
|
||||
|
||||
class SourceCompatInfo {
|
||||
const SourceCompatInfo({
|
||||
required this.level,
|
||||
required this.searchOk,
|
||||
required this.bookInfoOk,
|
||||
required this.tocOk,
|
||||
required this.contentOk,
|
||||
required this.hasJsRule,
|
||||
required this.hasPutGet,
|
||||
this.warnings = const <String>[],
|
||||
});
|
||||
|
||||
final SourceCompatLevel level;
|
||||
final bool searchOk;
|
||||
final bool bookInfoOk;
|
||||
final bool tocOk;
|
||||
final bool contentOk;
|
||||
final bool hasJsRule;
|
||||
final bool hasPutGet;
|
||||
final List<String> warnings;
|
||||
|
||||
String get label {
|
||||
switch (level) {
|
||||
case SourceCompatLevel.full:
|
||||
return '完全兼容';
|
||||
case SourceCompatLevel.partial:
|
||||
return '部分兼容';
|
||||
case SourceCompatLevel.needsJs:
|
||||
return '需要 JS';
|
||||
case SourceCompatLevel.needsPost:
|
||||
return 'POST 源';
|
||||
case SourceCompatLevel.needsHeaders:
|
||||
return '需请求头';
|
||||
case SourceCompatLevel.broken:
|
||||
return '规则不完整';
|
||||
case SourceCompatLevel.unknown:
|
||||
return '待检测';
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
class UnifiedSearchResult {
|
||||
const UnifiedSearchResult({
|
||||
required this.sourceId,
|
||||
required this.sourceName,
|
||||
required this.title,
|
||||
this.author,
|
||||
this.coverUrl,
|
||||
this.detailUrl,
|
||||
this.errorMessage,
|
||||
});
|
||||
|
||||
const UnifiedSearchResult.error({
|
||||
required this.sourceId,
|
||||
required this.sourceName,
|
||||
required this.errorMessage,
|
||||
}) : title = '搜索失败',
|
||||
author = null,
|
||||
coverUrl = null,
|
||||
detailUrl = null;
|
||||
|
||||
final String sourceId;
|
||||
final String sourceName;
|
||||
final String title;
|
||||
final String? author;
|
||||
final String? coverUrl;
|
||||
final String? detailUrl;
|
||||
final String? errorMessage;
|
||||
|
||||
bool get isError => errorMessage?.trim().isNotEmpty == true;
|
||||
}
|
||||
|
||||
String _sourceId(String name, String url) {
|
||||
final raw = '$name|$url';
|
||||
return raw.codeUnits.fold<int>(0, (value, unit) => value + unit).toString();
|
||||
}
|
||||
|
||||
String? _string(Object? value) {
|
||||
final text = value?.toString().trim();
|
||||
return text == null || text.isEmpty ? null : text;
|
||||
}
|
||||
|
||||
int? _int(Object? value) {
|
||||
if (value is int) return value;
|
||||
if (value is num) return value.toInt();
|
||||
return int.tryParse(value?.toString() ?? '');
|
||||
}
|
||||
|
||||
int _sourceType(
|
||||
Object? value, {
|
||||
Map<String, dynamic> json = const <String, dynamic>{},
|
||||
Map<String, dynamic> search = const <String, dynamic>{},
|
||||
Map<String, dynamic> content = const <String, dynamic>{},
|
||||
}) {
|
||||
final number = _int(value);
|
||||
if (number == 2) return 2;
|
||||
final text = [
|
||||
value,
|
||||
json['bookSourceName'],
|
||||
json['bookSourceGroup'],
|
||||
json['bookSourceUrl'],
|
||||
].whereType<Object>().join(' ').toLowerCase();
|
||||
final imageStyle = _string(content['imageStyle'])?.toLowerCase() ?? '';
|
||||
final contentRule = _string(content['content'])?.toLowerCase() ?? '';
|
||||
final hasComicFields = const [
|
||||
'comicList',
|
||||
'comicName',
|
||||
'comicUrl',
|
||||
'comicCover',
|
||||
].any(search.containsKey);
|
||||
final hasImageContent = imageStyle == 'full' ||
|
||||
contentRule.contains('<img') ||
|
||||
contentRule.contains('@img') ||
|
||||
contentRule.contains('jpglist') ||
|
||||
contentRule.contains('chapter_img');
|
||||
final mangaNamed = text.contains('comic') ||
|
||||
text.contains('manga') ||
|
||||
text.contains('manhua') ||
|
||||
text.contains('\u6f2b\u753b');
|
||||
if (hasComicFields || (mangaNamed && hasImageContent)) return 2;
|
||||
if (number != null) return number;
|
||||
if (text.contains('comic') || text.contains('manga') || text.contains('漫画')) {
|
||||
return 2;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
String? _firstString(Iterable<Object?> values) {
|
||||
for (final value in values) {
|
||||
final text = _string(value);
|
||||
if (text != null) return text;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
Map<String, dynamic> _map(Object? value) {
|
||||
return value is Map ? Map<String, dynamic>.from(value) : <String, dynamic>{};
|
||||
}
|
||||
|
||||
Map<String, String> _headers(Object? value) {
|
||||
if (value is Map) {
|
||||
return value.map((key, item) => MapEntry(key.toString(), item.toString()));
|
||||
}
|
||||
if (value is String) {
|
||||
final trimmed = value.trim();
|
||||
if (trimmed.isEmpty) return const <String, String>{};
|
||||
try {
|
||||
final decoded = _mapFromJsonString(trimmed);
|
||||
if (decoded.isNotEmpty) return _headers(decoded);
|
||||
} catch (_) {
|
||||
// Fall through to the line parser used by several Legado repositories.
|
||||
}
|
||||
final headers = <String, String>{};
|
||||
for (final line in trimmed.split(RegExp(r'[\r\n]+'))) {
|
||||
final index = line.indexOf(':');
|
||||
if (index <= 0) continue;
|
||||
final key = line.substring(0, index).trim();
|
||||
final item = line.substring(index + 1).trim();
|
||||
if (key.isNotEmpty && item.isNotEmpty) headers[key] = item;
|
||||
}
|
||||
return headers;
|
||||
}
|
||||
return const <String, String>{};
|
||||
}
|
||||
|
||||
Map<String, dynamic> _mapFromJsonString(String value) {
|
||||
final decoded = value.startsWith('{') ? _jsonDecode(value) : null;
|
||||
return decoded is Map
|
||||
? Map<String, dynamic>.from(decoded)
|
||||
: <String, dynamic>{};
|
||||
}
|
||||
|
||||
Object? _jsonDecode(String value) {
|
||||
// Kept local so malformed header strings do not affect source import.
|
||||
try {
|
||||
return jsonDecode(value);
|
||||
} catch (_) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,484 @@
|
||||
import 'package:html/dom.dart';
|
||||
import 'package:html/parser.dart' as html_parser;
|
||||
|
||||
import 'legado_rule_parser.dart';
|
||||
|
||||
typedef LegadoJsCallback = String Function({
|
||||
required String script,
|
||||
required String result,
|
||||
required String rawHtml,
|
||||
required String baseUrl,
|
||||
required Map<String, String> context,
|
||||
});
|
||||
|
||||
class UnsupportedLegadoRule implements Exception {
|
||||
const UnsupportedLegadoRule(this.rule, this.feature);
|
||||
|
||||
final String rule;
|
||||
final String feature;
|
||||
|
||||
@override
|
||||
String toString() => 'Unsupported Legado rule feature: $feature';
|
||||
}
|
||||
|
||||
class LegadoRuleExecutor {
|
||||
LegadoRuleExecutor({LegadoJsCallback? runJs}) : _runJs = runJs;
|
||||
|
||||
final LegadoJsCallback? _runJs;
|
||||
final Map<String, String> _context = <String, String>{};
|
||||
|
||||
Map<String, String> get context => Map.unmodifiable(_context);
|
||||
|
||||
void clearContext() => _context.clear();
|
||||
|
||||
void setContext(String key, Object? value) {
|
||||
_context[key] = value?.toString() ?? '';
|
||||
}
|
||||
|
||||
String expandContext(String value) {
|
||||
final withGet = value.replaceAllMapped(
|
||||
RegExp(r'@get:\{([^}]+)\}'),
|
||||
(match) {
|
||||
final key = (match.group(1) ?? '').trim();
|
||||
return _context[key] ?? match.group(0) ?? '';
|
||||
},
|
||||
);
|
||||
return withGet.replaceAllMapped(
|
||||
RegExp(r'\{\{(?!\$\.)([^}]+)\}\}'),
|
||||
(match) {
|
||||
final key = (match.group(1) ?? '').trim();
|
||||
return _context[key] ?? match.group(0) ?? '';
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
String select(
|
||||
String rawHtml,
|
||||
String fragment,
|
||||
String? rule, {
|
||||
required String baseUrl,
|
||||
String? kind,
|
||||
}) {
|
||||
final values = selectList(
|
||||
rawHtml,
|
||||
fragment,
|
||||
rule,
|
||||
baseUrl: baseUrl,
|
||||
kind: kind,
|
||||
);
|
||||
return values.join('\n');
|
||||
}
|
||||
|
||||
List<String> selectList(
|
||||
String rawHtml,
|
||||
String fragment,
|
||||
String? rule, {
|
||||
required String baseUrl,
|
||||
String? kind,
|
||||
}) {
|
||||
final normalized = rule?.trim() ?? '';
|
||||
if (normalized.isEmpty) return const <String>[];
|
||||
|
||||
for (final alternative in _splitOutsideJs(normalized, '||')) {
|
||||
final joined = <String>[];
|
||||
var failed = false;
|
||||
for (final part in _splitOutsideJs(alternative, '&&')) {
|
||||
final values = _executePart(
|
||||
rawHtml,
|
||||
fragment,
|
||||
part,
|
||||
baseUrl: baseUrl,
|
||||
kind: kind,
|
||||
);
|
||||
if (values.isEmpty) {
|
||||
failed = true;
|
||||
break;
|
||||
}
|
||||
joined.addAll(values);
|
||||
}
|
||||
if (!failed && joined.isNotEmpty) return joined;
|
||||
}
|
||||
return const <String>[];
|
||||
}
|
||||
|
||||
List<String> _executePart(
|
||||
String rawHtml,
|
||||
String fragment,
|
||||
String rawRule, {
|
||||
required String baseUrl,
|
||||
String? kind,
|
||||
}) {
|
||||
var rule = expandContext(rawRule.trim());
|
||||
final js = _extractJs(rule);
|
||||
rule = js.rule;
|
||||
final replacements = _extractReplacements(rule);
|
||||
rule = replacements.rule.trim();
|
||||
final put = RegExp(r'@put:\{([^:}]+):([^}]+)\}').firstMatch(rawRule);
|
||||
rule = rule.replaceAll(RegExp(r'@put:\{[^}]+\}'), '').trim();
|
||||
|
||||
var values = rule.isEmpty
|
||||
? <String>[fragment]
|
||||
: _executeChain(fragment, rule, baseUrl: baseUrl, kind: kind);
|
||||
|
||||
if (put != null) {
|
||||
final key = put.group(1)?.trim() ?? '';
|
||||
final valueRule = put.group(2)?.trim() ?? '';
|
||||
var value = values.isEmpty ? '' : values.first;
|
||||
if (valueRule.isNotEmpty) {
|
||||
for (final candidate in valueRule.split('||')) {
|
||||
final candidateRule = candidate.trim().startsWith(r'$')
|
||||
? candidate.trim()
|
||||
: r'$.' + candidate.trim();
|
||||
value = RuleParser(fragment, baseUrl: baseUrl)
|
||||
.select(fragment, candidateRule, kind: 'json');
|
||||
if (value.isNotEmpty) break;
|
||||
}
|
||||
}
|
||||
if (key.isNotEmpty && value.isNotEmpty) _context[key] = value;
|
||||
}
|
||||
|
||||
if (js.script != null) {
|
||||
final callback = _runJs;
|
||||
if (callback == null) {
|
||||
throw UnsupportedLegadoRule(rawRule, 'javascript');
|
||||
}
|
||||
final input = values.join('\n');
|
||||
final output = callback(
|
||||
script: js.script!,
|
||||
result: input.isEmpty ? rawHtml : input,
|
||||
rawHtml: rawHtml,
|
||||
baseUrl: baseUrl,
|
||||
context: _context,
|
||||
);
|
||||
values = output
|
||||
.split(RegExp(r'[\r\n]+'))
|
||||
.map((item) => item.trim())
|
||||
.where((item) => item.isNotEmpty)
|
||||
.toList();
|
||||
if (js.afterRule.trim().isNotEmpty && values.isNotEmpty) {
|
||||
values = _executeChain(
|
||||
values.join('\n'),
|
||||
expandContext(js.afterRule),
|
||||
baseUrl: baseUrl,
|
||||
kind: kind,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
for (final replacement in replacements.items) {
|
||||
values = values
|
||||
.map((value) => value.replaceAll(
|
||||
RegExp(replacement.pattern, dotAll: true),
|
||||
replacement.replacement,
|
||||
))
|
||||
.map((value) => value.trim())
|
||||
.where((value) => value.isNotEmpty)
|
||||
.toList();
|
||||
}
|
||||
return values;
|
||||
}
|
||||
|
||||
List<String> _executeChain(
|
||||
String fragment,
|
||||
String rule, {
|
||||
required String baseUrl,
|
||||
String? kind,
|
||||
}) {
|
||||
final expandedRule = _expandJsonTemplate(rule, fragment, baseUrl);
|
||||
if (_looksLikeLiteral(expandedRule)) return <String>[expandedRule];
|
||||
if (_isAtomicRule(expandedRule, kind)) {
|
||||
final parser = RuleParser(fragment, baseUrl: baseUrl);
|
||||
final values = parser.selectList(expandedRule, kind: kind);
|
||||
if (values.isNotEmpty) return values;
|
||||
final single = parser.select(fragment, expandedRule, kind: kind);
|
||||
return single.isEmpty ? const <String>[] : <String>[single];
|
||||
}
|
||||
|
||||
final tokens = _chainTokens(expandedRule);
|
||||
if (tokens.isEmpty) return const <String>[];
|
||||
var current = <String>[fragment];
|
||||
for (var index = 0; index < tokens.length; index++) {
|
||||
final token = tokens[index];
|
||||
if (token.startsWith('put:') || token.startsWith('js:')) continue;
|
||||
if (token.startsWith('get:')) {
|
||||
final key = token.substring(4).replaceAll(RegExp(r'[{}]'), '').trim();
|
||||
final value = _context[key] ?? '';
|
||||
current = value.isEmpty ? const <String>[] : <String>[value];
|
||||
} else if (token == 'text') {
|
||||
current = current.map(_elementText).where(_notEmpty).toList();
|
||||
} else if (token == 'html') {
|
||||
current = current.map(_elementHtml).where(_notEmpty).toList();
|
||||
} else if (_isAttribute(token)) {
|
||||
current = current
|
||||
.map((value) => _attribute(value, token))
|
||||
.where(_notEmpty)
|
||||
.toList();
|
||||
} else {
|
||||
final selectorToken = token.startsWith('css:')
|
||||
? token.substring(4)
|
||||
: token.startsWith('tag.')
|
||||
? token.substring(4)
|
||||
: token;
|
||||
current = _selectElements(current, selectorToken);
|
||||
}
|
||||
if (current.isEmpty) return const <String>[];
|
||||
}
|
||||
return current;
|
||||
}
|
||||
|
||||
List<String> _selectElements(List<String> inputs, String rawSelector) {
|
||||
final spec = _selectorSpec(rawSelector);
|
||||
final output = <String>[];
|
||||
for (final input in inputs) {
|
||||
try {
|
||||
final document = html_parser.parseFragment(input);
|
||||
var elements = spec.textContains == null
|
||||
? document.querySelectorAll(spec.selector)
|
||||
: document
|
||||
.querySelectorAll('*')
|
||||
.where((element) => element.text.contains(spec.textContains!))
|
||||
.toList(growable: false);
|
||||
if (spec.excludedIndex != null && elements.isNotEmpty) {
|
||||
final excluded =
|
||||
_normalizedIndex(spec.excludedIndex!, elements.length);
|
||||
elements = <Element>[
|
||||
for (var i = 0; i < elements.length; i++)
|
||||
if (i != excluded) elements[i],
|
||||
];
|
||||
}
|
||||
if (spec.index != null && elements.isNotEmpty) {
|
||||
final selected = _normalizedIndex(spec.index!, elements.length);
|
||||
if (selected >= 0 && selected < elements.length) {
|
||||
output.add(elements[selected].outerHtml);
|
||||
}
|
||||
} else {
|
||||
output.addAll(elements.map((element) => element.outerHtml));
|
||||
}
|
||||
} catch (_) {
|
||||
// A malformed selector returns no values and allows the next || rule.
|
||||
}
|
||||
}
|
||||
return output;
|
||||
}
|
||||
|
||||
_SelectorSpec _selectorSpec(String raw) {
|
||||
var value = raw.trim();
|
||||
int? excluded;
|
||||
final exclusion = RegExp(r'!(\-?\d+)$').firstMatch(value);
|
||||
if (exclusion != null) {
|
||||
excluded = int.tryParse(exclusion.group(1) ?? '');
|
||||
value = value.substring(0, exclusion.start);
|
||||
}
|
||||
int? index;
|
||||
final indexed = RegExp(r'\.(\-?\d+)$').firstMatch(value);
|
||||
if (indexed != null) {
|
||||
index = int.tryParse(indexed.group(1) ?? '');
|
||||
value = value.substring(0, indexed.start);
|
||||
}
|
||||
if (value.startsWith('class.')) {
|
||||
value = '.${value.substring(6)}';
|
||||
} else if (value.startsWith('id.')) {
|
||||
value = '#${value.substring(3)}';
|
||||
} else if (value.startsWith('tag.')) {
|
||||
value = value.substring(4);
|
||||
} else if (value.startsWith('text.')) {
|
||||
final text = value.substring(5).trim();
|
||||
return _SelectorSpec('*', index: index, textContains: text);
|
||||
}
|
||||
if (value.isEmpty) value = '*';
|
||||
return _SelectorSpec(value, index: index, excludedIndex: excluded);
|
||||
}
|
||||
|
||||
int _normalizedIndex(int index, int length) =>
|
||||
index < 0 ? length + index : index;
|
||||
|
||||
List<String> _chainTokens(String rule) {
|
||||
final normalized = rule.replaceAll(RegExp(r'@put:\{[^}]+\}'), '');
|
||||
final pieces = normalized.split('@');
|
||||
final tokens = <String>[];
|
||||
if (pieces.first.trim().isNotEmpty) tokens.add(pieces.first.trim());
|
||||
for (var i = 1; i < pieces.length; i++) {
|
||||
final piece = pieces[i].trim();
|
||||
if (piece.isEmpty) continue;
|
||||
if (piece.startsWith('tag.') || piece.startsWith('css:')) {
|
||||
tokens.add(piece);
|
||||
} else {
|
||||
tokens.add(piece);
|
||||
}
|
||||
}
|
||||
return tokens;
|
||||
}
|
||||
|
||||
bool _isAtomicRule(String rule, String? kind) {
|
||||
final lower = rule.toLowerCase();
|
||||
return kind == 'json' ||
|
||||
kind == 'regex' ||
|
||||
lower.startsWith(r'$.') ||
|
||||
lower.startsWith('json:') ||
|
||||
lower.startsWith('regex:');
|
||||
}
|
||||
|
||||
String _expandJsonTemplate(String rule, String fragment, String baseUrl) {
|
||||
return rule.replaceAllMapped(RegExp(r'\{\{(\$\.[^}]+)\}\}'), (match) {
|
||||
final path = match.group(1) ?? '';
|
||||
final value = RuleParser(fragment, baseUrl: baseUrl)
|
||||
.select(fragment, path, kind: 'json');
|
||||
return value.isEmpty ? match.group(0) ?? '' : value;
|
||||
});
|
||||
}
|
||||
|
||||
bool _looksLikeLiteral(String rule) {
|
||||
final value = rule.trim().toLowerCase();
|
||||
return value.startsWith('http://') ||
|
||||
value.startsWith('https://') ||
|
||||
value.startsWith('//') ||
|
||||
(value.startsWith('/') && !value.startsWith('//##'));
|
||||
}
|
||||
|
||||
bool _isAttribute(String token) {
|
||||
const attributes = <String>{
|
||||
'src',
|
||||
'href',
|
||||
'class',
|
||||
'alt',
|
||||
'title',
|
||||
'content',
|
||||
'value',
|
||||
'style',
|
||||
};
|
||||
return attributes.contains(token) || token.startsWith('data-');
|
||||
}
|
||||
|
||||
String _attribute(String html, String name) {
|
||||
final fragment = html_parser.parseFragment(html);
|
||||
return (fragment.querySelector('*')?.attributes[name] ?? '').trim();
|
||||
}
|
||||
|
||||
String _elementText(String html) =>
|
||||
(html_parser.parseFragment(html).text ?? '')
|
||||
.replaceAll(RegExp(r'\s+'), ' ')
|
||||
.trim();
|
||||
|
||||
String _elementHtml(String html) {
|
||||
final fragment = html_parser.parseFragment(html);
|
||||
final element = fragment.querySelector('*');
|
||||
return element?.innerHtml.trim() ?? '';
|
||||
}
|
||||
|
||||
_JsRule _extractJs(String rule) {
|
||||
final block =
|
||||
RegExp(r'<js>([\s\S]*?)</js>', caseSensitive: false).firstMatch(rule);
|
||||
if (block != null) {
|
||||
return _JsRule(
|
||||
rule.substring(0, block.start),
|
||||
block.group(1)?.trim(),
|
||||
rule.substring(block.end),
|
||||
);
|
||||
}
|
||||
final marker = RegExp(r'@js:', caseSensitive: false).firstMatch(rule);
|
||||
if (marker != null) {
|
||||
return _JsRule(
|
||||
rule.substring(0, marker.start),
|
||||
rule.substring(marker.end).trim(),
|
||||
'',
|
||||
);
|
||||
}
|
||||
return _JsRule(rule, null, '');
|
||||
}
|
||||
|
||||
_ReplaceRule _extractReplacements(String rule) {
|
||||
final items = <_Replacement>[];
|
||||
var base = rule;
|
||||
final marker = rule.indexOf('###');
|
||||
if (marker >= 0) {
|
||||
final tail = rule.substring(marker + 3);
|
||||
final end = tail.indexOf('###');
|
||||
final pattern = end >= 0 ? tail.substring(0, end) : tail;
|
||||
if (pattern.isNotEmpty) items.add(_Replacement(pattern, ''));
|
||||
base = rule.substring(0, marker);
|
||||
}
|
||||
final replaceMarker = base.indexOf('##');
|
||||
if (replaceMarker >= 0) {
|
||||
final tail = base.substring(replaceMarker + 2);
|
||||
final separator = tail.indexOf('##');
|
||||
final pattern = separator >= 0 ? tail.substring(0, separator) : tail;
|
||||
final replacement = separator >= 0 ? tail.substring(separator + 2) : '';
|
||||
if (pattern.isNotEmpty) items.add(_Replacement(pattern, replacement));
|
||||
base = base.substring(0, replaceMarker);
|
||||
}
|
||||
return _ReplaceRule(base, items);
|
||||
}
|
||||
|
||||
List<String> _splitOutsideJs(String rule, String separator) {
|
||||
final jsIndex = <int>[
|
||||
rule.indexOf('@js:'),
|
||||
rule.toLowerCase().indexOf('<js>'),
|
||||
]
|
||||
.where((index) => index >= 0)
|
||||
.fold<int>(rule.length, (a, b) => a < b ? a : b);
|
||||
final prefix = rule.substring(0, jsIndex);
|
||||
final suffix = rule.substring(jsIndex);
|
||||
final parts = <String>[];
|
||||
var start = 0;
|
||||
var braceDepth = 0;
|
||||
String? quote;
|
||||
for (var index = 0; index <= prefix.length - separator.length; index++) {
|
||||
final char = prefix[index];
|
||||
if (quote != null) {
|
||||
if (char == quote && (index == 0 || prefix[index - 1] != '\\')) {
|
||||
quote = null;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if (char == '"' || char == "'") {
|
||||
quote = char;
|
||||
continue;
|
||||
}
|
||||
if (char == '{') braceDepth++;
|
||||
if (char == '}' && braceDepth > 0) braceDepth--;
|
||||
if (braceDepth == 0 && prefix.startsWith(separator, index)) {
|
||||
parts.add(prefix.substring(start, index));
|
||||
start = index + separator.length;
|
||||
index += separator.length - 1;
|
||||
}
|
||||
}
|
||||
parts.add(prefix.substring(start));
|
||||
if (parts.length == 1) return <String>[rule];
|
||||
parts[parts.length - 1] = '${parts.last}$suffix';
|
||||
return parts.map((part) => part.trim()).where(_notEmpty).toList();
|
||||
}
|
||||
|
||||
bool _notEmpty(String value) => value.trim().isNotEmpty;
|
||||
}
|
||||
|
||||
class _SelectorSpec {
|
||||
const _SelectorSpec(
|
||||
this.selector, {
|
||||
this.index,
|
||||
this.excludedIndex,
|
||||
this.textContains,
|
||||
});
|
||||
final String selector;
|
||||
final int? index;
|
||||
final int? excludedIndex;
|
||||
final String? textContains;
|
||||
}
|
||||
|
||||
class _JsRule {
|
||||
const _JsRule(this.rule, this.script, this.afterRule);
|
||||
final String rule;
|
||||
final String? script;
|
||||
final String afterRule;
|
||||
}
|
||||
|
||||
class _ReplaceRule {
|
||||
const _ReplaceRule(this.rule, this.items);
|
||||
final String rule;
|
||||
final List<_Replacement> items;
|
||||
}
|
||||
|
||||
class _Replacement {
|
||||
const _Replacement(this.pattern, this.replacement);
|
||||
final String pattern;
|
||||
final String replacement;
|
||||
}
|
||||
@@ -0,0 +1,266 @@
|
||||
import 'dart:convert';
|
||||
|
||||
import 'package:html/parser.dart' as html_parser;
|
||||
|
||||
class RuleParser {
|
||||
RuleParser(this.body, {required this.baseUrl});
|
||||
|
||||
final String body;
|
||||
final String baseUrl;
|
||||
|
||||
Object? _decodedJson;
|
||||
|
||||
List<String> selectList(String? rule, {String? kind}) {
|
||||
for (final normalized in _ruleAlternatives(rule)) {
|
||||
final type = _resolveKind(normalized, kind);
|
||||
if (type == 'json') {
|
||||
final values = _jsonPath(normalized);
|
||||
final result =
|
||||
values.map(_stringifyJsonValue).where(_notEmpty).toList();
|
||||
if (result.isNotEmpty) return result;
|
||||
continue;
|
||||
}
|
||||
if (type == 'regex') {
|
||||
final matches = RegExp(_stripPrefix(normalized), dotAll: true)
|
||||
.allMatches(body)
|
||||
.map((match) =>
|
||||
match.groupCount >= 1 ? match.group(1) : match.group(0))
|
||||
.whereType<String>()
|
||||
.where(_notEmpty)
|
||||
.toList();
|
||||
if (matches.isNotEmpty) return matches;
|
||||
continue;
|
||||
}
|
||||
final fragments = _cssFragments(normalized);
|
||||
if (fragments.isNotEmpty) return fragments;
|
||||
}
|
||||
return const <String>[];
|
||||
}
|
||||
|
||||
String select(String fragment, String? rule, {String? kind}) {
|
||||
for (final normalized in _ruleAlternatives(rule)) {
|
||||
final type = _resolveKind(normalized, kind);
|
||||
if (type == 'json') {
|
||||
final values =
|
||||
RuleParser(fragment, baseUrl: baseUrl)._jsonPath(normalized);
|
||||
final value = values.isEmpty ? '' : _stringifyJsonValue(values.first);
|
||||
if (value.isNotEmpty) return value;
|
||||
continue;
|
||||
}
|
||||
if (type == 'regex') {
|
||||
final match =
|
||||
RegExp(_stripPrefix(normalized), dotAll: true).firstMatch(fragment);
|
||||
final value =
|
||||
_clean(match?.groupCount == 0 ? match?.group(0) : match?.group(1));
|
||||
if (value.isNotEmpty) return value;
|
||||
continue;
|
||||
}
|
||||
final value = _cssText(fragment, normalized);
|
||||
if (value.isNotEmpty) return value;
|
||||
}
|
||||
return '';
|
||||
}
|
||||
|
||||
List<Object?> _jsonPath(String rule) {
|
||||
final path = _stripPrefix(rule)
|
||||
.replaceFirst(RegExp(r'^\$\.?'), '')
|
||||
.split('.')
|
||||
.where((item) => item.isNotEmpty)
|
||||
.toList();
|
||||
var current = _jsonBody();
|
||||
for (final segment in path) {
|
||||
if (segment.endsWith('[*]')) {
|
||||
final key = segment.substring(0, segment.length - 3);
|
||||
final list = _child(current, key);
|
||||
current = list is List ? list : const <Object?>[];
|
||||
continue;
|
||||
}
|
||||
current = _child(current, segment);
|
||||
}
|
||||
if (current is List) return current;
|
||||
if (current == null) return const <Object?>[];
|
||||
return [current];
|
||||
}
|
||||
|
||||
Object? _jsonBody() {
|
||||
if (_decodedJson != null) return _decodedJson;
|
||||
try {
|
||||
var text = body.trimLeft();
|
||||
if (text.isNotEmpty && text.codeUnitAt(0) == 0xFEFF) {
|
||||
text = text.substring(1);
|
||||
}
|
||||
final jsonp = RegExp(
|
||||
r'^[a-zA-Z_$][\w$]*\s*\(\s*(.*)\s*\)\s*;?\s*$',
|
||||
dotAll: true,
|
||||
).firstMatch(text.trim());
|
||||
if (jsonp != null) {
|
||||
text = jsonp.group(1) ?? text;
|
||||
}
|
||||
_decodedJson = jsonDecode(text);
|
||||
} on FormatException {
|
||||
_decodedJson = null;
|
||||
}
|
||||
return _decodedJson;
|
||||
}
|
||||
|
||||
Object? _child(Object? node, String key) {
|
||||
if (key.isEmpty) return node;
|
||||
if (key == '*') {
|
||||
if (node is List) return node;
|
||||
if (node is Map) return node.values.toList(growable: false);
|
||||
return null;
|
||||
}
|
||||
final indexed = RegExp(r'^([^\[]*)\[(\d+|\*)\]$').firstMatch(key);
|
||||
if (indexed != null) {
|
||||
final parentKey = indexed.group(1) ?? '';
|
||||
final indexText = indexed.group(2) ?? '';
|
||||
final parent = parentKey.isEmpty ? node : _child(node, parentKey);
|
||||
if (parent is List) {
|
||||
if (indexText == '*') return parent;
|
||||
final index = int.tryParse(indexText);
|
||||
if (index != null && index >= 0 && index < parent.length) {
|
||||
return parent[index];
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
if (node is Map) return node[key];
|
||||
if (node is List) {
|
||||
return node
|
||||
.map((item) => _child(item, key))
|
||||
.where((item) => item != null)
|
||||
.toList();
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
List<String> _cssFragments(String selector) {
|
||||
final cleanSelector = _selectorWithoutAttr(selector);
|
||||
if (cleanSelector.isEmpty) return const <String>[];
|
||||
try {
|
||||
final document = html_parser.parse(body);
|
||||
final elements = document.querySelectorAll(cleanSelector);
|
||||
final values = elements
|
||||
.map((element) => element.outerHtml)
|
||||
.where(_notEmpty)
|
||||
.toList(growable: false);
|
||||
if (values.isNotEmpty) return values;
|
||||
} catch (_) {
|
||||
// Fall through to the legacy regex parser for malformed selectors.
|
||||
}
|
||||
return _legacyCssFragments(cleanSelector);
|
||||
}
|
||||
|
||||
String _cssText(String fragment, String selector) {
|
||||
final attr = RegExp(r'@([a-zA-Z0-9_-]+)$').firstMatch(selector)?.group(1);
|
||||
final cleanSelector = _selectorWithoutAttr(selector);
|
||||
try {
|
||||
final document = html_parser.parse(fragment);
|
||||
final element = cleanSelector.isEmpty
|
||||
? document.body
|
||||
: document.querySelector(cleanSelector);
|
||||
if (element != null) {
|
||||
if (attr != null) return _clean(element.attributes[attr]);
|
||||
return _clean(element.text);
|
||||
}
|
||||
} catch (_) {
|
||||
// Fall through to the legacy regex parser for malformed selectors.
|
||||
}
|
||||
return _legacyCssText(fragment, selector);
|
||||
}
|
||||
|
||||
List<String> _legacyCssFragments(String selector) {
|
||||
final tag = _selectorTag(selector);
|
||||
if (tag == null) return const <String>[];
|
||||
final pattern =
|
||||
RegExp('<$tag\\b[^>]*>.*?</$tag>', caseSensitive: false, dotAll: true);
|
||||
return pattern
|
||||
.allMatches(body)
|
||||
.map((match) => match.group(0) ?? '')
|
||||
.where(_notEmpty)
|
||||
.toList();
|
||||
}
|
||||
|
||||
String _legacyCssText(String fragment, String selector) {
|
||||
final attr = RegExp(r'@([a-zA-Z0-9_-]+)$').firstMatch(selector)?.group(1);
|
||||
final cleanSelector = _selectorWithoutAttr(selector);
|
||||
final tag = _selectorTag(cleanSelector);
|
||||
final target = tag == null
|
||||
? fragment
|
||||
: RegExp('<$tag\\b[^>]*>.*?</$tag>', caseSensitive: false, dotAll: true)
|
||||
.firstMatch(fragment)
|
||||
?.group(0) ??
|
||||
'';
|
||||
if (attr != null) {
|
||||
return _clean(
|
||||
RegExp(
|
||||
"$attr=[\"']([^\"']+)[\"']",
|
||||
caseSensitive: false,
|
||||
).firstMatch(target)?.group(1),
|
||||
);
|
||||
}
|
||||
return _clean(target.replaceAll(RegExp(r'<[^>]+>'), ' '));
|
||||
}
|
||||
|
||||
String _selectorWithoutAttr(String selector) {
|
||||
return selector.replaceFirst(RegExp(r'@([a-zA-Z0-9_-]+)$'), '').trim();
|
||||
}
|
||||
|
||||
String? _selectorTag(String selector) {
|
||||
final match =
|
||||
RegExp(r'^[a-zA-Z][a-zA-Z0-9_-]*').firstMatch(selector.trim());
|
||||
return match?.group(0);
|
||||
}
|
||||
|
||||
String _normalizeRule(String? rule) {
|
||||
return rule?.split('&&').first.trim() ?? '';
|
||||
}
|
||||
|
||||
List<String> _ruleAlternatives(String? rule) {
|
||||
final normalized = _normalizeRule(rule);
|
||||
if (normalized.isEmpty) return const <String>[];
|
||||
return normalized
|
||||
.split('||')
|
||||
.map((item) => item.trim())
|
||||
.where((item) => item.isNotEmpty)
|
||||
.toList(growable: false);
|
||||
}
|
||||
|
||||
String _resolveKind(String rule, String? explicitKind) {
|
||||
final explicit = explicitKind?.trim().toLowerCase();
|
||||
if (explicit == 'json' || explicit == 'regex' || explicit == 'css') {
|
||||
return explicit!;
|
||||
}
|
||||
final lower = rule.toLowerCase();
|
||||
if (lower.startsWith('json:') || lower.startsWith(r'$.')) return 'json';
|
||||
if (lower.startsWith('regex:')) return 'regex';
|
||||
return 'css';
|
||||
}
|
||||
|
||||
String _stripPrefix(String rule) {
|
||||
final stripped = rule
|
||||
.replaceFirst(RegExp(r'^(json|regex):', caseSensitive: false), '')
|
||||
.trim();
|
||||
return stripped.replaceAllMapped(
|
||||
RegExp(r'''\[['"]([^'"]+)['"]\]'''),
|
||||
(match) => '.${match.group(1)}',
|
||||
);
|
||||
}
|
||||
|
||||
String _stringifyJsonValue(Object? value) {
|
||||
if (value == null) return '';
|
||||
if (value is String) return _clean(value);
|
||||
if (value is Map || value is List) return jsonEncode(value);
|
||||
return _clean(value.toString());
|
||||
}
|
||||
|
||||
bool _notEmpty(String value) => value.trim().isNotEmpty;
|
||||
|
||||
String _clean(String? value) {
|
||||
return (value ?? '')
|
||||
.replaceAll(RegExp(r'\s+'), ' ')
|
||||
.replaceAll(' ', ' ')
|
||||
.replaceAll('&', '&')
|
||||
.trim();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,111 @@
|
||||
import 'package:html/parser.dart' as html_parser;
|
||||
|
||||
import 'legado_rule_executor.dart';
|
||||
|
||||
class TocPaginationResolver {
|
||||
TocPaginationResolver(this._rules);
|
||||
|
||||
final LegadoRuleExecutor _rules;
|
||||
|
||||
String? resolveNextPage({
|
||||
required String currentUrl,
|
||||
required String currentHtml,
|
||||
required String? rule,
|
||||
required int pageIndex,
|
||||
}) {
|
||||
final raw = rule?.trim() ?? '';
|
||||
if (raw.isEmpty) return null;
|
||||
|
||||
if (raw.startsWith('!')) {
|
||||
return _applySlice(currentUrl, raw.substring(1));
|
||||
}
|
||||
if (raw.contains('{{page')) {
|
||||
return _resolve(currentUrl, renderPageTemplate(raw, pageIndex + 1));
|
||||
}
|
||||
if (RegExp(r'(?:[?&]|\b)(offset|start)=\d+').hasMatch(raw)) {
|
||||
return _resolve(currentUrl, _renderOffset(raw, pageIndex));
|
||||
}
|
||||
if (raw.startsWith('//')) {
|
||||
final value = _selectSimpleXPath(currentHtml, raw);
|
||||
return value == null ? null : _resolve(currentUrl, value);
|
||||
}
|
||||
if (_isSelector(raw) || raw.startsWith('<js>') || raw.startsWith('@js:')) {
|
||||
final value = _rules.select(
|
||||
currentHtml,
|
||||
currentHtml,
|
||||
raw,
|
||||
baseUrl: currentUrl,
|
||||
);
|
||||
return value.trim().isEmpty ? null : _resolve(currentUrl, value.trim());
|
||||
}
|
||||
return _resolve(currentUrl, renderPageTemplate(raw, pageIndex + 1));
|
||||
}
|
||||
|
||||
String renderPageTemplate(String template, int page) {
|
||||
return template
|
||||
.replaceAll('{{page+1}}', '${page + 1}')
|
||||
.replaceAll('{{page-1}}', '${page - 1}')
|
||||
.replaceAll('{{page}}', '$page')
|
||||
.replaceAll('{page+1}', '${page + 1}')
|
||||
.replaceAll('{page-1}', '${page - 1}')
|
||||
.replaceAll('{page}', '$page');
|
||||
}
|
||||
|
||||
String _renderOffset(String template, int pageIndex) {
|
||||
return template.replaceAllMapped(
|
||||
RegExp(r'(offset|start)=(\d+)'),
|
||||
(match) {
|
||||
final name = match.group(1)!;
|
||||
final initial = int.parse(match.group(2)!);
|
||||
return '$name=${initial + initial * pageIndex}';
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
String? _applySlice(String value, String expression) {
|
||||
final parts = expression.split(':');
|
||||
if (parts.length != 2) return null;
|
||||
final rawStart = int.tryParse(parts[0]) ?? 0;
|
||||
final rawEnd = parts[1].isEmpty ? null : int.tryParse(parts[1]);
|
||||
final start = (rawStart < 0 ? value.length + rawStart : rawStart)
|
||||
.clamp(0, value.length);
|
||||
final end = (rawEnd == null
|
||||
? value.length
|
||||
: rawEnd < 0
|
||||
? value.length + rawEnd
|
||||
: rawEnd)
|
||||
.clamp(start, value.length);
|
||||
return value.substring(start, end);
|
||||
}
|
||||
|
||||
String? _selectSimpleXPath(String html, String xpath) {
|
||||
final text = RegExp(
|
||||
r'''contains\s*\(\s*text\(\)\s*,\s*['"]([^'"]+)['"]\s*\)''',
|
||||
caseSensitive: false,
|
||||
).firstMatch(xpath)?.group(1);
|
||||
final attribute =
|
||||
RegExp(r'/@([a-zA-Z0-9_-]+)\s*$').firstMatch(xpath)?.group(1) ?? 'href';
|
||||
final document = html_parser.parse(html);
|
||||
for (final element in document.querySelectorAll('a')) {
|
||||
if (text == null || element.text.contains(text)) {
|
||||
final value = element.attributes[attribute];
|
||||
if (value?.trim().isNotEmpty == true) return value!.trim();
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
bool _isSelector(String value) {
|
||||
return value.startsWith('text.') ||
|
||||
value.startsWith('class.') ||
|
||||
value.startsWith('id.') ||
|
||||
value.startsWith('tag.') ||
|
||||
value.startsWith('@');
|
||||
}
|
||||
|
||||
String _resolve(String baseUrl, String value) {
|
||||
final parsed = Uri.tryParse(value);
|
||||
if (parsed?.hasScheme == true) return value;
|
||||
return Uri.parse(baseUrl).resolve(value).toString();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,208 @@
|
||||
import '../models/artwork.dart';
|
||||
|
||||
class MangaCollection {
|
||||
const MangaCollection({
|
||||
required this.id,
|
||||
required this.title,
|
||||
required this.author,
|
||||
required this.cover,
|
||||
required this.items,
|
||||
});
|
||||
|
||||
final String id;
|
||||
final String title;
|
||||
final String? author;
|
||||
final Artwork cover;
|
||||
final List<Artwork> items;
|
||||
|
||||
String get latestItemTitle => items.isEmpty ? '' : items.last.title;
|
||||
|
||||
int get readPageCount =>
|
||||
items.where((item) => item.lastViewedAt != null).length;
|
||||
|
||||
String get readProgressLabel =>
|
||||
readPageCount <= 0 ? '未开始' : '已读 $readPageCount / ${items.length} 页';
|
||||
|
||||
DateTime? get latestActivityAt {
|
||||
return items
|
||||
.map((item) => item.lastViewedAt ?? item.updatedAt ?? item.createdAt)
|
||||
.whereType<DateTime>()
|
||||
.fold<DateTime?>(
|
||||
null,
|
||||
(value, item) => value == null || item.isAfter(value) ? item : value,
|
||||
);
|
||||
}
|
||||
|
||||
String get itemTitlesPreview =>
|
||||
items.take(3).map((item) => item.title).join(' · ');
|
||||
|
||||
int get preferredStartIndex {
|
||||
var bestIndex = 0;
|
||||
DateTime? bestTime;
|
||||
for (var index = 0; index < items.length; index += 1) {
|
||||
final value = items[index].lastViewedAt;
|
||||
if (value == null) {
|
||||
continue;
|
||||
}
|
||||
if (bestTime == null || value.isAfter(bestTime)) {
|
||||
bestTime = value;
|
||||
bestIndex = index;
|
||||
}
|
||||
}
|
||||
return bestIndex;
|
||||
}
|
||||
}
|
||||
|
||||
List<MangaCollection> buildMangaCollections(List<Artwork> items) {
|
||||
final groups = <String, List<Artwork>>{};
|
||||
for (final item in items.where((item) => item.contentType == 'manga')) {
|
||||
final key = '${item.author ?? ''}::${normalizeMangaTitle(item.title)}';
|
||||
groups.putIfAbsent(key, () => <Artwork>[]).add(item);
|
||||
}
|
||||
final entries = groups.entries.map((entry) {
|
||||
final sortedItems = sortMangaItems(entry.value);
|
||||
final cover = sortedItems.first;
|
||||
return MangaCollection(
|
||||
id: entry.key,
|
||||
title: normalizeMangaTitle(cover.title),
|
||||
author: cover.author,
|
||||
cover: cover,
|
||||
items: sortedItems,
|
||||
);
|
||||
}).toList();
|
||||
entries.sort((a, b) {
|
||||
final aTime = a.latestActivityAt;
|
||||
final bTime = b.latestActivityAt;
|
||||
if (aTime != null && bTime != null) {
|
||||
return bTime.compareTo(aTime);
|
||||
}
|
||||
if (aTime != null) {
|
||||
return -1;
|
||||
}
|
||||
if (bTime != null) {
|
||||
return 1;
|
||||
}
|
||||
return a.title.compareTo(b.title);
|
||||
});
|
||||
return entries;
|
||||
}
|
||||
|
||||
MangaCollection? findMangaCollectionForArtwork(
|
||||
List<Artwork> items,
|
||||
Artwork artwork,
|
||||
) {
|
||||
for (final entry in buildMangaCollections(items)) {
|
||||
if (entry.items.any((item) => item.id == artwork.id)) {
|
||||
return entry;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
List<Artwork> sortMangaItems(Iterable<Artwork> items) {
|
||||
final sortedItems = [...items]..sort(compareMangaItems);
|
||||
return sortedItems;
|
||||
}
|
||||
|
||||
int compareMangaItems(Artwork a, Artwork b) {
|
||||
final aOrder = extractMangaItemOrder(a.title);
|
||||
final bOrder = extractMangaItemOrder(b.title);
|
||||
if (aOrder != bOrder) {
|
||||
return aOrder.compareTo(bOrder);
|
||||
}
|
||||
final aViewed = a.lastViewedAt;
|
||||
final bViewed = b.lastViewedAt;
|
||||
if (aViewed != null && bViewed != null) {
|
||||
return aViewed.compareTo(bViewed);
|
||||
}
|
||||
return a.title.compareTo(b.title);
|
||||
}
|
||||
|
||||
String normalizeMangaTitle(String title) {
|
||||
final trimmed = title.trim();
|
||||
final patterns = <RegExp>[
|
||||
RegExp(
|
||||
r'\s*[-_·•]\s*第?[0-9一二三四五六七八九十百千零两]+(?:话|章|卷|册|回|节|篇)?\s*$',
|
||||
caseSensitive: false,
|
||||
),
|
||||
RegExp(
|
||||
r'\s*第?[0-9一二三四五六七八九十百千零两]+(?:话|章|卷|册|回|节|篇)?\s*$',
|
||||
caseSensitive: false,
|
||||
),
|
||||
RegExp(r'\s*(?:ep|episode|chapter|part)\s*\d+\s*$', caseSensitive: false),
|
||||
RegExp(r'\s*#\d+\s*$', caseSensitive: false),
|
||||
RegExp(r'\s*(?:page|p)\s*\d+\s*$', caseSensitive: false),
|
||||
];
|
||||
var value = trimmed;
|
||||
for (final pattern in patterns) {
|
||||
value = value.replaceFirst(pattern, '').trim();
|
||||
}
|
||||
return value.isEmpty ? trimmed : value;
|
||||
}
|
||||
|
||||
int extractMangaItemOrder(String title) {
|
||||
final direct = RegExp(
|
||||
r'第?\s*([0-9]+|[一二三四五六七八九十百千零两]+)\s*(?:话|章|卷|册|回|节|篇)',
|
||||
caseSensitive: false,
|
||||
).firstMatch(title);
|
||||
if (direct != null) {
|
||||
return _parseMangaNumber(direct.group(1) ?? '') ?? 0;
|
||||
}
|
||||
final english = RegExp(
|
||||
r'(?:ep|episode|chapter|part|page|p)\s*(\d+)',
|
||||
caseSensitive: false,
|
||||
).firstMatch(title);
|
||||
if (english != null) {
|
||||
return int.tryParse(english.group(1) ?? '') ?? 0;
|
||||
}
|
||||
final hash = RegExp(r'#(\d+)').firstMatch(title);
|
||||
return int.tryParse(hash?.group(1) ?? '') ?? 0;
|
||||
}
|
||||
|
||||
int? _parseMangaNumber(String value) {
|
||||
final trimmed = value.trim();
|
||||
if (trimmed.isEmpty) {
|
||||
return null;
|
||||
}
|
||||
final direct = int.tryParse(trimmed);
|
||||
if (direct != null) {
|
||||
return direct;
|
||||
}
|
||||
const digits = {
|
||||
'零': 0,
|
||||
'一': 1,
|
||||
'二': 2,
|
||||
'两': 2,
|
||||
'三': 3,
|
||||
'四': 4,
|
||||
'五': 5,
|
||||
'六': 6,
|
||||
'七': 7,
|
||||
'八': 8,
|
||||
'九': 9,
|
||||
};
|
||||
const units = {
|
||||
'十': 10,
|
||||
'百': 100,
|
||||
'千': 1000,
|
||||
};
|
||||
var total = 0;
|
||||
var current = 0;
|
||||
for (final rune in trimmed.runes) {
|
||||
final char = String.fromCharCode(rune);
|
||||
if (digits.containsKey(char)) {
|
||||
current = digits[char]!;
|
||||
total += current;
|
||||
continue;
|
||||
}
|
||||
if (units.containsKey(char)) {
|
||||
final unit = units[char]!;
|
||||
if (current == 0) {
|
||||
current = 1;
|
||||
}
|
||||
total = total - current + current * unit;
|
||||
current = 0;
|
||||
}
|
||||
}
|
||||
return total == 0 ? null : total;
|
||||
}
|
||||
@@ -0,0 +1,240 @@
|
||||
import 'dart:convert';
|
||||
|
||||
import 'package:dio/dio.dart';
|
||||
|
||||
const mangaDefaultUserAgent =
|
||||
'Mozilla/5.0 (Linux; Android 13) AppleWebKit/537.36 Chrome/120 Mobile Safari/537.36';
|
||||
|
||||
class ImageCandidate {
|
||||
const ImageCandidate({
|
||||
required this.raw,
|
||||
required this.url,
|
||||
required this.isValid,
|
||||
this.reason,
|
||||
});
|
||||
|
||||
final String raw;
|
||||
final String? url;
|
||||
final bool isValid;
|
||||
final String? reason;
|
||||
}
|
||||
|
||||
class ParsedImageSpec {
|
||||
const ParsedImageSpec({required this.url, this.headers = const {}});
|
||||
final String url;
|
||||
final Map<String, String> headers;
|
||||
}
|
||||
|
||||
class PageImage {
|
||||
const PageImage({
|
||||
required this.index,
|
||||
required this.raw,
|
||||
required this.url,
|
||||
required this.headers,
|
||||
});
|
||||
|
||||
final int index;
|
||||
final String raw;
|
||||
final String url;
|
||||
final Map<String, String> headers;
|
||||
}
|
||||
|
||||
class ImageProbeResult {
|
||||
const ImageProbeResult({
|
||||
required this.url,
|
||||
required this.contentLength,
|
||||
required this.first16BytesHex,
|
||||
required this.looksLikeImage,
|
||||
this.statusCode,
|
||||
this.contentType,
|
||||
this.error,
|
||||
});
|
||||
|
||||
final String url;
|
||||
final int? statusCode;
|
||||
final String? contentType;
|
||||
final int contentLength;
|
||||
final String first16BytesHex;
|
||||
final bool looksLikeImage;
|
||||
final String? error;
|
||||
}
|
||||
|
||||
ParsedImageSpec splitLegadoImageSpec(String raw) {
|
||||
final normalizedRaw = raw.replaceAll('"', '"').replaceAll('&', '&');
|
||||
final index = normalizedRaw.indexOf(',{');
|
||||
if (index < 0) return ParsedImageSpec(url: normalizedRaw.trim());
|
||||
final headers = <String, String>{};
|
||||
try {
|
||||
final decoded = jsonDecode(normalizedRaw.substring(index + 1).trim());
|
||||
if (decoded is Map) {
|
||||
final value = decoded['headers'];
|
||||
final headerMap = value is String ? jsonDecode(value) : value;
|
||||
if (headerMap is Map) {
|
||||
headerMap.forEach((key, item) {
|
||||
headers[key.toString()] = item.toString();
|
||||
});
|
||||
}
|
||||
}
|
||||
} catch (_) {
|
||||
// A malformed optional header suffix must not discard a valid URL.
|
||||
}
|
||||
return ParsedImageSpec(
|
||||
url: normalizedRaw.substring(0, index).trim(),
|
||||
headers: headers,
|
||||
);
|
||||
}
|
||||
|
||||
String normalizeMangaImageUrl(String raw, String baseUrl) {
|
||||
var value = raw.trim().replaceAll(r'\/', '/').replaceAll(r'\u002F', '/');
|
||||
if (value.startsWith('//')) {
|
||||
final scheme = Uri.tryParse(baseUrl)?.scheme;
|
||||
value = '${scheme?.isNotEmpty == true ? scheme : 'https'}:$value';
|
||||
}
|
||||
return Uri.parse(baseUrl).resolve(value).toString();
|
||||
}
|
||||
|
||||
ImageCandidate validateImageCandidate(String raw, String baseUrl) {
|
||||
final parsed = splitLegadoImageSpec(raw);
|
||||
final value = parsed.url.trim();
|
||||
if (value.isEmpty) {
|
||||
return ImageCandidate(raw: raw, url: null, isValid: false, reason: 'empty');
|
||||
}
|
||||
if (value.toLowerCase().startsWith('data:')) {
|
||||
return ImageCandidate(
|
||||
raw: raw,
|
||||
url: null,
|
||||
isValid: false,
|
||||
reason: 'data-uri',
|
||||
);
|
||||
}
|
||||
final lower = value.toLowerCase();
|
||||
if (const ['loading', 'placeholder', 'logo', 'icon'].any(lower.contains)) {
|
||||
return ImageCandidate(
|
||||
raw: raw,
|
||||
url: value,
|
||||
isValid: false,
|
||||
reason: 'placeholder',
|
||||
);
|
||||
}
|
||||
try {
|
||||
final normalized = normalizeMangaImageUrl(value, baseUrl);
|
||||
final uri = Uri.tryParse(normalized);
|
||||
if (uri == null || !uri.hasScheme || uri.host.isEmpty) {
|
||||
return ImageCandidate(
|
||||
raw: raw,
|
||||
url: normalized,
|
||||
isValid: false,
|
||||
reason: 'invalid-url',
|
||||
);
|
||||
}
|
||||
return ImageCandidate(raw: raw, url: normalized, isValid: true);
|
||||
} catch (_) {
|
||||
return ImageCandidate(
|
||||
raw: raw,
|
||||
url: value,
|
||||
isValid: false,
|
||||
reason: 'invalid-url',
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
PageImage? buildPageImage({
|
||||
required String raw,
|
||||
required String chapterUrl,
|
||||
required int index,
|
||||
required Map<String, String> sourceHeaders,
|
||||
String? userAgent,
|
||||
}) {
|
||||
final candidate = validateImageCandidate(raw, chapterUrl);
|
||||
if (!candidate.isValid || candidate.url == null) return null;
|
||||
final parsed = splitLegadoImageSpec(raw);
|
||||
return PageImage(
|
||||
index: index,
|
||||
raw: raw,
|
||||
url: candidate.url!,
|
||||
headers: {
|
||||
...sourceHeaders,
|
||||
'User-Agent': userAgent?.trim().isNotEmpty == true
|
||||
? userAgent!.trim()
|
||||
: mangaDefaultUserAgent,
|
||||
'Referer': chapterUrl,
|
||||
...parsed.headers,
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
Future<ImageProbeResult> probeImage(Dio dio, PageImage image) async {
|
||||
try {
|
||||
final response = await dio.get<List<int>>(
|
||||
image.url,
|
||||
options: Options(
|
||||
responseType: ResponseType.bytes,
|
||||
headers: image.headers,
|
||||
validateStatus: (_) => true,
|
||||
),
|
||||
);
|
||||
final bytes = response.data ?? const <int>[];
|
||||
return ImageProbeResult(
|
||||
url: image.url,
|
||||
statusCode: response.statusCode,
|
||||
contentType: response.headers.value('content-type'),
|
||||
contentLength: bytes.length,
|
||||
first16BytesHex: bytes
|
||||
.take(16)
|
||||
.map((value) => value.toRadixString(16).padLeft(2, '0'))
|
||||
.join(),
|
||||
looksLikeImage: isImageMagic(bytes),
|
||||
);
|
||||
} catch (error) {
|
||||
return ImageProbeResult(
|
||||
url: image.url,
|
||||
contentLength: 0,
|
||||
first16BytesHex: '',
|
||||
looksLikeImage: false,
|
||||
error: error.toString(),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
bool isImageMagic(List<int> bytes) {
|
||||
if (bytes.length < 4) return false;
|
||||
if (bytes[0] == 0xFF && bytes[1] == 0xD8 && bytes[2] == 0xFF) {
|
||||
return true;
|
||||
}
|
||||
if (bytes[0] == 0x89 &&
|
||||
bytes[1] == 0x50 &&
|
||||
bytes[2] == 0x4E &&
|
||||
bytes[3] == 0x47) {
|
||||
return true;
|
||||
}
|
||||
if (bytes.length >= 12 &&
|
||||
bytes[0] == 0x52 &&
|
||||
bytes[1] == 0x49 &&
|
||||
bytes[2] == 0x46 &&
|
||||
bytes[3] == 0x46 &&
|
||||
bytes[8] == 0x57 &&
|
||||
bytes[9] == 0x45 &&
|
||||
bytes[10] == 0x42 &&
|
||||
bytes[11] == 0x50) {
|
||||
return true;
|
||||
}
|
||||
if (bytes[0] == 0x47 &&
|
||||
bytes[1] == 0x49 &&
|
||||
bytes[2] == 0x46 &&
|
||||
bytes[3] == 0x38) {
|
||||
return true;
|
||||
}
|
||||
return bytes[0] == 0x42 && bytes[1] == 0x4D;
|
||||
}
|
||||
|
||||
double? extractMangaChapterNumber(String title) {
|
||||
for (final pattern in <RegExp>[
|
||||
RegExp(r'第\s*(\d+(?:\.\d+)?)\s*[回话章节节]'),
|
||||
RegExp(r'\bch\.?\s*(\d+(?:\.\d+)?)', caseSensitive: false),
|
||||
RegExp(r'^\s*(\d+(?:\.\d+)?)\s*(?:话|回|章|节)?'),
|
||||
]) {
|
||||
final value = pattern.firstMatch(title)?.group(1);
|
||||
if (value != null) return double.tryParse(value);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
import 'legado_models.dart';
|
||||
|
||||
class OnlineContentCache {
|
||||
final _bookInfo = <String, OnlineBookInfo>{};
|
||||
final _toc = <String, List<OnlineChapter>>{};
|
||||
final _chapters = <String, OnlineChapterContent>{};
|
||||
|
||||
String _key(String sourceId, String url) => '$sourceId|$url';
|
||||
|
||||
OnlineBookInfo? getBookInfo(String sourceId, String url) =>
|
||||
_bookInfo[_key(sourceId, url)];
|
||||
void putBookInfo(String sourceId, String url, OnlineBookInfo value) =>
|
||||
_bookInfo[_key(sourceId, url)] = value;
|
||||
|
||||
List<OnlineChapter>? getToc(String sourceId, String url) =>
|
||||
_toc[_key(sourceId, url)];
|
||||
void putToc(String sourceId, String url, List<OnlineChapter> value) =>
|
||||
_toc[_key(sourceId, url)] = List.unmodifiable(value);
|
||||
|
||||
OnlineChapterContent? getChapter(String sourceId, String url) =>
|
||||
_chapters[_key(sourceId, url)];
|
||||
void putChapter(String sourceId, String url, OnlineChapterContent value) =>
|
||||
_chapters[_key(sourceId, url)] = value;
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
import 'dart:convert';
|
||||
|
||||
import 'package:shared_preferences/shared_preferences.dart';
|
||||
|
||||
import 'legado_models.dart';
|
||||
|
||||
class OnlineReadingHistory {
|
||||
static const _storageKey = 'online_reading_history_v1';
|
||||
static const _maxRecords = 50;
|
||||
|
||||
static Future<List<OnlineReadingRecord>> all() async {
|
||||
final prefs = await SharedPreferences.getInstance();
|
||||
final raw = prefs.getString(_storageKey);
|
||||
if (raw == null || raw.isEmpty) return const [];
|
||||
try {
|
||||
final decoded = jsonDecode(raw);
|
||||
if (decoded is! List) return const [];
|
||||
return decoded
|
||||
.whereType<Map>()
|
||||
.map((item) => OnlineReadingRecord.fromJson(
|
||||
Map<String, dynamic>.from(item),
|
||||
))
|
||||
.toList(growable: false);
|
||||
} on FormatException {
|
||||
return const [];
|
||||
}
|
||||
}
|
||||
|
||||
static Future<OnlineReadingRecord?> find(
|
||||
String sourceId,
|
||||
String detailUrl,
|
||||
) async {
|
||||
final records = await all();
|
||||
for (final record in records) {
|
||||
if (record.sourceId == sourceId && record.detailUrl == detailUrl) {
|
||||
return record;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
static Future<void> save(OnlineReadingRecord record) async {
|
||||
final records = (await all()).toList();
|
||||
records.removeWhere((item) =>
|
||||
item.sourceId == record.sourceId && item.detailUrl == record.detailUrl);
|
||||
records.insert(0, record);
|
||||
if (records.length > _maxRecords) {
|
||||
records.removeRange(_maxRecords, records.length);
|
||||
}
|
||||
final prefs = await SharedPreferences.getInstance();
|
||||
await prefs.setString(
|
||||
_storageKey,
|
||||
jsonEncode(records.map((item) => item.toJson()).toList()),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,108 @@
|
||||
import 'dart:convert';
|
||||
|
||||
import 'package:flutter/foundation.dart';
|
||||
import 'package:shared_preferences/shared_preferences.dart';
|
||||
|
||||
class OnlineShelfEntry {
|
||||
const OnlineShelfEntry({
|
||||
required this.sourceId,
|
||||
required this.sourceName,
|
||||
required this.title,
|
||||
required this.detailUrl,
|
||||
required this.savedAt,
|
||||
this.contentType = 'novel',
|
||||
this.author,
|
||||
this.coverUrl,
|
||||
});
|
||||
|
||||
final String sourceId;
|
||||
final String sourceName;
|
||||
final String title;
|
||||
final String? author;
|
||||
final String? coverUrl;
|
||||
final String detailUrl;
|
||||
final DateTime savedAt;
|
||||
final String contentType;
|
||||
|
||||
String get id => '$contentType|$sourceId|$detailUrl';
|
||||
bool get isManga => contentType == 'manga';
|
||||
bool get isNovel => !isManga;
|
||||
|
||||
Map<String, dynamic> toJson() => {
|
||||
'sourceId': sourceId,
|
||||
'sourceName': sourceName,
|
||||
'title': title,
|
||||
'author': author,
|
||||
'coverUrl': coverUrl,
|
||||
'detailUrl': detailUrl,
|
||||
'savedAt': savedAt.toIso8601String(),
|
||||
'contentType': contentType,
|
||||
};
|
||||
|
||||
factory OnlineShelfEntry.fromJson(Map<String, dynamic> json) =>
|
||||
OnlineShelfEntry(
|
||||
sourceId: json['sourceId']?.toString() ?? '',
|
||||
sourceName: json['sourceName']?.toString() ?? '',
|
||||
title: json['title']?.toString() ?? '未命名作品',
|
||||
author: json['author']?.toString(),
|
||||
coverUrl: json['coverUrl']?.toString(),
|
||||
detailUrl: json['detailUrl']?.toString() ?? '',
|
||||
savedAt: DateTime.tryParse(json['savedAt']?.toString() ?? '') ??
|
||||
DateTime.now(),
|
||||
contentType:
|
||||
json['contentType']?.toString() == 'manga' ? 'manga' : 'novel',
|
||||
);
|
||||
}
|
||||
|
||||
class OnlineShelfStore extends ChangeNotifier {
|
||||
static const _storageKey = 'online_novel_shelf_v1';
|
||||
final List<OnlineShelfEntry> _entries = [];
|
||||
bool _loaded = false;
|
||||
|
||||
List<OnlineShelfEntry> get entries => List.unmodifiable(_entries);
|
||||
|
||||
Future<void> load() async {
|
||||
if (_loaded) return;
|
||||
final prefs = await SharedPreferences.getInstance();
|
||||
final raw = prefs.getString(_storageKey);
|
||||
if (raw != null) {
|
||||
try {
|
||||
final decoded = jsonDecode(raw);
|
||||
if (decoded is List) {
|
||||
_entries.addAll(decoded.whereType<Map>().map(
|
||||
(item) => OnlineShelfEntry.fromJson(
|
||||
Map<String, dynamic>.from(item),
|
||||
),
|
||||
));
|
||||
}
|
||||
} catch (_) {
|
||||
// Keep the shelf usable even if an old local record is malformed.
|
||||
}
|
||||
}
|
||||
_loaded = true;
|
||||
notifyListeners();
|
||||
}
|
||||
|
||||
Future<void> save(OnlineShelfEntry entry) async {
|
||||
await load();
|
||||
_entries.removeWhere((item) => item.id == entry.id);
|
||||
_entries.insert(0, entry);
|
||||
await _persist();
|
||||
notifyListeners();
|
||||
}
|
||||
|
||||
Future<void> remove(String id) async {
|
||||
await load();
|
||||
_entries.removeWhere((item) => item.id == id);
|
||||
await _persist();
|
||||
notifyListeners();
|
||||
}
|
||||
|
||||
Future<void> _persist() async {
|
||||
final prefs = await SharedPreferences.getInstance();
|
||||
await prefs.setString(
|
||||
_storageKey,
|
||||
jsonEncode(_entries.map((item) => item.toJson()).toList()),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
import 'package:flutter_riverpod/flutter_riverpod.dart';
|
||||
|
||||
import 'api_client.dart';
|
||||
import 'legado_engine.dart';
|
||||
import 'session.dart';
|
||||
import 'source_health.dart';
|
||||
import 'source_manager.dart';
|
||||
import 'search_scheduler.dart';
|
||||
import 'online_shelf.dart';
|
||||
import 'unified_search.dart';
|
||||
|
||||
final sessionProvider = StateNotifierProvider<SessionController, SessionState>(
|
||||
(ref) => SessionController());
|
||||
|
||||
final apiClientProvider = Provider<SakuraApiClient>((ref) {
|
||||
ref.watch(sessionProvider);
|
||||
return ref.read(sessionProvider.notifier).client();
|
||||
});
|
||||
|
||||
final sourceManagerProvider = ChangeNotifierProvider<SourceManager>((ref) {
|
||||
final manager = SourceManager();
|
||||
manager.initializeIfFirstRun();
|
||||
return manager;
|
||||
});
|
||||
|
||||
final legadoEngineProvider = Provider<LegadoEngine>((ref) => LegadoEngine());
|
||||
|
||||
final sourceHealthProvider = Provider<SourceHealthStore>((ref) {
|
||||
final store = SourceHealthStore();
|
||||
store.load();
|
||||
ref.onDispose(store.flush);
|
||||
return store;
|
||||
});
|
||||
|
||||
final searchSchedulerProvider = Provider<SearchScheduler>((ref) {
|
||||
return SearchScheduler(
|
||||
ref.watch(legadoEngineProvider),
|
||||
ref.watch(sourceHealthProvider),
|
||||
);
|
||||
});
|
||||
|
||||
final onlineShelfProvider = ChangeNotifierProvider<OnlineShelfStore>((ref) {
|
||||
final store = OnlineShelfStore();
|
||||
store.load();
|
||||
return store;
|
||||
});
|
||||
|
||||
final unifiedSearchProvider = Provider<UnifiedSearch>((ref) {
|
||||
return UnifiedSearch(
|
||||
api: ref.watch(apiClientProvider),
|
||||
sourceManager: ref.watch(sourceManagerProvider),
|
||||
engine: ref.watch(legadoEngineProvider),
|
||||
scheduler: ref.watch(searchSchedulerProvider),
|
||||
);
|
||||
});
|
||||
@@ -0,0 +1,134 @@
|
||||
import 'dart:async';
|
||||
import 'dart:math';
|
||||
|
||||
import 'package:firebase_core/firebase_core.dart';
|
||||
import 'package:firebase_messaging/firebase_messaging.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:shared_preferences/shared_preferences.dart';
|
||||
|
||||
import '../pages/reminder_center_page.dart';
|
||||
import 'api_client.dart';
|
||||
|
||||
class PushNotifications {
|
||||
PushNotifications._();
|
||||
|
||||
static final GlobalKey<NavigatorState> navigatorKey =
|
||||
GlobalKey<NavigatorState>();
|
||||
|
||||
static const _deviceIdKey = 'sakura.push.deviceId';
|
||||
static StreamSubscription<String>? _tokenRefreshSubscription;
|
||||
static bool _initialized = false;
|
||||
static bool _available = false;
|
||||
|
||||
static Future<void> initialize() async {
|
||||
if (_initialized) {
|
||||
return;
|
||||
}
|
||||
try {
|
||||
await Firebase.initializeApp();
|
||||
_available = true;
|
||||
_initialized = true;
|
||||
await FirebaseMessaging.instance.requestPermission();
|
||||
FirebaseMessaging.onMessageOpenedApp.listen(_openReminderCenter);
|
||||
final initialMessage =
|
||||
await FirebaseMessaging.instance.getInitialMessage();
|
||||
if (initialMessage != null) {
|
||||
_openReminderCenter(initialMessage);
|
||||
}
|
||||
} catch (_) {
|
||||
_available = false;
|
||||
}
|
||||
}
|
||||
|
||||
static Future<void> registerWithSession({
|
||||
required String baseUrl,
|
||||
required String accessToken,
|
||||
}) async {
|
||||
if (accessToken.isEmpty) {
|
||||
return;
|
||||
}
|
||||
await initialize();
|
||||
if (!_available) {
|
||||
return;
|
||||
}
|
||||
|
||||
final token = await FirebaseMessaging.instance.getToken();
|
||||
if (token == null || token.isEmpty) {
|
||||
return;
|
||||
}
|
||||
final deviceId = await _deviceId();
|
||||
await SakuraApiClient(baseUrl: baseUrl, token: accessToken)
|
||||
.registerPushToken(
|
||||
deviceId: deviceId,
|
||||
platform: 'android',
|
||||
fcmToken: token,
|
||||
);
|
||||
|
||||
await _tokenRefreshSubscription?.cancel();
|
||||
_tokenRefreshSubscription =
|
||||
FirebaseMessaging.instance.onTokenRefresh.listen((newToken) async {
|
||||
if (newToken.isEmpty) {
|
||||
return;
|
||||
}
|
||||
try {
|
||||
final prefs = await SharedPreferences.getInstance();
|
||||
final latestBaseUrl = prefs.getString('sakura.baseUrl') ?? baseUrl;
|
||||
final latestAccessToken =
|
||||
prefs.getString('sakura.accessToken') ?? accessToken;
|
||||
if (latestAccessToken.isEmpty) {
|
||||
return;
|
||||
}
|
||||
await SakuraApiClient(baseUrl: latestBaseUrl, token: latestAccessToken)
|
||||
.registerPushToken(
|
||||
deviceId: deviceId,
|
||||
platform: 'android',
|
||||
fcmToken: newToken,
|
||||
);
|
||||
} catch (_) {
|
||||
// Token refresh can happen while the network is unavailable; the next
|
||||
// app start or login will register again.
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
static Future<void> unregisterWithSession({
|
||||
required String baseUrl,
|
||||
required String accessToken,
|
||||
}) async {
|
||||
await _tokenRefreshSubscription?.cancel();
|
||||
_tokenRefreshSubscription = null;
|
||||
if (accessToken.isEmpty) {
|
||||
return;
|
||||
}
|
||||
final deviceId = await _deviceId();
|
||||
try {
|
||||
await SakuraApiClient(baseUrl: baseUrl, token: accessToken)
|
||||
.unregisterPushToken(deviceId: deviceId);
|
||||
} catch (_) {
|
||||
// Logout should not be blocked by a transient network failure.
|
||||
}
|
||||
}
|
||||
|
||||
static void _openReminderCenter(RemoteMessage message) {
|
||||
final navigator = navigatorKey.currentState;
|
||||
if (navigator == null) {
|
||||
return;
|
||||
}
|
||||
navigator.push(
|
||||
MaterialPageRoute(builder: (_) => const ReminderCenterPage()),
|
||||
);
|
||||
}
|
||||
|
||||
static Future<String> _deviceId() async {
|
||||
final prefs = await SharedPreferences.getInstance();
|
||||
final existing = prefs.getString(_deviceIdKey);
|
||||
if (existing != null && existing.isNotEmpty) {
|
||||
return existing;
|
||||
}
|
||||
final random = Random.secure().nextInt(1 << 32).toRadixString(16);
|
||||
final generated =
|
||||
'android-${DateTime.now().microsecondsSinceEpoch.toRadixString(16)}-$random';
|
||||
await prefs.setString(_deviceIdKey, generated);
|
||||
return generated;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,185 @@
|
||||
import 'dart:async';
|
||||
|
||||
import 'legado_engine.dart';
|
||||
import 'legado_models.dart';
|
||||
import 'source_health.dart';
|
||||
|
||||
class OnlineSearchPhase {
|
||||
const OnlineSearchPhase({
|
||||
required this.name,
|
||||
this.items = const <UnifiedSearchResult>[],
|
||||
this.doneCount = 0,
|
||||
this.totalCount = 0,
|
||||
this.message,
|
||||
});
|
||||
|
||||
final String name;
|
||||
final List<UnifiedSearchResult> items;
|
||||
final int doneCount;
|
||||
final int totalCount;
|
||||
final String? message;
|
||||
}
|
||||
|
||||
class SearchScheduler {
|
||||
SearchScheduler(this._engine, this._health);
|
||||
|
||||
static const fastTimeout = Duration(seconds: 5);
|
||||
static const normalTimeout = Duration(seconds: 8);
|
||||
static const maxConcurrent = 6;
|
||||
|
||||
final LegadoEngine _engine;
|
||||
final SourceHealthStore _health;
|
||||
int _searchToken = 0;
|
||||
|
||||
void cancel() => _searchToken++;
|
||||
|
||||
Stream<OnlineSearchPhase> search(
|
||||
String keyword,
|
||||
List<LegadoSource> allSources,
|
||||
) async* {
|
||||
await _health.load();
|
||||
final token = ++_searchToken;
|
||||
final usable = allSources.toList()
|
||||
..sort((a, b) => _health.score(b.id).compareTo(_health.score(a.id)));
|
||||
if (usable.isEmpty) {
|
||||
yield const OnlineSearchPhase(
|
||||
name: 'error',
|
||||
message: '没有可用的在线书源,请到书源管理中检查。',
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
final fast =
|
||||
usable.where((source) => _health.score(source.id) >= 70).toList();
|
||||
final normal = usable.where((source) {
|
||||
final score = _health.score(source.id);
|
||||
return score >= 40 && score < 70;
|
||||
}).toList();
|
||||
final slow =
|
||||
usable.where((source) => _health.score(source.id) < 40).toList();
|
||||
final results = <UnifiedSearchResult>[];
|
||||
final seen = <String>{};
|
||||
var doneCount = 0;
|
||||
|
||||
yield OnlineSearchPhase(
|
||||
name: 'searching',
|
||||
totalCount: usable.length,
|
||||
message: '正在搜索 ${usable.length} 个源…',
|
||||
);
|
||||
|
||||
for (final stage in <(List<LegadoSource>, Duration, String)>[
|
||||
(fast, fastTimeout, 'fast'),
|
||||
(normal, normalTimeout, 'normal'),
|
||||
(slow, normalTimeout, 'slow'),
|
||||
]) {
|
||||
if (stage.$1.isEmpty) continue;
|
||||
if (stage.$3 == 'slow') {
|
||||
yield OnlineSearchPhase(
|
||||
name: 'pending_slow',
|
||||
items: List.unmodifiable(results),
|
||||
doneCount: doneCount,
|
||||
totalCount: usable.length,
|
||||
message: '${stage.$1.length} 个慢源正在后台搜索…',
|
||||
);
|
||||
}
|
||||
await for (final completed in _pool(
|
||||
stage.$1,
|
||||
keyword,
|
||||
timeout: stage.$2,
|
||||
token: token,
|
||||
)) {
|
||||
if (token != _searchToken) return;
|
||||
doneCount++;
|
||||
for (final item in completed.items) {
|
||||
final key = '${item.sourceId}|${item.detailUrl ?? item.title}';
|
||||
if (seen.add(key)) results.add(item);
|
||||
}
|
||||
yield OnlineSearchPhase(
|
||||
name: stage.$3 == 'slow' ? 'slow_append' : 'partial',
|
||||
items: List.unmodifiable(results),
|
||||
doneCount: doneCount,
|
||||
totalCount: usable.length,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
if (token != _searchToken) return;
|
||||
yield OnlineSearchPhase(
|
||||
name: 'complete',
|
||||
items: List.unmodifiable(results),
|
||||
doneCount: doneCount,
|
||||
totalCount: usable.length,
|
||||
);
|
||||
unawaited(_health.save());
|
||||
}
|
||||
|
||||
Stream<_CompletedSource> _pool(
|
||||
List<LegadoSource> sources,
|
||||
String keyword, {
|
||||
required Duration timeout,
|
||||
required int token,
|
||||
}) async* {
|
||||
final pending = sources.toList();
|
||||
final running = <int, Future<_CompletedSlot>>{};
|
||||
var slotId = 0;
|
||||
while (pending.isNotEmpty || running.isNotEmpty) {
|
||||
while (running.length < maxConcurrent && pending.isNotEmpty) {
|
||||
final source = pending.removeAt(0);
|
||||
final id = slotId++;
|
||||
running[id] = _searchOne(source, keyword, timeout, token: token)
|
||||
.then((value) => _CompletedSlot(id, value));
|
||||
}
|
||||
if (running.isEmpty) break;
|
||||
final completed = await Future.any(running.values);
|
||||
running.remove(completed.slotId);
|
||||
if (completed.result != null) yield completed.result!;
|
||||
}
|
||||
}
|
||||
|
||||
Future<_CompletedSource?> _searchOne(
|
||||
LegadoSource source,
|
||||
String keyword,
|
||||
Duration timeout, {
|
||||
required int token,
|
||||
}) async {
|
||||
if (token != _searchToken) return null;
|
||||
final stopwatch = Stopwatch()..start();
|
||||
try {
|
||||
final items = await _engine.search(source, keyword).timeout(timeout);
|
||||
if (token != _searchToken) return null;
|
||||
stopwatch.stop();
|
||||
_health.recordSuccess(source.id, stopwatch.elapsedMilliseconds);
|
||||
return _CompletedSource(source.id, items);
|
||||
} on TimeoutException {
|
||||
_health.recordFailure(source.id, timeout: true);
|
||||
return _CompletedSource(source.id, [
|
||||
UnifiedSearchResult.error(
|
||||
sourceId: source.id,
|
||||
sourceName: source.name,
|
||||
errorMessage: '连接超时,已降低该书源的搜索优先级。',
|
||||
),
|
||||
]);
|
||||
} catch (error) {
|
||||
_health.recordFailure(source.id);
|
||||
return _CompletedSource(source.id, [
|
||||
UnifiedSearchResult.error(
|
||||
sourceId: source.id,
|
||||
sourceName: source.name,
|
||||
errorMessage: error.toString(),
|
||||
),
|
||||
]);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
class _CompletedSource {
|
||||
const _CompletedSource(this.sourceId, this.items);
|
||||
final String sourceId;
|
||||
final List<UnifiedSearchResult> items;
|
||||
}
|
||||
|
||||
class _CompletedSlot {
|
||||
const _CompletedSlot(this.slotId, this.result);
|
||||
final int slotId;
|
||||
final _CompletedSource? result;
|
||||
}
|
||||
@@ -0,0 +1,304 @@
|
||||
import 'package:dio/dio.dart';
|
||||
import 'package:flutter_riverpod/flutter_riverpod.dart';
|
||||
import 'package:shared_preferences/shared_preferences.dart';
|
||||
|
||||
import 'api_client.dart';
|
||||
import 'push_notifications.dart';
|
||||
|
||||
class SessionState {
|
||||
const SessionState({
|
||||
required this.baseUrl,
|
||||
required this.accessToken,
|
||||
this.refreshToken = '',
|
||||
this.username = '',
|
||||
this.loading = false,
|
||||
this.error,
|
||||
});
|
||||
|
||||
final String baseUrl;
|
||||
final String accessToken;
|
||||
final String refreshToken;
|
||||
final String username;
|
||||
final bool loading;
|
||||
final String? error;
|
||||
|
||||
bool get signedIn => accessToken.isNotEmpty;
|
||||
|
||||
SessionState copyWith({
|
||||
String? baseUrl,
|
||||
String? accessToken,
|
||||
String? refreshToken,
|
||||
String? username,
|
||||
bool? loading,
|
||||
String? error,
|
||||
}) {
|
||||
return SessionState(
|
||||
baseUrl: baseUrl ?? this.baseUrl,
|
||||
accessToken: accessToken ?? this.accessToken,
|
||||
refreshToken: refreshToken ?? this.refreshToken,
|
||||
username: username ?? this.username,
|
||||
loading: loading ?? this.loading,
|
||||
error: error,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class SessionController extends StateNotifier<SessionState> {
|
||||
SessionController()
|
||||
: super(const SessionState(
|
||||
baseUrl: defaultCloudApi, accessToken: '', loading: true)) {
|
||||
_load();
|
||||
}
|
||||
|
||||
static const _baseUrlKey = 'sakura.baseUrl';
|
||||
static const _accessTokenKey = 'sakura.accessToken';
|
||||
static const _refreshTokenKey = 'sakura.refreshToken';
|
||||
static const _usernameKey = 'sakura.username';
|
||||
static const _oldDefaultCloudApi = 'http://api.kunkunxiaomao.top:8000';
|
||||
|
||||
Future<void> _load() async {
|
||||
final prefs = await SharedPreferences.getInstance();
|
||||
final savedBaseUrl = prefs.getString(_baseUrlKey);
|
||||
final baseUrl = normalizeCloudBaseUrl(
|
||||
savedBaseUrl == _oldDefaultCloudApi ? defaultCloudApi : savedBaseUrl ?? defaultCloudApi,
|
||||
);
|
||||
await prefs.setString(_baseUrlKey, baseUrl);
|
||||
final accessToken = prefs.getString(_accessTokenKey) ?? '';
|
||||
final refreshToken = prefs.getString(_refreshTokenKey) ?? '';
|
||||
final validated = await _validateStoredSession(
|
||||
baseUrl: baseUrl,
|
||||
accessToken: accessToken,
|
||||
refreshToken: refreshToken,
|
||||
);
|
||||
state = SessionState(
|
||||
baseUrl: baseUrl,
|
||||
accessToken: validated?.accessToken ?? '',
|
||||
refreshToken: validated?.refreshToken ?? '',
|
||||
username: validated?.username ?? '',
|
||||
);
|
||||
if (state.signedIn) {
|
||||
await PushNotifications.registerWithSession(
|
||||
baseUrl: state.baseUrl,
|
||||
accessToken: state.accessToken,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
SakuraApiClient client() => SakuraApiClient(
|
||||
baseUrl: state.baseUrl,
|
||||
token: state.accessToken,
|
||||
refreshToken: state.refreshToken,
|
||||
onTokensRefreshed: _storeRefreshedTokens,
|
||||
);
|
||||
|
||||
Future<void> saveServer(String baseUrl) async {
|
||||
final normalized = normalizeCloudBaseUrl(baseUrl);
|
||||
final prefs = await SharedPreferences.getInstance();
|
||||
await prefs.setString(_baseUrlKey, normalized);
|
||||
state = state.copyWith(baseUrl: normalized, error: null);
|
||||
}
|
||||
|
||||
Future<void> login(String usernameOrEmail, String password) async {
|
||||
state = state.copyWith(loading: true, error: null);
|
||||
try {
|
||||
final api = SakuraApiClient(baseUrl: state.baseUrl);
|
||||
final tokens = await api.login(usernameOrEmail, password);
|
||||
final accessToken = tokens['access_token']?.toString() ?? '';
|
||||
final refreshToken = tokens['refresh_token']?.toString() ?? '';
|
||||
final prefs = await SharedPreferences.getInstance();
|
||||
await _clearAuthPrefs(prefs);
|
||||
final authedApi =
|
||||
SakuraApiClient(baseUrl: state.baseUrl, token: accessToken);
|
||||
final me = await authedApi.me();
|
||||
final username = me['username']?.toString() ?? '';
|
||||
if (username.isEmpty) {
|
||||
throw Exception('登录成功但无法获取用户身份信息。');
|
||||
}
|
||||
await prefs.setString(_accessTokenKey, accessToken);
|
||||
await prefs.setString(_refreshTokenKey, refreshToken);
|
||||
await prefs.setString(_usernameKey, username);
|
||||
state = state.copyWith(
|
||||
accessToken: accessToken,
|
||||
refreshToken: refreshToken,
|
||||
username: username,
|
||||
loading: false,
|
||||
error: null,
|
||||
);
|
||||
await PushNotifications.registerWithSession(
|
||||
baseUrl: state.baseUrl,
|
||||
accessToken: accessToken,
|
||||
);
|
||||
} catch (error) {
|
||||
state = state.copyWith(loading: false, error: _friendlyError(error));
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> register(String username, String email, String password) async {
|
||||
state = state.copyWith(loading: true, error: null);
|
||||
try {
|
||||
final api = SakuraApiClient(baseUrl: state.baseUrl);
|
||||
await api.register(username, email, password);
|
||||
state = state.copyWith(loading: false, error: null);
|
||||
} catch (error) {
|
||||
state = state.copyWith(loading: false, error: _friendlyError(error));
|
||||
rethrow;
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> logout() async {
|
||||
// 不调用 /api/v1/auth/logout,避免手机退出时吊销 exe 端 token
|
||||
try {
|
||||
await PushNotifications.unregisterWithSession(
|
||||
baseUrl: state.baseUrl,
|
||||
accessToken: state.accessToken,
|
||||
);
|
||||
} catch (_) {
|
||||
// 推送注销失败不影响本地退出
|
||||
}
|
||||
|
||||
final prefs = await SharedPreferences.getInstance();
|
||||
await _clearAuthPrefs(prefs);
|
||||
|
||||
state = state.copyWith(
|
||||
accessToken: '',
|
||||
refreshToken: '',
|
||||
username: '',
|
||||
error: null,
|
||||
);
|
||||
}
|
||||
|
||||
Future<_ValidatedSession?> _validateStoredSession({
|
||||
required String baseUrl,
|
||||
required String accessToken,
|
||||
required String refreshToken,
|
||||
}) async {
|
||||
if (accessToken.isEmpty) {
|
||||
return null;
|
||||
}
|
||||
final prefs = await SharedPreferences.getInstance();
|
||||
try {
|
||||
var currentAccessToken = accessToken;
|
||||
var currentRefreshToken = refreshToken;
|
||||
var api = SakuraApiClient(baseUrl: baseUrl, token: currentAccessToken);
|
||||
Map<String, dynamic> me;
|
||||
try {
|
||||
me = await api.me();
|
||||
} on DioException catch (error) {
|
||||
if (error.response?.statusCode != 401 || currentRefreshToken.isEmpty) {
|
||||
rethrow;
|
||||
}
|
||||
final tokens = await api.refresh(currentRefreshToken);
|
||||
currentAccessToken = tokens['access_token']?.toString() ?? '';
|
||||
currentRefreshToken = tokens['refresh_token']?.toString() ?? '';
|
||||
if (currentAccessToken.isEmpty || currentRefreshToken.isEmpty) {
|
||||
throw StateError('Refresh response did not contain a token pair');
|
||||
}
|
||||
api = SakuraApiClient(baseUrl: baseUrl, token: currentAccessToken);
|
||||
me = await api.me();
|
||||
await prefs.setString(_accessTokenKey, currentAccessToken);
|
||||
await prefs.setString(_refreshTokenKey, currentRefreshToken);
|
||||
}
|
||||
|
||||
final savedUsername = prefs.getString(_usernameKey) ?? '';
|
||||
final actualUsername = me['username']?.toString() ?? '';
|
||||
|
||||
if (actualUsername.isEmpty) {
|
||||
return _ValidatedSession(
|
||||
accessToken: accessToken,
|
||||
refreshToken: refreshToken,
|
||||
username: savedUsername,
|
||||
);
|
||||
}
|
||||
|
||||
// 如果刷新后返回了 sakura/其他账号,不覆盖本地账号
|
||||
if (savedUsername.isNotEmpty && actualUsername != savedUsername) {
|
||||
return _ValidatedSession(
|
||||
accessToken: accessToken,
|
||||
refreshToken: refreshToken,
|
||||
username: savedUsername,
|
||||
);
|
||||
}
|
||||
|
||||
await prefs.setString(_usernameKey, actualUsername);
|
||||
return _ValidatedSession(
|
||||
accessToken: currentAccessToken,
|
||||
refreshToken: currentRefreshToken,
|
||||
username: actualUsername,
|
||||
);
|
||||
} catch (_) {
|
||||
await _clearAuthPrefs(prefs);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> _clearAuthPrefs(SharedPreferences prefs) async {
|
||||
await prefs.remove(_accessTokenKey);
|
||||
await prefs.remove(_refreshTokenKey);
|
||||
await prefs.remove(_usernameKey);
|
||||
}
|
||||
|
||||
Future<void> _storeRefreshedTokens(
|
||||
String accessToken,
|
||||
String refreshToken,
|
||||
) async {
|
||||
final prefs = await SharedPreferences.getInstance();
|
||||
await prefs.setString(_accessTokenKey, accessToken);
|
||||
await prefs.setString(_refreshTokenKey, refreshToken);
|
||||
state = state.copyWith(
|
||||
accessToken: accessToken,
|
||||
refreshToken: refreshToken,
|
||||
error: null,
|
||||
);
|
||||
}
|
||||
|
||||
void clearError() {
|
||||
state = state.copyWith(error: null);
|
||||
}
|
||||
|
||||
String _friendlyError(Object error) {
|
||||
if (error is DioException) {
|
||||
final data = error.response?.data;
|
||||
if (data is Map<String, dynamic>) {
|
||||
final detail = data['detail']?.toString();
|
||||
final message = data['message']?.toString();
|
||||
final text = (detail?.isNotEmpty ?? false)
|
||||
? detail!
|
||||
: (message?.isNotEmpty ?? false)
|
||||
? message!
|
||||
: '';
|
||||
if (text.isNotEmpty) {
|
||||
final normalized = text.toLowerCase();
|
||||
if (normalized.contains('internal server error')) {
|
||||
return '服务器暂时开小差了,请稍后再试。';
|
||||
}
|
||||
return text;
|
||||
}
|
||||
}
|
||||
if (error.type == DioExceptionType.connectionError ||
|
||||
error.type == DioExceptionType.connectionTimeout ||
|
||||
error.type == DioExceptionType.receiveTimeout) {
|
||||
return '无法连接服务器,请检查网络状态。';
|
||||
}
|
||||
final statusCode = error.response?.statusCode;
|
||||
if (statusCode == 500) {
|
||||
return '服务器暂时开小差了,请稍后再试。';
|
||||
}
|
||||
if (statusCode != null) {
|
||||
return '请求失败(HTTP $statusCode),请稍后重试。';
|
||||
}
|
||||
}
|
||||
return '操作失败,请稍后重试。';
|
||||
}
|
||||
}
|
||||
|
||||
class _ValidatedSession {
|
||||
const _ValidatedSession({
|
||||
required this.accessToken,
|
||||
required this.refreshToken,
|
||||
required this.username,
|
||||
});
|
||||
|
||||
final String accessToken;
|
||||
final String refreshToken;
|
||||
final String username;
|
||||
}
|
||||
@@ -0,0 +1,141 @@
|
||||
import 'dart:async';
|
||||
import 'dart:convert';
|
||||
|
||||
import 'package:shared_preferences/shared_preferences.dart';
|
||||
|
||||
class SourceHealth {
|
||||
SourceHealth({required this.sourceId});
|
||||
|
||||
final String sourceId;
|
||||
int successCount = 0;
|
||||
int failCount = 0;
|
||||
int timeoutCount = 0;
|
||||
int totalLatencyMs = 0;
|
||||
DateTime? lastSuccessAt;
|
||||
DateTime? lastFailAt;
|
||||
int consecutiveFails = 0;
|
||||
|
||||
bool get isUsable {
|
||||
if (consecutiveFails >= 5) {
|
||||
final last = lastFailAt;
|
||||
return last != null && DateTime.now().difference(last).inHours >= 1;
|
||||
}
|
||||
return !(failCount >= 5 && successCount == 0);
|
||||
}
|
||||
|
||||
double get score {
|
||||
final latest = lastSuccessAt ?? lastFailAt;
|
||||
final decay =
|
||||
latest != null && DateTime.now().difference(latest).inDays >= 7
|
||||
? 0.5
|
||||
: 1.0;
|
||||
final total = successCount + failCount + timeoutCount;
|
||||
if (total == 0) return 50 * decay;
|
||||
var value = 60.0 * successCount / total;
|
||||
if (successCount > 0 && totalLatencyMs > 0) {
|
||||
final average = totalLatencyMs / successCount;
|
||||
if (average < 500) {
|
||||
value += 25;
|
||||
} else if (average < 2000) {
|
||||
value += 25 * (1 - (average - 500) / 1500);
|
||||
}
|
||||
}
|
||||
if (lastSuccessAt != null) {
|
||||
final hours = DateTime.now().difference(lastSuccessAt!).inHours;
|
||||
if (hours < 1) {
|
||||
value += 15;
|
||||
} else if (hours < 24) {
|
||||
value += 15 * (1 - hours / 24);
|
||||
}
|
||||
}
|
||||
return (value * decay).clamp(0, 100);
|
||||
}
|
||||
|
||||
void recordSuccess(int latencyMs) {
|
||||
successCount++;
|
||||
totalLatencyMs += latencyMs;
|
||||
lastSuccessAt = DateTime.now();
|
||||
consecutiveFails = 0;
|
||||
}
|
||||
|
||||
void recordFailure({bool timeout = false}) {
|
||||
timeout ? timeoutCount++ : failCount++;
|
||||
lastFailAt = DateTime.now();
|
||||
consecutiveFails++;
|
||||
}
|
||||
|
||||
Map<String, dynamic> toJson() => {
|
||||
'sourceId': sourceId,
|
||||
'successCount': successCount,
|
||||
'failCount': failCount,
|
||||
'timeoutCount': timeoutCount,
|
||||
'totalLatencyMs': totalLatencyMs,
|
||||
'lastSuccessAt': lastSuccessAt?.toIso8601String(),
|
||||
'lastFailAt': lastFailAt?.toIso8601String(),
|
||||
'consecutiveFails': consecutiveFails,
|
||||
};
|
||||
|
||||
factory SourceHealth.fromJson(Map<String, dynamic> json) {
|
||||
return SourceHealth(sourceId: json['sourceId']?.toString() ?? '')
|
||||
..successCount = (json['successCount'] as num?)?.toInt() ?? 0
|
||||
..failCount = (json['failCount'] as num?)?.toInt() ?? 0
|
||||
..timeoutCount = (json['timeoutCount'] as num?)?.toInt() ?? 0
|
||||
..totalLatencyMs = (json['totalLatencyMs'] as num?)?.toInt() ?? 0
|
||||
..lastSuccessAt =
|
||||
DateTime.tryParse(json['lastSuccessAt']?.toString() ?? '')
|
||||
..lastFailAt = DateTime.tryParse(json['lastFailAt']?.toString() ?? '')
|
||||
..consecutiveFails = (json['consecutiveFails'] as num?)?.toInt() ?? 0;
|
||||
}
|
||||
}
|
||||
|
||||
class SourceHealthStore {
|
||||
static const _storageKey = 'source_health_v1';
|
||||
final Map<String, SourceHealth> _data = {};
|
||||
Timer? _saveTimer;
|
||||
bool _loaded = false;
|
||||
|
||||
Future<void> load() async {
|
||||
if (_loaded) return;
|
||||
final prefs = await SharedPreferences.getInstance();
|
||||
for (final raw in prefs.getStringList(_storageKey) ?? const <String>[]) {
|
||||
try {
|
||||
final health = SourceHealth.fromJson(
|
||||
Map<String, dynamic>.from(jsonDecode(raw) as Map),
|
||||
);
|
||||
if (health.sourceId.isNotEmpty) _data[health.sourceId] = health;
|
||||
} catch (_) {
|
||||
// One corrupt record must not discard health data for other sources.
|
||||
}
|
||||
}
|
||||
_loaded = true;
|
||||
}
|
||||
|
||||
SourceHealth health(String id) =>
|
||||
_data.putIfAbsent(id, () => SourceHealth(sourceId: id));
|
||||
bool isUsable(String id) => health(id).isUsable;
|
||||
double score(String id) => health(id).score;
|
||||
void recordSuccess(String id, int latencyMs) =>
|
||||
health(id).recordSuccess(latencyMs);
|
||||
void recordFailure(String id, {bool timeout = false}) =>
|
||||
health(id).recordFailure(timeout: timeout);
|
||||
|
||||
void resetAll() {
|
||||
for (final item in _data.values) {
|
||||
item.consecutiveFails = 0;
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> save() async {
|
||||
_saveTimer?.cancel();
|
||||
_saveTimer = Timer(const Duration(seconds: 2), flush);
|
||||
}
|
||||
|
||||
Future<void> flush() async {
|
||||
_saveTimer?.cancel();
|
||||
final prefs = await SharedPreferences.getInstance();
|
||||
await prefs.setStringList(
|
||||
_storageKey,
|
||||
_data.values.map((item) => jsonEncode(item.toJson())).toList(),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,434 @@
|
||||
import 'dart:async';
|
||||
import 'dart:convert';
|
||||
|
||||
import 'package:dio/dio.dart';
|
||||
import 'package:flutter/foundation.dart';
|
||||
import 'package:shared_preferences/shared_preferences.dart';
|
||||
|
||||
import 'legado_engine.dart';
|
||||
import 'legado_models.dart';
|
||||
|
||||
class SourceManager extends ChangeNotifier {
|
||||
SourceManager({LegadoEngine? engine, Dio? http})
|
||||
: _engine = engine ?? LegadoEngine(),
|
||||
_http = http ??
|
||||
Dio(
|
||||
BaseOptions(
|
||||
connectTimeout: LegadoEngine.perSourceTimeout,
|
||||
receiveTimeout: LegadoEngine.perSourceTimeout,
|
||||
),
|
||||
);
|
||||
|
||||
static const _sourcesKey = 'legado_sources_v1';
|
||||
static const _initializedKey = 'source_manager_initialized_v1';
|
||||
static const _subscriptionsKey = 'legado_subscription_urls_v1';
|
||||
static const _lastSubscriptionUpdateKey =
|
||||
'legado_last_subscription_update_v1';
|
||||
|
||||
// P0: do not ship third-party repository URLs or placeholder sources.
|
||||
static const List<SourceRepo> builtinRepos = <SourceRepo>[];
|
||||
|
||||
final LegadoEngine _engine;
|
||||
final Dio _http;
|
||||
final List<LegadoSource> _sources = <LegadoSource>[];
|
||||
final List<SourceCheckResult> _lastChecks = <SourceCheckResult>[];
|
||||
Timer? _autoUpdateTimer;
|
||||
bool _loaded = false;
|
||||
bool _busy = false;
|
||||
String? _message;
|
||||
DateTime? _lastSubscriptionUpdate;
|
||||
|
||||
List<LegadoSource> get sources => List.unmodifiable(_sources);
|
||||
List<LegadoSource> get enabledSources =>
|
||||
_sources.where((source) => source.enabled).toList(growable: false);
|
||||
List<LegadoSource> get enabledNovelSources =>
|
||||
enabledSources.where((source) => source.isNovel).toList(growable: false);
|
||||
List<LegadoSource> get enabledMangaSources =>
|
||||
enabledSources.where((source) => source.isManga).toList(growable: false);
|
||||
bool get loaded => _loaded;
|
||||
bool get busy => _busy;
|
||||
String? get message => _message;
|
||||
DateTime? get lastSubscriptionUpdate => _lastSubscriptionUpdate;
|
||||
List<SourceCheckResult> get lastChecks => List.unmodifiable(_lastChecks);
|
||||
|
||||
LegadoSource? sourceById(String sourceId) {
|
||||
for (final source in _sources) {
|
||||
if (source.id == sourceId) return source;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
SourceCompatInfo compatibilityFor(LegadoSource source) {
|
||||
final rules = <String?>[
|
||||
source.searchUrl,
|
||||
source.searchListRule,
|
||||
source.searchNameRule,
|
||||
source.searchAuthorRule,
|
||||
source.searchCoverRule,
|
||||
source.searchDetailRule,
|
||||
source.bookInfoNameRule,
|
||||
source.bookInfoAuthorRule,
|
||||
source.bookInfoCoverRule,
|
||||
source.bookInfoIntroRule,
|
||||
source.bookInfoTocRule,
|
||||
source.tocUrl,
|
||||
source.tocListRule,
|
||||
source.tocNameRule,
|
||||
source.tocUrlRule,
|
||||
source.tocNextPageRule,
|
||||
source.contentRule,
|
||||
source.contentNextRule,
|
||||
source.contentPrevRule,
|
||||
].whereType<String>().toList(growable: false);
|
||||
final allRules = rules.join('\n').toLowerCase();
|
||||
final hasJs = allRules.contains('@js') || allRules.contains('<js>');
|
||||
final hasPutGet = allRules.contains('@put') || allRules.contains('@get');
|
||||
final searchOk = source.searchUrl?.trim().isNotEmpty == true &&
|
||||
source.searchListRule?.trim().isNotEmpty == true;
|
||||
final bookInfoOk = source.bookInfoNameRule?.trim().isNotEmpty == true ||
|
||||
source.bookInfoTocRule?.trim().isNotEmpty == true;
|
||||
final tocOk = source.tocListRule?.trim().isNotEmpty == true &&
|
||||
source.tocUrlRule?.trim().isNotEmpty == true;
|
||||
final contentOk = source.contentRule?.trim().isNotEmpty == true;
|
||||
final warnings = <String>[
|
||||
if (!searchOk) '搜索规则不完整',
|
||||
if (!bookInfoOk) '详情规则不完整',
|
||||
if (!tocOk) '目录规则不完整',
|
||||
if (!contentOk) '正文规则不完整',
|
||||
if (allRules.contains('java.ajax')) 'JS 规则请求外部网络,安全沙箱会拒绝',
|
||||
if (allRules.contains('org.jsoup')) 'JS 规则依赖 Legado Java DOM 桥接',
|
||||
];
|
||||
final method = source.searchMethod?.trim().toUpperCase();
|
||||
late final SourceCompatLevel level;
|
||||
if (!searchOk && !contentOk) {
|
||||
level = SourceCompatLevel.broken;
|
||||
} else if (hasJs) {
|
||||
level = SourceCompatLevel.needsJs;
|
||||
} else if (hasPutGet || !bookInfoOk || !tocOk || !contentOk) {
|
||||
level = SourceCompatLevel.partial;
|
||||
} else if (method == 'POST') {
|
||||
level = SourceCompatLevel.needsPost;
|
||||
} else if (source.headers.isNotEmpty) {
|
||||
level = SourceCompatLevel.needsHeaders;
|
||||
} else {
|
||||
level = SourceCompatLevel.full;
|
||||
}
|
||||
return SourceCompatInfo(
|
||||
level: level,
|
||||
searchOk: searchOk,
|
||||
bookInfoOk: bookInfoOk,
|
||||
tocOk: tocOk,
|
||||
contentOk: contentOk,
|
||||
hasJsRule: hasJs,
|
||||
hasPutGet: hasPutGet,
|
||||
warnings: warnings,
|
||||
);
|
||||
}
|
||||
|
||||
Future<void> load() async {
|
||||
if (_loaded) return;
|
||||
final prefs = await SharedPreferences.getInstance();
|
||||
_lastSubscriptionUpdate = DateTime.tryParse(
|
||||
prefs.getString(_lastSubscriptionUpdateKey) ?? '',
|
||||
);
|
||||
final raw = prefs.getString(_sourcesKey);
|
||||
if (raw != null && raw.isNotEmpty) {
|
||||
final decoded = jsonDecode(raw);
|
||||
if (decoded is List) {
|
||||
_sources
|
||||
..clear()
|
||||
..addAll(
|
||||
decoded.whereType<Map>().map(
|
||||
(item) => LegadoSource.fromJson(
|
||||
Map<String, dynamic>.from(item),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
_loaded = true;
|
||||
notifyListeners();
|
||||
}
|
||||
|
||||
Future<void> initializeIfFirstRun() async {
|
||||
await load();
|
||||
final prefs = await SharedPreferences.getInstance();
|
||||
if (prefs.getBool(_initializedKey) != true) {
|
||||
await prefs.setBool(_initializedKey, true);
|
||||
_message = '当前没有可用书源,请从你信任的仓库导入。';
|
||||
notifyListeners();
|
||||
}
|
||||
startAutoUpdateTimer();
|
||||
await checkSubscriptionUpdatesIfDue();
|
||||
}
|
||||
|
||||
void startAutoUpdateTimer() {
|
||||
_autoUpdateTimer ??= Timer.periodic(
|
||||
const Duration(hours: 6),
|
||||
(_) => checkSubscriptionUpdatesIfDue(),
|
||||
);
|
||||
}
|
||||
|
||||
Future<int> importFromRepo(SourceRepo repo) async {
|
||||
if (repo.url.trim().isEmpty) {
|
||||
_message = '请手动输入你信任的书源仓库 URL。';
|
||||
notifyListeners();
|
||||
return 0;
|
||||
}
|
||||
_setBusy('正在导入 ${repo.name}...');
|
||||
try {
|
||||
if (repo.isSubscription) {
|
||||
await _addSubscription(repo.url);
|
||||
}
|
||||
final response = await _http
|
||||
.get<String>(
|
||||
repo.url,
|
||||
options: Options(responseType: ResponseType.plain),
|
||||
)
|
||||
.timeout(LegadoEngine.perSourceTimeout);
|
||||
return await importFromJsonText(response.data ?? '');
|
||||
} catch (error) {
|
||||
_message = '导入失败:${_shortError(error)}';
|
||||
notifyListeners();
|
||||
return 0;
|
||||
} finally {
|
||||
_setIdle();
|
||||
}
|
||||
}
|
||||
|
||||
Future<int> importFromUrl(String url) async {
|
||||
final normalized = url.trim();
|
||||
if (normalized.isEmpty) {
|
||||
_message = '请输入书源仓库 URL。';
|
||||
notifyListeners();
|
||||
return 0;
|
||||
}
|
||||
_setBusy('正在导入自定义书源...');
|
||||
try {
|
||||
final response = await _http
|
||||
.get<String>(
|
||||
normalized,
|
||||
options: Options(responseType: ResponseType.plain),
|
||||
)
|
||||
.timeout(LegadoEngine.perSourceTimeout);
|
||||
return await importFromJsonText(response.data ?? '');
|
||||
} catch (error) {
|
||||
_message = '导入失败:${_shortError(error)}';
|
||||
notifyListeners();
|
||||
return 0;
|
||||
} finally {
|
||||
_setIdle();
|
||||
}
|
||||
}
|
||||
|
||||
Future<int> checkSubscriptionUpdatesIfDue({bool force = false}) async {
|
||||
await load();
|
||||
final prefs = await SharedPreferences.getInstance();
|
||||
final urls = prefs.getStringList(_subscriptionsKey) ?? const <String>[];
|
||||
if (urls.isEmpty) return 0;
|
||||
|
||||
final last = _lastSubscriptionUpdate;
|
||||
if (!force &&
|
||||
last != null &&
|
||||
DateTime.now().difference(last) < const Duration(hours: 24)) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
_setBusy('正在检查订阅书源...');
|
||||
var added = 0;
|
||||
try {
|
||||
for (final url in urls) {
|
||||
try {
|
||||
final response = await _http
|
||||
.get<String>(
|
||||
url,
|
||||
options: Options(responseType: ResponseType.plain),
|
||||
)
|
||||
.timeout(LegadoEngine.perSourceTimeout);
|
||||
added += await importFromJsonText(response.data ?? '');
|
||||
} catch (error) {
|
||||
_message = '部分订阅书源更新失败:${_shortError(error)}';
|
||||
}
|
||||
}
|
||||
_lastSubscriptionUpdate = DateTime.now();
|
||||
await prefs.setString(
|
||||
_lastSubscriptionUpdateKey,
|
||||
_lastSubscriptionUpdate!.toIso8601String(),
|
||||
);
|
||||
_message = '订阅更新完成,新增 $added 个书源。';
|
||||
notifyListeners();
|
||||
return added;
|
||||
} finally {
|
||||
_setIdle();
|
||||
}
|
||||
}
|
||||
|
||||
Future<List<SourceCheckResult>> checkEnabledSources() async {
|
||||
await load();
|
||||
_setBusy('正在检测已启用的书源...');
|
||||
final targets = enabledSources.take(LegadoEngine.maxConcurrency).toList();
|
||||
try {
|
||||
final results = await Future.wait(targets.map(_checkSource));
|
||||
_lastChecks
|
||||
..clear()
|
||||
..addAll(results);
|
||||
final healthy = results.where((item) => item.ok).length;
|
||||
_message = '已检测 ${results.length} 个书源,$healthy 个可用。';
|
||||
notifyListeners();
|
||||
return List.unmodifiable(_lastChecks);
|
||||
} finally {
|
||||
_setIdle();
|
||||
}
|
||||
}
|
||||
|
||||
Future<int> importFromJsonText(String body) async {
|
||||
await load();
|
||||
final imported = _engine.parseSources(body);
|
||||
if (imported.isEmpty) {
|
||||
_message = '没有识别到书源,请确认链接返回的是书源 JSON。';
|
||||
notifyListeners();
|
||||
return 0;
|
||||
}
|
||||
var added = 0;
|
||||
for (final source in imported) {
|
||||
final existing = _sources.indexWhere((item) => item.id == source.id);
|
||||
final next = source.copyWith(
|
||||
enabled: existing >= 0 ? _sources[existing].enabled : source.enabled,
|
||||
);
|
||||
if (existing >= 0) {
|
||||
_sources[existing] = next;
|
||||
} else {
|
||||
_sources.add(next);
|
||||
added += 1;
|
||||
}
|
||||
}
|
||||
await _save();
|
||||
_message = '已导入 $added 个新书源。';
|
||||
notifyListeners();
|
||||
return added;
|
||||
}
|
||||
|
||||
Future<void> setEnabled(String sourceId, bool enabled) async {
|
||||
await load();
|
||||
final index = _sources.indexWhere((source) => source.id == sourceId);
|
||||
if (index < 0) return;
|
||||
_sources[index] = _sources[index].copyWith(enabled: enabled);
|
||||
await _save();
|
||||
notifyListeners();
|
||||
}
|
||||
|
||||
Future<void> _save() async {
|
||||
final prefs = await SharedPreferences.getInstance();
|
||||
await prefs.setString(
|
||||
_sourcesKey,
|
||||
jsonEncode(_sources.map((source) => source.toJson()).toList()),
|
||||
);
|
||||
}
|
||||
|
||||
Future<void> _addSubscription(String url) async {
|
||||
final prefs = await SharedPreferences.getInstance();
|
||||
final urls = (prefs.getStringList(_subscriptionsKey) ?? <String>[]).toSet()
|
||||
..add(url);
|
||||
await prefs.setStringList(_subscriptionsKey, urls.toList());
|
||||
}
|
||||
|
||||
Future<SourceCheckResult> _checkSource(LegadoSource source) async {
|
||||
final stopwatch = Stopwatch()..start();
|
||||
try {
|
||||
final url = _healthCheckUrl(source);
|
||||
final response = await _http
|
||||
.get<Object>(
|
||||
url,
|
||||
options: Options(
|
||||
responseType: ResponseType.plain,
|
||||
headers: {
|
||||
...source.headers,
|
||||
if (source.userAgent?.isNotEmpty == true)
|
||||
'User-Agent': source.userAgent!,
|
||||
},
|
||||
),
|
||||
)
|
||||
.timeout(LegadoEngine.perSourceTimeout);
|
||||
stopwatch.stop();
|
||||
final status = response.statusCode ?? 0;
|
||||
return SourceCheckResult(
|
||||
sourceId: source.id,
|
||||
sourceName: source.name,
|
||||
ok: status >= 200 && status < 400,
|
||||
elapsedMs: stopwatch.elapsedMilliseconds,
|
||||
message: 'HTTP $status',
|
||||
);
|
||||
} catch (error) {
|
||||
stopwatch.stop();
|
||||
return SourceCheckResult(
|
||||
sourceId: source.id,
|
||||
sourceName: source.name,
|
||||
ok: false,
|
||||
elapsedMs: stopwatch.elapsedMilliseconds,
|
||||
message: _shortError(error),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
String _healthCheckUrl(LegadoSource source) {
|
||||
return (source.searchUrl ?? source.url)
|
||||
.replaceAll('{{key}}', Uri.encodeComponent('test'))
|
||||
.replaceAll('{{page}}', '1');
|
||||
}
|
||||
|
||||
String _shortError(Object error) {
|
||||
if (error is FormatException && error.message == 'source-html') {
|
||||
return '这个链接返回的是网页,不是书源 JSON。请复制书源仓库的 raw/json 地址。';
|
||||
}
|
||||
if (error is DioException) {
|
||||
final host = error.requestOptions.uri.host;
|
||||
switch (error.type) {
|
||||
case DioExceptionType.connectionTimeout:
|
||||
case DioExceptionType.receiveTimeout:
|
||||
case DioExceptionType.sendTimeout:
|
||||
return '连接超时:${host.isEmpty ? '目标站点' : host} 暂时没有响应。';
|
||||
case DioExceptionType.connectionError:
|
||||
return '连接失败:${host.isEmpty ? '目标站点' : host} 断开了连接,请稍后重试或更换 raw/json 链接。';
|
||||
case DioExceptionType.badResponse:
|
||||
return '服务器返回 HTTP ${error.response?.statusCode ?? '-'},请确认链接可公开访问。';
|
||||
default:
|
||||
break;
|
||||
}
|
||||
}
|
||||
final message = error.toString();
|
||||
return message.length > 120 ? '${message.substring(0, 120)}...' : message;
|
||||
}
|
||||
|
||||
void _setBusy(String message) {
|
||||
_busy = true;
|
||||
_message = message;
|
||||
notifyListeners();
|
||||
}
|
||||
|
||||
void _setIdle() {
|
||||
_busy = false;
|
||||
notifyListeners();
|
||||
}
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
_autoUpdateTimer?.cancel();
|
||||
super.dispose();
|
||||
}
|
||||
}
|
||||
|
||||
class SourceCheckResult {
|
||||
const SourceCheckResult({
|
||||
required this.sourceId,
|
||||
required this.sourceName,
|
||||
required this.ok,
|
||||
required this.elapsedMs,
|
||||
required this.message,
|
||||
});
|
||||
|
||||
final String sourceId;
|
||||
final String sourceName;
|
||||
final bool ok;
|
||||
final int elapsedMs;
|
||||
final String message;
|
||||
}
|
||||
@@ -0,0 +1,239 @@
|
||||
import 'dart:async';
|
||||
|
||||
import '../models/artwork.dart';
|
||||
import '../models/novel.dart';
|
||||
import 'api_client.dart';
|
||||
import 'legado_engine.dart';
|
||||
import 'legado_models.dart';
|
||||
import 'source_manager.dart';
|
||||
import 'search_scheduler.dart';
|
||||
import 'source_health.dart';
|
||||
|
||||
enum UnifiedSearchMode { manga, novel }
|
||||
|
||||
class UnifiedSearch {
|
||||
UnifiedSearch({
|
||||
required SakuraApiClient api,
|
||||
required SourceManager sourceManager,
|
||||
required LegadoEngine engine,
|
||||
SearchScheduler? scheduler,
|
||||
}) : _api = api,
|
||||
_sourceManager = sourceManager,
|
||||
_scheduler = scheduler ?? SearchScheduler(engine, SourceHealthStore());
|
||||
|
||||
final SakuraApiClient _api;
|
||||
final SourceManager _sourceManager;
|
||||
final SearchScheduler _scheduler;
|
||||
|
||||
Future<List<SearchSection>> search({
|
||||
required String query,
|
||||
required UnifiedSearchMode mode,
|
||||
}) async {
|
||||
final normalized = query.trim();
|
||||
if (normalized.isEmpty) {
|
||||
return const <SearchSection>[];
|
||||
}
|
||||
await _sourceManager.initializeIfFirstRun();
|
||||
|
||||
var result = const <SearchSection>[];
|
||||
await for (final snapshot in searchStream(query: query, mode: mode)) {
|
||||
result = snapshot.sections;
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
Stream<UnifiedSearchSnapshot> searchStream({
|
||||
required String query,
|
||||
required UnifiedSearchMode mode,
|
||||
}) {
|
||||
final normalized = query.trim();
|
||||
if (normalized.isEmpty) return const Stream.empty();
|
||||
late final StreamController<UnifiedSearchSnapshot> controller;
|
||||
var cloudItems = <SearchItem>[];
|
||||
var onlineItems = <SearchItem>[];
|
||||
var cloudDone = false;
|
||||
var onlineDone = false;
|
||||
var doneCount = 0;
|
||||
var totalCount = 0;
|
||||
String? message;
|
||||
|
||||
List<SearchSection> sections() => [
|
||||
if (cloudItems.isNotEmpty)
|
||||
SearchSection(id: 'cloud', title: '我的云库', items: cloudItems),
|
||||
if (onlineItems.isNotEmpty)
|
||||
SearchSection(id: 'online', title: '在线源', items: onlineItems),
|
||||
];
|
||||
|
||||
void emit() {
|
||||
if (controller.isClosed) return;
|
||||
controller.add(UnifiedSearchSnapshot(
|
||||
sections: sections(),
|
||||
message: message,
|
||||
doneCount: doneCount,
|
||||
totalCount: totalCount,
|
||||
isComplete: cloudDone && onlineDone,
|
||||
));
|
||||
}
|
||||
|
||||
Future<void> finishIfDone() async {
|
||||
if (cloudDone && onlineDone && !controller.isClosed) {
|
||||
emit();
|
||||
await controller.close();
|
||||
}
|
||||
}
|
||||
|
||||
controller = StreamController<UnifiedSearchSnapshot>(
|
||||
onListen: () {
|
||||
unawaited(() async {
|
||||
await _sourceManager.initializeIfFirstRun();
|
||||
try {
|
||||
cloudItems = await (mode == UnifiedSearchMode.manga
|
||||
? _searchCloudManga(normalized)
|
||||
: _searchCloudNovels(normalized))
|
||||
.timeout(const Duration(seconds: 6));
|
||||
} catch (_) {
|
||||
cloudItems = <SearchItem>[];
|
||||
} finally {
|
||||
cloudDone = true;
|
||||
emit();
|
||||
await finishIfDone();
|
||||
}
|
||||
}());
|
||||
unawaited(() async {
|
||||
final sources = mode == UnifiedSearchMode.manga
|
||||
? _sourceManager.enabledMangaSources
|
||||
: _sourceManager.enabledNovelSources;
|
||||
await for (final phase in _scheduler.search(normalized, sources)) {
|
||||
onlineItems = phase.items.map(SearchItem.online).toList();
|
||||
doneCount = phase.doneCount;
|
||||
totalCount = phase.totalCount;
|
||||
message = phase.message;
|
||||
if (phase.name == 'complete' || phase.name == 'error') {
|
||||
onlineDone = true;
|
||||
}
|
||||
emit();
|
||||
}
|
||||
onlineDone = true;
|
||||
await finishIfDone();
|
||||
}());
|
||||
},
|
||||
onCancel: _scheduler.cancel,
|
||||
);
|
||||
return controller.stream;
|
||||
}
|
||||
|
||||
Future<List<SearchItem>> _searchCloudManga(String query) async {
|
||||
final rows = await _api.gallery(search: query, contentType: 'manga');
|
||||
return rows
|
||||
.map((item) => Artwork.fromJson(item as Map<String, dynamic>))
|
||||
.map(SearchItem.cloudArtwork)
|
||||
.toList(growable: false);
|
||||
}
|
||||
|
||||
Future<List<SearchItem>> _searchCloudNovels(String query) async {
|
||||
final rows = await _api.novels(search: query);
|
||||
return rows
|
||||
.map((item) => Novel.fromJson(item as Map<String, dynamic>))
|
||||
.map(SearchItem.cloudNovel)
|
||||
.toList(growable: false);
|
||||
}
|
||||
}
|
||||
|
||||
class UnifiedSearchSnapshot {
|
||||
const UnifiedSearchSnapshot({
|
||||
this.sections = const <SearchSection>[],
|
||||
this.message,
|
||||
this.doneCount = 0,
|
||||
this.totalCount = 0,
|
||||
this.isComplete = false,
|
||||
});
|
||||
|
||||
final List<SearchSection> sections;
|
||||
final String? message;
|
||||
final int doneCount;
|
||||
final int totalCount;
|
||||
final bool isComplete;
|
||||
}
|
||||
|
||||
class SearchSection {
|
||||
const SearchSection({
|
||||
required this.id,
|
||||
required this.title,
|
||||
required this.items,
|
||||
});
|
||||
|
||||
final String id;
|
||||
final String title;
|
||||
final List<SearchItem> items;
|
||||
}
|
||||
|
||||
class SearchItem {
|
||||
const SearchItem._({
|
||||
required this.title,
|
||||
required this.sourceName,
|
||||
this.author,
|
||||
this.coverUrl,
|
||||
this.detailUrl,
|
||||
this.artwork,
|
||||
this.novel,
|
||||
this.online,
|
||||
this.errorMessage,
|
||||
});
|
||||
|
||||
factory SearchItem.cloudArtwork(Artwork artwork) {
|
||||
return SearchItem._(
|
||||
title: artwork.title,
|
||||
sourceName: artwork.sourcePlatform,
|
||||
author: artwork.author,
|
||||
coverUrl: artwork.thumbnailUrl ?? artwork.thumbnailPath,
|
||||
artwork: artwork,
|
||||
);
|
||||
}
|
||||
|
||||
factory SearchItem.cloudNovel(Novel novel) {
|
||||
return SearchItem._(
|
||||
title: novel.displayChapterTitle,
|
||||
sourceName: novel.sourcePlatform,
|
||||
author: novel.author,
|
||||
coverUrl: novel.coverPath,
|
||||
detailUrl: novel.contentUrl,
|
||||
novel: novel,
|
||||
);
|
||||
}
|
||||
|
||||
factory SearchItem.online(UnifiedSearchResult result) {
|
||||
return SearchItem._(
|
||||
title: result.title,
|
||||
sourceName: result.sourceName,
|
||||
author: result.author,
|
||||
coverUrl: result.coverUrl,
|
||||
detailUrl: result.detailUrl,
|
||||
online: result,
|
||||
errorMessage: result.errorMessage,
|
||||
);
|
||||
}
|
||||
|
||||
factory SearchItem.error({
|
||||
required String sourceName,
|
||||
required String message,
|
||||
}) {
|
||||
return SearchItem._(
|
||||
title: '搜索失败',
|
||||
sourceName: sourceName,
|
||||
errorMessage: message,
|
||||
);
|
||||
}
|
||||
|
||||
final String title;
|
||||
final String sourceName;
|
||||
final String? author;
|
||||
final String? coverUrl;
|
||||
final String? detailUrl;
|
||||
final Artwork? artwork;
|
||||
final Novel? novel;
|
||||
final UnifiedSearchResult? online;
|
||||
final String? errorMessage;
|
||||
|
||||
bool get isCloud => artwork != null || novel != null;
|
||||
bool get isError => errorMessage?.trim().isNotEmpty == true;
|
||||
}
|
||||
@@ -0,0 +1,119 @@
|
||||
class Artwork {
|
||||
const Artwork({
|
||||
required this.id,
|
||||
required this.title,
|
||||
required this.sourcePlatform,
|
||||
this.contentType = 'illust',
|
||||
this.author,
|
||||
this.thumbnailPath,
|
||||
this.imageUrl,
|
||||
this.thumbnailUrl,
|
||||
this.mimeType,
|
||||
this.fileSize = 0,
|
||||
this.tags = const [],
|
||||
this.isFavorite = false,
|
||||
this.lastViewedAt,
|
||||
this.createdAt,
|
||||
this.updatedAt,
|
||||
this.pageCount = 1,
|
||||
this.matchedBy,
|
||||
this.artworkMetadata = const {},
|
||||
});
|
||||
|
||||
final String id;
|
||||
final String title;
|
||||
final String sourcePlatform;
|
||||
final String contentType;
|
||||
final String? author;
|
||||
final String? thumbnailPath;
|
||||
final String? imageUrl;
|
||||
final String? thumbnailUrl;
|
||||
final String? mimeType;
|
||||
final int fileSize;
|
||||
final List<String> tags;
|
||||
final bool isFavorite;
|
||||
final DateTime? lastViewedAt;
|
||||
final DateTime? createdAt;
|
||||
final DateTime? updatedAt;
|
||||
final int pageCount;
|
||||
final String? matchedBy;
|
||||
final Map<String, dynamic> artworkMetadata;
|
||||
|
||||
Map<String, String> get imageHeaders {
|
||||
final raw = artworkMetadata['headers'];
|
||||
if (raw is! Map) return const {};
|
||||
return raw.map((key, value) => MapEntry(key.toString(), value.toString()));
|
||||
}
|
||||
|
||||
bool get isVideo =>
|
||||
contentType == 'video' || (mimeType ?? '').toLowerCase().startsWith('video/');
|
||||
|
||||
String? get primaryMediaPath => imageUrl ?? thumbnailUrl ?? thumbnailPath;
|
||||
|
||||
Artwork copyWith({
|
||||
String? title,
|
||||
String? author,
|
||||
String? contentType,
|
||||
String? thumbnailPath,
|
||||
String? imageUrl,
|
||||
String? thumbnailUrl,
|
||||
String? mimeType,
|
||||
int? fileSize,
|
||||
List<String>? tags,
|
||||
bool? isFavorite,
|
||||
DateTime? lastViewedAt,
|
||||
DateTime? createdAt,
|
||||
DateTime? updatedAt,
|
||||
int? pageCount,
|
||||
String? matchedBy,
|
||||
Map<String, dynamic>? artworkMetadata,
|
||||
}) {
|
||||
return Artwork(
|
||||
id: id,
|
||||
title: title ?? this.title,
|
||||
sourcePlatform: sourcePlatform,
|
||||
contentType: contentType ?? this.contentType,
|
||||
author: author ?? this.author,
|
||||
thumbnailPath: thumbnailPath ?? this.thumbnailPath,
|
||||
imageUrl: imageUrl ?? this.imageUrl,
|
||||
thumbnailUrl: thumbnailUrl ?? this.thumbnailUrl,
|
||||
mimeType: mimeType ?? this.mimeType,
|
||||
fileSize: fileSize ?? this.fileSize,
|
||||
tags: tags ?? this.tags,
|
||||
isFavorite: isFavorite ?? this.isFavorite,
|
||||
lastViewedAt: lastViewedAt ?? this.lastViewedAt,
|
||||
createdAt: createdAt ?? this.createdAt,
|
||||
updatedAt: updatedAt ?? this.updatedAt,
|
||||
pageCount: pageCount ?? this.pageCount,
|
||||
matchedBy: matchedBy ?? this.matchedBy,
|
||||
artworkMetadata: artworkMetadata ?? this.artworkMetadata,
|
||||
);
|
||||
}
|
||||
|
||||
factory Artwork.fromJson(Map<String, dynamic> json) {
|
||||
return Artwork(
|
||||
id: json['id'] as String,
|
||||
title: json['title'] as String? ?? '未命名',
|
||||
sourcePlatform: json['source_platform'] as String? ?? '未知',
|
||||
contentType: json['content_type'] as String? ?? 'illust',
|
||||
author: json['author'] as String?,
|
||||
thumbnailPath: json['thumbnail_path'] as String?,
|
||||
imageUrl: json['image_url'] as String?,
|
||||
thumbnailUrl: json['thumbnail_url'] as String?,
|
||||
mimeType: json['mime_type'] as String?,
|
||||
fileSize: (json['file_size'] as num?)?.toInt() ?? 0,
|
||||
tags: ((json['tags'] as List?) ?? const [])
|
||||
.map((item) => item.toString())
|
||||
.toList(),
|
||||
isFavorite: json['is_favorite'] as bool? ?? false,
|
||||
lastViewedAt: DateTime.tryParse(json['last_viewed_at']?.toString() ?? ''),
|
||||
createdAt: DateTime.tryParse(json['created_at']?.toString() ?? ''),
|
||||
updatedAt: DateTime.tryParse(json['updated_at']?.toString() ?? ''),
|
||||
pageCount: (json['page_count'] as num?)?.toInt() ?? 1,
|
||||
matchedBy: json['matched_by'] as String?,
|
||||
artworkMetadata: json['artwork_metadata'] is Map
|
||||
? Map<String, dynamic>.from(json['artwork_metadata'] as Map)
|
||||
: const {},
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,147 @@
|
||||
class Novel {
|
||||
const Novel({
|
||||
required this.id,
|
||||
required this.title,
|
||||
required this.sourcePlatform,
|
||||
this.author,
|
||||
this.seriesId,
|
||||
this.seriesTitle,
|
||||
this.chapterTitle,
|
||||
this.chapterOrder = 0,
|
||||
this.description,
|
||||
this.contentUrl,
|
||||
this.coverPath,
|
||||
this.wordCount = 0,
|
||||
this.currentPage = 0,
|
||||
this.bookmark,
|
||||
this.tags = const [],
|
||||
this.isFavorite = false,
|
||||
this.lastReadAt,
|
||||
this.lastViewedAt,
|
||||
});
|
||||
|
||||
final String id;
|
||||
final String title;
|
||||
final String sourcePlatform;
|
||||
final String? author;
|
||||
final String? seriesId;
|
||||
final String? seriesTitle;
|
||||
final String? chapterTitle;
|
||||
final int chapterOrder;
|
||||
final String? description;
|
||||
final String? contentUrl;
|
||||
final String? coverPath;
|
||||
final int wordCount;
|
||||
final int currentPage;
|
||||
final String? bookmark;
|
||||
final List<String> tags;
|
||||
final bool isFavorite;
|
||||
final DateTime? lastReadAt;
|
||||
final DateTime? lastViewedAt;
|
||||
|
||||
bool get isSeriesEntry => (seriesId?.isNotEmpty ?? false);
|
||||
String get displayChapterTitle =>
|
||||
chapterTitle?.trim().isNotEmpty == true ? chapterTitle! : title;
|
||||
|
||||
Novel copyWith({
|
||||
String? title,
|
||||
String? author,
|
||||
String? seriesId,
|
||||
String? seriesTitle,
|
||||
String? chapterTitle,
|
||||
int? chapterOrder,
|
||||
String? description,
|
||||
String? contentUrl,
|
||||
String? coverPath,
|
||||
int? wordCount,
|
||||
int? currentPage,
|
||||
String? bookmark,
|
||||
List<String>? tags,
|
||||
bool? isFavorite,
|
||||
DateTime? lastReadAt,
|
||||
DateTime? lastViewedAt,
|
||||
}) {
|
||||
return Novel(
|
||||
id: id,
|
||||
title: title ?? this.title,
|
||||
sourcePlatform: sourcePlatform,
|
||||
author: author ?? this.author,
|
||||
seriesId: seriesId ?? this.seriesId,
|
||||
seriesTitle: seriesTitle ?? this.seriesTitle,
|
||||
chapterTitle: chapterTitle ?? this.chapterTitle,
|
||||
chapterOrder: chapterOrder ?? this.chapterOrder,
|
||||
description: description ?? this.description,
|
||||
contentUrl: contentUrl ?? this.contentUrl,
|
||||
coverPath: coverPath ?? this.coverPath,
|
||||
wordCount: wordCount ?? this.wordCount,
|
||||
currentPage: currentPage ?? this.currentPage,
|
||||
bookmark: bookmark ?? this.bookmark,
|
||||
tags: tags ?? this.tags,
|
||||
isFavorite: isFavorite ?? this.isFavorite,
|
||||
lastReadAt: lastReadAt ?? this.lastReadAt,
|
||||
lastViewedAt: lastViewedAt ?? this.lastViewedAt,
|
||||
);
|
||||
}
|
||||
|
||||
factory Novel.fromJson(Map<String, dynamic> json) {
|
||||
return Novel(
|
||||
id: json['id'] as String,
|
||||
title: json['title'] as String? ?? '未命名',
|
||||
sourcePlatform: json['source_platform'] as String? ?? '未知',
|
||||
author: json['author'] as String?,
|
||||
seriesId: json['series_id'] as String?,
|
||||
seriesTitle: json['series_title'] as String?,
|
||||
chapterTitle: json['chapter_title'] as String?,
|
||||
chapterOrder: json['chapter_order'] as int? ?? 0,
|
||||
description: json['description'] as String?,
|
||||
contentUrl: json['content_url'] as String?,
|
||||
coverPath: json['cover_path'] as String?,
|
||||
wordCount: json['word_count'] as int? ?? 0,
|
||||
currentPage: json['current_page'] as int? ?? 0,
|
||||
bookmark: json['bookmark'] as String?,
|
||||
tags: ((json['tags'] as List?) ?? const [])
|
||||
.map((item) => item.toString())
|
||||
.toList(),
|
||||
isFavorite: json['is_favorite'] as bool? ?? false,
|
||||
lastReadAt: DateTime.tryParse(json['last_read_at']?.toString() ?? ''),
|
||||
lastViewedAt: DateTime.tryParse(json['last_viewed_at']?.toString() ?? ''),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class NovelSeries {
|
||||
const NovelSeries({
|
||||
required this.seriesId,
|
||||
required this.seriesTitle,
|
||||
required this.chapterCount,
|
||||
required this.chapters,
|
||||
this.author,
|
||||
this.coverPath,
|
||||
this.lastReadAt,
|
||||
this.lastViewedAt,
|
||||
});
|
||||
|
||||
final String seriesId;
|
||||
final String seriesTitle;
|
||||
final String? author;
|
||||
final int chapterCount;
|
||||
final String? coverPath;
|
||||
final DateTime? lastReadAt;
|
||||
final DateTime? lastViewedAt;
|
||||
final List<Novel> chapters;
|
||||
|
||||
factory NovelSeries.fromJson(Map<String, dynamic> json) {
|
||||
return NovelSeries(
|
||||
seriesId: json['series_id'] as String? ?? '',
|
||||
seriesTitle: json['series_title'] as String? ?? '未命名系列',
|
||||
author: json['author'] as String?,
|
||||
chapterCount: json['chapter_count'] as int? ?? 0,
|
||||
coverPath: json['cover_path'] as String?,
|
||||
lastReadAt: DateTime.tryParse(json['last_read_at']?.toString() ?? ''),
|
||||
lastViewedAt: DateTime.tryParse(json['last_viewed_at']?.toString() ?? ''),
|
||||
chapters: ((json['chapters'] as List?) ?? const [])
|
||||
.map((item) => Novel.fromJson(item as Map<String, dynamic>))
|
||||
.toList(),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,967 @@
|
||||
import 'package:cached_network_image/cached_network_image.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_riverpod/flutter_riverpod.dart';
|
||||
import 'package:flutter/services.dart';
|
||||
import 'package:photo_view/photo_view.dart';
|
||||
|
||||
import '../core/manga_collections.dart';
|
||||
import '../core/api_client.dart';
|
||||
import '../core/providers.dart';
|
||||
import '../models/artwork.dart';
|
||||
|
||||
const MethodChannel _mediaChannel =
|
||||
MethodChannel('top.kunkunxiaomao.sakura_mobile/media');
|
||||
|
||||
class ArtworkDetailPage extends ConsumerStatefulWidget {
|
||||
const ArtworkDetailPage({
|
||||
super.key,
|
||||
required this.artwork,
|
||||
this.artworkSequence,
|
||||
this.titleOverride,
|
||||
this.initialIndex,
|
||||
});
|
||||
|
||||
final Artwork artwork;
|
||||
final List<Artwork>? artworkSequence;
|
||||
final String? titleOverride;
|
||||
final int? initialIndex;
|
||||
|
||||
@override
|
||||
ConsumerState<ArtworkDetailPage> createState() => _ArtworkDetailPageState();
|
||||
}
|
||||
|
||||
class _ArtworkDetailPageState extends ConsumerState<ArtworkDetailPage> {
|
||||
late List<Artwork> artworks;
|
||||
late int currentIndex;
|
||||
late PageController mangaController;
|
||||
bool saving = false;
|
||||
bool changed = false;
|
||||
|
||||
Artwork get currentArtwork => artworks[currentIndex];
|
||||
|
||||
bool get _isManga => currentArtwork.contentType == 'manga';
|
||||
|
||||
bool get _hasMangaSequence => _isManga && artworks.length > 1;
|
||||
|
||||
String get _displayTitle {
|
||||
final override = widget.titleOverride?.trim();
|
||||
if (override != null && override.isNotEmpty) {
|
||||
return override;
|
||||
}
|
||||
return currentArtwork.title;
|
||||
}
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
_syncFromWidget();
|
||||
Future.microtask(_markCurrentArtworkViewed);
|
||||
}
|
||||
|
||||
@override
|
||||
void didUpdateWidget(covariant ArtworkDetailPage oldWidget) {
|
||||
super.didUpdateWidget(oldWidget);
|
||||
if (oldWidget.artwork.id != widget.artwork.id ||
|
||||
!_sameArtworkIds(oldWidget.artworkSequence, widget.artworkSequence) ||
|
||||
oldWidget.initialIndex != widget.initialIndex ||
|
||||
oldWidget.titleOverride != widget.titleOverride) {
|
||||
final previousController = mangaController;
|
||||
_syncFromWidget();
|
||||
previousController.dispose();
|
||||
Future.microtask(_markCurrentArtworkViewed);
|
||||
}
|
||||
}
|
||||
|
||||
void _syncFromWidget() {
|
||||
artworks = _resolveArtworks();
|
||||
currentIndex = _resolveInitialIndex();
|
||||
mangaController = PageController(initialPage: currentIndex);
|
||||
}
|
||||
|
||||
List<Artwork> _resolveArtworks() {
|
||||
final seed = widget.artworkSequence?.isNotEmpty == true
|
||||
? widget.artworkSequence!
|
||||
: <Artwork>[widget.artwork];
|
||||
final unique = <String, Artwork>{};
|
||||
for (final item in seed) {
|
||||
unique[item.id] = item;
|
||||
}
|
||||
unique.putIfAbsent(widget.artwork.id, () => widget.artwork);
|
||||
final resolved = unique.values.toList(growable: false);
|
||||
if (resolved.every((item) => item.contentType == 'manga')) {
|
||||
return sortMangaItems(resolved);
|
||||
}
|
||||
return resolved;
|
||||
}
|
||||
|
||||
int _resolveInitialIndex() {
|
||||
final rawIndex = widget.initialIndex;
|
||||
if (rawIndex != null) {
|
||||
if (rawIndex < 0) {
|
||||
return 0;
|
||||
}
|
||||
if (rawIndex >= artworks.length) {
|
||||
return artworks.length - 1;
|
||||
}
|
||||
return rawIndex;
|
||||
}
|
||||
final matched = artworks.indexWhere((item) => item.id == widget.artwork.id);
|
||||
return matched < 0 ? 0 : matched;
|
||||
}
|
||||
|
||||
Future<void> _markCurrentArtworkViewed() async {
|
||||
changed = true;
|
||||
try {
|
||||
await ref.read(apiClientProvider).markArtworkViewed(currentArtwork.id);
|
||||
} catch (_) {
|
||||
// Viewing state is best-effort and shouldn't block the reader.
|
||||
}
|
||||
}
|
||||
|
||||
void _replaceCurrentArtwork(Artwork updated) {
|
||||
artworks = [...artworks]..[currentIndex] = updated;
|
||||
}
|
||||
|
||||
Future<void> _toggleFavorite() async {
|
||||
if (saving) {
|
||||
return;
|
||||
}
|
||||
setState(() {
|
||||
saving = true;
|
||||
});
|
||||
try {
|
||||
final api = ref.read(apiClientProvider);
|
||||
final response = currentArtwork.isFavorite
|
||||
? await api.unfavoriteArtwork(currentArtwork.id)
|
||||
: await api.favoriteArtwork(currentArtwork.id);
|
||||
if (!mounted) {
|
||||
return;
|
||||
}
|
||||
setState(() {
|
||||
_replaceCurrentArtwork(Artwork.fromJson(response));
|
||||
changed = true;
|
||||
});
|
||||
} catch (_) {
|
||||
if (!mounted) {
|
||||
return;
|
||||
}
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
const SnackBar(content: Text('收藏状态更新失败,请稍后再试。')),
|
||||
);
|
||||
} finally {
|
||||
if (mounted) {
|
||||
setState(() {
|
||||
saving = false;
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> _downloadArtwork() async {
|
||||
if (saving) {
|
||||
return;
|
||||
}
|
||||
setState(() {
|
||||
saving = true;
|
||||
});
|
||||
try {
|
||||
final api = ref.read(apiClientProvider);
|
||||
final targets = _hasMangaSequence ? artworks : <Artwork>[currentArtwork];
|
||||
String? lastPath;
|
||||
var saved = 0;
|
||||
for (var index = 0; index < targets.length; index += 1) {
|
||||
final item = targets[index];
|
||||
lastPath = await api.downloadProtectedFile(
|
||||
item.imageUrl ?? item.thumbnailUrl ?? item.thumbnailPath,
|
||||
fileName: _hasMangaSequence
|
||||
? '${_displayTitle}_${(index + 1).toString().padLeft(3, '0')}'
|
||||
: '${item.title}_${item.id}',
|
||||
subdirectory: item.isVideo
|
||||
? 'videos'
|
||||
: item.contentType == 'manga'
|
||||
? 'manga'
|
||||
: 'images',
|
||||
);
|
||||
saved += 1;
|
||||
}
|
||||
if (!mounted) {
|
||||
return;
|
||||
}
|
||||
final message =
|
||||
_hasMangaSequence ? '已保存 $saved 页到本地。' : '已保存到本地:${lastPath ?? ''}';
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
SnackBar(content: Text(message)),
|
||||
);
|
||||
} catch (_) {
|
||||
if (!mounted) {
|
||||
return;
|
||||
}
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
const SnackBar(content: Text('下载失败,请稍后再试。')),
|
||||
);
|
||||
} finally {
|
||||
if (mounted) {
|
||||
setState(() {
|
||||
saving = false;
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> _editArtwork() async {
|
||||
final titleController = TextEditingController(text: currentArtwork.title);
|
||||
final tagsController =
|
||||
TextEditingController(text: currentArtwork.tags.join(','));
|
||||
final updated = await showDialog<Artwork>(
|
||||
context: context,
|
||||
builder: (context) {
|
||||
return AlertDialog(
|
||||
title: const Text('编辑图片信息'),
|
||||
content: SizedBox(
|
||||
width: 420,
|
||||
child: Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
TextField(
|
||||
controller: titleController,
|
||||
decoration: const InputDecoration(labelText: '图片名称'),
|
||||
),
|
||||
const SizedBox(height: 12),
|
||||
TextField(
|
||||
controller: tagsController,
|
||||
minLines: 2,
|
||||
maxLines: 4,
|
||||
decoration: const InputDecoration(
|
||||
labelText: '图片标签',
|
||||
hintText: '多个标签请用中文逗号、英文逗号或换行分隔',
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
actions: [
|
||||
TextButton(
|
||||
onPressed: () => Navigator.of(context).pop(),
|
||||
child: const Text('取消'),
|
||||
),
|
||||
FilledButton(
|
||||
onPressed: () async {
|
||||
final title = titleController.text.trim();
|
||||
final tags = _parseTags(tagsController.text);
|
||||
if (title.isEmpty) {
|
||||
return;
|
||||
}
|
||||
final response =
|
||||
await ref.read(apiClientProvider).updateArtwork(
|
||||
currentArtwork.id,
|
||||
title: title,
|
||||
tags: tags,
|
||||
);
|
||||
if (!context.mounted) {
|
||||
return;
|
||||
}
|
||||
Navigator.of(context).pop(Artwork.fromJson(response));
|
||||
},
|
||||
child: const Text('保存'),
|
||||
),
|
||||
],
|
||||
);
|
||||
},
|
||||
);
|
||||
titleController.dispose();
|
||||
tagsController.dispose();
|
||||
|
||||
if (updated == null || !mounted) {
|
||||
return;
|
||||
}
|
||||
setState(() {
|
||||
_replaceCurrentArtwork(updated);
|
||||
changed = true;
|
||||
});
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
const SnackBar(content: Text('图片信息已更新。')),
|
||||
);
|
||||
}
|
||||
|
||||
Future<void> _deleteArtwork() async {
|
||||
final confirmed = await showDialog<bool>(
|
||||
context: context,
|
||||
builder: (context) {
|
||||
return AlertDialog(
|
||||
title: const Text('删除图片'),
|
||||
content: Text('确定要删除《${currentArtwork.title}》吗?删除后会从图库移除。'),
|
||||
actions: [
|
||||
TextButton(
|
||||
onPressed: () => Navigator.of(context).pop(false),
|
||||
child: const Text('取消'),
|
||||
),
|
||||
FilledButton(
|
||||
onPressed: () => Navigator.of(context).pop(true),
|
||||
child: const Text('删除'),
|
||||
),
|
||||
],
|
||||
);
|
||||
},
|
||||
);
|
||||
if (confirmed != true || !mounted) {
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
await ref.read(apiClientProvider).deleteArtwork(currentArtwork.id);
|
||||
if (!mounted) {
|
||||
return;
|
||||
}
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
const SnackBar(content: Text('图片已删除。')),
|
||||
);
|
||||
Navigator.of(context).pop(true);
|
||||
} catch (_) {
|
||||
if (!mounted) {
|
||||
return;
|
||||
}
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
const SnackBar(content: Text('删除失败,请稍后再试。')),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
void _handleMangaPageChanged(int index) {
|
||||
if (index == currentIndex) {
|
||||
return;
|
||||
}
|
||||
setState(() {
|
||||
currentIndex = index;
|
||||
changed = true;
|
||||
});
|
||||
Future.microtask(_markCurrentArtworkViewed);
|
||||
}
|
||||
|
||||
void _close() {
|
||||
Navigator.of(context).pop(changed);
|
||||
}
|
||||
|
||||
Future<void> _openVideo() async {
|
||||
if (saving) {
|
||||
return;
|
||||
}
|
||||
setState(() {
|
||||
saving = true;
|
||||
});
|
||||
try {
|
||||
final api = ref.read(apiClientProvider);
|
||||
final localPath = await api.downloadProtectedFile(
|
||||
currentArtwork.primaryMediaPath,
|
||||
fileName: '${currentArtwork.title}_${currentArtwork.id}',
|
||||
subdirectory: 'videos',
|
||||
);
|
||||
await _mediaChannel.invokeMethod<bool>('openUrl', {
|
||||
'url': localPath.startsWith('file://') ? localPath : 'file://$localPath',
|
||||
'mimeType': currentArtwork.mimeType ?? 'video/*',
|
||||
});
|
||||
} catch (_) {
|
||||
if (!mounted) {
|
||||
return;
|
||||
}
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
const SnackBar(content: Text('视频打开失败,请先下载后用本地播放器查看。')),
|
||||
);
|
||||
} finally {
|
||||
if (mounted) {
|
||||
setState(() {
|
||||
saving = false;
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
mangaController.dispose();
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final api = ref.watch(apiClientProvider);
|
||||
final theme = Theme.of(context);
|
||||
|
||||
return Scaffold(
|
||||
appBar: AppBar(
|
||||
leading: IconButton(
|
||||
icon: const Icon(Icons.arrow_back),
|
||||
onPressed: _close,
|
||||
),
|
||||
title: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
Text(
|
||||
_displayTitle,
|
||||
maxLines: 1,
|
||||
overflow: TextOverflow.ellipsis,
|
||||
),
|
||||
Text(
|
||||
_hasMangaSequence
|
||||
? '第 ${currentIndex + 1} / ${artworks.length} 页'
|
||||
: (currentArtwork.author?.isNotEmpty == true
|
||||
? currentArtwork.author!
|
||||
: currentArtwork.sourcePlatform),
|
||||
maxLines: 1,
|
||||
overflow: TextOverflow.ellipsis,
|
||||
style: theme.textTheme.labelMedium?.copyWith(
|
||||
color: theme.colorScheme.onSurfaceVariant,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
actions: [
|
||||
IconButton(
|
||||
tooltip: currentArtwork.isFavorite ? '取消收藏' : '加入收藏',
|
||||
onPressed: saving ? null : _toggleFavorite,
|
||||
icon: Icon(
|
||||
currentArtwork.isFavorite
|
||||
? Icons.favorite
|
||||
: Icons.favorite_border,
|
||||
),
|
||||
),
|
||||
IconButton(
|
||||
tooltip: '编辑名称和标签',
|
||||
onPressed: saving ? null : _editArtwork,
|
||||
icon: const Icon(Icons.edit_outlined),
|
||||
),
|
||||
IconButton(
|
||||
tooltip: _hasMangaSequence ? '下载整组' : '下载到本地',
|
||||
onPressed: saving ? null : _downloadArtwork,
|
||||
icon: const Icon(Icons.download_rounded),
|
||||
),
|
||||
PopupMenuButton<String>(
|
||||
onSelected: (value) async {
|
||||
if (value == 'delete') {
|
||||
await _deleteArtwork();
|
||||
}
|
||||
},
|
||||
itemBuilder: (context) => const [
|
||||
PopupMenuItem<String>(
|
||||
value: 'delete',
|
||||
child: Text('删除图片'),
|
||||
),
|
||||
],
|
||||
),
|
||||
],
|
||||
),
|
||||
body: _isManga
|
||||
? _buildMangaBody(context: context, api: api)
|
||||
: currentArtwork.isVideo
|
||||
? _buildVideoBody(context: context, api: api)
|
||||
: _buildIllustrationBody(
|
||||
context: context,
|
||||
api: api,
|
||||
imageUrl: api.resolveUrl(
|
||||
currentArtwork.imageUrl ??
|
||||
currentArtwork.thumbnailUrl ??
|
||||
currentArtwork.thumbnailPath,
|
||||
),
|
||||
thumbUrl: api.resolveUrl(
|
||||
currentArtwork.thumbnailUrl ?? currentArtwork.thumbnailPath,
|
||||
),
|
||||
imageHeaders: currentArtwork.imageHeaders,
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Widget _buildVideoBody({
|
||||
required BuildContext context,
|
||||
required SakuraApiClient api,
|
||||
}) {
|
||||
final thumbUrl = api.resolveUrl(
|
||||
currentArtwork.thumbnailUrl ?? currentArtwork.thumbnailPath,
|
||||
);
|
||||
return ListView(
|
||||
padding: const EdgeInsets.fromLTRB(16, 16, 16, 28),
|
||||
children: [
|
||||
AspectRatio(
|
||||
aspectRatio: 16 / 9,
|
||||
child: ClipRRect(
|
||||
borderRadius: BorderRadius.circular(24),
|
||||
child: DecoratedBox(
|
||||
decoration: const BoxDecoration(color: Color(0xFF241C22)),
|
||||
child: Stack(
|
||||
fit: StackFit.expand,
|
||||
children: [
|
||||
if (thumbUrl.isNotEmpty)
|
||||
CachedNetworkImage(
|
||||
imageUrl: thumbUrl,
|
||||
httpHeaders: api.authHeaders(),
|
||||
fit: BoxFit.cover,
|
||||
),
|
||||
Container(color: Colors.black.withValues(alpha: 0.24)),
|
||||
Center(
|
||||
child: IconButton.filled(
|
||||
iconSize: 40,
|
||||
onPressed: saving ? null : _openVideo,
|
||||
icon: const Icon(Icons.play_arrow_rounded),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 18),
|
||||
Text(currentArtwork.title, style: Theme.of(context).textTheme.titleLarge),
|
||||
if (currentArtwork.author?.isNotEmpty == true) ...[
|
||||
const SizedBox(height: 4),
|
||||
Text(currentArtwork.author!),
|
||||
],
|
||||
const SizedBox(height: 12),
|
||||
Wrap(
|
||||
spacing: 8,
|
||||
runSpacing: 8,
|
||||
children: [
|
||||
const Chip(label: Text('视频')),
|
||||
if ((currentArtwork.mimeType ?? '').isNotEmpty)
|
||||
Chip(label: Text(currentArtwork.mimeType!)),
|
||||
if (currentArtwork.fileSize > 0)
|
||||
Chip(label: Text(_formatBytes(currentArtwork.fileSize))),
|
||||
],
|
||||
),
|
||||
const SizedBox(height: 18),
|
||||
Wrap(
|
||||
spacing: 10,
|
||||
runSpacing: 10,
|
||||
children: [
|
||||
FilledButton.icon(
|
||||
onPressed: saving ? null : _openVideo,
|
||||
icon: const Icon(Icons.play_circle_outline_rounded),
|
||||
label: const Text('播放视频'),
|
||||
),
|
||||
OutlinedButton.icon(
|
||||
onPressed: saving ? null : _downloadArtwork,
|
||||
icon: const Icon(Icons.download_rounded),
|
||||
label: const Text('下载到本地'),
|
||||
),
|
||||
FilledButton.tonalIcon(
|
||||
onPressed: saving ? null : _toggleFavorite,
|
||||
icon: Icon(
|
||||
currentArtwork.isFavorite ? Icons.favorite : Icons.favorite_border,
|
||||
),
|
||||
label: Text(currentArtwork.isFavorite ? '已收藏' : '收藏'),
|
||||
),
|
||||
],
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
Widget _buildMangaBody({
|
||||
required BuildContext context,
|
||||
required SakuraApiClient api,
|
||||
}) {
|
||||
return DecoratedBox(
|
||||
decoration: const BoxDecoration(color: Color(0xFF161316)),
|
||||
child: Stack(
|
||||
children: [
|
||||
PageView.builder(
|
||||
key: ValueKey(
|
||||
artworks.map((item) => item.id).join(':'),
|
||||
),
|
||||
controller: mangaController,
|
||||
scrollDirection: Axis.vertical,
|
||||
itemCount: artworks.length,
|
||||
onPageChanged: _handleMangaPageChanged,
|
||||
itemBuilder: (context, index) {
|
||||
final item = artworks[index];
|
||||
final imageUrl = api.resolveUrl(
|
||||
item.imageUrl ?? item.thumbnailUrl ?? item.thumbnailPath,
|
||||
);
|
||||
final thumbUrl = api.resolveUrl(
|
||||
item.thumbnailUrl ?? item.thumbnailPath,
|
||||
);
|
||||
final imageHeaders = item.imageHeaders;
|
||||
return SafeArea(
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.fromLTRB(16, 12, 16, 24),
|
||||
child: Column(
|
||||
children: [
|
||||
Expanded(
|
||||
child: ClipRRect(
|
||||
borderRadius: BorderRadius.circular(24),
|
||||
child: DecoratedBox(
|
||||
decoration: const BoxDecoration(
|
||||
color: Color(0xFF221D22),
|
||||
),
|
||||
child: imageUrl.isEmpty
|
||||
? const Center(
|
||||
child: Icon(
|
||||
Icons.image_not_supported_outlined,
|
||||
size: 48,
|
||||
color: Colors.white70,
|
||||
),
|
||||
)
|
||||
: InteractiveViewer(
|
||||
minScale: 1,
|
||||
maxScale: 4,
|
||||
child: Center(
|
||||
child: CachedNetworkImage(
|
||||
imageUrl: imageUrl,
|
||||
httpHeaders: api.headersForUrl(
|
||||
imageUrl,
|
||||
extraHeaders: imageHeaders,
|
||||
),
|
||||
fit: BoxFit.contain,
|
||||
placeholder: (context, _) =>
|
||||
_buildImageLoadingPlaceholder(
|
||||
api: api,
|
||||
thumbUrl: thumbUrl,
|
||||
imageHeaders: imageHeaders,
|
||||
fit: BoxFit.contain,
|
||||
),
|
||||
errorWidget: (context, _, __) =>
|
||||
const Center(
|
||||
child: Icon(
|
||||
Icons.broken_image_outlined,
|
||||
size: 42,
|
||||
color: Colors.white70,
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
},
|
||||
),
|
||||
Positioned(
|
||||
left: 16,
|
||||
right: 16,
|
||||
bottom: 18,
|
||||
child: IgnorePointer(
|
||||
child: Center(
|
||||
child: DecoratedBox(
|
||||
decoration: BoxDecoration(
|
||||
color: Colors.black.withValues(alpha: 0.62),
|
||||
borderRadius: BorderRadius.circular(999),
|
||||
),
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.symmetric(
|
||||
horizontal: 14,
|
||||
vertical: 8,
|
||||
),
|
||||
child: Text(
|
||||
artworks.length > 1
|
||||
? '第 ${currentIndex + 1} 页,共 ${artworks.length} 页'
|
||||
: '单页阅读',
|
||||
style: Theme.of(context).textTheme.labelLarge?.copyWith(
|
||||
color: Colors.white,
|
||||
fontWeight: FontWeight.w700,
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Widget _buildIllustrationBody({
|
||||
required BuildContext context,
|
||||
required SakuraApiClient api,
|
||||
required String imageUrl,
|
||||
required String thumbUrl,
|
||||
required Map<String, String> imageHeaders,
|
||||
}) {
|
||||
return Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Expanded(
|
||||
child: imageUrl.isEmpty
|
||||
? const Center(
|
||||
child: Icon(Icons.image_not_supported_outlined, size: 48),
|
||||
)
|
||||
: PhotoView(
|
||||
imageProvider: CachedNetworkImageProvider(
|
||||
imageUrl,
|
||||
headers: api.headersForUrl(
|
||||
imageUrl,
|
||||
extraHeaders: imageHeaders,
|
||||
),
|
||||
),
|
||||
loadingBuilder: (context, event) =>
|
||||
_buildImageLoadingPlaceholder(
|
||||
api: api,
|
||||
thumbUrl: thumbUrl,
|
||||
imageHeaders: imageHeaders,
|
||||
fit: BoxFit.contain,
|
||||
),
|
||||
backgroundDecoration: BoxDecoration(
|
||||
color: Theme.of(context).colorScheme.surface,
|
||||
),
|
||||
minScale: PhotoViewComputedScale.contained,
|
||||
maxScale: PhotoViewComputedScale.covered * 4,
|
||||
),
|
||||
),
|
||||
Padding(
|
||||
padding: const EdgeInsets.all(16),
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Text(
|
||||
currentArtwork.title,
|
||||
style: Theme.of(context).textTheme.titleLarge,
|
||||
),
|
||||
if (currentArtwork.author != null &&
|
||||
currentArtwork.author!.isNotEmpty) ...[
|
||||
const SizedBox(height: 4),
|
||||
Text(currentArtwork.author!),
|
||||
],
|
||||
const SizedBox(height: 10),
|
||||
Wrap(
|
||||
spacing: 8,
|
||||
runSpacing: 8,
|
||||
children: currentArtwork.tags.isEmpty
|
||||
? const [Chip(label: Text('暂无标签'))]
|
||||
: currentArtwork.tags
|
||||
.take(20)
|
||||
.map((tag) => Chip(label: Text(tag)))
|
||||
.toList(),
|
||||
),
|
||||
const SizedBox(height: 14),
|
||||
_ArtworkOcrPanel(artworkId: currentArtwork.id),
|
||||
const SizedBox(height: 14),
|
||||
Wrap(
|
||||
spacing: 10,
|
||||
runSpacing: 10,
|
||||
children: [
|
||||
FilledButton.tonalIcon(
|
||||
onPressed: saving ? null : _toggleFavorite,
|
||||
icon: Icon(
|
||||
currentArtwork.isFavorite
|
||||
? Icons.favorite
|
||||
: Icons.favorite_border,
|
||||
),
|
||||
label: Text(currentArtwork.isFavorite ? '已收藏' : '收藏'),
|
||||
),
|
||||
OutlinedButton.icon(
|
||||
onPressed: saving ? null : _editArtwork,
|
||||
icon: const Icon(Icons.sell_outlined),
|
||||
label: const Text('改名和标签'),
|
||||
),
|
||||
OutlinedButton.icon(
|
||||
onPressed: saving ? null : _downloadArtwork,
|
||||
icon: const Icon(Icons.download_rounded),
|
||||
label: const Text('下载到本地'),
|
||||
),
|
||||
],
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
Widget _buildImageLoadingPlaceholder({
|
||||
required SakuraApiClient api,
|
||||
required String thumbUrl,
|
||||
Map<String, String> imageHeaders = const {},
|
||||
required BoxFit fit,
|
||||
}) {
|
||||
return Stack(
|
||||
fit: StackFit.expand,
|
||||
children: [
|
||||
if (thumbUrl.isNotEmpty)
|
||||
CachedNetworkImage(
|
||||
imageUrl: thumbUrl,
|
||||
httpHeaders: api.headersForUrl(
|
||||
thumbUrl,
|
||||
extraHeaders: imageHeaders,
|
||||
),
|
||||
fit: fit,
|
||||
),
|
||||
const Center(child: CircularProgressIndicator()),
|
||||
],
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
bool _sameArtworkIds(List<Artwork>? a, List<Artwork>? b) {
|
||||
final aIds = (a ?? const <Artwork>[]).map((item) => item.id).toList();
|
||||
final bIds = (b ?? const <Artwork>[]).map((item) => item.id).toList();
|
||||
if (aIds.length != bIds.length) {
|
||||
return false;
|
||||
}
|
||||
for (var index = 0; index < aIds.length; index += 1) {
|
||||
if (aIds[index] != bIds[index]) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
String _formatBytes(int bytes) {
|
||||
if (bytes <= 0) return '0 B';
|
||||
const units = ['B', 'KB', 'MB', 'GB'];
|
||||
var value = bytes.toDouble();
|
||||
var index = 0;
|
||||
while (value >= 1024 && index < units.length - 1) {
|
||||
value /= 1024;
|
||||
index += 1;
|
||||
}
|
||||
return '${value.toStringAsFixed(index == 0 ? 0 : 1)} ${units[index]}';
|
||||
}
|
||||
|
||||
class _ArtworkOcrPanel extends ConsumerStatefulWidget {
|
||||
const _ArtworkOcrPanel({required this.artworkId});
|
||||
|
||||
final String artworkId;
|
||||
|
||||
@override
|
||||
ConsumerState<_ArtworkOcrPanel> createState() => _ArtworkOcrPanelState();
|
||||
}
|
||||
|
||||
class _ArtworkOcrPanelState extends ConsumerState<_ArtworkOcrPanel> {
|
||||
late Future<Map<String, dynamic>?> future = _load();
|
||||
|
||||
@override
|
||||
void didUpdateWidget(covariant _ArtworkOcrPanel oldWidget) {
|
||||
super.didUpdateWidget(oldWidget);
|
||||
if (oldWidget.artworkId != widget.artworkId) {
|
||||
future = _load();
|
||||
}
|
||||
}
|
||||
|
||||
Future<Map<String, dynamic>?> _load() {
|
||||
return ref.read(apiClientProvider).artworkOcr(widget.artworkId);
|
||||
}
|
||||
|
||||
Future<void> _retry() async {
|
||||
await ref.read(apiClientProvider).retryArtworkOcr(widget.artworkId);
|
||||
if (!mounted) {
|
||||
return;
|
||||
}
|
||||
setState(() {
|
||||
future = _load();
|
||||
});
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return FutureBuilder<Map<String, dynamic>?>(
|
||||
future: future,
|
||||
builder: (context, snapshot) {
|
||||
final row = snapshot.data;
|
||||
final status = row?['status']?.toString() ?? '';
|
||||
final text = row?['ocr_text']?.toString() ?? '';
|
||||
return ExpansionTile(
|
||||
tilePadding: EdgeInsets.zero,
|
||||
childrenPadding: EdgeInsets.zero,
|
||||
leading: const Icon(Icons.document_scanner_outlined),
|
||||
title: const Text('图片文字'),
|
||||
subtitle: Text(_statusText(status, snapshot.connectionState)),
|
||||
children: [
|
||||
if (snapshot.connectionState == ConnectionState.waiting)
|
||||
const Padding(
|
||||
padding: EdgeInsets.only(bottom: 12),
|
||||
child: LinearProgressIndicator(),
|
||||
)
|
||||
else if (status == 'done' && text.trim().isNotEmpty)
|
||||
Container(
|
||||
width: double.infinity,
|
||||
padding: const EdgeInsets.all(14),
|
||||
decoration: BoxDecoration(
|
||||
color: const Color(0xFFFFF5F8),
|
||||
borderRadius: BorderRadius.circular(16),
|
||||
border: Border.all(color: const Color(0xFFF1CAD7)),
|
||||
),
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Text(
|
||||
text,
|
||||
style: Theme.of(context).textTheme.bodyMedium?.copyWith(
|
||||
height: 1.6,
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 10),
|
||||
Align(
|
||||
alignment: Alignment.centerRight,
|
||||
child: OutlinedButton.icon(
|
||||
onPressed: () async {
|
||||
await Clipboard.setData(ClipboardData(text: text));
|
||||
if (!context.mounted) {
|
||||
return;
|
||||
}
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
const SnackBar(content: Text('已复制图片文字')),
|
||||
);
|
||||
},
|
||||
icon: const Icon(Icons.copy_rounded),
|
||||
label: const Text('复制'),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
)
|
||||
else
|
||||
Padding(
|
||||
padding: const EdgeInsets.only(bottom: 12),
|
||||
child: Row(
|
||||
children: [
|
||||
Expanded(
|
||||
child: Text(
|
||||
status == 'failed'
|
||||
? '这张图片暂时没有识别出文字,可以稍后重试。'
|
||||
: '图片文字还在等待识别。',
|
||||
),
|
||||
),
|
||||
TextButton.icon(
|
||||
onPressed: _retry,
|
||||
icon: const Icon(Icons.refresh_rounded),
|
||||
label: const Text('重新识别'),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
],
|
||||
);
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
String _statusText(String status, ConnectionState state) {
|
||||
if (state == ConnectionState.waiting) {
|
||||
return '正在读取 OCR 状态';
|
||||
}
|
||||
switch (status) {
|
||||
case 'done':
|
||||
return '已识别';
|
||||
case 'running':
|
||||
return '正在识别';
|
||||
case 'pending':
|
||||
return '等待识别';
|
||||
case 'failed':
|
||||
return '识别失败';
|
||||
default:
|
||||
return '暂无识别结果';
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
List<String> _parseTags(String raw) {
|
||||
return raw
|
||||
.split(RegExp(r'[\n,,]+'))
|
||||
.map((item) => item.trim())
|
||||
.where((item) => item.isNotEmpty)
|
||||
.toSet()
|
||||
.toList()
|
||||
..sort();
|
||||
}
|
||||
@@ -0,0 +1,511 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_riverpod/flutter_riverpod.dart';
|
||||
|
||||
import '../core/providers.dart';
|
||||
import '../core/online_shelf.dart';
|
||||
import '../core/unified_search.dart';
|
||||
import 'artwork_detail_page.dart';
|
||||
import 'novel_reader_page.dart';
|
||||
import 'online_book_detail_page.dart';
|
||||
import 'source_manager_page.dart';
|
||||
|
||||
class ExplorePage extends ConsumerStatefulWidget {
|
||||
const ExplorePage({
|
||||
super.key,
|
||||
this.initialMode = UnifiedSearchMode.manga,
|
||||
});
|
||||
|
||||
final UnifiedSearchMode initialMode;
|
||||
|
||||
@override
|
||||
ConsumerState<ExplorePage> createState() => _ExplorePageState();
|
||||
}
|
||||
|
||||
class _ExplorePageState extends ConsumerState<ExplorePage> {
|
||||
final search = TextEditingController();
|
||||
late UnifiedSearchMode mode = widget.initialMode;
|
||||
Stream<UnifiedSearchSnapshot>? resultStream;
|
||||
final savingOnline = <String>{};
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
search.dispose();
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
void _submit() {
|
||||
final query = search.text.trim();
|
||||
if (query.isEmpty) return;
|
||||
setState(() {
|
||||
resultStream = ref
|
||||
.read(unifiedSearchProvider)
|
||||
.searchStream(query: query, mode: mode);
|
||||
});
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final manager = ref.watch(sourceManagerProvider);
|
||||
return Scaffold(
|
||||
appBar: AppBar(
|
||||
title: const Text('在线搜索'),
|
||||
actions: [
|
||||
IconButton(
|
||||
tooltip: '书源管理',
|
||||
onPressed: () {
|
||||
Navigator.of(context).push(
|
||||
MaterialPageRoute(builder: (_) => const SourceManagerPage()),
|
||||
);
|
||||
},
|
||||
icon: const Icon(Icons.tune_rounded),
|
||||
),
|
||||
],
|
||||
),
|
||||
body: ListView(
|
||||
padding: const EdgeInsets.fromLTRB(16, 10, 16, 28),
|
||||
children: [
|
||||
SearchBar(
|
||||
controller: search,
|
||||
hintText: mode == UnifiedSearchMode.manga
|
||||
? '在云库和已启用的书源中搜索漫画'
|
||||
: '在云库和已启用的书源中搜索小说',
|
||||
leading: const Icon(Icons.search),
|
||||
trailing: [
|
||||
IconButton(
|
||||
tooltip: '搜索',
|
||||
onPressed: _submit,
|
||||
icon: const Icon(Icons.arrow_forward_rounded),
|
||||
),
|
||||
],
|
||||
onSubmitted: (_) => _submit(),
|
||||
),
|
||||
const SizedBox(height: 12),
|
||||
SegmentedButton<UnifiedSearchMode>(
|
||||
segments: const [
|
||||
ButtonSegment(
|
||||
value: UnifiedSearchMode.manga,
|
||||
icon: Icon(Icons.menu_book_rounded),
|
||||
label: Text('漫画'),
|
||||
),
|
||||
ButtonSegment(
|
||||
value: UnifiedSearchMode.novel,
|
||||
icon: Icon(Icons.auto_stories_rounded),
|
||||
label: Text('小说'),
|
||||
),
|
||||
],
|
||||
selected: {mode},
|
||||
onSelectionChanged: (value) {
|
||||
setState(() {
|
||||
mode = value.first;
|
||||
resultStream = null;
|
||||
});
|
||||
},
|
||||
),
|
||||
const SizedBox(height: 12),
|
||||
_SourceSummary(
|
||||
enabledCount: mode == UnifiedSearchMode.manga
|
||||
? manager.enabledMangaSources.length
|
||||
: manager.enabledNovelSources.length,
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
StreamBuilder<UnifiedSearchSnapshot>(
|
||||
stream: resultStream,
|
||||
builder: (context, snapshot) {
|
||||
if (resultStream == null) {
|
||||
return const _ExploreEmptyState(
|
||||
icon: Icons.travel_explore_outlined,
|
||||
title: '搜索云库和在线书源',
|
||||
message: '在线结果可以预览,也可以保存到漫画或书架后用原阅读模式继续阅读。',
|
||||
);
|
||||
}
|
||||
if (!snapshot.hasData &&
|
||||
snapshot.connectionState == ConnectionState.waiting) {
|
||||
return const Padding(
|
||||
padding: EdgeInsets.only(top: 80),
|
||||
child: Center(child: CircularProgressIndicator()),
|
||||
);
|
||||
}
|
||||
if (snapshot.hasError) {
|
||||
return const _ExploreEmptyState(
|
||||
icon: Icons.cloud_off_outlined,
|
||||
title: '搜索失败',
|
||||
message: '云端或书源规则暂时不可用。',
|
||||
);
|
||||
}
|
||||
final result = snapshot.data ?? const UnifiedSearchSnapshot();
|
||||
final sections = result.sections;
|
||||
if (sections.isEmpty && !result.isComplete) {
|
||||
return _SearchProgress(
|
||||
message: result.message ?? '正在寻找新内容…',
|
||||
doneCount: result.doneCount,
|
||||
totalCount: result.totalCount,
|
||||
);
|
||||
}
|
||||
if (sections.isEmpty && result.isComplete) {
|
||||
return const _ExploreEmptyState(
|
||||
icon: Icons.search_off_rounded,
|
||||
title: '暂无搜索结果',
|
||||
message: '试试其他关键词,或启用更多书源。',
|
||||
);
|
||||
}
|
||||
return Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
if (!result.isComplete) ...[
|
||||
_SearchProgress(
|
||||
message: result.message ?? '在线书源仍在搜索…',
|
||||
doneCount: result.doneCount,
|
||||
totalCount: result.totalCount,
|
||||
),
|
||||
const SizedBox(height: 14),
|
||||
],
|
||||
for (final section in sections) ...[
|
||||
Text(
|
||||
'${section.title} (${section.items.length})',
|
||||
style: Theme.of(context).textTheme.titleMedium?.copyWith(
|
||||
fontWeight: FontWeight.w800,
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 8),
|
||||
for (final item in section.items)
|
||||
_SearchResultTile(
|
||||
item: item,
|
||||
mode: mode,
|
||||
onTap: () => _openItem(item),
|
||||
onSave: item.isCloud || item.isError
|
||||
? null
|
||||
: () => _saveOnlineItem(item),
|
||||
saving: savingOnline.contains(_itemKey(item)),
|
||||
),
|
||||
const SizedBox(height: 14),
|
||||
],
|
||||
],
|
||||
);
|
||||
},
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
void _openItem(SearchItem item) {
|
||||
if (item.artwork != null) {
|
||||
Navigator.of(context).push(
|
||||
MaterialPageRoute(
|
||||
builder: (_) => ArtworkDetailPage(artwork: item.artwork!),
|
||||
),
|
||||
);
|
||||
return;
|
||||
}
|
||||
if (item.novel != null) {
|
||||
Navigator.of(context).push(
|
||||
MaterialPageRoute(
|
||||
builder: (_) => NovelReaderPage(novel: item.novel!),
|
||||
),
|
||||
);
|
||||
return;
|
||||
}
|
||||
final online = item.online;
|
||||
if (item.isError) {
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
SnackBar(content: Text(item.errorMessage ?? '搜索失败,请稍后再试。')),
|
||||
);
|
||||
return;
|
||||
}
|
||||
if (online == null) return;
|
||||
final source = ref.read(sourceManagerProvider).sourceById(online.sourceId);
|
||||
if (source == null) {
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
const SnackBar(content: Text('书源已不可用。')),
|
||||
);
|
||||
return;
|
||||
}
|
||||
Navigator.of(context).push(
|
||||
MaterialPageRoute(
|
||||
builder: (_) => OnlineBookDetailPage(
|
||||
source: source,
|
||||
initialTitle: item.title,
|
||||
initialAuthor: item.author,
|
||||
initialCoverUrl: item.coverUrl,
|
||||
detailUrl: item.detailUrl ?? '',
|
||||
onSave: () => _saveOnlineItem(item),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
String _itemKey(SearchItem item) {
|
||||
return [
|
||||
item.online?.sourceId ?? item.sourceName,
|
||||
item.detailUrl ?? item.coverUrl ?? item.title,
|
||||
mode.name,
|
||||
].join('|');
|
||||
}
|
||||
|
||||
Future<void> _saveOnlineItem(SearchItem item) async {
|
||||
final online = item.online;
|
||||
if (online == null || item.isError) return;
|
||||
final key = _itemKey(item);
|
||||
if (savingOnline.contains(key)) return;
|
||||
final source = ref.read(sourceManagerProvider).sourceById(online.sourceId);
|
||||
if (source == null) {
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
const SnackBar(content: Text('书源已不可用。')),
|
||||
);
|
||||
return;
|
||||
}
|
||||
setState(() {
|
||||
savingOnline.add(key);
|
||||
});
|
||||
try {
|
||||
final detailUrl = item.detailUrl ?? item.coverUrl ?? '';
|
||||
if (detailUrl.isEmpty) {
|
||||
throw Exception('结果缺少详情链接');
|
||||
}
|
||||
if (mode == UnifiedSearchMode.manga) {
|
||||
await ref.read(onlineShelfProvider).save(OnlineShelfEntry(
|
||||
sourceId: online.sourceId,
|
||||
sourceName: item.sourceName,
|
||||
title: item.title,
|
||||
author: item.author,
|
||||
detailUrl: detailUrl,
|
||||
coverUrl: item.coverUrl,
|
||||
savedAt: DateTime.now(),
|
||||
contentType: 'manga',
|
||||
));
|
||||
if (!mounted) return;
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
const SnackBar(content: Text('已添加到漫画,打开时按原书源加载。')),
|
||||
);
|
||||
} else {
|
||||
await ref.read(onlineShelfProvider).save(OnlineShelfEntry(
|
||||
sourceId: online.sourceId,
|
||||
sourceName: item.sourceName,
|
||||
title: item.title,
|
||||
author: item.author,
|
||||
detailUrl: detailUrl,
|
||||
coverUrl: item.coverUrl,
|
||||
savedAt: DateTime.now(),
|
||||
contentType: 'novel',
|
||||
));
|
||||
if (!mounted) return;
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
const SnackBar(content: Text('已保存到书架,阅读时再加载章节。')),
|
||||
);
|
||||
}
|
||||
} catch (error) {
|
||||
if (!mounted) return;
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
SnackBar(content: Text('保存失败:$error')),
|
||||
);
|
||||
} finally {
|
||||
if (mounted) {
|
||||
setState(() {
|
||||
savingOnline.remove(key);
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
class _SourceSummary extends StatelessWidget {
|
||||
const _SourceSummary({required this.enabledCount});
|
||||
|
||||
final int enabledCount;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Card(
|
||||
color: const Color(0xFFFFF7FA),
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.all(14),
|
||||
child: Row(
|
||||
children: [
|
||||
const Icon(Icons.speed_rounded, color: Color(0xFFD95A83)),
|
||||
const SizedBox(width: 10),
|
||||
Expanded(
|
||||
child: Text(
|
||||
'已启用 $enabledCount 个书源,本次会搜索全部来源。',
|
||||
style: Theme.of(context).textTheme.bodySmall?.copyWith(
|
||||
color: const Color(0xFF7B6570),
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class _SearchResultTile extends StatelessWidget {
|
||||
const _SearchResultTile({
|
||||
required this.item,
|
||||
required this.mode,
|
||||
required this.onTap,
|
||||
this.onSave,
|
||||
this.saving = false,
|
||||
});
|
||||
|
||||
final SearchItem item;
|
||||
final UnifiedSearchMode mode;
|
||||
final VoidCallback onTap;
|
||||
final VoidCallback? onSave;
|
||||
final bool saving;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Card(
|
||||
color: item.isError ? const Color(0xFFFFF7FA) : null,
|
||||
margin: const EdgeInsets.only(bottom: 10),
|
||||
child: ListTile(
|
||||
leading: _ResultThumb(
|
||||
url: item.coverUrl,
|
||||
icon: item.isError
|
||||
? Icons.warning_amber_rounded
|
||||
: mode == UnifiedSearchMode.manga
|
||||
? Icons.menu_book_rounded
|
||||
: Icons.auto_stories_rounded,
|
||||
),
|
||||
title: Text(item.title, maxLines: 1, overflow: TextOverflow.ellipsis),
|
||||
subtitle: Text(
|
||||
item.isError
|
||||
? '${item.sourceName} - ${item.errorMessage ?? '搜索失败'}'
|
||||
: [
|
||||
item.author?.trim().isNotEmpty == true
|
||||
? item.author!
|
||||
: '未知作者',
|
||||
item.sourceName,
|
||||
item.isCloud ? '云库' : '在线',
|
||||
].join(' - '),
|
||||
maxLines: 2,
|
||||
overflow: TextOverflow.ellipsis,
|
||||
),
|
||||
trailing: onSave == null
|
||||
? Icon(item.isError ? Icons.info_outline : Icons.chevron_right)
|
||||
: IconButton(
|
||||
tooltip: mode == UnifiedSearchMode.manga ? '添加到漫画' : '加入书架',
|
||||
onPressed: saving ? null : onSave,
|
||||
icon: saving
|
||||
? const SizedBox(
|
||||
width: 18,
|
||||
height: 18,
|
||||
child: CircularProgressIndicator(strokeWidth: 2),
|
||||
)
|
||||
: Icon(
|
||||
mode == UnifiedSearchMode.manga
|
||||
? Icons.library_add_rounded
|
||||
: Icons.bookmark_add_outlined,
|
||||
),
|
||||
),
|
||||
onTap: item.isError ? null : onTap,
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class _SearchProgress extends StatelessWidget {
|
||||
const _SearchProgress({
|
||||
required this.message,
|
||||
required this.doneCount,
|
||||
required this.totalCount,
|
||||
});
|
||||
|
||||
final String message;
|
||||
final int doneCount;
|
||||
final int totalCount;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final progress = totalCount > 0 ? doneCount / totalCount : null;
|
||||
return Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
LinearProgressIndicator(value: progress),
|
||||
const SizedBox(height: 8),
|
||||
Text(
|
||||
totalCount > 0 ? '$message $doneCount/$totalCount' : message,
|
||||
style: Theme.of(context).textTheme.bodySmall?.copyWith(
|
||||
color: const Color(0xFF7B6570),
|
||||
),
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class _ResultThumb extends StatelessWidget {
|
||||
const _ResultThumb({required this.url, required this.icon});
|
||||
|
||||
final String? url;
|
||||
final IconData icon;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final value = url?.trim() ?? '';
|
||||
return ClipRRect(
|
||||
borderRadius: BorderRadius.circular(12),
|
||||
child: SizedBox(
|
||||
width: 52,
|
||||
height: 64,
|
||||
child: value.startsWith('http')
|
||||
? Image.network(
|
||||
value,
|
||||
fit: BoxFit.cover,
|
||||
cacheWidth: 160,
|
||||
cacheHeight: 220,
|
||||
errorBuilder: (_, __, ___) => _ThumbFallback(icon: icon),
|
||||
)
|
||||
: _ThumbFallback(icon: icon),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class _ThumbFallback extends StatelessWidget {
|
||||
const _ThumbFallback({required this.icon});
|
||||
|
||||
final IconData icon;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return ColoredBox(
|
||||
color: const Color(0xFFFFE8EE),
|
||||
child: Icon(icon, color: const Color(0xFFD95A83)),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class _ExploreEmptyState extends StatelessWidget {
|
||||
const _ExploreEmptyState({
|
||||
required this.icon,
|
||||
required this.title,
|
||||
required this.message,
|
||||
});
|
||||
|
||||
final IconData icon;
|
||||
final String title;
|
||||
final String message;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Padding(
|
||||
padding: const EdgeInsets.only(top: 96),
|
||||
child: Column(
|
||||
children: [
|
||||
Icon(icon, size: 44, color: const Color(0xFFD95A83)),
|
||||
const SizedBox(height: 12),
|
||||
Text(title, style: Theme.of(context).textTheme.titleLarge),
|
||||
const SizedBox(height: 8),
|
||||
Text(
|
||||
message,
|
||||
textAlign: TextAlign.center,
|
||||
style: Theme.of(context).textTheme.bodyMedium?.copyWith(
|
||||
color: const Color(0xFF7B6570),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,355 @@
|
||||
import 'package:cached_network_image/cached_network_image.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_riverpod/flutter_riverpod.dart';
|
||||
|
||||
import '../core/manga_collections.dart';
|
||||
import '../core/providers.dart';
|
||||
import '../models/artwork.dart';
|
||||
import '../models/novel.dart';
|
||||
import 'artwork_detail_page.dart';
|
||||
import 'novel_reader_page.dart';
|
||||
|
||||
class FavoritesPage extends ConsumerStatefulWidget {
|
||||
const FavoritesPage({super.key, this.initialIndex = 0});
|
||||
|
||||
final int initialIndex;
|
||||
|
||||
@override
|
||||
ConsumerState<FavoritesPage> createState() => _FavoritesPageState();
|
||||
}
|
||||
|
||||
class _FavoritesPageState extends ConsumerState<FavoritesPage> with SingleTickerProviderStateMixin {
|
||||
late final TabController controller = TabController(
|
||||
length: 2,
|
||||
vsync: this,
|
||||
initialIndex: widget.initialIndex.clamp(0, 1),
|
||||
);
|
||||
late Future<_FavoritesData> future = _load();
|
||||
|
||||
Future<_FavoritesData> _load() async {
|
||||
final api = ref.read(apiClientProvider);
|
||||
final results = await Future.wait<List<dynamic>>([
|
||||
api.gallery(isFavorite: true, limit: 100),
|
||||
api.novels(isFavorite: true),
|
||||
]);
|
||||
return _FavoritesData(
|
||||
artworks: results[0].map((item) => Artwork.fromJson(item as Map<String, dynamic>)).toList(),
|
||||
novels: results[1].map((item) => Novel.fromJson(item as Map<String, dynamic>)).toList(),
|
||||
);
|
||||
}
|
||||
|
||||
void _refresh() {
|
||||
ref.invalidate(apiClientProvider);
|
||||
setState(() {
|
||||
future = _load();
|
||||
});
|
||||
}
|
||||
|
||||
Future<void> _openArtwork(Artwork item, List<Artwork> artworks) async {
|
||||
final mangaCollection = item.contentType == 'manga'
|
||||
? findMangaCollectionForArtwork(artworks, item)
|
||||
: null;
|
||||
final changed = await Navigator.of(context).push<bool>(
|
||||
MaterialPageRoute(
|
||||
builder: (_) => ArtworkDetailPage(
|
||||
artwork: item,
|
||||
artworkSequence: mangaCollection?.items,
|
||||
titleOverride: mangaCollection?.title,
|
||||
initialIndex: mangaCollection?.items
|
||||
.indexWhere((entry) => entry.id == item.id),
|
||||
),
|
||||
),
|
||||
);
|
||||
if (changed == true && mounted) {
|
||||
_refresh();
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> _openNovel(Novel item) async {
|
||||
final changed = await Navigator.of(context).push<bool>(
|
||||
MaterialPageRoute(builder: (_) => NovelReaderPage(novel: item)),
|
||||
);
|
||||
if (changed == true && mounted) {
|
||||
_refresh();
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
controller.dispose();
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final api = ref.watch(apiClientProvider);
|
||||
final headers = api.authHeaders();
|
||||
final theme = Theme.of(context);
|
||||
|
||||
return Scaffold(
|
||||
appBar: AppBar(
|
||||
title: const Text('我的收藏'),
|
||||
bottom: TabBar(
|
||||
controller: controller,
|
||||
tabs: const [
|
||||
Tab(text: '收藏图片'),
|
||||
Tab(text: '收藏小说'),
|
||||
],
|
||||
),
|
||||
),
|
||||
body: FutureBuilder<_FavoritesData>(
|
||||
future: future,
|
||||
builder: (context, snapshot) {
|
||||
if (snapshot.hasError) {
|
||||
return const Center(child: Text('收藏内容加载失败,请稍后再试。'));
|
||||
}
|
||||
if (!snapshot.hasData) {
|
||||
return const Center(child: CircularProgressIndicator());
|
||||
}
|
||||
|
||||
final data = snapshot.data!;
|
||||
return TabBarView(
|
||||
controller: controller,
|
||||
children: [
|
||||
data.artworks.isEmpty
|
||||
? const _FavoriteEmptyState(
|
||||
icon: Icons.favorite_border,
|
||||
title: '还没有收藏图片',
|
||||
message: '在画廊里点一下爱心,喜欢的图片就会出现在这里。',
|
||||
)
|
||||
: GridView.builder(
|
||||
padding: const EdgeInsets.all(12),
|
||||
gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
|
||||
crossAxisCount: 2,
|
||||
crossAxisSpacing: 10,
|
||||
mainAxisSpacing: 10,
|
||||
childAspectRatio: 0.72,
|
||||
),
|
||||
itemCount: data.artworks.length,
|
||||
itemBuilder: (context, index) {
|
||||
final item = data.artworks[index];
|
||||
final thumbUrl = api.resolveUrl(item.thumbnailUrl ?? item.thumbnailPath);
|
||||
|
||||
return Card(
|
||||
clipBehavior: Clip.antiAlias,
|
||||
child: InkWell(
|
||||
onTap: () => _openArtwork(item, data.artworks),
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.all(12),
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Expanded(
|
||||
child: ClipRRect(
|
||||
borderRadius: BorderRadius.circular(16),
|
||||
child: thumbUrl.isEmpty
|
||||
? DecoratedBox(
|
||||
decoration: BoxDecoration(
|
||||
color: theme.colorScheme.surfaceContainerHighest,
|
||||
),
|
||||
child: const Center(child: Icon(Icons.image_outlined, size: 38)),
|
||||
)
|
||||
: CachedNetworkImage(
|
||||
imageUrl: thumbUrl,
|
||||
httpHeaders: headers,
|
||||
fit: BoxFit.cover,
|
||||
fadeInDuration: const Duration(milliseconds: 120),
|
||||
placeholder: (_, __) => const Center(
|
||||
child: CircularProgressIndicator(strokeWidth: 2),
|
||||
),
|
||||
errorWidget: (_, __, ___) => DecoratedBox(
|
||||
decoration: BoxDecoration(
|
||||
color: theme.colorScheme.surfaceContainerHighest,
|
||||
),
|
||||
child: const Center(
|
||||
child: Icon(Icons.broken_image_outlined, size: 32),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 10),
|
||||
Text(item.title, maxLines: 2, overflow: TextOverflow.ellipsis),
|
||||
const SizedBox(height: 4),
|
||||
Text(
|
||||
item.author?.isNotEmpty == true ? item.author! : item.sourcePlatform,
|
||||
maxLines: 1,
|
||||
overflow: TextOverflow.ellipsis,
|
||||
style: theme.textTheme.bodySmall?.copyWith(
|
||||
color: const Color(0xFF6E727A),
|
||||
),
|
||||
),
|
||||
if (item.tags.isNotEmpty) ...[
|
||||
const SizedBox(height: 8),
|
||||
Text(
|
||||
item.tags.take(2).join(' '),
|
||||
maxLines: 1,
|
||||
overflow: TextOverflow.ellipsis,
|
||||
style: theme.textTheme.bodySmall?.copyWith(
|
||||
color: const Color(0xFFB0662B),
|
||||
fontWeight: FontWeight.w600,
|
||||
),
|
||||
),
|
||||
],
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
},
|
||||
),
|
||||
data.novels.isEmpty
|
||||
? const _FavoriteEmptyState(
|
||||
icon: Icons.auto_stories_outlined,
|
||||
title: '还没有收藏小说',
|
||||
message: '在书架或阅读页点一下爱心,喜欢的小说就会收进这里。',
|
||||
)
|
||||
: GridView.builder(
|
||||
padding: const EdgeInsets.all(12),
|
||||
gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
|
||||
crossAxisCount: 3,
|
||||
crossAxisSpacing: 12,
|
||||
mainAxisSpacing: 16,
|
||||
childAspectRatio: 0.56,
|
||||
),
|
||||
itemCount: data.novels.length,
|
||||
itemBuilder: (context, index) {
|
||||
final item = data.novels[index];
|
||||
final coverUrl = api.resolveUrl(item.coverPath);
|
||||
|
||||
return InkWell(
|
||||
borderRadius: BorderRadius.circular(20),
|
||||
onTap: () => _openNovel(item),
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Expanded(
|
||||
child: ClipRRect(
|
||||
borderRadius: BorderRadius.circular(18),
|
||||
child: coverUrl.isEmpty
|
||||
? DecoratedBox(
|
||||
decoration: BoxDecoration(
|
||||
gradient: LinearGradient(
|
||||
colors: _coverColors(index),
|
||||
begin: Alignment.topLeft,
|
||||
end: Alignment.bottomRight,
|
||||
),
|
||||
),
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.all(12),
|
||||
child: Align(
|
||||
alignment: Alignment.topLeft,
|
||||
child: Text(
|
||||
item.title,
|
||||
maxLines: 5,
|
||||
overflow: TextOverflow.ellipsis,
|
||||
style: theme.textTheme.titleMedium?.copyWith(
|
||||
color: Colors.white,
|
||||
fontWeight: FontWeight.w800,
|
||||
height: 1.25,
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
)
|
||||
: CachedNetworkImage(
|
||||
imageUrl: coverUrl,
|
||||
httpHeaders: headers,
|
||||
fit: BoxFit.cover,
|
||||
fadeInDuration: const Duration(milliseconds: 120),
|
||||
placeholder: (_, __) => DecoratedBox(
|
||||
decoration: BoxDecoration(
|
||||
gradient: LinearGradient(
|
||||
colors: _coverColors(index),
|
||||
begin: Alignment.topLeft,
|
||||
end: Alignment.bottomRight,
|
||||
),
|
||||
),
|
||||
child: const Center(
|
||||
child: CircularProgressIndicator(strokeWidth: 2),
|
||||
),
|
||||
),
|
||||
errorWidget: (_, __, ___) => DecoratedBox(
|
||||
decoration: BoxDecoration(
|
||||
gradient: LinearGradient(
|
||||
colors: _coverColors(index),
|
||||
begin: Alignment.topLeft,
|
||||
end: Alignment.bottomRight,
|
||||
),
|
||||
),
|
||||
child: const Icon(
|
||||
Icons.menu_book_outlined,
|
||||
color: Colors.white,
|
||||
size: 34,
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 8),
|
||||
Text(item.title, maxLines: 2, overflow: TextOverflow.ellipsis),
|
||||
const SizedBox(height: 4),
|
||||
Text(
|
||||
'读到第 ${item.currentPage + 1} 页',
|
||||
style: theme.textTheme.bodySmall?.copyWith(
|
||||
color: const Color(0xFF6E727A),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
},
|
||||
),
|
||||
],
|
||||
);
|
||||
},
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
static List<Color> _coverColors(int index) {
|
||||
const palettes = [
|
||||
[Color(0xFF7A4D2A), Color(0xFFC48B54)],
|
||||
[Color(0xFF32558C), Color(0xFF6E8DD0)],
|
||||
[Color(0xFF5B3447), Color(0xFFB36B8D)],
|
||||
[Color(0xFF21504A), Color(0xFF59A093)],
|
||||
];
|
||||
return palettes[index % palettes.length];
|
||||
}
|
||||
}
|
||||
|
||||
class _FavoritesData {
|
||||
const _FavoritesData({required this.artworks, required this.novels});
|
||||
|
||||
final List<Artwork> artworks;
|
||||
final List<Novel> novels;
|
||||
}
|
||||
|
||||
class _FavoriteEmptyState extends StatelessWidget {
|
||||
const _FavoriteEmptyState({
|
||||
required this.icon,
|
||||
required this.title,
|
||||
required this.message,
|
||||
});
|
||||
|
||||
final IconData icon;
|
||||
final String title;
|
||||
final String message;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Padding(
|
||||
padding: const EdgeInsets.all(24),
|
||||
child: Column(
|
||||
mainAxisAlignment: MainAxisAlignment.center,
|
||||
children: [
|
||||
Icon(icon, size: 44, color: Theme.of(context).colorScheme.primary),
|
||||
const SizedBox(height: 14),
|
||||
Text(title, style: Theme.of(context).textTheme.titleLarge),
|
||||
const SizedBox(height: 8),
|
||||
Text(message, textAlign: TextAlign.center),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,83 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_riverpod/flutter_riverpod.dart';
|
||||
|
||||
import '../core/providers.dart';
|
||||
import 'login_page.dart';
|
||||
import 'tabs/feed_tab.dart';
|
||||
import 'tabs/gallery_tab.dart';
|
||||
import 'tabs/novels_tab.dart';
|
||||
import 'tabs/profile_tab.dart';
|
||||
|
||||
class HomePage extends ConsumerStatefulWidget {
|
||||
const HomePage({super.key});
|
||||
|
||||
@override
|
||||
ConsumerState<HomePage> createState() => _HomePageState();
|
||||
}
|
||||
|
||||
class _HomePageState extends ConsumerState<HomePage> {
|
||||
int index = 0;
|
||||
|
||||
final pages = const [
|
||||
FeedTab(key: ValueKey('feed-tab')),
|
||||
GalleryTab(
|
||||
key: ValueKey('gallery-illust-tab'),
|
||||
pageTitle: '图片图库',
|
||||
fixedContentType: 'illust',
|
||||
showTypeFilters: false,
|
||||
),
|
||||
GalleryTab(
|
||||
key: ValueKey('gallery-manga-tab'),
|
||||
pageTitle: '漫画图库',
|
||||
fixedContentType: 'manga',
|
||||
showTypeFilters: false,
|
||||
),
|
||||
NovelsTab(key: ValueKey('novels-tab')),
|
||||
ProfileTab(key: ValueKey('profile-tab')),
|
||||
];
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final session = ref.watch(sessionProvider);
|
||||
if (session.loading) {
|
||||
return const Scaffold(body: Center(child: CircularProgressIndicator()));
|
||||
}
|
||||
if (!session.signedIn) {
|
||||
return const LoginPage();
|
||||
}
|
||||
return Scaffold(
|
||||
body: SafeArea(
|
||||
child: AnimatedSwitcher(
|
||||
duration: const Duration(milliseconds: 220),
|
||||
child: pages[index],
|
||||
),
|
||||
),
|
||||
bottomNavigationBar: NavigationBar(
|
||||
selectedIndex: index,
|
||||
onDestinationSelected: (value) => setState(() => index = value),
|
||||
destinations: const [
|
||||
NavigationDestination(
|
||||
icon: Icon(Icons.local_florist_rounded),
|
||||
label: '发现',
|
||||
),
|
||||
NavigationDestination(
|
||||
icon: Icon(Icons.image_outlined),
|
||||
label: '图片',
|
||||
),
|
||||
NavigationDestination(
|
||||
icon: Icon(Icons.menu_book_rounded),
|
||||
label: '漫画',
|
||||
),
|
||||
NavigationDestination(
|
||||
icon: Icon(Icons.auto_stories_rounded),
|
||||
label: '书架',
|
||||
),
|
||||
NavigationDestination(
|
||||
icon: Icon(Icons.person_outline),
|
||||
label: '我的',
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,411 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_riverpod/flutter_riverpod.dart';
|
||||
|
||||
import '../core/providers.dart';
|
||||
|
||||
class LoginPage extends ConsumerStatefulWidget {
|
||||
const LoginPage({super.key});
|
||||
|
||||
@override
|
||||
ConsumerState<LoginPage> createState() => _LoginPageState();
|
||||
}
|
||||
|
||||
class _LoginPageState extends ConsumerState<LoginPage> with SingleTickerProviderStateMixin {
|
||||
final account = TextEditingController();
|
||||
final password = TextEditingController();
|
||||
final registerUsername = TextEditingController();
|
||||
final registerEmail = TextEditingController();
|
||||
final registerPassword = TextEditingController();
|
||||
final registerConfirmPassword = TextEditingController();
|
||||
|
||||
late final TabController _tabController;
|
||||
String? _message;
|
||||
bool _messageIsError = false;
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
_tabController = TabController(length: 2, vsync: this);
|
||||
_tabController.addListener(() {
|
||||
if (!_tabController.indexIsChanging && mounted) {
|
||||
ref.read(sessionProvider.notifier).clearError();
|
||||
setState(() {
|
||||
_message = null;
|
||||
_messageIsError = false;
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
_tabController.dispose();
|
||||
account.dispose();
|
||||
password.dispose();
|
||||
registerUsername.dispose();
|
||||
registerEmail.dispose();
|
||||
registerPassword.dispose();
|
||||
registerConfirmPassword.dispose();
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final session = ref.watch(sessionProvider);
|
||||
final bannerText = session.error ?? _message;
|
||||
final bannerIsError = session.error != null || _messageIsError;
|
||||
final theme = Theme.of(context);
|
||||
|
||||
return Scaffold(
|
||||
body: DecoratedBox(
|
||||
decoration: const BoxDecoration(
|
||||
gradient: LinearGradient(
|
||||
begin: Alignment.topCenter,
|
||||
end: Alignment.bottomCenter,
|
||||
colors: [Color(0xFFFFF7FA), Color(0xFFFFE8F0)],
|
||||
),
|
||||
),
|
||||
child: SafeArea(
|
||||
child: Center(
|
||||
child: ConstrainedBox(
|
||||
constraints: const BoxConstraints(maxWidth: 520),
|
||||
child: ListView(
|
||||
padding: const EdgeInsets.fromLTRB(20, 24, 20, 28),
|
||||
children: [
|
||||
Container(
|
||||
padding: const EdgeInsets.fromLTRB(22, 24, 22, 24),
|
||||
decoration: BoxDecoration(
|
||||
color: Colors.white.withValues(alpha: 0.96),
|
||||
borderRadius: BorderRadius.circular(30),
|
||||
boxShadow: const [
|
||||
BoxShadow(
|
||||
color: Color(0x160F2740),
|
||||
blurRadius: 28,
|
||||
offset: Offset(0, 12),
|
||||
),
|
||||
],
|
||||
),
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Container(
|
||||
width: 58,
|
||||
height: 58,
|
||||
decoration: BoxDecoration(
|
||||
color: const Color(0xFFD95A83).withValues(alpha: 0.12),
|
||||
borderRadius: BorderRadius.circular(18),
|
||||
),
|
||||
child: const Icon(Icons.cloud_done_outlined, color: Color(0xFFD95A83), size: 30),
|
||||
),
|
||||
const SizedBox(height: 18),
|
||||
Text(
|
||||
'樱云同步',
|
||||
style: theme.textTheme.headlineMedium?.copyWith(fontWeight: FontWeight.w800),
|
||||
),
|
||||
const SizedBox(height: 10),
|
||||
Text(
|
||||
'一个账号管理你的收藏、阅读进度和移动端浏览体验。',
|
||||
style: theme.textTheme.bodyLarge?.copyWith(
|
||||
color: const Color(0xFF607287),
|
||||
height: 1.55,
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 20),
|
||||
Container(
|
||||
decoration: BoxDecoration(
|
||||
color: const Color(0xFFFFF1F6),
|
||||
borderRadius: BorderRadius.circular(18),
|
||||
),
|
||||
child: TabBar(
|
||||
controller: _tabController,
|
||||
indicator: const UnderlineTabIndicator(
|
||||
borderSide: BorderSide(color: Color(0xFFD95A83), width: 3),
|
||||
insets: EdgeInsets.symmetric(horizontal: 28),
|
||||
),
|
||||
indicatorSize: TabBarIndicatorSize.label,
|
||||
labelColor: const Color(0xFFD95A83),
|
||||
unselectedLabelColor: const Color(0xFF5A6D80),
|
||||
dividerColor: Colors.transparent,
|
||||
tabs: const [
|
||||
Tab(text: '登录'),
|
||||
Tab(text: '注册'),
|
||||
],
|
||||
),
|
||||
),
|
||||
if (bannerText != null) ...[
|
||||
const SizedBox(height: 16),
|
||||
_StatusBanner(text: bannerText, isError: bannerIsError),
|
||||
],
|
||||
const SizedBox(height: 18),
|
||||
SizedBox(
|
||||
height: 430,
|
||||
child: TabBarView(
|
||||
controller: _tabController,
|
||||
children: [
|
||||
_LoginForm(
|
||||
account: account,
|
||||
password: password,
|
||||
loading: session.loading,
|
||||
onSubmit: _submitLogin,
|
||||
),
|
||||
_RegisterForm(
|
||||
username: registerUsername,
|
||||
email: registerEmail,
|
||||
password: registerPassword,
|
||||
confirmPassword: registerConfirmPassword,
|
||||
loading: session.loading,
|
||||
onSubmit: _submitRegister,
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Future<void> _submitLogin() async {
|
||||
final loginId = account.text.trim();
|
||||
final pwd = password.text;
|
||||
if (loginId.isEmpty || pwd.isEmpty) {
|
||||
_showMessage('请输入账号和密码。', isError: true);
|
||||
return;
|
||||
}
|
||||
|
||||
_showMessage(null);
|
||||
final notifier = ref.read(sessionProvider.notifier);
|
||||
notifier.clearError();
|
||||
await notifier.login(loginId, pwd);
|
||||
}
|
||||
|
||||
Future<void> _submitRegister() async {
|
||||
final username = registerUsername.text.trim();
|
||||
final email = registerEmail.text.trim();
|
||||
final pwd = registerPassword.text;
|
||||
final confirmPwd = registerConfirmPassword.text;
|
||||
|
||||
if (username.length < 3) {
|
||||
_showMessage('用户名至少需要 3 个字符。', isError: true);
|
||||
return;
|
||||
}
|
||||
if (!_looksLikeEmail(email)) {
|
||||
_showMessage('请输入有效的邮箱地址。', isError: true);
|
||||
return;
|
||||
}
|
||||
if (pwd.length < 8) {
|
||||
_showMessage('密码至少需要 8 位。', isError: true);
|
||||
return;
|
||||
}
|
||||
if (pwd != confirmPwd) {
|
||||
_showMessage('两次输入的密码不一致。', isError: true);
|
||||
return;
|
||||
}
|
||||
|
||||
_showMessage(null);
|
||||
final notifier = ref.read(sessionProvider.notifier);
|
||||
notifier.clearError();
|
||||
try {
|
||||
await notifier.register(username, email, pwd);
|
||||
if (!mounted) return;
|
||||
account.text = email;
|
||||
password.clear();
|
||||
_tabController.animateTo(0);
|
||||
_showMessage('注册成功,请使用刚刚创建的账号登录。');
|
||||
} catch (_) {
|
||||
if (!mounted) return;
|
||||
}
|
||||
}
|
||||
|
||||
bool _looksLikeEmail(String value) {
|
||||
return RegExp(r'^[^@\s]+@[^@\s]+\.[^@\s]+$').hasMatch(value);
|
||||
}
|
||||
|
||||
void _showMessage(String? text, {bool isError = false}) {
|
||||
if (!mounted) return;
|
||||
setState(() {
|
||||
_message = text;
|
||||
_messageIsError = isError;
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
class _LoginForm extends StatelessWidget {
|
||||
const _LoginForm({
|
||||
required this.account,
|
||||
required this.password,
|
||||
required this.loading,
|
||||
required this.onSubmit,
|
||||
});
|
||||
|
||||
final TextEditingController account;
|
||||
final TextEditingController password;
|
||||
final bool loading;
|
||||
final Future<void> Function() onSubmit;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return ListView(
|
||||
physics: const NeverScrollableScrollPhysics(),
|
||||
children: [
|
||||
const SizedBox(height: 4),
|
||||
TextField(
|
||||
controller: account,
|
||||
decoration: const InputDecoration(
|
||||
labelText: '邮箱或用户名',
|
||||
prefixIcon: Icon(Icons.person_outline),
|
||||
hintText: '请输入邮箱或用户名',
|
||||
),
|
||||
textInputAction: TextInputAction.next,
|
||||
),
|
||||
const SizedBox(height: 14),
|
||||
TextField(
|
||||
controller: password,
|
||||
decoration: const InputDecoration(
|
||||
labelText: '密码',
|
||||
prefixIcon: Icon(Icons.lock_outline),
|
||||
hintText: '请输入密码',
|
||||
),
|
||||
obscureText: true,
|
||||
onSubmitted: (_) => onSubmit(),
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
Text(
|
||||
'推荐使用邮箱登录,后续找回账号和多设备同步都会更方便。',
|
||||
style: Theme.of(context).textTheme.bodySmall?.copyWith(color: const Color(0xFF6B7B8D), height: 1.5),
|
||||
),
|
||||
const SizedBox(height: 24),
|
||||
FilledButton.icon(
|
||||
onPressed: loading ? null : onSubmit,
|
||||
icon: loading
|
||||
? const SizedBox(width: 18, height: 18, child: CircularProgressIndicator(strokeWidth: 2))
|
||||
: const Icon(Icons.login),
|
||||
label: const Text('登录'),
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class _RegisterForm extends StatelessWidget {
|
||||
const _RegisterForm({
|
||||
required this.username,
|
||||
required this.email,
|
||||
required this.password,
|
||||
required this.confirmPassword,
|
||||
required this.loading,
|
||||
required this.onSubmit,
|
||||
});
|
||||
|
||||
final TextEditingController username;
|
||||
final TextEditingController email;
|
||||
final TextEditingController password;
|
||||
final TextEditingController confirmPassword;
|
||||
final bool loading;
|
||||
final Future<void> Function() onSubmit;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return ListView(
|
||||
physics: const NeverScrollableScrollPhysics(),
|
||||
children: [
|
||||
const SizedBox(height: 4),
|
||||
TextField(
|
||||
controller: username,
|
||||
decoration: const InputDecoration(
|
||||
labelText: '用户名',
|
||||
prefixIcon: Icon(Icons.badge_outlined),
|
||||
hintText: '至少 3 个字符',
|
||||
),
|
||||
textInputAction: TextInputAction.next,
|
||||
),
|
||||
const SizedBox(height: 12),
|
||||
TextField(
|
||||
controller: email,
|
||||
decoration: const InputDecoration(
|
||||
labelText: '邮箱',
|
||||
prefixIcon: Icon(Icons.mail_outline),
|
||||
hintText: 'name@example.com',
|
||||
),
|
||||
keyboardType: TextInputType.emailAddress,
|
||||
textInputAction: TextInputAction.next,
|
||||
),
|
||||
const SizedBox(height: 12),
|
||||
TextField(
|
||||
controller: password,
|
||||
decoration: const InputDecoration(
|
||||
labelText: '密码',
|
||||
prefixIcon: Icon(Icons.lock_outline),
|
||||
hintText: '至少 8 位',
|
||||
),
|
||||
obscureText: true,
|
||||
textInputAction: TextInputAction.next,
|
||||
),
|
||||
const SizedBox(height: 12),
|
||||
TextField(
|
||||
controller: confirmPassword,
|
||||
decoration: const InputDecoration(
|
||||
labelText: '确认密码',
|
||||
prefixIcon: Icon(Icons.verified_user_outlined),
|
||||
hintText: '请再次输入密码',
|
||||
),
|
||||
obscureText: true,
|
||||
onSubmitted: (_) => onSubmit(),
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
Text(
|
||||
'注册完成后不会自动登录,返回登录页即可继续使用。',
|
||||
style: Theme.of(context).textTheme.bodySmall?.copyWith(color: const Color(0xFF6B7B8D), height: 1.5),
|
||||
),
|
||||
const SizedBox(height: 24),
|
||||
FilledButton.icon(
|
||||
onPressed: loading ? null : onSubmit,
|
||||
icon: loading
|
||||
? const SizedBox(width: 18, height: 18, child: CircularProgressIndicator(strokeWidth: 2))
|
||||
: const Icon(Icons.person_add_alt_1),
|
||||
label: const Text('注册'),
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class _StatusBanner extends StatelessWidget {
|
||||
const _StatusBanner({required this.text, required this.isError});
|
||||
|
||||
final String text;
|
||||
final bool isError;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final foreground = isError ? const Color(0xFF8A1C1C) : const Color(0xFF0E6245);
|
||||
final background = isError ? const Color(0xFFFFEFEF) : const Color(0xFFEAF9F1);
|
||||
final icon = isError ? Icons.error_outline : Icons.check_circle_outline;
|
||||
return Container(
|
||||
padding: const EdgeInsets.all(14),
|
||||
decoration: BoxDecoration(
|
||||
color: background,
|
||||
borderRadius: BorderRadius.circular(16),
|
||||
),
|
||||
child: Row(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Icon(icon, color: foreground, size: 20),
|
||||
const SizedBox(width: 10),
|
||||
Expanded(
|
||||
child: Text(
|
||||
text,
|
||||
style: Theme.of(context).textTheme.bodyMedium?.copyWith(color: foreground, height: 1.45),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,401 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_riverpod/flutter_riverpod.dart';
|
||||
|
||||
import '../core/providers.dart';
|
||||
import '../models/novel.dart';
|
||||
import 'novel_reader_page.dart';
|
||||
|
||||
class NovelDetailPage extends ConsumerStatefulWidget {
|
||||
const NovelDetailPage({
|
||||
super.key,
|
||||
required this.title,
|
||||
required this.chapters,
|
||||
this.author,
|
||||
});
|
||||
|
||||
final String title;
|
||||
final String? author;
|
||||
final List<Novel> chapters;
|
||||
|
||||
@override
|
||||
ConsumerState<NovelDetailPage> createState() => _NovelDetailPageState();
|
||||
}
|
||||
|
||||
class _NovelDetailPageState extends ConsumerState<NovelDetailPage> {
|
||||
final ScrollController _scrollController = ScrollController();
|
||||
bool _changed = false;
|
||||
|
||||
List<Novel> get _chapters {
|
||||
final chapters = [...widget.chapters];
|
||||
chapters.sort((a, b) {
|
||||
final orderDelta = a.chapterOrder.compareTo(b.chapterOrder);
|
||||
if (orderDelta != 0) {
|
||||
return orderDelta;
|
||||
}
|
||||
return a.displayChapterTitle.compareTo(b.displayChapterTitle);
|
||||
});
|
||||
return chapters;
|
||||
}
|
||||
|
||||
Novel get _firstChapter => _chapters.first;
|
||||
|
||||
Novel get _continueChapter {
|
||||
final chapters = _chapters;
|
||||
final read = chapters
|
||||
.where((item) => item.lastReadAt != null || item.currentPage > 0)
|
||||
.toList()
|
||||
..sort((a, b) {
|
||||
final aTime = a.lastReadAt ?? DateTime.fromMillisecondsSinceEpoch(0);
|
||||
final bTime = b.lastReadAt ?? DateTime.fromMillisecondsSinceEpoch(0);
|
||||
return bTime.compareTo(aTime);
|
||||
});
|
||||
return read.isNotEmpty ? read.first : chapters.first;
|
||||
}
|
||||
|
||||
Future<void> _openReader(Novel novel, {bool fromStart = false}) async {
|
||||
final target = fromStart ? novel.copyWith(currentPage: 0) : novel;
|
||||
final changed = await Navigator.of(context).push<bool>(
|
||||
MaterialPageRoute(builder: (_) => NovelReaderPage(novel: target)),
|
||||
);
|
||||
if (changed == true) {
|
||||
_changed = true;
|
||||
}
|
||||
}
|
||||
|
||||
void _scrollToCatalog() {
|
||||
_scrollController.animateTo(
|
||||
430,
|
||||
duration: const Duration(milliseconds: 260),
|
||||
curve: Curves.easeOutCubic,
|
||||
);
|
||||
}
|
||||
|
||||
void _close() {
|
||||
Navigator.of(context).pop(_changed);
|
||||
}
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
_scrollController.dispose();
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final chapters = _chapters;
|
||||
final first = _firstChapter;
|
||||
final title = widget.title.trim().isNotEmpty ? widget.title : first.title;
|
||||
final author = widget.author?.trim().isNotEmpty == true
|
||||
? widget.author!
|
||||
: (first.author?.trim().isNotEmpty == true ? first.author! : '未知作者');
|
||||
final latest = chapters.last;
|
||||
final coverUrl = ref.read(apiClientProvider).resolveUrl(first.coverPath);
|
||||
final description = first.description?.trim();
|
||||
|
||||
return Scaffold(
|
||||
appBar: AppBar(
|
||||
title: Text(title, maxLines: 1, overflow: TextOverflow.ellipsis),
|
||||
leading: IconButton(
|
||||
icon: const Icon(Icons.arrow_back),
|
||||
onPressed: _close,
|
||||
),
|
||||
),
|
||||
body: ListView(
|
||||
controller: _scrollController,
|
||||
padding: const EdgeInsets.fromLTRB(16, 12, 16, 28),
|
||||
children: [
|
||||
Row(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
_NovelDetailCover(coverUrl: coverUrl, title: title),
|
||||
const SizedBox(width: 16),
|
||||
Expanded(
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Text(
|
||||
title,
|
||||
style: Theme.of(context).textTheme.headlineSmall?.copyWith(
|
||||
fontWeight: FontWeight.w800,
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 8),
|
||||
_MetaLine(label: '作者', value: author),
|
||||
_MetaLine(label: '章节', value: '${chapters.length} 章'),
|
||||
_MetaLine(
|
||||
label: '最新',
|
||||
value: latest.displayChapterTitle,
|
||||
highlight: true,
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
const SizedBox(height: 18),
|
||||
_ActionGrid(
|
||||
onContinue: () => _openReader(_continueChapter),
|
||||
onCatalog: _scrollToCatalog,
|
||||
onStart: () => _openReader(first, fromStart: true),
|
||||
),
|
||||
if (description != null && description.isNotEmpty) ...[
|
||||
const SizedBox(height: 18),
|
||||
Text(
|
||||
'内容简介',
|
||||
style: Theme.of(context).textTheme.titleMedium?.copyWith(
|
||||
fontWeight: FontWeight.w800,
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 8),
|
||||
Text(
|
||||
description,
|
||||
style: Theme.of(context).textTheme.bodyMedium?.copyWith(
|
||||
color: const Color(0xFF6F6470),
|
||||
height: 1.6,
|
||||
),
|
||||
),
|
||||
],
|
||||
const SizedBox(height: 22),
|
||||
Row(
|
||||
children: [
|
||||
Expanded(
|
||||
child: Text(
|
||||
'目录',
|
||||
style: Theme.of(context).textTheme.titleLarge?.copyWith(
|
||||
fontWeight: FontWeight.w800,
|
||||
),
|
||||
),
|
||||
),
|
||||
Text(
|
||||
'${chapters.length} 章',
|
||||
style: Theme.of(context).textTheme.bodyMedium?.copyWith(
|
||||
color: const Color(0xFF8D7B84),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
const SizedBox(height: 10),
|
||||
DecoratedBox(
|
||||
decoration: BoxDecoration(
|
||||
color: Colors.white,
|
||||
borderRadius: BorderRadius.circular(18),
|
||||
border: Border.all(color: const Color(0xFFFFD5E1)),
|
||||
),
|
||||
child: Column(
|
||||
children: [
|
||||
for (var index = 0; index < chapters.length; index++)
|
||||
_ChapterRow(
|
||||
index: index,
|
||||
chapter: chapters[index],
|
||||
isLast: index == chapters.length - 1,
|
||||
onTap: () => _openReader(chapters[index]),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class _NovelDetailCover extends StatelessWidget {
|
||||
const _NovelDetailCover({required this.coverUrl, required this.title});
|
||||
|
||||
final String coverUrl;
|
||||
final String title;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return ClipRRect(
|
||||
borderRadius: BorderRadius.circular(16),
|
||||
child: SizedBox(
|
||||
width: 104,
|
||||
child: AspectRatio(
|
||||
aspectRatio: 0.72,
|
||||
child: ColoredBox(
|
||||
color: const Color(0xFFFFE7EF),
|
||||
child: coverUrl.isEmpty
|
||||
? _CoverFallback(title: title)
|
||||
: Image.network(
|
||||
coverUrl,
|
||||
fit: BoxFit.cover,
|
||||
errorBuilder: (_, __, ___) => _CoverFallback(title: title),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class _CoverFallback extends StatelessWidget {
|
||||
const _CoverFallback({required this.title});
|
||||
|
||||
final String title;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Padding(
|
||||
padding: const EdgeInsets.all(12),
|
||||
child: Center(
|
||||
child: Text(
|
||||
title,
|
||||
maxLines: 5,
|
||||
overflow: TextOverflow.ellipsis,
|
||||
textAlign: TextAlign.center,
|
||||
style: Theme.of(context).textTheme.titleSmall?.copyWith(
|
||||
color: const Color(0xFFD95A83),
|
||||
fontWeight: FontWeight.w800,
|
||||
height: 1.3,
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class _MetaLine extends StatelessWidget {
|
||||
const _MetaLine({
|
||||
required this.label,
|
||||
required this.value,
|
||||
this.highlight = false,
|
||||
});
|
||||
|
||||
final String label;
|
||||
final String value;
|
||||
final bool highlight;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Padding(
|
||||
padding: const EdgeInsets.only(bottom: 6),
|
||||
child: Row(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Text(
|
||||
'$label:',
|
||||
style: Theme.of(context).textTheme.bodyMedium?.copyWith(
|
||||
color: const Color(0xFF7B6570),
|
||||
),
|
||||
),
|
||||
Expanded(
|
||||
child: Text(
|
||||
value,
|
||||
maxLines: 2,
|
||||
overflow: TextOverflow.ellipsis,
|
||||
style: Theme.of(context).textTheme.bodyMedium?.copyWith(
|
||||
color: highlight
|
||||
? const Color(0xFFD95A83)
|
||||
: const Color(0xFF4F4650),
|
||||
fontWeight: highlight ? FontWeight.w700 : FontWeight.w500,
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class _ActionGrid extends StatelessWidget {
|
||||
const _ActionGrid({
|
||||
required this.onContinue,
|
||||
required this.onCatalog,
|
||||
required this.onStart,
|
||||
});
|
||||
|
||||
final VoidCallback onContinue;
|
||||
final VoidCallback onCatalog;
|
||||
final VoidCallback onStart;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return LayoutBuilder(
|
||||
builder: (context, constraints) {
|
||||
final buttons = [
|
||||
FilledButton.icon(
|
||||
onPressed: onContinue,
|
||||
icon: const Icon(Icons.play_arrow_rounded),
|
||||
label: const Text('继续阅读'),
|
||||
),
|
||||
FilledButton.tonalIcon(
|
||||
onPressed: onCatalog,
|
||||
icon: const Icon(Icons.list_alt_rounded),
|
||||
label: const Text('目录'),
|
||||
),
|
||||
OutlinedButton.icon(
|
||||
onPressed: onStart,
|
||||
icon: const Icon(Icons.first_page_rounded),
|
||||
label: const Text('从头开始'),
|
||||
),
|
||||
];
|
||||
if (constraints.maxWidth < 390) {
|
||||
return Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||
children: [
|
||||
for (var index = 0; index < buttons.length; index++) ...[
|
||||
buttons[index],
|
||||
if (index != buttons.length - 1) const SizedBox(height: 8),
|
||||
],
|
||||
],
|
||||
);
|
||||
}
|
||||
return Row(
|
||||
children: [
|
||||
for (var index = 0; index < buttons.length; index++) ...[
|
||||
Expanded(child: buttons[index]),
|
||||
if (index != buttons.length - 1) const SizedBox(width: 8),
|
||||
],
|
||||
],
|
||||
);
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class _ChapterRow extends StatelessWidget {
|
||||
const _ChapterRow({
|
||||
required this.index,
|
||||
required this.chapter,
|
||||
required this.isLast,
|
||||
required this.onTap,
|
||||
});
|
||||
|
||||
final int index;
|
||||
final Novel chapter;
|
||||
final bool isLast;
|
||||
final VoidCallback onTap;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final readLabel = chapter.lastReadAt != null || chapter.currentPage > 0
|
||||
? '已读到第 ${chapter.currentPage + 1} 页'
|
||||
: '未开始';
|
||||
return Column(
|
||||
children: [
|
||||
ListTile(
|
||||
contentPadding: const EdgeInsets.symmetric(horizontal: 14),
|
||||
leading: Text(
|
||||
'${index + 1}'.padLeft(2, '0'),
|
||||
style: Theme.of(context).textTheme.labelLarge?.copyWith(
|
||||
color: const Color(0xFFD95A83),
|
||||
fontWeight: FontWeight.w800,
|
||||
),
|
||||
),
|
||||
title: Text(
|
||||
chapter.displayChapterTitle,
|
||||
maxLines: 1,
|
||||
overflow: TextOverflow.ellipsis,
|
||||
style: const TextStyle(fontWeight: FontWeight.w700),
|
||||
),
|
||||
subtitle: Text(readLabel),
|
||||
trailing: const Icon(Icons.chevron_right),
|
||||
onTap: onTap,
|
||||
),
|
||||
if (!isLast)
|
||||
const Divider(height: 1, indent: 14, endIndent: 14),
|
||||
],
|
||||
);
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,464 @@
|
||||
import 'package:cached_network_image/cached_network_image.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_riverpod/flutter_riverpod.dart';
|
||||
|
||||
import '../core/legado_models.dart';
|
||||
import '../core/providers.dart';
|
||||
import '../core/online_reading_history.dart';
|
||||
import '../core/api_client.dart';
|
||||
import 'online_manga_reader_page.dart';
|
||||
import 'online_novel_reader_page.dart';
|
||||
|
||||
class OnlineBookDetailPage extends ConsumerStatefulWidget {
|
||||
const OnlineBookDetailPage({
|
||||
super.key,
|
||||
required this.source,
|
||||
required this.detailUrl,
|
||||
required this.initialTitle,
|
||||
this.initialAuthor,
|
||||
this.initialCoverUrl,
|
||||
this.onSave,
|
||||
});
|
||||
|
||||
final LegadoSource source;
|
||||
final String detailUrl;
|
||||
final String initialTitle;
|
||||
final String? initialAuthor;
|
||||
final String? initialCoverUrl;
|
||||
final Future<void> Function()? onSave;
|
||||
|
||||
@override
|
||||
ConsumerState<OnlineBookDetailPage> createState() =>
|
||||
_OnlineBookDetailPageState();
|
||||
}
|
||||
|
||||
class _OnlineBookDetailPageState extends ConsumerState<OnlineBookDetailPage> {
|
||||
OnlineBookInfo? info;
|
||||
List<OnlineChapter> chapters = const [];
|
||||
Object? infoError;
|
||||
Object? tocError;
|
||||
bool loadingInfo = true;
|
||||
bool loadingToc = true;
|
||||
bool descending = false;
|
||||
bool saving = false;
|
||||
OnlineReadingRecord? readingRecord;
|
||||
final parsedContentByUrl = <String, OnlineChapterContent>{};
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
_load();
|
||||
}
|
||||
|
||||
Future<void> _load() async {
|
||||
if (widget.detailUrl.trim().isEmpty) {
|
||||
setState(() {
|
||||
loadingInfo = false;
|
||||
loadingToc = false;
|
||||
infoError = StateError('搜索结果缺少详情链接。');
|
||||
});
|
||||
return;
|
||||
}
|
||||
final engine = ref.read(legadoEngineProvider);
|
||||
try {
|
||||
final value = await engine.fetchBookInfo(
|
||||
widget.source,
|
||||
widget.detailUrl,
|
||||
initialTitle: widget.initialTitle,
|
||||
initialAuthor: widget.initialAuthor,
|
||||
initialCoverUrl: widget.initialCoverUrl,
|
||||
);
|
||||
if (!mounted) return;
|
||||
setState(() {
|
||||
info = value;
|
||||
loadingInfo = false;
|
||||
loadingToc = true;
|
||||
});
|
||||
await _loadToc(value.tocUrl);
|
||||
final record = await OnlineReadingHistory.find(
|
||||
widget.source.id,
|
||||
widget.detailUrl,
|
||||
);
|
||||
if (mounted) setState(() => readingRecord = record);
|
||||
} catch (error) {
|
||||
await _loadFromCloudParser(error);
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> _loadToc(String url) async {
|
||||
setState(() {
|
||||
tocError = null;
|
||||
loadingToc = true;
|
||||
});
|
||||
try {
|
||||
final value = await ref.read(legadoEngineProvider).fetchToc(
|
||||
widget.source,
|
||||
url,
|
||||
);
|
||||
if (!mounted) return;
|
||||
if (value.isEmpty) {
|
||||
await _loadFromCloudParser(StateError('Empty TOC'), keepInfo: true);
|
||||
return;
|
||||
}
|
||||
setState(() {
|
||||
chapters = value;
|
||||
loadingToc = false;
|
||||
});
|
||||
} catch (error) {
|
||||
if (!mounted) return;
|
||||
setState(() {
|
||||
tocError = error;
|
||||
loadingToc = false;
|
||||
});
|
||||
await _loadFromCloudParser(error, keepInfo: true);
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> _loadFromCloudParser(
|
||||
Object originalError, {
|
||||
bool keepInfo = false,
|
||||
}) async {
|
||||
if (!mounted) return;
|
||||
try {
|
||||
final parsed = await ref.read(apiClientProvider).parseOnlineContent(
|
||||
mode: widget.source.isManga ? 'manga' : 'novel',
|
||||
detailUrl: widget.detailUrl,
|
||||
);
|
||||
final converted = _convertParsedContent(parsed);
|
||||
if (converted.chapters.isEmpty) {
|
||||
throw StateError('Cloud parser returned empty chapters');
|
||||
}
|
||||
final record = await OnlineReadingHistory.find(
|
||||
widget.source.id,
|
||||
widget.detailUrl,
|
||||
);
|
||||
if (!mounted) return;
|
||||
setState(() {
|
||||
info = keepInfo && info != null
|
||||
? info
|
||||
: OnlineBookInfo(
|
||||
title: converted.title,
|
||||
author: widget.initialAuthor,
|
||||
coverUrl: converted.coverUrl,
|
||||
intro: null,
|
||||
tocUrl: widget.detailUrl,
|
||||
sourceName: widget.source.name,
|
||||
);
|
||||
chapters = converted.chapters;
|
||||
parsedContentByUrl
|
||||
..clear()
|
||||
..addAll(converted.contentByUrl);
|
||||
readingRecord = record;
|
||||
infoError = null;
|
||||
tocError = null;
|
||||
loadingInfo = false;
|
||||
loadingToc = false;
|
||||
});
|
||||
} catch (_) {
|
||||
if (!mounted) return;
|
||||
setState(() {
|
||||
if (keepInfo) {
|
||||
tocError = originalError;
|
||||
loadingToc = false;
|
||||
} else {
|
||||
infoError = originalError;
|
||||
loadingInfo = false;
|
||||
loadingToc = false;
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
_ParsedOnlineBook _convertParsedContent(OnlineParsedContent parsed) {
|
||||
final title = parsed.title.trim().isNotEmpty
|
||||
? parsed.title.trim()
|
||||
: widget.initialTitle;
|
||||
final cover = parsed.cover?.trim().isNotEmpty == true
|
||||
? parsed.cover!.trim()
|
||||
: widget.initialCoverUrl;
|
||||
final chapters = <OnlineChapter>[];
|
||||
final contentByUrl = <String, OnlineChapterContent>{};
|
||||
for (final item in parsed.chapters) {
|
||||
final rawUrl = item.url?.trim();
|
||||
final chapterUrl = rawUrl == null || rawUrl.isEmpty
|
||||
? '${widget.detailUrl}#parsed-${chapters.length + 1}'
|
||||
: rawUrl;
|
||||
final chapterTitle = item.name.trim().isNotEmpty
|
||||
? item.name.trim()
|
||||
: '第 ${chapters.length + 1} 章';
|
||||
final chapter = OnlineChapter(
|
||||
title: chapterTitle,
|
||||
url: chapterUrl,
|
||||
index: chapters.length + 1,
|
||||
);
|
||||
chapters.add(chapter);
|
||||
final text = item.content?.trim();
|
||||
if ((text != null && text.isNotEmpty) || item.images.isNotEmpty) {
|
||||
contentByUrl[chapterUrl] = OnlineChapterContent(
|
||||
title: chapterTitle,
|
||||
textContent: text,
|
||||
imageUrls: item.images,
|
||||
);
|
||||
}
|
||||
}
|
||||
return _ParsedOnlineBook(
|
||||
title: title,
|
||||
coverUrl: cover,
|
||||
chapters: chapters,
|
||||
contentByUrl: contentByUrl,
|
||||
);
|
||||
}
|
||||
|
||||
Future<void> _openChapter(int index) async {
|
||||
final page = widget.source.isManga
|
||||
? OnlineMangaReaderPage(
|
||||
source: widget.source,
|
||||
title: info?.title ?? widget.initialTitle,
|
||||
chapters: chapters,
|
||||
currentChapterIndex: index,
|
||||
detailUrl: widget.detailUrl,
|
||||
initialContentByUrl: parsedContentByUrl,
|
||||
)
|
||||
: OnlineNovelReaderPage(
|
||||
source: widget.source,
|
||||
title: info?.title ?? widget.initialTitle,
|
||||
chapters: chapters,
|
||||
currentChapterIndex: index,
|
||||
detailUrl: widget.detailUrl,
|
||||
initialContentByUrl: parsedContentByUrl,
|
||||
);
|
||||
await Navigator.of(context).push(MaterialPageRoute(builder: (_) => page));
|
||||
final record = await OnlineReadingHistory.find(
|
||||
widget.source.id,
|
||||
widget.detailUrl,
|
||||
);
|
||||
if (mounted) setState(() => readingRecord = record);
|
||||
}
|
||||
|
||||
Future<void> _save() async {
|
||||
final callback = widget.onSave;
|
||||
if (callback == null || saving) return;
|
||||
setState(() => saving = true);
|
||||
try {
|
||||
await callback();
|
||||
} finally {
|
||||
if (mounted) setState(() => saving = false);
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Scaffold(
|
||||
appBar: AppBar(title: const Text('书籍详情')),
|
||||
body: loadingInfo
|
||||
? const Center(child: CircularProgressIndicator())
|
||||
: infoError != null
|
||||
? _ErrorState(
|
||||
message: _failureMessage(
|
||||
infoError,
|
||||
'详情加载失败,请检查书源后重试。',
|
||||
),
|
||||
onRetry: _load,
|
||||
)
|
||||
: _buildContent(context),
|
||||
);
|
||||
}
|
||||
|
||||
Widget _buildContent(BuildContext context) {
|
||||
final value = info!;
|
||||
final ordered = descending ? chapters.reversed.toList() : chapters;
|
||||
return ListView(
|
||||
padding: const EdgeInsets.fromLTRB(18, 12, 18, 32),
|
||||
children: [
|
||||
Row(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
ClipRRect(
|
||||
borderRadius: BorderRadius.circular(8),
|
||||
child: SizedBox(
|
||||
width: 104,
|
||||
height: 142,
|
||||
child: value.coverUrl?.isNotEmpty == true
|
||||
? CachedNetworkImage(
|
||||
imageUrl: value.coverUrl!,
|
||||
httpHeaders: widget.source.headers,
|
||||
fit: BoxFit.cover,
|
||||
errorWidget: (_, __, ___) => const _CoverPlaceholder(),
|
||||
)
|
||||
: const _CoverPlaceholder(),
|
||||
),
|
||||
),
|
||||
const SizedBox(width: 16),
|
||||
Expanded(
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Text(value.title,
|
||||
style: Theme.of(context).textTheme.headlineSmall),
|
||||
const SizedBox(height: 10),
|
||||
Text(value.author?.trim().isNotEmpty == true
|
||||
? value.author!
|
||||
: '未知作者'),
|
||||
const SizedBox(height: 6),
|
||||
Text(
|
||||
value.sourceName,
|
||||
style: const TextStyle(color: Color(0xFF7B6570)),
|
||||
),
|
||||
const SizedBox(height: 10),
|
||||
Text('${chapters.length} 章',
|
||||
style: const TextStyle(color: Color(0xFFD05A82))),
|
||||
],
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
if (value.intro?.trim().isNotEmpty == true) ...[
|
||||
const SizedBox(height: 18),
|
||||
ExpansionTile(
|
||||
tilePadding: EdgeInsets.zero,
|
||||
title: const Text('简介'),
|
||||
children: [
|
||||
Padding(
|
||||
padding: const EdgeInsets.only(bottom: 12),
|
||||
child: Text(value.intro!, style: const TextStyle(height: 1.65)),
|
||||
),
|
||||
],
|
||||
),
|
||||
],
|
||||
const SizedBox(height: 16),
|
||||
FilledButton.icon(
|
||||
onPressed: chapters.isEmpty
|
||||
? null
|
||||
: () => _openChapter(
|
||||
readingRecord == null
|
||||
? 0
|
||||
: readingRecord!.chapterIndex
|
||||
.clamp(0, chapters.length - 1),
|
||||
),
|
||||
icon: Icon(readingRecord == null
|
||||
? Icons.play_arrow_rounded
|
||||
: Icons.history_rounded),
|
||||
label: Text(readingRecord == null ? '从第一章开始阅读' : '继续阅读'),
|
||||
),
|
||||
if (widget.onSave != null) ...[
|
||||
const SizedBox(height: 10),
|
||||
OutlinedButton.icon(
|
||||
onPressed: saving ? null : _save,
|
||||
icon: saving
|
||||
? const SizedBox.square(
|
||||
dimension: 18,
|
||||
child: CircularProgressIndicator(strokeWidth: 2))
|
||||
: const Icon(Icons.bookmark_add_outlined),
|
||||
label: const Text('保存到书架'),
|
||||
),
|
||||
],
|
||||
const SizedBox(height: 24),
|
||||
Row(
|
||||
children: [
|
||||
Expanded(
|
||||
child: Text(
|
||||
'章节目录${chapters.isEmpty ? '' : '(共 ${chapters.length} 章)'}',
|
||||
style: Theme.of(context).textTheme.titleLarge,
|
||||
),
|
||||
),
|
||||
TextButton.icon(
|
||||
onPressed: chapters.isEmpty
|
||||
? null
|
||||
: () => setState(() => descending = !descending),
|
||||
icon: Icon(descending
|
||||
? Icons.arrow_downward_rounded
|
||||
: Icons.arrow_upward_rounded),
|
||||
label: Text(descending ? '倒序' : '正序'),
|
||||
),
|
||||
],
|
||||
),
|
||||
if (loadingToc)
|
||||
const Padding(
|
||||
padding: EdgeInsets.all(28),
|
||||
child: Center(child: CircularProgressIndicator()),
|
||||
)
|
||||
else if (tocError != null)
|
||||
_ErrorState(
|
||||
message: _failureMessage(
|
||||
tocError,
|
||||
'目录加载失败,点这里再试一次。',
|
||||
),
|
||||
onRetry: () => _loadToc(value.tocUrl),
|
||||
)
|
||||
else if (chapters.isEmpty)
|
||||
const Padding(
|
||||
padding: EdgeInsets.symmetric(vertical: 30),
|
||||
child: Center(child: Text('这本书的目录还没有被书源找到。')),
|
||||
)
|
||||
else
|
||||
for (final chapter in ordered)
|
||||
ListTile(
|
||||
contentPadding: EdgeInsets.zero,
|
||||
leading: const Icon(Icons.menu_book_outlined),
|
||||
title: Text(chapter.title,
|
||||
maxLines: 2, overflow: TextOverflow.ellipsis),
|
||||
trailing: readingRecord != null &&
|
||||
chapter.index - 1 <= readingRecord!.chapterIndex
|
||||
? const Icon(Icons.check_rounded, color: Color(0xFFD05A82))
|
||||
: const Icon(Icons.chevron_right_rounded),
|
||||
onTap: () => _openChapter(chapter.index - 1),
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
String _failureMessage(Object? error, String fallback) {
|
||||
if (error is LegadoLoadException) return error.message;
|
||||
return fallback;
|
||||
}
|
||||
}
|
||||
|
||||
class _CoverPlaceholder extends StatelessWidget {
|
||||
const _CoverPlaceholder();
|
||||
@override
|
||||
Widget build(BuildContext context) => Container(
|
||||
color: const Color(0xFFFFECF2),
|
||||
alignment: Alignment.center,
|
||||
child: const Icon(Icons.auto_stories_outlined,
|
||||
size: 38, color: Color(0xFFD05A82)),
|
||||
);
|
||||
}
|
||||
|
||||
class _ParsedOnlineBook {
|
||||
const _ParsedOnlineBook({
|
||||
required this.title,
|
||||
required this.chapters,
|
||||
required this.contentByUrl,
|
||||
this.coverUrl,
|
||||
});
|
||||
|
||||
final String title;
|
||||
final String? coverUrl;
|
||||
final List<OnlineChapter> chapters;
|
||||
final Map<String, OnlineChapterContent> contentByUrl;
|
||||
}
|
||||
|
||||
class _ErrorState extends StatelessWidget {
|
||||
const _ErrorState({required this.message, required this.onRetry});
|
||||
final String message;
|
||||
final VoidCallback onRetry;
|
||||
@override
|
||||
Widget build(BuildContext context) => Padding(
|
||||
padding: const EdgeInsets.all(24),
|
||||
child: Column(
|
||||
mainAxisAlignment: MainAxisAlignment.center,
|
||||
children: [
|
||||
const Icon(Icons.cloud_off_outlined,
|
||||
size: 44, color: Color(0xFFD05A82)),
|
||||
const SizedBox(height: 10),
|
||||
Text(message, textAlign: TextAlign.center),
|
||||
const SizedBox(height: 12),
|
||||
OutlinedButton.icon(
|
||||
onPressed: onRetry,
|
||||
icon: const Icon(Icons.refresh_rounded),
|
||||
label: const Text('重试'),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,234 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_riverpod/flutter_riverpod.dart';
|
||||
|
||||
import '../core/legado_models.dart';
|
||||
import '../core/manga_image.dart';
|
||||
import '../core/providers.dart';
|
||||
import '../core/online_reading_history.dart';
|
||||
|
||||
class OnlineMangaReaderPage extends ConsumerStatefulWidget {
|
||||
const OnlineMangaReaderPage({
|
||||
super.key,
|
||||
required this.source,
|
||||
required this.title,
|
||||
required this.chapters,
|
||||
required this.currentChapterIndex,
|
||||
required this.detailUrl,
|
||||
this.initialContentByUrl = const <String, OnlineChapterContent>{},
|
||||
});
|
||||
|
||||
final LegadoSource source;
|
||||
final String title;
|
||||
final List<OnlineChapter> chapters;
|
||||
final int currentChapterIndex;
|
||||
final String detailUrl;
|
||||
final Map<String, OnlineChapterContent> initialContentByUrl;
|
||||
|
||||
@override
|
||||
ConsumerState<OnlineMangaReaderPage> createState() =>
|
||||
_OnlineMangaReaderPageState();
|
||||
}
|
||||
|
||||
class _OnlineMangaReaderPageState extends ConsumerState<OnlineMangaReaderPage> {
|
||||
late int chapterIndex = widget.currentChapterIndex;
|
||||
late Future<OnlineChapterContent> contentFuture = _load();
|
||||
final pageController = PageController();
|
||||
int pageIndex = 0;
|
||||
|
||||
OnlineChapter get chapter => widget.chapters[chapterIndex];
|
||||
|
||||
Future<OnlineChapterContent> _load() async {
|
||||
final preloaded = widget.initialContentByUrl[chapter.url];
|
||||
if (preloaded != null &&
|
||||
(preloaded.imageUrls.isNotEmpty || preloaded.pageImages.isNotEmpty)) {
|
||||
await _saveHistory();
|
||||
return preloaded;
|
||||
}
|
||||
final engine = ref.read(legadoEngineProvider);
|
||||
final content = await engine.fetchChapterContent(widget.source, chapter);
|
||||
await _saveHistory();
|
||||
final next = chapterIndex + 1;
|
||||
if (next < widget.chapters.length) {
|
||||
engine
|
||||
.fetchChapterContent(widget.source, widget.chapters[next])
|
||||
.catchError((_) => OnlineChapterContent(
|
||||
title: widget.chapters[next].title,
|
||||
));
|
||||
}
|
||||
return content;
|
||||
}
|
||||
|
||||
Future<void> _saveHistory() {
|
||||
return OnlineReadingHistory.save(OnlineReadingRecord(
|
||||
sourceId: widget.source.id,
|
||||
sourceName: widget.source.name,
|
||||
bookTitle: widget.title,
|
||||
detailUrl: widget.detailUrl,
|
||||
chapterUrl: chapter.url,
|
||||
chapterTitle: chapter.title,
|
||||
chapterIndex: chapterIndex,
|
||||
totalChapters: widget.chapters.length,
|
||||
lastReadTime: DateTime.now(),
|
||||
));
|
||||
}
|
||||
|
||||
void _move(int delta) {
|
||||
final target = chapterIndex + delta;
|
||||
if (target < 0 || target >= widget.chapters.length) return;
|
||||
setState(() {
|
||||
chapterIndex = target;
|
||||
pageIndex = 0;
|
||||
contentFuture = _load();
|
||||
});
|
||||
if (pageController.hasClients) pageController.jumpToPage(0);
|
||||
}
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
pageController.dispose();
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Scaffold(
|
||||
appBar: AppBar(
|
||||
title: Text(
|
||||
'${chapter.title}(${chapterIndex + 1}/${widget.chapters.length})',
|
||||
maxLines: 1,
|
||||
overflow: TextOverflow.ellipsis,
|
||||
),
|
||||
),
|
||||
body: FutureBuilder<OnlineChapterContent>(
|
||||
future: contentFuture,
|
||||
builder: (context, snapshot) {
|
||||
if (snapshot.hasError) {
|
||||
return _MangaState(
|
||||
message: '这个章节暂时没有加载成功。',
|
||||
onRetry: () => setState(() => contentFuture = _load()),
|
||||
);
|
||||
}
|
||||
if (!snapshot.hasData) {
|
||||
return const Center(child: CircularProgressIndicator());
|
||||
}
|
||||
final content = snapshot.data!;
|
||||
final pages = content.pageImages.isNotEmpty
|
||||
? content.pageImages
|
||||
: content.imageUrls
|
||||
.asMap()
|
||||
.entries
|
||||
.map((entry) => buildPageImage(
|
||||
raw: entry.value,
|
||||
chapterUrl: chapter.url,
|
||||
index: entry.key,
|
||||
sourceHeaders: widget.source.headers,
|
||||
userAgent: widget.source.userAgent,
|
||||
))
|
||||
.whereType<PageImage>()
|
||||
.toList(growable: false);
|
||||
if (pages.isEmpty) {
|
||||
return _MangaState(
|
||||
message: '这一章还没有找到漫画页面,可以换个书源试试。',
|
||||
onRetry: () => setState(() => contentFuture = _load()),
|
||||
);
|
||||
}
|
||||
return Stack(
|
||||
children: [
|
||||
PageView.builder(
|
||||
controller: pageController,
|
||||
itemCount: pages.length,
|
||||
onPageChanged: (value) => setState(() => pageIndex = value),
|
||||
itemBuilder: (context, index) => InteractiveViewer(
|
||||
child: Center(
|
||||
child: Image.network(
|
||||
pages[index].url,
|
||||
headers: pages[index].headers,
|
||||
fit: BoxFit.contain,
|
||||
loadingBuilder: (_, child, progress) => progress == null
|
||||
? child
|
||||
: const Center(child: CircularProgressIndicator()),
|
||||
errorBuilder: (_, __, ___) =>
|
||||
const Icon(Icons.broken_image_outlined, size: 48),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
Positioned(
|
||||
right: 12,
|
||||
bottom: 10,
|
||||
child: DecoratedBox(
|
||||
decoration: BoxDecoration(
|
||||
color: Colors.black54,
|
||||
borderRadius: BorderRadius.circular(6),
|
||||
),
|
||||
child: Padding(
|
||||
padding:
|
||||
const EdgeInsets.symmetric(horizontal: 9, vertical: 4),
|
||||
child: Text('${pageIndex + 1}/${pages.length}',
|
||||
style: const TextStyle(color: Colors.white)),
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
);
|
||||
},
|
||||
),
|
||||
bottomNavigationBar: SafeArea(
|
||||
child: Row(
|
||||
children: [
|
||||
Expanded(
|
||||
child: TextButton.icon(
|
||||
onPressed: chapterIndex > 0 ? () => _move(-1) : null,
|
||||
icon: const Icon(Icons.arrow_back_rounded),
|
||||
label: const Text('上一章'),
|
||||
),
|
||||
),
|
||||
Expanded(
|
||||
child: TextButton.icon(
|
||||
onPressed: () => Navigator.of(context).pop(),
|
||||
icon: const Icon(Icons.list_rounded),
|
||||
label: const Text('目录'),
|
||||
),
|
||||
),
|
||||
Expanded(
|
||||
child: TextButton.icon(
|
||||
onPressed: chapterIndex < widget.chapters.length - 1
|
||||
? () => _move(1)
|
||||
: null,
|
||||
icon: const Icon(Icons.arrow_forward_rounded),
|
||||
label: const Text('下一章'),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class _MangaState extends StatelessWidget {
|
||||
const _MangaState({required this.message, required this.onRetry});
|
||||
final String message;
|
||||
final VoidCallback onRetry;
|
||||
@override
|
||||
Widget build(BuildContext context) => Center(
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.all(28),
|
||||
child: Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
const Icon(Icons.image_not_supported_outlined,
|
||||
size: 44, color: Color(0xFFD05A82)),
|
||||
const SizedBox(height: 12),
|
||||
Text(message, textAlign: TextAlign.center),
|
||||
const SizedBox(height: 12),
|
||||
OutlinedButton.icon(
|
||||
onPressed: onRetry,
|
||||
icon: const Icon(Icons.refresh_rounded),
|
||||
label: const Text('重试'),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,206 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_riverpod/flutter_riverpod.dart';
|
||||
|
||||
import '../core/legado_models.dart';
|
||||
import '../core/providers.dart';
|
||||
import '../core/online_reading_history.dart';
|
||||
|
||||
class OnlineNovelReaderPage extends ConsumerStatefulWidget {
|
||||
const OnlineNovelReaderPage({
|
||||
super.key,
|
||||
required this.source,
|
||||
required this.title,
|
||||
required this.chapters,
|
||||
required this.currentChapterIndex,
|
||||
required this.detailUrl,
|
||||
this.initialContentByUrl = const <String, OnlineChapterContent>{},
|
||||
});
|
||||
|
||||
final LegadoSource source;
|
||||
final String title;
|
||||
final List<OnlineChapter> chapters;
|
||||
final int currentChapterIndex;
|
||||
final String detailUrl;
|
||||
final Map<String, OnlineChapterContent> initialContentByUrl;
|
||||
|
||||
@override
|
||||
ConsumerState<OnlineNovelReaderPage> createState() =>
|
||||
_OnlineNovelReaderPageState();
|
||||
}
|
||||
|
||||
class _OnlineNovelReaderPageState extends ConsumerState<OnlineNovelReaderPage> {
|
||||
late int chapterIndex = widget.currentChapterIndex;
|
||||
late Future<OnlineChapterContent> contentFuture = _load();
|
||||
double fontSize = 18;
|
||||
|
||||
OnlineChapter get chapter => widget.chapters[chapterIndex];
|
||||
|
||||
Future<OnlineChapterContent> _load() async {
|
||||
final preloaded = widget.initialContentByUrl[chapter.url];
|
||||
if (preloaded != null &&
|
||||
(preloaded.textContent?.trim().isNotEmpty == true)) {
|
||||
await _saveHistory();
|
||||
return preloaded;
|
||||
}
|
||||
final engine = ref.read(legadoEngineProvider);
|
||||
final content = await engine.fetchChapterContent(widget.source, chapter);
|
||||
await _saveHistory();
|
||||
final next = chapterIndex + 1;
|
||||
if (next < widget.chapters.length) {
|
||||
engine
|
||||
.fetchChapterContent(widget.source, widget.chapters[next])
|
||||
.catchError((_) => OnlineChapterContent(
|
||||
title: widget.chapters[next].title,
|
||||
));
|
||||
}
|
||||
return content;
|
||||
}
|
||||
|
||||
Future<void> _saveHistory() {
|
||||
return OnlineReadingHistory.save(OnlineReadingRecord(
|
||||
sourceId: widget.source.id,
|
||||
sourceName: widget.source.name,
|
||||
bookTitle: widget.title,
|
||||
detailUrl: widget.detailUrl,
|
||||
chapterUrl: chapter.url,
|
||||
chapterTitle: chapter.title,
|
||||
chapterIndex: chapterIndex,
|
||||
totalChapters: widget.chapters.length,
|
||||
lastReadTime: DateTime.now(),
|
||||
));
|
||||
}
|
||||
|
||||
void _move(int delta) {
|
||||
final target = chapterIndex + delta;
|
||||
if (target < 0 || target >= widget.chapters.length) return;
|
||||
setState(() {
|
||||
chapterIndex = target;
|
||||
contentFuture = _load();
|
||||
});
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Scaffold(
|
||||
appBar: AppBar(
|
||||
title: Text(
|
||||
'${chapter.title}(${chapterIndex + 1}/${widget.chapters.length})',
|
||||
maxLines: 1,
|
||||
overflow: TextOverflow.ellipsis,
|
||||
),
|
||||
actions: [
|
||||
IconButton(
|
||||
tooltip: '缩小字体',
|
||||
onPressed: () =>
|
||||
setState(() => fontSize = (fontSize - 1).clamp(14, 26)),
|
||||
icon: const Icon(Icons.text_decrease),
|
||||
),
|
||||
IconButton(
|
||||
tooltip: '放大字体',
|
||||
onPressed: () =>
|
||||
setState(() => fontSize = (fontSize + 1).clamp(14, 26)),
|
||||
icon: const Icon(Icons.text_increase),
|
||||
),
|
||||
],
|
||||
),
|
||||
body: FutureBuilder<OnlineChapterContent>(
|
||||
future: contentFuture,
|
||||
builder: (context, snapshot) {
|
||||
if (snapshot.hasError) {
|
||||
return _ReaderState(
|
||||
icon: Icons.cloud_off_outlined,
|
||||
title: '章节加载失败',
|
||||
message: '这个章节暂时没有读到,稍后再试一次吧。',
|
||||
onRetry: () => setState(() => contentFuture = _load()),
|
||||
);
|
||||
}
|
||||
if (!snapshot.hasData) {
|
||||
return const Center(child: CircularProgressIndicator());
|
||||
}
|
||||
final text = snapshot.data!.textContent?.trim() ?? '';
|
||||
if (text.isEmpty) {
|
||||
return _ReaderState(
|
||||
icon: Icons.article_outlined,
|
||||
title: '这一章还是空白',
|
||||
message: '可以换一个书源,或者回目录选择其他章节。',
|
||||
onRetry: () => setState(() => contentFuture = _load()),
|
||||
);
|
||||
}
|
||||
return ListView(
|
||||
padding: const EdgeInsets.fromLTRB(20, 14, 20, 32),
|
||||
children: [
|
||||
Text(chapter.title,
|
||||
style: Theme.of(context).textTheme.titleLarge),
|
||||
const SizedBox(height: 18),
|
||||
Text(text, style: TextStyle(fontSize: fontSize, height: 1.75)),
|
||||
],
|
||||
);
|
||||
},
|
||||
),
|
||||
bottomNavigationBar: SafeArea(
|
||||
child: Row(
|
||||
children: [
|
||||
Expanded(
|
||||
child: TextButton.icon(
|
||||
onPressed: chapterIndex > 0 ? () => _move(-1) : null,
|
||||
icon: const Icon(Icons.arrow_back_rounded),
|
||||
label: const Text('上一章'),
|
||||
),
|
||||
),
|
||||
Expanded(
|
||||
child: TextButton.icon(
|
||||
onPressed: () => Navigator.of(context).pop(),
|
||||
icon: const Icon(Icons.list_rounded),
|
||||
label: const Text('目录'),
|
||||
),
|
||||
),
|
||||
Expanded(
|
||||
child: TextButton.icon(
|
||||
onPressed: chapterIndex < widget.chapters.length - 1
|
||||
? () => _move(1)
|
||||
: null,
|
||||
icon: const Icon(Icons.arrow_forward_rounded),
|
||||
label: const Text('下一章'),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class _ReaderState extends StatelessWidget {
|
||||
const _ReaderState({
|
||||
required this.icon,
|
||||
required this.title,
|
||||
required this.message,
|
||||
required this.onRetry,
|
||||
});
|
||||
final IconData icon;
|
||||
final String title;
|
||||
final String message;
|
||||
final VoidCallback onRetry;
|
||||
@override
|
||||
Widget build(BuildContext context) => Center(
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.all(28),
|
||||
child: Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
Icon(icon, size: 44, color: const Color(0xFFD05A82)),
|
||||
const SizedBox(height: 12),
|
||||
Text(title, style: Theme.of(context).textTheme.titleLarge),
|
||||
const SizedBox(height: 8),
|
||||
Text(message, textAlign: TextAlign.center),
|
||||
const SizedBox(height: 12),
|
||||
OutlinedButton.icon(
|
||||
onPressed: onRetry,
|
||||
icon: const Icon(Icons.refresh_rounded),
|
||||
label: const Text('重试'),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,911 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_riverpod/flutter_riverpod.dart';
|
||||
import 'package:dio/dio.dart';
|
||||
|
||||
import '../core/providers.dart';
|
||||
|
||||
class ReminderCenterPage extends ConsumerStatefulWidget {
|
||||
const ReminderCenterPage({super.key});
|
||||
|
||||
@override
|
||||
ConsumerState<ReminderCenterPage> createState() => _ReminderCenterPageState();
|
||||
}
|
||||
|
||||
class _ReminderCenterPageState extends ConsumerState<ReminderCenterPage> {
|
||||
late Future<_ReminderCenterData> _future = _load();
|
||||
bool _savingReminder = false;
|
||||
final Set<String> _markingAlertIds = <String>{};
|
||||
final Set<String> _deletingFollowIds = <String>{};
|
||||
|
||||
Future<_ReminderCenterData> _load() async {
|
||||
final api = ref.read(apiClientProvider);
|
||||
final results = await Future.wait<Object?>([
|
||||
api.me(),
|
||||
api.follows(enabled: true),
|
||||
api.alerts(limit: 50),
|
||||
]);
|
||||
return _ReminderCenterData(
|
||||
user: Map<String, dynamic>.from(results[0]! as Map),
|
||||
follows: (results[1]! as List<dynamic>)
|
||||
.map((item) => Map<String, dynamic>.from(item as Map))
|
||||
.toList(),
|
||||
alerts: (results[2]! as List<dynamic>)
|
||||
.map((item) => Map<String, dynamic>.from(item as Map))
|
||||
.toList(),
|
||||
);
|
||||
}
|
||||
|
||||
void _refresh() {
|
||||
ref.invalidate(apiClientProvider);
|
||||
setState(() {
|
||||
_future = _load();
|
||||
});
|
||||
}
|
||||
|
||||
Future<void> _updateReminder(
|
||||
Map<String, dynamic> user, {
|
||||
bool? reminderEnabled,
|
||||
int? reminderHour,
|
||||
int? reminderMinute,
|
||||
}) async {
|
||||
if (_savingReminder) {
|
||||
return;
|
||||
}
|
||||
|
||||
final enabled =
|
||||
reminderEnabled ?? (user['reminder_enabled'] as bool? ?? true);
|
||||
final hour = reminderHour ?? (user['reminder_hour'] as int? ?? 9);
|
||||
final minute = reminderMinute ?? (user['reminder_minute'] as int? ?? 0);
|
||||
final timezone = user['reminder_timezone']?.toString() ?? 'Asia/Shanghai';
|
||||
|
||||
setState(() {
|
||||
_savingReminder = true;
|
||||
});
|
||||
|
||||
try {
|
||||
await ref.read(apiClientProvider).updateMe(
|
||||
reminderEnabled: enabled,
|
||||
reminderHour: hour,
|
||||
reminderMinute: minute,
|
||||
reminderTimezone: timezone,
|
||||
);
|
||||
if (!mounted) {
|
||||
return;
|
||||
}
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
SnackBar(
|
||||
content: Text(
|
||||
enabled
|
||||
? '已更新每日 ${_timeLabel(hour, minute)} 提醒'
|
||||
: '已关闭每日更新提醒',
|
||||
),
|
||||
),
|
||||
);
|
||||
_refresh();
|
||||
} catch (error) {
|
||||
if (!mounted) {
|
||||
return;
|
||||
}
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
SnackBar(content: Text('提醒设置保存失败:$error')),
|
||||
);
|
||||
} finally {
|
||||
if (mounted) {
|
||||
setState(() {
|
||||
_savingReminder = false;
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> _pickReminderTime(Map<String, dynamic> user) async {
|
||||
final initialTime = TimeOfDay(
|
||||
hour: user['reminder_hour'] as int? ?? 9,
|
||||
minute: user['reminder_minute'] as int? ?? 0,
|
||||
);
|
||||
final picked = await showTimePicker(
|
||||
context: context,
|
||||
initialTime: initialTime,
|
||||
helpText: '选择每日提醒时间',
|
||||
builder: (context, child) {
|
||||
return Theme(
|
||||
data: Theme.of(context).copyWith(
|
||||
colorScheme: Theme.of(context).colorScheme.copyWith(
|
||||
primary: const Color(0xFFD95A83),
|
||||
surface: const Color(0xFFFFFBFD),
|
||||
),
|
||||
),
|
||||
child: child ?? const SizedBox.shrink(),
|
||||
);
|
||||
},
|
||||
);
|
||||
if (picked == null) {
|
||||
return;
|
||||
}
|
||||
await _updateReminder(
|
||||
user,
|
||||
reminderEnabled: true,
|
||||
reminderHour: picked.hour,
|
||||
reminderMinute: picked.minute,
|
||||
);
|
||||
}
|
||||
|
||||
Future<void> _openAlert(Map<String, dynamic> alert) async {
|
||||
final alertId = alert['id']?.toString() ?? '';
|
||||
final isRead = alert['is_read'] as bool? ?? false;
|
||||
if (alertId.isNotEmpty && !isRead) {
|
||||
setState(() {
|
||||
_markingAlertIds.add(alertId);
|
||||
});
|
||||
try {
|
||||
await ref.read(apiClientProvider).markAlertRead(alertId);
|
||||
} catch (_) {
|
||||
// Keep the detail page usable even if read-state sync fails.
|
||||
} finally {
|
||||
if (mounted) {
|
||||
setState(() {
|
||||
_markingAlertIds.remove(alertId);
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
if (!mounted) {
|
||||
return;
|
||||
}
|
||||
await Navigator.of(context).push(
|
||||
MaterialPageRoute(
|
||||
builder: (_) => _ReminderAlertDetailPage(alert: alert),
|
||||
),
|
||||
);
|
||||
if (mounted) {
|
||||
_refresh();
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> _deleteFollow(Map<String, dynamic> follow) async {
|
||||
final followId = follow['id']?.toString() ?? '';
|
||||
if (followId.isEmpty || _deletingFollowIds.contains(followId)) {
|
||||
return;
|
||||
}
|
||||
final creatorName = _creatorName(follow);
|
||||
final confirmed = await showDialog<bool>(
|
||||
context: context,
|
||||
builder: (context) {
|
||||
return AlertDialog(
|
||||
title: const Text('取消关注'),
|
||||
content: Text('确定不再关注 $creatorName 吗?手机端会从云端关闭这位作者的更新提醒。'),
|
||||
actions: [
|
||||
TextButton(
|
||||
onPressed: () => Navigator.of(context).pop(false),
|
||||
child: const Text('先保留'),
|
||||
),
|
||||
FilledButton(
|
||||
onPressed: () => Navigator.of(context).pop(true),
|
||||
child: const Text('取消关注'),
|
||||
),
|
||||
],
|
||||
);
|
||||
},
|
||||
);
|
||||
if (confirmed != true) {
|
||||
return;
|
||||
}
|
||||
setState(() {
|
||||
_deletingFollowIds.add(followId);
|
||||
});
|
||||
try {
|
||||
await ref.read(apiClientProvider).deleteFollow(followId);
|
||||
if (!mounted) {
|
||||
return;
|
||||
}
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
SnackBar(content: Text('已取消关注 $creatorName')),
|
||||
);
|
||||
_refresh();
|
||||
} catch (error) {
|
||||
if (!mounted) {
|
||||
return;
|
||||
}
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
SnackBar(content: Text('取消关注失败:${_friendlyLoadError(error)}')),
|
||||
);
|
||||
} finally {
|
||||
if (mounted) {
|
||||
setState(() {
|
||||
_deletingFollowIds.remove(followId);
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return FutureBuilder<_ReminderCenterData>(
|
||||
future: _future,
|
||||
builder: (context, snapshot) {
|
||||
final user = snapshot.data?.user ?? <String, dynamic>{};
|
||||
final follows = snapshot.data?.follows ?? <Map<String, dynamic>>[];
|
||||
final alerts = snapshot.data?.alerts ?? <Map<String, dynamic>>[];
|
||||
final unreadCount =
|
||||
alerts.where((item) => !(item['is_read'] as bool? ?? false)).length;
|
||||
final reminderEnabled = user['reminder_enabled'] as bool? ?? true;
|
||||
final reminderHour = user['reminder_hour'] as int? ?? 9;
|
||||
final reminderMinute = user['reminder_minute'] as int? ?? 0;
|
||||
|
||||
return Scaffold(
|
||||
appBar: AppBar(title: const Text('每日提醒')),
|
||||
body: RefreshIndicator(
|
||||
color: const Color(0xFFD95A83),
|
||||
onRefresh: () async {
|
||||
_refresh();
|
||||
await _future;
|
||||
},
|
||||
child: ListView(
|
||||
padding: const EdgeInsets.fromLTRB(16, 14, 16, 28),
|
||||
children: [
|
||||
Text(
|
||||
'提醒中心',
|
||||
style: Theme.of(context)
|
||||
.textTheme
|
||||
.headlineMedium
|
||||
?.copyWith(fontWeight: FontWeight.w900),
|
||||
),
|
||||
const SizedBox(height: 8),
|
||||
Text(
|
||||
'在这里调整每日提醒时间,查看最近提醒,以及你已经同步到云端的关注作者。',
|
||||
style: Theme.of(context).textTheme.bodyMedium?.copyWith(
|
||||
color: const Color(0xFF7B6570),
|
||||
height: 1.55,
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 14),
|
||||
_ReminderSummaryCard(
|
||||
unreadCount: unreadCount,
|
||||
followCount: follows.length,
|
||||
reminderLabel: _timeLabel(reminderHour, reminderMinute),
|
||||
),
|
||||
if (snapshot.hasError) ...[
|
||||
const SizedBox(height: 12),
|
||||
Card(
|
||||
child: ListTile(
|
||||
leading: const Icon(Icons.cloud_off_outlined),
|
||||
title: const Text('提醒数据暂时加载失败'),
|
||||
subtitle: Text(
|
||||
'下拉刷新后再试:${_friendlyLoadError(snapshot.error)}',
|
||||
maxLines: 2,
|
||||
overflow: TextOverflow.ellipsis,
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
const SizedBox(height: 12),
|
||||
Card(
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.all(18),
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Row(
|
||||
children: [
|
||||
const Icon(
|
||||
Icons.notifications_active_outlined,
|
||||
color: Color(0xFFD95A83),
|
||||
),
|
||||
const SizedBox(width: 10),
|
||||
Expanded(
|
||||
child: Text(
|
||||
'每日更新提醒',
|
||||
style: Theme.of(context)
|
||||
.textTheme
|
||||
.titleMedium
|
||||
?.copyWith(fontWeight: FontWeight.w800),
|
||||
),
|
||||
),
|
||||
Switch.adaptive(
|
||||
value: reminderEnabled,
|
||||
activeThumbColor: const Color(0xFFD95A83),
|
||||
onChanged: _savingReminder
|
||||
? null
|
||||
: (value) => _updateReminder(
|
||||
user,
|
||||
reminderEnabled: value,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
const SizedBox(height: 8),
|
||||
Text(
|
||||
'云端会在设定时间后检查你关注的 Pixiv / X 作者更新,并生成新的摘要提醒。',
|
||||
style:
|
||||
Theme.of(context).textTheme.bodyMedium?.copyWith(
|
||||
color: const Color(0xFF7B6570),
|
||||
height: 1.5,
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 14),
|
||||
Row(
|
||||
children: [
|
||||
FilledButton.tonalIcon(
|
||||
onPressed: _savingReminder
|
||||
? null
|
||||
: () => _pickReminderTime(user),
|
||||
icon: const Icon(Icons.schedule_outlined),
|
||||
label: Text(
|
||||
'提醒时间 ${_timeLabel(reminderHour, reminderMinute)}',
|
||||
),
|
||||
),
|
||||
const SizedBox(width: 10),
|
||||
if (_savingReminder)
|
||||
const SizedBox(
|
||||
width: 20,
|
||||
height: 20,
|
||||
child:
|
||||
CircularProgressIndicator(strokeWidth: 2),
|
||||
),
|
||||
],
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 12),
|
||||
_SectionCard(
|
||||
icon: Icons.people_alt_outlined,
|
||||
title: '已关注作者',
|
||||
subtitle: '这里展示已经同步到云端的关注作者,手机提醒会以此为准。',
|
||||
child: follows.isEmpty
|
||||
? const _EmptyMessage(
|
||||
icon: Icons.person_search_outlined,
|
||||
title: '还没有已同步的关注作者',
|
||||
message: '先在桌面端同步 Pixiv / X 关注,稍后回到这里刷新即可。',
|
||||
)
|
||||
: Column(
|
||||
children: [
|
||||
for (final follow in follows)
|
||||
_FollowTile(
|
||||
follow: follow,
|
||||
busy: _deletingFollowIds
|
||||
.contains(follow['id']?.toString() ?? ''),
|
||||
onDelete: () => _deleteFollow(follow),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 12),
|
||||
_SectionCard(
|
||||
icon: Icons.mark_email_unread_outlined,
|
||||
title: '最近提醒',
|
||||
subtitle: '点开单条提醒可以查看完整内容,并把它标记为已读。',
|
||||
child: alerts.isEmpty
|
||||
? const _EmptyMessage(
|
||||
icon: Icons.notifications_off_outlined,
|
||||
title: '还没有提醒',
|
||||
message: '当你关注的作者出现新内容后,这里会自动出现提醒摘要。',
|
||||
)
|
||||
: Column(
|
||||
children: [
|
||||
for (final alert in alerts)
|
||||
_AlertTile(
|
||||
alert: alert,
|
||||
busy: _markingAlertIds
|
||||
.contains(alert['id']?.toString() ?? ''),
|
||||
onTap: () => _openAlert(alert),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class _ReminderCenterData {
|
||||
const _ReminderCenterData({
|
||||
required this.user,
|
||||
required this.follows,
|
||||
required this.alerts,
|
||||
});
|
||||
|
||||
final Map<String, dynamic> user;
|
||||
final List<Map<String, dynamic>> follows;
|
||||
final List<Map<String, dynamic>> alerts;
|
||||
}
|
||||
|
||||
class _ReminderSummaryCard extends StatelessWidget {
|
||||
const _ReminderSummaryCard({
|
||||
required this.unreadCount,
|
||||
required this.followCount,
|
||||
required this.reminderLabel,
|
||||
});
|
||||
|
||||
final int unreadCount;
|
||||
final int followCount;
|
||||
final String reminderLabel;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Container(
|
||||
decoration: BoxDecoration(
|
||||
borderRadius: BorderRadius.circular(28),
|
||||
gradient: const LinearGradient(
|
||||
colors: [Color(0xFFFFE6EE), Color(0xFFFFF8FB)],
|
||||
begin: Alignment.topLeft,
|
||||
end: Alignment.bottomRight,
|
||||
),
|
||||
),
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.all(18),
|
||||
child: Row(
|
||||
children: [
|
||||
const CircleAvatar(
|
||||
radius: 26,
|
||||
backgroundColor: Colors.white,
|
||||
child: Icon(
|
||||
Icons.auto_awesome_outlined,
|
||||
color: Color(0xFFD95A83),
|
||||
),
|
||||
),
|
||||
const SizedBox(width: 14),
|
||||
Expanded(
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Text(
|
||||
'今天的提醒总览',
|
||||
style: Theme.of(context)
|
||||
.textTheme
|
||||
.titleMedium
|
||||
?.copyWith(fontWeight: FontWeight.w800),
|
||||
),
|
||||
const SizedBox(height: 4),
|
||||
Text(
|
||||
'未读提醒 $unreadCount 条,已关注作者 $followCount 位,每日 $reminderLabel 推送摘要。',
|
||||
style: Theme.of(context).textTheme.bodyMedium?.copyWith(
|
||||
color: const Color(0xFF7B6570),
|
||||
height: 1.45,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class _SectionCard extends StatelessWidget {
|
||||
const _SectionCard({
|
||||
required this.icon,
|
||||
required this.title,
|
||||
required this.subtitle,
|
||||
required this.child,
|
||||
});
|
||||
|
||||
final IconData icon;
|
||||
final String title;
|
||||
final String subtitle;
|
||||
final Widget child;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Card(
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.all(18),
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Row(
|
||||
children: [
|
||||
Icon(icon, color: const Color(0xFFD95A83)),
|
||||
const SizedBox(width: 10),
|
||||
Expanded(
|
||||
child: Text(
|
||||
title,
|
||||
style: Theme.of(context)
|
||||
.textTheme
|
||||
.titleMedium
|
||||
?.copyWith(fontWeight: FontWeight.w800),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
const SizedBox(height: 6),
|
||||
Text(
|
||||
subtitle,
|
||||
style: Theme.of(context).textTheme.bodyMedium?.copyWith(
|
||||
color: const Color(0xFF7B6570),
|
||||
height: 1.5,
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 14),
|
||||
child,
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class _EmptyMessage extends StatelessWidget {
|
||||
const _EmptyMessage({
|
||||
required this.icon,
|
||||
required this.title,
|
||||
required this.message,
|
||||
});
|
||||
|
||||
final IconData icon;
|
||||
final String title;
|
||||
final String message;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Container(
|
||||
width: double.infinity,
|
||||
padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 18),
|
||||
decoration: BoxDecoration(
|
||||
borderRadius: BorderRadius.circular(22),
|
||||
color: const Color(0xFFFFF8FB),
|
||||
),
|
||||
child: Column(
|
||||
children: [
|
||||
Icon(icon, color: const Color(0xFFD95A83)),
|
||||
const SizedBox(height: 10),
|
||||
Text(
|
||||
title,
|
||||
style: Theme.of(context)
|
||||
.textTheme
|
||||
.titleSmall
|
||||
?.copyWith(fontWeight: FontWeight.w700),
|
||||
textAlign: TextAlign.center,
|
||||
),
|
||||
const SizedBox(height: 6),
|
||||
Text(
|
||||
message,
|
||||
style: Theme.of(context).textTheme.bodyMedium?.copyWith(
|
||||
color: const Color(0xFF7B6570),
|
||||
height: 1.5,
|
||||
),
|
||||
textAlign: TextAlign.center,
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class _FollowTile extends StatelessWidget {
|
||||
const _FollowTile({
|
||||
required this.follow,
|
||||
required this.busy,
|
||||
required this.onDelete,
|
||||
});
|
||||
|
||||
final Map<String, dynamic> follow;
|
||||
final bool busy;
|
||||
final VoidCallback onDelete;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final creatorName = _creatorName(follow);
|
||||
final handle = follow['creator_handle']?.toString() ?? '';
|
||||
final platform = follow['platform']?.toString() ?? 'unknown';
|
||||
final checkedAt = _formatDateTime(follow['last_checked_at']?.toString());
|
||||
final publishedAt =
|
||||
_formatDateTime(follow['latest_published_at']?.toString());
|
||||
|
||||
return Container(
|
||||
margin: const EdgeInsets.only(bottom: 10),
|
||||
padding: const EdgeInsets.all(14),
|
||||
decoration: BoxDecoration(
|
||||
borderRadius: BorderRadius.circular(20),
|
||||
color: const Color(0xFFFFF8FB),
|
||||
),
|
||||
child: Row(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
CircleAvatar(
|
||||
backgroundColor: const Color(0xFFFFE1EA),
|
||||
child: Text(
|
||||
creatorName.isNotEmpty
|
||||
? creatorName.substring(0, 1).toUpperCase()
|
||||
: '?',
|
||||
style: const TextStyle(
|
||||
color: Color(0xFFD95A83),
|
||||
fontWeight: FontWeight.w700,
|
||||
),
|
||||
),
|
||||
),
|
||||
const SizedBox(width: 12),
|
||||
Expanded(
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Row(
|
||||
children: [
|
||||
Expanded(
|
||||
child: Text(
|
||||
creatorName,
|
||||
style: Theme.of(context)
|
||||
.textTheme
|
||||
.titleSmall
|
||||
?.copyWith(fontWeight: FontWeight.w700),
|
||||
),
|
||||
),
|
||||
_PlatformPill(platform: platform),
|
||||
],
|
||||
),
|
||||
if (handle.isNotEmpty) ...[
|
||||
const SizedBox(height: 4),
|
||||
Text(
|
||||
'@$handle',
|
||||
style: Theme.of(context).textTheme.bodyMedium?.copyWith(
|
||||
color: const Color(0xFF7B6570),
|
||||
),
|
||||
),
|
||||
],
|
||||
const SizedBox(height: 6),
|
||||
Text(
|
||||
'最近检查:$checkedAt',
|
||||
style: Theme.of(context).textTheme.bodySmall?.copyWith(
|
||||
color: const Color(0xFF7B6570),
|
||||
),
|
||||
),
|
||||
Text(
|
||||
'最近更新:$publishedAt',
|
||||
style: Theme.of(context).textTheme.bodySmall?.copyWith(
|
||||
color: const Color(0xFF7B6570),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
const SizedBox(width: 8),
|
||||
IconButton(
|
||||
tooltip: '取消关注',
|
||||
onPressed: busy ? null : onDelete,
|
||||
icon: busy
|
||||
? const SizedBox(
|
||||
width: 18,
|
||||
height: 18,
|
||||
child: CircularProgressIndicator(strokeWidth: 2),
|
||||
)
|
||||
: const Icon(Icons.person_remove_outlined),
|
||||
color: const Color(0xFFD95A83),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class _AlertTile extends StatelessWidget {
|
||||
const _AlertTile({
|
||||
required this.alert,
|
||||
required this.busy,
|
||||
required this.onTap,
|
||||
});
|
||||
|
||||
final Map<String, dynamic> alert;
|
||||
final bool busy;
|
||||
final VoidCallback onTap;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final title = alert['title']?.toString() ?? '新动态';
|
||||
final body = alert['body']?.toString() ?? '你关注的作者有更新了。';
|
||||
final platform = alert['platform']?.toString() ?? '';
|
||||
final createdAt = _formatDateTime(alert['created_at']?.toString());
|
||||
final isRead = alert['is_read'] as bool? ?? false;
|
||||
|
||||
return Card(
|
||||
margin: const EdgeInsets.only(bottom: 10),
|
||||
child: ListTile(
|
||||
contentPadding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
|
||||
onTap: onTap,
|
||||
leading: CircleAvatar(
|
||||
backgroundColor:
|
||||
isRead ? const Color(0xFFF0EEF0) : const Color(0xFFFFE1EA),
|
||||
child: busy
|
||||
? const SizedBox(
|
||||
width: 18,
|
||||
height: 18,
|
||||
child: CircularProgressIndicator(strokeWidth: 2),
|
||||
)
|
||||
: Icon(
|
||||
isRead
|
||||
? Icons.notifications_none_outlined
|
||||
: Icons.notifications_active_outlined,
|
||||
color: isRead
|
||||
? const Color(0xFF8A7E84)
|
||||
: const Color(0xFFD95A83),
|
||||
),
|
||||
),
|
||||
title: Text(
|
||||
title,
|
||||
maxLines: 1,
|
||||
overflow: TextOverflow.ellipsis,
|
||||
),
|
||||
subtitle: Text(
|
||||
'$platform · $createdAt\n$body',
|
||||
maxLines: 3,
|
||||
overflow: TextOverflow.ellipsis,
|
||||
),
|
||||
trailing: const Icon(Icons.chevron_right),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class _PlatformPill extends StatelessWidget {
|
||||
const _PlatformPill({required this.platform});
|
||||
|
||||
final String platform;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final label = platform.toUpperCase();
|
||||
return Container(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 4),
|
||||
decoration: BoxDecoration(
|
||||
borderRadius: BorderRadius.circular(999),
|
||||
color: const Color(0xFFFFE8EE),
|
||||
),
|
||||
child: Text(
|
||||
label,
|
||||
style: Theme.of(context).textTheme.labelMedium?.copyWith(
|
||||
color: const Color(0xFFD95A83),
|
||||
fontWeight: FontWeight.w700,
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class _ReminderAlertDetailPage extends StatelessWidget {
|
||||
const _ReminderAlertDetailPage({required this.alert});
|
||||
|
||||
final Map<String, dynamic> alert;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final title = alert['title']?.toString() ?? '提醒详情';
|
||||
final body = alert['body']?.toString() ?? '暂无详细说明';
|
||||
final platform = alert['platform']?.toString() ?? '';
|
||||
final creatorName = _creatorName(alert['payload'] is Map
|
||||
? Map<String, dynamic>.from(alert['payload'] as Map)
|
||||
: <String, dynamic>{});
|
||||
final targetUrl = alert['target_url']?.toString() ?? '';
|
||||
final createdAt = _formatDateTime(alert['created_at']?.toString());
|
||||
|
||||
return Scaffold(
|
||||
appBar: AppBar(title: const Text('提醒详情')),
|
||||
body: ListView(
|
||||
padding: const EdgeInsets.fromLTRB(16, 14, 16, 28),
|
||||
children: [
|
||||
Text(
|
||||
title,
|
||||
style: Theme.of(context)
|
||||
.textTheme
|
||||
.headlineSmall
|
||||
?.copyWith(fontWeight: FontWeight.w900),
|
||||
),
|
||||
const SizedBox(height: 12),
|
||||
Card(
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.all(18),
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Row(
|
||||
children: [
|
||||
_PlatformPill(platform: platform),
|
||||
const SizedBox(width: 10),
|
||||
Expanded(
|
||||
child: Text(
|
||||
createdAt,
|
||||
style:
|
||||
Theme.of(context).textTheme.bodyMedium?.copyWith(
|
||||
color: const Color(0xFF7B6570),
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
if (creatorName.isNotEmpty) ...[
|
||||
const SizedBox(height: 12),
|
||||
Text(
|
||||
'作者:$creatorName',
|
||||
style:
|
||||
Theme.of(context).textTheme.titleSmall?.copyWith(
|
||||
fontWeight: FontWeight.w700,
|
||||
),
|
||||
),
|
||||
],
|
||||
const SizedBox(height: 12),
|
||||
Text(
|
||||
body,
|
||||
style: Theme.of(context).textTheme.bodyLarge?.copyWith(
|
||||
height: 1.6,
|
||||
),
|
||||
),
|
||||
if (targetUrl.isNotEmpty) ...[
|
||||
const SizedBox(height: 16),
|
||||
Text(
|
||||
'目标链接',
|
||||
style:
|
||||
Theme.of(context).textTheme.titleSmall?.copyWith(
|
||||
fontWeight: FontWeight.w700,
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 6),
|
||||
SelectionArea(
|
||||
child: Text(
|
||||
targetUrl,
|
||||
style: Theme.of(context).textTheme.bodyMedium?.copyWith(
|
||||
color: const Color(0xFF7B6570),
|
||||
height: 1.5,
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
String _creatorName(Map<String, dynamic> item) {
|
||||
final creatorName = item['creator_name']?.toString() ?? '';
|
||||
if (creatorName.isNotEmpty) {
|
||||
return creatorName;
|
||||
}
|
||||
final handle = item['creator_handle']?.toString() ?? '';
|
||||
if (handle.isNotEmpty) {
|
||||
return '@$handle';
|
||||
}
|
||||
final creatorId = item['creator_id']?.toString() ?? '';
|
||||
return creatorId.isNotEmpty ? creatorId : '未命名作者';
|
||||
}
|
||||
|
||||
String _timeLabel(int hour, int minute) {
|
||||
return '${hour.toString().padLeft(2, '0')}:${minute.toString().padLeft(2, '0')}';
|
||||
}
|
||||
|
||||
String _formatDateTime(String? raw) {
|
||||
if (raw == null || raw.isEmpty) {
|
||||
return '暂未记录';
|
||||
}
|
||||
final parsed = DateTime.tryParse(raw)?.toLocal();
|
||||
if (parsed == null) {
|
||||
return raw;
|
||||
}
|
||||
return '${parsed.year}-${parsed.month.toString().padLeft(2, '0')}-${parsed.day.toString().padLeft(2, '0')} '
|
||||
'${parsed.hour.toString().padLeft(2, '0')}:${parsed.minute.toString().padLeft(2, '0')}';
|
||||
}
|
||||
|
||||
String _friendlyLoadError(Object? error) {
|
||||
if (error is DioException) {
|
||||
final statusCode = error.response?.statusCode;
|
||||
final data = error.response?.data;
|
||||
var detail = '';
|
||||
if (data is Map) {
|
||||
detail = (data['detail'] ?? data['message'] ?? data['error'] ?? '').toString();
|
||||
} else if (data != null) {
|
||||
detail = data.toString();
|
||||
}
|
||||
final status = statusCode == null ? '' : 'HTTP $statusCode';
|
||||
final message = detail.isNotEmpty ? detail : (error.message ?? error.type.name);
|
||||
return [status, message].where((item) => item.isNotEmpty).join(' - ');
|
||||
}
|
||||
return error?.toString() ?? 'unknown error';
|
||||
}
|
||||
@@ -0,0 +1,679 @@
|
||||
import 'dart:async';
|
||||
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_riverpod/flutter_riverpod.dart';
|
||||
import 'package:flutter/services.dart';
|
||||
|
||||
import '../core/legado_models.dart';
|
||||
import '../core/providers.dart';
|
||||
import '../core/source_manager.dart';
|
||||
|
||||
class SourceManagerPage extends ConsumerStatefulWidget {
|
||||
const SourceManagerPage({super.key});
|
||||
|
||||
@override
|
||||
ConsumerState<SourceManagerPage> createState() => _SourceManagerPageState();
|
||||
}
|
||||
|
||||
class _SourceManagerPageState extends ConsumerState<SourceManagerPage> {
|
||||
static const _sourceImportChannel =
|
||||
MethodChannel('top.kunkunxiaomao.sakura_mobile/source_import');
|
||||
|
||||
final customUrl = TextEditingController();
|
||||
final jsonText = TextEditingController();
|
||||
final searchController = TextEditingController();
|
||||
Timer? _debounce;
|
||||
String filter = '';
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
Future.microtask(
|
||||
() => ref.read(sourceManagerProvider).initializeIfFirstRun(),
|
||||
);
|
||||
}
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
_debounce?.cancel();
|
||||
customUrl.dispose();
|
||||
jsonText.dispose();
|
||||
searchController.dispose();
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
void _onSearchChanged(String value) {
|
||||
_debounce?.cancel();
|
||||
_debounce = Timer(const Duration(milliseconds: 180), () {
|
||||
if (!mounted) return;
|
||||
setState(() {
|
||||
filter = value;
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final manager = ref.watch(sourceManagerProvider);
|
||||
final sources = _filterSources(manager);
|
||||
|
||||
return Scaffold(
|
||||
body: RefreshIndicator(
|
||||
color: const Color(0xFFD95A83),
|
||||
onRefresh: () async {
|
||||
await ref.read(sourceManagerProvider).load();
|
||||
},
|
||||
child: CustomScrollView(
|
||||
slivers: [
|
||||
SliverAppBar(
|
||||
pinned: true,
|
||||
title: const Text('书源管理'),
|
||||
actions: [
|
||||
IconButton(
|
||||
tooltip: '刷新',
|
||||
onPressed: manager.busy
|
||||
? null
|
||||
: () => ref.read(sourceManagerProvider).load(),
|
||||
icon: const Icon(Icons.refresh),
|
||||
),
|
||||
],
|
||||
bottom: PreferredSize(
|
||||
preferredSize: const Size.fromHeight(64),
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.fromLTRB(16, 0, 16, 10),
|
||||
child: SearchBar(
|
||||
controller: searchController,
|
||||
hintText: '搜索已导入的书源',
|
||||
leading: const Icon(Icons.search),
|
||||
onChanged: _onSearchChanged,
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
SliverToBoxAdapter(
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.fromLTRB(16, 12, 16, 0),
|
||||
child: Column(
|
||||
children: [
|
||||
_StatsCard(manager: manager),
|
||||
const SizedBox(height: 12),
|
||||
_MaintenanceCard(
|
||||
manager: manager,
|
||||
onUpdateSubscriptions: _updateSubscriptions,
|
||||
onCheckSources: _checkSources,
|
||||
),
|
||||
const SizedBox(height: 12),
|
||||
if (manager.lastChecks.isNotEmpty) ...[
|
||||
_CheckResultsCard(results: manager.lastChecks),
|
||||
const SizedBox(height: 12),
|
||||
],
|
||||
_RepoSection(manager: manager, onImport: _importRepo),
|
||||
const SizedBox(height: 12),
|
||||
_CustomImportCard(
|
||||
controller: customUrl,
|
||||
jsonController: jsonText,
|
||||
busy: manager.busy,
|
||||
onImport: _importCustomUrl,
|
||||
onImportJson: _importJsonText,
|
||||
onPickJson: _pickJsonFile,
|
||||
),
|
||||
if (manager.busy) ...[
|
||||
const SizedBox(height: 12),
|
||||
const LinearProgressIndicator(),
|
||||
],
|
||||
if (manager.message?.isNotEmpty == true) ...[
|
||||
const SizedBox(height: 10),
|
||||
Align(
|
||||
alignment: Alignment.centerLeft,
|
||||
child: Text(
|
||||
manager.message!,
|
||||
style:
|
||||
Theme.of(context).textTheme.bodySmall?.copyWith(
|
||||
color: const Color(0xFF7B6570),
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
const SizedBox(height: 16),
|
||||
Align(
|
||||
alignment: Alignment.centerLeft,
|
||||
child: Text(
|
||||
'已导入 (${sources.length})',
|
||||
style: Theme.of(context)
|
||||
.textTheme
|
||||
.titleMedium
|
||||
?.copyWith(fontWeight: FontWeight.w800),
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 8),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
if (sources.isEmpty)
|
||||
const SliverToBoxAdapter(
|
||||
child: Padding(
|
||||
padding: EdgeInsets.all(28),
|
||||
child: Center(
|
||||
child: Text('还没有可用书源,请先从你信任的 URL 导入。'),
|
||||
),
|
||||
),
|
||||
)
|
||||
else
|
||||
SliverPadding(
|
||||
padding: const EdgeInsets.fromLTRB(16, 0, 16, 28),
|
||||
sliver: SliverList.builder(
|
||||
itemCount: sources.length,
|
||||
itemBuilder: (context, index) {
|
||||
final source = sources[index];
|
||||
return _SourceTile(
|
||||
source: source,
|
||||
busy: manager.busy,
|
||||
onChanged: (value) => ref
|
||||
.read(sourceManagerProvider)
|
||||
.setEnabled(source.id, value),
|
||||
);
|
||||
},
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
List<LegadoSource> _filterSources(SourceManager manager) {
|
||||
final query = filter.trim().toLowerCase();
|
||||
if (query.isEmpty) return manager.sources;
|
||||
return manager.sources.where((source) {
|
||||
return '${source.name} ${source.url}'.toLowerCase().contains(query);
|
||||
}).toList(growable: false);
|
||||
}
|
||||
|
||||
Future<void> _importRepo(SourceRepo repo) async {
|
||||
final manager = ref.read(sourceManagerProvider);
|
||||
final count = await manager.importFromRepo(repo);
|
||||
if (!mounted) return;
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
SnackBar(
|
||||
content: Text(
|
||||
count > 0 ? '已导入 $count 个新书源。' : manager.message ?? '没有导入新书源。'),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Future<void> _updateSubscriptions() async {
|
||||
final count = await ref
|
||||
.read(sourceManagerProvider)
|
||||
.checkSubscriptionUpdatesIfDue(force: true);
|
||||
if (!mounted) return;
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
SnackBar(content: Text('订阅更新添加了 $count 个书源。')),
|
||||
);
|
||||
}
|
||||
|
||||
Future<void> _checkSources() async {
|
||||
final results = await ref.read(sourceManagerProvider).checkEnabledSources();
|
||||
if (!mounted) return;
|
||||
final healthy = results.where((item) => item.ok).length;
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
SnackBar(content: Text('已检测 ${results.length} 个书源,$healthy 个可用。')),
|
||||
);
|
||||
}
|
||||
|
||||
Future<void> _importCustomUrl() async {
|
||||
final url = customUrl.text.trim();
|
||||
if (url.isEmpty) return;
|
||||
final manager = ref.read(sourceManagerProvider);
|
||||
final count = await manager.importFromUrl(url);
|
||||
if (!mounted) return;
|
||||
if (count > 0) {
|
||||
customUrl.clear();
|
||||
}
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
SnackBar(
|
||||
content: Text(
|
||||
count > 0 ? '已导入 $count 个新书源。' : manager.message ?? '导入失败,请检查链接。'),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Future<void> _importJsonText() async {
|
||||
final body = jsonText.text.trim();
|
||||
if (body.isEmpty) return;
|
||||
final manager = ref.read(sourceManagerProvider);
|
||||
final count = await manager.importFromJsonText(body);
|
||||
if (!mounted) return;
|
||||
if (count > 0) {
|
||||
jsonText.clear();
|
||||
}
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
SnackBar(
|
||||
content: Text(
|
||||
count > 0 ? '已导入 $count 个新书源。' : manager.message ?? '没有识别到书源。'),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Future<void> _pickJsonFile() async {
|
||||
try {
|
||||
final body = await _sourceImportChannel.invokeMethod<String>('pickJson');
|
||||
if (body == null || body.trim().isEmpty) return;
|
||||
final manager = ref.read(sourceManagerProvider);
|
||||
final count = await manager.importFromJsonText(body);
|
||||
if (!mounted) return;
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
SnackBar(
|
||||
content: Text(count > 0
|
||||
? '已从 JSON 文件导入 $count 个新书源。'
|
||||
: manager.message ?? '文件里没有识别到书源。'),
|
||||
),
|
||||
);
|
||||
} on PlatformException catch (error) {
|
||||
if (!mounted) return;
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
SnackBar(content: Text(error.message ?? '无法读取 JSON 文件。')),
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
class _SourceTile extends StatelessWidget {
|
||||
const _SourceTile({
|
||||
required this.source,
|
||||
required this.busy,
|
||||
required this.onChanged,
|
||||
});
|
||||
|
||||
final LegadoSource source;
|
||||
final bool busy;
|
||||
final ValueChanged<bool> onChanged;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Card(
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.fromLTRB(14, 12, 10, 12),
|
||||
child: Row(
|
||||
crossAxisAlignment: CrossAxisAlignment.center,
|
||||
children: [
|
||||
Icon(
|
||||
source.isManga
|
||||
? Icons.menu_book_rounded
|
||||
: Icons.auto_stories_rounded,
|
||||
color: const Color(0xFFD95A83),
|
||||
),
|
||||
const SizedBox(width: 12),
|
||||
Expanded(
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
Text(
|
||||
source.name,
|
||||
maxLines: 2,
|
||||
overflow: TextOverflow.ellipsis,
|
||||
softWrap: false,
|
||||
style: Theme.of(context).textTheme.titleSmall?.copyWith(
|
||||
fontWeight: FontWeight.w700,
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 4),
|
||||
Text(
|
||||
'${source.isManga ? '漫画' : '小说'} - ${source.url}',
|
||||
maxLines: 2,
|
||||
overflow: TextOverflow.ellipsis,
|
||||
softWrap: false,
|
||||
style: Theme.of(context).textTheme.bodySmall?.copyWith(
|
||||
color: const Color(0xFF7B6570),
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 6),
|
||||
_CompatBadge(source: source),
|
||||
],
|
||||
),
|
||||
),
|
||||
const SizedBox(width: 8),
|
||||
Switch(
|
||||
value: source.enabled,
|
||||
activeThumbColor: const Color(0xFFD95A83),
|
||||
onChanged: busy ? null : onChanged,
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class _CompatBadge extends ConsumerWidget {
|
||||
const _CompatBadge({required this.source});
|
||||
|
||||
final LegadoSource source;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context, WidgetRef ref) {
|
||||
final info = ref.read(sourceManagerProvider).compatibilityFor(source);
|
||||
final color = switch (info.level) {
|
||||
SourceCompatLevel.full => const Color(0xFF3A8C62),
|
||||
SourceCompatLevel.needsJs => const Color(0xFFC56A3D),
|
||||
SourceCompatLevel.broken => const Color(0xFF8B737D),
|
||||
_ => const Color(0xFFD05A82),
|
||||
};
|
||||
return Tooltip(
|
||||
message:
|
||||
info.warnings.isEmpty ? '当前规则可以由本地引擎执行' : info.warnings.join('\n'),
|
||||
child: Row(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
Icon(Icons.circle, size: 8, color: color),
|
||||
const SizedBox(width: 5),
|
||||
Text(
|
||||
info.label,
|
||||
style: Theme.of(context).textTheme.labelSmall?.copyWith(
|
||||
color: color,
|
||||
fontWeight: FontWeight.w700,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class _MaintenanceCard extends StatelessWidget {
|
||||
const _MaintenanceCard({
|
||||
required this.manager,
|
||||
required this.onUpdateSubscriptions,
|
||||
required this.onCheckSources,
|
||||
});
|
||||
|
||||
final SourceManager manager;
|
||||
final VoidCallback onUpdateSubscriptions;
|
||||
final VoidCallback onCheckSources;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final last = manager.lastSubscriptionUpdate;
|
||||
final lastLabel = last == null
|
||||
? '还没有订阅更新记录。'
|
||||
: '上次订阅更新:${last.month}月${last.day}日 ${last.hour.toString().padLeft(2, '0')}:${last.minute.toString().padLeft(2, '0')}';
|
||||
return Card(
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.all(16),
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Text(
|
||||
'维护',
|
||||
style: Theme.of(context)
|
||||
.textTheme
|
||||
.titleMedium
|
||||
?.copyWith(fontWeight: FontWeight.w800),
|
||||
),
|
||||
const SizedBox(height: 6),
|
||||
Text(
|
||||
lastLabel,
|
||||
style: Theme.of(context).textTheme.bodySmall?.copyWith(
|
||||
color: const Color(0xFF7B6570),
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 12),
|
||||
Wrap(
|
||||
spacing: 10,
|
||||
runSpacing: 10,
|
||||
children: [
|
||||
FilledButton.tonalIcon(
|
||||
onPressed: manager.busy ? null : onUpdateSubscriptions,
|
||||
icon: const Icon(Icons.sync_rounded),
|
||||
label: const Text('更新订阅'),
|
||||
),
|
||||
OutlinedButton.icon(
|
||||
onPressed: manager.busy || manager.enabledSources.isEmpty
|
||||
? null
|
||||
: onCheckSources,
|
||||
icon: const Icon(Icons.speed_rounded),
|
||||
label: const Text('检测已启用书源'),
|
||||
),
|
||||
],
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class _CheckResultsCard extends StatelessWidget {
|
||||
const _CheckResultsCard({required this.results});
|
||||
|
||||
final List<SourceCheckResult> results;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Card(
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.all(16),
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Text(
|
||||
'最近书源检测',
|
||||
style: Theme.of(context)
|
||||
.textTheme
|
||||
.titleMedium
|
||||
?.copyWith(fontWeight: FontWeight.w800),
|
||||
),
|
||||
const SizedBox(height: 10),
|
||||
for (final result in results.take(10))
|
||||
Padding(
|
||||
padding: const EdgeInsets.only(bottom: 8),
|
||||
child: Row(
|
||||
children: [
|
||||
Icon(
|
||||
result.ok
|
||||
? Icons.check_circle_outline
|
||||
: Icons.error_outline,
|
||||
color: result.ok
|
||||
? const Color(0xFF0E6245)
|
||||
: const Color(0xFFB3261E),
|
||||
size: 20,
|
||||
),
|
||||
const SizedBox(width: 8),
|
||||
Expanded(
|
||||
child: Text(
|
||||
result.sourceName,
|
||||
maxLines: 1,
|
||||
overflow: TextOverflow.ellipsis,
|
||||
),
|
||||
),
|
||||
const SizedBox(width: 8),
|
||||
Text('${result.elapsedMs} ms'),
|
||||
],
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class _StatsCard extends StatelessWidget {
|
||||
const _StatsCard({required this.manager});
|
||||
|
||||
final SourceManager manager;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Card(
|
||||
color: const Color(0xFFFFF7FA),
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.all(16),
|
||||
child: Row(
|
||||
children: [
|
||||
const CircleAvatar(
|
||||
backgroundColor: Color(0xFFFFE1EA),
|
||||
child: Icon(Icons.tune_rounded, color: Color(0xFFD95A83)),
|
||||
),
|
||||
const SizedBox(width: 14),
|
||||
Expanded(
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Text(
|
||||
'已导入 ${manager.sources.length} 个,已启用 ${manager.enabledSources.length} 个',
|
||||
style: Theme.of(context)
|
||||
.textTheme
|
||||
.titleMedium
|
||||
?.copyWith(fontWeight: FontWeight.w800),
|
||||
),
|
||||
const SizedBox(height: 4),
|
||||
Text(
|
||||
'搜索最多使用 10 个已启用书源。客户端不内置第三方仓库,请只导入你信任且有使用权限的书源。',
|
||||
style: Theme.of(context).textTheme.bodySmall?.copyWith(
|
||||
color: const Color(0xFF7B6570),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class _RepoSection extends StatelessWidget {
|
||||
const _RepoSection({
|
||||
required this.manager,
|
||||
required this.onImport,
|
||||
});
|
||||
|
||||
final SourceManager manager;
|
||||
final ValueChanged<SourceRepo> onImport;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Card(
|
||||
child: ExpansionTile(
|
||||
initiallyExpanded: false,
|
||||
leading: const Icon(Icons.cloud_download_outlined),
|
||||
title: const Text('内置书源仓库'),
|
||||
subtitle: const Text('当前版本不内置第三方仓库 URL'),
|
||||
children: [
|
||||
if (SourceManager.builtinRepos.isEmpty)
|
||||
const Padding(
|
||||
padding: EdgeInsets.fromLTRB(16, 0, 16, 16),
|
||||
child: Align(
|
||||
alignment: Alignment.centerLeft,
|
||||
child: Text('请使用下方自定义 URL 导入你信任的书源。'),
|
||||
),
|
||||
)
|
||||
else
|
||||
for (final repo in SourceManager.builtinRepos)
|
||||
ListTile(
|
||||
leading: const Icon(Icons.cloud_download_outlined),
|
||||
title: Text(repo.name),
|
||||
subtitle: Text(repo.description),
|
||||
trailing: FilledButton.tonal(
|
||||
onPressed: manager.busy ? null : () => onImport(repo),
|
||||
child: Text(repo.isSubscription ? '订阅' : '导入'),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class _CustomImportCard extends StatelessWidget {
|
||||
const _CustomImportCard({
|
||||
required this.controller,
|
||||
required this.jsonController,
|
||||
required this.busy,
|
||||
required this.onImport,
|
||||
required this.onImportJson,
|
||||
required this.onPickJson,
|
||||
});
|
||||
|
||||
final TextEditingController controller;
|
||||
final TextEditingController jsonController;
|
||||
final bool busy;
|
||||
final VoidCallback onImport;
|
||||
final VoidCallback onImportJson;
|
||||
final VoidCallback onPickJson;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Card(
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.all(16),
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Text(
|
||||
'导入书源',
|
||||
style: Theme.of(context)
|
||||
.textTheme
|
||||
.titleMedium
|
||||
?.copyWith(fontWeight: FontWeight.w800),
|
||||
),
|
||||
const SizedBox(height: 10),
|
||||
Text(
|
||||
'可以选择本地 JSON 文件,也可以粘贴 JSON 内容或输入 URL。',
|
||||
style: Theme.of(context).textTheme.bodySmall?.copyWith(
|
||||
color: const Color(0xFF7B6570),
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 12),
|
||||
FilledButton.icon(
|
||||
onPressed: busy ? null : onPickJson,
|
||||
icon: const Icon(Icons.upload_file_rounded),
|
||||
label: const Text('选择 JSON 文件'),
|
||||
),
|
||||
const SizedBox(height: 12),
|
||||
TextField(
|
||||
controller: jsonController,
|
||||
decoration: const InputDecoration(
|
||||
hintText: '粘贴 source.json 内容',
|
||||
prefixIcon: Icon(Icons.data_object_rounded),
|
||||
),
|
||||
minLines: 3,
|
||||
maxLines: 6,
|
||||
keyboardType: TextInputType.multiline,
|
||||
),
|
||||
const SizedBox(height: 10),
|
||||
Align(
|
||||
alignment: Alignment.centerRight,
|
||||
child: OutlinedButton.icon(
|
||||
onPressed: busy ? null : onImportJson,
|
||||
icon: const Icon(Icons.input_rounded),
|
||||
label: const Text('导入 JSON 内容'),
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
TextField(
|
||||
controller: controller,
|
||||
decoration: const InputDecoration(
|
||||
hintText: 'https://example.com/source.json',
|
||||
prefixIcon: Icon(Icons.link),
|
||||
),
|
||||
keyboardType: TextInputType.url,
|
||||
),
|
||||
const SizedBox(height: 10),
|
||||
Align(
|
||||
alignment: Alignment.centerRight,
|
||||
child: FilledButton.icon(
|
||||
onPressed: busy ? null : onImport,
|
||||
icon: const Icon(Icons.add_link),
|
||||
label: const Text('从 URL 导入'),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,881 @@
|
||||
import 'package:cached_network_image/cached_network_image.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_riverpod/flutter_riverpod.dart';
|
||||
|
||||
import '../../core/api_client.dart';
|
||||
import '../../core/manga_collections.dart';
|
||||
import '../../core/providers.dart';
|
||||
import '../../models/artwork.dart';
|
||||
import '../../models/novel.dart';
|
||||
import '../artwork_detail_page.dart';
|
||||
import '../novel_reader_page.dart';
|
||||
import '../reminder_center_page.dart';
|
||||
|
||||
class FeedTab extends ConsumerStatefulWidget {
|
||||
const FeedTab({super.key});
|
||||
|
||||
@override
|
||||
ConsumerState<FeedTab> createState() => _FeedTabState();
|
||||
}
|
||||
|
||||
class _FeedTabState extends ConsumerState<FeedTab> {
|
||||
final _scrollController = ScrollController();
|
||||
Future<Map<String, dynamic>>? _statFuture;
|
||||
Future<List<Artwork>>? _todayFuture;
|
||||
Future<List<Artwork>>? _recentFuture;
|
||||
Future<List<Novel>>? _novelFuture;
|
||||
Future<List<Map<String, dynamic>>>? _alertFuture;
|
||||
Future<_TodaySummary>? _todaySummaryFuture;
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
_ensureFutures();
|
||||
}
|
||||
|
||||
void _ensureFutures() {
|
||||
final api = ref.read(apiClientProvider);
|
||||
_statFuture ??= api.galleryStat().timeout(const Duration(seconds: 3),
|
||||
onTimeout: () => <String, dynamic>{});
|
||||
_recentFuture ??= _loadRecentArtworks(api);
|
||||
_todayFuture ??= Future.delayed(const Duration(milliseconds: 200))
|
||||
.then((_) => _loadUpdatedArtworks(api));
|
||||
_novelFuture ??= Future.delayed(const Duration(milliseconds: 500))
|
||||
.then((_) => api.recentNovels(limit: 12))
|
||||
.then((items) => items
|
||||
.map((item) => Novel.fromJson(item as Map<String, dynamic>))
|
||||
.toList());
|
||||
_alertFuture ??= Future.delayed(const Duration(milliseconds: 500))
|
||||
.then((_) => api.unreadAlerts(limit: 12))
|
||||
.then((items) =>
|
||||
items.map((item) => item as Map<String, dynamic>).toList());
|
||||
_todaySummaryFuture ??= _loadTodaySummary();
|
||||
}
|
||||
|
||||
Future<void> _refresh() async {
|
||||
await ref.read(apiClientProvider).invalidateCache();
|
||||
setState(() {
|
||||
_statFuture = null;
|
||||
_todayFuture = null;
|
||||
_recentFuture = null;
|
||||
_novelFuture = null;
|
||||
_alertFuture = null;
|
||||
_todaySummaryFuture = null;
|
||||
_ensureFutures();
|
||||
});
|
||||
}
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
_scrollController.dispose();
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return RefreshIndicator(
|
||||
color: const Color(0xFFD95A83),
|
||||
onRefresh: _refresh,
|
||||
child: ListView(
|
||||
controller: _scrollController,
|
||||
physics: const ClampingScrollPhysics(
|
||||
parent: AlwaysScrollableScrollPhysics(),
|
||||
),
|
||||
keyboardDismissBehavior: ScrollViewKeyboardDismissBehavior.onDrag,
|
||||
padding: const EdgeInsets.fromLTRB(16, 14, 16, 24),
|
||||
children: [
|
||||
Text(
|
||||
'发现',
|
||||
style: Theme.of(context).textTheme.headlineMedium?.copyWith(
|
||||
fontWeight: FontWeight.w600,
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 12),
|
||||
FutureBuilder<_TodaySummary>(
|
||||
future: _todaySummaryFuture,
|
||||
builder: (context, snapshot) {
|
||||
final data = snapshot.data ?? _TodaySummary.empty;
|
||||
return Text(
|
||||
snapshot.connectionState == ConnectionState.waiting
|
||||
? '正在看看今天有没有新内容...'
|
||||
: '今日新增 ${data.total} 个作品,先把新鲜内容放到眼前。',
|
||||
style: Theme.of(context).textTheme.bodyMedium?.copyWith(
|
||||
color: const Color(0xFF7B6570),
|
||||
height: 1.55,
|
||||
),
|
||||
);
|
||||
},
|
||||
),
|
||||
const SizedBox(height: 14),
|
||||
FutureBuilder<_TodaySummary>(
|
||||
future: _todaySummaryFuture,
|
||||
builder: (context, snapshot) {
|
||||
if (snapshot.connectionState == ConnectionState.waiting) {
|
||||
return const _SkeletonCard(height: 112);
|
||||
}
|
||||
final data = snapshot.data ?? _TodaySummary.empty;
|
||||
return _TodayUpdateCard(summary: data);
|
||||
},
|
||||
),
|
||||
const SizedBox(height: 22),
|
||||
const _SectionHeader(
|
||||
title: '最近更新',
|
||||
subtitle: '按内容类型整理,新作品会优先出现。',
|
||||
),
|
||||
const SizedBox(height: 12),
|
||||
FutureBuilder<List<Artwork>>(
|
||||
future: _todayFuture,
|
||||
builder: (context, snapshot) {
|
||||
final items = (snapshot.data ?? <Artwork>[])
|
||||
..sort(_compareArtworkUpdateDesc);
|
||||
final illusts =
|
||||
items.where((item) => item.contentType != 'manga').toList();
|
||||
return _ArtworkStrip(
|
||||
title: '插画',
|
||||
items: illusts,
|
||||
loading: snapshot.connectionState == ConnectionState.waiting,
|
||||
emptyText: '今天的插画还在路上',
|
||||
emptyMessage: '同步新作品后,这里会开出第一朵小花。',
|
||||
);
|
||||
},
|
||||
),
|
||||
const SizedBox(height: 18),
|
||||
FutureBuilder<List<Artwork>>(
|
||||
future: _todayFuture,
|
||||
builder: (context, snapshot) {
|
||||
final items = snapshot.data ?? <Artwork>[];
|
||||
final mangas =
|
||||
items.where((item) => item.contentType == 'manga').toList();
|
||||
return _ArtworkStrip(
|
||||
title: '漫画',
|
||||
items: mangas,
|
||||
loading: snapshot.connectionState == ConnectionState.waiting,
|
||||
emptyText: '今天还没有新漫画',
|
||||
emptyMessage: '漫画同步完成后,会按页整理好放在这里。',
|
||||
);
|
||||
},
|
||||
),
|
||||
const SizedBox(height: 18),
|
||||
FutureBuilder<List<Novel>>(
|
||||
future: _novelFuture,
|
||||
builder: (context, snapshot) => _NovelStrip(
|
||||
novels: snapshot.data ?? <Novel>[],
|
||||
loading: snapshot.connectionState == ConnectionState.waiting,
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 18),
|
||||
FutureBuilder<List<Map<String, dynamic>>>(
|
||||
future: _alertFuture,
|
||||
builder: (context, snapshot) {
|
||||
final alerts = snapshot.data ?? <Map<String, dynamic>>[];
|
||||
final xAlerts = alerts.where(_isXAlert).toList();
|
||||
return _AlertStrip(
|
||||
alerts: xAlerts.isEmpty ? alerts : xAlerts,
|
||||
loading: snapshot.connectionState == ConnectionState.waiting,
|
||||
);
|
||||
},
|
||||
),
|
||||
const SizedBox(height: 26),
|
||||
const _SectionHeader(
|
||||
title: '最近浏览',
|
||||
subtitle: '保留上次看过的内容,想接着翻也方便。',
|
||||
),
|
||||
const SizedBox(height: 12),
|
||||
FutureBuilder<List<Artwork>>(
|
||||
future: _recentFuture,
|
||||
builder: (context, snapshot) => _ArtworkStrip(
|
||||
title: '刚刚看过',
|
||||
items: snapshot.data ?? <Artwork>[],
|
||||
loading: snapshot.connectionState == ConnectionState.waiting,
|
||||
emptyText: '还没有浏览记录',
|
||||
emptyMessage: '打开一张图或一页漫画后,它会回到这里。',
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 22),
|
||||
SizedBox(
|
||||
height: 106,
|
||||
child: FutureBuilder<Map<String, dynamic>>(
|
||||
future: _statFuture,
|
||||
builder: (context, snapshot) =>
|
||||
_StatCard(stat: snapshot.data ?? const {}),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Future<_TodaySummary> _loadTodaySummary() async {
|
||||
final results = await Future.wait<Object?>([
|
||||
_todayFuture ?? Future.value(<Artwork>[]),
|
||||
_novelFuture ?? Future.value(<Novel>[]),
|
||||
_alertFuture ?? Future.value(<Map<String, dynamic>>[]),
|
||||
]);
|
||||
final artworks = results[0] as List<Artwork>;
|
||||
final novels = results[1] as List<Novel>;
|
||||
final alerts = results[2] as List<Map<String, dynamic>>;
|
||||
final illusts =
|
||||
artworks.where((item) => item.contentType != 'manga').length;
|
||||
final mangas = artworks.where((item) => item.contentType == 'manga').length;
|
||||
final todayCount = [
|
||||
...artworks.map((item) => item.createdAt ?? item.updatedAt),
|
||||
...novels.map((item) => item.lastViewedAt ?? item.lastReadAt),
|
||||
...alerts.map((item) => _parseDate(item['created_at'])),
|
||||
].whereType<DateTime>().where(_isToday).length;
|
||||
return _TodaySummary(
|
||||
total: todayCount,
|
||||
illustCount: illusts,
|
||||
mangaCount: mangas,
|
||||
novelCount: novels.length,
|
||||
alertCount: alerts.where(_isXAlert).length,
|
||||
);
|
||||
}
|
||||
|
||||
Future<List<Artwork>> _loadUpdatedArtworks(SakuraApiClient api) async {
|
||||
final rows =
|
||||
await api.gallery(sort: 'updated', limit: 36, includeTotal: false);
|
||||
return _artworksFromPayload(rows)..sort(_compareArtworkUpdateDesc);
|
||||
}
|
||||
|
||||
Future<List<Artwork>> _loadRecentArtworks(SakuraApiClient api) async {
|
||||
try {
|
||||
final rows = await api.gallery(limit: 24, includeTotal: false);
|
||||
final items = _artworksFromPayload(rows);
|
||||
final viewed = items
|
||||
.where((item) => item.lastViewedAt != null)
|
||||
.toList(growable: false)
|
||||
..sort(_compareArtworkRecentDesc);
|
||||
if (viewed.isNotEmpty) {
|
||||
return viewed;
|
||||
}
|
||||
return items..sort(_compareArtworkRecentDesc);
|
||||
} catch (_) {
|
||||
return api
|
||||
.galleryFeed(mode: 'recent', limit: 24)
|
||||
.then(_artworksFromPayload);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
List<Artwork> _artworksFromPayload(List<dynamic> items) {
|
||||
return items
|
||||
.map((item) => Artwork.fromJson(item as Map<String, dynamic>))
|
||||
.toList();
|
||||
}
|
||||
|
||||
class _TodaySummary {
|
||||
const _TodaySummary({
|
||||
required this.total,
|
||||
required this.illustCount,
|
||||
required this.mangaCount,
|
||||
required this.novelCount,
|
||||
required this.alertCount,
|
||||
});
|
||||
|
||||
static const empty = _TodaySummary(
|
||||
total: 0,
|
||||
illustCount: 0,
|
||||
mangaCount: 0,
|
||||
novelCount: 0,
|
||||
alertCount: 0,
|
||||
);
|
||||
|
||||
final int total;
|
||||
final int illustCount;
|
||||
final int mangaCount;
|
||||
final int novelCount;
|
||||
final int alertCount;
|
||||
}
|
||||
|
||||
class _TodayUpdateCard extends StatelessWidget {
|
||||
const _TodayUpdateCard({required this.summary});
|
||||
|
||||
final _TodaySummary summary;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Card(
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.all(18),
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Row(
|
||||
children: [
|
||||
const CircleAvatar(
|
||||
backgroundColor: Color(0xFFFFE1EA),
|
||||
child: Icon(Icons.auto_awesome, color: Color(0xFFD95A83)),
|
||||
),
|
||||
const SizedBox(width: 12),
|
||||
Expanded(
|
||||
child: Text(
|
||||
summary.total > 0
|
||||
? '今日新增 ${summary.total} 个作品'
|
||||
: '今天还在安静等待更新',
|
||||
style: Theme.of(context).textTheme.titleMedium?.copyWith(
|
||||
fontWeight: FontWeight.w700,
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
const SizedBox(height: 14),
|
||||
Wrap(
|
||||
spacing: 8,
|
||||
runSpacing: 8,
|
||||
children: [
|
||||
_UpdatePill(label: '插画 ${summary.illustCount}'),
|
||||
_UpdatePill(label: '漫画 ${summary.mangaCount}'),
|
||||
_UpdatePill(label: '小说 ${summary.novelCount}'),
|
||||
_UpdatePill(label: 'X 动态/视频 ${summary.alertCount}'),
|
||||
],
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class _UpdatePill extends StatelessWidget {
|
||||
const _UpdatePill({required this.label});
|
||||
|
||||
final String label;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return DecoratedBox(
|
||||
decoration: BoxDecoration(
|
||||
color: const Color(0xFFFFEFF5),
|
||||
borderRadius: BorderRadius.circular(999),
|
||||
),
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 7),
|
||||
child: Text(
|
||||
label,
|
||||
style: Theme.of(context).textTheme.labelMedium?.copyWith(
|
||||
color: const Color(0xFFD95A83),
|
||||
fontWeight: FontWeight.w700,
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class _SectionHeader extends StatelessWidget {
|
||||
const _SectionHeader({required this.title, required this.subtitle});
|
||||
|
||||
final String title;
|
||||
final String subtitle;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Text(
|
||||
title,
|
||||
style: Theme.of(context).textTheme.titleLarge?.copyWith(
|
||||
fontWeight: FontWeight.w600,
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 4),
|
||||
Text(
|
||||
subtitle,
|
||||
style: Theme.of(context)
|
||||
.textTheme
|
||||
.bodyMedium
|
||||
?.copyWith(color: const Color(0xFF7B6570)),
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class _StatCard extends StatelessWidget {
|
||||
const _StatCard({required this.stat});
|
||||
|
||||
final Map<String, dynamic> stat;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Card(
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.all(18),
|
||||
child: Row(
|
||||
mainAxisAlignment: MainAxisAlignment.spaceAround,
|
||||
children: [
|
||||
_Metric(label: '作品', value: '${stat['total'] ?? '--'}'),
|
||||
_Metric(label: '收藏', value: '${stat['favorites'] ?? '--'}'),
|
||||
_Metric(
|
||||
label: '空间',
|
||||
value: stat['storage_used'] == null
|
||||
? '--'
|
||||
: '${((stat['storage_used'] ?? 0) / 1024 / 1024).toStringAsFixed(1)} MB',
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class _Metric extends StatelessWidget {
|
||||
const _Metric({required this.label, required this.value});
|
||||
|
||||
final String label;
|
||||
final String value;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Column(
|
||||
children: [
|
||||
Text(
|
||||
value,
|
||||
style: Theme.of(context).textTheme.titleLarge?.copyWith(
|
||||
fontWeight: FontWeight.w800,
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 4),
|
||||
Text(label, style: Theme.of(context).textTheme.bodySmall),
|
||||
],
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class _ArtworkStrip extends ConsumerWidget {
|
||||
const _ArtworkStrip({
|
||||
required this.title,
|
||||
required this.items,
|
||||
required this.loading,
|
||||
required this.emptyText,
|
||||
required this.emptyMessage,
|
||||
});
|
||||
|
||||
final String title;
|
||||
final List<Artwork> items;
|
||||
final bool loading;
|
||||
final String emptyText;
|
||||
final String emptyMessage;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context, WidgetRef ref) {
|
||||
final api = ref.watch(apiClientProvider);
|
||||
return Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Text(
|
||||
title,
|
||||
style: Theme.of(context).textTheme.titleMedium?.copyWith(
|
||||
fontWeight: FontWeight.w700,
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 10),
|
||||
if (loading)
|
||||
const _SkeletonStrip()
|
||||
else if (items.isEmpty)
|
||||
_MessageCard(
|
||||
icon: Icons.image_outlined,
|
||||
title: emptyText,
|
||||
message: emptyMessage,
|
||||
)
|
||||
else
|
||||
SizedBox(
|
||||
height: 210,
|
||||
child: ListView.separated(
|
||||
scrollDirection: Axis.horizontal,
|
||||
itemCount: items.take(10).length,
|
||||
separatorBuilder: (_, __) => const SizedBox(width: 12),
|
||||
itemBuilder: (context, index) {
|
||||
final item = items[index];
|
||||
final thumbUrl = api.resolveUrl(
|
||||
item.thumbnailUrl ?? item.imageUrl ?? item.thumbnailPath,
|
||||
);
|
||||
return SizedBox(
|
||||
width: 148,
|
||||
child: InkWell(
|
||||
borderRadius: BorderRadius.circular(22),
|
||||
onTap: () {
|
||||
final mangaCollection = item.contentType == 'manga'
|
||||
? findMangaCollectionForArtwork(items, item)
|
||||
: null;
|
||||
Navigator.of(context).push(
|
||||
MaterialPageRoute(
|
||||
builder: (_) => ArtworkDetailPage(
|
||||
artwork: item,
|
||||
artworkSequence: mangaCollection?.items,
|
||||
titleOverride: mangaCollection?.title,
|
||||
initialIndex: mangaCollection?.items.indexWhere(
|
||||
(entry) => entry.id == item.id,
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
},
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Expanded(
|
||||
child: ClipRRect(
|
||||
borderRadius: BorderRadius.circular(22),
|
||||
child: thumbUrl.isEmpty
|
||||
? _ImagePlaceholder(title: item.title)
|
||||
: CachedNetworkImage(
|
||||
imageUrl: thumbUrl,
|
||||
httpHeaders: api.authHeaders(),
|
||||
fit: BoxFit.cover,
|
||||
memCacheWidth: 320,
|
||||
memCacheHeight: 420,
|
||||
placeholder: (_, __) =>
|
||||
_ImagePlaceholder(title: item.title),
|
||||
errorWidget: (_, __, ___) =>
|
||||
_ImagePlaceholder(title: item.title),
|
||||
),
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 8),
|
||||
Text(
|
||||
item.title,
|
||||
maxLines: 2,
|
||||
overflow: TextOverflow.ellipsis,
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
},
|
||||
),
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class _NovelStrip extends StatelessWidget {
|
||||
const _NovelStrip({required this.novels, required this.loading});
|
||||
|
||||
final List<Novel> novels;
|
||||
final bool loading;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Text(
|
||||
'小说',
|
||||
style: Theme.of(context).textTheme.titleMedium?.copyWith(
|
||||
fontWeight: FontWeight.w700,
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 10),
|
||||
if (loading)
|
||||
const _SkeletonCard(height: 96)
|
||||
else if (novels.isEmpty)
|
||||
const _MessageCard(
|
||||
icon: Icons.menu_book_outlined,
|
||||
title: '今天还没有新小说',
|
||||
message: '同步完成后,新的章节会在这里排好队。',
|
||||
)
|
||||
else
|
||||
...novels.take(4).map((novel) => _RecentNovelTile(novel: novel)),
|
||||
],
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class _AlertStrip extends StatelessWidget {
|
||||
const _AlertStrip({required this.alerts, required this.loading});
|
||||
|
||||
final List<Map<String, dynamic>> alerts;
|
||||
final bool loading;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Row(
|
||||
children: [
|
||||
Expanded(
|
||||
child: Text(
|
||||
'X 动态 / 视频',
|
||||
style: Theme.of(context).textTheme.titleMedium?.copyWith(
|
||||
fontWeight: FontWeight.w700,
|
||||
),
|
||||
),
|
||||
),
|
||||
TextButton.icon(
|
||||
onPressed: () {
|
||||
Navigator.of(context).push(
|
||||
MaterialPageRoute(builder: (_) => const ReminderCenterPage()),
|
||||
);
|
||||
},
|
||||
icon: const Icon(Icons.tune_outlined),
|
||||
label: const Text('提醒中心'),
|
||||
),
|
||||
],
|
||||
),
|
||||
const SizedBox(height: 10),
|
||||
if (loading)
|
||||
const _SkeletonCard(height: 96)
|
||||
else if (alerts.isEmpty)
|
||||
const _MessageCard(
|
||||
icon: Icons.notifications_active_outlined,
|
||||
title: '还没有新的动态提醒',
|
||||
message: '关注作者更新后,X 动态和视频提醒会出现在这里。',
|
||||
)
|
||||
else
|
||||
...alerts.take(4).map((item) => _AlertCard(item: item)),
|
||||
],
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class _AlertCard extends StatelessWidget {
|
||||
const _AlertCard({required this.item});
|
||||
|
||||
final Map<String, dynamic> item;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final title = item['title']?.toString() ?? '新的动态';
|
||||
final body = item['body']?.toString() ?? '你关注的作者有更新了。';
|
||||
final platform = item['platform']?.toString() ?? '';
|
||||
return Card(
|
||||
margin: const EdgeInsets.only(bottom: 10),
|
||||
child: ListTile(
|
||||
leading: const CircleAvatar(
|
||||
backgroundColor: Color(0xFFFFE1EA),
|
||||
child: Icon(
|
||||
Icons.notifications_active_outlined,
|
||||
color: Color(0xFFD95A83),
|
||||
),
|
||||
),
|
||||
title: Text(title, maxLines: 1, overflow: TextOverflow.ellipsis),
|
||||
subtitle: Text(
|
||||
[platform, body].where((item) => item.isNotEmpty).join(' - '),
|
||||
maxLines: 2,
|
||||
overflow: TextOverflow.ellipsis,
|
||||
),
|
||||
trailing: const Icon(Icons.chevron_right),
|
||||
onTap: () {
|
||||
Navigator.of(context).push(
|
||||
MaterialPageRoute(builder: (_) => const ReminderCenterPage()),
|
||||
);
|
||||
},
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class _RecentNovelTile extends ConsumerWidget {
|
||||
const _RecentNovelTile({required this.novel});
|
||||
|
||||
final Novel novel;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context, WidgetRef ref) {
|
||||
final api = ref.watch(apiClientProvider);
|
||||
return Card(
|
||||
margin: const EdgeInsets.only(bottom: 10),
|
||||
child: ListTile(
|
||||
contentPadding:
|
||||
const EdgeInsets.symmetric(horizontal: 16, vertical: 10),
|
||||
leading: SizedBox(
|
||||
width: 48,
|
||||
child: ClipRRect(
|
||||
borderRadius: BorderRadius.circular(14),
|
||||
child: _NovelCover(
|
||||
coverUrl: api.resolveUrl(novel.coverPath),
|
||||
title: novel.title,
|
||||
),
|
||||
),
|
||||
),
|
||||
title: Text(
|
||||
novel.seriesTitle?.isNotEmpty == true
|
||||
? novel.seriesTitle!
|
||||
: novel.title,
|
||||
),
|
||||
subtitle: Text(
|
||||
novel.chapterTitle?.isNotEmpty == true
|
||||
? novel.chapterTitle!
|
||||
: (novel.author ?? '未知作者'),
|
||||
maxLines: 1,
|
||||
overflow: TextOverflow.ellipsis,
|
||||
),
|
||||
trailing: const Icon(Icons.chevron_right),
|
||||
onTap: () => Navigator.of(context).push(
|
||||
MaterialPageRoute(builder: (_) => NovelReaderPage(novel: novel)),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class _NovelCover extends StatelessWidget {
|
||||
const _NovelCover({required this.coverUrl, required this.title});
|
||||
|
||||
final String coverUrl;
|
||||
final String title;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
if (coverUrl.isEmpty) {
|
||||
return _ImagePlaceholder(title: title, icon: Icons.menu_book_outlined);
|
||||
}
|
||||
return CachedNetworkImage(
|
||||
imageUrl: coverUrl,
|
||||
fit: BoxFit.cover,
|
||||
memCacheWidth: 160,
|
||||
memCacheHeight: 220,
|
||||
placeholder: (_, __) =>
|
||||
_ImagePlaceholder(title: title, icon: Icons.menu_book_outlined),
|
||||
errorWidget: (_, __, ___) =>
|
||||
_ImagePlaceholder(title: title, icon: Icons.menu_book_outlined),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class _ImagePlaceholder extends StatelessWidget {
|
||||
const _ImagePlaceholder(
|
||||
{required this.title, this.icon = Icons.image_outlined});
|
||||
|
||||
final String title;
|
||||
final IconData icon;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Container(
|
||||
color: const Color(0xFFFFE8EE),
|
||||
alignment: Alignment.center,
|
||||
child: Icon(icon, color: const Color(0xFFD95A83)),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class _MessageCard extends StatelessWidget {
|
||||
const _MessageCard({
|
||||
required this.icon,
|
||||
required this.title,
|
||||
required this.message,
|
||||
});
|
||||
|
||||
final IconData icon;
|
||||
final String title;
|
||||
final String message;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Card(
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.all(18),
|
||||
child: Column(
|
||||
children: [
|
||||
Icon(icon, color: const Color(0xFFD95A83)),
|
||||
const SizedBox(height: 10),
|
||||
Text(
|
||||
title,
|
||||
style: Theme.of(context).textTheme.titleMedium?.copyWith(
|
||||
fontWeight: FontWeight.w700,
|
||||
),
|
||||
textAlign: TextAlign.center,
|
||||
),
|
||||
const SizedBox(height: 6),
|
||||
Text(
|
||||
message,
|
||||
style: Theme.of(context).textTheme.bodyMedium?.copyWith(
|
||||
color: const Color(0xFF7B6570),
|
||||
height: 1.5,
|
||||
),
|
||||
textAlign: TextAlign.center,
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class _SkeletonStrip extends StatelessWidget {
|
||||
const _SkeletonStrip();
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return SizedBox(
|
||||
height: 210,
|
||||
child: ListView.separated(
|
||||
scrollDirection: Axis.horizontal,
|
||||
physics: const NeverScrollableScrollPhysics(),
|
||||
itemCount: 3,
|
||||
separatorBuilder: (_, __) => const SizedBox(width: 12),
|
||||
itemBuilder: (_, __) => const SizedBox(
|
||||
width: 148,
|
||||
child: _SkeletonCard(height: 210),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class _SkeletonCard extends StatelessWidget {
|
||||
const _SkeletonCard({required this.height});
|
||||
|
||||
final double height;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Container(
|
||||
height: height,
|
||||
decoration: BoxDecoration(
|
||||
color: const Color(0xFFFFE8EE),
|
||||
borderRadius: BorderRadius.circular(18),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
int _compareArtworkUpdateDesc(Artwork a, Artwork b) {
|
||||
final aTime = a.createdAt ?? a.updatedAt ?? a.lastViewedAt;
|
||||
final bTime = b.createdAt ?? b.updatedAt ?? b.lastViewedAt;
|
||||
if (aTime != null && bTime != null) {
|
||||
return bTime.compareTo(aTime);
|
||||
}
|
||||
if (aTime != null) {
|
||||
return -1;
|
||||
}
|
||||
if (bTime != null) {
|
||||
return 1;
|
||||
}
|
||||
return a.title.compareTo(b.title);
|
||||
}
|
||||
|
||||
int _compareArtworkRecentDesc(Artwork a, Artwork b) {
|
||||
final aTime = a.lastViewedAt ?? a.updatedAt ?? a.createdAt;
|
||||
final bTime = b.lastViewedAt ?? b.updatedAt ?? b.createdAt;
|
||||
if (aTime != null && bTime != null) {
|
||||
return bTime.compareTo(aTime);
|
||||
}
|
||||
if (aTime != null) return -1;
|
||||
if (bTime != null) return 1;
|
||||
return a.title.compareTo(b.title);
|
||||
}
|
||||
|
||||
DateTime? _parseDate(Object? value) {
|
||||
return DateTime.tryParse(value?.toString() ?? '');
|
||||
}
|
||||
|
||||
bool _isToday(DateTime value) {
|
||||
final local = value.toLocal();
|
||||
final now = DateTime.now();
|
||||
return local.year == now.year &&
|
||||
local.month == now.month &&
|
||||
local.day == now.day;
|
||||
}
|
||||
|
||||
bool _isXAlert(Map<String, dynamic> item) {
|
||||
final platform = item['platform']?.toString().toLowerCase() ?? '';
|
||||
final source = item['source_platform']?.toString().toLowerCase() ?? '';
|
||||
return platform == 'x' || platform == 'twitter' || source == 'x';
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,431 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_riverpod/flutter_riverpod.dart';
|
||||
|
||||
import '../../core/providers.dart';
|
||||
import '../favorites_page.dart';
|
||||
import '../reminder_center_page.dart';
|
||||
import '../source_manager_page.dart';
|
||||
|
||||
class ProfileTab extends ConsumerStatefulWidget {
|
||||
const ProfileTab({super.key});
|
||||
|
||||
@override
|
||||
ConsumerState<ProfileTab> createState() => _ProfileTabState();
|
||||
}
|
||||
|
||||
class _ProfileTabState extends ConsumerState<ProfileTab> {
|
||||
late Future<_ProfileData> _future = _load();
|
||||
bool _savingReminder = false;
|
||||
|
||||
Future<_ProfileData> _load() async {
|
||||
final api = ref.read(apiClientProvider);
|
||||
Map<String, dynamic> user = <String, dynamic>{};
|
||||
Map<String, dynamic> stat = <String, dynamic>{};
|
||||
try {
|
||||
// ignore: unused_local_variable
|
||||
final session = ref.read(sessionProvider);
|
||||
} catch (_) {
|
||||
// keep empty user map
|
||||
}
|
||||
try {
|
||||
stat = await api.galleryStat().timeout(const Duration(seconds: 3),
|
||||
onTimeout: () => <String, dynamic>{});
|
||||
} catch (_) {
|
||||
// keep empty stat map
|
||||
}
|
||||
return _ProfileData(user: user, stat: stat);
|
||||
}
|
||||
|
||||
void _refresh() {
|
||||
ref.invalidate(apiClientProvider);
|
||||
setState(() {
|
||||
_future = _load();
|
||||
});
|
||||
}
|
||||
|
||||
Future<void> _updateReminder(
|
||||
Map<String, dynamic> user, {
|
||||
bool? reminderEnabled,
|
||||
int? reminderHour,
|
||||
int? reminderMinute,
|
||||
}) async {
|
||||
if (_savingReminder) {
|
||||
return;
|
||||
}
|
||||
|
||||
final enabled =
|
||||
reminderEnabled ?? (user['reminder_enabled'] as bool? ?? true);
|
||||
final hour = reminderHour ?? (user['reminder_hour'] as int? ?? 9);
|
||||
final minute = reminderMinute ?? (user['reminder_minute'] as int? ?? 0);
|
||||
final timezone = user['reminder_timezone']?.toString() ?? 'Asia/Shanghai';
|
||||
|
||||
setState(() {
|
||||
_savingReminder = true;
|
||||
});
|
||||
|
||||
try {
|
||||
await ref.read(apiClientProvider).updateMe(
|
||||
reminderEnabled: enabled,
|
||||
reminderHour: hour,
|
||||
reminderMinute: minute,
|
||||
reminderTimezone: timezone,
|
||||
);
|
||||
if (!mounted) {
|
||||
return;
|
||||
}
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
SnackBar(
|
||||
content: Text(
|
||||
enabled ? '已更新每日 ${_timeLabel(hour, minute)} 提醒' : '已关闭每日更新提醒',
|
||||
),
|
||||
),
|
||||
);
|
||||
_refresh();
|
||||
} catch (error) {
|
||||
if (!mounted) {
|
||||
return;
|
||||
}
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
SnackBar(content: Text('提醒设置保存失败:$error')),
|
||||
);
|
||||
} finally {
|
||||
if (mounted) {
|
||||
setState(() {
|
||||
_savingReminder = false;
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> _pickReminderTime(Map<String, dynamic> user) async {
|
||||
final initialTime = TimeOfDay(
|
||||
hour: user['reminder_hour'] as int? ?? 9,
|
||||
minute: user['reminder_minute'] as int? ?? 0,
|
||||
);
|
||||
final picked = await showTimePicker(
|
||||
context: context,
|
||||
initialTime: initialTime,
|
||||
helpText: '选择每日提醒时间',
|
||||
builder: (context, child) {
|
||||
return Theme(
|
||||
data: Theme.of(context).copyWith(
|
||||
colorScheme: Theme.of(context).colorScheme.copyWith(
|
||||
primary: const Color(0xFFD95A83),
|
||||
surface: const Color(0xFFFFFBFD),
|
||||
),
|
||||
),
|
||||
child: child ?? const SizedBox.shrink(),
|
||||
);
|
||||
},
|
||||
);
|
||||
if (picked == null) {
|
||||
return;
|
||||
}
|
||||
await _updateReminder(
|
||||
user,
|
||||
reminderEnabled: true,
|
||||
reminderHour: picked.hour,
|
||||
reminderMinute: picked.minute,
|
||||
);
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return FutureBuilder<_ProfileData>(
|
||||
future: _future,
|
||||
builder: (context, snapshot) {
|
||||
final data = snapshot.data ?? const _ProfileData();
|
||||
final user = data.user;
|
||||
final stat = data.stat;
|
||||
final session = ref.read(sessionProvider);
|
||||
final username = session.username;
|
||||
final email = (user['email'] as String?) ?? '欢迎回来';
|
||||
final initial =
|
||||
username.isNotEmpty ? username.substring(0, 1).toUpperCase() : 'S';
|
||||
final reminderEnabled = user['reminder_enabled'] as bool? ?? true;
|
||||
final reminderHour = user['reminder_hour'] as int? ?? 9;
|
||||
final reminderMinute = user['reminder_minute'] as int? ?? 0;
|
||||
final reminderLabel = _timeLabel(reminderHour, reminderMinute);
|
||||
|
||||
// prefer stat endpoint for gallery numbers, fall back to user payload
|
||||
final storageUsed =
|
||||
(stat['storage_used'] ?? user['storage_used'] ?? 0) as num;
|
||||
final totalWorks = stat['total'] ?? user['gallery_total'] ?? 0;
|
||||
final totalFavorites =
|
||||
stat['favorites'] ?? user['gallery_favorites'] ?? 0;
|
||||
|
||||
return RefreshIndicator(
|
||||
color: const Color(0xFFD95A83),
|
||||
onRefresh: () async {
|
||||
_refresh();
|
||||
await _future;
|
||||
},
|
||||
child: ListView(
|
||||
padding: const EdgeInsets.fromLTRB(16, 14, 16, 28),
|
||||
children: [
|
||||
Text(
|
||||
'我的',
|
||||
style: Theme.of(context)
|
||||
.textTheme
|
||||
.headlineMedium
|
||||
?.copyWith(fontWeight: FontWeight.w900),
|
||||
),
|
||||
const SizedBox(height: 14),
|
||||
Container(
|
||||
decoration: BoxDecoration(
|
||||
borderRadius: BorderRadius.circular(28),
|
||||
gradient: const LinearGradient(
|
||||
colors: [Color(0xFFFFE6EE), Color(0xFFFFF8FB)],
|
||||
begin: Alignment.topLeft,
|
||||
end: Alignment.bottomRight,
|
||||
),
|
||||
),
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.all(20),
|
||||
child: Row(
|
||||
children: [
|
||||
CircleAvatar(
|
||||
radius: 30,
|
||||
backgroundColor: Colors.white,
|
||||
child: Text(
|
||||
initial,
|
||||
style:
|
||||
Theme.of(context).textTheme.titleLarge?.copyWith(
|
||||
color: const Color(0xFFD95A83),
|
||||
fontWeight: FontWeight.w900,
|
||||
),
|
||||
),
|
||||
),
|
||||
const SizedBox(width: 16),
|
||||
Expanded(
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Text(
|
||||
username,
|
||||
style: Theme.of(context)
|
||||
.textTheme
|
||||
.titleLarge
|
||||
?.copyWith(fontWeight: FontWeight.w800),
|
||||
),
|
||||
const SizedBox(height: 4),
|
||||
Text(
|
||||
email,
|
||||
style: Theme.of(context)
|
||||
.textTheme
|
||||
.bodyMedium
|
||||
?.copyWith(
|
||||
color: const Color(0xFF7B6570),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
if (snapshot.hasError) ...[
|
||||
const SizedBox(height: 16),
|
||||
const Card(
|
||||
child: ListTile(
|
||||
leading: Icon(Icons.cloud_off_outlined),
|
||||
title: Text('资料暂时加载失败'),
|
||||
subtitle: Text('服务端可能正在忙,稍后下拉刷新再试。'),
|
||||
),
|
||||
),
|
||||
] else ...[
|
||||
const SizedBox(height: 18),
|
||||
Card(
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.all(18),
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Row(
|
||||
children: [
|
||||
const Icon(
|
||||
Icons.notifications_active_outlined,
|
||||
color: Color(0xFFD95A83),
|
||||
),
|
||||
const SizedBox(width: 10),
|
||||
Expanded(
|
||||
child: Text(
|
||||
'每日更新提醒',
|
||||
style: Theme.of(context)
|
||||
.textTheme
|
||||
.titleMedium
|
||||
?.copyWith(fontWeight: FontWeight.w800),
|
||||
),
|
||||
),
|
||||
Switch.adaptive(
|
||||
value: reminderEnabled,
|
||||
activeThumbColor: const Color(0xFFD95A83),
|
||||
onChanged: _savingReminder
|
||||
? null
|
||||
: (value) => _updateReminder(
|
||||
user,
|
||||
reminderEnabled: value,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
const SizedBox(height: 8),
|
||||
Text(
|
||||
'云端会在每天设定时间后检查你关注的 Pixiv / X 作者更新,并生成摘要提醒。关注入口请先到电脑端的缩略图墙里操作。',
|
||||
style:
|
||||
Theme.of(context).textTheme.bodyMedium?.copyWith(
|
||||
color: const Color(0xFF7B6570),
|
||||
height: 1.5,
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 14),
|
||||
Row(
|
||||
children: [
|
||||
FilledButton.tonalIcon(
|
||||
onPressed: _savingReminder
|
||||
? null
|
||||
: () => _pickReminderTime(user),
|
||||
icon: const Icon(Icons.schedule_outlined),
|
||||
label: Text('提醒时间 $reminderLabel'),
|
||||
),
|
||||
const SizedBox(width: 10),
|
||||
if (_savingReminder)
|
||||
const SizedBox(
|
||||
width: 20,
|
||||
height: 20,
|
||||
child:
|
||||
CircularProgressIndicator(strokeWidth: 2),
|
||||
),
|
||||
],
|
||||
),
|
||||
const SizedBox(height: 12),
|
||||
OutlinedButton.icon(
|
||||
onPressed: () {
|
||||
Navigator.of(context).push(
|
||||
MaterialPageRoute(
|
||||
builder: (_) => const ReminderCenterPage(),
|
||||
),
|
||||
);
|
||||
},
|
||||
icon: const Icon(Icons.open_in_new_outlined),
|
||||
label: const Text('打开提醒中心'),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 12),
|
||||
Card(
|
||||
color: const Color(0xFFFFF7FA),
|
||||
child: ListTile(
|
||||
leading: const CircleAvatar(
|
||||
backgroundColor: Color(0xFFFFE1EA),
|
||||
child: Icon(
|
||||
Icons.favorite,
|
||||
color: Color(0xFFD95A83),
|
||||
),
|
||||
),
|
||||
title: const Text('我的收藏'),
|
||||
subtitle: const Text('喜欢的插画、漫画和小说都在这里。'),
|
||||
trailing: const Icon(Icons.chevron_right),
|
||||
onTap: () {
|
||||
Navigator.of(context).push(
|
||||
MaterialPageRoute(
|
||||
builder: (_) => const FavoritesPage(),
|
||||
),
|
||||
);
|
||||
},
|
||||
),
|
||||
),
|
||||
Card(
|
||||
child: ListTile(
|
||||
leading: const Icon(Icons.storage_outlined),
|
||||
title: const Text('云端空间'),
|
||||
subtitle: Text(
|
||||
'${(storageUsed.toDouble() / 1024 / 1024).toStringAsFixed(1)} MB 已使用'
|
||||
' · $totalWorks 个作品'
|
||||
' · $totalFavorites 个收藏',
|
||||
),
|
||||
),
|
||||
),
|
||||
Card(
|
||||
child: ListTile(
|
||||
leading: const Icon(Icons.travel_explore_outlined),
|
||||
title: const Text('书源管理'),
|
||||
subtitle: const Text('导入和启用小说或漫画书源。'),
|
||||
trailing: const Icon(Icons.chevron_right),
|
||||
onTap: () {
|
||||
Navigator.of(context).push(
|
||||
MaterialPageRoute(
|
||||
builder: (_) => const SourceManagerPage(),
|
||||
),
|
||||
);
|
||||
},
|
||||
),
|
||||
),
|
||||
Card(
|
||||
child: ListTile(
|
||||
leading: const Icon(Icons.photo_library_outlined),
|
||||
title: const Text('收藏图片'),
|
||||
subtitle: const Text('最近收藏的插画和漫画都会在这里整理。'),
|
||||
trailing: const Icon(Icons.chevron_right),
|
||||
onTap: () {
|
||||
Navigator.of(context).push(
|
||||
MaterialPageRoute(
|
||||
builder: (_) => const FavoritesPage(initialIndex: 0),
|
||||
),
|
||||
);
|
||||
},
|
||||
),
|
||||
),
|
||||
Card(
|
||||
child: ListTile(
|
||||
leading: const Icon(Icons.menu_book_outlined),
|
||||
title: const Text('收藏小说'),
|
||||
subtitle: const Text('系列小说会按书名和章节顺序归档。'),
|
||||
trailing: const Icon(Icons.chevron_right),
|
||||
onTap: () {
|
||||
Navigator.of(context).push(
|
||||
MaterialPageRoute(
|
||||
builder: (_) => const FavoritesPage(initialIndex: 1),
|
||||
),
|
||||
);
|
||||
},
|
||||
),
|
||||
),
|
||||
const Card(
|
||||
child: ListTile(
|
||||
leading: Icon(Icons.sync_outlined),
|
||||
title: Text('同步说明'),
|
||||
subtitle: Text('登录后会同步最近浏览、收藏、阅读进度和每日提醒设置。'),
|
||||
),
|
||||
),
|
||||
],
|
||||
const SizedBox(height: 16),
|
||||
OutlinedButton.icon(
|
||||
onPressed: () => ref.read(sessionProvider.notifier).logout(),
|
||||
icon: const Icon(Icons.logout),
|
||||
label: const Text('退出登录'),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class _ProfileData {
|
||||
const _ProfileData({
|
||||
this.user = const <String, dynamic>{},
|
||||
this.stat = const <String, dynamic>{},
|
||||
});
|
||||
|
||||
final Map<String, dynamic> user;
|
||||
final Map<String, dynamic> stat;
|
||||
}
|
||||
|
||||
String _timeLabel(int hour, int minute) {
|
||||
return '${hour.toString().padLeft(2, '0')}:${minute.toString().padLeft(2, '0')}';
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
class SakuraSearchBar extends StatelessWidget {
|
||||
const SakuraSearchBar({
|
||||
super.key,
|
||||
required this.hintText,
|
||||
this.controller,
|
||||
this.onSubmitted,
|
||||
this.onExploreTap,
|
||||
this.onRefreshTap,
|
||||
});
|
||||
|
||||
final String hintText;
|
||||
final TextEditingController? controller;
|
||||
final ValueChanged<String>? onSubmitted;
|
||||
final VoidCallback? onExploreTap;
|
||||
final VoidCallback? onRefreshTap;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return SearchBar(
|
||||
controller: controller,
|
||||
hintText: hintText,
|
||||
leading: const Icon(Icons.search),
|
||||
trailing: [
|
||||
if (onExploreTap != null)
|
||||
IconButton(
|
||||
tooltip: '在线搜索',
|
||||
icon: const Icon(Icons.travel_explore_outlined),
|
||||
onPressed: onExploreTap,
|
||||
),
|
||||
if (onRefreshTap != null)
|
||||
IconButton(
|
||||
tooltip: '刷新',
|
||||
icon: const Icon(Icons.refresh_rounded),
|
||||
onPressed: onRefreshTap,
|
||||
),
|
||||
],
|
||||
onSubmitted: onSubmitted,
|
||||
padding: const WidgetStatePropertyAll(EdgeInsets.symmetric(horizontal: 4)),
|
||||
);
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user