docs: add i18n support with Chinese as default language

- Configure VitePress locales with zh-CN as root and en-US as /en/
- Translate all documentation to Chinese (31 files)
- Create English documentation under /en/ directory
- Add Chinese UI labels for navigation and pagination
- Language switcher now available in site header

Generated with [Claude Code](https://claude.ai/code)
via [Happy](https://happy.engineering)

Co-Authored-By: Claude <noreply@anthropic.com>
Co-Authored-By: Happy <yesreply@happy.engineering>
This commit is contained in:
Estrella Pan
2026-01-27 07:57:13 +01:00
parent 7e9f3a707a
commit 03bf265651
63 changed files with 4750 additions and 1414 deletions

View File

@@ -1,219 +1,219 @@
# Database Developer Guide
# 数据库开发指南
This guide covers the database architecture, models, and operations in AutoBangumi.
本指南介绍 AutoBangumi 中的数据库架构、模型和操作。
## Overview
## 概述
AutoBangumi uses **SQLite** as its database with **SQLModel** (Pydantic + SQLAlchemy hybrid) for ORM. The database file is located at `data/data.db`.
AutoBangumi 使用 **SQLite** 作为数据库,使用 **SQLModel**(Pydantic + SQLAlchemy 混合)作为 ORM。数据库文件位于 `data/data.db`。
### Architecture
### 架构
```
module/database/
├── engine.py # SQLAlchemy engine configuration
├── combine.py # Database class, migrations, session management
├── bangumi.py # Bangumi (anime subscription) operations
├── rss.py # RSS feed operations
├── torrent.py # Torrent tracking operations
└── user.py # User authentication operations
├── engine.py # SQLAlchemy 引擎配置
├── combine.py # Database 类、迁移、会话管理
├── bangumi.py # 番剧(动画订阅)操作
├── rss.py # RSS 订阅源操作
├── torrent.py # 种子跟踪操作
└── user.py # 用户认证操作
```
## Core Components
## 核心组件
### Database Class
### Database 类
The `Database` class in `combine.py` is the main entry point. It inherits from SQLModel's `Session` and provides access to all sub-databases:
`combine.py` 中的 `Database` 类是主入口点。它继承自 SQLModel 的 `Session`,并提供对所有子数据库的访问:
```python
from module.database import Database
with Database() as db:
# Access sub-databases
# 访问子数据库
bangumis = db.bangumi.search_all()
rss_items = db.rss.search_active()
torrents = db.torrent.search_all()
```
### Sub-Database Classes
### 子数据库类
| Class | Model | Purpose |
| 类 | 模型 | 用途 |
|-------|-------|---------|
| `BangumiDatabase` | `Bangumi` | Anime subscription rules |
| `RSSDatabase` | `RSSItem` | RSS feed sources |
| `TorrentDatabase` | `Torrent` | Downloaded torrent tracking |
| `UserDatabase` | `User` | Authentication |
| `BangumiDatabase` | `Bangumi` | 动画订阅规则 |
| `RSSDatabase` | `RSSItem` | RSS 订阅源 |
| `TorrentDatabase` | `Torrent` | 已下载种子跟踪 |
| `UserDatabase` | `User` | 认证 |
## Models
## 模型
### Bangumi Model
### Bangumi 模型
Core model for anime subscriptions:
动画订阅的核心模型:
```python
class Bangumi(SQLModel, table=True):
id: int # Primary key
official_title: str # Display name (e.g., "Mushoku Tensei")
title_raw: str # Raw title for torrent matching (indexed)
season: int = 1 # Season number
episode_offset: int = 0 # Episode numbering adjustment
season_offset: int = 0 # Season numbering adjustment
rss_link: str # Comma-separated RSS feed URLs
filter: str # Exclusion filter (e.g., "720,\\d+-\\d+")
poster_link: str # TMDB poster URL
save_path: str # Download destination path
rule_name: str # qBittorrent RSS rule name
added: bool = False # Whether rule is added to downloader
deleted: bool = False # Soft delete flag (indexed)
archived: bool = False # For completed series (indexed)
needs_review: bool = False # Offset mismatch detected
needs_review_reason: str # Reason for review
suggested_season_offset: int # Suggested season offset
suggested_episode_offset: int # Suggested episode offset
air_weekday: int # Airing day (0=Sunday, 6=Saturday)
id: int # 主键
official_title: str # 显示名称(如"无职转生")
title_raw: str # 用于种子匹配的原始标题(有索引)
season: int = 1 # 季度编号
episode_offset: int = 0 # 集数编号调整
season_offset: int = 0 # 季度编号调整
rss_link: str # 逗号分隔的 RSS 订阅源 URL
filter: str # 排除过滤器(如 "720,\\d+-\\d+")
poster_link: str # TMDB 海报 URL
save_path: str # 下载目标路径
rule_name: str # qBittorrent RSS 规则名称
added: bool = False # 规则是否已添加到下载器
deleted: bool = False # 软删除标志(有索引)
archived: bool = False # 用于已完结系列(有索引)
needs_review: bool = False # 检测到偏移不匹配
needs_review_reason: str # 需要审核的原因
suggested_season_offset: int # 建议的季度偏移
suggested_episode_offset: int # 建议的集数偏移
air_weekday: int # 放送日(0=周日,6=周六)
```
### RSSItem Model
### RSSItem 模型
RSS feed subscriptions:
RSS 订阅源:
```python
class RSSItem(SQLModel, table=True):
id: int # Primary key
name: str # Display name
url: str # Feed URL (unique, indexed)
aggregate: bool = True # Whether to parse torrents
parser: str = "mikan" # Parser type: mikan, dmhy, nyaa
enabled: bool = True # Active flag
connection_status: str # "healthy" or "error"
last_checked_at: str # ISO timestamp
last_error: str # Last error message
id: int # 主键
name: str # 显示名称
url: str # 订阅源 URL(唯一,有索引)
aggregate: bool = True # 是否解析种子
parser: str = "mikan" # 解析器类型:mikan、dmhy、nyaa
enabled: bool = True # 启用标志
connection_status: str # "healthy" 或 "error"
last_checked_at: str # ISO 时间戳
last_error: str # 最后一次错误消息
```
### Torrent Model
### Torrent 模型
Tracks downloaded torrents:
跟踪已下载的种子:
```python
class Torrent(SQLModel, table=True):
id: int # Primary key
name: str # Torrent name (indexed)
url: str # Torrent/magnet URL (unique, indexed)
rss_id: int # Source RSS feed ID
bangumi_id: int # Linked Bangumi ID (nullable)
qb_hash: str # qBittorrent info hash (indexed)
downloaded: bool = False # Download completed
id: int # 主键
name: str # 种子名称(有索引)
url: str # 种子/磁力链接 URL(唯一,有索引)
rss_id: int # 来源 RSS 订阅源 ID
bangumi_id: int # 关联的番剧 ID(可为空)
qb_hash: str # qBittorrent 信息哈希(有索引)
downloaded: bool = False # 下载完成
```
## Common Operations
## 常用操作
### BangumiDatabase
```python
with Database() as db:
# Create
db.bangumi.add(bangumi) # Single insert
db.bangumi.add_all(bangumi_list) # Batch insert (deduplicates)
# 创建
db.bangumi.add(bangumi) # 单条插入
db.bangumi.add_all(bangumi_list) # 批量插入(去重)
# Read
db.bangumi.search_all() # All records (cached, 5min TTL)
db.bangumi.search_id(123) # By ID
db.bangumi.match_torrent("torrent name") # Find by title_raw match
db.bangumi.not_complete() # Incomplete series
db.bangumi.get_needs_review() # Flagged for review
# 读取
db.bangumi.search_all() # 所有记录(缓存,5分钟 TTL)
db.bangumi.search_id(123) # 按 ID 查询
db.bangumi.match_torrent("torrent name") # 按 title_raw 匹配查找
db.bangumi.not_complete() # 未完结系列
db.bangumi.get_needs_review() # 标记需要审核的
# Update
db.bangumi.update(bangumi) # Update single record
db.bangumi.update_all(bangumi_list) # Batch update
# 更新
db.bangumi.update(bangumi) # 更新单条记录
db.bangumi.update_all(bangumi_list) # 批量更新
# Delete
db.bangumi.delete_one(123) # Hard delete
db.bangumi.disable_rule(123) # Soft delete (deleted=True)
# 删除
db.bangumi.delete_one(123) # 硬删除
db.bangumi.disable_rule(123) # 软删除(deleted=True)
```
### RSSDatabase
```python
with Database() as db:
# Create
db.rss.add(rss_item) # Single insert
db.rss.add_all(rss_items) # Batch insert (deduplicates)
# 创建
db.rss.add(rss_item) # 单条插入
db.rss.add_all(rss_items) # 批量插入(去重)
# Read
db.rss.search_all() # All feeds
db.rss.search_active() # Enabled feeds only
db.rss.search_aggregate() # Enabled + aggregate=True
# 读取
db.rss.search_all() # 所有订阅源
db.rss.search_active() # 仅启用的订阅源
db.rss.search_aggregate() # 启用且 aggregate=True
# Update
db.rss.update(id, rss_update) # Partial update
db.rss.enable(id) # Enable feed
db.rss.disable(id) # Disable feed
db.rss.enable_batch([1, 2, 3]) # Batch enable
db.rss.disable_batch([1, 2, 3]) # Batch disable
# 更新
db.rss.update(id, rss_update) # 部分更新
db.rss.enable(id) # 启用订阅源
db.rss.disable(id) # 禁用订阅源
db.rss.enable_batch([1, 2, 3]) # 批量启用
db.rss.disable_batch([1, 2, 3]) # 批量禁用
```
### TorrentDatabase
```python
with Database() as db:
# Create
db.torrent.add(torrent) # Single insert
db.torrent.add_all(torrents) # Batch insert
# 创建
db.torrent.add(torrent) # 单条插入
db.torrent.add_all(torrents) # 批量插入
# Read
db.torrent.search_all() # All torrents
db.torrent.search_by_qb_hash(hash) # By qBittorrent hash
db.torrent.search_by_url(url) # By URL
db.torrent.check_new(torrents) # Filter out existing
# 读取
db.torrent.search_all() # 所有种子
db.torrent.search_by_qb_hash(hash) # 按 qBittorrent 哈希查询
db.torrent.search_by_url(url) # 按 URL 查询
db.torrent.check_new(torrents) # 过滤掉已存在的
# Update
db.torrent.update_qb_hash(id, hash) # Set qb_hash
# 更新
db.torrent.update_qb_hash(id, hash) # 设置 qb_hash
```
## Caching
## 缓存
### Bangumi Cache
### 番剧缓存
`search_all()` results are cached at the module level with a 5-minute TTL:
`search_all()` 的结果在模块级别缓存,TTL 为 5 分钟:
```python
# Module-level cache in bangumi.py
# bangumi.py 中的模块级缓存
_bangumi_cache: list[Bangumi] | None = None
_bangumi_cache_time: float = 0
_BANGUMI_CACHE_TTL: float = 300.0 # 5 minutes
_BANGUMI_CACHE_TTL: float = 300.0 # 5 分钟
# Cache invalidation
# 缓存失效
def _invalidate_bangumi_cache():
global _bangumi_cache, _bangumi_cache_time
_bangumi_cache = None
_bangumi_cache_time = 0
```
**Important:** The cache is automatically invalidated on:
- `add()`, `add_all()`
- `update()`, `update_all()`
- `delete_one()`, `delete_all()`
- `archive_one()`, `unarchive_one()`
- Any RSS link update operations
**重要:** 缓存在以下操作时自动失效:
- `add()`、`add_all()`
- `update()`、`update_all()`
- `delete_one()`、`delete_all()`
- `archive_one()`、`unarchive_one()`
- 任何 RSS 链接更新操作
### Session Expunge
### 会话分离
Cached objects are **expunged** from the session to prevent `DetachedInstanceError`:
缓存的对象会从会话中**分离**,以防止 `DetachedInstanceError`:
```python
for b in bangumis:
self.session.expunge(b) # Detach from session
self.session.expunge(b) # 从会话中分离
```
## Migration System
## 迁移系统
### Schema Versioning
### Schema 版本控制
Migrations are tracked via a `schema_version` table:
迁移通过 `schema_version` 表跟踪:
```python
CURRENT_SCHEMA_VERSION = 7
# Each migration: (version, description, [SQL statements])
# 每个迁移:(版本号, 描述, [SQL 语句])
MIGRATIONS = [
(1, "add air_weekday column", [...]),
(2, "add connection status columns", [...]),
@@ -225,14 +225,14 @@ MIGRATIONS = [
]
```
### Adding a New Migration
### 添加新迁移
1. Increment `CURRENT_SCHEMA_VERSION` in `combine.py`
2. Add migration tuple to `MIGRATIONS` list:
1. 在 `combine.py` 中增加 `CURRENT_SCHEMA_VERSION`
2. 在 `MIGRATIONS` 列表中添加迁移元组:
```python
MIGRATIONS = [
# ... existing migrations ...
# ... 现有迁移 ...
(
8,
"add my_new_column to bangumi",
@@ -243,7 +243,7 @@ MIGRATIONS = [
]
```
3. Add idempotency check in `run_migrations()`:
3. 在 `run_migrations()` 中添加幂等性检查:
```python
if "bangumi" in tables and version == 8:
@@ -252,28 +252,28 @@ if "bangumi" in tables and version == 8:
needs_run = False
```
4. Update the corresponding Pydantic model in `module/models/`
4. 更新 `module/models/` 中对应的 Pydantic 模型
### Default Value Backfill
### 默认值回填
After migrations, `_fill_null_with_defaults()` automatically fills NULL values based on model defaults:
迁移后,`_fill_null_with_defaults()` 会根据模型默认值自动填充 NULL 值:
```python
# If model defines:
# 如果模型定义为:
class Bangumi(SQLModel, table=True):
my_field: bool = False
# Then existing rows with NULL will be updated to False
# 那么现有记录中的 NULL 值将被更新为 False
```
## Performance Patterns
## 性能模式
### Batch Queries
### 批量查询
`add_all()` uses a single query to check for duplicates instead of N queries:
`add_all()` 使用单个查询检查重复项,而不是 N 个查询:
```python
# Efficient: single SELECT
# 高效:单个 SELECT
keys_to_check = [(d.title_raw, d.group_name) for d in datas]
conditions = [
and_(Bangumi.title_raw == tr, Bangumi.group_name == gn)
@@ -282,40 +282,40 @@ conditions = [
statement = select(Bangumi.title_raw, Bangumi.group_name).where(or_(*conditions))
```
### Regex Matching
### 正则表达式匹配
`match_list()` compiles a single regex pattern for all title matches:
`match_list()` 为所有标题匹配编译单个正则表达式模式:
```python
# Compile once, match many
# 编译一次,匹配多次
sorted_titles = sorted(title_index.keys(), key=len, reverse=True)
pattern = "|".join(re.escape(title) for title in sorted_titles)
title_regex = re.compile(pattern)
# O(1) lookup per torrent instead of O(n)
# 每个种子 O(1) 查找而不是 O(n)
for torrent in torrent_list:
match = title_regex.search(torrent.name)
```
### Indexed Columns
### 索引列
The following columns have indexes for fast lookups:
以下列具有索引以实现快速查找:
| Table | Column | Index Type |
| 表 | 列 | 索引类型 |
|-------|--------|------------|
| `bangumi` | `title_raw` | Regular |
| `bangumi` | `deleted` | Regular |
| `bangumi` | `archived` | Regular |
| `rssitem` | `url` | Unique |
| `torrent` | `name` | Regular |
| `torrent` | `url` | Unique |
| `torrent` | `qb_hash` | Regular |
| `bangumi` | `title_raw` | 普通 |
| `bangumi` | `deleted` | 普通 |
| `bangumi` | `archived` | 普通 |
| `rssitem` | `url` | 唯一 |
| `torrent` | `name` | 普通 |
| `torrent` | `url` | 唯一 |
| `torrent` | `qb_hash` | 普通 |
## Testing
## 测试
### Test Database Setup
### 测试数据库设置
Tests use an in-memory SQLite database:
测试使用内存中的 SQLite 数据库:
```python
# conftest.py
@@ -332,56 +332,56 @@ def db_session(db_engine):
yield session
```
### Factory Functions
### 工厂函数
Use factory functions for creating test data:
使用工厂函数创建测试数据:
```python
from test.factories import make_bangumi, make_torrent, make_rss_item
def test_bangumi_search():
bangumi = make_bangumi(title_raw="Test Title", season=2)
# ... test logic
# ... 测试逻辑
```
## Design Notes
## 设计说明
### No Foreign Keys
### 无外键
SQLite foreign key enforcement is disabled by default. Relationships (like `Torrent.bangumi_id`) are managed in application logic rather than database constraints.
SQLite 外键强制默认是禁用的。关系(如 `Torrent.bangumi_id`)在应用程序逻辑中管理,而不是通过数据库约束。
### Soft Deletes
### 软删除
The `Bangumi.deleted` flag enables soft deletes. Queries should filter by `deleted=False` for user-facing data:
`Bangumi.deleted` 标志启用软删除。面向用户的数据查询应按 `deleted=False` 过滤:
```python
statement = select(Bangumi).where(Bangumi.deleted == false())
```
### Torrent Tagging
### 种子标记
Torrents are tagged in qBittorrent with `ab:{bangumi_id}` for offset lookup during rename operations. This enables fast bangumi identification without database queries.
种子在 qBittorrent 中使用 `ab:{bangumi_id}` 标记,用于重命名操作时的偏移查找。这使得无需数据库查询即可快速识别番剧。
## Common Issues
## 常见问题
### DetachedInstanceError
If you access cached objects from a different session:
如果您从不同的会话访问缓存的对象:
```python
# Wrong: accessing cached object in new session
bangumis = db.bangumi.search_all() # Cached
# 错误:在新会话中访问缓存的对象
bangumis = db.bangumi.search_all() # 已缓存
with Database() as new_db:
new_db.session.add(bangumis[0]) # Error!
new_db.session.add(bangumis[0]) # 错误!
# Right: objects are expunged, work independently
# 正确:对象已分离,可独立工作
bangumis = db.bangumi.search_all()
bangumis[0].title_raw = "New Title" # OK, but won't persist
bangumis[0].title_raw = "New Title" # 可以,但不会持久化
```
### Cache Staleness
### 缓存过期
If manual SQL updates bypass the ORM, invalidate the cache:
如果手动 SQL 更新绕过了 ORM,请使缓存失效:
```python
from module.database.bangumi import _invalidate_bangumi_cache
@@ -390,5 +390,5 @@ with engine.connect() as conn:
conn.execute(text("UPDATE bangumi SET ..."))
conn.commit()
_invalidate_bangumi_cache() # Important!
_invalidate_bangumi_cache() # 重要!
```