plex

package
v0.2.0 Latest Latest
Warning

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

Go to latest
Published: Sep 9, 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.

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.

func SameConnection

func SameConnection(left, right Server) bool

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

func ValidThumbPath

func ValidThumbPath(path string) bool

ValidThumbPath reports whether path is a Plex library thumbnail path.

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.

func NewClientWithHTTPClient

func NewClientWithHTTPClient(cfg ClientConfig, httpClient HTTPClient) *Client

NewClientWithHTTPClient creates a new Plex client with a custom HTTP client.

func (*Client) DiscoverServers

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

DiscoverServers discovers Plex servers.

func (*Client) GeneratePIN

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

GeneratePIN generates a new PIN for authentication.

func (*Client) GetAuthURL

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

GetAuthURL builds the Plex Auth App URL.

Plex requires parameters in the URL fragment after a literal "#?", not a query string. url.URL.String encodes that "?" and re-encodes already-escaped values, so this concatenates the encoded parameters onto the documented prefix.

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.

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.

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.

func (*Client) GetMedia

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

GetMedia fetches media items from a library.

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.

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.

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.

Facet must be firstCharacter or year.

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.

func (*Client) GetSessions

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

GetSessions fetches active sessions using the Plex.tv API.

func (*Client) GetSessionsOnServer

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

GetSessionsOnServer fetches active sessions from a Plex Media Server.

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.

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.

func (*Client) PollPIN

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

PollPIN polls for PIN authentication.

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.

func (*Client) SearchOnServer

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

SearchOnServer searches media via GET /hubs/search.

func (*Client) SetBaseURL

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

SetBaseURL sets the base URL for server-specific requests.

func (*Client) SetToken

func (client *Client) SetToken(token string)

SetToken sets the authentication token.

func (*Client) ValidateToken

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

ValidateToken validates the current authentication token.

type ClientConfig

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

ClientConfig represents configuration for the Plex client.

type FiberClient

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

FiberClient wraps the Fiber v3 client to implement HTTPClient.

func (*FiberClient) Get

func (client *FiberClient) Get(
	requestURL string,
	cfg ...fiberClient.Config,
) (*fiberClient.Response, error)

Get sends a GET request.

func (*FiberClient) Post

func (client *FiberClient) Post(
	requestURL string,
	cfg ...fiberClient.Config,
) (*fiberClient.Response, error)

Post sends a POST request.

type HTTPClient

type HTTPClient interface {
	Get(requestURL string, cfg ...fiberClient.Config) (*fiberClient.Response, error)
	Post(requestURL string, cfg ...fiberClient.Config) (*fiberClient.Response, error)
}

HTTPClient defines the interface for HTTP operations.

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