plexapi

package module
v3.0.0-dev.15 Latest Latest
Warning

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

Go to latest
Published: Nov 10, 2026 License: Apache-2.0 Imports: 18 Imported by: 0

README

plexapi

Go Reference Go version

plexapi lets your Go tool read a Plex Media Server and set each user's audio and subtitle tracks. Its built-in transport keeps the X-Plex-Token on that server.

It saves you writing your own Plex client, which needs the token header, the JSON envelope Plex wraps every answer in, retries and size limits. You supply the token, because it has no sign-in flow. It needs Go 1.27.1 or later, depends on httpclient and xmlx by the same author, and is licensed under Apache-2.0.

Why use it

plexapi is built for Go tools that run beside a Plex Media Server, such as exporters and sync services.

  • Typed calls read library items, live sessions, watch history, server statistics and a server's shared users.
  • It sets a user's audio or subtitle track with that user's token, never retried.
  • The token travels only in the X-Plex-Token header, and request paths cannot name another host. The built-in transport refuses every redirect.
  • It retries 408, 429 and 5xx answers other than 501, 505, 506, 508, 510 and 511, whose answer repeats, and transient network errors with backoff, honoring Retry-After.
  • Response bodies are capped before decoding.
  • A self-signed server works by pinning its CA, and TLS verification stays on.

Consider go-plex-client if your tool reacts to live WebSocket events, marks items watched or gets a token through the plex.tv/link PIN flow. Consider plexgo if you need the whole Plex Media Server and plex.tv API from an SDK generated from the Plex OpenAPI specification.

Install

go get github.com/cplieger/plexapi/v3@latest

Usage

// Token is a named type: a swapped token and URL is a compile error.
client, err := plexapi.New("http://plex:32400", plexapi.Token(token))
if err != nil { ... }

// Library indexing: sections and their items (rating keys, GUIDs, years).
sections, err := client.Sections(ctx)
items, err := client.SectionItems(ctx, plexapi.RatingKey(sections[0].Key))

// One item; the endpoint is polymorphic (movie/show/season/episode).
item, err := client.Metadata(ctx, "49915")
episodes, err := client.AllLeaves(ctx, "1345") // every episode of a show

// Live sessions and server-side-filtered watch history.
sessions, err := client.Sessions(ctx)
history, err := client.History(ctx, time.Now().Add(-24*time.Hour).Unix())

// Episodes Plex changed since a time, an upgraded file included, oldest
// change first, 500 per request.
for ep, err := range client.UpdatedSince(ctx, "2", plexapi.MetadataTypeEpisode, since, 500, nil) {
	if err != nil { ... }
	since = max(since, ep.UpdatedAt)
}

// Ask Plex to refresh one item's metadata; the PUT is sent once.
err = client.RefreshMetadata(ctx, "49915")

// Plex records a track change against the user whose token sent it,
// so change a user's tracks with a client holding that user's token.
userClient := client.ForToken(plexapi.Token(userToken))
err = userClient.SetSubtitleStream(ctx, plexapi.StreamSelection{PartID: partID, StreamID: streamID})

// plex.tv: the shared users of a server, with their access tokens.
tv := plexapi.NewTV(plexapi.Token(adminToken))
shared, err := tv.SharedServers(ctx, machineID)

A rating key is the number Plex gives each library item, and a GUID is an item's external ID such as imdb://tt0903747. For a server behind a self-signed certificate, pin its CA with WithCACertPEM. Verification stays on, and your code reads the PEM file:

pem, _ := os.ReadFile(caPath) // the caller owns file I/O
client, err := plexapi.New(serverURL, plexapi.Token(token), plexapi.WithCACertPEM(pem))

API

  • New(baseURL, token, ...Option) builds a server client. ForToken gives the same server and connection pool another user's token.
  • Options are WithCACertPEM, WithMaxAttempts, WithBaseDelay, WithTimeout, WithMaxBodyBytes, WithMaxListBodyBytes, WithLogger, WithOnRetry and WithHTTPClient.
  • Library reads are Sections, SectionItems, SectionItemsPage, WalkSectionItems, RecentlyAdded, UpdatedSince, Metadata, Children, AllLeaves, ItemExists, ItemsByGUID, ShowForEpisodeGUID and CountSectionItems.
  • Activity and server reads are Sessions, History, WalkHistory, Activities, UpdateStatus, Identity, Accounts, AdminAccount, Providers, StatisticsResources and StatisticsBandwidth.
  • Writes are SetAudioStream, SetSubtitleStream, DisableSubtitles and RefreshMetadata. NewTV(token).SharedServers(machineID) lists a server's shared users from plex.tv.
  • WalkSectionItems and WalkHistory read a large listing one Page at a time.
  • FlexInt64 and FlexBool read fields Plex sends in more than one form.
  • To decode into your own types, pass a path builder such as MetadataPath to FetchMetadata, FetchMetadataList or FetchDirectory. Get calls any endpoint no typed call covers.
  • Errors are ErrNotFound, *StatusError with IsTransient, *ResponseTooLargeError, IsNotFound and IsConfigError.

The full reference is on pkg.go.dev. How plexapi works explains each group's behavior.

How it protects the token

The token grants full access to the server, so the client defends it on every request:

  • The token goes in the X-Plex-Token header only, never in a query string, so a logged URL cannot leak it.
  • Redirects are refused. Go forwards custom headers on a cross-origin redirect, so a hostile 302 would hand the token to another host. The Plex API issues no redirects.
  • A request path must be relative to the server. An absolute or scheme-relative path, which would point the request at another host, is rejected before any request is built.
  • Rating keys are checked to be numbers before they go into a URL.
  • Pinning a CA keeps TLS verification on and trusts only that CA. The built-in transport has no option that turns verification off.
  • New logs a warning when the base URL is plain http:// to a host that is not local, because the token would travel unencrypted. It treats localhost, a loopback address and a hostname without a dot, such as the Docker container name plex, as local.
  • Transport errors are reduced to their cause, so error text never holds a full request URL.

Redirect refusal and TLS verification belong to the built-in transport. A client you pass with WithHTTPClient replaces it, so that client must refuse redirects and verify TLS itself.

How it handles failures

  • GET requests are retried on 408, 429 and 5xx answers other than 501, 505, 506, 508, 510 and 511, and on transient network errors, with jittered exponential backoff that honors Retry-After. StatusError.IsTransient reports the same statuses. WithMaxAttempts(1) turns retries off.
  • A track change or a metadata refresh is a PUT and is sent at most once, never retried.
  • Each attempt times out after 15 seconds without response headers, which makes a stalled attempt a retryable error. WithTimeout sets a per-request limit, 2 minutes by default, that applies only when your context has no deadline. Your deadline always wins.
  • Response bodies are capped before decoding, at 10 MB by default and 40 MB for full section listings. Both are configurable, and a body over the cap returns *ResponseTooLargeError instead of a cut-off decode.

Unsupported by design

These are deliberate non-goals:

Feature Rationale
Library management writes (edit metadata, delete items, trigger library scans) plexapi serves tools that read a library and pick tracks, so it models only track changes and one-item metadata refreshes.
WebSocket notifications A different transport whose reconnect policy belongs to each app. BaseTransport() and RedirectPolicy() let your own dialer reuse the hardened transport.
Full plex.tv account surface (devices, friends, PINs) SharedServers is the one account call the client covers.
Insecure TLS (InsecureSkipVerify) Pin the CA instead. The built-in transport always verifies TLS.
Response caching or request coalescing Your code owns caching. The client holds no cache and takes no locks of its own.

Documentation

  • How plexapi works is for developers who need each call's contract, the defaults, the read caps, the types and the error classes.
  • Walking a large listing is for developers who page through a section or read what changed in it since a time.

Contributing

Issues and pull requests are welcome. See CONTRIBUTING.md.

Disclaimer

This project is built with care and follows security best practices, but it is intended for personal / self-hosted use. No guarantees of fitness for production environments. Use at your own risk.

This project was built with AI-assisted tooling using Claude, GPT, and Kiro. The human maintainer defines architecture, supervises implementation, and makes all final decisions.

License

Apache-2.0. See LICENSE.

Documentation

Overview

Package plexapi is a typed, resilient client for the Plex Media Server HTTP API, plus a small client for the plex.tv account API.

New builds the server Client and NewTV the plex.tv TV client.

Security model

The X-Plex-Token grants full server access, so the client defends it on every request:

  • The token travels only in the X-Plex-Token header, never a query string.
  • Redirects are never followed, because Go forwards custom headers on a cross-origin redirect.
  • Every request path must be server-relative. An absolute or scheme-relative reference is rejected.
  • A self-signed Plex works by pinning its CA with WithCACertPEM, and TLS verification stays on.

Resilience model

GET requests on the server client retry the answers httpclient's status rule accepts (408, 429 and a 5xx other than 501, 505, 506, 508, 510 and 511) and transient transport errors with jittered exponential backoff, honoring Retry-After. A PUT is never retried, so a change is applied at most once per call. Response bodies are size-capped before decode.

Wire model

MC is Plex's MediaContainer envelope, Item the polymorphic metadata item and FlexInt a numeric field Plex sends as a number or a quoted string. The path builders carry each endpoint's path and read cap, and Client.FetchMetadata, Client.FetchMetadataList and Client.FetchDirectory decode them into a caller-owned type. Client.Get is the escape hatch for an endpoint with no typed method. docs/how-it-works.md covers every option, cap and error.

Index

Constants

View Source
const (
	// SectionTypeMovie and SectionTypeShow are the section "type" values.
	SectionTypeMovie = "movie"
	SectionTypeShow  = "show"
	// TypeEpisode is the metadata "type" string on episode items.
	TypeEpisode = "episode"
	// MetadataTypeMovie and MetadataTypeEpisode are the numeric type IDs
	// for ?type= filters.
	MetadataTypeMovie   = 1
	MetadataTypeEpisode = 4
)

Section type strings and metadata type IDs used in section filters.

View Source
const DefaultMaxBodyBytes = 10 << 20

DefaultMaxBodyBytes caps metadata, session, history, and server-info responses (10 MB).

View Source
const DefaultMaxListBodyBytes = 40 << 20

DefaultMaxListBodyBytes caps full section listings (40 MB).

Variables

View Source
var ErrNotFound = errors.New("not found")

ErrNotFound is returned when Plex answers 404 for an item lookup.

Functions

func IsConfigError

func IsConfigError(err error) bool

IsConfigError reports whether err is a 4xx StatusError that IsTransient does not report, a configuration or authorization problem that will not fix itself.

func IsNotFound

func IsNotFound(err error) bool

IsNotFound reports whether err is (or wraps) the ErrNotFound sentinel.

Types

type Account

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

Account is a Plex system account from GET /accounts.

type Activity

type Activity struct {
	Progress         *float64
	UUID             string
	Type             string
	Title            string
	Subtitle         string
	LibrarySectionID string
}

Activity is one server background task from GET /activities (a library scan, media analysis, credits detection). Progress is a percentage, -1 when Plex reports it as indeterminate and nil when absent. LibrarySectionID is the section the task works on, read from the activity's Context, empty for a server-wide task.

type Client

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

Client is a Plex Media Server API client for one base URL + token. A single Client is safe for concurrent use. Construct with New.

func New

func New(baseURL string, token Token, opts ...Option) (*Client, error)

New parses and validates baseURL (http/https scheme, non-empty host) and returns a Client. Unless WithHTTPClient overrides it, the transport is: OS trust store or the pinned CA from WithCACertPEM, a per-attempt response-header timeout, an httpclient retry round-tripper (the statuses httpclient.IsRetryableStatus accepts and transient transport errors, honoring Retry-After), and a refuse-all redirect policy. Construction warns via slog when baseURL is plain http to a non-local host.

func (*Client) Accounts

func (c *Client) Accounts(ctx context.Context) ([]Account, error)

Accounts returns the server's system accounts (GET /accounts): the local account IDs history entries reference.

func (*Client) Activities

func (c *Client) Activities(ctx context.Context) ([]Activity, error)

Activities returns the server's running background tasks (GET /activities). An activity whose Context is absent or not an object decodes with an empty LibrarySectionID rather than failing the call.

func (*Client) AdminAccount

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

AdminAccount resolves the server's admin (owner) system account: the owner is always account id 1 in the system accounts list.

It deliberately does not consult /myplex/account: that endpoint's username decodes as "" and previously name-matched the id-0 placeholder account, so consumers comparing session user ids against the admin id skipped every owner event. Verified live 2026-07 against Plex 1.43.3.

func (*Client) AllLeaves

func (c *Client) AllLeaves(ctx context.Context, key RatingKey) ([]Item, error)

AllLeaves returns an item's leaf descendants (every episode of a show).

func (*Client) BaseTransport

func (c *Client) BaseTransport() *http.Transport

BaseTransport returns an independent clone of the hardened base transport the client was constructed with — the same CA trust and per-attempt response-header timeout, without the retry round-tripper. It is the seam for a caller-owned protocol upgrade (a WebSocket dialer) that must share the client's trust settings while owning its own dial policy. Mutating the returned clone never affects the client. Returns nil when the client was built with WithHTTPClient.

func (*Client) BaseURL

func (c *Client) BaseURL() *url.URL

BaseURL returns a deep copy of the configured server base URL (for deriving a websocket URL or logging the host). Mutating it never re-targets the client.

func (*Client) Children

func (c *Client) Children(ctx context.Context, key RatingKey) ([]Item, error)

Children returns an item's direct children (a show's seasons, a season's episodes).

func (*Client) CountSectionItems

func (c *Client) CountSectionItems(ctx context.Context, section RatingKey, metadataType int) (int64, error)

CountSectionItems returns the number of items in a library section, optionally filtered to one metadata type (metadataType > 0 adds ?type=N; 0 means unfiltered). It requests a single item and reads the container's totalSize body field — the X-Plex-Container-Total-Size header is used nowhere because it is not populated for type-filtered queries.

func (*Client) DisableSubtitles

func (c *Client) DisableSubtitles(ctx context.Context, partID int) error

DisableSubtitles turns subtitles off for a media part (stream ID 0).

func (*Client) FetchDirectory

func (c *Client) FetchDirectory[T any](ctx context.Context, path Path) ([]T, error)

FetchDirectory fetches a general-cap endpoint and decodes the {"MediaContainer":{"Directory":[...]}} envelope (library sections) into the caller-owned type T.

func (*Client) FetchMetadata

func (c *Client) FetchMetadata[T any](ctx context.Context, path Path) ([]T, error)

FetchMetadata fetches a general-cap endpoint and decodes the {"MediaContainer":{"Metadata":[...]}} envelope into the caller-owned item type T. Compose it with the path builders (HistoryPath, MetadataPath, ...); use FetchMetadataList for the ListPath builders (SectionItemsPath, RecentlyAddedPath).

A generic METHOD (Go 1.27): the type parameter is the caller's item type, so a consumer that wants to mock this surface wraps it in a non-generic method of its own (see plex-language-sync's internal/plex adapter).

func (*Client) FetchMetadataList

func (c *Client) FetchMetadataList[T any](ctx context.Context, path ListPath) ([]T, error)

FetchMetadataList is FetchMetadata under the large-listing read cap (WithMaxListBodyBytes). It accepts only ListPath.

func (*Client) ForToken

func (c *Client) ForToken(token Token) *Client

ForToken returns a Client for the same server and transport but a different token — the per-user client for stream selection (see SetAudioStream).

func (*Client) Get

func (c *Client) Get(ctx context.Context, path string, result any) error

Get fetches a server-relative path and decodes the JSON response into result. It is the escape hatch for endpoints without a typed method; the same hardening (path guard, redirect refusal, retries, body cap) applies.

func (*Client) History

func (c *Client) History(ctx context.Context, sinceUnix int64) ([]Item, error)

History returns watch-history entries viewed at or after sinceUnix, newest first, filtered server-side (see HistoryPath for the literal-operator wire contract).

func (*Client) Identity

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

Identity returns the server identity from GET / (name, machine ID, version, platform, Plex Pass subscription, active transcode count).

func (*Client) ItemExists

func (c *Client) ItemExists(ctx context.Context, key RatingKey) (bool, error)

ItemExists reports whether the rating key currently addresses an item: (true, nil) on 200, (false, nil) on a definitive 404. Any other failure (auth, rate limit, 5xx, transport) returns an error — existence could not be determined, and callers deciding "is this item stale?" must fail closed on it. The body is discarded without decoding.

func (*Client) ItemsByGUID

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

ItemsByGUID returns every library item matching an external GUID (e.g. "plex://episode/<hash>", "imdb://tt0903747") via /library/all. An unknown GUID yields an empty slice (Plex answers 200 with no items).

func (*Client) Metadata

func (c *Client) Metadata(ctx context.Context, key RatingKey) (*Item, error)

Metadata fetches one library item by rating key. The endpoint is polymorphic: the same call returns a movie, show, season, or episode Item depending on what the key addresses. Returns ErrNotFound when the key no longer exists.

func (*Client) Providers

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

Providers returns the media-provider tree (GET /media/providers with storage rollups) — per-library duration and storage totals.

func (*Client) RecentlyAdded

func (c *Client) RecentlyAdded(ctx context.Context, sectionKey RatingKey, metadataType int, sinceUnix int64) ([]Item, error)

RecentlyAdded returns a section's items of the given metadata type added at or after sinceUnix, newest first, filtered server-side (see RecentlyAddedPath for the literal-operator wire contract).

func (*Client) RedirectPolicy

func (c *Client) RedirectPolicy() func(req *http.Request, via []*http.Request) error

RedirectPolicy returns the client's redirect policy (its CheckRedirect function) so a caller-owned protocol upgrade — a websocket dialer — can enforce the same policy on its own http.Client. Nil when the client was built via WithHTTPClient without a CheckRedirect.

func (*Client) RefreshMetadata

func (c *Client) RefreshMetadata(ctx context.Context, key RatingKey) error

RefreshMetadata asks Plex to refresh one item's metadata (PUT /library/metadata/{key}/refresh). The key is checked as MetadataPath checks it before any request is built, and the PUT is sent at most once.

func (*Client) SectionItems

func (c *Client) SectionItems(ctx context.Context, sectionKey RatingKey) ([]Item, error)

SectionItems returns all items in a library section — the full listing used to index a library (rating keys, titles, years, GUIDs). Uses the large-body cap: a big section's listing is far larger than any other Plex response.

func (*Client) SectionItemsPage

func (c *Client) SectionItemsPage(ctx context.Context, section RatingKey, metadataType int, page Page) ([]Item, int64, error)

SectionItemsPage returns one page of a section listing (see SectionItemsPagePath) and the section's totalSize, 0 when Plex omits it. It decodes under the list cap.

func (*Client) Sections

func (c *Client) Sections(ctx context.Context) ([]Section, error)

Sections returns every library section. Filter by Section.Type (SectionTypeMovie, SectionTypeShow) app-side.

func (*Client) Sessions

func (c *Client) Sessions(ctx context.Context) ([]Item, error)

Sessions returns the currently playing sessions (GET /status/sessions). Session items populate User, Player, Session, TranscodeSession, and the Media graph; a direct-play session has no TranscodeSession.

func (*Client) SetAudioStream

func (c *Client) SetAudioStream(ctx context.Context, sel StreamSelection) error

SetAudioStream selects the audio stream for a media part.

Plex stores stream selection per user: a write is recorded against the REQUESTING TOKEN's user, and a library read returns the reading token's own selection. Selecting for another user requires that user's token — use ForToken. Mutations are applied at most once (never retried).

func (*Client) SetSubtitleStream

func (c *Client) SetSubtitleStream(ctx context.Context, sel StreamSelection) error

SetSubtitleStream selects the subtitle stream for a media part. Same user-scoping contract as SetAudioStream.

func (*Client) ShowForEpisodeGUID

func (c *Client) ShowForEpisodeGUID(ctx context.Context, episodeGUID string) (string, error)

ShowForEpisodeGUID resolves an episode GUID to the rating key of the show currently containing it. Returns ("", nil) when the GUID matches nothing or when matches disagree on their show (an ambiguous GUID that must not drive a decision); a non-nil error means the lookup could not be completed.

func (*Client) StatisticsBandwidth

func (c *Client) StatisticsBandwidth(ctx context.Context, timespan int) ([]StatisticsBandwidth, error)

StatisticsBandwidth returns bandwidth samples from the Plex Pass endpoint /statistics/bandwidth. 404s (ErrNotFound) without Plex Pass.

func (*Client) StatisticsResources

func (c *Client) StatisticsResources(ctx context.Context, timespan int) ([]StatisticsResource, error)

StatisticsResources returns host CPU/memory samples from the Plex Pass endpoint /statistics/resources over the trailing timespan bucket. The endpoint 404s (ErrNotFound) without Plex Pass; callers degrade gracefully.

func (*Client) Token

func (c *Client) Token() Token

Token returns the client's token. Sanctioned in-process uses: comparing tokens for cache eviction/rotation, constructing the plex.tv client (NewTV) with the same credential, and authenticating a caller-owned protocol upgrade (the X-Plex-Token header on a websocket dial). Never log it, and never place it in a URL.

func (*Client) UpdateStatus

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

UpdateStatus returns the server's update check (GET /updater/status). ErrNotFound when the server does not expose the updater.

func (*Client) UpdatedSince

func (c *Client) UpdatedSince(ctx context.Context, section RatingKey, metadataType int, sinceUnix int64, size int, wait func(context.Context) error) iter.Seq2[Item, error]

UpdatedSince walks a section's items of metadataType updated at or after sinceUnix (UpdatedSincePath), oldest update first, up to size new items per request, calling a non-nil wait before each. Each request reads from the first item updated at or after the newest updatedAt yielded, so an item that changes mid-walk never hides an unread one; an updated one comes again. Every error is yielded once and ends the walk: a bad argument, a failed wait or request, an answer that ignores the filter, sort, size or totalSize or repeats or omits a ratingKey, and growth past the first totalSize plus size.

func (*Client) WalkHistory

func (c *Client) WalkHistory(ctx context.Context, sinceUnix int64, page Page, wait func(context.Context) error) iter.Seq2[HistoryEntry, error]

WalkHistory pages through watch history viewed at or after sinceUnix, oldest first (see HistoryPagePath), from page.Start, page.Size rows per request, under the general read cap. It stops, fails and calls a non-nil wait as WalkSectionItems does.

func (*Client) WalkSectionItems

func (c *Client) WalkSectionItems(ctx context.Context, section RatingKey, metadataType int, page Page, wait func(context.Context) error) iter.Seq2[Item, error]

WalkSectionItems pages through a section listing from page.Start, page.Size items per request with one request in flight; metadataType filters as in SectionItemsPagePath. It ends at an empty page or after totalSize items, and with an error once a growing listing has given totalSize+page.Size rows, counting the first page's totalSize. An item added or removed mid-walk can be skipped or read twice. The first error, a cancelled ctx included, is yielded once and ends the walk. A non-nil wait is called right before every page request, and its error ends it too.

type FlexBool

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

FlexBool decodes a Plex JSON flag sent as true/false, 0/1, "0"/"1", or "true"/"false". Null decodes to false.

Decoding never fails: any other value decodes to false and Valid reports false. A wrong wire type on one session field must not make the whole MediaContainer undecodable. The zero value is a valid false. FlexBool is decode-only: it has no MarshalJSON, so encoding one writes {}.

func (*FlexBool) Bool

func (b *FlexBool) Bool() bool

Bool returns the decoded value; false when Valid is false.

func (*FlexBool) UnmarshalJSON

func (b *FlexBool) UnmarshalJSON(data []byte) error

UnmarshalJSON decodes the accepted forms and never returns an error.

func (*FlexBool) Valid

func (b *FlexBool) Valid() bool

Valid reports whether the wire value was one of the accepted forms.

type FlexInt

type FlexInt int

FlexInt decodes a Plex JSON field that may arrive as a number or a quoted numeric string. Null, absent, and empty-string values decode to 0.

func (*FlexInt) UnmarshalJSON

func (f *FlexInt) UnmarshalJSON(data []byte) error

UnmarshalJSON accepts a JSON number, a quoted numeric string, null, or an empty string. Anything else (non-numeric text, floats, objects) is a parse error.

type FlexInt64

type FlexInt64 int64

FlexInt64 is FlexInt for 64-bit values (file sizes, unix timestamps). Null, absent, and empty-string values decode to 0; a pointer field of this type stays nil when the field is absent or null.

func (*FlexInt64) UnmarshalJSON

func (f *FlexInt64) UnmarshalJSON(data []byte) error

UnmarshalJSON accepts a JSON number, a quoted numeric string, null, or an empty string. Anything else is a parse error.

type GUID

type GUID struct {
	ID string `json:"id"`
}

GUID is one external-identity entry from an item's Guid array (e.g. "imdb://tt0903747", "tvdb://81189", "plex://episode/<hash>").

type HistoryEntry

type HistoryEntry struct {
	RatingKey  string
	HistoryKey string
	ViewedAt   int64
	AccountID  int64
}

HistoryEntry is one watch-history row from WalkHistory. Every decoded row is returned as Plex sent it: RatingKey is empty when Plex omits it, which it does for a play of an item since deleted, and ViewedAt is 0 when absent, so the caller decides which rows it can use. AccountID is the server-local account (see Accounts), 0 when absent.

HistoryKey is Plex's per-row key, kept verbatim when it is at most 512 bytes and empty otherwise. It is opaque: never parse it.

type Item

type Item struct {
	LastViewedAt         *FlexInt64        `json:"lastViewedAt,omitempty"`
	ViewCount            *FlexInt          `json:"viewCount,omitempty"`
	User                 *SessionUser      `json:"User,omitempty"`
	TranscodeSession     *TranscodeSession `json:"TranscodeSession,omitempty"`
	Session              *SessionBandwidth `json:"Session,omitempty"`
	Player               *Player           `json:"Player,omitempty"`
	GrandparentRatingKey string            `json:"grandparentRatingKey"`
	Key                  string            `json:"key"`
	RatingKey            string            `json:"ratingKey"`
	GrandparentKey       string            `json:"grandparentKey"`
	Title                string            `json:"title"`
	ParentTitle          string            `json:"parentTitle"`
	GrandparentTitle     string            `json:"grandparentTitle"`
	Type                 string            `json:"type"`
	GUID                 string            `json:"guid"`
	LibrarySectionTitle  string            `json:"librarySectionTitle"`
	SessionKey           string            `json:"sessionKey"`
	ParentRatingKey      string            `json:"parentRatingKey"`
	GUIDs                []GUID            `json:"Guid"`
	Media                []Media           `json:"Media"`
	Label                []Label           `json:"Label"`
	AddedAt              int64             `json:"addedAt"`
	UpdatedAt            int64             `json:"updatedAt"`
	ViewedAt             int64             `json:"viewedAt"`
	Year                 int               `json:"year"`
	Index                FlexInt           `json:"index"`
	ParentIndex          FlexInt           `json:"parentIndex"`
	LibrarySectionID     FlexInt           `json:"librarySectionID"`
	AccountID            FlexInt           `json:"accountID"`
}

Item is Plex's polymorphic metadata item: episodes, seasons, shows, movies, history entries, and live sessions all share this wire shape with different fields populated. Field presence follows the endpoint: a library listing populates identity + GUIDs, a session adds User / Player / TranscodeSession, a metadata fetch adds the Media→Part→Stream graph.

LastViewedAt and ViewCount are the token's account's watch state, nil when absent; AddedAt and UpdatedAt are Unix seconds, <= 0 when unknown.

func (*Item) EpisodeNum

func (i *Item) EpisodeNum() int

EpisodeNum returns the episode index (Index), 0 when absent.

func (*Item) SeasonNum

func (i *Item) SeasonNum() int

SeasonNum returns the season index (ParentIndex), 0 when absent.

type Label

type Label struct {
	Tag string `json:"tag"`
}

Label is a label tag on a metadata item.

type ListPath

type ListPath string

ListPath is a server-relative full-listing endpoint path whose response decodes under the large-listing read cap (WithMaxListBodyBytes). Produced by the listing builders (SectionItemsPath, SectionItemsPagePath, RecentlyAddedPath, UpdatedSincePath); Client.FetchMetadataList accepts only this type.

func RecentlyAddedPath

func RecentlyAddedPath(section RatingKey, metadataType int, sinceUnix int64) (ListPath, error)

RecentlyAddedPath returns a section's listing path filtered server-side to items of metadataType added at or after sinceUnix, newest first. A recently-added window is a section listing (ListPath): a generous window on a large section outgrows the general cap.

func SectionItemsPagePath

func SectionItemsPagePath(section RatingKey, metadataType int, page Page) (ListPath, error)

SectionItemsPagePath returns one page of a section listing; metadataType > 0 adds a ?type= filter (0 is unfiltered). It validates the section key and the page.

func SectionItemsPath

func SectionItemsPath(section RatingKey) (ListPath, error)

SectionItemsPath returns the full-listing endpoint path for a library section, validating the section key first.

func UpdatedSincePath

func UpdatedSincePath(section RatingKey, metadataType int, sinceUnix int64) (ListPath, error)

UpdatedSincePath returns a section's listing path filtered server-side to items of metadataType (MetadataTypeMovie or MetadataTypeEpisode) whose updatedAt is at or after sinceUnix, oldest update first. It refuses an invalid section key, any other metadata type and a negative bound.

type MC

type MC[T any] struct {
	MediaContainer T `json:"MediaContainer"`
}

MC is the generic MediaContainer envelope Plex wraps every JSON response in. Typed methods decode through it internally; it is exported for use with Get on endpoints the typed surface does not model.

type Media

type Media struct {
	VideoResolution string  `json:"videoResolution"`
	VideoCodec      string  `json:"videoCodec"`
	Part            []Part  `json:"Part"`
	ID              FlexInt `json:"id"`
	Bitrate         int     `json:"bitrate"`
}

Media is one media rendition of an item, wrapping its parts.

ID is FlexInt because the Media→Part→Stream graph is the one place Plex disagrees with itself about the wire type of an id: /library/metadata/<key> and /library/sections/<n>/all send a bare number, /status/sessions sends the same field quoted (verified live 2026-08-21 against Plex 1.43.3). A plain int makes an active session's payload undecodable and takes every other field on the MediaContainer down with it.

type MediaProvider

type MediaProvider struct {
	Identifier string            `json:"identifier"`
	Features   []ProviderFeature `json:"Feature"`
}

MediaProvider is one provider entry in MediaProviders.

type MediaProviders

type MediaProviders struct {
	FriendlyName      string          `json:"friendlyName"`
	MachineIdentifier string          `json:"machineIdentifier"`
	Version           string          `json:"version"`
	MediaProviders    []MediaProvider `json:"MediaProvider"`
}

MediaProviders models GET /media/providers?includeStorage=1: the per- library duration/storage rollups behind library metrics.

type Option

type Option func(*options)

Option configures New.

func WithBaseDelay

func WithBaseDelay(d time.Duration) Option

WithBaseDelay sets the initial retry backoff (default 200ms).

func WithCACertPEM

func WithCACertPEM(pem []byte) Option

WithCACertPEM pins the CA(s) in pem as the sole TLS trust anchors, for a Plex behind a self-signed or private CA. The caller owns reading the PEM (the library does no file I/O); an empty pem is an error at construction.

func WithHTTPClient

func WithHTTPClient(hc *http.Client) Option

WithHTTPClient supplies a caller-owned *http.Client, replacing the built-in transport entirely (no retry round-tripper, no CA pinning, no redirect policy are installed). Intended for tests and callers with bespoke transport needs.

func WithLogger

func WithLogger(l *slog.Logger) Option

WithLogger sets the slog.Logger for the client's own diagnostics (the construction-time plaintext-URL warning and the over-cap response warning). Defaults to slog.Default().

func WithMaxAttempts

func WithMaxAttempts(n int) Option

WithMaxAttempts sets the TOTAL number of attempts per GET including the first (default 3, minimum 1 — 1 disables retries). Writes are never retried regardless.

func WithMaxBodyBytes

func WithMaxBodyBytes(n int64) Option

WithMaxBodyBytes sets the read cap for metadata, session, history, and server-info responses (default DefaultMaxBodyBytes). Non-positive values are ignored.

func WithMaxListBodyBytes

func WithMaxListBodyBytes(n int64) Option

WithMaxListBodyBytes sets the read cap for full section listings (default DefaultMaxListBodyBytes). Non-positive values are ignored.

func WithOnRetry

func WithOnRetry(fn func(attempt int, req *http.Request, resp *http.Response, err error)) Option

WithOnRetry installs a per-retry observability hook (attempt number, request, response, error), forwarded to the underlying round-tripper.

func WithTimeout

func WithTimeout(d time.Duration) Option

WithTimeout sets the per-request ceiling applied ONLY when the caller's context has no deadline (default 2m).

type Page

type Page struct {
	Start int
	Size  int
}

Page selects an offset window of a paged listing: Start is the offset of the first row (X-Plex-Container-Start, >= 0) and Size the row count per request (X-Plex-Container-Size, > 0). A walk starts at Start and reads Size rows per request.

type Part

type Part struct {
	Size     *FlexInt64 `json:"size,omitempty"`
	File     string     `json:"file"`
	Decision string     `json:"decision"`
	Stream   []Stream   `json:"Stream"`
	ID       FlexInt    `json:"id"`
}

Part is one file of a Media, wrapping its streams. File is the file's path as the server sees it. Decision is populated on session responses (the transcoder's per-part verdict). ID is FlexInt for the reason given on Media. Size is the file size in bytes: nil when absent or null, non-nil 0 when Plex sends 0.

type Path

type Path string

Path is a server-relative endpoint path whose response decodes under the general read cap (WithMaxBodyBytes). Construct one explicitly (plexapi.Path("/x")) only for an endpoint no builder models.

func AllLeavesPath

func AllLeavesPath(key RatingKey) (Path, error)

AllLeavesPath returns the leaf-descendants endpoint path for an item (every episode of a show), validating the key first.

func ChildrenPath

func ChildrenPath(key RatingKey) (Path, error)

ChildrenPath returns the direct-children endpoint path for an item (a show's seasons, a season's episodes), validating the key first.

func HistoryPagePath

func HistoryPagePath(sinceUnix int64, page Page) (Path, error)

HistoryPagePath returns one page of watch history viewed at or after sinceUnix, oldest first, so plays recorded during a walk land after the read position instead of shifting earlier pages. It validates the page. A general-cap Path for the reason given on HistoryPath.

func HistoryPath

func HistoryPath(sinceUnix int64) Path

HistoryPath returns the watch-history endpoint path filtered server-side to entries viewed at or after sinceUnix, newest first. It is deliberately a general-cap Path, not a ListPath: an over-cap error here is the tripwire for the malformed-operator failure mode (Plex answering with the FULL unfiltered history).

func MetadataPath

func MetadataPath(key RatingKey) (Path, error)

MetadataPath returns the metadata endpoint path for one library item, validating the key first. The endpoint is polymorphic: the same path returns a movie, show, season, or episode depending on the key.

func SectionsPath

func SectionsPath() Path

SectionsPath returns the library-sections directory endpoint path (GET /library/sections).

func SessionsPath

func SessionsPath() Path

SessionsPath returns the active-sessions endpoint path (GET /status/sessions).

type Player

type Player struct {
	Device            string `json:"device"`
	Product           string `json:"product"`
	State             string `json:"state"`
	MachineIdentifier string `json:"machineIdentifier"`
	Local             bool   `json:"local"`
}

Player is the Player element on a session item.

type ProviderDirectory

type ProviderDirectory struct {
	Title         string `json:"title"`
	ID            string `json:"id"`
	Type          string `json:"type"`
	DurationTotal int64  `json:"durationTotal"`
	StorageTotal  int64  `json:"storageTotal"`
}

ProviderDirectory is one library directory entry in MediaProviders.

type ProviderFeature

type ProviderFeature struct {
	Type        string              `json:"type"`
	Directories []ProviderDirectory `json:"Directory"`
}

ProviderFeature is one feature of a MediaProvider; content features carry the library directories.

type RatingKey

type RatingKey string

RatingKey is Plex's opaque numeric-string identifier for a library item (movie, show, season, episode) or section. The type exists so keys are validated once at the API boundary instead of being interpolated into URL paths unchecked.

func (RatingKey) String

func (r RatingKey) String() string

String returns the key as a plain string.

func (RatingKey) Validate

func (r RatingKey) Validate() error

Validate reports whether the key is a non-empty numeric string. Anything else indicates a programming error (a foreign identifier in a rating-key slot) that must not reach URL construction.

type ResponseTooLargeError

type ResponseTooLargeError struct {
	Path  string
	Limit int64
}

ResponseTooLargeError is returned when a response body exceeds the endpoint's read cap.

func (*ResponseTooLargeError) Error

func (e *ResponseTooLargeError) Error() string

Error implements the error interface.

type Section

type Section struct {
	ScannedAt *FlexInt64 `json:"scannedAt,omitempty"`
	Key       string     `json:"key"`
	Title     string     `json:"title"`
	Type      string     `json:"type"`
}

Section is a library section from GET /library/sections. ScannedAt is the last scan as unix seconds, nil when Plex omits it.

type ServerIdentity

type ServerIdentity struct {
	FriendlyName                  string `json:"friendlyName"`
	MachineIdentifier             string `json:"machineIdentifier"`
	Version                       string `json:"version"`
	Platform                      string `json:"platform"`
	PlatformVersion               string `json:"platformVersion"`
	MyPlexSubscription            bool   `json:"myPlexSubscription"`
	TranscoderActiveVideoSessions int    `json:"transcoderActiveVideoSessions"`
}

ServerIdentity is the server info from GET / (the union of the fields the consumers read; the endpoint returns more).

type SessionBandwidth

type SessionBandwidth struct {
	Location  string `json:"location"`
	Bandwidth int    `json:"bandwidth"`
}

SessionBandwidth is the Session element on a session item.

type SessionUser

type SessionUser struct {
	Title string  `json:"title"`
	ID    FlexInt `json:"id"`
}

SessionUser is the User element on a session or history item.

type SharedServer

type SharedServer struct {
	UserID      string `xml:"userID,attr"`
	Username    string `xml:"username,attr"`
	AccessToken string `xml:"accessToken,attr"`
}

SharedServer is one <SharedServer> element from the plex.tv shared_servers endpoint: a user the server is shared with, and the user-scoped access token for it.

type StatisticsBandwidth

type StatisticsBandwidth struct {
	Bytes int64 `json:"bytes"`
	At    int   `json:"at"`
}

StatisticsBandwidth is one bandwidth sample from the Plex Pass endpoint GET /statistics/bandwidth.

type StatisticsResource

type StatisticsResource struct {
	HostCPUUtilization    float64 `json:"hostCpuUtilization"`
	HostMemoryUtilization float64 `json:"hostMemoryUtilization"`
}

StatisticsResource is one host CPU/memory sample from the Plex Pass endpoint GET /statistics/resources.

type StatusError

type StatusError struct {
	Method string
	Path   string
	Status string
	Code   int
}

StatusError is returned for a non-200, non-404 Plex response, after any transparent retries are exhausted.

func (*StatusError) Error

func (e *StatusError) Error() string

Error implements the error interface.

func (*StatusError) IsTransient

func (e *StatusError) IsTransient() bool

IsTransient reports the answers httpclient's retry rule retries (httpclient.IsRetryableStatus): 408, 429 and a 5xx other than 501, 505, 506, 508, 510 and 511, whose answer repeats. httpclient.IsTransient then classifies a *StatusError like a transient transport error.

type Stream

type Stream struct {
	Key                  string     `json:"key"`
	LanguageCode         string     `json:"languageCode"`
	LanguageTag          string     `json:"languageTag"`
	DisplayTitle         string     `json:"displayTitle"`
	ExtendedDisplayTitle string     `json:"extendedDisplayTitle"`
	Title                string     `json:"title"`
	Codec                string     `json:"codec"`
	AudioChannelLayout   string     `json:"audioChannelLayout"`
	ID                   FlexInt    `json:"id"`
	StreamType           StreamType `json:"streamType"`
	Channels             int        `json:"channels"`
	Selected             bool       `json:"selected"`
	Default              bool       `json:"default"`
	Forced               bool       `json:"forced"`
	HearingImpaired      bool       `json:"hearingImpaired"`
	VisualImpaired       bool       `json:"visualImpaired"`
}

Stream is a single video/audio/subtitle stream on a Part. ID is FlexInt for the reason given on Media. Key is "/library/streams/<id>" for a stream read from a sidecar file and empty for a track inside the media file; Plex names no sidecar's path. Selected is the token's user's selection on a library read, and the playing user's (Item.User) on a session item. Plex sends Selected and Default only when true, and one part can mark several subtitle streams Default.

func (*Stream) IsAudio

func (s *Stream) IsAudio() bool

IsAudio reports whether the stream is an audio track.

func (*Stream) IsSubtitle

func (s *Stream) IsSubtitle() bool

IsSubtitle reports whether the stream is a subtitle track.

type StreamSelection

type StreamSelection struct {
	// PartID is the media part whose stream selection changes (Part.ID).
	PartID int
	// StreamID is the stream to select (Stream.ID). Zero disables the track
	// for a subtitle selection; see DisableSubtitles for the named form.
	StreamID int
}

StreamSelection names which stream to select on which media part. The two IDs are a struct rather than two adjacent ints because a transposition type-checked and produced a request against a part that does not exist — detectable only after the round trip, as a Plex error about the wrong object.

Both fields are required. The zero value selects nothing meaningful: part 0 is not a Plex part id, so a zero StreamSelection reaches the server and is refused there rather than silently retargeting.

type StreamType

type StreamType int

StreamType identifies the kind of stream. The integer values are the Plex wire format.

const (
	StreamTypeVideo    StreamType = 1
	StreamTypeAudio    StreamType = 2
	StreamTypeSubtitle StreamType = 3
)

Stream-type wire values.

type TV

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

TV is a client for the plex.tv account API (as opposed to a local Plex Media Server). It always verifies TLS against the OS trust store and never follows redirects, so the admin token cannot be forwarded off plex.tv by a compromised redirect or CDN front.

func NewTV

func NewTV(token Token, opts ...TVOption) *TV

NewTV returns a plex.tv client authenticated with the given token.

func (*TV) SharedServers

func (t *TV) SharedServers(ctx context.Context, machineIdentifier string) ([]SharedServer, error)

SharedServers returns the users the identified server is shared with, including their user-scoped access tokens. An empty response body (which plex.tv sometimes returns instead of an empty <MediaContainer/>) yields zero servers, not a parse error.

type TVOption

type TVOption func(*TV)

TVOption configures NewTV.

func WithTVBaseURL

func WithTVBaseURL(base string) TVOption

WithTVBaseURL replaces the plex.tv origin (tests).

func WithTVHTTPClient

func WithTVHTTPClient(hc *http.Client) TVOption

WithTVHTTPClient replaces the built-in hardened client (tests).

type Token

type Token string

Token is a Plex authentication token, the credential sent as X-Plex-Token.

It is a distinct type so it cannot be transposed with the server URL on New: the two are adjacent and both are strings on the wire, and a named type makes a swapped pair of variables a compile error.

type TranscodeSession

type TranscodeSession struct {
	TranscodeHwRequested    *FlexBool `json:"transcodeHwRequested,omitempty"`
	TranscodeHwFullPipeline *FlexBool `json:"transcodeHwFullPipeline,omitempty"`
	TranscodeHwDecoding     string    `json:"transcodeHwDecoding"`
	TranscodeHwEncoding     string    `json:"transcodeHwEncoding"`
	VideoDecision           string    `json:"videoDecision"`
	AudioDecision           string    `json:"audioDecision"`
	SubtitleDecision        string    `json:"subtitleDecision"`
	SourceVideoCodec        string    `json:"sourceVideoCodec"`
	SourceAudioCodec        string    `json:"sourceAudioCodec"`
	VideoCodec              string    `json:"videoCodec"`
	AudioCodec              string    `json:"audioCodec"`
}

TranscodeSession is the TranscodeSession element on a session item; its decision fields distinguish direct play / direct stream / transcode.

The TranscodeHw* fields report hardware transcoding: the two flags are nil when Plex omits them, and TranscodeHwDecoding / TranscodeHwEncoding name the hardware API Plex reports for that stage (for example "vaapi"), empty when it reports none.

type UpdateRelease

type UpdateRelease struct {
	Version string `json:"version"`
	State   string `json:"state"`
}

UpdateRelease is one release in UpdateStatus. State is Plex's release state ("available", "downloaded", "skipped", ...), passed through as sent.

type UpdateStatus

type UpdateStatus struct {
	CheckedAt *FlexInt64      `json:"checkedAt"`
	Status    *int            `json:"status"`
	Releases  []UpdateRelease `json:"Release"`
}

UpdateStatus is the server's update check from GET /updater/status. CheckedAt is the last check as unix seconds and Status the updater's error code (0 means no error); both are nil when absent. Download URLs are not decoded, because Plex embeds the server token in them.

Jump to

Keyboard shortcuts

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