libmangal

package module
v0.34.2 Latest Latest
Warning

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

Go to latest
Published: Nov 29, 2026 License: Unlicense Imports: 49 Imported by: 4 modules, 31 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.

README

logo depicting a cartoon octopus

libmangal

Go Reference

Warning

The API is not stable and may change at any time.

This is an engine for downloading, managing and tagging manga with native AniList, Kitsu and MyAnimeList integration. A powerful wrapper around anything that implements its Provider interface.

Designed to be the backend for applications such as CLI, TUI, web apps, gRPC server, etc.

Note: This is a fork of mangalorg/libmangal.

Features

  • Skips chapters that are already downloaded, caches metadata lookups.
  • Different export formats:
    • PDF - chapters stored a single PDF file.
    • CBZ - Comic Book ZIP format.
    • EPUB - fixed-layout EPUB 3, one page per image.
    • TAR - TAR archive.
    • TAR.GZ - gzipped TAR archive.
    • ZIP - ZIP archive.
    • Images - a plain directory of images.
  • Optional WebP conversion of the page images.
  • Monolith - no runtime dependencies.
  • Generates metadata files:
    • ComicInfo.xml - The ComicInfo.xml file originates from the ComicRack application, which is not developed anymore. The ComicInfo.xml however is used by a variety of applications.
    • series.json - A JSON file containing metadata about the series. Originates from mylar3.
  • Automatically populates missing metadata by querying AniList, Kitsu, MyAnimeList or MangaUpdates, bad title matches are never used.
  • Syncs reading progress with AniList, Kitsu and MyAnimeList.
  • Finds a manga's directory again when its name changes (title updates, renamed providers, name templates).
  • Providers keep a history of their old ids and names, so old ids still work.
  • Gets a manga by its id without a search, for providers that support it (MangaByIDProvider).
  • Every request can be cancelled with a context.Context, errors can be checked with errors.Is/errors.As.
  • Filesystem abstraction - can be used with any filesystem that implements afero:
    • Remote filesystems.
    • In-memory filesystems.
    • etc.
  • Highly configurable:
    • Define how you want to name your files.
    • Define how you want to organize your files.
    • Define how you want to tag your files.
    • Define how you want to cache your files.
  • Cross-platform - every OS that Go compiles to is supported:
    • Windows
    • Linux
    • MacOS
    • WASM
    • etc.

Install

go get github.com/luevano/libmangal@latest

Providers

See their READMEs for usage examples.

Apps using libmangal

  • mangal - Advanced CLI manga downloader. Lua scrapers, export formats, AniList integration, fancy TUI and more.

Credits

Octopus logo: Octopus icons created by Freepik - Flaticon

Documentation

Index

Constants

View Source
const (
	MangaDirNoMatch = iota
	// MangaDirMetadataMatch shares a metadata id (e.g. the same Anilist manga from another provider).
	MangaDirMetadataMatch
	// MangaDirMangaMatch is the same provider (current or old id) and manga id.
	MangaDirMangaMatch
)

Manga directory matches, from MatchMangaDir.

View Source
const (
	// DefaultPageRetries: How many times a page is tried again after a 429.
	DefaultPageRetries = 3
	// DefaultPageRetryWait: The first wait without Retry-After, doubled each time.
	DefaultPageRetryWait = 5 * time.Second
	// DefaultMaxPageRetryWait caps each wait, Retry-After included.
	DefaultMaxPageRetryWait = time.Minute
	// DefaultMaxPageImageSize: Larger images are an error.
	DefaultMaxPageImageSize int64 = 100 << 20
)

Defaults of FetchPageImageOptions.

View Source
const (
	InvalidPathCharsUNIX    = `/`
	InvalidPathCharsDarwin  = `/:`
	InvalidPathCharsWindows = `<>:"/\|?*`
)

Chars a file name can't have, for SanitizeName (InvalidPathCharsOS is this OS's).

View Source
const DefaultImageQuality = 90

DefaultImageQuality is the quality used when DownloadOptions.ImageQuality is 0.

View Source
const DefaultUserAgent = netutil.BrowserUserAgent

DefaultUserAgent of DefaultClientOptions, a current Firefox (netutil.BrowserUserAgent).

View Source
const FilenameMangaDirInfo = ".libmangal.json"

FilenameMangaDirInfo is the file with the MangaDirInfo written in every manga directory.

View Source
const InvalidPathCharsOS = InvalidPathCharsUNIX

InvalidPathCharsOS are the chars a file name can't have on this OS.

Variables

View Source
var (
	// ErrUnavailable: The chapter can't be downloaded, see mangadata.ChapterInfo.Unavailable.
	ErrUnavailable = errors.New("unavailable")

	// ErrMangaByIDUnsupported: The provider doesn't implement MangaByIDProvider.
	ErrMangaByIDUnsupported = errors.New("manga by id unsupported")

	// ErrInvalidResult: The provider returned something unusable as found (e.g. a manga
	// without an id): the site's reply wasn't what it expected. A failure to retry, not a
	// missing item.
	ErrInvalidResult = errors.New("invalid result")

	// ErrNotImage: A page's content is no image, e.g. a site's HTML error page.
	ErrNotImage = errors.New("not an image")

	// ErrNotFound: The site doesn't have it. Provider errors should match it,
	// metadata.ErrNotFound is the same value (see netutil).
	ErrNotFound = netutil.ErrNotFound

	// ErrRateLimited: The site is rate limiting. Provider errors should match it,
	// metadata.ErrRateLimited is the same value (see netutil, RetryAfter).
	ErrRateLimited = netutil.ErrRateLimited
)

Errors to check with errors.Is.

Functions

func FetchPageImage added in v0.31.0

func FetchPageImage(ctx context.Context, client *http.Client, page PageImageRequest, options FetchPageImageOptions) ([]byte, error)

FetchPageImage gets a page image with a GET, sending the request's headers and cookies. A 429 is tried again (FetchPageImageOptions.Retries), so is a 5xx (but 501), a network error or a body that isn't an image (ErrNotImage, FailureRetries), waiting Retry-After or a doubling wait with jitter; a last 429 is a *netutil.RateLimitError (matches ErrRateLimited) saying how long to wait. Other statuses than 200 are errors, so is an image over MaxSize.

func FindLoader added in v0.22.1

func FindLoader(loaders []ProviderLoader, id string) (ProviderLoader, *ProviderAlias, bool)

FindLoader finds the loader of the provider with the given id, current or old.

Current ids win over old ones (a new provider may reuse an old id). If the id is an old one, the matching History entry is returned too, so callers can warn about it.

func FormatStrings

func FormatStrings() []string

FormatStrings returns a slice of all String values of the enum

func ImageFormatStrings added in v0.34.0

func ImageFormatStrings() []string

ImageFormatStrings returns a slice of all String values of the enum

func MatchMangaDir added in v0.23.0

func MatchMangaDir(provider ProviderInfo, want, have MangaDirInfo) int

MatchMangaDir says how well the info of a directory (have) matches the wanted manga, downloaded with the provider. Higher is better.

func SanitizeName added in v0.26.0

func SanitizeName(name, invalid string, windows bool) string

SanitizeName makes name usable as a single file or directory name: control chars and the invalid ones become underscores (repeated ones collapse), it's capped to 240 bytes, and it's never empty, "." or "..". With windows, trailing dots and spaces go and reserved names (CON, NUL, ...) get a "_" prefix.

func SanitizeNameOS added in v0.32.0

func SanitizeNameOS(name string) string

SanitizeNameOS is SanitizeName for this OS: InvalidPathCharsOS, and the Windows rules on Windows. It's what the default naming options use.

func SplitList added in v0.33.0

func SplitList(value string) []string

SplitList splits a SettingList value into its trimmed, non-empty items.

func WriteMangaDirInfo added in v0.26.0

func WriteMangaDirInfo(fsys afero.Fs, dir string, info MangaDirInfo, mode fs.FileMode) error

WriteMangaDirInfo writes info as the FilenameMangaDirInfo of dir, atomically (a temp file renamed over it), so a crash never leaves a truncated one.

Types

type Account added in v0.24.0

type Account = metadata.Account

Account is a service the user is logged into or subscribed to.

type AccountProvider added in v0.24.0

type AccountProvider interface {
	// Account gets the user's account, found false if the provider has none set up.
	Account(ctx context.Context) (account Account, found bool, err error)
}

AccountProvider is a Provider with a user account (e.g. a subscription).

type ChapterIndex added in v0.24.0

type ChapterIndex interface {
	// FindChapter returns the path of the chapter with the same number in the format,
	// downloaded in mangaDir (by any provider), and the provider id it came from.
	FindChapter(mangaDir string, chapter mangadata.Chapter, format Format) (path, provider string, found bool, err error)
}

ChapterIndex knows the chapters downloaded in each manga directory. See ClientOptions.ChapterIndex.

type ChapterIndexContext added in v0.31.0

type ChapterIndexContext interface {
	ChapterIndex
	FindChapterContext(ctx context.Context, mangaDir string, chapter mangadata.Chapter, format Format) (path, provider string, found bool, err error)
}

ChapterIndexContext is a ChapterIndex whose lookup takes a context, called instead of FindChapter when the ClientOptions.ChapterIndex implements it.

type Client

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

Client is a wrapper around Provider with extended functionality.

It's the core of libmangal.

func NewClient

func NewClient(loader ProviderLoader, options ClientOptions) (*Client, error)

NewClient creates a new client from given ProviderLoader.

ClientOptions must be non-zero. Use DefaultClientOptions for defaults. It will validate ProviderLoader.Info and load the provider.

func NewClientContext added in v0.22.0

func NewClientContext(
	ctx context.Context,
	loader ProviderLoader,
	options ClientOptions,
) (*Client, error)

NewClientContext is NewClient with a context.

func (*Client) Account added in v0.24.0

func (c *Client) Account() (Account, bool, error)

Account gets the account of the provider, found false if it has none.

func (*Client) AccountContext added in v0.24.0

func (c *Client) AccountContext(ctx context.Context) (Account, bool, error)

AccountContext is Account with a context.

func (*Client) ChapterDir added in v0.22.1

func (c *Client) ChapterDir(chapter mangadata.Chapter, options DownloadOptions) (string, error)

ChapterDir returns the directory the chapter is (or would be) downloaded to with the options, including a reused manga directory (DownloadOptions.ReuseMangaDir).

func (*Client) ChapterDirContext added in v0.31.0

func (c *Client) ChapterDirContext(ctx context.Context, chapter mangadata.Chapter, options DownloadOptions) (string, error)

ChapterDirContext is ChapterDir with a context, passed to the ClientOptions.MangaDirIndex.

func (*Client) ChapterName added in v0.17.2

func (c *Client) ChapterName(chapter mangadata.Chapter, format Format) string

ChapterName determines the chapter file name. E.g. "[001] chapter 1" or "Chainsaw Man - Ch. 1"

func (*Client) ChapterPages

func (c *Client) ChapterPages(chapter mangadata.Chapter) ([]mangadata.Page, error)

ChapterPages gets pages of the given chapter.

func (*Client) ChapterPagesContext added in v0.22.0

func (c *Client) ChapterPagesContext(ctx context.Context, chapter mangadata.Chapter) ([]mangadata.Page, error)

ChapterPagesContext is ChapterPages with a context. A mangadata.WrappedChapter's pages are its provider's chapter's.

func (*Client) Close

func (c *Client) Close() error

func (*Client) DownloadChapter

func (c *Client) DownloadChapter(chapter mangadata.Chapter, options DownloadOptions) (*metadata.DownloadedChapter, error)

DownloadChapter downloads and writes chapter to disk with the given DownloadOptions.

It will return resulting chapter download information via metadata.DownloadedChapter.

func (*Client) DownloadChapterContext added in v0.22.0

func (c *Client) DownloadChapterContext(
	ctx context.Context,
	chapter mangadata.Chapter,
	options DownloadOptions,
) (*metadata.DownloadedChapter, error)

DownloadChapterContext is DownloadChapter with a context.

func (*Client) DownloadPage

func (c *Client) DownloadPage(page mangadata.Page) (mangadata.PageWithImage, error)

DownloadPage downloads a page contents (image), an ErrNotImage when the provider got something else (e.g. an HTML error page).

func (*Client) DownloadPageContext added in v0.22.0

func (c *Client) DownloadPageContext(
	ctx context.Context,
	page mangadata.Page,
) (mangadata.PageWithImage, error)

DownloadPageContext is DownloadPage with a context.

func (*Client) DownloadPagesInBatch

func (c *Client) DownloadPagesInBatch(pages []mangadata.Page) ([]mangadata.PageWithImage, error)

DownloadPagesInBatch downloads multiple pages in batch by calling DownloadPage for each page, ClientOptions.ConcurrentPages at a time.

If any of the pages fails to download it will stop downloading other pages and return error immediately.

func (*Client) DownloadPagesInBatchContext added in v0.22.0

func (c *Client) DownloadPagesInBatchContext(
	ctx context.Context,
	pages []mangadata.Page,
) ([]mangadata.PageWithImage, error)

DownloadPagesInBatchContext is DownloadPagesInBatch with a context.

func (*Client) FS

func (c *Client) FS() afero.Fs

FS returns the client's FileSystem.

func (*Client) GetMetadataProvider added in v0.20.0

func (c *Client) GetMetadataProvider(id metadata.IDSource) (*metadata.ProviderWithCache, error)

GetMetadataProvider returns the requested metadata Provider for the given id.

func (*Client) Info

func (c *Client) Info() ProviderInfo

Info returns info about provider.

func (*Client) Logger

func (c *Client) Logger() *logger.Logger

Logger returns the client's Logger.

func (*Client) MangaByID added in v0.27.0

func (c *Client) MangaByID(id string) (mangadata.Manga, bool, error)

MangaByID gets the manga with the given id (mangadata.MangaInfo.ID), the same manga a search would return.

found is false, with a nil error, when there is no such manga. If the provider doesn't implement MangaByIDProvider the error matches ErrMangaByIDUnsupported, if it found a manga without an id or title it matches ErrInvalidResult.

func (*Client) MangaByIDContext added in v0.27.0

func (c *Client) MangaByIDContext(ctx context.Context, id string) (mangadata.Manga, bool, error)

MangaByIDContext is MangaByID with a context.

func (*Client) MangaName added in v0.17.2

func (c *Client) MangaName(manga mangadata.Manga) string

MangaName determines the manga directory name.

func (*Client) MangaVolumes

func (c *Client) MangaVolumes(manga mangadata.Manga) ([]mangadata.Volume, error)

MangaVolumes gets volumes of the given manga.

func (*Client) MangaVolumesContext added in v0.22.0

func (c *Client) MangaVolumesContext(ctx context.Context, manga mangadata.Manga) ([]mangadata.Volume, error)

MangaVolumesContext is MangaVolumes with a context.

func (*Client) MatchManga added in v0.22.1

func (c *Client) MatchManga(provider *metadata.ProviderWithCache, manga mangadata.Manga) (metadata.Match, bool, error)

MatchManga finds the metadata that best matches the manga, even a bad match (metadata.Match.Bad) so it can be shown to the user, never used automatically.

Tries to search manga metadata in the following order:

1. If the manga contains non-nil metadata, by its metadata IDs if available (a bound match).

2. If the manga title is bound to a metadata ID (a bound match).

3. The closest search result (metadata.ProviderWithCache.FindClosest) for the manga title, then the alternate titles of its metadata.

func (*Client) MatchMangaContext added in v0.22.1

func (c *Client) MatchMangaContext(
	ctx context.Context,
	provider *metadata.ProviderWithCache,
	manga mangadata.Manga,
) (metadata.Match, bool, error)

MatchMangaContext is MatchManga with a context.

func (*Client) MatchMangas added in v0.23.0

func (c *Client) MatchMangas(provider *metadata.ProviderWithCache, mangas []mangadata.Manga) ([]metadata.Match, []bool, error)

MatchMangas is MatchManga for several mangas, with as few requests as possible (see metadata.ProviderWithCache.FindClosestMany).

func (*Client) MatchMangasContext added in v0.23.0

func (c *Client) MatchMangasContext(
	ctx context.Context,
	provider *metadata.ProviderWithCache,
	mangas []mangadata.Manga,
) ([]metadata.Match, []bool, error)

MatchMangasContext is MatchMangas with a context.

func (*Client) ProviderName added in v0.17.2

func (c *Client) ProviderName(provider ProviderInfo) string

ProviderName determines the provider directory name.

Names from ClientOptions that aren't a single path element (empty, ".", "..", or with a path separator) are sanitized with SanitizeName, for all the name methods.

func (*Client) ReadChapter

func (c *Client) ReadChapter(path string, chapter mangadata.Chapter, options ReadOptions) error

ReadChapter opens the chapter for reading and marks it as read if authorized. It will use os default app for resulting mimetype.

E.g. `xdg-open` for Linux.

It will also set the reading progress on Anilist, MyAnimeList and Kitsu if enabled in the ReadOptions.

Note, that underlying filesystem must be mapped with OsFs in order for os to open it. Failing to open it is an *OpenError.

func (*Client) ReadChapterContext added in v0.22.0

func (c *Client) ReadChapterContext(
	ctx context.Context,
	path string,
	chapter mangadata.Chapter,
	options ReadOptions,
) error

ReadChapterContext is ReadChapter with a context.

func (*Client) SearchByManga added in v0.20.0

func (c *Client) SearchByManga(provider *metadata.ProviderWithCache, manga mangadata.Manga) (metadata.Metadata, bool, error)

SearchByManga is a convenience method to search given a Manga. It's meant to be used by the SearchMetadata method.

It's MatchManga, but only good matches (see metadata.Match.Bad) count as found.

func (*Client) SearchByMangaContext added in v0.22.0

func (c *Client) SearchByMangaContext(
	ctx context.Context,
	provider *metadata.ProviderWithCache,
	manga mangadata.Manga,
) (metadata.Metadata, bool, error)

SearchByMangaContext is SearchByManga with a context.

func (*Client) SearchMangas

func (c *Client) SearchMangas(query string) ([]mangadata.Manga, error)

SearchMangas searches for mangas with the given query.

func (*Client) SearchMangasContext added in v0.22.0

func (c *Client) SearchMangasContext(ctx context.Context, query string) ([]mangadata.Manga, error)

SearchMangasContext is SearchMangas with a context.

func (*Client) SearchMetadata added in v0.16.0

func (c *Client) SearchMetadata(manga mangadata.Manga) (metadata.Metadata, error)

SearchMetadata will search for metadata on the available metadata providers, in the order they were set, returning the first found.

Tries to search manga metadata in the following order:

1. If the manga contains non-nil metadata, by its metadata ID if available.

2. If the manga Title field is binded to a metadata ID.

3. Find closest manga metadata (FindClosest) by using the manga Title field.

func (*Client) SearchMetadataContext added in v0.22.0

func (c *Client) SearchMetadataContext(
	ctx context.Context,
	manga mangadata.Manga,
) (metadata.Metadata, error)

SearchMetadataContext is SearchMetadata with a context.

func (*Client) SetMetadataProvider added in v0.20.1

func (c *Client) SetMetadataProvider(provider *metadata.ProviderWithCache) error

SetMetadataProvider will add or update the given metadata Provider.

The provider keeps its own logger (ProviderWithCache.SetLogger), it may be shared by several clients.

func (*Client) String

func (c *Client) String() string

func (*Client) VolumeChapters

func (c *Client) VolumeChapters(volume mangadata.Volume) ([]mangadata.Chapter, error)

VolumeChapters gets chapters of the given volume.

func (*Client) VolumeChaptersContext added in v0.22.0

func (c *Client) VolumeChaptersContext(ctx context.Context, volume mangadata.Volume) ([]mangadata.Chapter, error)

VolumeChaptersContext is VolumeChapters with a context.

func (*Client) VolumeName added in v0.17.2

func (c *Client) VolumeName(volume mangadata.Volume) string

VolumeName determines the volume directory name. E.g. "Vol. 1" or "Volume 1"

type ClientOptions

type ClientOptions struct {
	// HTTPClient is http client that client would use for requests
	// (netutil.NewClient by default, with netutil.DefaultTimeout).
	HTTPClient *http.Client

	// UserAgent to use when making HTTP requests.
	UserAgent string

	// FS is a file system abstraction that the client will use.
	FS afero.Fs

	// ModeDir is the permission bits used for all dirs created.
	ModeDir fs.FileMode

	// ModeFile is the permission bits used for all files created.
	ModeFile fs.FileMode

	// ChapterIndex is asked whether a manga directory already has the chapter (by number,
	// in the format), so it isn't downloaded again under another name, e.g. from another
	// provider. Optional, used when DownloadOptions.SkipIfExists is set.
	ChapterIndex ChapterIndex

	// MangaDirIndex is asked for the directory of a manga before scanning the MangaDirInfo
	// files (DownloadOptions.ReuseMangaDir), and told the downloaded ones. Optional; one
	// implementing MangaDirInfoIndex also adds to the MangaDirInfo a download writes.
	MangaDirIndex MangaDirIndex

	// ConcurrentPages is how many pages of a chapter are downloaded at the same time.
	// Zero or less means no limit.
	ConcurrentPages int

	// ProviderName determines the provider directory name.
	ProviderName func(
		provider ProviderInfo,
	) string

	// MangaName determines the manga directory name.
	MangaName func(
		provider ProviderInfo,
		manga mangadata.Manga,
	) string

	// VolumeName determines the volume directory name.
	// E.g. "Vol. 1" or "Volume 1"
	VolumeName func(
		provider ProviderInfo,
		volume mangadata.Volume,
	) string

	// ChapterName determines the chapter file name.
	// E.g. "[001] chapter 1" or "Chainsaw Man - Ch. 1"
	ChapterName func(
		provider ProviderInfo,
		chapter mangadata.Chapter,
	) string
}

ClientOptions is options that client would use during its runtime.

func DefaultClientOptions

func DefaultClientOptions() ClientOptions

DefaultClientOptions constructs default ClientOptions, with default Anilist options as well.

type DownloadOptions

type DownloadOptions struct {
	// Format in which a chapter must be downloaded.
	Format Format

	// Directory is the directory where manga will be downloaded to.
	Directory string

	// CreateProviderDir will create provider directory.
	CreateProviderDir bool

	// CreateMangaDir will create manga directory.
	CreateMangaDir bool

	// ReuseMangaDir will download into the directory that already has the manga (see
	// MangaDirInfo) instead of a new one when the manga directory name changes (title
	// updates, renamed providers, name template changes). Needs CreateMangaDir.
	ReuseMangaDir bool

	// CreateVolumeDir will create volume directory.
	//
	// If CreateMangaDir is also true, volume directory
	// will be created under it.
	CreateVolumeDir bool

	// Strict means that if the metadata search fails, the metadata is invalid or if an
	// error occurs during metadata files creation, the chapter will not be written to disk.
	// Without it, a failed search is logged and the chapter is downloaded without metadata.
	//
	// Some metadata is potentially written to disk.
	Strict bool

	// SkipIfExists will skip downloading chapter if its already downloaded (exists at path).
	//
	// However, metadata will still be created if needed.
	SkipIfExists bool

	// SearchMetadata will search for metadata on the available metadata providers,
	// and use the found metadata regardless of the incoming manga metadata which
	// could result in `nil` metadata when not found.
	//
	// Search priority is always by ID (if provided as part of one of the metadata fields), then by the title.
	SearchMetadata bool

	// DownloadMangaCover or not. Will not download cover again if its already downloaded.
	DownloadMangaCover bool

	// DownloadMangaBanner or not. Will not download banner again if its already downloaded.
	DownloadMangaBanner bool

	// WriteSeriesJSON write metadata series.json file in the manga directory.
	WriteSeriesJSON bool

	// SkipSeriesJSONIfOngoing will avoid writing series.json file for ongoing series,
	// due to lack of TotalIssues metadata provided by Anilist for example.
	//
	// There are issues with _some_ parsers when the TotalIssues is zero (I see you, Komga),
	// so this is a workaround. Also this avoids checks to overwrite series.json on each chapter,
	// silly, no (if only Komga would fix that)?
	SkipSeriesJSONIfOngoing bool

	// WriteComicInfoXML write metadata ComicInfo.xml file to the .cbz archive when
	// downloading with FormatCBZ.
	WriteComicInfoXML bool

	// ComicInfoXMLOptions options to use for ComicInfo.xml when WriteComicInfoXml is true.
	ComicInfoXMLOptions metadata.ComicInfoXMLOptions

	// ImageTransformer is applied for each image for the chapter.
	//
	// E.g. grayscale effect. Nil leaves the images as they are. WebP pages come as they are:
	// Go's decoders return them as limited-range YCbCr, read as full range the blacks wash
	// out when encoded again; gen2brain/vpx's webp.Decode with Options.ToRGBA converts them
	// right.
	ImageTransformer func([]byte) ([]byte, error)

	// ImageFormat the page images are saved as (after ImageTransformer), the zero value is
	// ImageFormatOriginal. Ignored for FormatPDF (the PDF would hold them decoded again).
	// A page keeps its original bytes when it already is WebP, can't be converted, or the
	// WebP wouldn't be smaller.
	ImageFormat ImageFormat

	// ImageQuality of the ImageFormat conversion, 1 to 100, 0 is DefaultImageQuality.
	ImageQuality int

	// OnProgress, if not nil, is called as the chapter download goes: at each stage, and
	// after each page image. Calls don't overlap.
	OnProgress func(DownloadProgress)
}

DownloadOptions configures Chapter downloading.

func DefaultDownloadOptions

func DefaultDownloadOptions() DownloadOptions

DefaultDownloadOptions constructs default DownloadOptions.

type DownloadProgress added in v0.29.0

type DownloadProgress struct {
	Chapter mangadata.Chapter
	Stage   DownloadStage
	// Done and Total count the page images (DownloadStageImages, and Total from then on).
	Done, Total int
}

DownloadProgress is where a chapter download is, see DownloadOptions.OnProgress.

type DownloadStage added in v0.29.0

type DownloadStage string

DownloadStage is a step of a chapter download.

const (
	// DownloadStageMetadata: searching the manga's metadata (DownloadOptions.SearchMetadata).
	DownloadStageMetadata DownloadStage = "metadata"
	// DownloadStagePages: getting the chapter's list of pages.
	DownloadStagePages DownloadStage = "pages"
	// DownloadStageImages: downloading the page images, Done of Total.
	DownloadStageImages DownloadStage = "images"
	// DownloadStageSaving: writing the chapter and its metadata files.
	DownloadStageSaving DownloadStage = "saving"
)

type FetchPageImageOptions added in v0.31.0

type FetchPageImageOptions struct {
	// Retries after a 429, DefaultPageRetries if 0, none if negative.
	Retries int

	// FailureRetries after a 5xx (but 501), a network error or a body that isn't an image
	// (ErrNotImage), Retries if 0, none if negative: a provider with other servers to try,
	// or a client retrying 5xx itself, passes -1.
	FailureRetries int

	// RetryWait is the first wait without Retry-After, doubled each time (each wait
	// jittered by up to half of it either way), DefaultPageRetryWait if 0.
	RetryWait time.Duration

	// MaxRetryWait caps each wait, DefaultMaxPageRetryWait if 0.
	MaxRetryWait time.Duration

	// MaxSize of the image, DefaultMaxPageImageSize if 0.
	MaxSize int64

	// OnRetry is called before each wait after a 429 (retry counts from 1). Other retries
	// are reported with progress.Report.
	OnRetry func(retry int, wait time.Duration)

	// StatusError makes the error of a response other than 200 and 429 (its body is closed
	// after), a 5xx's is still retried. Nil gives "GET <url>: 404 not found".
	StatusError func(request *http.Request, response *http.Response) error
}

FetchPageImageOptions of FetchPageImage, the zero value takes the defaults.

type FilterOptions added in v0.30.0

type FilterOptions struct {
	// NSFW if the manga results can contain NSFW content.
	//
	// Only if the source allows to filter by NSFW.
	NSFW bool

	// Language of the manga and chapter results, e.g. "en", empty for any language.
	//
	// Only if the source allows to filter by language.
	Language string

	// AvoidDuplicateChapters keeps only one chapter per number.
	AvoidDuplicateChapters bool

	// ShowUnavailableChapters also shows chapters that can't be downloaded,
	// such as ones hosted on external sites (MangaDex chapters on MangaPlus).
	ShowUnavailableChapters bool

	// ShowRetiredChapters also lists chapters the source took down but still
	// knows about (MangaDex's unavailable chapters), shown as unavailable.
	ShowRetiredChapters bool
}

FilterOptions are the user's filters, providers should respect them when the source supports it.

func DefaultFilterOptions added in v0.30.0

func DefaultFilterOptions() FilterOptions

DefaultFilterOptions constructs FilterOptions that filter nothing: NSFW included, any language, duplicate, unavailable and retired chapters kept.

func (*FilterOptions) String added in v0.30.0

func (f *FilterOptions) String() string

String is a stable representation of the filters, e.g. for cache keys.

type Format

type Format uint8

Format is the format for saving chapters

const (
	// FormatPDF saves chapter as a PDF document
	FormatPDF Format = iota + 1

	// FormatImages saves chapter as a directory of plain images
	FormatImages

	// FormatCBZ saves chapter as CBZ archive.
	// CBZ stands for Comic Book Zip format.
	// Common among comic readers
	FormatCBZ

	// FormatTAR saves chapter images as tar archive
	FormatTAR

	// FormatTARGZ saves chapter images tar.gz archive
	FormatTARGZ

	// FormatZIP save chapter images as zip archive
	FormatZIP

	// FormatEPUB saves chapter as a fixed-layout EPUB 3, one page per image, with the
	// manga metadata (when valid) in its package document.
	FormatEPUB
)

func FormatOf added in v0.32.0

func FormatOf(name string) (Format, bool)

FormatOf is the format of a chapter file by its name's extension (any case), the inverse of Format.Extension. FormatImages (a directory) has none, so it's never found.

func FormatString

func FormatString(s string) (Format, error)

FormatString retrieves an enum value from the enum constants string name. Throws an error if the param is not part of the enum.

func FormatValues

func FormatValues() []Format

FormatValues returns all values of the enum

func (Format) Extension

func (f Format) Extension() string

Extension returns extension of the format with the leading dot.

func (Format) IsAFormat

func (i Format) IsAFormat() bool

IsAFormat returns "true" if the value is listed in the enum definition. "false" otherwise

func (Format) MarshalJSON

func (i Format) MarshalJSON() ([]byte, error)

MarshalJSON implements the json.Marshaler interface for Format

func (Format) MarshalText

func (i Format) MarshalText() ([]byte, error)

MarshalText implements the encoding.TextMarshaler interface for Format

func (Format) MarshalYAML

func (i Format) MarshalYAML() (interface{}, error)

MarshalYAML implements a YAML Marshaler for Format

func (Format) String

func (i Format) String() string

func (*Format) UnmarshalJSON

func (i *Format) UnmarshalJSON(data []byte) error

UnmarshalJSON implements the json.Unmarshaler interface for Format

func (*Format) UnmarshalText

func (i *Format) UnmarshalText(text []byte) error

UnmarshalText implements the encoding.TextUnmarshaler interface for Format

func (*Format) UnmarshalYAML

func (i *Format) UnmarshalYAML(unmarshal func(interface{}) error) error

UnmarshalYAML implements a YAML Unmarshaler for Format

type ImageFormat added in v0.34.0

type ImageFormat uint8

ImageFormat is what the page images are saved as, whatever the chapter's Format.

const (
	// ImageFormatOriginal keeps the page images as the provider gave them.
	ImageFormatOriginal ImageFormat = iota

	// ImageFormatWebP converts the page images to lossy WebP.
	ImageFormatWebP
)

func ImageFormatString added in v0.34.0

func ImageFormatString(s string) (ImageFormat, error)

ImageFormatString retrieves an enum value from the enum constants string name. Throws an error if the param is not part of the enum.

func ImageFormatValues added in v0.34.0

func ImageFormatValues() []ImageFormat

ImageFormatValues returns all values of the enum

func (ImageFormat) IsAImageFormat added in v0.34.0

func (i ImageFormat) IsAImageFormat() bool

IsAImageFormat returns "true" if the value is listed in the enum definition. "false" otherwise

func (ImageFormat) MarshalJSON added in v0.34.0

func (i ImageFormat) MarshalJSON() ([]byte, error)

MarshalJSON implements the json.Marshaler interface for ImageFormat

func (ImageFormat) MarshalText added in v0.34.0

func (i ImageFormat) MarshalText() ([]byte, error)

MarshalText implements the encoding.TextMarshaler interface for ImageFormat

func (ImageFormat) MarshalYAML added in v0.34.0

func (i ImageFormat) MarshalYAML() (interface{}, error)

MarshalYAML implements a YAML Marshaler for ImageFormat

func (ImageFormat) String added in v0.34.0

func (i ImageFormat) String() string

func (*ImageFormat) UnmarshalJSON added in v0.34.0

func (i *ImageFormat) UnmarshalJSON(data []byte) error

UnmarshalJSON implements the json.Unmarshaler interface for ImageFormat

func (*ImageFormat) UnmarshalText added in v0.34.0

func (i *ImageFormat) UnmarshalText(text []byte) error

UnmarshalText implements the encoding.TextUnmarshaler interface for ImageFormat

func (*ImageFormat) UnmarshalYAML added in v0.34.0

func (i *ImageFormat) UnmarshalYAML(unmarshal func(interface{}) error) error

UnmarshalYAML implements a YAML Unmarshaler for ImageFormat

type MangaByIDProvider added in v0.27.0

type MangaByIDProvider interface {
	// MangaByID gets the manga with the given id, the same manga a search would return.
	//
	// found is false, with a nil error, when there is no such manga.
	MangaByID(ctx context.Context, id string) (manga mangadata.Manga, found bool, err error)
}

MangaByIDProvider is an optional interface for providers that can get a manga by its id (mangadata.MangaInfo.ID) without a search.

type MangaDirIndex added in v0.23.0

type MangaDirIndex interface {
	// FindMangaDir returns the name of the directory under parent with the manga,
	// matching like MatchMangaDir.
	FindMangaDir(parent string, provider ProviderInfo, info MangaDirInfo) (name string, found bool, err error)

	// RememberMangaDir records the manga of the directory parent/name.
	RememberMangaDir(parent, name string, info MangaDirInfo) error
}

MangaDirIndex is an index of the downloaded mangas' directories kept by the application (e.g. in a database), asked before scanning the MangaDirInfo files. See ClientOptions.MangaDirIndex.

type MangaDirIndexContext added in v0.31.0

type MangaDirIndexContext interface {
	MangaDirIndex
	FindMangaDirContext(ctx context.Context, parent string, provider ProviderInfo, info MangaDirInfo) (name string, found bool, err error)
	RememberMangaDirContext(ctx context.Context, parent, name string, info MangaDirInfo) error
}

MangaDirIndexContext is a MangaDirIndex whose lookups take a context (e.g. a database query that can be cancelled). The client calls these instead when the ClientOptions.MangaDirIndex implements it; the plain methods should call them with context.Background().

type MangaDirInfo added in v0.22.1

type MangaDirInfo struct {
	// Provider is the ID of the provider the manga was last downloaded from.
	Provider string `json:"provider"`

	// Manga is the provider's manga.
	Manga mangadata.MangaInfo `json:"manga"`

	// MetadataIDs are the ids of the manga's metadata, other than the provider's own
	// (e.g. its Anilist id).
	MetadataIDs []metadata.ID `json:"metadata_ids,omitempty"`
}

MangaDirInfo identifies the manga downloaded in a directory, so the directory is found again when the name it would get changes (title updates, renamed providers, name template changes). See DownloadOptions.ReuseMangaDir.

func NewMangaDirInfo added in v0.32.4

func NewMangaDirInfo(provider ProviderInfo, manga mangadata.Manga) MangaDirInfo

NewMangaDirInfo is the MangaDirInfo a download of the provider's manga writes.

func ReadMangaDirInfo added in v0.22.1

func ReadMangaDirInfo(fsys afero.Fs, dir string) (MangaDirInfo, error)

ReadMangaDirInfo reads the MangaDirInfo of a manga directory.

func (*MangaDirInfo) AddMetadataIDs added in v0.34.0

func (info *MangaDirInfo) AddMetadataIDs(ids ...metadata.ID)

AddMetadataIDs adds the ids of the sources info has no id of (e.g. those its directory's MangaDirInfo had before a download, see MangaDirInfoIndex).

type MangaDirInfoIndex added in v0.34.0

type MangaDirInfoIndex interface {
	MangaDirIndex
	MangaDirInfoContext(ctx context.Context, parent, name string, info MangaDirInfo) (MangaDirInfo, error)
}

MangaDirInfoIndex is a MangaDirIndex that knows more of a manga than its download (e.g. metadata ids bound by hand): a download writes the MangaDirInfo it returns for the directory parent/name, given the one it would write (NewMangaDirInfo, plus the ids of other sources the directory's MangaDirInfo had). The client calls it when the ClientOptions.MangaDirIndex implements it.

type OpenError added in v0.30.0

type OpenError struct {
	Path string
	Err  error
}

OpenError: Client.ReadChapter couldn't open the file with the default app, so no reading progress was set.

func (*OpenError) Error added in v0.30.0

func (e *OpenError) Error() string

func (*OpenError) Unwrap added in v0.30.0

func (e *OpenError) Unwrap() error

type PageImageRequest added in v0.31.0

type PageImageRequest struct {
	URL     string
	Headers map[string]string
	Cookies map[string]string
}

PageImageRequest is what FetchPageImage gets: a page image URL with the headers and cookies the site wants. Without an Accept header, FetchPageImage sends imageAccept.

type Provider

type Provider interface {
	fmt.Stringer
	io.Closer

	// Info information about Provider.
	Info() ProviderInfo

	// SetLogger sets logger to use for this provider.
	SetLogger(*logger.Logger)

	// SearchMangas searches for mangas with the given query.
	//
	// Implementation should utilize given logger.
	SearchMangas(
		ctx context.Context,
		query string,
	) ([]mangadata.Manga, error)

	// MangaVolumes gets volumes of the manga.
	//
	// Implementation should utilize given logger.
	MangaVolumes(
		ctx context.Context,
		manga mangadata.Manga,
	) ([]mangadata.Volume, error)

	// VolumeChapters gets chapters of the given volume.
	//
	// Implementation should utilize given logger.
	VolumeChapters(
		ctx context.Context,
		volume mangadata.Volume,
	) ([]mangadata.Chapter, error)

	// ChapterPages gets pages of the given chapter.
	//
	// Implementation should utilize given logger
	ChapterPages(
		ctx context.Context,
		chapter mangadata.Chapter,
	) ([]mangadata.Page, error)

	// GetPageImage gets raw image contents of the given page.
	//
	// Implementation should utilize given logger.
	GetPageImage(
		ctx context.Context,
		page mangadata.Page,
	) ([]byte, error)
}

Provider exposes methods for searching mangas, getting chapters, pages and images.

type ProviderAlias added in v0.22.1

type ProviderAlias struct {
	// ID the provider had. Non-empty.
	ID string `json:"id"`

	// Name the provider had. May be empty if only the ID changed.
	Name string `json:"name,omitempty"`

	// Website the provider had. May be empty.
	Website string `json:"website,omitempty"`
}

ProviderAlias is a previous identity of a provider.

type ProviderInfo

type ProviderInfo struct {
	// ID is the unique identifier of the provider.
	ID string `json:"id"`

	// Name is the non-empty name of the provider.
	Name string `json:"name"`

	// Version is a semantic version of the provider.
	//
	// "v" prefix is not permitted.
	// E.g. "0.1.0" is valid, but "v0.1.0" is not.
	//
	// See https://semver.org/
	Version string `json:"version"`

	// Description of the provider. May be empty.
	Description string `json:"description"`

	// Website of the provider. May be empty.
	Website string `json:"website"`

	// Icon is the url of the site's icon. May be empty, then the website's
	// /favicon.ico is used.
	Icon string `json:"icon,omitempty"`

	// Mirrors are other websites serving the same content, tried when Website is down.
	// Absolute http(s) urls. May be empty.
	Mirrors []string `json:"mirrors,omitempty"`

	// History of previous ids, names and websites, newest first. May be empty.
	//
	// Sites move or get renamed; the current ID, Name and Website are the ones to use,
	// every entry here is deprecated. An entry may keep the current ID when only the
	// name or website changed.
	History []ProviderAlias `json:"history,omitempty"`

	// Settings the user may change for this provider, shown and stored by the app, which
	// hands the values back through the loader's SettingsFunc. May be empty.
	Settings []ProviderSetting `json:"settings,omitempty"`

	// Traits tell the app how to treat the provider.
	Traits ProviderTraits `json:"traits,omitzero"`
}

ProviderInfo is the passport of the provider.

func (ProviderInfo) Alias added in v0.22.1

func (p ProviderInfo) Alias(id string) (ProviderAlias, bool)

Alias returns the newest History entry with the given old id, false if the id is the current one or unknown.

func (ProviderInfo) Matches added in v0.22.1

func (p ProviderInfo) Matches(id string) bool

Matches reports whether id is the provider's current ID or one in its History.

func (ProviderInfo) Setting added in v0.33.0

func (p ProviderInfo) Setting(key string) (ProviderSetting, bool)

Setting returns the provider's setting with the given key.

func (ProviderInfo) SettingValues added in v0.33.0

func (p ProviderInfo) SettingValues(set map[string]string) (map[string]string, error)

SettingValues returns a value for every declared setting: the one in set if there is one, else its Default. Values in set are checked; keys in set the provider doesn't declare are ignored (they may belong to a setting it no longer has).

func (ProviderInfo) Validate

func (p ProviderInfo) Validate() error

Validate checks if the ProviderInfo is valid. This means that ID and Name are non-empty, Version is a valid semver, Icon and every Mirror are absolute http(s) urls, every History entry has an ID and every Setting is valid (see ProviderSetting.Validate) with a unique Key.

type ProviderLoader

type ProviderLoader interface {
	fmt.Stringer

	// Info information about Provider.
	Info() ProviderInfo

	// Load loads the Provider.
	Load(ctx context.Context) (Provider, error)
}

ProviderLoader gives information about provider without loading it first.

type ProviderSetting added in v0.33.0

type ProviderSetting struct {
	// Key of the setting, unique in the provider: lowercase letters, digits and "_",
	// starting with a letter. E.g. "data_saver".
	Key string `json:"key"`

	// Name shown to the user. May be empty, then Key is shown.
	Name string `json:"name,omitempty"`

	// Description of what the setting does. May be empty.
	Description string `json:"description,omitempty"`

	// Kind of the value.
	Kind SettingKind `json:"kind"`

	// Default value, as text. Must be valid for Kind (empty is valid for every kind but
	// bool, int, duration and enum).
	Default string `json:"default,omitempty"`

	// Values are the choices of a SettingEnum, non-empty for it. Unused by other kinds.
	Values []string `json:"values,omitempty"`

	// Warning shown when the user changes the setting, e.g. a risk to the account. May be
	// empty.
	Warning string `json:"warning,omitempty"`
}

ProviderSetting is a setting the user may change for a provider. The provider declares it, the app stores, shows and validates it, and hands the values back (SettingsFunc).

func (ProviderSetting) Check added in v0.33.0

func (s ProviderSetting) Check(value string) error

Check reports whether value is valid for the setting's Kind.

func (ProviderSetting) Validate added in v0.33.0

func (s ProviderSetting) Validate() error

Validate checks the setting's Key, Kind, Values and Default.

type ProviderTraits added in v0.33.0

type ProviderTraits struct {
	// PartialChapters: the provider lists only some of a manga's chapters (e.g. the first
	// and latest), so a library having more isn't a sign of a wrong match.
	PartialChapters bool `json:"partial_chapters,omitempty"`

	// AvoidUnattended: background jobs (maintenance checks) shouldn't make requests to it
	// unless the user turns them on, e.g. because of an account lockout risk. Watches the
	// user set up are not unattended.
	AvoidUnattended bool `json:"avoid_unattended,omitempty"`
}

ProviderTraits tell the app how to treat the provider. All false by default.

type ReadOptions

type ReadOptions struct {
	// SaveAnilist will set the Anilist reading progress, needs to be logged in.
	SaveAnilist bool

	// SaveMyAnimeList will set the MyAnimeList reading progress, needs to be logged in.
	SaveMyAnimeList bool

	// SaveKitsu will set the Kitsu reading progress, needs to be logged in.
	SaveKitsu bool
}

ReadOptions configures the reader options.

func DefaultReadOptions

func DefaultReadOptions() ReadOptions

DefaultReadOptions constructs default ReadOptions.

type SettingKind added in v0.33.0

type SettingKind string

SettingKind is the type of a ProviderSetting's value. Values are always text, as in a config file.

const (
	// SettingBool is "true" or "false" (strconv.ParseBool).
	SettingBool SettingKind = "bool"
	// SettingString is any text.
	SettingString SettingKind = "string"
	// SettingInt is a whole number.
	SettingInt SettingKind = "int"
	// SettingDuration is a Go duration, e.g. "500ms".
	SettingDuration SettingKind = "duration"
	// SettingEnum is one of the setting's Values.
	SettingEnum SettingKind = "enum"
	// SettingList is comma-separated items, see SplitList.
	SettingList SettingKind = "list"
	// SettingPath is a file or directory path.
	SettingPath SettingKind = "path"
	// SettingSecret is text the app keeps with its secrets and never shows.
	SettingSecret SettingKind = "secret"
)

type SettingsFunc added in v0.33.0

type SettingsFunc func(providerID string) map[string]string

SettingsFunc returns the values the user set for a provider's settings, by key; keys not in it get their defaults, nil means all defaults. Providers' loader options take one and call it when the provider loads; the app decides where values come from.

Directories

Path Synopsis
internal/ratelimit
Package ratelimit has the rate limit handling shared by the metadata providers.
Package ratelimit has the rate limit handling shared by the metadata providers.
internal/session
Package session is the login of a metadata provider: searches read it while Login and Logout change it from another goroutine (a long-running mangal serve).
Package session is the login of a metadata provider: searches read it while Login and Logout change it from another goroutine (a long-running mangal serve).
mangaupdates
Package mangaupdates is a metadata.Provider for MangaUpdates (Baka-Updates Manga), read only: search and series by id, no login or reading progress.
Package mangaupdates is a metadata.Provider for MangaUpdates (Baka-Updates Manga), read only: search and series by id, no login or reading progress.
Package netutil has the HTTP basics shared by libmangal, its metadata providers and the manga providers: default timeout and user agents, Retry-After parsing, request logging with redaction (LoggingTransport) and the error sentinels every provider error should match.
Package netutil has the HTTP basics shared by libmangal, its metadata providers and the manga providers: default timeout and user agents, Retry-After parsing, request logging with redaction (LoggingTransport) and the error sentinels every provider error should match.
Package progress carries a status reporter in a context, so long work (requests, rate-limit waits, pagination) can say what it's doing without printing anything.
Package progress carries a status reporter in a context, so long work (requests, rate-limit waits, pagination) can say what it's doing without printing anything.

Jump to

Keyboard shortcuts

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