first commit

Co-Authored-By: Claude <noreply@anthropic.com>
This commit is contained in:
kunkunxiaomaoandClaude committed 2026-11-16 20:45:22 +08:00
commit 9c5fef1a4d
412 files changed
+94582

No files matched your search

@@ -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('重试'),
),
],
),
);
}