zlib

package module
v0.0.11 Latest Latest
Warning

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

Go to latest
Published: Oct 21, 2026 License: MIT Imports: 27 Imported by: 0

README

zlib

zlib

A Z-Library CLI to search, download, and send books to Kindle, for you and AI agents like Claude Code and Codex.

Go version CI Release Downloads License

English | 简体中文

Install · Quick start · Terminal interface · Commands · Agent setup · Docs

Book search in the terminal

Features

🔍 Search — filter by year, language, and format; sort results
📚 Browse — favorites, recommendations, popular books, and download history
📥 Download — view book details and choose a download directory
📖 Send to Kindle — deliver files to your Kindle address
🕒 Profile — check your daily download quota
🎨 Themes — switch color themes with /theme
🌐 Network — find working mirrors with zlib doctor, or use a proxy
🤖 AI Agent Integration — integrate with Claude Code and Codex through Agent plugins

Install

macOS / Linux with Homebrew:

brew install heartleo/tap/zlib

macOS / Linux with the install script (installs to /usr/local/bin, may ask for sudo):

curl -fsSL https://raw.githubusercontent.com/heartleo/zlib/main/install.sh | sh

Windows with winget:

winget install --id heartleo.zlib --exact

Or download a binary from Releases and put it on your PATH. See Installation for Go installation, source builds, and upgrades.

Quick start

You need a Z-Library account. First, find a domain reachable from your network:

zlib doctor

Log in with a domain from the results. Replace the example URL below with one from your results; enter your email and password in the prompt:

zlib login --domain https://z-lib.gd
zlib tui

Press /, choose /search, enter a title, author, or ISBN, and press Ctrl+S. You can also type /search dune and press Enter. Select a book and press Enter to confirm the download.

Downloads default to the current directory. You can choose another folder before downloading. Login is saved locally; subsequent sessions only need zlib tui.

If no domain works or login fails, see Troubleshooting. Existing browser sessions can be imported as cookies.

Terminal interface

zlib tui opens one persistent shell. Every screen lists its keys at the bottom; these cover a first session:

Key Action
/ Open the command list: search, favorites, history, profile, settings, themes
↑/↓ or j/k Select a book
←/→ Previous or next page of results
Enter Download the selected book, after a confirmation
Ctrl+F Change the query and filters of the current search
Esc Go back
/quit Exit

Settings live under /config (network, downloads, Kindle). See Terminal interface for every screen and key.

Commands

Pass a query for table output, or add --json for scripts:

zlib search "dune" --ext epub
zlib search "dune" --ext epub --json --count 10
Task Command
Browse favorites zlib favorites
Browse recommendations zlib recommended
Browse popular books zlib most-popular
Browse download history zlib history
Check account and quota zlib profile
Send to Kindle zlib kindle send ./book.epub

To download, replace id:hash with a book's complete id from the results:

zlib download "id:hash"

Run zlib <command> --help for flags. Usage covers filters, pagination, and download options.

Agent setup

Install the plugin. If zlib is missing, the agent installs it on first use. Log in yourself with zlib login so your password stays out of chat.

Claude Code

Run inside Claude Code:

/plugin marketplace add heartleo/zlib
/plugin install zlib@zlib-plugin-cc
Codex

Run in your terminal:

codex plugin marketplace add heartleo/zlib
codex plugin add zlib@zlib

Then ask your agent:

Use zlib to find The Pragmatic Programmer in EPUB. Show the results before downloading.

Documentation

Guide Covers
Installation Install methods, source builds, zlib update
Usage Search, downloads, favorites, history
Terminal interface Commands and keyboard controls
Configuration Domains, proxies, folders, configuration paths
Themes Available palettes and preview controls
Kindle SMTP setup and delivery
Troubleshooting Login and network problems

Report bugs in Issues with your zlib version, OS, command, and error. Omit passwords, cookies, and session files. Report security vulnerabilities privately as described in SECURITY.md.

Star History

Star History Chart

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")
)
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 added in v0.0.7

func AllowedDomainSuffixes() []string

AllowedDomainSuffixes returns the only upstream hostname suffixes accepted by the CLI. A hostname must equal a suffix or be 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 KnownDomains added in v0.0.7

func KnownDomains() []string

KnownDomains returns the domains checked by the CLI doctor command.

func ParseAllowedDomain added in v0.0.7

func ParseAllowedDomain(raw string) (string, error)

ParseAllowedDomain validates an HTTPS origin against AllowedDomainSuffixes and returns its normalized origin.

func SendToKindle

func SendToKindle(filePath string, cfg KindleConfig, smtpPassword string) error

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.

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 added in v0.0.7

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 added in v0.0.7

func (e *BotProtectionError) Error() string

func (*BotProtectionError) Unwrap added in v0.0.7

func (e *BotProtectionError) Unwrap() error

type Client

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

func NewClient

func NewClient(opts ...ClientOption) *Client

func (*Client) Cookies

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

func (*Client) DeleteDownloadHistory added in v0.0.9

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) 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) 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) 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) 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) GetProfile added in v0.0.9

func (c *Client) GetProfile() (UserProfile, error)

func (*Client) Login

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

func (*Client) LoginEAPI added in v0.0.7

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

func (*Client) LoginEAPIContext added in v0.0.11

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 added in v0.0.7

func (c *Client) Mode() ClientMode

func (*Client) MostPopularBooks added in v0.0.9

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

MostPopularBooks returns the EAPI most-popular list.

func (*Client) RecommendedBooks added in v0.0.9

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

RecommendedBooks returns the account's recommended books.

func (*Client) SavedBooks added in v0.0.9

func (c *Client) SavedBooks(page int) (SearchResult, error)

SavedBooks returns one page of the account's saved books.

func (*Client) Search

func (c *Client) Search(query string, page, count int, opts *SearchOptions) (SearchResult, error)

func (*Client) SetCookies

func (c *Client) SetCookies(cookies map[string]string)

func (*Client) SetDomain

func (c *Client) SetDomain(domain string)

func (*Client) SetMode added in v0.0.7

func (c *Client) SetMode(mode ClientMode)

type ClientMode added in v0.0.7

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.

type DomainCheck added in v0.0.7

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"`
}

DomainCheck contains the result of a read-only unauthenticated domain probe.

func ProbeDomain added in v0.0.7

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 added in v0.0.7

func ProbeDomainWithOptions(ctx context.Context, domain string, opts DomainProbeOptions) DomainCheck

ProbeDomainWithOptions checks a single domain using opts.

func ProbeDomains added in v0.0.7

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 added in v0.0.7

func ProbeDomainsWithOptions(ctx context.Context, domains []string, opts DomainProbeOptions) []DomainCheck

ProbeDomainsWithOptions checks domains concurrently using opts.

type DomainProbeOptions added in v0.0.7

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 added in v0.0.7

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"`
}

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"`
	DailyReset     string `json:"daily_reset"`
}

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 added in v0.0.7

type HTTPStatusError struct {
	StatusCode int
	URL        string
}

HTTPStatusError describes an unexpected non-success HTTP response.

func (*HTTPStatusError) Error added in v0.0.7

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 added in v0.0.11

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 added in v0.0.9

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.

Directories

Path Synopsis
cmd
zlib command
internal
cli

Jump to

Keyboard shortcuts

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