Documentation
¶
Overview ¶
Package library indexes a directory tree of books and searches it.
Files on disk are the source of truth. This index is a derived cache: it can be deleted at any time and rebuilt by rescanning, and nothing in it is authoritative except the shelves, which are mirrored to TOML for exactly that reason.
Index ¶
- Variables
- func CompileQuery(query string) (string, []any, error)
- func FoldPath(p string) string
- func HashFile(path string) (string, error)
- func NormalizePath(p string) string
- func NormalizeString(s string) string
- func RenderTemplate(tmpl string, b *Book) (string, error)
- func SameFile(a, b string) bool
- func SanitizeComponent(s string) string
- func SanitizePath(p string) string
- func ValidFATName(s string) (bool, string)
- type Book
- type DB
- func (db *DB) AddToShelf(name string, paths []string) error
- func (db *DB) All() ([]*Book, error)
- func (db *DB) Authors() ([]GroupCount, error)
- func (db *DB) ByID(id int64) (*Book, error)
- func (db *DB) ByPath(path string) (*Book, error)
- func (db *DB) BySHA256(sum string) ([]*Book, error)
- func (db *DB) Close() error
- func (db *DB) Count() (int, error)
- func (db *DB) CreateShelf(s Shelf) error
- func (db *DB) Delete(path string) error
- func (db *DB) DeleteShelf(name string) error
- func (db *DB) Duplicates() ([][]*Book, error)
- func (db *DB) GetShelf(name string) (*Shelf, error)
- func (db *DB) Import(ctx context.Context, root string, sources []string, opts ImportOptions) ([]ImportResult, error)
- func (db *DB) ListShelves() ([]*Shelf, error)
- func (db *DB) LoadShelves(path string) error
- func (db *DB) Path() string
- func (db *DB) RebuildFTS() error
- func (db *DB) RemoveFromShelf(name string, paths []string) error
- func (db *DB) SaveShelves(path string) error
- func (db *DB) Scan(ctx context.Context, root string, opts ScanOptions) (*ScanResult, error)
- func (db *DB) Search(query string, opts SearchOptions) ([]*Book, error)
- func (db *DB) Series() ([]GroupCount, error)
- func (db *DB) ShelfBooks(name string) ([]*Book, error)
- func (db *DB) ShelfNames() ([]string, error)
- func (db *DB) Snapshot() (PathIndex, error)
- func (db *DB) Stats() (Stats, error)
- func (db *DB) Tags() ([]TagCount, error)
- func (db *DB) Upsert(b *Book) error
- type Filter
- type FilterField
- type Format
- type GroupCount
- type ImportMode
- type ImportOptions
- type ImportResult
- type PathIndex
- type PathState
- type ScanAction
- type ScanError
- type ScanOptions
- type ScanProgress
- type ScanResult
- type SearchOptions
- type Shelf
- type ShelfKind
- type Stats
- type TagCount
Constants ¶
This section is empty.
Variables ¶
var ErrNotFound = errors.New("library: book not found")
ErrNotFound is returned when a lookup matches no book.
var ErrShelfNotFound = errors.New("library: shelf not found")
ErrShelfNotFound is returned when a shelf name does not exist.
Functions ¶
func CompileQuery ¶
CompileQuery turns a query string into a SQL condition and its arguments. Exported so the sync planner can resolve a shelf's saved query without duplicating the parser.
func FoldPath ¶
FoldPath returns a case-folded, normalized form for collision detection.
Case matters here on every platform, not just the case-insensitive ones: the device's FAT32 SD card is case-insensitive regardless of the host, so two books that differ only in case will collide on the device even when they coexist happily on a Linux workstation.
func HashFile ¶
HashFile is the exported form, used by the sync engine to hash the bytes it is about to send.
func NormalizePath ¶
NormalizePath canonicalizes a filesystem path for storage in the index.
This exists because of a genuine cross-platform hazard rather than tidiness. APFS returns filenames decomposed (NFD), while Linux filesystems generally hold whatever bytes were written, usually composed (NFC). "Ursula Le Guin" written on Linux and read on macOS produces different byte sequences for the same name, so a library scanned on both machines would accumulate duplicate rows for every book with a non-ASCII character in its path.
Everything stored or compared inside shelf is NFC. The raw OS-native form is used only for the actual syscall, which is why callers open files with the path the walk gave them, not with this one.
func NormalizeString ¶
NormalizeString applies the same normalization to metadata text, so that a title typed one way matches a title stored the other.
func RenderTemplate ¶
RenderTemplate produces a relative, slash-separated path (without extension) for a book.
func SameFile ¶
SameFile reports whether two paths refer to the same entry, accounting for normalization differences between platforms.
func SanitizeComponent ¶
SanitizeComponent makes a single path component safe for a FAT32 volume.
This runs at import rather than at sync time on purpose. A name that has to be rewritten during transfer would change the book's device path, and every path change costs the reader their position in that book.
func SanitizePath ¶
SanitizePath sanitizes every component of a slash-separated relative path.
func ValidFATName ¶
ValidFATName reports whether a component is already safe for FAT32, and why not when it is not. Used by the sync planner to warn before transferring.
Types ¶
type Book ¶
type Book struct {
ID int64
SHA256 string
// DocID is the KOReader partial-MD5 that reading progress is keyed by.
DocID string
Path string // absolute, canonical, NFC-normalized
Size int64
MTimeUnix int64
Format Format
Title string
AuthorSort string
Authors []string
Series string
SeriesIndex float64
Language string
Publisher string
PubDate string
Identifiers map[string]string
AddedUnix int64
Tags []string
Cover []byte
MetaJSON string
}
Book is one indexed file.
func (*Book) DisplayAuthor ¶
DisplayAuthor returns the best available author string.
func (*Book) DisplayTitle ¶
DisplayTitle falls back to the filename for books with no title metadata, since an empty column in a book list is useless.
type DB ¶
type DB struct {
// contains filtered or unexported fields
}
DB is an open library index.
func Open ¶
Open opens the index at path, creating or rebuilding it as needed.
A schema mismatch or a corrupt file is not an error: the index is derived data, so it is discarded and recreated. The caller is expected to rescan.
func (*DB) AddToShelf ¶
AddToShelf adds books to a manual shelf by path.
func (*DB) Authors ¶
func (db *DB) Authors() ([]GroupCount, error)
Authors returns every author_sort in the library with its book count.
Grouped on author_sort rather than the authors list: a book with two authors has one sort key, and browsing wants one row per shelf-neighbour, not one per contributor. Books with no author at all are left out — an "" heading is a dead end to click on.
func (*DB) BySHA256 ¶
BySHA256 returns every book whose content hash matches. More than one result means the library holds duplicate files, which is allowed.
func (*DB) Delete ¶
Delete removes a book from the index by path. Removing a row never touches the file: the index is a cache, and only explicit user commands delete books.
func (*DB) DeleteShelf ¶
DeleteShelf removes a shelf by name.
func (*DB) Duplicates ¶
Duplicates returns groups of books that share a content hash.
The index deliberately allows the same file to exist at several paths, so this reports them rather than the schema forbidding them.
func (*DB) Import ¶
func (db *DB) Import(ctx context.Context, root string, sources []string, opts ImportOptions) ([]ImportResult, error)
Import places files into the library according to the naming template.
This is one of only two operations that may decide a book's path; the other is `shelf organize`. Metadata edits never move files, because a moved book loses its reading position on the device.
func (*DB) ListShelves ¶
ListShelves returns every shelf, sorted by name.
func (*DB) LoadShelves ¶
LoadShelves reads the TOML file and replaces the index's shelf tables with its contents. Call after opening an index that may be stale or freshly built.
func (*DB) RebuildFTS ¶
RebuildFTS regenerates the full-text index from the books table. Used by `shelf scan --deep` and as a repair for an index that predates a schema fix.
func (*DB) RemoveFromShelf ¶
RemoveFromShelf removes books from a manual shelf by path.
func (*DB) SaveShelves ¶
SaveShelves writes every shelf to TOML atomically.
func (*DB) Scan ¶
func (db *DB) Scan(ctx context.Context, root string, opts ScanOptions) (*ScanResult, error)
Scan walks root and brings the index into agreement with what is on disk.
Change detection is by (size, mtime); files whose stat data is unchanged are not opened at all. This is what makes a rescan of a large library cheap.
func (*DB) Search ¶
func (db *DB) Search(query string, opts SearchOptions) ([]*Book, error)
Search returns books matching a query string.
An empty query returns the whole library, which is what `shelf ls` with no arguments should do.
func (*DB) Series ¶
func (db *DB) Series() ([]GroupCount, error)
Series returns every series in the library with its book count.
func (*DB) ShelfBooks ¶
ShelfBooks resolves a shelf to its current book set.
Query shelves are re-evaluated on every call, so a saved search reflects the library as it is now rather than as it was when the shelf was created.
func (*DB) ShelfNames ¶
ShelfNames lists shelf names, sorted.
func (*DB) Snapshot ¶
Snapshot loads the stat-level state of every indexed book. Scanning compares against this in memory rather than issuing a query per file.
type Filter ¶
type Filter struct {
Field FilterField
Value string
}
Filter is an exact-match predicate on one field.
type FilterField ¶
type FilterField string
FilterField names the fields an exact filter can apply to. A closed set, because each one compiles to a hand-written SQL predicate.
const ( FilterAuthor FilterField = "author" FilterSeries FilterField = "series" FilterTag FilterField = "tag" )
type Format ¶
type Format string
Format identifies a book's container format.
func (Format) SyncableToDevice ¶
SyncableToDevice reports whether the firmware can render this format directly. PDF is indexed but must be converted before it reaches a device.
type GroupCount ¶
GroupCount is one value of a browse dimension and how many books share it.
type ImportMode ¶
type ImportMode string
ImportMode selects what happens to the source file.
const ( ImportCopy ImportMode = "copy" ImportMove ImportMode = "move" ImportLink ImportMode = "link" // hard link, falling back to copy )
type ImportOptions ¶
type ImportOptions struct {
Mode ImportMode
Template string
// DryRun computes destinations without touching the filesystem.
DryRun bool
// Overwrite permits replacing an existing destination file.
Overwrite bool
}
ImportOptions controls an import.
type ImportResult ¶
type ImportResult struct {
Source string
Dest string
Action string // imported | would-import | skipped
Err error
}
ImportResult describes what happened to one file.
type PathIndex ¶
PathIndex is the (size, mtime) snapshot a scan compares against to decide which files need rehashing.
type ScanAction ¶
type ScanAction string
ScanAction is what a scan did with one file.
const ( ActionAdded ScanAction = "added" ActionUpdated ScanAction = "updated" ActionUnchanged ScanAction = "unchanged" ActionRemoved ScanAction = "removed" ActionSkipped ScanAction = "skipped" ActionFailed ScanAction = "failed" )
type ScanError ¶
ScanError records a file that could not be indexed. One bad book must not abort a scan of ten thousand.
type ScanOptions ¶
type ScanOptions struct {
// Deep rehashes and re-reads metadata for every file, ignoring the
// (size, mtime) fast path. Use after an external tool has edited books.
Deep bool
// Covers extracts cover thumbnails. Scanning without covers is
// substantially faster on a large library.
Covers bool
// Progress, when set, is called as each file is processed.
Progress func(ScanProgress)
}
ScanOptions controls a library scan.
type ScanProgress ¶
type ScanProgress struct {
Path string
Action ScanAction
Err error
}
ScanProgress reports a single file's outcome during a scan.
type ScanResult ¶
type ScanResult struct {
Added int
Updated int
Unchanged int
Removed int
Skipped int
Errors []ScanError
}
ScanResult summarizes a completed scan.
type SearchOptions ¶
type SearchOptions struct {
Limit int
Offset int
// OrderBy overrides the default author/series/title ordering.
OrderBy string
// Filter narrows to an exact value of one field.
//
// Separate from the query text on purpose. Browsing by author or tag means
// filtering on a value that came out of book metadata, and the query lexer
// ends a quoted string at the first matching quote with no escape — an
// author like O'Brien "Bob" cannot be expressed in query syntax at all.
// Binding the value as a parameter sidesteps the question.
Filter *Filter
}
SearchOptions tunes a search.
type Shelf ¶
type Shelf struct {
ID int64 `toml:"-"`
Name string `toml:"name"`
Kind ShelfKind `toml:"kind"`
Query string `toml:"query,omitempty"`
// Members holds book paths for manual shelves. Paths, not index ids,
// because the index is a cache that can be rebuilt from scratch.
Members []string `toml:"members,omitempty"`
}
Shelf is a named set of books, and the unit that syncs to a device.
type ShelfKind ¶
type ShelfKind string
ShelfKind distinguishes the two ways a shelf decides what it contains.
type Stats ¶
type Stats struct {
Books int `json:"books"`
Authors int `json:"authors"`
Series int `json:"series"`
Tags int `json:"tags"`
Bytes int64 `json:"bytes"`
Formats map[Format]int `json:"formats"`
}
Stats summarises the whole library.
One call rather than five, because the TUI header redraws on every keystroke and a header that costs a round of separate queries per frame is a header that makes scrolling feel slow.