abs

package
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: Sep 12, 2026 License: GPL-3.0 Imports: 17 Imported by: 0

Documentation

Overview

Package abs is a minimal client for the Audiobookshelf HTTP API. It speaks the "old JSON" shapes the server returns to its own web client (the public API docs are out of date; the server source is the reference, see docs/README.md). Everything above this package works with the typed structs here and never sees raw payloads.

Index

Constants

This section is empty.

Variables

View Source
var ErrNoCover = errors.New("item has no cover")

ErrNoCover reports that an item has no cover image at all.

Functions

func EncodeFilter

func EncodeFilter(group, value string) string

EncodeFilter builds the value for the `filter` query parameter of list endpoints: "<group>.<base64(value)>", e.g. genres, tags, series, authors, narrators, languages, publishers, publishedDecades, progress, missing, issues, ebooks, tracks, abridged, feed-open, recent.

func IsNotFound

func IsNotFound(err error) bool

IsNotFound reports whether err is an HTTP 404 from the server.

func Millis

func Millis(ms int64) time.Time

Millis converts an Audiobookshelf epoch-milliseconds timestamp to time.Time (zero when unset).

func SplitCSV

func SplitCSV(s string) []string

SplitCSV splits a comma-separated string into trimmed non-empty parts.

Types

type APIKey

type APIKey struct {
	ID     string `json:"id"`
	Name   string `json:"name"`
	UserID string `json:"userId"`
	// these are ISO timestamps, not the epoch milliseconds the rest of the
	// API uses
	ExpiresAt string `json:"expiresAt"`
	LastUsed  string `json:"lastUsedAt"`
	CreatedAt string `json:"createdAt"`
	IsActive  bool   `json:"isActive"`
	Key       string `json:"apiKey,omitempty"`
}

APIKey is a key that acts as one user. The plaintext key is returned only when it is created.

type AudioFile

type AudioFile struct {
	Index                int               `json:"index"`
	Ino                  string            `json:"ino"`
	Metadata             FileMetadata      `json:"metadata"`
	AddedAt              int64             `json:"addedAt"`
	UpdatedAt            int64             `json:"updatedAt"`
	TrackNumFromMeta     *int              `json:"trackNumFromMeta"`
	DiscNumFromMeta      *int              `json:"discNumFromMeta"`
	TrackNumFromFilename *int              `json:"trackNumFromFilename"`
	DiscNumFromFilename  *int              `json:"discNumFromFilename"`
	ManuallyVerified     bool              `json:"manuallyVerified"`
	Exclude              bool              `json:"exclude"`
	Error                string            `json:"error"`
	Format               string            `json:"format"`
	Duration             float64           `json:"duration"`
	BitRate              int64             `json:"bitRate"`
	Language             string            `json:"language"`
	Codec                string            `json:"codec"`
	TimeBase             string            `json:"timeBase"`
	Channels             int               `json:"channels"`
	ChannelLayout        string            `json:"channelLayout"`
	Chapters             []Chapter         `json:"chapters"`
	EmbeddedCoverArt     string            `json:"embeddedCoverArt"`
	MetaTags             map[string]string `json:"metaTags"`
	MimeType             string            `json:"mimeType"`
}

type AudioTrack

type AudioTrack struct {
	Index       int           `json:"index"`
	StartOffset float64       `json:"startOffset"`
	Duration    float64       `json:"duration"`
	Title       string        `json:"title"`
	ContentURL  string        `json:"contentUrl"`
	MimeType    string        `json:"mimeType"`
	Metadata    *FileMetadata `json:"metadata"`
}

type Author

type Author struct {
	ID          string `json:"id"`
	ASIN        string `json:"asin"`
	Name        string `json:"name"`
	Description string `json:"description"`
	ImagePath   string `json:"imagePath"`
	LibraryID   string `json:"libraryId"`
	AddedAt     int64  `json:"addedAt"`
	UpdatedAt   int64  `json:"updatedAt"`
	NumBooks    int    `json:"numBooks"`
	// include=items on GET /api/authors/:id
	LibraryItems []Item `json:"libraryItems"`
}

type AuthorUpdate

type AuthorUpdate struct {
	Name        *string `json:"name,omitempty"`
	Description *string `json:"description,omitempty"`
	ASIN        *string `json:"asin,omitempty"`
}

AuthorUpdate holds editable author fields; nil pointers are unchanged.

type Backup

type Backup struct {
	ID            string `json:"id"`
	Key           string `json:"key"`
	BackupDirPath string `json:"backupDirPath"`
	DatePretty    string `json:"datePretty"`
	FullPath      string `json:"fullPath"`
	Path          string `json:"path"`
	Filename      string `json:"filename"`
	FileSize      int64  `json:"fileSize"`
	CreatedAt     int64  `json:"createdAt"`
	ServerVersion string `json:"serverVersion"`
}

type BatchMediaUpdate

type BatchMediaUpdate struct {
	ID           string      `json:"id"`
	MediaPayload MediaUpdate `json:"mediaPayload"`
}

BatchMediaUpdate is one entry of BatchUpdate. The update must be nested under mediaPayload: the server reads up.mediaPayload.metadata without checking, so a flattened entry crashes it with an unhandled rejection rather than returning an error.

type BatchProgressUpdate

type BatchProgressUpdate struct {
	LibraryItemID string `json:"libraryItemId"`
	EpisodeID     string `json:"episodeId,omitempty"`
	ProgressUpdate
}

BatchProgressUpdate is one entry of BatchSetProgress: the item (and episode) to update, with the fields to set.

type BookSearchResult

type BookSearchResult struct {
	Title         string      `json:"title"`
	Subtitle      string      `json:"subtitle"`
	Author        string      `json:"author"`
	Narrator      string      `json:"narrator"`
	Publisher     string      `json:"publisher"`
	PublishedYear FlexString  `json:"publishedYear"`
	Description   string      `json:"description"`
	Cover         string      `json:"cover"`
	ASIN          string      `json:"asin"`
	ISBN          string      `json:"isbn"`
	Genres        []string    `json:"genres"`
	Tags          []string    `json:"tags"`
	Series        []SeriesRef `json:"series"`
	Language      string      `json:"language"`
	Duration      float64     `json:"duration"` // minutes
	Region        string      `json:"region"`
	Rating        FlexString  `json:"rating"`
	Abridged      bool        `json:"abridged"`
	// custom providers may return an id
	ID FlexString `json:"id"`
}

BookSearchResult is one provider hit from GET /api/search/books.

type Bookmark

type Bookmark struct {
	LibraryItemID string  `json:"libraryItemId"`
	Title         string  `json:"title"`
	Time          float64 `json:"time"`
	CreatedAt     int64   `json:"createdAt"`
}

type Chapter

type Chapter struct {
	ID    int     `json:"id"`
	Start float64 `json:"start"`
	End   float64 `json:"end"`
	Title string  `json:"title"`
}

type Client

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

func New

func New(baseURL, token string) (*Client, error)

New returns a client for the Audiobookshelf server at baseURL that authenticates with an API key (Settings -> Users -> API Keys) or a user token, sent as a bearer token.

func (*Client) APIKeys

func (c *Client) APIKeys(ctx context.Context) ([]APIKey, error)

APIKeys lists the server's API keys (admin only). The keys themselves are not returned, only their metadata.

func (*Client) AddBookToCollection

func (c *Client) AddBookToCollection(ctx context.Context, id, bookID string) (*Collection, error)

AddBookToCollection adds a single book. AddToCollection is the batch form.

func (*Client) AddItemToPlaylist

func (c *Client) AddItemToPlaylist(ctx context.Context, id string, entry PlaylistEntry) (*Playlist, error)

AddItemToPlaylist appends a single entry. AddToPlaylist is the batch form.

func (*Client) AddToCollection

func (c *Client) AddToCollection(ctx context.Context, id string, bookIDs []string) (*Collection, error)

AddToCollection appends books to a collection.

func (*Client) AddToPlaylist

func (c *Client) AddToPlaylist(ctx context.Context, id string, items []PlaylistEntry) (*Playlist, error)

AddToPlaylist appends entries to a playlist.

func (*Client) AllProgress

func (c *Client) AllProgress(ctx context.Context) ([]MediaProgress, error)

AllProgress returns every progress record the API key user has, which is the whole listening history in one call rather than one item at a time.

func (*Client) ApplyBackup

func (c *Client) ApplyBackup(ctx context.Context, id string) error

ApplyBackup restores the server from a backup (admin only). This replaces the database and restarts the server: everything created since the backup is lost.

func (*Client) AuthSettings

func (c *Client) AuthSettings(ctx context.Context) (map[string]any, error)

AuthSettings returns the authentication configuration (admin only).

func (*Client) Author

func (c *Client) Author(ctx context.Context, id string, withItems bool) (*Author, error)

Author fetches one author; withItems attaches their library items.

func (*Client) AuthorImage

func (c *Client) AuthorImage(ctx context.Context, authorID string, width, height int) (io.ReadCloser, error)

AuthorImage streams an author's photo.

func (*Client) Authorize

func (c *Client) Authorize(ctx context.Context) (map[string]any, error)

Authorize exchanges the current credentials for the user and server settings, which is what a client calls on start-up.

func (*Client) Authors

func (c *Client) Authors(ctx context.Context, libraryID string, opts ListOptions) ([]Author, int, error)

Authors lists a library's authors with their book counts. Sort: name, lastFirst, addedAt, updatedAt, numBooks.

func (*Client) Backups

func (c *Client) Backups(ctx context.Context) ([]Backup, string, error)

Backups lists server backups and where they are stored (admin only).

func (*Client) BaseURL

func (c *Client) BaseURL() string

BaseURL is the server address the client was created with, without a trailing slash.

func (*Client) BatchDelete

func (c *Client) BatchDelete(ctx context.Context, ids []string) error

BatchDelete removes several items' records at once (requires the delete permission). Files on disk are untouched.

func (*Client) BatchEmbedMetadata

func (c *Client) BatchEmbedMetadata(ctx context.Context, ids []string, backup bool) error

BatchEmbedMetadata writes metadata and chapters into several items' audio files (admin only). Runs in the background.

func (*Client) BatchQuickMatch

func (c *Client) BatchQuickMatch(ctx context.Context, ids []string, provider string, overrideCover, overrideDetails bool) error

BatchQuickMatch queues a quick match of several items (admin only, runs in the background).

func (*Client) BatchScan

func (c *Client) BatchScan(ctx context.Context, ids []string) error

BatchScan rescans several items' folders (admin only). Returns immediately; the scans run in the background.

func (*Client) BatchSetProgress

func (c *Client) BatchSetProgress(ctx context.Context, updates []BatchProgressUpdate) error

BatchSetProgress updates progress on several items at once, which is how to mark a whole series finished without a call per book.

func (*Client) BatchUpdate

func (c *Client) BatchUpdate(ctx context.Context, updates []BatchMediaUpdate) (int, error)

BatchUpdate applies media updates to several items; each entry needs the item id. Returns the number of items changed.

func (*Client) Bookmarks

func (c *Client) Bookmarks(ctx context.Context) ([]Bookmark, error)

Bookmarks lists the API key user's bookmarks across all items.

func (*Client) CancelEncodeM4B

func (c *Client) CancelEncodeM4B(ctx context.Context, id string) error

CancelEncodeM4B stops an m4b encode that is still running.

func (*Client) ChangePassword

func (c *Client) ChangePassword(ctx context.Context, currentPassword, newPassword string) error

ChangePassword changes the calling user's password.

func (*Client) CheckNewEpisodes

func (c *Client) CheckNewEpisodes(ctx context.Context, itemID string, limit int) ([]FeedEpisode, error)

CheckNewEpisodes fetches the podcast's feed and downloads up to limit new episodes (admin only). Returns the episodes queued.

func (*Client) ClearDownloadQueue

func (c *Client) ClearDownloadQueue(ctx context.Context, itemID string) error

ClearDownloadQueue drops every queued download for a podcast (admin only).

func (*Client) CloseFeed

func (c *Client) CloseFeed(ctx context.Context, feedID string) error

CloseFeed stops publishing a feed.

func (*Client) CloseMeSession

func (c *Client) CloseMeSession(ctx context.Context, id string) error

CloseMeSession ends one of the calling user's device sessions.

func (*Client) CloseSession

func (c *Client) CloseSession(ctx context.Context, id string, final map[string]any) error

CloseSession ends a playback session, optionally with a final sync.

func (*Client) Collection

func (c *Client) Collection(ctx context.Context, id string) (*Collection, error)

Collection fetches one collection with its books.

func (*Client) Collections

func (c *Client) Collections(ctx context.Context, libraryID string) ([]Collection, error)

Collections lists collections, optionally restricted to one library.

func (*Client) Cover

func (c *Client) Cover(ctx context.Context, itemID string, width, height int, format string) (io.ReadCloser, error)

Cover streams an item's cover image. CoverSize reads only the header when all that is wanted is the dimensions.

func (*Client) CoverSize

func (c *Client) CoverSize(ctx context.Context, itemID string) (width, height int, err error)

CoverSize returns the pixel dimensions of an item's cover without holding the image: only the header is decoded, and the bytes are discarded. Returns ErrNoCover when the item has none, and an unsupported-format error for anything the standard library cannot read (webp, avif).

func (*Client) CreateAPIKey

func (c *Client) CreateAPIKey(ctx context.Context, name, userID string, expiresIn int, active bool) (*APIKey, error)

CreateAPIKey mints a key for a user (admin only). The plaintext key is in the returned Key field and is never shown again.

func (*Client) CreateBackup

func (c *Client) CreateBackup(ctx context.Context) ([]Backup, error)

CreateBackup runs a backup now and returns the updated backup list (admin only). Older servers return the single new backup instead; both are handled.

func (*Client) CreateBookmark

func (c *Client) CreateBookmark(ctx context.Context, itemID string, seconds float64, title string) (*Bookmark, error)

CreateBookmark adds a bookmark at time (seconds) on an item.

func (*Client) CreateCollection

func (c *Client) CreateCollection(ctx context.Context, libraryID, name, description string, bookIDs []string) (*Collection, error)

CreateCollection creates a collection in a library, optionally with initial books.

func (*Client) CreateCustomMetadataProvider

func (c *Client) CreateCustomMetadataProvider(ctx context.Context, name, providerURL, mediaType, authHeader string) (*CustomMetadataProvider, error)

CreateCustomMetadataProvider adds one. mediaType is "book" or "podcast". The server will call <url>/search?mediaType=&query=&author= and expects {"matches":[...]} back.

func (*Client) CreateLibrary

func (c *Client) CreateLibrary(ctx context.Context, in LibraryCreate) (*Library, error)

CreateLibrary adds a library over folders already present on the server (admin only). The library is created empty: ScanLibrary populates it.

func (*Client) CreateNotification

func (c *Client) CreateNotification(ctx context.Context, n map[string]any) (*NotificationSettings, error)

CreateNotification adds a notification (admin only) and returns the settings as they now stand. Note the server answers this one with the settings unwrapped, where the GET wraps them in a settings key.

func (*Client) CreatePlaylist

func (c *Client) CreatePlaylist(ctx context.Context, libraryID, name, description string, items []PlaylistEntry) (*Playlist, error)

CreatePlaylist creates a playlist for the API key's user.

func (*Client) CreatePlaylistFromCollection

func (c *Client) CreatePlaylistFromCollection(ctx context.Context, collectionID string) (*Playlist, error)

CreatePlaylistFromCollection copies a collection's books into a new playlist.

func (*Client) CreatePodcast

func (c *Client) CreatePodcast(ctx context.Context, p NewPodcast) (*Item, error)

CreatePodcast adds a podcast from a parsed feed (admin only).

func (*Client) CreatePodcastsFromOPML

func (c *Client) CreatePodcastsFromOPML(ctx context.Context, libraryID, folderID string, feedURLs []string, autoDownload bool) error

CreatePodcastsFromOPML subscribes to every feed in an OPML document.

func (*Client) CreateUser

func (c *Client) CreateUser(ctx context.Context, in UserCreate) (*User, error)

CreateUser adds an account (admin only).

func (*Client) CustomMetadataProviders

func (c *Client) CustomMetadataProviders(ctx context.Context) ([]CustomMetadataProvider, error)

CustomMetadataProviders lists them (admin only).

func (*Client) DeleteAPIKey

func (c *Client) DeleteAPIKey(ctx context.Context, id string) error

DeleteAPIKey revokes a key.

func (*Client) DeleteAuthor

func (c *Client) DeleteAuthor(ctx context.Context, id string) error

DeleteAuthor removes an author record and unlinks them from their books (the books stay). Requires the delete permission.

func (*Client) DeleteAuthorImage

func (c *Client) DeleteAuthorImage(ctx context.Context, authorID string) (*Author, error)

DeleteAuthorImage removes an author's photo.

func (*Client) DeleteBackup

func (c *Client) DeleteBackup(ctx context.Context, id string) ([]Backup, error)

DeleteBackup removes a backup file (admin only) and returns the remaining backups.

func (*Client) DeleteBookmark

func (c *Client) DeleteBookmark(ctx context.Context, itemID string, seconds float64) error

DeleteBookmark removes the bookmark at time (seconds) on an item.

func (*Client) DeleteCollection

func (c *Client) DeleteCollection(ctx context.Context, id string) error

DeleteCollection deletes a collection (its books stay in the library).

func (*Client) DeleteCustomMetadataProvider

func (c *Client) DeleteCustomMetadataProvider(ctx context.Context, id string) error

DeleteCustomMetadataProvider removes one.

func (*Client) DeleteEpisode

func (c *Client) DeleteEpisode(ctx context.Context, itemID, episodeID string, hard bool) error

DeleteEpisode removes an episode; hard also deletes its audio file.

func (*Client) DeleteGenre

func (c *Client) DeleteGenre(ctx context.Context, genre string) (int, error)

DeleteGenre removes a genre from every item that carries it (admin only).

func (*Client) DeleteItem

func (c *Client) DeleteItem(ctx context.Context, id string, hard bool) error

DeleteItem removes an item from the library; hard also deletes its files from disk. Requires the delete permission.

func (*Client) DeleteItemFile

func (c *Client) DeleteItemFile(ctx context.Context, itemID, fileID string) (*Item, error)

DeleteItemFile removes one file from an item, by the file id the item reports in LibraryFiles.

func (*Client) DeleteLibrary

func (c *Client) DeleteLibrary(ctx context.Context, libraryID string) error

DeleteLibrary removes a library and its item records (admin only). The files on disk are untouched.

func (*Client) DeleteNotification

func (c *Client) DeleteNotification(ctx context.Context, id string) error

DeleteNotification removes one.

func (*Client) DeletePlaylist

func (c *Client) DeletePlaylist(ctx context.Context, id string) error

DeletePlaylist deletes a playlist.

func (*Client) DeleteSession

func (c *Client) DeleteSession(ctx context.Context, id string) error

DeleteSession removes a session record (admin only).

func (*Client) DeleteSessions

func (c *Client) DeleteSessions(ctx context.Context, ids []string) error

DeleteSessions removes several session records at once (admin only).

func (*Client) DeleteTag

func (c *Client) DeleteTag(ctx context.Context, tag string) (int, error)

DeleteTag removes a tag from every item that carries it, across all libraries (admin only). Returns how many items were updated. Unlike RenameTag this drops the value entirely, which is what a placeholder such as "XXX" needs rather than a merge.

func (*Client) DeleteUser

func (c *Client) DeleteUser(ctx context.Context, id string) error

DeleteUser removes an account (admin only). The root account cannot be deleted.

func (*Client) DownloadBackup

func (c *Client) DownloadBackup(ctx context.Context, id string) (io.ReadCloser, error)

DownloadBackup streams a backup file.

func (*Client) DownloadEpisodes

func (c *Client) DownloadEpisodes(ctx context.Context, itemID string, episodes []FeedEpisode) error

DownloadEpisodes queues feed episodes (from SearchFeedEpisodes / ParseFeed) for download (admin only).

func (*Client) DownloadItem

func (c *Client) DownloadItem(ctx context.Context, itemID string) (io.ReadCloser, error)

DownloadItem streams an item's files as a zip, or the single file itself when the item has only one.

func (*Client) DownloadItemFile

func (c *Client) DownloadItemFile(ctx context.Context, itemID, fileID string) (io.ReadCloser, error)

DownloadItemFile streams one file as an attachment rather than inline.

func (*Client) DownloadLibrary

func (c *Client) DownloadLibrary(ctx context.Context, libraryID string, itemIDs []string) (io.ReadCloser, error)

DownloadLibrary streams the named items from a library as a zip. The server requires the ids: there is no download-everything form.

func (*Client) Ebook

func (c *Client) Ebook(ctx context.Context, itemID, fileID string) (io.ReadCloser, error)

Ebook streams an item's ebook file. An empty fileID takes the primary one.

func (*Client) EmailSettings

func (c *Client) EmailSettings(ctx context.Context) (*EmailSettings, error)

EmailSettings returns the SMTP configuration (admin only).

func (*Client) EmbedMetadata

func (c *Client) EmbedMetadata(ctx context.Context, id string, forceEmbedChapters, backup bool) error

EmbedMetadata queues writing the item's metadata (and optionally chapters) into its audio file tags (admin only). backup keeps a copy of the original files.

func (*Client) EncodeM4B

func (c *Client) EncodeM4B(ctx context.Context, id, bitrate, channels, codec string) error

EncodeM4B merges an item's audio files into a single m4b (admin only). Runs in the background; poll Tasks for completion.

func (*Client) Episode

func (c *Client) Episode(ctx context.Context, itemID, episodeID string) (*Episode, error)

Episode fetches one podcast episode.

func (*Client) EpisodeDownloads

func (c *Client) EpisodeDownloads(ctx context.Context, libraryID string) (current *EpisodeDownload, queue []EpisodeDownload, err error)

EpisodeDownloads returns the podcast download queue for a library.

func (*Client) FFProbe

func (c *Client) FFProbe(ctx context.Context, itemID, fileID string) (map[string]any, error)

FFProbe returns the raw ffprobe output for one audio file, which is what the scanner read when it decided the file's duration and codec.

func (*Client) Feeds

func (c *Client) Feeds(ctx context.Context) ([]Feed, error)

Feeds lists the RSS feeds the server is currently publishing (admin only).

func (*Client) Filesystem

func (c *Client) Filesystem(ctx context.Context) ([]FilesystemPath, error)

Filesystem lists the directories the server can reach, which is what the folder picker reads when a library is created.

func (*Client) FilterData

func (c *Client) FilterData(ctx context.Context, libraryID string) (*FilterData, error)

FilterData returns the distinct authors, genres, tags, series, narrators, languages and publishers in a library.

func (*Client) Genres

func (c *Client) Genres(ctx context.Context) ([]string, error)

Genres lists every genre in use across all libraries.

func (*Client) HideFromContinueListening

func (c *Client) HideFromContinueListening(ctx context.Context, progressID string) error

HideFromContinueListening removes an in-progress item from the continue listening shelf without changing its progress.

func (*Client) HideSeriesFromContinueListening

func (c *Client) HideSeriesFromContinueListening(ctx context.Context, seriesID string) error

HideSeriesFromContinueListening stops a whole series appearing on the continue-listening shelf.

func (*Client) Item

func (c *Client) Item(ctx context.Context, id string) (*Item, error)

Item fetches one library item in the expanded shape (audio files, chapters, tracks, episodes) with the API key user's progress attached.

func (*Client) ItemBookmarks

func (c *Client) ItemBookmarks(ctx context.Context, itemID string) ([]Bookmark, error)

ItemBookmarks lists the API key user's bookmarks on one item. Bookmarks returns them all.

func (*Client) ItemFile

func (c *Client) ItemFile(ctx context.Context, itemID, fileID string) (io.ReadCloser, error)

ItemFile streams one file from an item, by the file id the item reports in LibraryFiles.

func (*Client) ItemListeningSessions

func (c *Client) ItemListeningSessions(ctx context.Context, itemID, episodeID string, itemsPerPage, page int) ([]Session, int, error)

ItemListeningSessions lists the API key user's sessions for one item or episode.

func (*Client) Items

func (c *Client) Items(ctx context.Context, libraryID string, opts ItemsOptions) (*ItemsPage, error)

Items lists items in a library. Total is the count of all matches, not just this page.

func (*Client) ItemsAll

func (c *Client) ItemsAll(ctx context.Context, libraryID string, opts ItemsOptions, fn func(items []Item) bool) error

ItemsAll walks every item matching opts (limit/page are managed here), calling fn per page until it returns false or the library is exhausted.

func (*Client) ItemsBatch

func (c *Client) ItemsBatch(ctx context.Context, ids []string) ([]Item, error)

ItemsBatch fetches several items by id in one request (expanded shape).

func (*Client) ItemsInProgress

func (c *Client) ItemsInProgress(ctx context.Context, limit int) ([]Item, error)

ItemsInProgress lists the items (and, for podcasts, the episode) the API key user is partway through, most recently updated first.

func (*Client) Libraries

func (c *Client) Libraries(ctx context.Context) ([]Library, error)

Libraries lists the libraries visible to the API key's user.

func (*Client) Library

func (c *Client) Library(ctx context.Context, id string) (*Library, error)

Library fetches one library by id.

func (*Client) LibraryOPML

func (c *Client) LibraryOPML(ctx context.Context, libraryID string) (io.ReadCloser, error)

LibraryOPML streams a library's podcast subscriptions as an OPML document, which is what another podcast client imports.

func (*Client) LibrarySeries

func (c *Client) LibrarySeries(ctx context.Context, libraryID, seriesID string) (*Series, error)

LibrarySeries returns one series with its books, from inside a library. Series looks the same record up by id alone.

func (*Client) LibraryStats

func (c *Client) LibraryStats(ctx context.Context, libraryID string) (*LibraryStats, error)

LibraryStats returns totals plus top authors, genres, largest and longest items.

func (*Client) LibraryWithFilterData

func (c *Client) LibraryWithFilterData(ctx context.Context, id string) (*Library, *FilterData, error)

LibraryWithFilterData fetches a library together with its filter data (authors, genres, tags, series, narrators, ...) and issue count.

func (*Client) ListeningSessions

func (c *Client) ListeningSessions(ctx context.Context, itemsPerPage, page int) ([]Session, int, error)

ListeningSessions lists the API key user's listening sessions, newest first.

func (*Client) ListeningStats

func (c *Client) ListeningStats(ctx context.Context) (*ListeningStats, error)

ListeningStats returns the API key user's total listening time, per-day and per-item breakdowns.

func (*Client) LoggerData

func (c *Client) LoggerData(ctx context.Context) (map[string]any, error)

LoggerData returns the server's log settings and the levels available.

func (*Client) Match

func (c *Client) Match(ctx context.Context, id string, opts MatchOptions) (*MatchResult, error)

Match quick-matches one item: searches the provider (by asin/isbn if given, otherwise title/author) and applies the best hit. Requires the update permission.

func (*Client) MatchAll

func (c *Client) MatchAll(ctx context.Context, libraryID string) error

MatchAll quick-matches every item in a library against its metadata provider (admin only, runs in the background).

func (*Client) MatchAuthor

func (c *Client) MatchAuthor(ctx context.Context, id, name, asin, region string) (author *Author, updated bool, err error)

MatchAuthor looks the author up on Audnexus by name (or ASIN) and fills in their ASIN, description and image.

func (*Client) MatchEpisodes

func (c *Client) MatchEpisodes(ctx context.Context, itemID string, override bool) (int, error)

MatchEpisodes quick-matches every episode of a podcast against its feed to fill in missing metadata (admin only).

func (*Client) Me

func (c *Client) Me(ctx context.Context) (*User, error)

Me returns the user the API key acts on behalf of, including their media progress and bookmarks.

func (*Client) MeSessions

func (c *Client) MeSessions(ctx context.Context) (map[string]any, error)

MeSessions lists the calling user's own device sessions - the logins, not the playback sessions.

func (*Client) MeUpdateEReaderDevices

func (c *Client) MeUpdateEReaderDevices(ctx context.Context, devices []EReaderDevice) ([]EReaderDevice, error)

MeUpdateEReaderDevices replaces the calling user's own device list. The server requires every device here to have AvailableTo "specificUsers" with Users naming only the calling user: a non-admin cannot make a device others can see.

func (*Client) MetadataObject

func (c *Client) MetadataObject(ctx context.Context, id string) (map[string]any, error)

MetadataObject returns the tags the server would write into an item's audio files, without writing them: the dry run for EmbedMetadata.

func (*Client) Narrators

func (c *Client) Narrators(ctx context.Context, libraryID string) ([]NarratorRow, error)

Narrators lists a library's narrators with book counts.

func (*Client) NotificationData

func (c *Client) NotificationData(ctx context.Context) (map[string]any, error)

NotificationData returns the events a notification can be attached to, and the variables each event makes available to its template.

func (*Client) Notifications

func (c *Client) Notifications(ctx context.Context) (*NotificationSettings, error)

Notifications returns the notification settings (admin only).

func (*Client) OpenCollectionFeed

func (c *Client) OpenCollectionFeed(ctx context.Context, collectionID, slug, serverAddress string) (*Feed, error)

OpenCollectionFeed publishes a feed for a whole collection.

func (*Client) OpenItemFeed

func (c *Client) OpenItemFeed(ctx context.Context, itemID, slug, serverAddress string) (*Feed, error)

OpenItemFeed starts publishing an RSS feed for one item. slug is the feed's path segment; serverAddress is the url the feed advertises, which has to be reachable by whatever reads it.

func (*Client) OpenSeriesFeed

func (c *Client) OpenSeriesFeed(ctx context.Context, seriesID, slug, serverAddress string) (*Feed, error)

OpenSeriesFeed publishes a feed for a whole series.

func (*Client) OpenSessions

func (c *Client) OpenSessions(ctx context.Context) ([]Session, error)

OpenSessions lists playback sessions currently open on the server (admin only).

func (*Client) ParseFeed

func (c *Client) ParseFeed(ctx context.Context, feedURL string) (*FeedPodcast, error)

ParseFeed fetches and parses a podcast RSS feed (admin only).

func (*Client) ParseOPML

func (c *Client) ParseOPML(ctx context.Context, opmlText string) ([]map[string]any, error)

ParseOPML reads an OPML document and returns the feeds in it, without subscribing to anything.

func (*Client) PathExists

func (c *Client) PathExists(ctx context.Context, folderPath, directory string) (exists bool, itemTitle string, err error)

PathExists reports whether a directory exists inside a library folder, and names the library item already there when one is. This is what the new-item dialog calls before it will let you create a folder.

func (*Client) Personalized

func (c *Client) Personalized(ctx context.Context, libraryID string, limit int) ([]Shelf, error)

Personalized returns the server's own home-screen shelves for a library.

func (*Client) Play

func (c *Client) Play(ctx context.Context, itemID, episodeID string, req PlayRequest) (*Session, error)

Play opens a playback session for an item, returning the session with the tracks to play. episodeID may be empty for a book.

func (*Client) Playlist

func (c *Client) Playlist(ctx context.Context, id string) (*Playlist, error)

Playlist fetches one of the API key user's playlists with its entries.

func (*Client) Playlists

func (c *Client) Playlists(ctx context.Context, libraryID string) ([]Playlist, error)

Playlists lists the API key user's playlists, optionally restricted to one library.

func (*Client) PodcastDownloads

func (c *Client) PodcastDownloads(ctx context.Context, itemID string) ([]EpisodeDownload, error)

PodcastDownloads lists downloads queued for one podcast.

func (*Client) PodcastTitles

func (c *Client) PodcastTitles(ctx context.Context, libraryID string) ([]string, error)

PodcastTitles lists the titles of the podcasts in a library, which is far cheaper than listing the items when all you need is what is subscribed.

func (*Client) Progress

func (c *Client) Progress(ctx context.Context, itemID, episodeID string) (*MediaProgress, error)

Progress returns the API key user's progress on an item (or a podcast episode). Nil when they have none.

func (*Client) Providers

func (c *Client) Providers(ctx context.Context) (book, podcast []string, err error)

Providers lists the metadata providers available for matching.

func (*Client) PurgeCache

func (c *Client) PurgeCache(ctx context.Context) error

PurgeCache empties the whole server cache (admin only).

func (*Client) PurgeItemsCache

func (c *Client) PurgeItemsCache(ctx context.Context) error

PurgeItemsCache empties just the cached item images.

func (*Client) RecentEpisodes

func (c *Client) RecentEpisodes(ctx context.Context, libraryID string, limit, page int) ([]Episode, error)

RecentEpisodes lists the newest episodes across a podcast library.

func (*Client) RemoveBookFromCollection

func (c *Client) RemoveBookFromCollection(ctx context.Context, id, bookID string) (*Collection, error)

RemoveBookFromCollection removes a single book. RemoveFromCollection is the batch form.

func (*Client) RemoveCover

func (c *Client) RemoveCover(ctx context.Context, id string) error

RemoveCover deletes the item's cover image.

func (*Client) RemoveFromCollection

func (c *Client) RemoveFromCollection(ctx context.Context, id string, bookIDs []string) (*Collection, error)

RemoveFromCollection removes books from a collection.

func (*Client) RemoveFromPlaylist

func (c *Client) RemoveFromPlaylist(ctx context.Context, id string, items []PlaylistEntry) (*Playlist, error)

RemoveFromPlaylist removes entries from a playlist.

func (*Client) RemoveIssues

func (c *Client) RemoveIssues(ctx context.Context, libraryID string) error

RemoveIssues deletes every missing or invalid item record from a library (admin only). Files are untouched.

func (*Client) RemoveItemFromPlaylist

func (c *Client) RemoveItemFromPlaylist(ctx context.Context, id, itemID, episodeID string) (*Playlist, error)

RemoveItemFromPlaylist removes a single entry. RemoveFromPlaylist is the batch form. episodeID may be empty for a book.

func (*Client) RemoveLibraryMetadata

func (c *Client) RemoveLibraryMetadata(ctx context.Context, libraryID, kind string) error

RemoveLibraryMetadata deletes the metadata files the server wrote into the library's item folders (admin only). kind is "json" or "abs"; empty removes both.

func (*Client) RemoveNarrator

func (c *Client) RemoveNarrator(ctx context.Context, libraryID, name string) (int, error)

RemoveNarrator drops a narrator from every book that carries them. Requires the update permission; returns how many items changed.

func (*Client) RemoveProgress

func (c *Client) RemoveProgress(ctx context.Context, progressID string) error

RemoveProgress deletes a progress record by its progress id (from Progress or Me), resetting the item to not started.

func (*Client) RenameGenre

func (c *Client) RenameGenre(ctx context.Context, genre, newGenre string) (int, error)

RenameGenre renames a genre on every item that carries it (admin only).

func (*Client) RenameNarrator

func (c *Client) RenameNarrator(ctx context.Context, libraryID, from, to string) (int, error)

RenameNarrator renames a narrator on every book that carries them, across the library. Renaming onto an existing narrator merges the two. Requires the update permission; returns how many items changed.

func (*Client) RenameTag

func (c *Client) RenameTag(ctx context.Context, tag, newTag string) (int, error)

RenameTag renames a tag on every item that carries it (admin only). Returns how many items were updated.

func (*Client) ReorderLibraries

func (c *Client) ReorderLibraries(ctx context.Context, ids []string) ([]Library, error)

ReorderLibraries sets the order libraries are shown in. The ids are given in the order wanted; the server is sent the display order it expects, which is an array of objects rather than bare ids (admin only).

func (*Client) ScanItem

func (c *Client) ScanItem(ctx context.Context, id string) (string, error)

ScanItem rescans one item's folder (admin only). Result is NOTHING, ADDED, UPDATED, REMOVED or UPTODATE.

func (*Client) ScanLibrary

func (c *Client) ScanLibrary(ctx context.Context, libraryID string, force bool) error

ScanLibrary starts a library scan (admin only). The server responds before the scan finishes; watch Tasks for completion.

func (*Client) Search

func (c *Client) Search(ctx context.Context, libraryID, query string, limit int) (*SearchResult, error)

Search searches one library's titles, authors, series, narrators, tags and genres.

func (*Client) SearchAuthors

func (c *Client) SearchAuthors(ctx context.Context, query string) ([]Author, error)

SearchAuthors looks an author up on the provider by name, without applying anything. MatchAuthor is the form that writes the result to a record.

func (*Client) SearchBooks

func (c *Client) SearchBooks(ctx context.Context, provider, title, author, itemID string) ([]BookSearchResult, error)

SearchBooks queries a metadata provider without changing anything. itemID (optional) lets the server use the item's existing identifiers to rank results.

func (*Client) SearchChapters

func (c *Client) SearchChapters(ctx context.Context, asin, region string) ([]Chapter, error)

SearchChapters fetches chapter data for an ASIN from Audible (region: us, ca, uk, au, fr, de, jp, it, in, es).

func (*Client) SearchCovers

func (c *Client) SearchCovers(ctx context.Context, provider, title, author string, podcast bool) ([]string, error)

SearchCovers returns candidate cover image URLs for a title/author.

func (*Client) SearchFeedEpisodes

func (c *Client) SearchFeedEpisodes(ctx context.Context, itemID, title string) ([]FeedEpisode, error)

SearchFeedEpisodes finds episodes in the podcast's feed whose title matches, without downloading.

func (*Client) SearchPodcasts

func (c *Client) SearchPodcasts(ctx context.Context, term, country string) ([]PodcastSearchResult, error)

SearchPodcasts searches iTunes for podcasts by name (country: us, gb, ...).

func (*Client) SendEbookToDevice

func (c *Client) SendEbookToDevice(ctx context.Context, itemID, deviceName string) error

SendEbookToDevice emails an item's ebook file to a configured device.

func (*Client) Series

func (c *Client) Series(ctx context.Context, id string) (*Series, error)

Series fetches one series with the API key user's progress through it.

func (*Client) SeriesList

func (c *Client) SeriesList(ctx context.Context, libraryID string, opts ListOptions) ([]Series, int, error)

SeriesList lists a library's series, each with its books (minified). Sort: name, numBooks, totalDuration, addedAt, lastBookAdded, lastBookUpdated.

func (*Client) ServerStats

func (c *Client) ServerStats(ctx context.Context) (*ServerStats, error)

ServerStats returns library size totals (admin only).

func (*Client) ServerYearStats

func (c *Client) ServerYearStats(ctx context.Context, year int) (*YearStats, error)

ServerYearStats returns the whole server's year in review, as opposed to YearStats which is the API key user's own.

func (*Client) Session

func (c *Client) Session(ctx context.Context, id string) (*Session, error)

Session returns one playback session by id.

func (*Client) Sessions

func (c *Client) Sessions(ctx context.Context, opts SessionsOptions) ([]Session, int, error)

Sessions lists past playback sessions across all users (admin only), newest first by default.

func (*Client) SetAuthorImage

func (c *Client) SetAuthorImage(ctx context.Context, id, imageURL string) (*Author, error)

SetAuthorImage downloads imageURL on the server and makes it the author's photo. Requires the upload permission.

func (*Client) SetBackupPath

func (c *Client) SetBackupPath(ctx context.Context, path string) error

SetBackupPath changes where backups are written (admin only).

func (*Client) SetChapters

func (c *Client) SetChapters(ctx context.Context, id string, chapters []Chapter) (updated bool, err error)

SetChapters replaces a book's chapter list. Requires the update permission.

func (*Client) SetCoverFromFile

func (c *Client) SetCoverFromFile(ctx context.Context, id, path string) error

SetCoverFromFile picks a file already inside the item's folder as its cover (path as reported in the item's library files).

func (*Client) SetCoverFromURL

func (c *Client) SetCoverFromURL(ctx context.Context, id, imageURL string) error

SetCoverFromURL downloads an image and sets it as the item's cover.

func (*Client) SetEbookPrimary

func (c *Client) SetEbookPrimary(ctx context.Context, itemID, fileID string, isPrimary bool) error

SetEbookPrimary marks which ebook file is the primary one when an item has several. isPrimary false makes it supplementary.

func (*Client) SetProgress

func (c *Client) SetProgress(ctx context.Context, itemID, episodeID string, upd ProgressUpdate) error

SetProgress creates or updates the API key user's progress on an item or episode.

func (*Client) ShareMediaItem

func (c *Client) ShareMediaItem(ctx context.Context, mediaItemID, mediaItemType, slug string, expiresAt int64, downloadable bool) (*MediaItemShare, error)

ShareMediaItem opens a public link to a media item (admin only). expiresAt is epoch milliseconds, not a duration; zero never expires. mediaItemType is "book" or "podcastEpisode". Note the id is the media item's, which is not the library item's id - take it from Item.Media.ID.

func (*Client) Status

func (c *Client) Status(ctx context.Context) (*Status, error)

Status returns the server's version and init state (no auth required).

func (*Client) SyncLocalSession

func (c *Client) SyncLocalSession(ctx context.Context, session map[string]any) error

SyncLocalSession uploads a session recorded while offline.

func (*Client) SyncLocalSessions

func (c *Client) SyncLocalSessions(ctx context.Context, sessions []map[string]any) error

SyncLocalSessions uploads several offline sessions at once.

func (*Client) SyncSession

func (c *Client) SyncSession(ctx context.Context, id string, currentTime, timeListened float64) error

SyncSession reports listening progress against an open session.

func (*Client) Tags

func (c *Client) Tags(ctx context.Context) ([]string, error)

Tags lists every tag in use across all libraries.

func (*Client) Tasks

func (c *Client) Tasks(ctx context.Context) ([]Task, error)

Tasks lists the task manager's current and recent tasks (scans, matches, embeds, encodes).

func (*Client) TestEmail

func (c *Client) TestEmail(ctx context.Context) error

TestEmail sends a test message to the configured test address.

func (*Client) TestNotification

func (c *Client) TestNotification(ctx context.Context) error

TestNotification fires a test event at every configured notification.

func (*Client) TestOneNotification

func (c *Client) TestOneNotification(ctx context.Context, id string) error

TestOneNotification fires a test event at one notification.

func (*Client) UnhideSeriesFromContinueListening

func (c *Client) UnhideSeriesFromContinueListening(ctx context.Context, seriesID string) error

UnhideSeriesFromContinueListening puts it back.

func (*Client) UnlinkOpenID

func (c *Client) UnlinkOpenID(ctx context.Context, userID string) error

UnlinkOpenID detaches a user's OpenID identity (admin only).

func (*Client) UnshareMediaItem

func (c *Client) UnshareMediaItem(ctx context.Context, id string) error

UnshareMediaItem closes a public link.

func (*Client) UpdateAPIKey

func (c *Client) UpdateAPIKey(ctx context.Context, id string, fields map[string]any) (*APIKey, error)

UpdateAPIKey changes a key's name or whether it is active.

func (*Client) UpdateAuthSettings

func (c *Client) UpdateAuthSettings(ctx context.Context, settings map[string]any) error

UpdateAuthSettings changes the authentication configuration.

func (*Client) UpdateAuthor

func (c *Client) UpdateAuthor(ctx context.Context, id string, upd AuthorUpdate) (author *Author, merged bool, err error)

UpdateAuthor edits an author. Renaming to an existing author's name merges the two; merged reports that.

func (*Client) UpdateBookmark

func (c *Client) UpdateBookmark(ctx context.Context, itemID string, seconds float64, title string) (*Bookmark, error)

UpdateBookmark renames the bookmark at time on an item.

func (*Client) UpdateCollection

func (c *Client) UpdateCollection(ctx context.Context, id string, name, description *string) (*Collection, error)

UpdateCollection renames or describes a collection; nil pointers are unchanged.

func (*Client) UpdateEReaderDevices

func (c *Client) UpdateEReaderDevices(ctx context.Context, devices []EReaderDevice) ([]EReaderDevice, error)

UpdateEReaderDevices replaces the list of devices ebooks can be sent to (admin only). MeUpdateEReaderDevices is the same for the calling user.

func (*Client) UpdateEmailSettings

func (c *Client) UpdateEmailSettings(ctx context.Context, settings map[string]any) error

UpdateEmailSettings changes the SMTP configuration.

func (*Client) UpdateEpisode

func (c *Client) UpdateEpisode(ctx context.Context, itemID, episodeID string, upd EpisodeUpdate) (*Item, error)

UpdateEpisode edits an episode's metadata.

func (*Client) UpdateLibrary

func (c *Client) UpdateLibrary(ctx context.Context, libraryID string, upd LibraryUpdate) (*Library, error)

UpdateLibrary edits a library's name, provider, icon or settings (admin only).

func (*Client) UpdateMedia

func (c *Client) UpdateMedia(ctx context.Context, id string, upd MediaUpdate) (updated bool, err error)

UpdateMedia edits an item's metadata, tags or podcast settings. Requires the update permission.

func (*Client) UpdateNotification

func (c *Client) UpdateNotification(ctx context.Context, id string, n map[string]any) (*NotificationSettings, error)

UpdateNotification edits one notification and returns the settings as they now stand.

func (*Client) UpdateNotificationSettings

func (c *Client) UpdateNotificationSettings(ctx context.Context, settings map[string]any) error

UpdateNotificationSettings changes the server-wide notification settings.

func (*Client) UpdatePlaylist

func (c *Client) UpdatePlaylist(ctx context.Context, id string, name, description *string) (*Playlist, error)

UpdatePlaylist renames or describes a playlist; nil pointers are unchanged.

func (*Client) UpdateSeries

func (c *Client) UpdateSeries(ctx context.Context, id string, upd SeriesUpdate) (*Series, error)

UpdateSeries renames or describes a series. Requires the update permission.

func (*Client) UpdateServerSettings

func (c *Client) UpdateServerSettings(ctx context.Context, settings map[string]any) (map[string]any, error)

UpdateServerSettings changes the server-wide settings (admin only).

func (*Client) UpdateSortingPrefixes

func (c *Client) UpdateSortingPrefixes(ctx context.Context, prefixes []string) error

UpdateSortingPrefixes sets the words ignored when sorting titles ("the", "a"), which changes how every list is ordered.

func (*Client) UpdateTracks

func (c *Client) UpdateTracks(ctx context.Context, id string, order []TrackOrder) (*Item, error)

UpdateTracks sets the play order of an item's audio files, and which of them to exclude. This is the fix for a multi-file book whose chapters play out of order.

func (*Client) UpdateUser

func (c *Client) UpdateUser(ctx context.Context, id string, upd UserUpdate) (*User, error)

UpdateUser edits an account (admin only).

func (*Client) UpdateWatcher

func (c *Client) UpdateWatcher(ctx context.Context, libraryID string, enabled bool) error

UpdateWatcher turns the filesystem watcher on or off for a library.

func (*Client) Upload

func (c *Client) Upload(ctx context.Context, libraryID, folderID, title, author, series, filename string, content io.Reader) error

Upload adds files to a library, creating the item folder. Each file is sent as its own part; the server places them under <library folder>/<path>.

func (*Client) UploadBackup

func (c *Client) UploadBackup(ctx context.Context, filename string, content io.Reader) error

UploadBackup restores a backup file onto the server without applying it.

func (*Client) User

func (c *Client) User(ctx context.Context, id string) (*User, error)

User fetches one user with their media progress (admin only).

func (*Client) UserListeningStats

func (c *Client) UserListeningStats(ctx context.Context, userID string) (*ListeningStats, error)

UserListeningStats returns one user's listening totals (admin only).

func (*Client) UserSessions

func (c *Client) UserSessions(ctx context.Context, userID string, itemsPerPage, page int) ([]Session, int, error)

UserSessions lists one user's listening sessions, newest first (admin only).

func (*Client) Users

func (c *Client) Users(ctx context.Context, includeLatestSession bool) ([]User, error)

Users lists all user accounts (admin only). includeLatestSession adds each user's most recent playback session.

func (*Client) UsersOnline

func (c *Client) UsersOnline(ctx context.Context) (usersOnline []User, openSessions []Session, err error)

UsersOnline returns the ids of users with an open socket plus the open playback sessions (admin only).

func (*Client) ValidateCron

func (c *Client) ValidateCron(ctx context.Context, expression string) error

ValidateCron checks a cron expression without scheduling anything.

func (*Client) YearStats

func (c *Client) YearStats(ctx context.Context, year int) (*YearStats, error)

YearStats returns the API key user's year-in-review stats.

type CollapsedSeries

type CollapsedSeries struct {
	ID       string `json:"id"`
	Name     string `json:"name"`
	NumBooks int    `json:"numBooks"`
}

type Collection

type Collection struct {
	ID          string `json:"id"`
	LibraryID   string `json:"libraryId"`
	UserID      string `json:"userId"`
	Name        string `json:"name"`
	Description string `json:"description"`
	Books       []Item `json:"books"`
	LastUpdate  int64  `json:"lastUpdate"`
	CreatedAt   int64  `json:"createdAt"`
}

type CountRow

type CountRow struct {
	Name     string `json:"name"`
	NumBooks int    `json:"numBooks"`
	NumItems int    `json:"numItems"`
	Count    int    `json:"count"`
}

func (CountRow) N

func (c CountRow) N() int

N returns whichever count field the endpoint populated.

type CustomMetadataProvider

type CustomMetadataProvider struct {
	ID              string `json:"id"`
	Name            string `json:"name"`
	URL             string `json:"url"`
	MediaType       string `json:"mediaType"`
	AuthHeaderValue string `json:"authHeaderValue"`
	Slug            string `json:"slug"`
}

CustomMetadataProvider is a provider the server will call for book matches, alongside the built-in ones.

type DeviceInfo

type DeviceInfo struct {
	ID             string `json:"id"`
	DeviceID       string `json:"deviceId"`
	IPAddress      string `json:"ipAddress"`
	DeviceName     string `json:"deviceName"`
	DeviceType     string `json:"deviceType"`
	ClientName     string `json:"clientName"`
	ClientVersion  string `json:"clientVersion"`
	Manufacturer   string `json:"manufacturer"`
	Model          string `json:"model"`
	SDKVersion     string `json:"sdkVersion"`
	BrowserName    string `json:"browserName"`
	BrowserVersion string `json:"browserVersion"`
	OSName         string `json:"osName"`
	OSVersion      string `json:"osVersion"`
}

func (*DeviceInfo) Describe

func (d *DeviceInfo) Describe() string

Describe returns a short "client on device" description.

type EReaderDevice

type EReaderDevice struct {
	Name        string   `json:"name"`
	Email       string   `json:"email"`
	AvailableTo string   `json:"availabilityOption"`
	Users       []string `json:"users"`
}

EReaderDevice is somewhere an ebook can be sent.

type EbookFile

type EbookFile struct {
	Ino         string       `json:"ino"`
	Metadata    FileMetadata `json:"metadata"`
	EbookFormat string       `json:"ebookFormat"`
	AddedAt     int64        `json:"addedAt"`
	UpdatedAt   int64        `json:"updatedAt"`
}

type EmailSettings

type EmailSettings struct {
	ID                 string          `json:"id"`
	Host               string          `json:"host"`
	Port               int             `json:"port"`
	Secure             bool            `json:"secure"`
	RejectUnauthorized bool            `json:"rejectUnauthorized"`
	User               string          `json:"user"`
	FromAddress        string          `json:"fromAddress"`
	TestAddress        string          `json:"testAddress"`
	EReaderDevices     []EReaderDevice `json:"ereaderDevices"`
}

EmailSettings is the SMTP configuration used to send ebooks.

type Enclosure

type Enclosure struct {
	URL    string     `json:"url"`
	Type   string     `json:"type"`
	Length FlexString `json:"length"`
}

type Episode

type Episode struct {
	LibraryItemID string      `json:"libraryItemId"`
	PodcastID     string      `json:"podcastId"`
	ID            string      `json:"id"`
	Index         int         `json:"index"`
	Season        FlexString  `json:"season"`
	Episode       FlexString  `json:"episode"`
	EpisodeType   string      `json:"episodeType"`
	Title         string      `json:"title"`
	Subtitle      string      `json:"subtitle"`
	Description   string      `json:"description"`
	Enclosure     *Enclosure  `json:"enclosure"`
	GUID          string      `json:"guid"`
	PubDate       string      `json:"pubDate"`
	Chapters      []Chapter   `json:"chapters"`
	AudioFile     *AudioFile  `json:"audioFile"`
	PublishedAt   int64       `json:"publishedAt"`
	AddedAt       int64       `json:"addedAt"`
	UpdatedAt     int64       `json:"updatedAt"`
	AudioTrack    *AudioTrack `json:"audioTrack"`
	Size          int64       `json:"size"`
	Duration      float64     `json:"duration"`
	// filled by /me/items-in-progress and recent-episodes
	Progress *MediaProgress `json:"progress,omitempty"`
}

func (*Episode) DurationSeconds

func (e *Episode) DurationSeconds() float64

DurationSeconds returns the episode's audio length from whichever field is populated.

type EpisodeDownload

type EpisodeDownload struct {
	ID                  string     `json:"id"`
	EpisodeDisplayTitle string     `json:"episodeDisplayTitle"`
	URL                 string     `json:"url"`
	LibraryItemID       string     `json:"libraryItemId"`
	LibraryID           string     `json:"libraryId"`
	IsFinished          bool       `json:"isFinished"`
	Failed              bool       `json:"failed"`
	StartedAt           int64      `json:"startedAt"`
	CreatedAt           int64      `json:"createdAt"`
	FinishedAt          int64      `json:"finishedAt"`
	PodcastTitle        string     `json:"podcastTitle"`
	Season              FlexString `json:"season"`
	Episode             FlexString `json:"episode"`
	EpisodeType         string     `json:"episodeType"`
	PublishedAt         int64      `json:"publishedAt"`
}

EpisodeDownload is a queued or running podcast episode download.

type EpisodeUpdate

type EpisodeUpdate struct {
	Title       *string `json:"title,omitempty"`
	Subtitle    *string `json:"subtitle,omitempty"`
	Description *string `json:"description,omitempty"`
	PubDate     *string `json:"pubDate,omitempty"`
	Episode     *string `json:"episode,omitempty"`
	Season      *string `json:"season,omitempty"`
	EpisodeType *string `json:"episodeType,omitempty"` // full, trailer, bonus
}

EpisodeUpdate holds editable episode fields; nil pointers are unchanged.

type Feed

type Feed struct {
	ID         string `json:"id"`
	Slug       string `json:"slug"`
	EntityType string `json:"entityType"`
	EntityID   string `json:"entityId"`
	FeedURL    string `json:"feedUrl"`
	ItemID     string `json:"itemId"`
	Meta       struct {
		Title       string `json:"title"`
		Description string `json:"description"`
		Author      string `json:"author"`
		ImageURL    string `json:"imageUrl"`
	} `json:"meta"`
}

Feed is an RSS feed the server is publishing for an item, collection or series.

type FeedEpisode

type FeedEpisode struct {
	Title            string          `json:"title"`
	Subtitle         string          `json:"subtitle"`
	Description      string          `json:"description"`
	DescriptionPlain string          `json:"descriptionPlain"`
	PubDate          string          `json:"pubDate"`
	EpisodeType      string          `json:"episodeType"`
	Season           FlexString      `json:"season"`
	Episode          FlexString      `json:"episode"`
	Author           string          `json:"author"`
	Duration         FlexString      `json:"duration"`
	DurationSeconds  *float64        `json:"durationSeconds"`
	Explicit         FlexString      `json:"explicit"`
	PublishedAt      int64           `json:"publishedAt"`
	Enclosure        *Enclosure      `json:"enclosure"`
	GUID             string          `json:"guid"`
	ChaptersURL      string          `json:"chaptersUrl"`
	ChaptersType     string          `json:"chaptersType"`
	Chapters         json.RawMessage `json:"chapters"`
}

FeedEpisode is an episode parsed from a podcast's RSS feed (not yet in the library). Passing it back to DownloadEpisodes queues the download.

type FeedPodcast

type FeedPodcast struct {
	Metadata struct {
		Image       string   `json:"image"`
		Categories  []string `json:"categories"`
		FeedURL     string   `json:"feedUrl"`
		Description string   `json:"description"`
		Title       string   `json:"title"`
		Language    string   `json:"language"`
		Explicit    string   `json:"explicit"`
		Author      string   `json:"author"`
		PubDate     string   `json:"pubDate"`
		Link        string   `json:"link"`
		Type        string   `json:"type"`
	} `json:"metadata"`
	Episodes    []FeedEpisode `json:"episodes"`
	NumEpisodes int           `json:"numEpisodes"`
}

FeedPodcast is the parsed feed from POST /api/podcasts/feed.

type FileMetadata

type FileMetadata struct {
	Filename    string `json:"filename"`
	Ext         string `json:"ext"`
	Path        string `json:"path"`
	RelPath     string `json:"relPath"`
	Size        int64  `json:"size"`
	MtimeMs     int64  `json:"mtimeMs"`
	CtimeMs     int64  `json:"ctimeMs"`
	BirthtimeMs int64  `json:"birthtimeMs"`
}

type FilesystemPath

type FilesystemPath struct {
	Path     string           `json:"path"`
	DirName  string           `json:"dirname"`
	Children []FilesystemPath `json:"children"`
}

FilesystemPath is a directory the server can see, as the folder picker shows it.

type FilterData

type FilterData struct {
	Authors          []NameRef `json:"authors"`
	Genres           []string  `json:"genres"`
	Tags             []string  `json:"tags"`
	Series           []NameRef `json:"series"`
	Narrators        []string  `json:"narrators"`
	Languages        []string  `json:"languages"`
	Publishers       []string  `json:"publishers"`
	PublishedDecades []string  `json:"publishedDecades"`
	BookCount        int       `json:"bookCount"`
	AuthorCount      int       `json:"authorCount"`
	SeriesCount      int       `json:"seriesCount"`
	PodcastCount     int       `json:"podcastCount"`
	NumIssues        int       `json:"numIssues"`
}

type FlexString

type FlexString string

FlexString accepts a JSON string or number (Audiobookshelf stores several fields, e.g. publishedYear and episode numbers, as strings but some providers and older records return numbers).

func (FlexString) Int

func (f FlexString) Int() int

Int parses the value as an integer, 0 when empty or not numeric.

func (FlexString) String

func (f FlexString) String() string

func (*FlexString) UnmarshalJSON

func (f *FlexString) UnmarshalJSON(b []byte) error

type Folder

type Folder struct {
	// omitempty matters on create: the server takes an empty id literally and
	// the second library then collides on the primary key
	ID        string `json:"id,omitempty"`
	FullPath  string `json:"fullPath"`
	LibraryID string `json:"libraryId,omitempty"`
	AddedAt   int64  `json:"addedAt,omitempty"`
}

type HTTPError

type HTTPError struct {
	Method string
	Path   string
	Status int
	Body   string
}

HTTPError is returned for non-2xx responses. Callers can inspect the status (e.g. 404 for "not found", 403 for a permission the API key lacks).

func (*HTTPError) Error

func (e *HTTPError) Error() string

type Item

type Item struct {
	ID                    string           `json:"id"`
	LibraryID             string           `json:"libraryId"`
	FolderID              string           `json:"folderId"`
	Path                  string           `json:"path"`
	RelPath               string           `json:"relPath"`
	IsFile                bool             `json:"isFile"`
	MtimeMs               int64            `json:"mtimeMs"`
	CtimeMs               int64            `json:"ctimeMs"`
	BirthtimeMs           int64            `json:"birthtimeMs"`
	AddedAt               int64            `json:"addedAt"`
	UpdatedAt             int64            `json:"updatedAt"`
	LastScan              int64            `json:"lastScan"`
	ScanVersion           string           `json:"scanVersion"`
	IsMissing             bool             `json:"isMissing"`
	IsInvalid             bool             `json:"isInvalid"`
	MediaType             string           `json:"mediaType"` // book or podcast
	Media                 Media            `json:"media"`
	NumFiles              int              `json:"numFiles"`
	Size                  int64            `json:"size"`
	LibraryFiles          []LibraryFile    `json:"libraryFiles"`
	CollapsedSeries       *CollapsedSeries `json:"collapsedSeries"`
	NumEpisodesIncomplete int              `json:"numEpisodesIncomplete"`
	RSSFeed               json.RawMessage  `json:"rssFeed"`

	// include=progress on the item endpoint; items-in-progress / continue shelves
	UserMediaProgress *MediaProgress `json:"userMediaProgress"`
	RecentEpisode     *Episode       `json:"recentEpisode"`
}

Item is a library item (a book folder or a podcast). List endpoints return the minified shape, GET /api/items/:id?expanded=1 the expanded one.

func (*Item) HasCover

func (i *Item) HasCover() bool

HasCover reports whether the item has a cover image.

func (*Item) IsPodcast

func (i *Item) IsPodcast() bool

IsPodcast reports whether the item is a podcast rather than a book.

func (*Item) SizeBytes

func (i *Item) SizeBytes() int64

SizeBytes returns the item's size from whichever field is populated.

func (*Item) Title

func (i *Item) Title() string

Title is the item's display title.

type ItemsOptions

type ItemsOptions struct {
	Limit          int
	Page           int
	Sort           string // e.g. media.metadata.title, media.metadata.authorName, media.metadata.publishedYear, media.duration, size, addedAt, birthtimeMs, mtimeMs, sequence, progress, random
	Desc           bool
	Filter         string
	Minified       bool
	CollapseSeries bool
	Include        string // comma-separated: rssfeed, numepisodesincomplete, share
}

ItemsOptions selects a page of library items. Filter is the raw value for the `filter` parameter; build it with EncodeFilter.

type ItemsPage

type ItemsPage struct {
	Results []Item
	Total   int
	Limit   int
	Page    int
}

ItemsPage is one page of Items results.

type Library

type Library struct {
	ID              string          `json:"id"`
	Name            string          `json:"name"`
	Folders         []Folder        `json:"folders"`
	DisplayOrder    int             `json:"displayOrder"`
	Icon            string          `json:"icon"`
	MediaType       string          `json:"mediaType"` // book or podcast
	Provider        string          `json:"provider"`  // default metadata provider, e.g. audible, google, itunes
	Settings        LibrarySettings `json:"settings"`
	LastScan        int64           `json:"lastScan"`
	LastScanVersion string          `json:"lastScanVersion"`
	CreatedAt       int64           `json:"createdAt"`
	LastUpdate      int64           `json:"lastUpdate"`
}

func (*Library) IsPodcast

func (l *Library) IsPodcast() bool

IsPodcast reports whether the library holds podcasts rather than books.

type LibraryCreate

type LibraryCreate struct {
	Name      string   `json:"name"`
	Folders   []Folder `json:"folders"`
	MediaType string   `json:"mediaType,omitempty"`
	Provider  string   `json:"provider,omitempty"`
	Icon      string   `json:"icon,omitempty"`
}

LibraryCreate holds the fields POST /api/libraries accepts. Folders are paths on the Audiobookshelf server, not on the caller's machine.

type LibraryFile

type LibraryFile struct {
	Ino             string       `json:"ino"`
	Metadata        FileMetadata `json:"metadata"`
	IsSupplementary bool         `json:"isSupplementary"`
	AddedAt         int64        `json:"addedAt"`
	UpdatedAt       int64        `json:"updatedAt"`
	FileType        string       `json:"fileType"` // audio, ebook, image, text, metadata, unknown
}

type LibrarySettings

type LibrarySettings struct {
	CoverAspectRatio                   int      `json:"coverAspectRatio"`
	DisableWatcher                     bool     `json:"disableWatcher"`
	SkipMatchingMediaWithASIN          bool     `json:"skipMatchingMediaWithAsin"`
	SkipMatchingMediaWithISBN          bool     `json:"skipMatchingMediaWithIsbn"`
	AudiobooksOnly                     bool     `json:"audiobooksOnly"`
	EpubsAllowScriptedContent          bool     `json:"epubsAllowScriptedContent"`
	HideSingleBookSeries               bool     `json:"hideSingleBookSeries"`
	OnlyShowLaterBooksInContinueSeries bool     `json:"onlyShowLaterBooksInContinueSeries"`
	MetadataPrecedence                 []string `json:"metadataPrecedence"`
	PodcastSearchRegion                string   `json:"podcastSearchRegion"`
	MarkAsFinishedPercentComplete      *float64 `json:"markAsFinishedPercentComplete"`
	MarkAsFinishedTimeRemaining        *float64 `json:"markAsFinishedTimeRemaining"`
}

type LibraryStats

type LibraryStats struct {
	TotalItems       int        `json:"totalItems"`
	TotalAuthors     int        `json:"totalAuthors"`
	TotalGenres      int        `json:"totalGenres"`
	TotalDuration    float64    `json:"totalDuration"`
	TotalSize        int64      `json:"totalSize"`
	NumAudioTracks   int        `json:"numAudioTracks"`
	LargestItems     []StatItem `json:"largestItems"`
	LongestItems     []StatItem `json:"longestItems"`
	AuthorsWithCount []struct {
		ID    string `json:"id"`
		Name  string `json:"name"`
		Count int    `json:"count"`
	} `json:"authorsWithCount"`
	GenresWithCount []struct {
		Genre string `json:"genre"`
		Count int    `json:"count"`
	} `json:"genresWithCount"`
}

type LibraryUpdate

type LibraryUpdate struct {
	Name     *string        `json:"name,omitempty"`
	Provider *string        `json:"provider,omitempty"`
	Icon     *string        `json:"icon,omitempty"`
	Settings map[string]any `json:"settings,omitempty"`
}

LibraryUpdate holds the editable library fields; nil pointers are left unchanged.

type ListOptions

type ListOptions struct {
	Limit  int
	Page   int
	Sort   string
	Desc   bool
	Filter string
}

ListOptions pages through authors or series listings.

type ListeningStatItem

type ListeningStatItem struct {
	ID            string          `json:"id"`
	TimeListening float64         `json:"timeListening"`
	MediaMetadata json.RawMessage `json:"mediaMetadata"`
}

type ListeningStats

type ListeningStats struct {
	TotalTime      float64                      `json:"totalTime"`
	Items          map[string]ListeningStatItem `json:"items"`
	Days           map[string]float64           `json:"days"`
	DayOfWeek      map[string]float64           `json:"dayOfWeek"`
	Today          float64                      `json:"today"`
	RecentSessions []Session                    `json:"recentSessions"`
}

type MatchOptions

type MatchOptions struct {
	Provider        string `json:"provider,omitempty"` // audible, audible.uk, google, itunes, openlibrary, fantlab, audiobookcovers, custom-<id>...; default is the library's provider
	Title           string `json:"title,omitempty"`
	Author          string `json:"author,omitempty"`
	ISBN            string `json:"isbn,omitempty"`
	ASIN            string `json:"asin,omitempty"`
	OverrideCover   bool   `json:"overrideCover"`
	OverrideDetails bool   `json:"overrideDetails"`
}

MatchOptions steers a quick match against a metadata provider.

type MatchResult

type MatchResult struct {
	Updated     bool   `json:"updated"`
	LibraryItem *Item  `json:"libraryItem"`
	Warning     string `json:"warning"`
}

MatchResult is the response of a quick match against a metadata provider.

type Media

type Media struct {
	ID            string       `json:"id"`
	LibraryItemID string       `json:"libraryItemId"`
	Metadata      Metadata     `json:"metadata"`
	CoverPath     string       `json:"coverPath"`
	Tags          []string     `json:"tags"`
	NumTracks     int          `json:"numTracks"`
	NumAudioFiles int          `json:"numAudioFiles"`
	NumChapters   int          `json:"numChapters"`
	Duration      float64      `json:"duration"`
	Size          int64        `json:"size"`
	EbookFormat   string       `json:"ebookFormat"`
	AudioFiles    []AudioFile  `json:"audioFiles"`
	Chapters      []Chapter    `json:"chapters"`
	EbookFile     *EbookFile   `json:"ebookFile"`
	Tracks        []AudioTrack `json:"tracks"`

	// podcast
	NumEpisodes              int       `json:"numEpisodes"`
	AutoDownloadEpisodes     bool      `json:"autoDownloadEpisodes"`
	AutoDownloadSchedule     string    `json:"autoDownloadSchedule"`
	LastEpisodeCheck         int64     `json:"lastEpisodeCheck"`
	MaxEpisodesToKeep        int       `json:"maxEpisodesToKeep"`
	MaxNewEpisodesToDownload int       `json:"maxNewEpisodesToDownload"`
	Episodes                 []Episode `json:"episodes"`
}

Media is the item's book or podcast payload.

type MediaItemShare

type MediaItemShare struct {
	ID          string `json:"id"`
	MediaItemID string `json:"mediaItemId"`
	Slug        string `json:"slug"`
	// ISO timestamps, like the API key ones and unlike the epoch
	// milliseconds the rest of the API uses
	ExpiresAt string `json:"expiresAt"`
	CreatedAt string `json:"createdAt"`
}

MediaItemShare is a public link to one item.

type MediaProgress

type MediaProgress struct {
	ID                        string  `json:"id"`
	UserID                    string  `json:"userId"`
	LibraryItemID             string  `json:"libraryItemId"`
	EpisodeID                 string  `json:"episodeId"`
	MediaItemID               string  `json:"mediaItemId"`
	MediaItemType             string  `json:"mediaItemType"` // book or podcastEpisode
	Duration                  float64 `json:"duration"`
	Progress                  float64 `json:"progress"` // 0..1
	CurrentTime               float64 `json:"currentTime"`
	IsFinished                bool    `json:"isFinished"`
	HideFromContinueListening bool    `json:"hideFromContinueListening"`
	EbookLocation             string  `json:"ebookLocation"`
	EbookProgress             float64 `json:"ebookProgress"`
	LastUpdate                int64   `json:"lastUpdate"`
	StartedAt                 int64   `json:"startedAt"`
	FinishedAt                int64   `json:"finishedAt"`
}

type MediaUpdate

type MediaUpdate struct {
	Metadata *MetadataUpdate `json:"metadata,omitempty"`
	Tags     []string        `json:"tags,omitempty"`
	// podcast settings
	AutoDownloadEpisodes     *bool   `json:"autoDownloadEpisodes,omitempty"`
	AutoDownloadSchedule     *string `json:"autoDownloadSchedule,omitempty"`
	MaxEpisodesToKeep        *int    `json:"maxEpisodesToKeep,omitempty"`
	MaxNewEpisodesToDownload *int    `json:"maxNewEpisodesToDownload,omitempty"`
}

MediaUpdate is the PATCH /api/items/:id/media payload.

type Metadata

type Metadata struct {
	Title            string     `json:"title"`
	Subtitle         string     `json:"subtitle"`
	AuthorName       string     `json:"authorName"`
	AuthorNameLF     string     `json:"authorNameLF"`
	NarratorName     string     `json:"narratorName"`
	SeriesName       string     `json:"seriesName"`
	Authors          []NameRef  `json:"authors"`
	Narrators        []string   `json:"narrators"`
	Series           SeriesRefs `json:"series"`
	Genres           []string   `json:"genres"`
	PublishedYear    FlexString `json:"publishedYear"`
	PublishedDate    string     `json:"publishedDate"`
	Publisher        string     `json:"publisher"`
	Description      string     `json:"description"`
	DescriptionPlain string     `json:"descriptionPlain"`
	ISBN             string     `json:"isbn"`
	ASIN             string     `json:"asin"`
	Language         string     `json:"language"`
	Explicit         bool       `json:"explicit"`
	Abridged         bool       `json:"abridged"`

	// podcast
	Author         string     `json:"author"`
	ReleaseDate    string     `json:"releaseDate"`
	FeedURL        string     `json:"feedUrl"`
	ImageURL       string     `json:"imageUrl"`
	ItunesPageURL  string     `json:"itunesPageUrl"`
	ItunesID       FlexString `json:"itunesId"`
	ItunesArtistID FlexString `json:"itunesArtistId"`
	PodcastType    string     `json:"type"`
}

Metadata is the book or podcast metadata block. Book fields and podcast fields are both present; only the ones for the item's mediaType are set. The minified (list) shape carries the flattened *Name fields, the expanded (detail) shape carries the structured Authors/Narrators/Series slices as well.

func (*Metadata) AuthorDisplay

func (m *Metadata) AuthorDisplay() string

AuthorDisplay returns the author(s) as one string whichever shape was returned.

func (*Metadata) NarratorDisplay

func (m *Metadata) NarratorDisplay() string

NarratorDisplay returns the narrator(s) as one string whichever shape was returned.

func (*Metadata) SeriesDisplay

func (m *Metadata) SeriesDisplay() []string

SeriesDisplay returns "Series #seq" strings whichever shape was returned.

type MetadataUpdate

type MetadataUpdate struct {
	Title         *string     `json:"title,omitempty"`
	Subtitle      *string     `json:"subtitle,omitempty"`
	Authors       []NameRef   `json:"authors,omitempty"`   // books; {name} entries are created if new
	Narrators     []string    `json:"narrators,omitempty"` // books
	Series        []SeriesRef `json:"series,omitempty"`    // books; {name, sequence}
	Genres        []string    `json:"genres,omitempty"`
	PublishedYear *string     `json:"publishedYear,omitempty"`
	PublishedDate *string     `json:"publishedDate,omitempty"`
	Publisher     *string     `json:"publisher,omitempty"`
	Description   *string     `json:"description,omitempty"`
	ISBN          *string     `json:"isbn,omitempty"`
	ASIN          *string     `json:"asin,omitempty"`
	Language      *string     `json:"language,omitempty"`
	Explicit      *bool       `json:"explicit,omitempty"`
	Abridged      *bool       `json:"abridged,omitempty"`
	// podcast
	Author      *string `json:"author,omitempty"`
	FeedURL     *string `json:"feedUrl,omitempty"`
	ImageURL    *string `json:"imageUrl,omitempty"`
	ItunesID    *string `json:"itunesId,omitempty"`
	ReleaseDate *string `json:"releaseDate,omitempty"`
	PodcastType *string `json:"type,omitempty"`
}

MetadataUpdate is the editable metadata for a book (or podcast: Title, Author, Description, Genres, Language, Explicit, FeedURL, ...). Nil pointers are left unchanged; a pointer to an empty string clears the field.

type NameRef

type NameRef struct {
	ID   string `json:"id"`
	Name string `json:"name"`
}

NameRef is the {id, name} pair used for authors and series references.

type NarratorRow

type NarratorRow struct {
	ID       string `json:"id"`
	Name     string `json:"name"`
	NumBooks int    `json:"numBooks"`
}

type NewPodcast

type NewPodcast struct {
	LibraryID string `json:"libraryId"`
	FolderID  string `json:"folderId"`
	Path      string `json:"path"` // folder to create, inside the library folder
	Media     struct {
		Metadata             map[string]any `json:"metadata"`
		AutoDownloadEpisodes bool           `json:"autoDownloadEpisodes"`
	} `json:"media"`
	EpisodesToDownload []FeedEpisode `json:"episodesToDownload,omitempty"`
}

NewPodcast is the payload to add a podcast to a library.

type Notification

type Notification struct {
	ID            string            `json:"id"`
	LibraryID     string            `json:"libraryId"`
	EventName     string            `json:"eventName"`
	URLs          []string          `json:"urls"`
	TitleTemplate string            `json:"titleTemplate"`
	BodyTemplate  string            `json:"bodyTemplate"`
	Headers       map[string]string `json:"headers"`
	Enabled       bool              `json:"enabled"`
	Type          string            `json:"type"`
	LastFiredAt   int64             `json:"lastFiredAt"`
	NumSuccess    int               `json:"numSuccess"`
	NumFailed     int               `json:"numFailed"`
}

Notification is one configured notification: an event, and the webhook to fire when it happens.

type NotificationSettings

type NotificationSettings struct {
	AppriseType          string         `json:"appriseType"`
	AppriseAPIURL        string         `json:"appriseApiUrl"`
	Notifications        []Notification `json:"notifications"`
	MaxFailedAttempts    int            `json:"maxFailedAttempts"`
	MaxNotificationQueue int            `json:"maxNotificationQueue"`
	Enabled              bool           `json:"enabled"`
}

NotificationSettings is the server's notification configuration, with the notifications themselves.

type Permissions

type Permissions struct {
	Download                  bool `json:"download"`
	Update                    bool `json:"update"`
	Delete                    bool `json:"delete"`
	Upload                    bool `json:"upload"`
	CreateEreader             bool `json:"createEreader"`
	AccessAllLibraries        bool `json:"accessAllLibraries"`
	AccessAllTags             bool `json:"accessAllTags"`
	AccessExplicitContent     bool `json:"accessExplicitContent"`
	SelectedTagsNotAccessible bool `json:"selectedTagsNotAccessible"`
}

type PlayRequest

type PlayRequest struct {
	DeviceInfo         map[string]any `json:"deviceInfo,omitempty"`
	SupportedMimeTypes []string       `json:"supportedMimeTypes,omitempty"`
	MediaPlayer        string         `json:"mediaPlayer,omitempty"`
	ForceDirectPlay    bool           `json:"forceDirectPlay,omitempty"`
	ForceTranscode     bool           `json:"forceTranscode,omitempty"`
}

PlayRequest is what a client tells the server when it starts playing, so the server can pick a stream and track progress.

type Playlist

type Playlist struct {
	ID          string         `json:"id"`
	LibraryID   string         `json:"libraryId"`
	UserID      string         `json:"userId"`
	Name        string         `json:"name"`
	Description string         `json:"description"`
	Items       []PlaylistItem `json:"items"`
	LastUpdate  int64          `json:"lastUpdate"`
	CreatedAt   int64          `json:"createdAt"`
}

type PlaylistEntry

type PlaylistEntry struct {
	LibraryItemID string `json:"libraryItemId"`
	EpisodeID     string `json:"episodeId,omitempty"`
}

PlaylistEntry identifies a book or a podcast episode for playlist calls.

type PlaylistItem

type PlaylistItem struct {
	LibraryItemID string   `json:"libraryItemId"`
	EpisodeID     string   `json:"episodeId,omitempty"`
	LibraryItem   *Item    `json:"libraryItem,omitempty"`
	Episode       *Episode `json:"episode,omitempty"`
}

type PodcastSearchResult

type PodcastSearchResult struct {
	ID               FlexString `json:"id"`
	ArtistID         FlexString `json:"artistId"`
	Title            string     `json:"title"`
	ArtistName       string     `json:"artistName"`
	Description      string     `json:"description"`
	DescriptionPlain string     `json:"descriptionPlain"`
	ReleaseDate      string     `json:"releaseDate"`
	Genres           []string   `json:"genres"`
	Cover            string     `json:"cover"`
	TrackCount       int        `json:"trackCount"`
	FeedURL          string     `json:"feedUrl"`
	PageURL          string     `json:"pageUrl"`
	Explicit         bool       `json:"explicit"`
}

PodcastSearchResult is one iTunes hit from GET /api/search/podcast.

type ProgressUpdate

type ProgressUpdate struct {
	CurrentTime               *float64 `json:"currentTime,omitempty"`
	Duration                  *float64 `json:"duration,omitempty"`
	Progress                  *float64 `json:"progress,omitempty"` // 0..1
	IsFinished                *bool    `json:"isFinished,omitempty"`
	HideFromContinueListening *bool    `json:"hideFromContinueListening,omitempty"`
	EbookLocation             *string  `json:"ebookLocation,omitempty"`
	EbookProgress             *float64 `json:"ebookProgress,omitempty"`
}

ProgressUpdate sets progress fields; nil pointers are unchanged. Setting IsFinished true marks the item finished; CurrentTime is in seconds.

type SearchMatch

type SearchMatch struct {
	LibraryItem Item   `json:"libraryItem"`
	MatchKey    string `json:"matchKey"`
	MatchText   string `json:"matchText"`
}

type SearchResult

type SearchResult struct {
	Book      []SearchMatch `json:"book"`
	Podcast   []SearchMatch `json:"podcast"`
	Narrators []CountRow    `json:"narrators"`
	Tags      []CountRow    `json:"tags"`
	Genres    []CountRow    `json:"genres"`
	Series    []SeriesMatch `json:"series"`
	Authors   []Author      `json:"authors"`
}

func (*SearchResult) Items

func (r *SearchResult) Items() []SearchMatch

Items returns book or podcast matches, whichever the library holds.

type Series

type Series struct {
	ID               string          `json:"id"`
	Name             string          `json:"name"`
	NameIgnorePrefix string          `json:"nameIgnorePrefix"`
	Description      string          `json:"description"`
	LibraryID        string          `json:"libraryId"`
	AddedAt          int64           `json:"addedAt"`
	UpdatedAt        int64           `json:"updatedAt"`
	Books            []Item          `json:"books"`
	TotalDuration    float64         `json:"totalDuration"`
	Progress         *SeriesProgress `json:"progress"`
	RSSFeed          json.RawMessage `json:"rssFeed"`
}

type SeriesMatch

type SeriesMatch struct {
	Series Series `json:"series"`
	Books  []Item `json:"books"`
}

type SeriesProgress

type SeriesProgress struct {
	LibraryItemIDs         []string `json:"libraryItemIds"`
	LibraryItemIDsFinished []string `json:"libraryItemIdsFinished"`
	IsFinished             bool     `json:"isFinished"`
}

type SeriesRef

type SeriesRef struct {
	ID       string `json:"id,omitempty"`
	Name     string `json:"name"`
	Sequence string `json:"sequence,omitempty"`
}

SeriesRef is a book's membership in a series.

type SeriesRefs

type SeriesRefs []SeriesRef

SeriesRefs accepts either an array of series refs (expanded/normal item JSON) or a single object (list results filtered by series collapse the field to the matched series).

func (*SeriesRefs) UnmarshalJSON

func (s *SeriesRefs) UnmarshalJSON(b []byte) error

type SeriesUpdate

type SeriesUpdate struct {
	Name        *string `json:"name,omitempty"`
	Description *string `json:"description,omitempty"`
}

SeriesUpdate holds editable series fields; nil pointers are unchanged.

type ServerStats

type ServerStats struct {
	Books    SizeStats `json:"books"`
	Podcasts SizeStats `json:"podcasts"`
	Total    SizeStats `json:"total"`
}

type Session

type Session struct {
	ID            string          `json:"id"`
	UserID        string          `json:"userId"`
	LibraryID     string          `json:"libraryId"`
	LibraryItemID string          `json:"libraryItemId"`
	BookID        string          `json:"bookId"`
	EpisodeID     string          `json:"episodeId"`
	MediaType     string          `json:"mediaType"`
	MediaMetadata json.RawMessage `json:"mediaMetadata"`
	DisplayTitle  string          `json:"displayTitle"`
	DisplayAuthor string          `json:"displayAuthor"`
	CoverPath     string          `json:"coverPath"`
	Duration      float64         `json:"duration"`
	PlayMethod    int             `json:"playMethod"` // 0 direct play, 1 direct stream, 2 transcode, 3 local
	MediaPlayer   string          `json:"mediaPlayer"`
	DeviceInfo    *DeviceInfo     `json:"deviceInfo"`
	ServerVersion string          `json:"serverVersion"`
	Date          string          `json:"date"`
	DayOfWeek     string          `json:"dayOfWeek"`
	TimeListening float64         `json:"timeListening"`
	StartTime     float64         `json:"startTime"`
	CurrentTime   float64         `json:"currentTime"`
	StartedAt     int64           `json:"startedAt"`
	UpdatedAt     int64           `json:"updatedAt"`
	// open sessions only
	User *NameRef `json:"user,omitempty"`
}

type SessionsOptions

type SessionsOptions struct {
	UserID       string
	Sort         string // displayTitle, duration, playMethod, startTime, currentTime, timeListening, updatedAt, createdAt
	Desc         bool
	ItemsPerPage int
	Page         int
}

SessionsOptions filters the admin playback-session listing.

type Shelf

type Shelf struct {
	ID       string          `json:"id"` // continue-listening, continue-series, recently-added, listen-again, recent-series, discover, newest-authors, newest-episodes, continue-reading, ...
	Label    string          `json:"label"`
	Type     string          `json:"type"` // book, podcast, episode, series, authors
	Entities json.RawMessage `json:"entities"`
}

Shelf is one row of the personalized home page.

type SizeStats

type SizeStats struct {
	TotalSize     int64 `json:"totalSize"`
	NumItems      int   `json:"numItems"`
	NumAudioFiles int   `json:"numAudioFiles"`
}

type StatItem

type StatItem struct {
	ID       string  `json:"id"`
	Title    string  `json:"title"`
	Size     int64   `json:"size"`
	Duration float64 `json:"duration"`
}

type Status

type Status struct {
	App           string `json:"app"`
	ServerVersion string `json:"serverVersion"`
	IsInit        bool   `json:"isInit"`
	Language      string `json:"language"`
}

Status is the unauthenticated GET /status response.

type Task

type Task struct {
	ID          string         `json:"id"`
	Action      string         `json:"action"`
	Data        map[string]any `json:"data"`
	Title       string         `json:"title"`
	Description string         `json:"description"`
	Error       string         `json:"error"`
	ShowSuccess bool           `json:"showSuccess"`
	IsFailed    bool           `json:"isFailed"`
	IsFinished  bool           `json:"isFinished"`
	StartedAt   int64          `json:"startedAt"`
	FinishedAt  int64          `json:"finishedAt"`
}

type TrackOrder

type TrackOrder struct {
	Ino     string `json:"ino"`
	Exclude bool   `json:"exclude"`
}

TrackOrder is one audio file in an item's play order, identified by its inode as the server reports it in LibraryFiles.

type User

type User struct {
	ID                  string          `json:"id"`
	Username            string          `json:"username"`
	Email               string          `json:"email"`
	Type                string          `json:"type"` // root, admin, user, guest
	MediaProgress       []MediaProgress `json:"mediaProgress"`
	Bookmarks           []Bookmark      `json:"bookmarks"`
	IsActive            bool            `json:"isActive"`
	IsLocked            bool            `json:"isLocked"`
	LastSeen            int64           `json:"lastSeen"`
	CreatedAt           int64           `json:"createdAt"`
	Permissions         Permissions     `json:"permissions"`
	LibrariesAccessible []string        `json:"librariesAccessible"`
	ItemTagsSelected    []string        `json:"itemTagsSelected"`
	HasOpenIDLink       bool            `json:"hasOpenIDLink"`
	LatestSession       *Session        `json:"latestSession,omitempty"`
}

func (*User) IsAdmin

func (u *User) IsAdmin() bool

IsAdmin reports whether the user is root or admin.

type UserCreate

type UserCreate struct {
	Username            string          `json:"username"`
	Password            string          `json:"password"`
	Type                string          `json:"type,omitempty"`
	Email               string          `json:"email,omitempty"`
	IsActive            *bool           `json:"isActive,omitempty"`
	Permissions         map[string]bool `json:"permissions,omitempty"`
	LibrariesAccessible []string        `json:"librariesAccessible,omitempty"`
	ItemTagsSelected    []string        `json:"itemTagsSelected,omitempty"`
}

UserCreate holds the fields POST /api/users accepts. Type is the account kind: "user", "guest" or "admin".

type UserUpdate

type UserUpdate struct {
	Username            *string         `json:"username,omitempty"`
	Password            *string         `json:"password,omitempty"`
	Type                *string         `json:"type,omitempty"`
	Email               *string         `json:"email,omitempty"`
	IsActive            *bool           `json:"isActive,omitempty"`
	Permissions         map[string]bool `json:"permissions,omitempty"`
	LibrariesAccessible []string        `json:"librariesAccessible,omitempty"`
	ItemTagsSelected    []string        `json:"itemTagsSelected,omitempty"`
}

UserUpdate holds the editable account fields; the zero value changes nothing. Id, password hash, token and bookmarks cannot be set here.

type YearStats

type YearStats struct {
	TotalListeningSessions int     `json:"totalListeningSessions"`
	TotalListeningTime     float64 `json:"totalListeningTime"`
	NumBooksListened       int     `json:"numBooksListened"`
	NumBooksFinished       int     `json:"numBooksFinished"`
	NumAuthors             int     `json:"numAuthors"`
	NumGenres              int     `json:"numGenres"`
	NumSeries              int     `json:"numSeries"`
	NumNarrators           int     `json:"numNarrators"`
	TotalDurationListened  float64 `json:"totalDurationListened"`
	BooksFinished          []struct {
		ID         string  `json:"id"`
		Title      string  `json:"title"`
		Duration   float64 `json:"duration"`
		FinishedAt int64   `json:"finishedAt"`
	} `json:"booksFinished"`
	ListeningTimeByDay map[string]float64 `json:"listeningTimeByDay"`
	MostListenedAuthor *struct {
		Name string  `json:"name"`
		Time float64 `json:"time"`
	} `json:"mostListenedAuthor"`
	MostListenedNarrator *struct {
		Name string  `json:"name"`
		Time float64 `json:"time"`
	} `json:"mostListenedNarrator"`
	MostListenedGenre *struct {
		Genre string  `json:"genre"`
		Time  float64 `json:"time"`
	} `json:"mostListenedGenre"`
	TopAuthors []struct {
		Name string  `json:"name"`
		Time float64 `json:"time"`
	} `json:"topAuthors"`
	TopNarrators []struct {
		Name string  `json:"name"`
		Time float64 `json:"time"`
	} `json:"topNarrators"`
	TopGenres []struct {
		Genre string  `json:"genre"`
		Time  float64 `json:"time"`
	} `json:"topGenres"`
}

Jump to

Keyboard shortcuts

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