Documentation
¶
Index ¶
- Constants
- Variables
- func AllowedDomainSuffixes() []string
- func CurrentDefaultDomain() string
- func IsBuiltInDomain(raw string) bool
- func KnownDomains() []string
- func ParseAllowedDomain(raw string) (string, error)
- func ParseMirrorOrigin(raw string) (string, error)
- func ProbeDomainsEach(ctx context.Context, domains []string, opts DomainProbeOptions, ...)
- func SendToKindle(filePath string, cfg KindleConfig, smtpPassword string) error
- func SendToKindleContext(ctx context.Context, filePath string, cfg KindleConfig, smtpPassword string) error
- func SetDefaultDomain(domain string)
- func SetUserMirrors(origins []string) error
- func UserMirrors() []string
- type Book
- type Booklist
- type BooklistResult
- type BotProtectionError
- type Client
- func (c *Client) CloseIdleConnections()
- func (c *Client) Cookies() map[string]string
- func (c *Client) DeleteDownloadHistory(ref string) error
- func (c *Client) DeleteDownloadHistoryContext(ctx context.Context, ref string) error
- func (c *Client) Domain() string
- func (c *Client) Download(downloadURL, destDir string, progressFn func(written, total int64)) (DownloadResult, error)
- func (c *Client) DownloadHistory(page int) (DownloadHistoryResult, error)
- func (c *Client) DownloadHistoryContext(ctx context.Context, page int) (DownloadHistoryResult, error)
- func (c *Client) DownloadWithContext(ctx context.Context, downloadURL, destDir string, ...) (DownloadResult, error)
- func (c *Client) FetchBook(ref string) (Book, error)
- func (c *Client) FetchBookContext(ctx context.Context, ref string) (Book, error)
- func (c *Client) FetchBookDetails(refs []string) map[string]Book
- func (c *Client) FetchBookDetailsContext(ctx context.Context, refs []string) (map[string]Book, error)
- func (c *Client) FetchCover(ctx context.Context, raw string) (image.Image, error)
- func (c *Client) FullTextSearch(query string, page, count int, opts *FullTextSearchOptions) (SearchResult, error)
- func (c *Client) GetLimits() (DownloadLimit, error)
- func (c *Client) GetLimitsContext(ctx context.Context) (DownloadLimit, error)
- func (c *Client) GetProfile() (UserProfile, error)
- func (c *Client) GetProfileContext(ctx context.Context) (UserProfile, error)
- func (c *Client) Login(email, password string) error
- func (c *Client) LoginEAPI(email, password string) error
- func (c *Client) LoginEAPIContext(ctx context.Context, email, password string) error
- func (c *Client) Logout()
- func (c *Client) Mode() ClientMode
- func (c *Client) MostPopularBooks() ([]Book, error)
- func (c *Client) MostPopularBooksContext(ctx context.Context) ([]Book, error)
- func (c *Client) RecommendedBooks() ([]Book, error)
- func (c *Client) RecommendedBooksContext(ctx context.Context) ([]Book, error)
- func (c *Client) SavedBooks(page int) (SearchResult, error)
- func (c *Client) SavedBooksContext(ctx context.Context, page int) (SearchResult, error)
- func (c *Client) Search(query string, page, count int, opts *SearchOptions) (SearchResult, error)
- func (c *Client) SearchContext(ctx context.Context, query string, page, count int, opts *SearchOptions) (SearchResult, error)
- func (c *Client) SetCookies(cookies map[string]string)
- func (c *Client) SetCoverCacheDir(dir string)
- func (c *Client) SetDomain(domain string)
- func (c *Client) SetMode(mode ClientMode)
- type ClientMode
- type ClientOption
- type DomainCheck
- func ProbeDomain(ctx context.Context, domain string) DomainCheck
- func ProbeDomainWithOptions(ctx context.Context, domain string, opts DomainProbeOptions) DomainCheck
- func ProbeDomains(ctx context.Context, domains []string) []DomainCheck
- func ProbeDomainsWithOptions(ctx context.Context, domains []string, opts DomainProbeOptions) []DomainCheck
- func VerifyUserMirror(ctx context.Context, raw string, opts DomainProbeOptions) (DomainCheck, error)
- type DomainProbeOptions
- type DomainStatus
- type DownloadHistoryItem
- type DownloadHistoryResult
- type DownloadLimit
- type DownloadResult
- type Extension
- type FullTextSearchOptions
- type HTTPStatusError
- type KindleConfig
- type Language
- type OrderOption
- type SearchOptions
- type SearchResult
- type UserProfile
Constants ¶
const ( // SMTPSecurityTLS starts TLS as soon as the connection opens: implicit // TLS (RFC 8314), often labelled "SSL/TLS". The standard port is 465. SMTPSecurityTLS = "tls" // SMTPSecuritySTARTTLS connects in plain text and must upgrade with // STARTTLS before anything else is sent. The standard port is 587. SMTPSecuritySTARTTLS = "starttls" )
SMTP connection security modes, as mail clients label them.
const ( DefaultDomain = "https://z-lib.gd" TorDomain = "http://bookszlibb74ugqojhzhg2a63w5i2atv5bqarulgczawnbmsb6s6qead.onion" EnvDomain = "ZLIB_DOMAIN" EnvProxy = "ZLIB_PROXY" EnvRetries = "ZLIB_DOWNLOAD_RETRIES" )
const DefaultDownloadRetries = 3
DefaultDownloadRetries is how many times a download request is reissued after a transient failure — a connection error, or one of the gateway statuses isRetryableStatus accepts. Other failures are never retried. EnvRetries overrides it, and 0 disables retrying.
const (
DefaultEAPIDomain = "https://z-lib.gd"
)
Variables ¶
var ( ErrLoginFailed = errors.New("zlibrary: login failed") ErrNotLoggedIn = errors.New("zlibrary: not logged in, call Login first") ErrNoDomain = errors.New("zlibrary: no working domain found") ErrEmptyQuery = errors.New("zlibrary: search query is empty") ErrNoID = errors.New("zlibrary: no book ID provided") ErrInvalidProxy = errors.New("zlibrary: proxy_list must be a non-empty slice") ErrParseFailed = errors.New("zlibrary: failed to parse page") ErrSessionExpired = errors.New("zlibrary: session expired or revoked, log in again") ErrPhraseMinWords = errors.New("zlibrary: phrase search requires at least 2 words") ErrUnsupported = errors.New("zlibrary: feature unavailable in EAPI") ErrDownloadFailed = errors.New("zlibrary: download failed") // ErrSMTPSend wraps every failure to deliver a Send-to-Kindle email after // the message was built, so the CLI can show the SMTP cause verbatim. ErrSMTPSend = errors.New("zlibrary: smtp send failed") // ErrBotProtection is returned when an upstream anti-bot page is served // instead of the requested Z-Library response. ErrBotProtection = errors.New("zlibrary: blocked by anti-bot protection") // ErrRedirectLoop is returned when an upstream keeps redirecting a request // beyond the client's redirect limit. ErrRedirectLoop = errors.New("zlibrary: too many redirects") // ErrChallengeFailed is returned when the JS challenge could not be cleared // within the client's attempt budget. ErrChallengeFailed = errors.New("zlibrary: could not clear the browser challenge") // ErrMirrorUnverified is returned when a domain offered as a user mirror // does not itself answer as the Z-Library EAPI. ErrMirrorUnverified = errors.New("zlibrary: mirror did not answer as Z-Library") )
var ( Version = "dev" Commit = "none" Date = "unknown" )
Version is always reported as vX.Y.Z (or a vX.Y.Z-based pre-release or pseudo-version), matching the git tag; "dev" marks a build without version metadata. See docs/versioning.md.
Functions ¶
func AllowedDomainSuffixes ¶
func AllowedDomainSuffixes() []string
AllowedDomainSuffixes returns the built-in upstream hostname suffixes. A hostname matches a suffix when it equals it or is one of its subdomains.
func CurrentDefaultDomain ¶
func CurrentDefaultDomain() string
CurrentDefaultDomain resolves the domain new clients start from: SetDefaultDomain > ZLIB_DOMAIN > DefaultDomain.
ZLIB_DOMAIN is read on every call rather than in an init function: the CLI loads .env after all init functions have run, so an init-time read would never observe a .env-supplied value.
func IsBuiltInDomain ¶
IsBuiltInDomain reports whether a domain is already covered by the built-in suffixes, so adding it as a user mirror would change nothing.
func KnownDomains ¶
func KnownDomains() []string
KnownDomains returns the domains checked by the CLI doctor command: the built-in ones, then the user's trusted mirrors.
func ParseAllowedDomain ¶
ParseAllowedDomain validates an HTTPS origin against the built-in suffixes and the user's trusted mirrors, and returns its normalized origin.
func ParseMirrorOrigin ¶
ParseMirrorOrigin normalizes a user mirror to "https://host". A bare host such as "mirror.example" is accepted. Plain HTTP, ports, paths, credentials, IP addresses and single-label hosts are rejected: the login is sent to this host, and each of those is more likely a mistake than a real mirror.
func ProbeDomainsEach ¶ added in v0.0.13
func ProbeDomainsEach(ctx context.Context, domains []string, opts DomainProbeOptions, each func(index int, check DomainCheck))
ProbeDomainsEach checks domains concurrently and calls each with a domain's index and result as soon as that domain finishes, so a caller can show results as they arrive. each runs on the probing goroutines, in completion order, and must be safe for concurrent use. It returns when every probe is done.
func SendToKindle ¶
func SendToKindle(filePath string, cfg KindleConfig, smtpPassword string) error
func SendToKindleContext ¶
func SendToKindleContext(ctx context.Context, filePath string, cfg KindleConfig, smtpPassword string) error
SendToKindleContext sends an attachment and stops local work when ctx is cancelled. Cancellation cannot retract a message already accepted by SMTP.
func SetDefaultDomain ¶
func SetDefaultDomain(domain string)
SetDefaultDomain overrides the default domain for clients created afterwards. Passing an empty string clears the override, restoring ZLIB_DOMAIN-or-default resolution.
func SetUserMirrors ¶
SetUserMirrors replaces the trusted user mirrors. Invalid entries are skipped and reported in the returned error; the valid ones still apply.
func UserMirrors ¶
func UserMirrors() []string
UserMirrors returns the trusted user mirrors as origins, in the order added.
Types ¶
type Book ¶
type Book struct {
ID string `json:"id"`
Hash string `json:"hash,omitempty"`
ISBN string `json:"isbn,omitempty"`
ISBN10 string `json:"isbn_10,omitempty"`
ISBN13 string `json:"isbn_13,omitempty"`
URL string `json:"url"`
Cover string `json:"cover,omitempty"`
Name string `json:"name"`
Authors []string `json:"authors,omitempty"`
Publisher string `json:"publisher,omitempty"`
Year string `json:"year,omitempty"`
Language string `json:"language,omitempty"`
Extension string `json:"extension,omitempty"`
Size string `json:"size,omitempty"`
Rating string `json:"rating,omitempty"`
Quality string `json:"quality,omitempty"`
Description string `json:"description,omitempty"`
Categories string `json:"categories,omitempty"`
Edition string `json:"edition,omitempty"`
Pages string `json:"pages,omitempty"`
DownloadURL string `json:"download_url,omitempty"`
}
type BooklistResult ¶
type BotProtectionError ¶
BotProtectionError describes an anti-bot response returned by the upstream. It unwraps to ErrBotProtection so callers can classify it with errors.Is.
func (*BotProtectionError) Error ¶
func (e *BotProtectionError) Error() string
func (*BotProtectionError) Unwrap ¶
func (e *BotProtectionError) Unwrap() error
type Client ¶
type Client struct {
// contains filtered or unexported fields
}
func NewClient ¶
func NewClient(opts ...ClientOption) *Client
func (*Client) CloseIdleConnections ¶
func (c *Client) CloseIdleConnections()
CloseIdleConnections releases idle connections owned by the client's transport. Active requests are not interrupted.
func (*Client) DeleteDownloadHistory ¶
DeleteDownloadHistory removes a remote history entry, leaving local files intact. ref accepts a numeric book ID or id:hash.
func (*Client) DeleteDownloadHistoryContext ¶
DeleteDownloadHistoryContext is DeleteDownloadHistory with cancellation support.
func (*Client) Download ¶
func (c *Client) Download(downloadURL, destDir string, progressFn func(written, total int64)) (DownloadResult, error)
func (*Client) DownloadHistory ¶
func (c *Client) DownloadHistory(page int) (DownloadHistoryResult, error)
func (*Client) DownloadHistoryContext ¶
func (c *Client) DownloadHistoryContext(ctx context.Context, page int) (DownloadHistoryResult, error)
DownloadHistoryContext is DownloadHistory with cancellation support.
func (*Client) DownloadWithContext ¶
func (c *Client) DownloadWithContext(ctx context.Context, downloadURL, destDir string, progressFn func(written, total int64)) (DownloadResult, error)
DownloadWithContext saves the file at downloadURL into destDir. The file is written to a temporary name and only renamed into place once complete, so a failed or cancelled download never truncates or removes an existing file of the same name.
func (*Client) FetchBookContext ¶
FetchBookContext is FetchBook with cancellation support.
func (*Client) FetchBookDetails ¶
FetchBookDetails resolves book references concurrently. Failed references retain a zero Book entry so callers can match results to their inputs.
func (*Client) FetchBookDetailsContext ¶
func (c *Client) FetchBookDetailsContext(ctx context.Context, refs []string) (map[string]Book, error)
FetchBookDetailsContext resolves references with bounded concurrency. On the first failure it cancels outstanding requests and returns a partial map and the error. Failed or unprocessed references retain a zero Book entry.
func (*Client) FetchCover ¶ added in v0.0.13
FetchCover fetches an untrusted image without account cookies or EAPI headers. It shares only the configured transport (including the user's proxy).
func (*Client) FullTextSearch ¶
func (c *Client) FullTextSearch(query string, page, count int, opts *FullTextSearchOptions) (SearchResult, error)
FullTextSearch is unavailable because the mobile EAPI has no verified equivalent to the website's full-text search.
func (*Client) GetLimits ¶
func (c *Client) GetLimits() (DownloadLimit, error)
func (*Client) GetLimitsContext ¶
func (c *Client) GetLimitsContext(ctx context.Context) (DownloadLimit, error)
GetLimitsContext is GetLimits with cancellation support.
func (*Client) GetProfile ¶
func (c *Client) GetProfile() (UserProfile, error)
func (*Client) GetProfileContext ¶
func (c *Client) GetProfileContext(ctx context.Context) (UserProfile, error)
GetProfileContext is GetProfile with cancellation support.
func (*Client) LoginEAPIContext ¶
LoginEAPIContext is LoginEAPI with a context, so an interactive caller can abandon a login that a slow mirror leaves hanging.
func (*Client) Mode ¶
func (c *Client) Mode() ClientMode
func (*Client) MostPopularBooks ¶
MostPopularBooks returns the EAPI most-popular list.
func (*Client) MostPopularBooksContext ¶
MostPopularBooksContext is MostPopularBooks with cancellation support.
func (*Client) RecommendedBooks ¶
RecommendedBooks returns the account's recommended books.
func (*Client) RecommendedBooksContext ¶
RecommendedBooksContext is RecommendedBooks with cancellation support.
func (*Client) SavedBooks ¶
func (c *Client) SavedBooks(page int) (SearchResult, error)
SavedBooks returns one page of the account's saved books.
func (*Client) SavedBooksContext ¶
SavedBooksContext is SavedBooks with cancellation support.
func (*Client) Search ¶
func (c *Client) Search(query string, page, count int, opts *SearchOptions) (SearchResult, error)
func (*Client) SearchContext ¶
func (c *Client) SearchContext(ctx context.Context, query string, page, count int, opts *SearchOptions) (SearchResult, error)
SearchContext is Search with cancellation support.
func (*Client) SetCookies ¶
func (*Client) SetCoverCacheDir ¶ added in v0.0.13
SetCoverCacheDir enables the on-disk cover cache. Entries are keyed by the SHA-256 of the cover URL and re-validated on every read.
func (*Client) SetMode ¶
func (c *Client) SetMode(mode ClientMode)
type ClientMode ¶
type ClientMode string
ClientMode identifies the upstream transport used by high-level operations.
const (
ClientModeEAPI ClientMode = "eapi"
)
type ClientOption ¶
type ClientOption func(*Client)
func WithDomain ¶
func WithDomain(domain string) ClientOption
func WithOnion ¶
func WithOnion(proxyURL string) ClientOption
func WithProxy ¶
func WithProxy(proxyURL string) ClientOption
WithProxy routes requests through proxyURL. It clones http.DefaultTransport so the connection pooling, HTTP/2 negotiation, and dial timeouts the stdlib tunes for us survive; only the proxy function is replaced.
func WithTransportFrom ¶
func WithTransportFrom(source *Client) ClientOption
WithTransportFrom shares source's HTTP connection pool without sharing its cookie jar or account state. Both clients must use the same proxy settings. Configure source before sharing it; do not change its transport concurrently.
type DomainCheck ¶
type DomainCheck struct {
Domain string `json:"domain"`
Status DomainStatus `json:"status"`
HTTPStatus int `json:"http_status,omitempty"`
FinalURL string `json:"final_url,omitempty"`
Detail string `json:"detail,omitempty"`
// contains filtered or unexported fields
}
DomainCheck contains the result of a read-only unauthenticated domain probe.
func ProbeDomain ¶
func ProbeDomain(ctx context.Context, domain string) DomainCheck
ProbeDomain checks whether an unauthenticated GET to a domain reaches a successful response. Redirects are followed manually so self-redirects and DiamWall's __diamwall cookie can be reported precisely.
func ProbeDomainWithOptions ¶
func ProbeDomainWithOptions(ctx context.Context, domain string, opts DomainProbeOptions) DomainCheck
ProbeDomainWithOptions checks a single domain using opts.
func ProbeDomains ¶
func ProbeDomains(ctx context.Context, domains []string) []DomainCheck
ProbeDomains checks domains concurrently. It makes only unauthenticated GET requests and never changes the client's configured default domain.
func ProbeDomainsWithOptions ¶
func ProbeDomainsWithOptions(ctx context.Context, domains []string, opts DomainProbeOptions) []DomainCheck
ProbeDomainsWithOptions checks domains concurrently using opts.
func VerifyUserMirror ¶
func VerifyUserMirror(ctx context.Context, raw string, opts DomainProbeOptions) (DomainCheck, error)
VerifyUserMirror checks, without credentials, that a candidate mirror itself answers /eapi/info/domains as the Z-Library EAPI does. A redirect to another host fails: the login would go to the first host, so that is the one that has to prove it serves Z-Library.
type DomainProbeOptions ¶
type DomainProbeOptions struct {
// ProxyURL overrides ZLIB_PROXY for this probe when non-empty.
ProxyURL string
// Path selects an endpoint below each candidate origin. Empty probes root.
Path string
}
DomainProbeOptions controls how doctor probes reach candidate domains.
type DomainStatus ¶
type DomainStatus string
DomainStatus is the health classification returned by ProbeDomain.
const ( DomainStatusHealthy DomainStatus = "healthy" // DomainStatusChallenged means the domain answered with an HTML challenge. // EAPI requests cannot use this domain until it serves JSON again. DomainStatusChallenged DomainStatus = "challenged" DomainStatusDiamWallBlocked DomainStatus = "diamwall_blocked" DomainStatusRedirectLoop DomainStatus = "redirect_loop" DomainStatusHTTPError DomainStatus = "http_error" DomainStatusNetworkError DomainStatus = "network_error" DomainStatusInvalidDomain DomainStatus = "invalid_domain" )
type DownloadHistoryItem ¶
type DownloadHistoryItem struct {
// ID and Hash identify the downloaded book in EAPI responses.
ID string `json:"id,omitempty"`
Hash string `json:"hash,omitempty"`
Name string `json:"name"`
Authors []string `json:"authors,omitempty"`
URL string `json:"url"`
DownloadURL string `json:"download_url,omitempty"`
Extension string `json:"extension,omitempty"`
Size string `json:"size,omitempty"`
Date string `json:"date"`
// ISBN, ISBN10 and ISBN13 are what the list response says, with the same
// meaning and normalization as on Book.
ISBN string `json:"isbn,omitempty"`
ISBN10 string `json:"isbn_10,omitempty"`
ISBN13 string `json:"isbn_13,omitempty"`
}
type DownloadHistoryResult ¶
type DownloadHistoryResult struct {
Items []DownloadHistoryItem `json:"items"`
Page int `json:"page"`
TotalPages int `json:"total_pages"`
}
type DownloadLimit ¶
type DownloadResult ¶
type FullTextSearchOptions ¶
type FullTextSearchOptions struct {
SearchOptions
Phrase bool
}
type HTTPStatusError ¶
HTTPStatusError describes an unexpected non-success HTTP response.
func (*HTTPStatusError) Error ¶
func (e *HTTPStatusError) Error() string
type KindleConfig ¶
type KindleConfig struct {
To string `json:"to"`
From string `json:"from"`
SMTPHost string `json:"smtp_host"`
SMTPPort int `json:"smtp_port"`
// SMTPSecurity is SMTPSecurityTLS or SMTPSecuritySTARTTLS. Empty picks the
// port's standard mode; see Security.
SMTPSecurity string `json:"smtp_security,omitempty"`
}
func (KindleConfig) Security ¶
func (c KindleConfig) Security() string
Security returns the connection mode to use. Without an explicit setting it follows the port's IANA assignment: 465 is submissions (implicit TLS), and every other port uses STARTTLS. Providers that document another implicit-TLS port, such as smtp.163.com on 994, need SMTPSecurity set to "tls".
func (KindleConfig) Validate ¶
func (c KindleConfig) Validate() error
type Language ¶
type Language string
const ( LangEnglish Language = "english" LangChinese Language = "chinese" LangRussian Language = "russian" LangFrench Language = "french" LangGerman Language = "german" LangSpanish Language = "spanish" LangJapanese Language = "japanese" LangKorean Language = "korean" LangItalian Language = "italian" LangPortuguese Language = "portuguese" LangArabic Language = "arabic" LangDutch Language = "dutch" LangPolish Language = "polish" LangTurkish Language = "turkish" LangHindi Language = "hindi" )
type OrderOption ¶
type OrderOption string
const ( OrderPopular OrderOption = "popular" OrderNewest OrderOption = "date_created" OrderRecent OrderOption = "date_updated" OrderBestMatch OrderOption = "bestmatch" OrderDate OrderOption = "date" OrderTitleAZ OrderOption = "titleA" OrderTitleZA OrderOption = "title" OrderYear OrderOption = "year" OrderFileSizeDesc OrderOption = "filesize" OrderFileSizeAsc OrderOption = "filesizeA" )
func (OrderOption) String ¶
func (o OrderOption) String() string
type SearchOptions ¶
type SearchResult ¶
type UserProfile ¶
type UserProfile struct {
DownloadLimit
ID string `json:"id,omitempty"`
Name string `json:"name,omitempty"`
Email string `json:"email,omitempty"`
KindleEmail string `json:"kindle_email,omitempty"`
Premium *bool `json:"premium,omitempty"`
Confirmed *bool `json:"confirmed,omitempty"`
DonationsActive *bool `json:"donations_active,omitempty"`
DonationsExpire string `json:"donations_expire,omitempty"`
PersonalDomains []string `json:"personal_domains,omitempty"`
QuotaKnown bool `json:"quota_known"`
}
UserProfile contains the account fields safe to display or serialize. Authentication credentials returned by EAPI are intentionally excluded.