plex

package
v0.4.0 Latest Latest
Warning

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

Go to latest
Published: Oct 13, 2026 License: AGPL-3.0 Imports: 20 Imported by: 0

Documentation

Overview

Package plex provides a client for the Plex Media Server API.

Index

Constants

View Source
const (
	// StatePlaying is a client playing the session.
	StatePlaying = "playing"

	// StatePaused is a client paused on the session.
	StatePaused = "paused"
)

The states a Plex client reports for a session.

View Source
const (
	// TypeShow is a TV show container.
	TypeShow = "show"

	// TypeEpisode is a TV episode.
	TypeEpisode = "episode"

	// TypeSeason is a season container.
	TypeSeason = "season"

	// TypeArtist is a music artist container.
	TypeArtist = "artist"

	// TypeAlbum is an album container.
	TypeAlbum = "album"
)

Variables

View Source
var (
	// ErrUnauthorized is returned when Plex rejects the token.
	ErrUnauthorized = errors.New("unauthorized")

	// ErrPlexError is returned when Plex responds with a failure status.
	ErrPlexError = errors.New("plex error")

	// ErrServerReturnedError is returned when a Plex server request fails.
	ErrServerReturnedError = errors.New("server returned error")

	// ErrNotFound is returned when a Plex server has nothing at a path for the
	// token it was asked with, as for an item in a library not shared with
	// that account.
	ErrNotFound = errors.New("not found")

	// ErrNoFilePathFound is returned when media metadata has no file path.
	ErrNoFilePathFound = errors.New("no file path found")

	// ErrPINNotYetClaimed is returned when a PIN has not been authorized.
	ErrPINNotYetClaimed = errors.New("PIN not yet claimed")

	// ErrInvalidThumbPath is returned when a thumbnail path is not a library asset.
	ErrInvalidThumbPath = errors.New("invalid thumbnail path")

	// ErrNotImage is returned when a thumbnail response is not an image.
	ErrNotImage = errors.New("thumbnail is not an image")

	// ErrInvalidMediaID is returned when a media id is not a Plex rating key.
	ErrInvalidMediaID = errors.New("invalid media id")

	// ErrUnsupportedSectionIndex is returned when a section facet is not firstCharacter or year.
	ErrUnsupportedSectionIndex = errors.New("unsupported section index")
)

Functions

func EpisodeCode

func EpisodeCode(season, episode int) string

EpisodeCode formats a season and episode number as S01E03.

Parameters:

  • season: 1-based season number, or 0 when unknown.
  • episode: 1-based episode number, or 0 when unknown.

Returns:

  • code: SxxExx, or empty when both values are missing.

func IsContainerType

func IsContainerType(mediaType string) bool

IsContainerType reports whether the metadata type has children to browse.

Parameters:

  • mediaType: Plex metadata type.

Returns:

  • ok: True for show, season, artist, and album.

func LetterOffset

func LetterOffset(index []LetterIndex, letter string) int

LetterOffset returns the item offset of letter in index order.

Parameters:

  • index: First-character buckets in PMS order.
  • letter: Directory title to find, such as "A" or "#".

Returns:

  • offset: Sum of sizes before the matching title, or 0 when missing.

func MapPlexType

func MapPlexType(plexType string) string

MapPlexType maps Plex type strings to standardized types.

Parameters:

  • plexType: The Plex metadata type.

Returns:

  • mediaType: The outtake type, or "unknown" for an unmapped value.

func SameConnection

func SameConnection(left, right Server) bool

SameConnection reports whether two servers share scheme, host, and port.

Parameters:

  • left: First server connection.
  • right: Second server connection.

Returns:

  • same: True when both connections reach the same origin.

func SelectionKey added in v0.4.0

func SelectionKey(server Server) string

SelectionKey names one discovered connection without carrying its token, so a page can post it back and the choice can be looked up again.

Parameters:

  • server: A discovered connection.

Returns:

  • key: The server's machine id and the connection's origin.

func ValidThumbPath

func ValidThumbPath(path string) bool

ValidThumbPath reports whether path is a Plex artwork path.

Anything else, including a query string or an escaped character, is refused, so the thumbnail proxy cannot reach any other Plex endpoint.

Parameters:

  • path: Candidate thumbnail path.

Returns:

  • ok: True when path names artwork.

func ViewerKey added in v0.4.0

func ViewerKey(server Server) string

ViewerKey names a server as one account reads it.

Each account sees only what the server shares with it, so a cache of what the server answered is kept per account. The key holds a digest of the token rather than the token itself.

Parameters:

  • server: A connection carrying the token it is read with.

Returns:

  • key: The connection's SelectionKey and the start of its token's digest.

Types

type Client

type Client struct {
	Token    string
	Product  string
	ClientID string
	// contains filtered or unexported fields
}

Client represents a Plex API client.

func NewClient

func NewClient(cfg ClientConfig) *Client

NewClient creates a new Plex client with the default Fiber HTTP client.

Parameters:

  • cfg: Product, client identifier, token, timeout, and optional base URL.

Returns:

  • client: A client that defaults the timeout and product name.

func (*Client) DiscoverServers

func (client *Client) DiscoverServers(ctx context.Context) ([]Server, error)

DiscoverServers discovers Plex servers.

Parameters:

  • ctx: Cancellation and deadline for the request.

Returns:

  • servers: One entry per connection the account exposes.
  • err: Non-nil when the plex.tv request or decode fails.

func (*Client) FirstReachable added in v0.4.0

func (client *Client) FirstReachable(ctx context.Context, connections []Server) (Server, bool)

FirstReachable returns the most preferred connection that answers a ping.

It pings every connection at once. The order of preference is local, then direct HTTPS, then any other direct connection, then the relay. A connection that answers no faster than a less preferred one still wins.

Parameters:

  • ctx: Cancellation and deadline for the pings.
  • connections: Connections of one server.

Returns:

  • server: The preferred reachable connection.
  • ok: False when no connection answered.

func (*Client) GeneratePIN

func (client *Client) GeneratePIN(ctx context.Context) (*PinResponse, error)

GeneratePIN generates a new PIN for authentication.

Parameters:

  • ctx: Cancellation and deadline for the request.

Returns:

  • pin: The Plex authentication PIN.
  • err: Non-nil when the PIN could not be created.

func (*Client) GetAuthURL

func (client *Client) GetAuthURL(pinCode, clientID, forwardURL string) string

GetAuthURL builds the Plex Auth App URL.

Parameters:

  • pinCode: Plex PIN code shown to the user.
  • clientID: Plex client identifier.
  • forwardURL: Where Plex returns the user after authorization.

Returns:

  • url: The Plex Auth App URL.

func (*Client) GetChildren

func (client *Client) GetChildren(
	ctx context.Context,
	server Server,
	mediaID string,
) ([]MediaItem, error)

GetChildren lists one level of children for a show, season, artist, or album.

Parameters:

  • ctx: Cancellation and deadline for the request.
  • server: PMS to query.
  • mediaID: Rating key of the container.

Returns:

  • items: The container's children.
  • err: Non-nil when both requests and the decode fail.

func (*Client) GetChildrenPage

func (client *Client) GetChildrenPage(
	ctx context.Context,
	server Server,
	mediaID string,
	start, size int,
) (MediaPage, error)

GetChildrenPage fetches one page of children for a container.

Parameters:

  • ctx: Cancellation and deadline for the request.
  • server: PMS to query.
  • mediaID: Rating key of the container.
  • start: Container offset.
  • size: Page size, or 0 for the PMS default.

Returns:

  • page: Children and total size for the requested window.
  • err: Non-nil when both requests and the decode fail.

func (*Client) GetFirstCharacters

func (client *Client) GetFirstCharacters(
	ctx context.Context,
	server Server,
	libraryID string,
) ([]LetterIndex, error)

GetFirstCharacters fetches title first-character buckets for a library.

Parameters:

  • ctx: Request context.
  • server: PMS to query.
  • libraryID: Section key.

Returns:

  • index: First-character buckets.
  • err: Non-nil when the PMS request or decode fails.

func (*Client) GetLibraries

func (client *Client) GetLibraries(ctx context.Context, server Server) ([]Library, error)

GetLibraries fetches libraries from the Plex server.

Parameters:

  • ctx: Cancellation and deadline for the request.
  • server: PMS to query.

Returns:

  • libraries: The server's library sections.
  • err: Non-nil when the PMS request or decode fails.

func (*Client) GetMedia

func (client *Client) GetMedia(
	ctx context.Context,
	server Server,
	libraryID string,
) ([]MediaItem, error)

GetMedia fetches media items from a library.

Parameters:

  • ctx: Cancellation and deadline for the request.
  • server: PMS to query.
  • libraryID: Section key.

Returns:

  • items: Every item the library returned.
  • err: Non-nil when the PMS request or decode fails.

func (*Client) GetMediaItem

func (client *Client) GetMediaItem(
	ctx context.Context,
	server Server,
	mediaID string,
) (*MediaItem, error)

GetMediaItem fetches a single media item from a Plex Media Server.

Parameters:

  • ctx: Cancellation and deadline for the request.
  • server: PMS to query.
  • mediaID: Rating key of the item.

Returns:

  • item: The mapped media item, keyed by mediaID, with the path of its first media part as the server sees it.
  • err: ErrNoFilePathFound when the server returned no metadata, or a request error.

func (*Client) GetMediaPage

func (client *Client) GetMediaPage(
	ctx context.Context,
	server Server,
	libraryID string,
	start, size int,
	sort string,
) (MediaPage, error)

GetMediaPage fetches one page of media items from a library.

Parameters:

  • ctx: Request context.
  • server: PMS to query.
  • libraryID: Section key.
  • start: Container offset.
  • size: Page size, or 0 for the PMS default.
  • sort: PMS sort value such as titleSort:asc, or empty.

Returns:

  • page: Items and total size for the requested window.
  • err: Non-nil when the PMS request or decode fails.

func (*Client) GetMediaPath

func (client *Client) GetMediaPath(
	ctx context.Context,
	server Server,
	mediaID string,
) (string, error)

GetMediaPath fetches the file path for a media item.

Parameters:

  • ctx: Cancellation and deadline for the request.
  • server: PMS holding the item.
  • mediaID: Rating key of the item.

Returns:

  • path: The first on-disk part path among the item's metadata rows.
  • err: ErrInvalidMediaID for an id that is not a rating key, ErrNoFilePathFound when no row carries a file, or a request error.

func (*Client) GetSectionIndex

func (client *Client) GetSectionIndex(
	ctx context.Context,
	server Server,
	libraryID, facet string,
) ([]LetterIndex, error)

GetSectionIndex fetches directory buckets for a library facet.

Parameters:

  • ctx: Request context.
  • server: PMS to query.
  • libraryID: Section key.
  • facet: Directory facet name.

Returns:

  • index: Directory buckets.
  • err: Non-nil when the facet is unsupported or the PMS request fails.

func (*Client) GetServerIdentity

func (client *Client) GetServerIdentity(
	ctx context.Context,
	server Server,
) (*ServerIdentity, error)

GetServerIdentity fetches the server identity.

Parameters:

  • ctx: Cancellation and deadline for the request.
  • server: PMS to query.

Returns:

  • identity: The PMS machine identifier and version.
  • err: Non-nil when the PMS request or decode fails.

func (*Client) GetSessionsOnServer

func (client *Client) GetSessionsOnServer(ctx context.Context, server Server) ([]Session, error)

GetSessionsOnServer fetches active sessions from a Plex Media Server.

Parameters:

  • ctx: Cancellation and deadline for the request.
  • server: PMS to query.

Returns:

  • sessions: The server's playback sessions.
  • err: Non-nil when the PMS request or decode fails.

func (*Client) GetThumb

func (client *Client) GetThumb(
	ctx context.Context,
	server Server,
	path string,
) ([]byte, string, error)

GetThumb fetches a thumbnail from the Plex Media Server.

Parameters:

  • ctx: Cancellation and deadline for the request.
  • server: PMS holding the asset.
  • path: Thumbnail path, as accepted by ValidThumbPath.

Returns:

  • body: The thumbnail bytes.
  • contentType: The image content type.
  • err: ErrInvalidThumbPath for an unusable path, ErrNotImage for a response that is not an image, or a request error. A response larger than 10 MiB fails as a request error.

func (*Client) GetYears

func (client *Client) GetYears(
	ctx context.Context,
	server Server,
	libraryID string,
) ([]LetterIndex, error)

GetYears fetches year buckets for a library section.

Parameters:

  • ctx: Request context.
  • server: PMS to query.
  • libraryID: Section key.

Returns:

  • index: Year buckets.
  • err: Non-nil when the PMS request or decode fails.

func (*Client) Ping

func (client *Client) Ping(ctx context.Context, server Server) error

Ping pings the server to check connectivity.

Parameters:

  • ctx: Cancellation and deadline for the request.
  • server: PMS to ping.

Returns:

  • err: ErrServerReturnedError for a non-200 status, or a request error.

func (*Client) PollPIN

func (client *Client) PollPIN(ctx context.Context, pinID int, pinCode string) (string, error)

PollPIN polls for PIN authentication.

Parameters:

  • ctx: Cancellation and deadline for the request.
  • pinID: Plex PIN identifier.
  • pinCode: Plex PIN code shown to the user.

Returns:

  • token: The Plex access token, once the PIN has been claimed.
  • err: ErrPINNotYetClaimed while the PIN is unclaimed, or a request error.

func (*Client) SearchMedia

func (client *Client) SearchMedia(ctx context.Context, query string) ([]MediaItem, error)

SearchMedia searches for media across all accessible servers using the Plex.tv API.

Parameters:

  • ctx: Cancellation and deadline for the request.
  • query: Free-text search query.

Returns:

  • items: The plex.tv search hits.
  • err: Non-nil when the plex.tv request or decode fails.

func (*Client) SearchOnServer

func (client *Client) SearchOnServer(
	ctx context.Context,
	server Server,
	query, sectionID string,
) ([]MediaItem, error)

SearchOnServer searches media via GET /hubs/search.

Parameters:

  • ctx: Cancellation and deadline for the request.
  • server: PMS to query.
  • query: Free-text search query.
  • sectionID: Library section key, or empty to search the whole server.

Returns:

  • items: Metadata from every hub the server returned.
  • err: Non-nil when the PMS request or decode fails.

func (*Client) SetBaseURL

func (client *Client) SetBaseURL(rawURL string) error

SetBaseURL sets the base URL for server-specific requests.

Parameters:

  • rawURL: New request origin.

Returns:

  • err: Non-nil when rawURL is not a valid URL.

func (*Client) SetToken

func (client *Client) SetToken(token string)

SetToken sets the authentication token.

Parameters:

  • token: Plex access token.

func (*Client) ValidateToken

func (client *Client) ValidateToken(ctx context.Context) (bool, *UserResponse, error)

ValidateToken validates the current authentication token.

Parameters:

  • ctx: Cancellation and deadline for the request.

Returns:

  • valid: True when Plex accepted the token.
  • user: The authenticated Plex user.
  • err: ErrUnauthorized when Plex rejected the token, or a request error.

type ClientConfig

type ClientConfig struct {
	Product  string
	ClientID string
	Token    string
	Timeout  time.Duration
	BaseURL  string
}

ClientConfig represents configuration for the Plex client.

type LetterIndex

type LetterIndex struct {
	Title string
	Size  int
}

LetterIndex is one first-character bucket from a library section.

func ReverseIndexes

func ReverseIndexes(index []LetterIndex) []LetterIndex

ReverseIndexes returns index in reverse order.

Parameters:

  • index: Buckets in original order.

Returns:

  • index: A reversed copy.

func SortYearIndexes

func SortYearIndexes(index []LetterIndex) []LetterIndex

SortYearIndexes orders year buckets from oldest to newest.

Parameters:

  • index: Year buckets in any order.

Returns:

  • index: A sorted copy.

type Library

type Library struct {
	ID        string `json:"id"`
	Title     string `json:"title"`
	Type      string `json:"type"`
	ThumbPath string `json:"thumbPath,omitempty"`
}

Library represents a Plex library.

type MediaItem

type MediaItem struct {
	ID               string  `json:"id"`
	Title            string  `json:"title"`
	Type             string  `json:"type"`
	Duration         float64 `json:"duration"`
	ThumbPath        string  `json:"thumbPath"`
	LibraryTitle     string  `json:"libraryTitle"`
	LibraryID        string  `json:"libraryId,omitempty"`
	Year             int     `json:"year,omitempty"`
	Index            int     `json:"index,omitempty"`
	ParentIndex      int     `json:"parentIndex,omitempty"`
	ParentID         string  `json:"parentId,omitempty"`
	ParentTitle      string  `json:"parentTitle,omitempty"`
	GrandparentID    string  `json:"grandparentId,omitempty"`
	GrandparentTitle string  `json:"grandparentTitle,omitempty"`
	TitleSort        string  `json:"titleSort,omitempty"`
	AddedAt          int64   `json:"addedAt,omitempty"`
	// FilePath is the item's first on-disk part as the Plex server sees it.
	// Only GetMediaItem fills it, and it never leaves the server.
	FilePath string `json:"-"`
}

MediaItem represents a media item in Plex.

func (MediaItem) DisplayTitle

func (item MediaItem) DisplayTitle() string

DisplayTitle returns a user-facing title, including show and episode codes.

Returns:

  • title: The label shown in lists, sessions, and page headings.

type MediaPage

type MediaPage struct {
	Items []MediaItem
	Total int
	Start int
	Size  int
}

MediaPage is one page of library or container children.

type PinResponse

type PinResponse struct {
	ID   int    `json:"id"`
	Code string `json:"code"`
	// ExpiresIn is how many seconds the PIN stays valid, zero when Plex did
	// not say.
	ExpiresIn int `json:"expiresIn"`
}

PinResponse represents a PIN response from Plex.

type Server

type Server struct {
	Name    string `json:"name"`
	Address string `json:"address"`
	Port    int    `json:"port"`
	Token   string `json:"token"`
	Scheme  string `json:"scheme"`
	Local   bool   `json:"local"`
	// MachineID is the server's Plex client identifier, shared by all of its
	// connections. Empty for a server that was not discovered.
	MachineID string `json:"machineId"`
	// Relay is true for a connection through the Plex relay.
	Relay bool `json:"relay"`
	// Owned is true when the account that discovered the server owns it,
	// rather than having it shared with them.
	Owned bool `json:"owned"`
}

Server represents one connection to a Plex server.

func ConnectionsOf added in v0.4.0

func ConnectionsOf(servers []Server, server Server) []Server

ConnectionsOf returns every connection of the server a connection belongs to.

Parameters:

  • servers: Discovered server connections.
  • server: One connection of the server.

Returns:

  • connections: The server's connections, in discovery order.

func EmptyServer

func EmptyServer() Server

EmptyServer returns a Server with every exported field set to its zero value.

Returns:

  • server: A Server ready to fill or return as a missing-server sentinel.

func OwnedServers added in v0.4.0

func OwnedServers(servers []Server) []Server

OwnedServers keeps the connections of servers the discovering account owns.

A server shared with the account is left out, because only its owner may bind it to this installation.

Parameters:

  • servers: Discovered server connections.

Returns:

  • owned: The connections of owned servers, in discovery order.

func ParseServerURL added in v0.4.0

func ParseServerURL(rawURL string) (Server, bool)

ParseServerURL reads a Plex Media Server URL a user typed, without a token.

Parameters:

Returns:

  • server: The connection the URL names, with no token.
  • ok: False unless the URL is http or https and names a host.

func PreferUniqueServers

func PreferUniqueServers(servers []Server) []Server

PreferUniqueServers keeps one connection per server, preferring local ones.

Servers are told apart by machine id, or by name when discovery reported none.

Parameters:

  • servers: Discovered server connections, possibly including remotes.

Returns:

  • unique: Deduplicated servers with local connections preferred.

func ServerFromParts added in v0.3.0

func ServerFromParts(scheme, address, port, token string) (Server, bool)

ServerFromParts builds a Server from the parts of a base URL.

Parameters:

  • scheme: URL scheme, defaulting to http when blank.
  • address: Server host, which is required.
  • port: Server port, where blank or zero means the scheme's own default.
  • token: Plex access token.

Returns:

  • server: Assembled server connection.
  • ok: False when the host or token is missing, or the port is not a number.

func ServerFromURL

func ServerFromURL(rawURL, token string) (Server, bool)

ServerFromURL builds a Server from a base URL and access token.

Parameters:

Returns:

  • server: Parsed server connection.
  • ok: False when the URL is empty or invalid.

type ServerIdentity

type ServerIdentity struct {
	MachineIdentifier string `json:"machineIdentifier"`
	Version           string `json:"version"`
}

ServerIdentity represents the server identity.

type Session

type Session struct {
	ID         string    `json:"id"`
	MediaItem  MediaItem `json:"mediaItem"`
	Title      string    `json:"title"`
	Duration   float64   `json:"duration"`
	ViewOffset float64   `json:"viewOffset"`
	// State is what the client is doing: StatePlaying, StatePaused, or
	// buffering. A paused client has reported its exact position.
	State string `json:"state"`
	// UserID is the plex.tv id of the account playing, or 1 for the server's
	// owner on a local server, and zero when the server did not say.
	UserID int `json:"userId"`
}

Session represents a playback session.

func SessionsWhere added in v0.4.0

func SessionsWhere(sessions []Session, includes func(userID int) bool) []Session

SessionsWhere keeps the playback sessions whose account passes a check.

Parameters:

  • sessions: Every session the server reported.
  • includes: Reports whether the asking account may see a session played by the given plex.tv account id.

Returns:

  • visible: The sessions the check keeps, in their order.

type UserResponse

type UserResponse struct {
	ID       int    `json:"id"`
	Username string `json:"username"`
	Title    string `json:"title"`
}

UserResponse represents a user response from Plex.

Directories

Path Synopsis
decode
key
Package key resolves Plex metadata identifiers from Plex metadata paths.
Package key resolves Plex metadata identifiers from Plex metadata paths.
plextv
Package plextv decodes plex.tv XML MediaContainer envelopes.
Package plextv decodes plex.tv XML MediaContainer envelopes.
pms
Package pms decodes documented Plex Media Server JSON envelopes.
Package pms decodes documented Plex Media Server JSON envelopes.
Package identity owns who the caller is and which Plex server answers for them.
Package identity owns who the caller is and which Plex server answers for them.
Package library holds the media library domain that sits behind the HTTP adapter.
Package library holds the media library domain that sits behind the HTTP adapter.
Package session monitors live playback sessions on a Plex Media Server.
Package session monitors live playback sessions on a Plex Media Server.

Jump to

Keyboard shortcuts

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