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.
Security model ¶
The X-Plex-Token grants full server access, so the client defends it in depth, on every request, by construction:
- The token travels only in the X-Plex-Token header, never a query string, so it cannot leak through URL logging.
- Redirects are never followed: Go's default policy forwards custom headers (including X-Plex-Token) on cross-origin redirects, so a hostile 302 (MITM, DNS poisoning, compromised upstream) would otherwise exfiltrate the token.
- Every request path must be server-relative. An absolute or scheme-relative reference would override the configured host via URL resolution and send the token to that origin; the client rejects it.
- A self-signed Plex is supported by pinning its CA (WithCACertPEM): TLS verification stays ON, trusting only that CA. There is no "insecure skip verify" option.
- Construction warns (once, via slog) when the base URL is plain http to a non-local host, because the token would transit unencrypted.
Resilience model ¶
On the server Client, GET requests ride an httpx retry round-tripper: 429/502/503/504 and transient transport errors (timeouts, resets, DNS) are retried with jittered exponential backoff, honoring Retry-After on 429. Writes (PUT) go through the same client but are never retried (body replay is not enabled), so a mutation is applied at most once per call. A per-attempt response-header timeout on the transport makes a stalled attempt fail as a retryable error instead of hanging the sequence; a per-request default timeout (WithTimeout) applies only when the caller's context carries no deadline, so a caller deadline is always the authoritative budget. Response bodies are size-capped before decode.
The plex.tv TV client is deliberately outside this model: a minimal client (30s timeout, refuse-all redirects, no retry transport) for one fixed public endpoint whose sole production caller owns its own semantically-aware retry policy.
Wire model ¶
Plex wraps every JSON payload in a MediaContainer envelope and returns polymorphic metadata items (an episode, a season, a show, a movie, and a live session all share one shape with different fields populated). The package mirrors that honestly: MC[T] is the envelope, Item is the polymorphic metadata item, and FlexInt absorbs Plex's habit of returning numeric fields as either numbers or quoted strings depending on the endpoint. Typed methods cover the endpoints the consumers use; Get is the documented escape hatch for anything else (for example the Plex Pass statistics endpoints have typed helpers, but a new undocumented endpoint can be reached without waiting for a release).
Consumers that decode into their own domain types do not give up the package's wire-grammar ownership: the exported path builders (SessionsPath, HistoryPath, MetadataPath, ...) carry the endpoint paths, rating-key validation, the literal filter-operator contract, and — via their Path/ListPath return types — each endpoint's read-cap class, and the client's FetchMetadata / FetchMetadataList / FetchDirectory generic methods decode the MediaContainer envelopes into any caller-owned type over the same hardened transport, with the cap class enforced at compile time (a listing endpoint cannot be fetched under the general cap by accident). The typed Item methods are composition over exactly these pieces.
Those three decoders are generic METHODS (Go 1.27), so they cannot appear in an interface: a consumer that mocks this client wraps them in non-generic methods of its own.
Index ¶
- Constants
- Variables
- func IsConfigError(err error) bool
- func IsNotFound(err error) bool
- type Account
- type Client
- func (c *Client) Accounts(ctx context.Context) ([]Account, error)
- func (c *Client) AdminAccount(ctx context.Context) (*Account, error)
- func (c *Client) AllLeaves(ctx context.Context, key RatingKey) ([]Item, error)
- func (c *Client) BaseTransport() *http.Transport
- func (c *Client) BaseURL() *url.URL
- func (c *Client) Children(ctx context.Context, key RatingKey) ([]Item, error)
- func (c *Client) CountSectionItems(ctx context.Context, section RatingKey, metadataType int) (int64, error)
- func (c *Client) DisableSubtitles(ctx context.Context, partID int) error
- func (c *Client) FetchDirectory[T any](ctx context.Context, path Path) ([]T, error)
- func (c *Client) FetchMetadata[T any](ctx context.Context, path Path) ([]T, error)
- func (c *Client) FetchMetadataList[T any](ctx context.Context, path ListPath) ([]T, error)
- func (c *Client) ForToken(token Token) *Client
- func (c *Client) Get(ctx context.Context, path string, result any) error
- func (c *Client) History(ctx context.Context, sinceUnix int64) ([]Item, error)
- func (c *Client) Identity(ctx context.Context) (*ServerIdentity, error)
- func (c *Client) ItemExists(ctx context.Context, key RatingKey) (bool, error)
- func (c *Client) ItemsByGUID(ctx context.Context, guid string) ([]Item, error)
- func (c *Client) Metadata(ctx context.Context, key RatingKey) (*Item, error)
- func (c *Client) Providers(ctx context.Context) (*MediaProviders, error)
- func (c *Client) RecentlyAdded(ctx context.Context, sectionKey RatingKey, metadataType int, sinceUnix int64) ([]Item, error)
- func (c *Client) RedirectPolicy() httpx.CheckRedirect
- func (c *Client) SectionItems(ctx context.Context, sectionKey RatingKey) ([]Item, error)
- func (c *Client) Sections(ctx context.Context) ([]Section, error)
- func (c *Client) Sessions(ctx context.Context) ([]Item, error)
- func (c *Client) SetAudioStream(ctx context.Context, sel StreamSelection) error
- func (c *Client) SetSubtitleStream(ctx context.Context, sel StreamSelection) error
- func (c *Client) ShowForEpisodeGUID(ctx context.Context, episodeGUID string) (string, error)
- func (c *Client) StatisticsBandwidth(ctx context.Context, timespan int) ([]StatisticsBandwidth, error)
- func (c *Client) StatisticsResources(ctx context.Context, timespan int) ([]StatisticsResource, error)
- func (c *Client) Token() Token
- type FlexInt
- type GUID
- type Item
- type Label
- type ListPath
- type MC
- type Media
- type MediaProvider
- type MediaProviders
- type Option
- func WithBaseDelay(d time.Duration) Option
- func WithCACertPEM(pem []byte) Option
- func WithHTTPClient(hc *http.Client) Option
- func WithLogger(l *slog.Logger) Option
- func WithMaxAttempts(n int) Option
- func WithMaxBodyBytes(n int64) Option
- func WithMaxListBodyBytes(n int64) Option
- func WithOnRetry(fn httpx.OnRetry) Option
- func WithTimeout(d time.Duration) Option
- type Part
- type Path
- type Player
- type ProviderDirectory
- type ProviderFeature
- type RatingKey
- type ResponseTooLargeError
- type Section
- type ServerIdentity
- type SessionBandwidth
- type SessionUser
- type SharedServer
- type StatisticsBandwidth
- type StatisticsResource
- type StatusError
- type Stream
- type StreamSelection
- type StreamType
- type TV
- type TVOption
- type Token
- type TranscodeSession
Constants ¶
const ( // DefaultMaxBodyBytes caps metadata, session, history, and server-info // responses (10 MB). DefaultMaxBodyBytes = 10 << 20 // DefaultMaxListBodyBytes caps full section listings (40 MB). DefaultMaxListBodyBytes = 40 << 20 )
Default read caps per endpoint class. A single item or a session/history page fits well inside the general cap; a full library-section listing can be an order of magnitude larger. Both are configurable (WithMaxBodyBytes, WithMaxListBodyBytes) for deployments whose libraries outgrow them.
const ( // SectionTypeMovie and SectionTypeShow are the section "type" values. SectionTypeMovie = "movie" SectionTypeShow = "show" // TypeEpisode is the metadata "type" string on episode items. TypeEpisode = "episode" // MetadataTypeEpisode is the numeric type ID for ?type= filters. MetadataTypeEpisode = 4 )
Section type strings and metadata type IDs used in section filters.
Variables ¶
var ErrNotFound = errors.New("not found")
ErrNotFound is returned when Plex answers 404 for an item lookup. Detect with errors.Is(err, plexapi.ErrNotFound).
Functions ¶
func IsConfigError ¶
IsConfigError reports whether err is a Plex response indicating a configuration or authorization problem — a 4xx StatusError other than 408 (request timeout) and 429 (rate limit, retried transparently and Retry-After-honored). Such a failure will not resolve without operator action (a bad token, a wrong server), unlike a 5xx (Plex up but not ready) or a transport error, both of which may clear on their own. TLS/certificate failures surface as transport errors and remain the caller's concern to classify.
func IsNotFound ¶
IsNotFound reports whether err is (or wraps) the ErrNotFound sentinel.
Types ¶
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 ¶
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 httpx retry round-tripper (429/502/503/504 + transient transport errors, honoring Retry-After), and a refuse-all redirect policy so the token can never ride a hostile 3xx. Construction warns via slog when baseURL is plain http to a non-local host (the token would transit unencrypted).
func (*Client) Accounts ¶
Accounts returns the server's system accounts (GET /accounts): the local account IDs history entries reference.
func (*Client) AdminAccount ¶
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 is the plex.tv account email wrapped in a {"MyPlex":{...}} envelope; the previous implementation decoded a top-level username (silently yielding ""), name-matched it against the id-0 placeholder account (name=""), and returned the placeholder as the admin — 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) BaseTransport ¶
BaseTransport returns an independent clone of the hardened base transport the client was constructed with — the same CA trust (WithCACertPEM or the OS store) 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: the retry wrapper's base transport is not otherwise reachable, and rebuilding a transport from scratch silently drops a pinned CA. Mutating the returned clone never affects the client. Returns nil when the client was built with WithHTTPClient (the caller already owns that transport).
func (*Client) BaseURL ¶
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, whose every request resolves against the internal original — handing out that pointer would reopen the origin-mutation class the server-relative path guard exists to close.
func (*Client) Children ¶
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.
Named for the work rather than for the number: the other noun-named methods on Client (Sections, Identity, Accounts, Providers) each name a RESOURCE, so a request is the obvious reading, while a bare ContainerTotalSize read as a property of something the caller already held. The rest of that naming question is answered by the signature — a context plus an error is Go's cost signal — but a noun that names no resource does not get that for free.
func (*Client) DisableSubtitles ¶
DisableSubtitles turns subtitles off for a media part (stream ID 0).
func (*Client) FetchDirectory ¶
FetchDirectory fetches a general-cap endpoint and decodes the {"MediaContainer":{"Directory":[...]}} envelope (library sections) into the caller-owned type T. The Directory counterpart of FetchMetadata.
func (*Client) FetchMetadata ¶
FetchMetadata fetches a general-cap endpoint and decodes the {"MediaContainer":{"Metadata":[...]}} envelope — the dominant Plex response shape — into the caller-owned item type T. It is the exported decode kernel for consumers that keep their own domain models: the same generic the typed Item methods are built on. Compose it with the path builders (HistoryPath, MetadataPath, ...): the builder's return type carries the endpoint's read-cap class, so a listing-sized endpoint cannot compile against the general cap — use FetchMetadataList for the ListPath builders (SectionItemsPath, RecentlyAddedPath).
A generic METHOD (Go 1.27): the type parameter is the caller's item type, which the receiver knows nothing about, so before 1.27 this had to be a package-level function taking the client as its first argument. It is a method now because the operation belongs to the client's namespace. The consequence to know: a generic method can never satisfy an interface, so a consumer that wants to mock this surface must wrap it in a non-generic method of its own (see plex-language-sync's internal/plex adapter, which does exactly that).
func (*Client) FetchMetadataList ¶
FetchMetadataList is FetchMetadata under the large-listing read cap (WithMaxListBodyBytes). It accepts only ListPath — the full-listing endpoints (SectionItemsPath, RecentlyAddedPath), whose responses on a big library are an order of magnitude larger than any other Plex response.
func (*Client) ForToken ¶
ForToken returns a Client for the same server and transport but a different token — the per-user client for user-scoped writes (Plex records a stream-selection PUT against the requesting token's user). The underlying connection pool is shared.
func (*Client) Get ¶
Get fetches a server-relative path and decodes the JSON response into result. It is the escape hatch for endpoints without a typed method (decode through MC[T] for container-wrapped payloads); the same hardening (path guard, redirect refusal, retries, body cap) applies.
func (*Client) History ¶
History returns watch-history entries viewed at or after sinceUnix, newest first, filtered server-side (see HistoryPath for the literal-operator wire contract: one `>`, unencoded — Plex silently ignores a malformed operator and returns the FULL history).
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 ¶
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 ¶
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 ¶
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() httpx.CheckRedirect
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 without access to the live client. Pair it with BaseTransport, which carries the trust half of that seam. Nil when the client was built via WithHTTPClient without a CheckRedirect (net/http's follow-all default; the caller owns policy on that path).
func (*Client) SectionItems ¶
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) Sections ¶
Sections returns every library section. Filter by Section.Type (SectionTypeMovie, SectionTypeShow) app-side.
func (*Client) Sessions ¶
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 records stream-selection writes against the REQUESTING TOKEN's user (unlike reads, which are not user-scoped): selecting for another user requires that user's token — use ForToken. Falling back to the admin token writes to the admin's view and silently drops the target user's preference. 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 ¶
ShowForEpisodeGUID resolves an episode GUID to the rating key of the show currently containing it — the handle back from a watch-history episode GUID to its show after a library rebuild. 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 ¶
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.
type FlexInt ¶
type FlexInt int
FlexInt decodes a Plex JSON field that may arrive as a number or a quoted numeric string. Plex is inconsistent on numeric fields across endpoints (an episode index can be 14 or "14"); FlexInt absorbs both so callers use a plain int. Null, absent, and empty-string values decode to 0.
func (*FlexInt) UnmarshalJSON ¶
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 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 Item ¶
type Item struct {
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"`
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.
func (*Item) EpisodeNum ¶
EpisodeNum returns the episode index (Index), 0 when absent.
type ListPath ¶
type ListPath string
ListPath is a server-relative full-listing endpoint path whose response decodes under the large-listing read cap (WithMaxListBodyBytes) — section listings are an order of magnitude larger than any other Plex response. Produced by the listing builders (SectionItemsPath, RecentlyAddedPath); Client.FetchMetadataList accepts only this type.
func RecentlyAddedPath ¶
RecentlyAddedPath returns a section's listing path filtered server-side to items of metadataType added at or after sinceUnix, newest first. The filter is literally `addedAt>=%d` (see the package comment on operator encoding). A recently-added window is a section listing (ListPath): a generous window on a large section outgrows the general cap.
func SectionItemsPath ¶
SectionItemsPath returns the full-listing endpoint path for a library section, validating the section key first.
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"`
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 because the failure is a decode error on the whole MediaContainer it takes every OTHER field on every session 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 ¶
WithBaseDelay sets the initial retry backoff (default 200ms).
func WithCACertPEM ¶
WithCACertPEM pins the CA(s) in pem as the sole TLS trust anchors, for a Plex behind a self-signed or private CA. Verification stays ON. The caller owns reading the PEM (the library does no file I/O); an empty pem is an error at construction.
func WithHTTPClient ¶
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 — the caller owns all of it). Intended for tests and callers with bespoke transport needs.
func WithLogger ¶
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(); pass a level-filtered or discard logger to quiet them.
func WithMaxAttempts ¶
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 ¶
WithMaxBodyBytes sets the read cap for metadata, session, history, and server-info responses (default DefaultMaxBodyBytes). Non-positive values are ignored.
func WithMaxListBodyBytes ¶
WithMaxListBodyBytes sets the read cap for full section listings (default DefaultMaxListBodyBytes) — the knob for libraries large enough that a section's listing outgrows the default. Non-positive values are ignored.
func WithOnRetry ¶
WithOnRetry installs a per-retry observability hook (attempt number, request, response, error), forwarded to the underlying round-tripper. Consumers use it to surface a retry counter metric.
func WithTimeout ¶
WithTimeout sets the per-request ceiling applied ONLY when the caller's context has no deadline (default 2m). A caller deadline is always the authoritative budget and is never undercut.
type Part ¶
type Part struct {
Decision string `json:"decision"`
Stream []Stream `json:"Stream"`
ID FlexInt `json:"id"`
}
Part is one file of a Media, wrapping its streams. Decision is populated on session responses (the transcoder's per-part verdict). ID is FlexInt for the reason given on Media.
type Path ¶
type Path string
Path is a server-relative endpoint path whose response decodes under the general read cap (WithMaxBodyBytes). The builder returning it decides the cap class, so a call site cannot silently read a listing-sized endpoint under the smaller cap or vice versa; construct one explicitly (plexapi.Path("/x")) only for an endpoint no builder models.
func AllLeavesPath ¶
AllLeavesPath returns the leaf-descendants endpoint path for an item (every episode of a show), validating the key first.
func ChildrenPath ¶
ChildrenPath returns the direct-children endpoint path for an item (a show's seasons, a season's episodes), validating the key first.
func HistoryPath ¶
HistoryPath returns the watch-history endpoint path filtered server-side to entries viewed at or after sinceUnix, newest first. The filter is literally `viewedAt>=N` (see the package comment on operator encoding). It is deliberately a general-cap Path, not a ListPath: a filtered history window fits the general cap, and an over-cap error here is the tripwire for the malformed-operator failure mode (Plex answering with the FULL unfiltered history).
func MetadataPath ¶
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 wire representation is always a string; the type exists so keys are validated once at the API boundary instead of being interpolated into URL paths unchecked.
func (RatingKey) Validate ¶
Validate reports whether the key is a non-empty numeric string. Plex rating keys are always numeric in practice; anything else indicates a programming error (a foreign identifier in a rating-key slot) that must not reach URL construction. The error names the offending value.
type ResponseTooLargeError ¶
ResponseTooLargeError is returned when a response body exceeds the endpoint's read cap. Carries the cap so operators can spot an unfiltered or oversized response class in logs.
func (*ResponseTooLargeError) Error ¶
func (e *ResponseTooLargeError) Error() string
Error implements the error interface.
type Section ¶
type Section struct {
Key string `json:"key"`
Title string `json:"title"`
Type string `json:"type"`
}
Section is a library section from GET /library/sections.
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 ¶
SessionBandwidth is the Session element on a session item.
type SessionUser ¶
SessionUser is the User element on a session or history item.
type SharedServer ¶
type SharedServer struct {
}
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 ¶
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 ¶
StatusError is returned for a non-200, non-404 Plex response, after any transparent retries are exhausted. It carries the status code so callers can classify the failure: a 4xx (bad token, wrong server) will not self-heal, while a 5xx (Plex still starting) may recover.
func (*StatusError) Error ¶
func (e *StatusError) Error() string
Error implements the error interface. The path is included (it is server-relative and never carries the token); the message shape follows the consumers' existing log grammar.
type Stream ¶
type Stream struct {
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"`
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.
func (*Stream) IsSubtitle ¶
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, and indistinguishable at the call site from a genuinely stale ID.
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 — there is no CA-pinning or skip option for a public endpoint — and never follows redirects, so the admin token cannot be forwarded off plex.tv by a compromised redirect or CDN front.
func (*TV) SharedServers ¶
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 ¶
WithTVBaseURL replaces the plex.tv origin (tests).
func WithTVHTTPClient ¶
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. Before this, a swapped pair was caught only because a token does not parse as an http(s) URL — detection at run time, and only because New happens to validate. A named type makes a swapped pair of VARIABLES a compile error instead. (Two untyped string LITERALS still convert either way, which is why New keeps its URL validation.)
plexapi declares its own rather than reusing another package's credential type: that would put a dependency in this package's public contract, and a caller would have to import it just to build a client.
type TranscodeSession ¶
type TranscodeSession struct {
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.