This commit is contained in:
truewhile
2026-10-02 11:05:59 +08:00
parent 42343212c5
commit 5acfa6292a
35 changed files with 4162 additions and 224 deletions
+111
View File
@@ -0,0 +1,111 @@
package reader
import (
"context"
"fmt"
"github.com/truewhile/MeBox/internal/model"
)
// 书架分组(对应 legado BookGroup;存储见 model.ReaderBookGroups)。
//
// 语义与影视模块的媒体库标签一致:整份替换、一本书只归一个组、组内顺序即展示顺序。
// 额外的两条收敛放在服务层,因为它们需要知道书籍是否存在:
// - 只保留该用户书架上的书(书被移出书架后分组里不留死 ID);
// - 一本书只归一个组(越靠前的分组优先)。
// 空分组会保留:用户可能就是先建好分组再往里放书。
// GetBookGroups 读用户的书架分组。没有分组时返回空切片(非 nil),方便前端直接遍历。
func (s *ReaderService) GetBookGroups(ctx context.Context, userID string) ([]model.BookGroupSet, error) {
if userID == "" {
return []model.BookGroupSet{}, nil
}
row, err := s.repo.GetBookGroups(ctx, userID)
if err != nil {
return nil, err
}
groups := model.NormalizeBookGroups(row.DecodeBookGroups())
if len(groups) == 0 {
return []model.BookGroupSet{}, nil
}
owned, err := s.ownedBookIDs(ctx, userID)
if err != nil {
return nil, err
}
return filterBookGroups(groups, owned), nil
}
// SetBookGroups 覆盖保存用户的书架分组,落库前做过收敛与归属过滤。
func (s *ReaderService) SetBookGroups(ctx context.Context, userID string, groups []model.BookGroupSet) ([]model.BookGroupSet, error) {
if userID == "" {
return nil, fmt.Errorf("缺少用户信息")
}
owned, err := s.ownedBookIDs(ctx, userID)
if err != nil {
return nil, err
}
normalized := dedupeBookGroups(filterBookGroups(model.NormalizeBookGroups(groups), owned))
raw, err := model.EncodeBookGroups(normalized)
if err != nil {
return nil, err
}
if err := s.repo.SaveBookGroups(ctx, &model.ReaderBookGroups{UserID: userID, Groups: raw}); err != nil {
return nil, err
}
if len(normalized) == 0 {
return []model.BookGroupSet{}, nil
}
return normalized, nil
}
// ownedBookIDs 返回该用户书架上的书籍 ID 集合。
func (s *ReaderService) ownedBookIDs(ctx context.Context, userID string) (map[string]struct{}, error) {
books, err := s.repo.ListBooks(ctx, userID)
if err != nil {
return nil, err
}
out := make(map[string]struct{}, len(books))
for i := range books {
out[books[i].ID] = struct{}{}
}
return out, nil
}
// filterBookGroups 只保留 owned 里的书籍 ID;空分组原样保留。
func filterBookGroups(groups []model.BookGroupSet, owned map[string]struct{}) []model.BookGroupSet {
if len(groups) == 0 {
return nil
}
out := make([]model.BookGroupSet, 0, len(groups))
for _, group := range groups {
ids := make([]string, 0, len(group.BookIDs))
for _, id := range group.BookIDs {
if _, ok := owned[id]; ok {
ids = append(ids, id)
}
}
out = append(out, model.BookGroupSet{Name: group.Name, BookIDs: ids})
}
return out
}
// dedupeBookGroups 收敛成「一本书只归一个组」:越靠前的分组优先,后面的重复项被移除。
func dedupeBookGroups(groups []model.BookGroupSet) []model.BookGroupSet {
if len(groups) == 0 {
return nil
}
claimed := make(map[string]struct{})
out := make([]model.BookGroupSet, 0, len(groups))
for _, group := range groups {
ids := make([]string, 0, len(group.BookIDs))
for _, id := range group.BookIDs {
if _, ok := claimed[id]; ok {
continue
}
claimed[id] = struct{}{}
ids = append(ids, id)
}
out = append(out, model.BookGroupSet{Name: group.Name, BookIDs: ids})
}
return out
}
+190
View File
@@ -0,0 +1,190 @@
package reader
import (
"context"
"fmt"
"math"
"strings"
"github.com/truewhile/MeBox/internal/model"
)
// 阅读器偏好(每个用户一条,见 model.ReaderProfile)。
//
// 这些值原本只存在浏览器 localStorage,属于设备级;现在按用户落库,让主题、
// 排版、听书、书架展示设置能跨设备一致。服务端只做「存储 + 收敛」,
// 具体语义(哪些主题、怎么排版)仍由前端决定,所以这里只校验取值范围与枚举,
// 不解释它们。
// 取值范围与前端 readerSettings store 里的 clamp 完全一致,两边改动需同步。
const (
readerFontSizeMin, readerFontSizeMax = 14, 32
readerLineHeightMin, readerLineHeightMax = 1.4, 2.6
readerParaSpacingMin, readerParaSpacingMax = 0, 32
readerAudioSpeedMin, readerAudioSpeedMax = 0.5, 3
readerAudioTimerMin, readerAudioTimerMax = 0, 180
readerGridColumnsMin, readerGridColumnsMax = 0, 6
// readerThemeIDDefault 主题标识的自愈值:themeId 不枚举校验(前端可以自由
// 新增主题),只限制长度,空值时回落到内置的「预设1」。
readerThemeIDDefault = "preset1"
readerThemeIDMaxLen = 32
)
// 前端定义的枚举取值;未知值一律回落成默认项,避免脏值把阅读器置于不可用状态。
var (
readerPageModes = []string{"page", "scroll"}
readerShelfLayout = []string{"grid", "list", "compact"}
readerShelfSorts = []string{"recent", "update", "mixed", "name", "author", "manual"}
)
// ReaderSettings 阅读器偏好的读写载荷(与前端 ReaderSettingsProfile 字段一一对应)。
type ReaderSettings struct {
ThemeID string `json:"theme_id"`
Night bool `json:"night"`
PageMode string `json:"page_mode"`
FontSize int `json:"font_size"`
LineHeight float64 `json:"line_height"`
ParagraphSpacing int `json:"paragraph_spacing"`
AudioSpeed float64 `json:"audio_speed"`
AudioTimerMinutes int `json:"audio_timer_minutes"`
ShelfLayout string `json:"shelf_layout"`
ShelfGridColumns int `json:"shelf_grid_columns"`
ShelfSort string `json:"shelf_sort"`
ShelfShowUnread bool `json:"shelf_show_unread"`
ShelfShowUpdateTime bool `json:"shelf_show_update_time"`
}
// GetReaderSettings 读用户阅读器偏好。
// 该用户还没保存过时返回 (nil, nil):由前端用它本地的值播种,避免这里再维护一份默认值。
func (s *ReaderService) GetReaderSettings(ctx context.Context, userID string) (*ReaderSettings, error) {
if userID == "" {
return nil, nil
}
row, err := s.repo.GetReaderProfile(ctx, userID)
if err != nil || row == nil {
return nil, err
}
out := settingsFromProfile(*row)
return &out, nil
}
// SaveReaderSettings 覆盖保存用户阅读器偏好,落库前先做范围收敛。
func (s *ReaderService) SaveReaderSettings(ctx context.Context, userID string, in ReaderSettings) (*ReaderSettings, error) {
if userID == "" {
return nil, fmt.Errorf("缺少用户信息")
}
sanitized := sanitizeReaderSettings(in)
row := &model.ReaderProfile{UserID: userID}
applySettingsToProfile(row, sanitized)
if err := s.repo.SaveReaderProfile(ctx, row); err != nil {
return nil, err
}
out := settingsFromProfile(*row)
return &out, nil
}
// sanitizeReaderSettings 把入参收敛到合法范围:数值夹到区间、枚举未知即回落默认、
// 主题标识去空白并限长。
func sanitizeReaderSettings(in ReaderSettings) ReaderSettings {
return ReaderSettings{
ThemeID: sanitizeThemeID(in.ThemeID),
Night: in.Night,
PageMode: oneOf(in.PageMode, readerPageModes, readerPageModes[0]),
FontSize: clampInt(in.FontSize, readerFontSizeMin, readerFontSizeMax),
LineHeight: roundTo1(clampFloat(in.LineHeight, readerLineHeightMin, readerLineHeightMax)),
ParagraphSpacing: clampInt(in.ParagraphSpacing, readerParaSpacingMin, readerParaSpacingMax),
AudioSpeed: roundTo1(clampFloat(in.AudioSpeed, readerAudioSpeedMin, readerAudioSpeedMax)),
AudioTimerMinutes: clampInt(in.AudioTimerMinutes, readerAudioTimerMin, readerAudioTimerMax),
ShelfLayout: oneOf(in.ShelfLayout, readerShelfLayout, readerShelfLayout[0]),
ShelfGridColumns: clampInt(in.ShelfGridColumns, readerGridColumnsMin, readerGridColumnsMax),
ShelfSort: oneOf(in.ShelfSort, readerShelfSorts, readerShelfSorts[0]),
ShelfShowUnread: in.ShelfShowUnread,
ShelfShowUpdateTime: in.ShelfShowUpdateTime,
}
}
func sanitizeThemeID(v string) string {
v = strings.TrimSpace(v)
if v == "" || len(v) > readerThemeIDMaxLen {
return readerThemeIDDefault
}
return v
}
func settingsFromProfile(p model.ReaderProfile) ReaderSettings {
return ReaderSettings{
ThemeID: p.ThemeID,
Night: p.Night,
PageMode: p.PageMode,
FontSize: p.FontSize,
LineHeight: p.LineHeight,
ParagraphSpacing: p.ParagraphSpacing,
AudioSpeed: p.AudioSpeed,
AudioTimerMinutes: p.AudioTimerMinutes,
ShelfLayout: p.ShelfLayout,
ShelfGridColumns: p.ShelfGridColumns,
ShelfSort: p.ShelfSort,
ShelfShowUnread: p.ShelfShowUnread,
ShelfShowUpdateTime: p.ShelfShowUpdateTime,
}
}
func applySettingsToProfile(p *model.ReaderProfile, in ReaderSettings) {
p.ThemeID = in.ThemeID
p.Night = in.Night
p.PageMode = in.PageMode
p.FontSize = in.FontSize
p.LineHeight = in.LineHeight
p.ParagraphSpacing = in.ParagraphSpacing
p.AudioSpeed = in.AudioSpeed
p.AudioTimerMinutes = in.AudioTimerMinutes
p.ShelfLayout = in.ShelfLayout
p.ShelfGridColumns = in.ShelfGridColumns
p.ShelfSort = in.ShelfSort
p.ShelfShowUnread = in.ShelfShowUnread
p.ShelfShowUpdateTime = in.ShelfShowUpdateTime
}
func clampInt(v, lo, hi int) int {
if v < lo {
return lo
}
if v > hi {
return hi
}
return v
}
func clampFloat(v, lo, hi float64) float64 {
// JSON 不会给出 NaN,这里是防御性的(例如将来接了别的调用方)
if math.IsNaN(v) || v < lo {
return lo
}
if v > hi {
return hi
}
return v
}
func roundTo1(v float64) float64 {
return math.Round(v*10) / 10
}
// oneOf 返回 v(当它属于 allowed 时),否则返回 fallback。
func oneOf(v string, allowed []string, fallback string) string {
for _, a := range allowed {
if v == a {
return v
}
}
return fallback
}
+140 -24
View File
@@ -610,24 +610,24 @@ func srcNameOf(src *model.ReaderBookSource, bs *BookSource) string {
// SearchBook 搜索结果项(对应 legado SearchBook)。
type SearchBook struct {
Name string `json:"name"`
Author string `json:"author"`
Kind string `json:"kind"`
WordCount string `json:"word_count"`
LatestChapter string `json:"latest_chapter"`
Intro string `json:"intro"`
CoverURL string `json:"cover_url"`
BookURL string `json:"book_url"`
Name string `json:"name"`
Author string `json:"author"`
Kind string `json:"kind"`
WordCount string `json:"word_count"`
LatestChapter string `json:"latest_chapter"`
Intro string `json:"intro"`
CoverURL string `json:"cover_url"`
BookURL string `json:"book_url"`
Origins []SearchOrigin `json:"origins"`
}
// SearchOrigin 命中该书目的书源(换源用)。
type SearchOrigin struct {
SourceID string `json:"source_id"`
Origin string `json:"origin"`
OriginName string `json:"origin_name"`
OriginType int `json:"origin_type"`
BookURL string `json:"book_url"`
SourceID string `json:"source_id"`
Origin string `json:"origin"`
OriginName string `json:"origin_name"`
OriginType int `json:"origin_type"`
BookURL string `json:"book_url"`
LatestChapter string `json:"latest_chapter"`
}
@@ -975,10 +975,10 @@ func (s *ReaderService) getBookInfoFrom(ctx context.Context, src *model.ReaderBo
// TocChapter 目录章节项。
type TocChapter struct {
Index int `json:"index"`
Title string `json:"title"`
URL string `json:"url"`
IsVolume bool `json:"is_volume"`
Index int `json:"index"`
Title string `json:"title"`
URL string `json:"url"`
IsVolume bool `json:"is_volume"`
UpdateTime string `json:"update_time"`
}
@@ -1016,22 +1016,53 @@ func (s *ReaderService) GetToc(ctx context.Context, userID, sourceID, sourceURL,
}
// 对应 legado:书源给 book.type 赋值后 legado 会持久化到 Book.type。
// 书架的「开始阅读」与详情页都会在这里拉目录,此时书籍已在书架时即可写回。
s.applyDeclaredBookType(ctx, userID, src.SourceURL, bookURL, declared)
// 顺便把末章标题与「最近更新」时间写回,供书架显示与排序。
s.applyTocMeta(ctx, userID, src.SourceURL, bookURL, declared, chapters)
return chapters, nil
}
// applyDeclaredBookType 把书源声明的书籍类型写回书架记录。
func (s *ReaderService) applyDeclaredBookType(ctx context.Context, userID, origin, bookURL string, declared int) {
if declared < 0 || userID == "" || origin == "" || bookURL == "" {
// latestChapterTitleOf 取目录里最后一个非卷章节的标题(对应 legado 的「最新章节」)。
// 目录为空或全是卷名时返回空串。
func latestChapterTitleOf(chapters []TocChapter) string {
for i := len(chapters) - 1; i >= 0; i-- {
if !chapters[i].IsVolume {
return strings.TrimSpace(chapters[i].Title)
}
}
return ""
}
// applyTocMeta 把目录阶段得到的信息写回书架记录:
// - 书源在规则 JS 里声明的书籍类型(declared >= 0 时);
// - 末章标题,以及末章变化时刷新的「最近更新」时间(对应 legado Book.latestChapterTime)。
//
// 书籍不在书架(搜索/详情预览)时直接跳过。首次记录末章标题不算「更新」,
// 只有原本已有标题、且新标题不同,才认为书源这边出现了新章节。
func (s *ReaderService) applyTocMeta(ctx context.Context, userID, origin, bookURL string, declared int, chapters []TocChapter) {
if userID == "" || origin == "" || bookURL == "" {
return
}
book, err := s.repo.FindBookByURL(ctx, userID, origin, bookURL)
if err != nil || book == nil || book.Type == declared {
if err != nil || book == nil {
return
}
dirty := false
if declared >= 0 && book.Type != declared {
book.Type = declared
dirty = true
}
if latest := latestChapterTitleOf(chapters); latest != "" && latest != book.LatestChapterTitle {
if book.LatestChapterTitle != "" {
book.LatestChapterTime = time.Now().UnixMilli()
}
book.LatestChapterTitle = latest
dirty = true
}
if !dirty {
return
}
book.Type = declared
if err := s.repo.UpdateBook(ctx, book); err != nil && s.log != nil {
s.log.Warn("reader: 写回书籍类型失败", zap.String("book", book.ID), zap.Error(err))
s.log.Warn("reader: 写回目录信息失败", zap.String("book", book.ID), zap.Error(err))
}
}
@@ -1568,6 +1599,91 @@ func (s *ReaderService) WarmUpBookChapters(ctx context.Context, userID string, b
}
}
// TocRefreshResult 「更新目录」的结果汇总(对应 legado 更新目录后的提示)。
type TocRefreshResult struct {
Total int `json:"total"` // 参与刷新的网络书籍数
Updated int `json:"updated"` // 章数变多的书(有新章节)
Failed int `json:"failed"` // 抓取或写入失败的书
}
// refreshTocConcurrency 「更新目录」的并发度。书源站点多有限流,不宜过大。
const refreshTocConcurrency = 4
// RefreshBooksToc 刷新用户书架里全部网络书籍的目录(对应 legado 的「更新目录」菜单)。
//
// 逐本重新抓目录、覆盖章节缓存;末章变化时由 GetToc → applyTocMeta 刷新
// latest_chapter_time。本地书籍与没有书源信息的书籍跳过。
// 并发受限,单本失败只计数、不中断整体;等待全部结束后返回汇总。
func (s *ReaderService) RefreshBooksToc(ctx context.Context, userID string) (*TocRefreshResult, error) {
books, err := s.repo.ListBooks(ctx, userID)
if err != nil {
return nil, err
}
res := &TocRefreshResult{}
targets := make([]model.ReaderBook, 0, len(books))
for i := range books {
b := books[i]
if b.LocalPath != "" || b.BookURL == "" || b.Origin == "" {
continue
}
targets = append(targets, b)
}
res.Total = len(targets)
if res.Total == 0 {
return res, nil
}
var mu sync.Mutex
var wg sync.WaitGroup
sem := make(chan struct{}, refreshTocConcurrency)
for i := range targets {
b := targets[i]
wg.Add(1)
sem <- struct{}{}
go func(b model.ReaderBook) {
defer wg.Done()
defer func() { <-sem }()
bookCtx, cancel := context.WithTimeout(ctx, perSourceTimeout)
defer cancel()
if s.refreshBookToc(bookCtx, userID, b) {
mu.Lock()
res.Updated++
mu.Unlock()
return
}
mu.Lock()
res.Failed++
mu.Unlock()
}(b)
}
wg.Wait()
return res, nil
}
// refreshBookToc 刷新单本书的目录,返回是否检测到新章节。
func (s *ReaderService) refreshBookToc(ctx context.Context, userID string, book model.ReaderBook) bool {
before, _ := s.repo.CountChaptersByBook(ctx, []string{book.ID})
chapters, err := s.GetToc(ctx, userID, "", book.Origin, book.BookURL, book.TocURL)
if err != nil || len(chapters) == 0 {
if err != nil && s.log != nil {
s.log.Debug("reader: 更新目录失败", zap.String("book", book.ID), zap.Error(err))
}
return false
}
inputs := make([]ChapterInput, 0, len(chapters))
for _, ch := range chapters {
inputs = append(inputs, ChapterInput{Index: ch.Index, Title: ch.Title, URL: ch.URL, IsVolume: ch.IsVolume})
}
if err := s.SaveChapters(ctx, book.ID, inputs); err != nil {
if s.log != nil {
s.log.Warn("reader: 更新目录写入失败", zap.String("book", book.ID), zap.Error(err))
}
return false
}
beforeCount := before[book.ID]
return beforeCount > 0 && len(chapters) > beforeCount
}
// ListReplaceRules 用户替换规则列表。
func (s *ReaderService) ListReplaceRules(ctx context.Context, userID string) ([]model.ReaderReplaceRule, error) {
return s.repo.ListReplaceRules(ctx, userID)