zlib

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: 35 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

Index

Constants

View Source
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.

View Source
const (
	DefaultDomain = "https://z-lib.gd"
	TorDomain     = "http://bookszlibb74ugqojhzhg2a63w5i2atv5bqarulgczawnbmsb6s6qead.onion"
	EnvDomain     = "ZLIB_DOMAIN"
	EnvProxy      = "ZLIB_PROXY"
	EnvRetries    = "ZLIB_DOWNLOAD_RETRIES"
)
View Source
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.

View Source
const (
	DefaultEAPIDomain = "https://z-lib.gd"
)

Variables

View Source
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")
)
View Source
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

func IsBuiltInDomain(raw string) bool

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

func ParseAllowedDomain(raw string) (string, error)

ParseAllowedDomain validates an HTTPS origin against the built-in suffixes and the user's trusted mirrors, and returns its normalized origin.

func ParseMirrorOrigin

func ParseMirrorOrigin(raw string) (string, error)

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

func SetUserMirrors(origins []string) error

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 Booklist

type Booklist struct {
	Name        string `json:"name"`
	URL         string `json:"url"`
	Description string `json:"description,omitempty"`
	Author      string `json:"author,omitempty"`
	Count       string `json:"count,omitempty"`
	Views       string `json:"views,omitempty"`
}

type BooklistResult

type BooklistResult struct {
	Lists      []Booklist `json:"lists"`
	Page       int        `json:"page"`
	TotalPages int        `json:"total_pages"`
}

type BotProtectionError

type BotProtectionError struct {
	StatusCode int
	URL        string
}

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) Cookies

func (c *Client) Cookies() map[string]string

func (*Client) DeleteDownloadHistory

func (c *Client) DeleteDownloadHistory(ref string) error

DeleteDownloadHistory removes a remote history entry, leaving local files intact. ref accepts a numeric book ID or id:hash.

func (*Client) DeleteDownloadHistoryContext

func (c *Client) DeleteDownloadHistoryContext(ctx context.Context, ref string) error

DeleteDownloadHistoryContext is DeleteDownloadHistory with cancellation support.

func (*Client) Domain

func (c *Client) Domain() string

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) FetchBook

func (c *Client) FetchBook(ref string) (Book, error)

func (*Client) FetchBookContext

func (c *Client) FetchBookContext(ctx context.Context, ref string) (Book, error)

FetchBookContext is FetchBook with cancellation support.

func (*Client) FetchBookDetails

func (c *Client) FetchBookDetails(refs []string) map[string]Book

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

func (c *Client) FetchCover(ctx context.Context, raw string) (image.Image, error)

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) Login

func (c *Client) Login(email, password string) error

func (*Client) LoginEAPI

func (c *Client) LoginEAPI(email, password string) error

func (*Client) LoginEAPIContext

func (c *Client) LoginEAPIContext(ctx context.Context, email, password string) error

LoginEAPIContext is LoginEAPI with a context, so an interactive caller can abandon a login that a slow mirror leaves hanging.

func (*Client) Logout

func (c *Client) Logout()

func (*Client) Mode

func (c *Client) Mode() ClientMode

func (*Client) MostPopularBooks

func (c *Client) MostPopularBooks() ([]Book, error)

MostPopularBooks returns the EAPI most-popular list.

func (*Client) MostPopularBooksContext

func (c *Client) MostPopularBooksContext(ctx context.Context) ([]Book, error)

MostPopularBooksContext is MostPopularBooks with cancellation support.

func (*Client) RecommendedBooks

func (c *Client) RecommendedBooks() ([]Book, error)

RecommendedBooks returns the account's recommended books.

func (*Client) RecommendedBooksContext

func (c *Client) RecommendedBooksContext(ctx context.Context) ([]Book, error)

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

func (c *Client) SavedBooksContext(ctx context.Context, page int) (SearchResult, error)

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 (c *Client) SetCookies(cookies map[string]string)

func (*Client) SetCoverCacheDir added in v0.0.13

func (c *Client) SetCoverCacheDir(dir string)

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) SetDomain

func (c *Client) SetDomain(domain string)

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 DownloadLimit struct {
	DailyAmount    int `json:"daily_amount"`
	DailyAllowed   int `json:"daily_allowed"`
	DailyRemaining int `json:"daily_remaining"`
}

type DownloadResult

type DownloadResult struct {
	FilePath string
	Size     int64
}

type Extension

type Extension string
const (
	ExtTXT  Extension = "TXT"
	ExtPDF  Extension = "PDF"
	ExtFB2  Extension = "FB2"
	ExtEPUB Extension = "EPUB"
	ExtLIT  Extension = "LIT"
	ExtMOBI Extension = "MOBI"
	ExtRTF  Extension = "RTF"
	ExtDJV  Extension = "DJV"
	ExtDJVU Extension = "DJVU"
	ExtAZW  Extension = "AZW"
	ExtAZW3 Extension = "AZW3"
)

func (Extension) String

func (e Extension) String() string

type FullTextSearchOptions

type FullTextSearchOptions struct {
	SearchOptions
	Phrase bool
}

type HTTPStatusError

type HTTPStatusError struct {
	StatusCode int
	URL        string
}

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 SearchOptions struct {
	Exact      bool
	FromYear   int
	ToYear     int
	Languages  []Language
	Extensions []Extension
	Order      OrderOption
}

type SearchResult

type SearchResult struct {
	Books      []Book `json:"books"`
	Page       int    `json:"page"`
	TotalPages int    `json:"total_pages"`
}

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.

Jump to

Keyboard shortcuts

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