Help us shape the future of Go! Take the 2026 Go Developer Survey

plex

package
v0.3.1 Latest Latest
Warning

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

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

Documentation

Overview

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

Index

Constants

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")

	// 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")

	// 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 ValidThumbPath

func ValidThumbPath(path string) bool

ValidThumbPath reports whether path is a Plex library thumbnail path.

Parameters:

  • path: Candidate thumbnail path.

Returns:

  • ok: True when the path is absolute and confined to a library asset route.

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) 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.
  • 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: 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) GetSessions

func (client *Client) GetSessions(ctx context.Context) ([]Session, error)

GetSessions fetches active sessions using the Plex.tv API.

Parameters:

  • ctx: Cancellation and deadline for the request.

Returns:

  • sessions: The plex.tv playback sessions.
  • err: Non-nil when the plex.tv 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 response content type, defaulting to image/jpeg.
  • err: ErrInvalidThumbPath for an unusable path, or 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"`
}

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"`
}

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"`
}

Server represents a Plex server.

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 PreferUniqueServers

func PreferUniqueServers(servers []Server) []Server

PreferUniqueServers keeps one connection per server name, preferring local ones.

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"`
}

Session represents a playback session.

type UserResponse

type UserResponse struct {
	ID    int    `json:"id"`
	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