1507 lines
51 KiB
Markdown
1507 lines
51 KiB
Markdown
# 在线搜索与阅读 — 源码架构总结
|
||
|
||
> 总结日期:2026-06-21
|
||
> 源码范围:`sakura_mobile/lib/src/core/` + `sakura_mobile/lib/src/pages/`
|
||
> 说明:本文档梳理在线搜索→详情→目录→阅读全流程的现有源码结构,不做方案设计。
|
||
|
||
---
|
||
|
||
## 目录
|
||
|
||
1. [文件清单与职责](#一文件清单与职责)
|
||
2. [核心类关系图](#二核心类关系图)
|
||
3. [Provider 依赖注入](#三provider-依赖注入)
|
||
4. [数据模型详解](#四数据模型详解)
|
||
5. [搜索引擎 LegadoEngine](#五搜索引擎-legadoengine)
|
||
6. [规则解析器 RuleParser](#六规则解析器-ruleparser)
|
||
7. [书源管理 SourceManager](#七书源管理-sourcemanager)
|
||
8. [统一搜索 UnifiedSearch](#八统一搜索-unifiedsearch)
|
||
9. [页面层源码](#九页面层源码)
|
||
10. [缓存与阅读记录](#十缓存与阅读记录)
|
||
11. [完整调用链路](#十一完整调用链路)
|
||
|
||
---
|
||
|
||
## 一、文件清单与职责
|
||
|
||
### Core 层(核心引擎 + 数据模型)
|
||
|
||
| 文件 | 行数 | 核心职责 |
|
||
|------|------|---------|
|
||
| `legado_models.dart` | 515 | 所有数据模型:`LegadoSource`、`OnlineBookInfo`、`OnlineChapter`、`OnlineChapterContent`、`OnlineReadingRecord`、`UnifiedSearchResult`、`SourceRepo` |
|
||
| `legado_engine.dart` | 956 | 在线内容引擎:HTTP 请求、搜索、BookInfo 解析、TOC 解析、章节内容解析、编码处理、错误归一化 |
|
||
| `legado_rule_parser.dart` | 262 | HTML/JSON/Regex 规则解析器:CSS 选择器、JSONPath、Regex 三种解析方式 |
|
||
| `source_manager.dart` | 368 | 书源生命周期管理:导入、启用/禁用、订阅更新、健康检查、SharedPreferences 持久化 |
|
||
| `unified_search.dart` | 173 | 统一搜索编排:合并云库搜索 + 在线书源搜索,返回 `SearchSection` 列表 |
|
||
| `online_cache.dart` | 25 | 会话级内存缓存:BookInfo、TOC、ChapterContent 三级缓存 |
|
||
| `online_reading_history.dart` | 57 | 阅读记录持久化:SharedPreferences 存储最近 50 条记录 |
|
||
| `providers.dart` | 32 | Riverpod 依赖注入:5 个全局 Provider |
|
||
| `api_client.dart` | — | 云端 API 客户端(搜索用 `gallery()` / `novels()`) |
|
||
| `session.dart` | — | 会话管理(登录态) |
|
||
|
||
### Pages 层(UI 页面)
|
||
|
||
| 文件 | 行数 | 核心职责 |
|
||
|------|------|---------|
|
||
| `explore_page.dart` | 503 | 在线搜索页:输入框、漫画/小说切换、结果列表展示、点击跳转 |
|
||
| `online_book_detail_page.dart` | 338 | 在线书籍详情页(合并 BookInfo + TOC UI):封面、书名、作者、简介、章节列表、正序/倒序、继续阅读 |
|
||
| `online_manga_reader_page.dart` | 208 | 在线漫画阅读器:PageView 图片浏览、上一章/下一章/目录导航、预加载、阅读记录 |
|
||
| `online_novel_reader_page.dart` | 195 | 在线小说阅读器:文本展示、字体缩放、上一章/下一章/目录导航、预加载、阅读记录 |
|
||
|
||
---
|
||
|
||
## 二、核心类关系图
|
||
|
||
```
|
||
┌──────────────────────────────────────────────────────────────┐
|
||
│ providers.dart │
|
||
│ ┌─────────────┐ ┌──────────────┐ ┌───────────────────┐ │
|
||
│ │ Session │ │SourceManager │ │ LegadoEngine │ │
|
||
│ │ Controller │ │ (书源管理) │ │ (在线内容引擎) │ │
|
||
│ └──────┬───────┘ └──────┬───────┘ └────────┬──────────┘ │
|
||
│ │ │ │ │
|
||
│ ┌──────▼───────┐ │ │ │
|
||
│ │SakuraApiClient│ │ │ │
|
||
│ │ (云端API) │ │ │ │
|
||
│ └──────┬───────┘ │ │ │
|
||
│ │ │ │ │
|
||
│ ┌──────▼─────────────────▼────────────────────▼──────────┐ │
|
||
│ │ UnifiedSearch │ │
|
||
│ │ (编排:cloudFuture + onlineFuture → SearchSection) │ │
|
||
│ └────────────────────────┬──────────────────────────────┘ │
|
||
└───────────────────────────┼────────────────────────────────┘
|
||
│
|
||
┌───────────────────┼───────────────────┐
|
||
▼ ▼ ▼
|
||
ExplorePage OnlineBookDetailPage OnlineXxxReaderPage
|
||
(搜索UI) (详情+目录UI) (阅读UI)
|
||
```
|
||
|
||
### LegadoEngine 内部结构
|
||
|
||
```
|
||
LegadoEngine
|
||
├── Dio _http ← HTTP 客户端(15s 连接超时,20s 接收超时)
|
||
├── OnlineContentCache cache ← 会话级缓存
|
||
│
|
||
├── 搜索 ───────────────────────────
|
||
│ ├── search() ← 单源搜索(构建请求 → 获取响应 → 解析结果)
|
||
│ ├── searchAll() ← 多源并发搜索(每批 10 个,Future.wait)
|
||
│ ├── _buildSearchRequest() ← 构建搜索 URL + 编码关键词
|
||
│ ├── _applySearchTemplate() ← 替换 {{key}} / {{page}} 占位符
|
||
│ └── _fallbackSearchResults() ← 回退:扫描 <a> 标签
|
||
│
|
||
├── 详情 ───────────────────────────
|
||
│ ├── fetchBookInfo() ← 解析书籍详情页 → OnlineBookInfo
|
||
│
|
||
├── 目录 ───────────────────────────
|
||
│ ├── fetchToc() ← 解析章节目录(带缓存)
|
||
│ ├── _fetchPaginatedToc() ← 分页目录加载(最多 20 页)
|
||
│ └── _fallbackChapters() ← 回退:章节识别器扫描 <a>
|
||
│
|
||
├── 内容 ───────────────────────────
|
||
│ ├── fetchChapterContent() ← 解析章节内容 → OnlineChapterContent
|
||
│ ├── fetchPlainText() ← 旧 API:从 URL 提取纯文本(无规则)
|
||
│ ├── fetchImageUrls() ← 旧 API:从 URL 提取图片(无规则)
|
||
│ └── _extractImageUrls() ← 图片提取(含 data-src/data-original)
|
||
│
|
||
├── 编解码 ─────────────────────────
|
||
│ ├── _encodeKeyword() ← URL 关键词编码(GBK/UTF-8/平台通道)
|
||
│ ├── _decodeBody() ← 响应体解码(GBK/UTF-8/Latin1)
|
||
│ └── _charsetFromContentType() ← 从 Content-Type 提取 charset
|
||
│
|
||
├── HTTP ───────────────────────────
|
||
│ ├── _fetchBody() ← 统一 HTTP 请求(GET/POST,字节响应 + 状态码检查)
|
||
│ ├── _debugDioException() ← Dio 异常日志
|
||
│ └── _debugHttpResponse() ← HTTP 错误日志
|
||
│
|
||
├── 工具 ───────────────────────────
|
||
│ ├── _resolveUrl() ← 相对 URL → 绝对 URL
|
||
│ ├── resolveResourceUrl() ← 公开版 URL 解析
|
||
│ ├── _htmlToText() ← HTML → 纯文本
|
||
│ ├── _plainTextFromJson() ← JSON → 提取文本字段
|
||
│ ├── _imageUrlsFromJson() ← JSON → 提取图片 URL
|
||
│ ├── _safeSelect() / _safeSelectList() ← 规则解析安全包装
|
||
│ ├── _shortError() ← 错误消息归一化(中文映射表)
|
||
│ └── parseSources() ← JSON 文本 → List<LegadoSource>
|
||
│
|
||
└── 数据类 ─────────────────────────
|
||
└── _LegadoRequest { method, url, body }
|
||
```
|
||
|
||
---
|
||
|
||
## 三、Provider 依赖注入
|
||
|
||
**文件**:`sakura_mobile/lib/src/core/providers.dart`
|
||
|
||
```dart
|
||
// 1. 会话管理(登录态)— StateNotifier
|
||
final sessionProvider = StateNotifierProvider<SessionController, SessionState>(...);
|
||
|
||
// 2. 云端 API 客户端 — 依赖 sessionProvider
|
||
final apiClientProvider = Provider<SakuraApiClient>((ref) {
|
||
ref.watch(sessionProvider);
|
||
return ref.read(sessionProvider.notifier).client();
|
||
});
|
||
|
||
// 3. 书源管理器 — ChangeNotifier(UI 可监听 busy/message 状态)
|
||
final sourceManagerProvider = ChangeNotifierProvider<SourceManager>((ref) {
|
||
final manager = SourceManager();
|
||
manager.initializeIfFirstRun(); // 首次运行提示导入书源
|
||
return manager;
|
||
});
|
||
|
||
// 4. 在线引擎 — 单例
|
||
final legadoEngineProvider = Provider<LegadoEngine>((ref) => LegadoEngine());
|
||
|
||
// 5. 统一搜索 — 组合 apiClient + sourceManager + engine
|
||
final unifiedSearchProvider = Provider<UnifiedSearch>((ref) {
|
||
return UnifiedSearch(
|
||
api: ref.watch(apiClientProvider),
|
||
sourceManager: ref.watch(sourceManagerProvider),
|
||
engine: ref.watch(legadoEngineProvider),
|
||
);
|
||
});
|
||
```
|
||
|
||
**Provider 消费方式**(在各页面中):
|
||
|
||
```dart
|
||
// 获取一次值(不监听变化)
|
||
final engine = ref.read(legadoEngineProvider);
|
||
|
||
// 监听变化(UI 自动刷新)
|
||
final manager = ref.watch(sourceManagerProvider);
|
||
```
|
||
|
||
---
|
||
|
||
## 四、数据模型详解
|
||
|
||
### 4.1 LegadoSource(书源规则)
|
||
|
||
**文件**:`legado_models.dart:21-306`
|
||
|
||
完整的 Legado 书源模型,包含四个规则模块。
|
||
|
||
**构造函数参数(共 29 个字段)**:
|
||
|
||
```dart
|
||
class LegadoSource {
|
||
// === 基础字段 ===
|
||
final String id; // 派生自 name+url 的 hash
|
||
final String name; // bookSourceName
|
||
final String url; // bookSourceUrl
|
||
final int type; // 0=小说, 2=漫画
|
||
final bool enabled;
|
||
|
||
// === HTTP 配置 ===
|
||
final String? userAgent;
|
||
final Map<String, String> headers; // 含 Cookie
|
||
final String? charset; // gbk / utf-8
|
||
final String? urlEncoding; // 关键词 URL 编码字符集
|
||
final String? ruleKind; // css / json / regex
|
||
|
||
// === Search 规则(ruleSearch)===
|
||
final String? searchUrl; // 搜索 URL 模板,含 {{key}} {{page}}
|
||
final String? searchListRule; // 结果条目列表选择器
|
||
final String? searchNameRule; // 书名选择器
|
||
final String? searchAuthorRule; // 作者选择器
|
||
final String? searchCoverRule; // 封面选择器
|
||
final String? searchDetailRule; // 详情链接选择器 → detailUrl
|
||
final String? searchMethod; // GET / POST
|
||
final String? searchBody; // POST body 模板
|
||
|
||
// === BookInfo 规则(ruleBookInfo)===
|
||
final String? bookInfoUrl; // 详情页 URL 模板
|
||
final String? bookInfoNameRule;
|
||
final String? bookInfoAuthorRule;
|
||
final String? bookInfoCoverRule;
|
||
final String? bookInfoIntroRule;
|
||
final String? bookInfoTocRule; // ⭐ 目录页 URL 选择器
|
||
|
||
// === TOC 规则(ruleToc)===
|
||
final String? tocUrl; // 目录页 URL 模板(支持 {{page}})
|
||
final String? tocListRule; // 章节条目列表选择器
|
||
final String? tocNameRule; // 章节名称选择器
|
||
final String? tocUrlRule; // 章节链接选择器
|
||
final String? tocNextPageRule; // 下一页目录选择器
|
||
|
||
// === Content 规则(ruleContent)===
|
||
final String? contentRule; // 正文内容选择器
|
||
final String? contentNextRule; // 下一章链接选择器
|
||
final String? contentPrevRule; // 上一章链接选择器
|
||
}
|
||
```
|
||
|
||
**类型判断**:
|
||
- `isNovel` → `type == 0`
|
||
- `isManga` → `type == 2`
|
||
|
||
**fromJson 解析逻辑**(`legado_models.dart:130-261`):
|
||
1. 从 `json['ruleSearch']` 提取搜索规则(13 种 key 备选)
|
||
2. 从 `json['ruleBookInfo']` 提取详情规则(4 种 key 备选)
|
||
3. 从 `json['ruleToc']` 提取目录规则(5 种 key 备选)
|
||
4. 从 `json['ruleContent']` 提取内容规则(3 种 key 备选)
|
||
5. 从 `json['header']` / `json['headers']` 提取请求头(支持 Map / JSON 字符串 / 冒号分隔行三种格式)
|
||
6. 从 `json['cookie']` 合并 Cookie 到 headers
|
||
|
||
**copyWith 方法**(`legado_models.dart:93-128`):
|
||
- 唯一可变参数:`enabled`
|
||
- 所有规则字段原样传递(不可变对象)
|
||
|
||
**toJson 方法**(`legado_models.dart:263-305`):
|
||
- 输出完整的 Legado 兼容 JSON
|
||
- 包含 `ruleSearch` / `ruleBookInfo` / `ruleToc` / `ruleContent` 四个顶层 key
|
||
- 空值不输出(`if (xxx != null)` 条件添加)
|
||
|
||
**字段名对照表**(输出 JSON key → Legado 标准名):
|
||
|
||
| 内部字段 | JSON key |
|
||
|---------|----------|
|
||
| `name` | `bookSourceName` |
|
||
| `url` | `bookSourceUrl` |
|
||
| `type` | `bookSourceType` |
|
||
| `searchListRule` | `ruleSearch.bookList` |
|
||
| `bookInfoTocRule` | `ruleBookInfo.tocUrl` |
|
||
| `tocListRule` | `ruleToc.chapterList` |
|
||
| `contentRule` | `ruleContent.content` |
|
||
|
||
---
|
||
|
||
### 4.2 OnlineBookInfo(运行时书籍详情)
|
||
|
||
```dart
|
||
class OnlineBookInfo {
|
||
final String title; // 书名(来自 bookInfoNameRule 解析或搜索结果的 initialTitle)
|
||
final String? author;
|
||
final String? coverUrl;
|
||
final String? intro; // 简介
|
||
final String tocUrl; // 目录页 URL ⭐
|
||
final String sourceName; // 来源书源名称
|
||
}
|
||
```
|
||
|
||
**来源**:`LegadoEngine.fetchBookInfo()` 解析 `detailUrl` 指向的页面。
|
||
|
||
---
|
||
|
||
### 4.3 OnlineChapter(运行时章节条目)
|
||
|
||
```dart
|
||
class OnlineChapter {
|
||
final String title; // 章节标题
|
||
final String url; // 章节内容 URL
|
||
final int index; // 序号(从 1 开始)
|
||
}
|
||
```
|
||
|
||
**来源**:`LegadoEngine.fetchToc()` 解析目录页。
|
||
|
||
---
|
||
|
||
### 4.4 OnlineChapterContent(运行时章节内容)
|
||
|
||
```dart
|
||
class OnlineChapterContent {
|
||
final String title; // 章节标题
|
||
final String? textContent; // 小说正文(纯文本)
|
||
final List<String> imageUrls; // 漫画图片 URL 列表
|
||
final String? nextChapterUrl; // 下一章 URL(contentNextRule 解析结果)
|
||
final String? prevChapterUrl; // 上一章 URL
|
||
}
|
||
```
|
||
|
||
**来源**:`LegadoEngine.fetchChapterContent()` 解析章节页。
|
||
|
||
---
|
||
|
||
### 4.5 OnlineReadingRecord(阅读记录)
|
||
|
||
```dart
|
||
class OnlineReadingRecord {
|
||
final String sourceId; // 书源 ID
|
||
final String sourceName; // 书源名称
|
||
final String bookTitle; // 书名
|
||
final String detailUrl; // 书籍详情页 URL
|
||
final String chapterUrl; // 当前阅读的章节 URL
|
||
final String chapterTitle; // 当前阅读的章节标题
|
||
final int chapterIndex; // 章节序号(0-based)
|
||
final int totalChapters; // 总章节数
|
||
final DateTime lastReadTime; // 最后阅读时间
|
||
}
|
||
```
|
||
|
||
**存储**:`OnlineReadingHistory` → SharedPreferences JSON 数组,最多 50 条。
|
||
|
||
---
|
||
|
||
### 4.6 UnifiedSearchResult(搜索结果条目)
|
||
|
||
```dart
|
||
class UnifiedSearchResult {
|
||
final String sourceId; // 书源 ID
|
||
final String sourceName; // 书源名称
|
||
final String title; // 书名
|
||
final String? author;
|
||
final String? coverUrl;
|
||
final String? detailUrl; // 书籍详情页 URL(非章节 URL)
|
||
final String? errorMessage; // 非空表示搜索失败
|
||
|
||
bool get isError => errorMessage?.trim().isNotEmpty == true;
|
||
}
|
||
```
|
||
|
||
**两种构造方式**:
|
||
- 正常结果:`UnifiedSearchResult(sourceId:, sourceName:, title:, ...)`
|
||
- 错误结果:`UnifiedSearchResult.error(sourceId:, sourceName:, errorMessage:)` → title 固定为"搜索失败"
|
||
|
||
---
|
||
|
||
### 4.7 SearchItem / SearchSection(搜索页 UI 数据)
|
||
|
||
```dart
|
||
class SearchItem {
|
||
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;
|
||
}
|
||
|
||
class SearchSection {
|
||
final String id; // 'cloud' | 'online'
|
||
final String title; // '我的云库' | '在线源'
|
||
final List<SearchItem> items;
|
||
}
|
||
```
|
||
|
||
---
|
||
|
||
## 五、搜索引擎 LegadoEngine
|
||
|
||
**文件**:`legado_engine.dart`(956 行)
|
||
|
||
### 5.1 初始化
|
||
|
||
```dart
|
||
class LegadoEngine {
|
||
LegadoEngine({Dio? http})
|
||
: _http = http ?? Dio(BaseOptions(
|
||
connectTimeout: Duration(seconds: 15),
|
||
receiveTimeout: perSourceTimeout, // 20s
|
||
headers: {
|
||
'User-Agent': 'Mozilla/5.0 ... Chrome/120 ...',
|
||
'Accept': 'text/html,...',
|
||
'Accept-Language': 'zh-CN,zh;q=0.9',
|
||
},
|
||
));
|
||
|
||
static const maxConcurrency = 10; // 单批并发数
|
||
static const perSourceTimeout = Duration(seconds: 20);
|
||
final OnlineContentCache cache = OnlineContentCache(); // 会话缓存实例
|
||
}
|
||
```
|
||
|
||
### 5.2 搜索方法
|
||
|
||
#### search() — 单源搜索
|
||
|
||
```
|
||
输入: LegadoSource, keyword, page
|
||
↓
|
||
1. 检查 searchUrl / searchListRule 非空
|
||
2. _buildSearchRequest(source, searchUrl, keyword, page)
|
||
→ _encodeKeyword(source, keyword) // GBK/UTF-8 百分号编码
|
||
→ _applySearchTemplate(template, encodedKeyword, page)
|
||
// 替换 {{key}} {{keyword}} {key} {keyword} <key> <keyword>
|
||
// searchKey %s {{page}} {page} <page>
|
||
→ resolveResourceUrl(source.url, rawUrl) // 相对→绝对
|
||
→ 返回 _LegadoRequest(method, url, body)
|
||
3. _fetchBody(source, url) // HTTP GET/POST
|
||
4. RuleParser(body) 解析
|
||
5. _safeSelectList(parser, searchListRule) → 提取结果条目片段
|
||
6. 每个片段提取: title/author/coverUrl/detailUrl
|
||
7. 过滤空 title
|
||
8. 如果规则解析无结果 → _fallbackSearchResults()
|
||
```
|
||
|
||
#### searchAll() — 多源并发搜索
|
||
|
||
```
|
||
输入: List<LegadoSource>, keyword
|
||
↓
|
||
循环: start=0; start < sources.length; start += 10
|
||
每批最多 10 个源,Future.wait 并发
|
||
每个源: search(source, keyword)
|
||
.timeout(20s)
|
||
.catchError() → UnifiedSearchResult.error()
|
||
结果追加到 results 列表
|
||
```
|
||
|
||
**关键**:`searchAll` 不做跨源去重。同一本书出现在 5 个书源中 → 5 条结果。
|
||
|
||
**错误处理**:
|
||
- 超时 → 返回带 `errorMessage` 的错误结果,不影响其他源
|
||
- 其他异常 → 同上
|
||
|
||
#### _fallbackSearchResults() — 搜索回退
|
||
|
||
当 `searchListRule` 解析不到结果时触发:
|
||
1. 扫描 HTML 中所有 `<a>` 标签
|
||
2. 标题必须包含搜索关键词(完全匹配)
|
||
3. 过滤 `#` 和 `javascript:` 链接
|
||
4. 最多返回 30 条
|
||
|
||
#### _applySearchTemplate() — 占位符替换
|
||
|
||
支持的占位符(按替换优先级):
|
||
|
||
```dart
|
||
{{key}} → encodedKeyword {{page}} → pageText
|
||
{{keyword}} → encodedKeyword {page} → pageText
|
||
{{searchKey}} → encodedKeyword <page> → pageText
|
||
{key} → encodedKeyword
|
||
{keyword} → encodedKeyword
|
||
{searchKey} → encodedKeyword
|
||
<key> → encodedKeyword
|
||
<keyword> → encodedKeyword
|
||
<searchKey> → encodedKeyword
|
||
searchKey → encodedKeyword // 无包裹的字符串直接替换
|
||
%s → encodedKeyword // printf 风格(仅替换第一个)
|
||
```
|
||
|
||
### 5.3 详情方法
|
||
|
||
#### fetchBookInfo() — 解析书籍详情
|
||
|
||
```
|
||
输入: LegadoSource, detailUrl, {initialTitle, initialAuthor, initialCoverUrl}
|
||
↓
|
||
1. 查缓存: cache.getBookInfo(source.id, absoluteUrl)
|
||
2. _fetchBody(source, absoluteUrl)
|
||
3. RuleParser(body) → 逐一提取:
|
||
→ bookInfoNameRule → parsedTitle
|
||
→ bookInfoAuthorRule → parsedAuthor
|
||
→ bookInfoCoverRule → parsedCover
|
||
→ bookInfoIntroRule → parsedIntro
|
||
→ bookInfoTocRule → parsedToc
|
||
4. 确定 tocUrl:
|
||
- 优先: parsedToc
|
||
- 其次: source.tocUrl
|
||
- 兜底: absoluteUrl (即 detailUrl 本身)
|
||
5. title 兜底: initialTitle → '未命名作品'
|
||
6. 写入 bookInfoCache
|
||
7. 返回 OnlineBookInfo
|
||
```
|
||
|
||
### 5.4 目录方法
|
||
|
||
#### fetchToc() — 解析章节目录
|
||
|
||
```
|
||
输入: LegadoSource, tocUrl
|
||
↓
|
||
1. 查缓存: cache.getToc(source.id, absoluteUrl)
|
||
2. 未命中 → _fetchPaginatedToc(source, absoluteUrl)
|
||
3. 写入 tocCache
|
||
4. 返回 List<OnlineChapter>
|
||
```
|
||
|
||
#### _fetchPaginatedToc() — 分页目录加载
|
||
|
||
```
|
||
输入: LegadoSource, template (含 {{page}} 的 URL)
|
||
↓
|
||
初始化: chapters=[], seenUrls={}, seenPages={}, nextUrl=template, page=1
|
||
循环条件: page <= 20 && nextUrl != null
|
||
1. 替换 {{page}} / {page} → requestedUrl
|
||
2. seenPages 去重 → break
|
||
3. _fetchBody → body
|
||
4. RuleParser(body) → tocListRule → fragments
|
||
5. 遍历 fragments:
|
||
→ tocNameRule → title
|
||
→ tocUrlRule → url
|
||
→ seenUrls 去重
|
||
→ chapters.add(OnlineChapter(title, url, index))
|
||
6. 如果 fragments 为空:
|
||
→ _fallbackChapters(body) // 章节识别器回退
|
||
7. 如果本页新增 0 条 → break
|
||
8. 检查 tocNextPageRule → 有则更新 nextUrl
|
||
否则如果 template 含 {{page}} → 继续 page++
|
||
否则 → nextUrl = null(停止)
|
||
返回 chapters
|
||
```
|
||
|
||
#### _fallbackChapters() — 章节识别器回退
|
||
|
||
当 `tocListRule` 不可用时触发:
|
||
1. 正则匹配 `<a>` 标签
|
||
2. 标题必须匹配章节特征正则:
|
||
```dart
|
||
r'(第\s*[0-9一二三四五六七八九十百千万零〇两]+\s*[章节卷回话]|chapter\s*\d+|episode\s*\d+)'
|
||
```
|
||
3. 按出现顺序排列
|
||
|
||
**与搜索回退的区别**:搜索回退要求标题包含搜索关键词,目录回退要求标题匹配章节正则。后者更精准,避免把导航链接当章节。
|
||
|
||
### 5.5 内容方法
|
||
|
||
#### fetchChapterContent() — 解析章节内容
|
||
|
||
```
|
||
输入: LegadoSource, OnlineChapter
|
||
↓
|
||
1. 查缓存: cache.getChapter(source.id, absoluteUrl)
|
||
2. _fetchBody → body
|
||
3. RuleParser(body) → contentRule → content(主内容)
|
||
4. 如果是漫画:
|
||
→ contentRule 提取 fragments 列表
|
||
→ 合并 fragments 为 contentBody
|
||
5. 如果是小说:
|
||
→ contentBody = content.isEmpty ? body : content
|
||
6. 提取导航:
|
||
→ contentNextRule → nextChapterUrl
|
||
→ contentPrevRule → prevChapterUrl
|
||
7. 构建 OnlineChapterContent:
|
||
- 小说: textContent = _plainTextFromJson(contentBody) || _htmlToText(contentBody)
|
||
- 漫画: imageUrls = _extractImageUrls(contentBody, absoluteUrl)
|
||
- nextChapterUrl / prevChapterUrl
|
||
8. 写入 chapterCache
|
||
9. 返回 OnlineChapterContent
|
||
```
|
||
|
||
#### fetchPlainText() — 旧 API(无规则)
|
||
|
||
```
|
||
输入: LegadoSource, url
|
||
↓
|
||
_fetchBody → body
|
||
_json 文本提取优先 → _plainTextFromJson(body)
|
||
回退 HTML → _htmlToText(body)
|
||
```
|
||
|
||
#### fetchImageUrls() — 旧 API(无规则)
|
||
|
||
```
|
||
输入: LegadoSource, url
|
||
↓
|
||
如果 url 本身是图片 → 直接返回 [url]
|
||
否则 _fetchBody → body
|
||
HTML img 扫描: <img src="...">
|
||
JSON 图片扫描: _imageUrlsFromJson(body)
|
||
合并去重
|
||
```
|
||
|
||
两者都是旧 API,不依赖 `contentRule`,直接从 HTML/JSON 中暴力提取。
|
||
|
||
### 5.6 HTTP 层
|
||
|
||
#### _fetchBody() — 统一 HTTP 请求
|
||
|
||
```
|
||
输入: LegadoSource, url, {method, data}
|
||
↓
|
||
1. 校验 URL(非空、有 scheme)
|
||
2. 构建 headers:
|
||
- Referer: source.url
|
||
- ...source.headers(含 Cookie)
|
||
- User-Agent: source.userAgent ?? 默认 UA
|
||
3. 发起请求:
|
||
- GET: _http.get<List<int>>(url, options: ResponseType.bytes, followRedirects: true, validateStatus: _ => true)
|
||
- POST: _http.post<List<int>>(url, data: data, ...)
|
||
4. 捕获 DioException → _debugDioException() 打日志 → rethrow
|
||
5. 检查 statusCode:
|
||
- 404 → throw 'Source search endpoint is missing or expired.'
|
||
- 403/444 → throw 'Source refused access...'
|
||
- 其他 >= 400 → throw 'HTTP $code from $host.'
|
||
6. 解码响应体: _decodeBody(bytes, declaredCharset: source.charset, contentType: headers['content-type'])
|
||
```
|
||
|
||
**关键设计**:
|
||
- `ResponseType.bytes` — 始终以字节数组接收,避免 Dio 自动用错误编码解码
|
||
- `validateStatus: (_) => true` — 不抛 DioException,自己检查状态码
|
||
- `followRedirects: true` — 自动跟随重定向
|
||
|
||
### 5.7 编解码层
|
||
|
||
#### _encodeKeyword() — URL 关键词编码
|
||
|
||
```
|
||
输入: LegadoSource, keyword
|
||
↓
|
||
确定编码: source.urlEncoding ?? source.charset ?? 'utf-8'
|
||
↓
|
||
utf-8 → Uri.encodeQueryComponent(keyword)
|
||
gbk/gb2312/gb18030 → gbk.encode(keyword) → 手动百分号编码
|
||
其他编码 → _encodingChannel.invokeMethod('encodeQuery') → 平台原生编码
|
||
MissingPluginException → throw
|
||
```
|
||
|
||
#### _decodeBody() — 响应体解码
|
||
|
||
```
|
||
输入: List<int> bytes, declaredCharset, contentType
|
||
↓
|
||
确定 charset: declaredCharset ?? _charsetFromContentType(contentType)
|
||
↓
|
||
latin1/iso-8859-1/windows-1252 → latin1.decode(bytes)
|
||
gbk/gb2312/gb18030 → gbk.decode(bytes) // FormatException → latin1 兜底
|
||
其他/未指定 → utf8.decode(bytes) // FormatException → latin1 兜底
|
||
```
|
||
|
||
#### _charsetFromContentType() — 提取 charset
|
||
|
||
```dart
|
||
// 从 "text/html; charset=gbk" 中提取 "gbk"
|
||
RegExp(r'charset=([^;]+)')
|
||
```
|
||
|
||
### 5.8 错误处理
|
||
|
||
#### _shortError() — 错误消息归一化
|
||
|
||
完整的错误消息映射链(按优先级):
|
||
|
||
```
|
||
1. DioException 类型匹配:
|
||
connectionTimeout/receiveTimeout/sendTimeout
|
||
→ '连接 {host} 超时,请稍后重试。'
|
||
connectionError
|
||
→ '无法连接 {host},请检查网络或更换书源。'
|
||
badResponse + 404
|
||
→ '书源搜索接口已失效(404)。'
|
||
badResponse + 403/444
|
||
→ '{host} 拒绝了访问,可能需要 Cookie 配置。'
|
||
badResponse + 其他
|
||
→ '{host} 返回了异常状态(HTTP {code})。'
|
||
|
||
2. FormatException:
|
||
含 utf/encoding → '响应编码异常,请检查书源的 charset 配置。'
|
||
其他 → '书源规则期望 JSON 格式,但站点返回了其他内容。'
|
||
|
||
3. 原始字符串归一化:
|
||
'[unknown]: null' / 'null' → '目标站点返回了空响应...'
|
||
'[unknown]: none' / 含 'unknown:none' → '连接异常,书源可能已失效。'
|
||
含 'connection refused' → '目标站点拒绝了连接。'
|
||
含 'connection timed out' → '连接超时,请稍后重试。'
|
||
含 'no address associated' → '无法解析目标站点域名,请检查网络。'
|
||
|
||
4. 兜底:
|
||
message > 120 字符 → 截断
|
||
空字符串 → '未知错误'
|
||
```
|
||
|
||
---
|
||
|
||
## 六、规则解析器 RuleParser
|
||
|
||
**文件**:`legado_rule_parser.dart`(262 行)
|
||
|
||
### 6.1 支持的三种解析类型
|
||
|
||
通过 `_resolveKind()` 自动识别:
|
||
|
||
```
|
||
规则前缀:
|
||
"json:" 或 "$." → json 模式
|
||
"regex:" → regex 模式
|
||
其他 → css 模式(默认)
|
||
```
|
||
|
||
### 6.2 CSS 模式
|
||
|
||
#### selectList() — 多元素选择
|
||
|
||
```
|
||
1. 清理选择器(去掉 @attr 后缀)
|
||
2. html_parser.parse(body) → document
|
||
3. document.querySelectorAll(cleanSelector)
|
||
4. 每个元素 → outerHtml
|
||
5. 如果 querySelectorAll 抛异常(畸形选择器)→ 降级到 _legacyCssFragments()
|
||
```
|
||
|
||
#### select() — 单元素选择
|
||
|
||
```
|
||
1. 检查 @attr 后缀(如 "img@src" → 提取 src 属性值)
|
||
2. html_parser.parse(fragment) → document
|
||
3. document.querySelector(cleanSelector)
|
||
4. 有 @attr → element.attributes[attr]
|
||
5. 无 @attr → element.text
|
||
6. 如果 querySelector 抛异常 → 降级到 _legacyCssText()
|
||
```
|
||
|
||
#### _legacyCssFragments() — 正则降级
|
||
|
||
```
|
||
提取选择器开头的 tag 名 → 正则匹配 <tag ...>...</tag> → 返回 outerHtml
|
||
```
|
||
|
||
#### _legacyCssText() — 正则降级
|
||
|
||
```
|
||
提取 tag 名 → 正则匹配 → @attr 提取属性值 / 默认提取 innerText
|
||
```
|
||
|
||
### 6.3 JSON 模式(JSONPath)
|
||
|
||
**支持的语法**:
|
||
```
|
||
$.data → 取 data 字段
|
||
$.data.chapters → 取 data.chapters 字段
|
||
$.data.chapters[*] → 取 chapters 数组全部元素
|
||
$.data.items[0] → 取 items 数组第 1 个元素
|
||
$.data.list[2].name → 取 list[2].name
|
||
["complex-key"] → 支持引号包裹的 key(自动转为 .key)
|
||
```
|
||
|
||
**JsonPath 解析流程**(`_jsonPath()`):
|
||
```
|
||
1. 去掉前缀: json: 或 $.
|
||
2. 按 . 分割 path
|
||
3. 逐段遍历:
|
||
- segment 以 [*] 结尾 → 取数组全量
|
||
- segment 含 [n] → 取数组第 n 个元素
|
||
- 普通 key → _child(node, key)
|
||
4. _child() 递归:
|
||
- key 为空 → 返回 node
|
||
- node is Map → node[key]
|
||
- node is List → node.map(item => _child(item, key))
|
||
```
|
||
|
||
**JSON Body 预处理**(`_jsonBody()`):
|
||
```
|
||
1. 去掉 UTF-8 BOM(0xFEFF)
|
||
2. 检测 JSONP 格式: callback({...})
|
||
→ 正则提取括号内 JSON
|
||
3. jsonDecode
|
||
```
|
||
|
||
### 6.4 Regex 模式
|
||
|
||
**selectList() — Regex 全量匹配**:
|
||
```
|
||
去掉 "regex:" 前缀
|
||
RegExp(rule, dotAll: true).allMatches(body)
|
||
→ 有捕获组: match.group(1)
|
||
→ 无捕获组: match.group(0)
|
||
过滤空值
|
||
```
|
||
|
||
**select() — Regex 首次匹配**:
|
||
```
|
||
去掉 "regex:" 前缀
|
||
RegExp(rule, dotAll: true).firstMatch(fragment)
|
||
→ match.group(1) ?? match.group(0)
|
||
```
|
||
|
||
### 6.5 规则多值支持
|
||
|
||
`_ruleAlternatives()` — 支持 `||` 分隔的多个规则备选:
|
||
```dart
|
||
// "div.title || h1.title || .book-name" → 三个规则依次尝试
|
||
// 第一个有结果的规则立即返回
|
||
```
|
||
|
||
---
|
||
|
||
## 七、书源管理 SourceManager
|
||
|
||
**文件**:`source_manager.dart`(368 行)
|
||
|
||
### 7.1 生命周期
|
||
|
||
```
|
||
构造 → load() → initializeIfFirstRun()
|
||
↓
|
||
SharedPreferences 读取已保存书源
|
||
↓
|
||
_loaded = true → notifyListeners()
|
||
↓
|
||
startAutoUpdateTimer() // 每 6 小时检查订阅更新
|
||
```
|
||
|
||
### 7.2 书源导入
|
||
|
||
#### importFromRepo(SourceRepo) — 从仓库导入
|
||
|
||
```
|
||
1. 如果是订阅源 → _addSubscription(url)
|
||
2. HTTP GET repo.url
|
||
3. importFromJsonText(response.body)
|
||
```
|
||
|
||
#### importFromUrl(String) — 从自定义 URL 导入
|
||
|
||
```
|
||
HTTP GET url → importFromJsonText(response.body)
|
||
```
|
||
|
||
#### importFromJsonText(String) — 解析 JSON 并入库
|
||
|
||
```
|
||
1. _engine.parseSources(body) → List<LegadoSource>
|
||
2. 遍历 imported:
|
||
- _sources.indexWhere(id 匹配) → 更新现有源
|
||
- 否则 → 追加新源
|
||
3. _save() → SharedPreferences
|
||
4. notifyListeners()
|
||
```
|
||
|
||
#### parseSources() — JSON → 书源列表
|
||
|
||
```
|
||
1. 检测 HTML(body 以 <!doctype / <html / < 开头)→ throw FormatException('source-html')
|
||
2. jsonDecode(body)
|
||
3. 如果是 List → 直接用
|
||
4. 如果是 Map → _sourceListFromMap(decoded)
|
||
// 尝试 key: sources / bookSources / data / list / items / results
|
||
5. 每个 Map 条目 → LegadoSource.fromJson()
|
||
6. 过滤 url 为空的源
|
||
```
|
||
|
||
### 7.3 书源查询
|
||
|
||
```dart
|
||
// 全部书源(不可变列表)
|
||
List<LegadoSource> get sources;
|
||
|
||
// 已启用书源
|
||
List<LegadoSource> get enabledSources;
|
||
|
||
// 已启用的小说源(type == 0)
|
||
List<LegadoSource> get enabledNovelSources;
|
||
|
||
// 已启用的漫画源(type == 2)
|
||
List<LegadoSource> get enabledMangaSources;
|
||
|
||
// 按 ID 查找
|
||
LegadoSource? sourceById(String sourceId);
|
||
```
|
||
|
||
### 7.4 书源状态管理
|
||
|
||
```dart
|
||
// 启用/禁用某个书源
|
||
setEnabled(sourceId, enabled) → _save() → notifyListeners()
|
||
|
||
// 健康检查(HTTP GET 搜索 URL,最多检查 10 个源)
|
||
checkEnabledSources() → Future.wait(targets.map(_checkSource)) → List<SourceCheckResult>
|
||
```
|
||
|
||
### 7.5 持久化
|
||
|
||
```dart
|
||
// 存储 key
|
||
_sourcesKey = 'legado_sources_v1'
|
||
_initializedKey = 'source_manager_initialized_v1'
|
||
_subscriptionsKey = 'legado_subscription_urls_v1'
|
||
_lastSubscriptionUpdateKey = 'legado_last_subscription_update_v1'
|
||
|
||
// 书源存储格式
|
||
jsonEncode(_sources.map(source.toJson()).toList())
|
||
// 即完整的 Legado 兼容 JSON 数组,含 ruleSearch/ruleBookInfo/ruleToc/ruleContent
|
||
```
|
||
|
||
---
|
||
|
||
## 八、统一搜索 UnifiedSearch
|
||
|
||
**文件**:`unified_search.dart`(173 行)
|
||
|
||
### 8.1 搜索编排
|
||
|
||
```dart
|
||
Future<List<SearchSection>> search({query, mode}) {
|
||
// 1. 并行发起两个搜索
|
||
cloudFuture = mode==manga ? _searchCloudManga(query) : _searchCloudNovels(query)
|
||
onlineFuture = engine.searchAll(sources, query)
|
||
.then(items => items.map(SearchItem.online))
|
||
|
||
// 2. 等待两个 Future 都完成(Future.wait)
|
||
results = await Future.wait([cloudFuture, onlineFuture])
|
||
|
||
// 3. 组装 SearchSection
|
||
return [
|
||
if (results[0].isNotEmpty) SearchSection(id: 'cloud', title: '我的云库', items: results[0]),
|
||
if (results[1].isNotEmpty) SearchSection(id: 'online', title: '在线源', items: results[1]),
|
||
]
|
||
}
|
||
```
|
||
|
||
### 8.2 云库搜索
|
||
|
||
```dart
|
||
_searchCloudManga(query) → api.gallery(search: query, contentType: 'manga')
|
||
→ rows.map(Artwork.fromJson).map(SearchItem.cloudArtwork)
|
||
|
||
_searchCloudNovels(query) → api.novels(search: query)
|
||
→ rows.map(Novel.fromJson).map(SearchItem.cloudNovel)
|
||
```
|
||
|
||
### 8.3 SearchItem 工厂方法
|
||
|
||
```dart
|
||
SearchItem.cloudArtwork(artwork) → title, sourcePlatform, author, coverUrl, artwork
|
||
SearchItem.cloudNovel(novel) → title, sourcePlatform, author, coverPath, novel
|
||
SearchItem.online(result) → title, sourceName, author, coverUrl, detailUrl, online, errorMessage
|
||
SearchItem.error(sourceName, msg)→ title='搜索失败', sourceName, errorMessage
|
||
```
|
||
|
||
---
|
||
|
||
## 九、页面层源码
|
||
|
||
### 9.1 ExplorePage — 在线搜索页
|
||
|
||
**文件**:`explore_page.dart`(503 行)
|
||
|
||
**状态管理**:
|
||
```dart
|
||
final search = TextEditingController(); // 搜索输入框
|
||
late UnifiedSearchMode mode; // manga / novel
|
||
Future<List<SearchSection>>? future; // 搜索结果 Future
|
||
final savingOnline = <String>{}; // 正在保存的 item key 集合
|
||
```
|
||
|
||
**搜索触发**:
|
||
```dart
|
||
_submit() {
|
||
query = search.text.trim();
|
||
if (query.isEmpty) return;
|
||
setState(() {
|
||
future = ref.read(unifiedSearchProvider).search(query: query, mode: mode);
|
||
});
|
||
}
|
||
```
|
||
|
||
**模式切换**(漫画 ↔ 小说):
|
||
```dart
|
||
SegmentedButton → onSelectionChanged → mode = newMode; future = null;
|
||
```
|
||
|
||
**搜索状态展示**(FutureBuilder 四种状态):
|
||
```
|
||
future == null → 空状态(搜索引导文案)
|
||
ConnectionState.waiting → CircularProgressIndicator
|
||
snapshot.hasError → 错误状态(cloud_off 图标 + 文案)
|
||
sections.isEmpty → 无结果状态(search_off 图标 + 文案)
|
||
有结果 → Column: section 标题 + SearchResultTile 列表
|
||
```
|
||
|
||
**搜索结果点击 — _openItem()**:
|
||
```
|
||
item.artwork != null
|
||
→ ArtworkDetailPage(artwork) // 云库漫画:本地详情页
|
||
|
||
item.novel != null
|
||
→ NovelReaderPage(novel) // 云库小说:本地阅读器
|
||
|
||
item.isError
|
||
→ SnackBar(errorMessage) // 错误提示
|
||
|
||
online != null
|
||
→ source = sourceManager.sourceById(online.sourceId)
|
||
→ source == null → SnackBar('书源已不可用')
|
||
→ OnlineBookDetailPage( // 🆕 在线结果 → 详情页
|
||
source, initialTitle, initialAuthor,
|
||
initialCoverUrl, detailUrl, onSave
|
||
)
|
||
```
|
||
|
||
**保存到书架 — _saveOnlineItem()**:
|
||
```
|
||
1. fetchBookInfo(source, detailUrl) → info
|
||
2. fetchToc(source, info.tocUrl) → chapters
|
||
3. fetchChapterContent(source, chapters.first) → content
|
||
4. 漫画: api.importOnlineManga(...) → 跳转到 ArtworkDetailPage
|
||
5. 小说: api.importOnlineNovel(...) → 跳转到 NovelReaderPage
|
||
6. 异常: SnackBar('保存失败:$error')
|
||
```
|
||
|
||
**UI 组件**:
|
||
- `_SourceSummary` — 已启用书源数量卡片
|
||
- `_SearchResultTile` — 搜索结果条目(封面缩略图 + 标题 + 作者/来源 + 保存按钮)
|
||
- subtitle 三要素:`作者(未知作者兜底) - 来源名称 - 云库/在线`
|
||
- 错误条目:粉色背景 + warning 图标 + errorMessage
|
||
- `_ResultThumb` — 封面缩略图(CachedNetworkImage,160×220,有 fallback 图标)
|
||
- `_ExploreEmptyState` — 空状态占位
|
||
|
||
---
|
||
|
||
### 9.2 OnlineBookDetailPage — 在线书籍详情页
|
||
|
||
**文件**:`online_book_detail_page.dart`(338 行)
|
||
|
||
**接收参数**:
|
||
```dart
|
||
source: LegadoSource // 书源
|
||
detailUrl: String // 书籍详情页 URL
|
||
initialTitle: String // 搜索结果中的书名(兜底)
|
||
initialAuthor: String? // 搜索结果中的作者(兜底)
|
||
initialCoverUrl: String? // 搜索结果中的封面(兜底)
|
||
onSave: Future<void> Function()? // 保存回调
|
||
```
|
||
|
||
**状态管理**:
|
||
```dart
|
||
OnlineBookInfo? info; // BookInfo 解析结果
|
||
List<OnlineChapter> chapters; // 章节列表
|
||
Object? infoError; // BookInfo 加载错误
|
||
Object? tocError; // TOC 加载错误
|
||
bool loadingInfo = true; // BookInfo 加载中
|
||
bool loadingToc = true; // TOC 加载中
|
||
bool descending = false; // 章节排序(正序/倒序)
|
||
bool saving = false; // 保存中
|
||
OnlineReadingRecord? readingRecord; // 阅读记录
|
||
```
|
||
|
||
**加载流程 — _load()**:
|
||
```
|
||
1. detailUrl 为空 → 显示错误
|
||
2. engine.fetchBookInfo(source, detailUrl, ...) → info
|
||
3. setState: loadingInfo=false, loadingToc=true
|
||
4. _loadToc(info.tocUrl)
|
||
5. OnlineReadingHistory.find(sourceId, detailUrl) → readingRecord
|
||
6. 异常 → setState: infoError=error, loadingInfo=false, loadingToc=false
|
||
```
|
||
|
||
**分段加载 — _loadToc(url)**:
|
||
```
|
||
1. setState: tocError=null, loadingToc=true
|
||
2. engine.fetchToc(source, url) → chapters
|
||
3. setState: loadingToc=false
|
||
4. 异常 → setState: tocError=error, loadingToc=false
|
||
```
|
||
|
||
**关键设计**:BookInfo 和 TOC 是两次独立的 HTTP 请求(因为 detailUrl ≠ tocUrl),但 UI 合并在同一页面。BookInfo 先渲染,TOC 区域独立 loading。
|
||
|
||
**章节点击 — _openChapter(index)**:
|
||
```
|
||
source.isManga
|
||
→ OnlineMangaReaderPage(source, title, chapters, currentChapterIndex: index, detailUrl)
|
||
→ push
|
||
→ 回来后重新查阅读记录 → 刷新已读标记
|
||
|
||
source.isNovel
|
||
→ OnlineNovelReaderPage(同上)
|
||
```
|
||
|
||
**页面结构**:
|
||
```
|
||
AppBar: '书籍详情'
|
||
↓
|
||
上半部分(BookInfo 渲染):
|
||
Row:
|
||
封面 (CachedNetworkImage, 104×142)
|
||
Column: 书名(headlineSmall) + 作者 + 来源(灰色) + 章节数(粉色)
|
||
简介 ExpansionTile(可展开/收起)
|
||
操作按钮:
|
||
FilledButton: '从第一章开始阅读' / '继续阅读'(根据 readingRecord)
|
||
OutlinedButton: '保存到书架'(条件显示)
|
||
|
||
下半部分(TOC 渲染):
|
||
Row: '章节目录(共 N 章)' + 正序/倒序切换按钮
|
||
三种状态:
|
||
loading → CircularProgressIndicator
|
||
error → _ErrorState(重试按钮)
|
||
chapters.isEmpty → 空状态文案
|
||
有数据 → ListView of ListTile:
|
||
- leading: menu_book 图标
|
||
- title: 章节名称
|
||
- trailing: 已读 ✓ 或 chevron_right
|
||
- onTap: _openChapter(chapter.index - 1)
|
||
```
|
||
|
||
---
|
||
|
||
### 9.3 OnlineMangaReaderPage — 在线漫画阅读器
|
||
|
||
**文件**:`online_manga_reader_page.dart`(208 行)
|
||
|
||
**接收参数**:
|
||
```dart
|
||
source: LegadoSource
|
||
title: String // 书名
|
||
chapters: List<OnlineChapter> // 完整章节列表
|
||
currentChapterIndex: int // 当前章节序号(0-based)
|
||
detailUrl: String // 书籍详情 URL(用于阅读记录)
|
||
```
|
||
|
||
**状态管理**:
|
||
```dart
|
||
late int chapterIndex = widget.currentChapterIndex;
|
||
late Future<OnlineChapterContent> contentFuture = _load();
|
||
final pageController = PageController();
|
||
int pageIndex = 0; // 当前漫画页(PageView 内)
|
||
```
|
||
|
||
**加载流程 — _load()**:
|
||
```
|
||
1. engine.fetchChapterContent(source, chapter) → content
|
||
2. OnlineReadingHistory.save(OnlineReadingRecord(...))
|
||
3. 预加载下一章:
|
||
next = chapterIndex + 1
|
||
if next < chapters.length:
|
||
engine.fetchChapterContent(source, chapters[next])
|
||
.catchError(...) // 预加载失败静默忽略
|
||
4. return content
|
||
```
|
||
|
||
**章节切换 — _move(delta)**:
|
||
```
|
||
target = chapterIndex + delta
|
||
if target < 0 || target >= chapters.length → return
|
||
setState:
|
||
chapterIndex = target
|
||
pageIndex = 0
|
||
contentFuture = _load()
|
||
pageController.jumpToPage(0)
|
||
```
|
||
|
||
**页面结构**:
|
||
```
|
||
AppBar: '章节标题(3/336)'
|
||
↓
|
||
FutureBuilder<OnlineChapterContent>:
|
||
error → _MangaState('这个章节暂时没有加载成功。', retry)
|
||
loading → CircularProgressIndicator
|
||
data.imageUrls.isEmpty → _MangaState('这一章还没有找到漫画页面...', retry)
|
||
data.imageUrls:
|
||
Stack:
|
||
PageView.builder:
|
||
InteractiveViewer → Image.network(pages[index], headers: source.headers)
|
||
Positioned(右下角): '3/18' 页数指示器
|
||
|
||
bottomNavigationBar:
|
||
[← 上一章] [📋 目录(pop)] [下一章 →]
|
||
- 上一章: chapterIndex > 0 可用
|
||
- 下一章: chapterIndex < chapters.length - 1 可用
|
||
```
|
||
|
||
---
|
||
|
||
### 9.4 OnlineNovelReaderPage — 在线小说阅读器
|
||
|
||
**文件**:`online_novel_reader_page.dart`(195 行)
|
||
|
||
**接收参数**:
|
||
```dart
|
||
source: LegadoSource
|
||
title: String // 书名
|
||
chapters: List<OnlineChapter> // 完整章节列表
|
||
currentChapterIndex: int // 当前章节序号(0-based)
|
||
detailUrl: String // 书籍详情 URL(用于阅读记录)
|
||
```
|
||
|
||
**状态管理**:
|
||
```dart
|
||
late int chapterIndex = widget.currentChapterIndex;
|
||
late Future<OnlineChapterContent> contentFuture = _load();
|
||
double fontSize = 18; // 可调字号(14-26)
|
||
```
|
||
|
||
**加载流程 — _load()**:与漫画阅读器完全相同的逻辑。
|
||
|
||
**页面结构**:
|
||
```
|
||
AppBar: '章节标题(3/336)'
|
||
actions: [缩小字体] [放大字体]
|
||
|
||
body → FutureBuilder:
|
||
error → _ReaderState('章节加载失败', retry)
|
||
loading → CircularProgressIndicator
|
||
data.textContent 为空 → _ReaderState('这一章还是空白', retry)
|
||
data.textContent:
|
||
ListView:
|
||
Text(章节标题, titleLarge)
|
||
Text(正文, fontSize: fontSize, height: 1.75)
|
||
|
||
bottomNavigationBar: 与漫画阅读器完全相同的三按钮导航
|
||
```
|
||
|
||
---
|
||
|
||
## 十、缓存与阅读记录
|
||
|
||
### 10.1 OnlineContentCache — 会话级内存缓存
|
||
|
||
**文件**:`online_cache.dart`(25 行)
|
||
|
||
```dart
|
||
class OnlineContentCache {
|
||
final _bookInfo = <String, OnlineBookInfo>{}; // key: sourceId|url
|
||
final _toc = <String, List<OnlineChapter>>{}; // key: sourceId|tocUrl
|
||
final _chapters = <String, OnlineChapterContent>{}; // key: sourceId|chapterUrl
|
||
|
||
// 缓存 key 规则
|
||
String _key(String sourceId, String url) => '$sourceId|$url';
|
||
|
||
// BookInfo
|
||
getBookInfo(sourceId, url) → _bookInfo[key]
|
||
putBookInfo(sourceId, url, value) → _bookInfo[key] = value
|
||
|
||
// TOC(返回不可变列表)
|
||
getToc(sourceId, url) → _toc[key]
|
||
putToc(sourceId, url, value) → _toc[key] = List.unmodifiable(value)
|
||
|
||
// Chapter
|
||
getChapter(sourceId, url) → _chapters[key]
|
||
putChapter(sourceId, url, value) → _chapters[key] = value
|
||
}
|
||
```
|
||
|
||
**缓存生命周期**:当次 APP 会话(进程存活期间)。APP 杀死后缓存消失。
|
||
|
||
**缓存消费者**:
|
||
- `fetchBookInfo()` → 查/写 `_bookInfo`
|
||
- `fetchToc()` → 查/写 `_toc`
|
||
- `fetchChapterContent()` → 查/写 `_chapters`
|
||
|
||
### 10.2 OnlineReadingHistory — 阅读记录持久化
|
||
|
||
**文件**:`online_reading_history.dart`(57 行)
|
||
|
||
**存储方式**:SharedPreferences,key = `online_reading_history_v1`
|
||
|
||
**数据格式**:JSON 数组,每个元素是 `OnlineReadingRecord.toJson()`
|
||
|
||
```dart
|
||
static Future<void> save(OnlineReadingRecord record) {
|
||
1. 读取现有记录 → all()
|
||
2. 删除同一本书的旧记录(按 sourceId + detailUrl 去重)
|
||
3. 新记录插入到数组头部(最近阅读排在前面)
|
||
4. 超过 50 条 → 截断尾部
|
||
5. 写回 SharedPreferences
|
||
}
|
||
|
||
static Future<OnlineReadingRecord?> find(sourceId, detailUrl) {
|
||
遍历 all() → 匹配 sourceId + detailUrl → 返回第一条
|
||
}
|
||
|
||
static Future<List<OnlineReadingRecord>> all() {
|
||
从 SharedPreferences 读取 → jsonDecode → List.map(OnlineReadingRecord.fromJson)
|
||
}
|
||
```
|
||
|
||
**调用的地方**:
|
||
- 进入章节时:`OnlineReadingHistory.save()`(在 `_load()` 中)
|
||
- 进入详情页时:`OnlineReadingHistory.find()`(显示"继续阅读"还是"从第一章开始")
|
||
- 从阅读器返回时:`OnlineReadingHistory.find()`(刷新章节已读标记)
|
||
|
||
---
|
||
|
||
## 十一、完整调用链路
|
||
|
||
### 11.1 搜索链路
|
||
|
||
```
|
||
用户输入 "海贼王" → 按回车
|
||
↓
|
||
ExplorePage._submit()
|
||
↓
|
||
UnifiedSearch.search(query: "海贼王", mode: manga)
|
||
↓ 并行
|
||
├─ _searchCloudManga("海贼王")
|
||
│ → SakuraApiClient.gallery(search: "海贼王", contentType: 'manga')
|
||
│ → HTTP GET /api/v1/gallery?search=海贼王&content_type=manga
|
||
│ → List<Artwork> → SearchItem.cloudArtwork()
|
||
│
|
||
└─ LegadoEngine.searchAll(enabledMangaSources, "海贼王")
|
||
↓ 分批(每批 10 个)
|
||
├─ search(源1, "海贼王")
|
||
│ ├─ _encodeKeyword(源1, "海贼王") → GBK/UTF-8 编码
|
||
│ ├─ _applySearchTemplate(源1.searchUrl, encoded, page=1)
|
||
│ │ → "https://example.com/search?keyword=%E6%B5%B7%E8%B4%BC%E7%8E%8B"
|
||
│ ├─ _fetchBody(源1, url) → HTTP GET → 字节数组 → _decodeBody → HTML 字符串
|
||
│ ├─ RuleParser(html).selectList(源1.searchListRule)
|
||
│ │ → fragments = ["<div class='item'>...", "<div class='item'>..."]
|
||
│ └─ 遍历 fragments:
|
||
│ ├─ select(fragment, searchNameRule) → "海贼王"
|
||
│ ├─ select(fragment, searchAuthorRule) → "尾田荣一郎"
|
||
│ ├─ select(fragment, searchDetailRule) → "/book/123"
|
||
│ └─ UnifiedSearchResult(title:"海贼王", detailUrl:"https://.../book/123")
|
||
│
|
||
├─ search(源2, "海贼王") → 同上...
|
||
└─ ...
|
||
↓
|
||
Future.wait → List<SearchSection>:
|
||
[SearchSection(id:'cloud', items: [...]),
|
||
SearchSection(id:'online', items: [UnifiedSearchResult...])]
|
||
↓
|
||
ExplorePage FutureBuilder → 渲染结果列表
|
||
```
|
||
|
||
### 11.2 详情链路
|
||
|
||
```
|
||
用户点击搜索结果中的 "海贼王"
|
||
↓
|
||
ExplorePage._openItem(item)
|
||
↓ item.online.detailUrl = "https://example.com/book/123"
|
||
Navigator.push(OnlineBookDetailPage(
|
||
source: 源1,
|
||
detailUrl: "https://example.com/book/123",
|
||
initialTitle: "海贼王",
|
||
initialAuthor: "尾田荣一郎",
|
||
))
|
||
↓
|
||
OnlineBookDetailPage._load()
|
||
↓
|
||
LegadoEngine.fetchBookInfo(源1, "https://example.com/book/123")
|
||
├─ cache.getBookInfo(源1.id, url) → 未命中
|
||
├─ _fetchBody(源1, url) → HTML 字符串
|
||
├─ RuleParser(html) → 提取:
|
||
│ ├─ bookInfoNameRule → "海贼王"
|
||
│ ├─ bookInfoAuthorRule → "尾田荣一郎"
|
||
│ ├─ bookInfoCoverRule → "https://example.com/img/cover.jpg"
|
||
│ ├─ bookInfoIntroRule → "拥有财富、名声、权力..."
|
||
│ └─ bookInfoTocRule → "/book/123/catalog"
|
||
├─ tocUrl = "https://example.com/book/123/catalog"
|
||
├─ cache.putBookInfo(...)
|
||
└─ return OnlineBookInfo(title:"海贼王", tocUrl:"https://.../catalog", ...)
|
||
↓
|
||
setState → loadingInfo=false, info=OnlineBookInfo, loadingToc=true
|
||
↓ 上半部分立即渲染(封面+书名+作者+简介+按钮)
|
||
↓
|
||
_loadToc("https://example.com/book/123/catalog")
|
||
↓
|
||
LegadoEngine.fetchToc(源1, "https://example.com/book/123/catalog")
|
||
├─ cache.getToc(源1.id, url) → 未命中
|
||
├─ _fetchPaginatedToc(源1, url)
|
||
│ ├─ page=1: _fetchBody → HTML
|
||
│ │ RuleParser → tocListRule → fragments
|
||
│ │ 每 fragment: tocNameRule="第1话" + tocUrlRule="/book/123/ch1"
|
||
│ │ → chapters.add(OnlineChapter("第1话", "https://.../ch1", index:1))
|
||
│ │ ...
|
||
│ ├─ tocNextPageRule → 有 → nextUrl = "?page=2"
|
||
│ ├─ page=2: 同上...
|
||
│ └─ tocNextPageRule → 空 → 停止
|
||
├─ cache.putToc(...) → List<OnlineChapter>(共 1130 条)
|
||
└─ return chapters
|
||
↓
|
||
setState → loadingToc=false, chapters=[1130条]
|
||
↓ 下半部分渲染章节列表
|
||
↓
|
||
OnlineReadingHistory.find(源1.id, detailUrl) → readingRecord 或 null
|
||
```
|
||
|
||
### 11.3 阅读链路
|
||
|
||
```
|
||
用户在详情页点击 "第1话"
|
||
↓
|
||
OnlineBookDetailPage._openChapter(0) // index 从 0 开始
|
||
↓
|
||
Navigator.push(OnlineMangaReaderPage(
|
||
source: 源1,
|
||
title: "海贼王",
|
||
chapters: [1130条],
|
||
currentChapterIndex: 0,
|
||
detailUrl: "https://example.com/book/123",
|
||
))
|
||
↓
|
||
OnlineMangaReaderPage._load()
|
||
↓
|
||
chapter = chapters[0] → {title:"第1话", url:"https://.../ch1"}
|
||
↓
|
||
LegadoEngine.fetchChapterContent(源1, chapter)
|
||
├─ cache.getChapter(源1.id, url) → 未命中
|
||
├─ _fetchBody(源1, url) → HTML
|
||
├─ RuleParser(html) → contentRule → "#chapter-content" 的 innerHtml
|
||
├─ _extractImageUrls(contentBody, absoluteUrl)
|
||
│ ├─ RegExp: <img src="..."> / data-src / data-original
|
||
│ └─ JSON 图片扫描
|
||
├─ contentNextRule → "/book/123/ch2" → nextChapterUrl
|
||
├─ contentPrevRule → 空 → prevChapterUrl=null
|
||
├─ cache.putChapter(...)
|
||
└─ return OnlineChapterContent(
|
||
title: "第1话",
|
||
imageUrls: ["https://.../img01.jpg", "https://.../img02.jpg", ...],
|
||
nextChapterUrl: "https://.../ch2",
|
||
)
|
||
↓
|
||
OnlineReadingHistory.save(OnlineReadingRecord(
|
||
sourceId, sourceName, bookTitle, detailUrl,
|
||
chapterUrl, chapterTitle, chapterIndex:0, totalChapters:1130,
|
||
lastReadTime: now,
|
||
))
|
||
↓
|
||
预加载下一章:
|
||
engine.fetchChapterContent(源1, chapters[1])
|
||
.catchError(...) // 后台静默,失败不影响当前阅读
|
||
↓
|
||
渲染 PageView:
|
||
Image.network("https://.../img01.jpg") ← 第1页
|
||
Image.network("https://.../img02.jpg") ← 第2页
|
||
...
|
||
|
||
用户点击 "下一章"
|
||
↓
|
||
_move(1) → chapterIndex = 1
|
||
↓
|
||
setState → contentFuture = _load()
|
||
↓
|
||
engine.fetchChapterContent(源1, chapters[1])
|
||
├─ cache 命中!(已预加载) → 秒切
|
||
└─ _load() 内部再次 save 阅读记录 + 预加载第3章
|
||
```
|
||
|
||
---
|
||
|
||
## 附录:关键设计要点总结
|
||
|
||
### 数据流方向
|
||
|
||
```
|
||
LegadoSource (静态规则,SharedPreferences 持久化)
|
||
↓
|
||
LegadoEngine (规则驱动解析,HTTP + 缓存)
|
||
↓
|
||
OnlineBookInfo / OnlineChapter / OnlineChapterContent (运行时数据,内存缓存)
|
||
↓
|
||
UI Pages (ExplorePage / OnlineBookDetailPage / ReaderPages)
|
||
```
|
||
|
||
### 编码处理链
|
||
|
||
```
|
||
搜索关键词:
|
||
_encodeKeyword(source, keyword)
|
||
→ gbk.encode / Uri.encodeQueryComponent / 平台通道
|
||
|
||
响应体:
|
||
_fetchBody → ResponseType.bytes
|
||
→ _decodeBody(bytes, source.charset, content-type charset)
|
||
→ gbk.decode / utf8.decode / latin1.decode
|
||
```
|
||
|
||
### 缓存策略
|
||
|
||
```
|
||
BookInfo → 进入详情页时缓存,同一书源 + 同一 detailUrl 只请求一次
|
||
TOC → 进入详情页时缓存,同一书源 + 同一 tocUrl 只请求一次
|
||
Chapter → 阅读时缓存当前章 + 预加载下一章
|
||
阅读记录 → SharedPreferences 持久化,跨会话保留
|
||
```
|
||
|
||
### 回退策略优先级
|
||
|
||
```
|
||
规则解析优先:
|
||
1. 用书源声明的 rule 解析(CSS/JSON/Regex)
|
||
2. 规则为空或无结果 → 回退
|
||
- 搜索: _fallbackSearchResults (全 <a> 扫描 + 关键词过滤)
|
||
- 目录: _fallbackChapters (章节正则过滤的 <a> 扫描)
|
||
- 内容: _htmlToText / _extractImageUrls (从 HTML 暴力提取)
|
||
```
|