metasource

package
v0.0.16 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 24, 2026 License: MIT Imports: 23 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package metasource looks up authoritative metadata for a book in public catalogues, ranks and merges what they return, and plans which fields to write into the file. It has no CLI dependencies and talks to a fixed set of hosts with a client that carries no credentials.

Index

Constants

View Source
const (
	// DefaultMaxResults is how many candidates a lookup returns unless told
	// otherwise.
	DefaultMaxResults = 10
	// MaxResultsCeiling is the most a lookup may be asked to return. A source
	// answers at most this many hits per request.
	MaxResultsCeiling = 50
)
View Source
const (
	NameOpenLibrary = "openlibrary"
	NameGoogle      = "google"
	NameGoodreads   = "goodreads"
	NameDouban      = "douban"
	NameWeRead      = "weread"
)

Names of the built-in sources, as written in a source list.

View Source
const (
	// NoteCheckEdition marks a field that differs between editions, taken
	// from a match found by title alone: it may describe another edition.
	NoteCheckEdition = "check edition"
	// NoteOtherBook marks every row of a match whose ISBN agrees but whose
	// title does not: it is probably another book.
	NoteOtherBook = "may be another book"
)

Notes on rows taken from a match that is not certain.

View Source
const NoteEdited = "edited"

NoteEdited marks a row whose new value the user typed in place of the catalogue's.

View Source
const SchemeZlibID = "zlib-id"

SchemeZlibID is the identifier a download writes for the Z-Library record a file came from, as id:hash, so it can be traced back to that record.

View Source
const (
	// SchemeZlibISBN holds an ISBN taken from the Z-Library record of a
	// download that nothing has confirmed. A lookup searches it, and the
	// matcher still checks the title, but it is never read as the book's own
	// ISBN: a wrong value here must not turn into an "exact" match later.
	SchemeZlibISBN = "zlib-isbn"
)

Variables

View Source
var (
	// ErrRateLimited means a source refused the request for quota reasons.
	ErrRateLimited = errors.New("rate limited")
	// ErrNoQuery means the query has nothing to search with.
	ErrNoQuery = errors.New("nothing to look up: no title, author or ISBN")
	// ErrAllSourcesFailed means every source failed and none found anything.
	ErrAllSourcesFailed = errors.New("every metadata source failed")
	// ErrKeyRejected means a source refused the configured API key.
	ErrKeyRejected = errors.New("the API key was rejected (invalid, restricted, or the Books API is not enabled for it)")
	// ErrKeyMalformed means the configured API key cannot be a key at all, so
	// it was not sent.
	ErrKeyMalformed = errors.New("the configured API key is malformed")
)
View Source
var (
	// ErrWeReadNoKey means the weread source is enabled but has no API key.
	ErrWeReadNoKey = errors.New("no API key (set ZLIB_WEREAD_API_KEY)")
	// ErrWeReadKeyMalformed means the configured key cannot be a WeRead key,
	// so it was not sent.
	ErrWeReadKeyMalformed = errors.New("the WeRead API key is malformed")
	// ErrWeReadKeyRejected means the gateway refused the key.
	ErrWeReadKeyRejected = errors.New("the WeRead API key was rejected")
	// ErrWeReadUpgrade means the gateway asked clients to upgrade. Its message
	// is written for an agent and is never shown or followed.
	ErrWeReadUpgrade = errors.New("the WeRead gateway reports a newer client version than this zlib supports; update zlib")
)
View Source
var DefaultSourceNames = []string{NameOpenLibrary}

DefaultSourceNames are the sources used for a book that is not Chinese when none are chosen and no Google Books key is set. See DefaultSourceNamesFor.

EditableFields are the fields the metadata editor shows, in its order: what a reader looks at first, then the edition, then the long text and the cover.

View Source
var ErrNotEditable = errors.New("this field cannot be edited here")

ErrNotEditable means a change has no value that can be edited by hand.

KnownSourceNames lists the built-in sources in the order they are offered.

NameLayouts lists the presets in the order they are offered.

Functions

func BuildChanges

func BuildChanges(plan []Change, selected func(Change) bool) *ebookmeta.Changes

BuildChanges returns the ebookmeta changes for the selected entries of plan. It returns nil when nothing is selected. A cover change is left out: its image has to be downloaded first, so the caller fetches it from Change.CoverURL and sets Changes.Cover.

func ChineseBook

func ChineseBook(languages []string, title string, authors []string) bool

ChineseBook reports whether a book is Chinese: its language is Chinese, or its title or first author is written in Han characters (a Chinese book is often tagged with the wrong language). Kana and hangul rule a title out, so a Japanese or Korean book is not Chinese.

func Clearable

func Clearable(f Field) bool

Clearable reports whether f can be emptied in the editor. A book always keeps a title, and a cover can only be replaced.

func DefaultSourceNamesFor

func DefaultSourceNamesFor(chinese, googleKey bool) []string

DefaultSourceNamesFor returns the sources used when none are chosen, by the language of the book: Douban for a Chinese book, which it covers best, and Open Library for any other, with Google Books added when a Google Books API key is set (without one Google answers from a shared quota that often refuses). WeRead is never a default: it sends the title to Tencent under the user's own API key, so it is enabled on purpose.

func ExplicitSourceNames

func ExplicitSourceNames(list string) []string

ExplicitSourceNames splits a comma-separated source list such as "douban,openlibrary" into its names, or returns nil when it names none.

func FetchCover

func FetchCover(ctx context.Context, rt http.RoundTripper, rawURL string) (*ebookmeta.Cover, error)

FetchCover downloads the cover image at rawURL through rt (nil for the default transport). The URL must be https on a known cover host, every redirect is held to the same rule, and the result must be a JPEG, PNG, GIF or WebP image of a sensible size.

func FileNameFor

func FileNameFor(title string, authors []string, ext string) string

FileNameFor builds the name an e-book file is given from its title and authors: "Title - Authors.ext" (see NameLayout for the other orders), or "Title.ext" when no author is known. It returns "" when there is no title, because a name of authors alone says nothing about the book.

The name is plain text any system takes: no path separators, no characters Windows rejects, no control or bidi marks (the text may come from a server), no leading or trailing dot, no reserved Windows device name, and at most 255 bytes, cut on a character boundary in the title. At most three authors are named, and "Last, First" for an author is written "First Last", as a comma would split it into two people. A subtitle is written after two spaces and not a colon, which Windows rejects; GuessFromFileName reads it back as a colon, so the name finds the same book again.

func FileNameWith

func FileNameWith(layout NameLayout, title string, authors []string, ext string) string

FileNameWith is FileNameFor in the given layout. The title is cut to what is left of the length limit after the authors, whatever the layout.

func FileValue

func FileValue(cur *ebookmeta.Metadata, f Field) string

FileValue is what cur holds for f, written the way the editor shows and edits it: authors joined with " & ", lists with ", ", a series as "Name #2". The cover is its media type. It is "" when the field is empty.

func ISBNsFromSnippets

func ISBNsFromSnippets(snippets []string) []string

ISBNsFromSnippets reads ISBNs from the text that follows an "ISBN" label in a book, as ebookmeta.ISBNSnippets returns it. Each snippet yields at most one ISBN, kept only when its check digit is right, so a price or a phone number next to the label is not mistaken for one. The result is unique and in order of appearance.

func MatchValue

func MatchValue(c Candidate, f Field) string

MatchValue is what c says about f, in the same form as FileValue, or "". The cover is the catalogue's address for it.

func NormalizeISBN

func NormalizeISBN(s string) string

NormalizeISBN returns s as a valid ISBN-13, or "" when it is not an ISBN. Hyphens and spaces are ignored and a valid ISBN-10 is converted, so the same book always yields the same key whichever form a source uses.

func NormalizeSourceList

func NormalizeSourceList(list string) (string, error)

NormalizeSourceList checks a comma-separated source list and returns it in the canonical order, without duplicates. An unknown name is an error, so a list that is saved cannot hold a typo. An empty list stays empty.

func ParseMaxResults

func ParseMaxResults(s string) (int, error)

ParseMaxResults reads a result limit: a whole number from 1 to MaxResultsCeiling. An empty string is DefaultMaxResults.

func ParseSourceNames

func ParseSourceNames(list string) []string

ParseSourceNames is ExplicitSourceNames, except that a list naming none selects DefaultSourceNames.

func PlainText

func PlainText(s string) string

PlainText is the HTML a description often holds (an EPUB's dc:description may carry escaped XHTML) as plain text, for display only: what is written back is always the value as it was.

func PlanDownloadISBN

func PlanDownloadISBN(cur *ebookmeta.Metadata, recordTitle string, isbns ...string) (string, *ebookmeta.Changes)

PlanDownloadISBN decides how to record the ISBN of a Z-Library record in the file it was downloaded as. isbns are tried in order and the first valid one is used. It returns the identifier scheme written and the change, or "" and nil when there is nothing to write:

  • the record has no valid ISBN;
  • the file already has an ISBN: it is never replaced here, and the record is not allowed to contradict it quietly;
  • the file already carries this ISBN under SchemeZlibISBN.

The scheme is "isbn" only when the file has a title, the record's title agrees with it, and the record names one edition: an identifier can list the ISBNs of several editions, and a title cannot say which one the file is. Otherwise it is SchemeZlibISBN.

func SanitizeFileName

func SanitizeFileName(stem, ext string) string

SanitizeFileName makes a name someone typed safe: the same rules as FileNameFor for characters, length and reserved names, but a spaced dash stays as written. The extension is added, or replaced when the name has it already. It returns "" when nothing is left of the name.

func TrustedCoverURL

func TrustedCoverURL(rawURL string) bool

TrustedCoverURL reports whether FetchCover would accept rawURL: https on a known cover host. It downloads nothing.

func UsefulTitle

func UsefulTitle(t string) bool

UsefulTitle reports whether a title read from a file is worth searching: it is not empty, a placeholder such as "Unknown" or "未知", a word processor's default, a UUID, a number or a file name. The list is narrow on purpose, and a title is only judged whole, so "The Unknown Soldier" is useful.

func ValidAPIKey

func ValidAPIKey(s string) bool

ValidAPIKey reports whether s can be a Google API key.

func ValidWeReadKey

func ValidWeReadKey(s string) bool

ValidWeReadKey reports whether s can be a WeRead API key.

func WritableIdentifier

func WritableIdentifier(scheme string) bool

WritableIdentifier reports whether a lookup, or an agent acting on one, may write an identifier of this scheme. A uuid names one file and never can.

Types

type Candidate

type Candidate struct {
	// Sources names every source that contributed, in lookup order.
	Sources     []string               `json:"sources"`
	Title       string                 `json:"title"`
	Authors     []string               `json:"authors,omitempty"`
	Publisher   string                 `json:"publisher,omitempty"`
	Languages   []string               `json:"languages,omitempty"` // BCP 47
	Tags        []string               `json:"tags,omitempty"`
	Published   string                 `json:"published,omitempty"` // YYYY, YYYY-MM or YYYY-MM-DD
	Description string                 `json:"description,omitempty"`
	Identifiers []ebookmeta.Identifier `json:"identifiers,omitempty"`
	CoverURL    string                 `json:"cover_url,omitempty"`
	// Series is the series the book belongs to, and SeriesIndex its position
	// in it; 0 means the position is not known. A series belongs to the work,
	// so unlike a publisher or a date it does not depend on the edition.
	Series      string  `json:"series,omitempty"`
	SeriesIndex float64 `json:"series_index,omitempty"`

	// EditionLevel is true when the source described one specific edition,
	// so its ISBN belongs to this book. Work-level results (a title search
	// on Open Library) say nothing about which edition a file is.
	EditionLevel bool `json:"edition_level"`

	// Match says how the candidate relates to the query; Score is 0 to 1.
	Match Match   `json:"match"`
	Score float64 `json:"score"`
	// contains filtered or unexported fields
}

Candidate is one book as a source describes it, or the merge of several.

func (*Candidate) ISBN

func (c *Candidate) ISBN() string

ISBN returns the candidate's ISBN-13, or "".

func (*Candidate) SeriesLabel

func (c *Candidate) SeriesLabel() string

SeriesLabel is the series and its position written "Name #2", or "".

type Change

type Change struct {
	Field Field
	// Old and New are display text; Old is "" when the field is empty.
	Old, New string
	// Fill is true when the file has no value yet. Replacing what a file
	// already says always needs an explicit decision.
	Fill bool
	// Note warns about the row when the match is not certain: NoteCheckEdition
	// or NoteOtherBook. It is "" for a confirmed match.
	Note string
	// contains filtered or unexported fields
}

Change is one proposed edit to a file's metadata.

func ChangeFromCover

func ChangeFromCover(old, label string, cover *ebookmeta.Cover) Change

ChangeFromCover is a change that writes cover, chosen by the user: an image file they named, or the bytes of a catalogue's cover already downloaded for the preview. label says what it is, for the editor's row.

func Clear

func Clear(f Field, old string) (Change, error)

Clear returns a change that empties f in a file that holds old. Clearing is an explicit decision, so the change starts selected.

func Plan

func Plan(cur *ebookmeta.Metadata, cand Candidate) []Change

Plan lists what cand would change in cur. Fields the candidate lacks, and fields that already agree, are left out. The file's own unique identifier and cover are never part of a plan.

func (Change) CoverURL

func (c Change) CoverURL() string

CoverURL is where a FieldCover change gets its image, or "".

func (Change) DefaultSelected

func (c Change) DefaultSelected() bool

DefaultSelected reports whether the change is applied unless the user opts out. Only fills are, and only when the match is sure of the book (and, for edition-specific fields, of the edition): a title-only match leaves publisher, date, language and identifiers unselected, and a match whose ISBN agrees but is not confirmed (its title differs, or nothing independent vouches for a hint) selects nothing.

func (Change) Edit

func (c Change) Edit(text string) (Change, error)

Edit returns c with its new value replaced by text, read the way the field is written: authors separated by "&", languages and tags by commas, a date as a year, month or day, and an ISBN as one valid ISBN. Typed text is cleaned of control characters, and a value that does not read as the field's kind is refused with a message that says what is expected.

Choosing a value by hand is an explicit decision, so the edited row starts selected and is marked NoteEdited. c itself is left as it was, so a failed or repeated edit starts from what the catalogue said.

func (Change) Editable

func (c Change) Editable() bool

Editable reports whether the change's value can be typed: every field the metadata editor shows except the cover (an image, chosen by path) and the catalogue identifiers other than the ISBN.

func (Change) Edited

func (c Change) Edited() bool

Edited reports whether the new value was typed by the user.

type Douban

type Douban struct {
	// contains filtered or unexported fields
}

Douban looks books up on Douban Books, the catalogue that covers Chinese editions best. It is the default for a Chinese book (DefaultSourceNamesFor) and is asked about no other unless chosen.

An ISBN is resolved through the book.douban.com/isbn/<isbn>/ redirect, which reads the subject ID from the Location header and downloads no page. A title is searched through the m.douban.com mobile search, and the best matches are read from the mobile detail API. Both mobile endpoints refuse requests without a Referer on m.douban.com, so one is sent: it is the only browser-like header, and there are no cookies, no login and no challenge solving. When Douban refuses a request the source reports an error and the lookup carries on with the other sources.

A Douban subject is one edition, so its candidates are edition level.

func NewDouban

func NewDouban(rt http.RoundTripper) *Douban

NewDouban returns the source for rt (nil for the default transport).

func (*Douban) Identify

func (s *Douban) Identify(ctx context.Context, q Query) ([]Candidate, error)

func (*Douban) Name

func (*Douban) Name() string

type Embedded

type Embedded struct {
	Title     string
	Authors   []string
	ISBNs     []string // the file's own, valid
	Publisher string
	Year      string
	Language  string
}

Embedded is the useful part of what a file carries: its own title, authors and ISBNs, and what it says about its edition. Placeholders such as "Unknown" are left out.

func EmbeddedOf

func EmbeddedOf(m *ebookmeta.Metadata) Embedded

EmbeddedOf is what is useful in a file's own metadata: a title that is not a placeholder, and its authors, cleaned and split.

type Extraction

type Extraction struct {
	FileName FileGuess
	Embedded Embedded
	Query    Query
	// TitleFrom and AuthorsFrom are "file name", "embedded" or "download
	// record", or "" when there is none.
	TitleFrom, AuthorsFrom string
	// AltTitle is the other title, when the name and the file offer two that
	// differ: the one the query did not use.
	AltTitle string
	// ISBNFrom says where each of Query.ISBNs came from, in the same order:
	// "embedded", "recorded by a download", "copyright page", "download
	// record" or "file name".
	ISBNFrom []string
	// ZlibID is the Z-Library record (id:hash) a download wrote into the file,
	// or "".
	ZlibID string
}

Extraction is what is known about a book before it is searched, read from its file name first and then from what the file carries, and the query made of it. Each part of the query says where it came from.

func Extract

func Extract(fileName string, m *ebookmeta.Metadata, scanned []string, hint Hint) Extraction

Extract builds the query for a book. The file name is read first: a Z-Library name is cleaner than the title inside the file, which often carries a marketing line or a series name. What the file itself says then fills what the name lacks and supplies the ISBN, the publisher and the year. scanned are ISBNs read from the book's text, and hint is the download's record.

Only the file's own ISBN is confirmed. Every other ISBN is a hint, and a title from the name or the record never confirms one (Query.TitleGuessed), unless the file's own title agrees with it.

func (Extraction) UseOtherTitle

func (x Extraction) UseOtherTitle() Extraction

UseOtherTitle returns x with the query using AltTitle, the title it did not pick: the file name's for the file's own, or the reverse. The other title takes its place as AltTitle, so switching twice returns where it started. Whether the title counts as a guess follows the new title: the file's own is never a guess, and the name's is one unless the file's title agrees.

type Field

type Field string

Field names a proposed change. Identifier changes are "identifier:<scheme>".

const (
	// FieldSeries is a book's series and its position in it, written "Name #2".
	FieldSeries Field = "series"
	// FieldTitleSort and FieldAuthorSort are the forms a library sorts by, such
	// as "Dune Messiah" and "Herbert, Frank".
	FieldTitleSort  Field = "title_sort"
	FieldAuthorSort Field = "author_sort"
	// FieldRating is 0 to 5 stars, halves allowed.
	FieldRating Field = "rating"
)

Fields the editor adds to those a match proposes.

const (
	FieldTitle       Field = "title"
	FieldAuthors     Field = "authors"
	FieldPublisher   Field = "publisher"
	FieldLanguages   Field = "languages"
	FieldTags        Field = "tags"
	FieldPublished   Field = "published"
	FieldDescription Field = "description"
	// FieldCover proposes the candidate's cover image. Its bytes are fetched
	// on demand with FetchCover, so a plan only carries the URL.
	FieldCover Field = "cover"
)

type FileGuess

type FileGuess struct {
	// Stem is the name without its extension.
	Stem string
	// Title is the main title; AltTitle is the second title of a bilingual name.
	Title, AltTitle string
	// Edition is a trailing group that names an edition, such as "第8版".
	Edition string
	Authors []string
	// ISBNs are valid ISBN-13 values found anywhere in the name.
	ISBNs []string
	// DashAuthors and DashTitle are the reading of an "Author - Title" name, the
	// shape FileNameFor builds. The name is just as likely a title with a dash
	// in it, so Title is left whole and Extract uses this only when the file's
	// own metadata agrees with it.
	DashAuthors []string
	DashTitle   string
	// RevAuthors and RevTitle are the other reading of a dashed name, "Title -
	// Author", the layout FileNameFor builds by default.
	RevAuthors []string
	RevTitle   string
	// Structured is true when the name has a trailing "(...)" group, which is
	// what makes its title worth trusting over a bare name.
	Structured bool
}

FileGuess is what a file's name says about the book it holds, read the way Z-Library saves names: "Title (Author)", with a second title after " = ", translators after the author, and a bracket group that may be an edition.

func GuessFromFileName

func GuessFromFileName(name string) FileGuess

GuessFromFileName reads a book's title, authors and ISBNs from its file name, the last element of its path. It trusts only what the name's shape shows: a name with no "(...)" group is Structured false, and a name that is only a number or an ISBN offers no title.

type Goodreads

type Goodreads struct {
	// contains filtered or unexported fields
}

Goodreads looks books up on Goodreads. It is opt-in: it is chosen by name and is never a default (DefaultSourceNamesFor).

It reads three addresses, with no cookies and no login, and a User-Agent (see goodreadsUserAgent):

  • /book/auto_complete?format=json&q=... returns up to a handful of books as JSON: title, author, cover, page count and a blurb that is cut short. It is searched with a title, a title and an author, or an ISBN.
  • /book/isbn/<isbn> redirects to the book's page. The redirect is read and not followed.
  • /book/show/<id> is the book's page, whose embedded data holds the whole record of one edition: authors, publisher, date, language, ISBNs, categories, series, the full description and the cover.

An ISBN is resolved to a book ID through the redirect and the page of that ID is read, which gives an edition-level candidate. A title search ranks the suggestions and reads the pages of the first few, so those rows are edition level too; the others stay as the suggestion list describes them, with a title, authors, a series and a cover. Goodreads sometimes answers a page with a bot check instead of the page (HTTP 202 and a script). The source does not answer it: it falls back to the suggestion for that book and reads no more pages in that lookup, so a lookup is never lost to it. A blurb that the suggestion list cut short is dropped, so it cannot replace a full description from another source with a fragment.

func NewGoodreads

func NewGoodreads(rt http.RoundTripper, opts ...GoodreadsOption) *Goodreads

NewGoodreads returns the source for rt (nil for the default transport).

func (*Goodreads) Identify

func (s *Goodreads) Identify(ctx context.Context, q Query) ([]Candidate, error)

func (*Goodreads) Name

func (*Goodreads) Name() string

type GoodreadsOption

type GoodreadsOption func(*Goodreads)

GoodreadsOption changes how a Goodreads source is built.

func WithGoodreadsUserAgent

func WithGoodreadsUserAgent(ua string) GoodreadsOption

WithGoodreadsUserAgent makes the source send ua instead of the default. An empty ua, or one with a line break in it, keeps the default.

type GoogleBooks

type GoogleBooks struct {
	// contains filtered or unexported fields
}

GoogleBooks queries the Google Books v1 API. Without an API key the quota is shared and a request may be refused with ErrRateLimited, which a lookup reports for this source only. A key gives the caller its own quota.

The key is sent in the x-goog-api-key header, never in the URL, so it does not reach logs, error text or a Referer, and the client refuses redirects off the Google host, so it cannot be sent anywhere else.

func NewGoogleBooks

func NewGoogleBooks(rt http.RoundTripper, key string) *GoogleBooks

NewGoogleBooks returns the source for rt (nil for the default transport). key may be empty. A malformed key is not sent: every lookup then fails with ErrKeyMalformed, rather than quietly falling back to the shared quota.

func (*GoogleBooks) Identify

func (s *GoogleBooks) Identify(ctx context.Context, q Query) ([]Candidate, error)

func (*GoogleBooks) Name

func (*GoogleBooks) Name() string

type Hint

type Hint struct {
	Title   string
	Authors []string
	ISBNs   []string // any form; an invalid one is ignored
	// NameLayout is how the user names their files. A dashed name that the file
	// does not explain is read that way round; empty reads it "Author - Title".
	NameLayout NameLayout
}

Hint is what is known about a book from outside the file: the Z-Library record of a download.

type Match

type Match string

Match classifies why a candidate was returned.

const (
	MatchISBN  Match = "isbn"  // shares an ISBN with the query
	MatchTitle Match = "title" // matched on title and authors
)

type NameLayout

type NameLayout string

NameLayout is the order in which a file name states the title and the authors: one of the presets, or a custom pattern such as "{title} [{authors}]", in which {title} and {authors} are replaced and any other text is kept.

const (
	// LayoutTitleAuthor is "Title - Authors": a folder sorts by title.
	LayoutTitleAuthor NameLayout = "title-author"
	// LayoutAuthorTitle is "Authors - Title": a folder sorts by author.
	LayoutAuthorTitle NameLayout = "author-title"
	// LayoutTitleParen is "Title (Authors)", the way Z-Library names its files.
	LayoutTitleParen NameLayout = "title-paren"

	// DefaultNameLayout is the layout when none is chosen.
	DefaultNameLayout = LayoutTitleAuthor
)

func ParseNameLayout

func ParseNameLayout(s string) (NameLayout, error)

ParseNameLayout reads a layout: a preset name, in any case, or a custom pattern. An empty one is DefaultNameLayout. A pattern that spells a preset is that preset.

func (NameLayout) IsPreset

func (l NameLayout) IsPreset() bool

IsPreset reports whether l is one of NameLayouts.

func (NameLayout) Label

func (l NameLayout) Label() string

Label is the layout as a pattern a person reads: "Title - Author" for a preset, the pattern itself for a custom layout.

func (NameLayout) Valid

func (l NameLayout) Valid() bool

Valid reports whether l can build names: a preset or a good custom pattern.

type OpenLibrary

type OpenLibrary struct {
	// contains filtered or unexported fields
}

OpenLibrary queries openlibrary.org. A lookup by ISBN returns that edition; a lookup by title and author returns works, which say nothing about the edition, so those candidates carry no ISBN, publisher or edition-specific date.

func NewOpenLibrary

func NewOpenLibrary(rt http.RoundTripper) *OpenLibrary

NewOpenLibrary returns the source for rt (nil for the default transport).

func (*OpenLibrary) Identify

func (s *OpenLibrary) Identify(ctx context.Context, q Query) ([]Candidate, error)

func (*OpenLibrary) Name

func (*OpenLibrary) Name() string

type Options

type Options struct {
	// Timeout bounds the whole lookup. Default 30s.
	Timeout time.Duration
	// Grace is how long to wait for slower sources once one has produced a
	// result. Default 8s.
	Grace time.Duration
	// MinScore drops title matches below it. Default 0.45.
	MinScore float64
	// MaxResults caps the candidates returned for each source. Default 10.
	MaxResults int
}

Options tunes a lookup. Zero values select the defaults.

type Query

type Query struct {
	Title   string   `json:"title,omitempty"`
	Authors []string `json:"authors,omitempty"`
	// ISBNs holds valid ISBN-13 values, see NormalizeISBN.
	ISBNs []string `json:"isbns,omitempty"`
	// Unconfirmed lists the ISBNs in ISBNs that nothing has vouched for: one
	// a download recorded from Z-Library's record, or one read from the
	// book's text. They are searched like any other, but only confirm a match
	// when the title agrees closely (hintTitleSimilarity).
	Unconfirmed []string `json:"unconfirmed_isbns,omitempty"`
	// TitleGuessed means the title was read from a file name or a download's
	// record, not from the file itself or from the user. A download's record
	// supplies both that name and a recorded ISBN, so such a title is no
	// independent evidence and cannot confirm an unconfirmed ISBN.
	TitleGuessed bool `json:"title_guessed,omitempty"`
	// Publisher and Year are what the file says about its edition. They do not
	// find a book; they only rank editions of one title a little.
	Publisher string `json:"publisher,omitempty"`
	Year      string `json:"year,omitempty"`
}

Query describes the book to look up.

func ParseQueryEdit

func ParseQueryEdit(old Query, title, authors, isbns string) (Query, error)

ParseQueryEdit reads what the user typed to change a search: a title, authors separated by "&" and ISBNs separated by commas, semicolons or line breaks. It returns the new query, or an error saying what cannot be searched.

Text is cleaned of control characters, and each ISBN must be valid (an ISBN-10 is read as its ISBN-13). An ISBN the user typed is confirmed, like one passed with --isbn. An ISBN the old query held as unconfirmed, such as a download's hint or one read from the book, stays unconfirmed for as long as it is left in the field, so it is still judged against the title searched (at the stricter hint bar). A title the user changes is theirs and no guess; one left as it was keeps its mark, so pressing Enter in the editor confirms nothing.

func QueryFromMetadata

func QueryFromMetadata(m *ebookmeta.Metadata) Query

QueryFromMetadata builds a query from what a file already knows.

func (*Query) AddUnconfirmedISBN

func (q *Query) AddUnconfirmedISBN(isbn string)

AddUnconfirmedISBN adds isbn, a valid ISBN-13, to the query as an unconfirmed ISBN, unless the query already has it.

func (Query) Empty

func (q Query) Empty() bool

Empty reports whether q has nothing to search with.

type Result

type Result struct {
	Candidates []Candidate
	Errors     []SourceError
}

Result is the outcome of a lookup: ranked candidates, each from one source, plus what went wrong at each source. A source failing never fails the lookup.

func Lookup

func Lookup(ctx context.Context, sources []Source, q Query, opt Options) (Result, error)

Lookup asks every source in parallel and returns the candidates of all of them in one ranked list, each candidate from a single source: the answers of different sources are not merged. It returns ErrNoQuery for an empty query and ErrAllSourcesFailed when every source failed and nothing was found; a lookup that simply finds nothing returns an empty Result and no error.

func (Result) ErrorSummary

func (r Result) ErrorSummary() string

ErrorSummary joins the per-source errors into one line.

type Source

type Source interface {
	Name() string
	// Identify returns candidates for q. Finding nothing is not an error.
	Identify(ctx context.Context, q Query) ([]Candidate, error)
}

Source is one catalogue.

func DefaultSources

func DefaultSources(rt http.RoundTripper, googleKey string) []Source

DefaultSources returns the default sources for a book that is not Chinese. googleKey is an optional Google Books API key, which adds Google Books.

func NewSources

func NewSources(names []string, cfg SourceConfig) []Source

NewSources builds the named sources in order. An unknown name becomes a source that fails with a clear error, so a typo shows up in the lookup's error list instead of silently dropping a catalogue.

type SourceConfig

type SourceConfig struct {
	// Transport is used by Open Library, Google Books and Douban.
	Transport http.RoundTripper
	// WeReadTransport is used by WeRead, which has its own proxy setting.
	WeReadTransport http.RoundTripper
	// GoogleKey is an optional Google Books API key; without one Google's
	// shared quota applies.
	GoogleKey string
	// WeReadKey is the WeRead API key the weread source needs.
	WeReadKey string
	// MaxResults is the result limit the lookup will apply; the sources fetch
	// enough hits to fill it. Zero is DefaultMaxResults.
	MaxResults int
}

SourceConfig carries what the built-in sources need. The zero value builds the sources on the default transport with no keys.

type SourceError

type SourceError struct {
	Source string
	Err    error
}

SourceError is the failure of one source, kept so a lookup can report it without failing as a whole.

func (SourceError) Error

func (e SourceError) Error() string

func (SourceError) Unwrap

func (e SourceError) Unwrap() error

type WeRead

type WeRead struct {
	// contains filtered or unexported fields
}

WeRead looks books up through the WeRead agent gateway, the API key interface Tencent publishes for agents (/store/search and /book/info). It is opt-in: it needs the user's own API key, which is bound to their account, so every title searched is sent to Tencent under that identity.

It shares nothing with the importer in internal/weread, which logs in as a device and signs requests; this source sends a plain bearer key and an honest User-Agent. The key goes in the Authorization header only, never in a URL, a log or an error text, and the client refuses any redirect off the gateway host, so it cannot be sent anywhere else.

The gateway has no lookup by ISBN: an ISBN used as a search keyword returns unrelated books. So a title is searched, each plausible hit is read with /book/info, and the ISBN the entry carries (often none) is what the matcher compares with the wanted one. A query with no title finds nothing.

func NewWeRead

func NewWeRead(rt http.RoundTripper, key string) *WeRead

NewWeRead returns the source for rt (nil for the default transport). key is the API key; without a valid one every lookup fails with a clear error.

func (*WeRead) Identify

func (s *WeRead) Identify(ctx context.Context, q Query) ([]Candidate, error)

func (*WeRead) Name

func (*WeRead) Name() string

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL