plexgo

package module
v0.16.1 Latest Latest
Warning

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

Go to latest
Published: Nov 14, 2024 License: MIT Imports: 15 Imported by: 2

README

github.com/LukeHagar/plexgo

Summary

Plex-API: An Open API Spec for interacting with Plex.tv and Plex Media Server

Plex Media Server OpenAPI Specification

An Open Source OpenAPI Specification for Plex Media Server

Automation and SDKs provided by Speakeasy

Documentation

API Documentation

SDKs

The following SDKs are generated from the OpenAPI Specification. They are automatically generated and may not be fully tested. If you find any issues, please open an issue on the main specification Repository.

Language Repository Releases Other
Python GitHub PyPI -
JavaScript/TypeScript GitHub NPM \ JSR -
Go GitHub Releases GoDoc
Ruby GitHub Releases -
Swift GitHub Releases -
PHP GitHub Releases -
Java GitHub Releases -
C# GitHub Releases -

Table of Contents

SDK Installation

To add the SDK as a dependency to your project:

go get github.com/LukeHagar/plexgo

SDK Example Usage

Example
package main

import (
	"context"
	"github.com/LukeHagar/plexgo"
	"log"
)

func main() {
	s := plexgo.New(
		plexgo.WithSecurity("<YOUR_API_KEY_HERE>"),
		plexgo.WithClientID("3381b62b-9ab7-4e37-827b-203e9809eb58"),
		plexgo.WithClientName("Plex for Roku"),
		plexgo.WithClientVersion("2.4.1"),
		plexgo.WithPlatform("Roku"),
		plexgo.WithDeviceNickname("Roku 3"),
	)

	ctx := context.Background()
	res, err := s.Server.GetServerCapabilities(ctx)
	if err != nil {
		log.Fatal(err)
	}
	if res.Object != nil {
		// handle response
	}
}

Available Resources and Operations

Available methods
Activities
Authentication
Butler
Hubs
Library
Log
Media
Playlists
Plex
Server
Sessions
Statistics
Updater
Video
Watchlist

Retries

Some of the endpoints in this SDK support retries. If you use the SDK without any configuration, it will fall back to the default retry strategy provided by the API. However, the default retry strategy can be overridden on a per-operation basis, or across the entire SDK.

To change the default retry strategy for a single API call, simply provide a retry.Config object to the call by using the WithRetries option:

package main

import (
	"context"
	"github.com/LukeHagar/plexgo"
	"github.com/LukeHagar/plexgo/retry"
	"log"
	"models/operations"
)

func main() {
	s := plexgo.New(
		plexgo.WithSecurity("<YOUR_API_KEY_HERE>"),
		plexgo.WithClientID("3381b62b-9ab7-4e37-827b-203e9809eb58"),
		plexgo.WithClientName("Plex for Roku"),
		plexgo.WithClientVersion("2.4.1"),
		plexgo.WithPlatform("Roku"),
		plexgo.WithDeviceNickname("Roku 3"),
	)

	ctx := context.Background()
	res, err := s.Server.GetServerCapabilities(ctx, operations.WithRetries(
		retry.Config{
			Strategy: "backoff",
			Backoff: &retry.BackoffStrategy{
				InitialInterval: 1,
				MaxInterval:     50,
				Exponent:        1.1,
				MaxElapsedTime:  100,
			},
			RetryConnectionErrors: false,
		}))
	if err != nil {
		log.Fatal(err)
	}
	if res.Object != nil {
		// handle response
	}
}

If you'd like to override the default retry strategy for all operations that support retries, you can use the WithRetryConfig option at SDK initialization:

package main

import (
	"context"
	"github.com/LukeHagar/plexgo"
	"github.com/LukeHagar/plexgo/retry"
	"log"
)

func main() {
	s := plexgo.New(
		plexgo.WithRetryConfig(
			retry.Config{
				Strategy: "backoff",
				Backoff: &retry.BackoffStrategy{
					InitialInterval: 1,
					MaxInterval:     50,
					Exponent:        1.1,
					MaxElapsedTime:  100,
				},
				RetryConnectionErrors: false,
			}),
		plexgo.WithSecurity("<YOUR_API_KEY_HERE>"),
		plexgo.WithClientID("3381b62b-9ab7-4e37-827b-203e9809eb58"),
		plexgo.WithClientName("Plex for Roku"),
		plexgo.WithClientVersion("2.4.1"),
		plexgo.WithPlatform("Roku"),
		plexgo.WithDeviceNickname("Roku 3"),
	)

	ctx := context.Background()
	res, err := s.Server.GetServerCapabilities(ctx)
	if err != nil {
		log.Fatal(err)
	}
	if res.Object != nil {
		// handle response
	}
}

Error Handling

Handling errors in this SDK should largely match your expectations. All operations return a response object or an error, they will never return both.

By Default, an API error will return sdkerrors.SDKError. When custom error responses are specified for an operation, the SDK may also return their associated error. You can refer to respective Errors tables in SDK docs for more details on possible error types for each operation.

For example, the GetServerCapabilities function may return the following errors:

Error Type Status Code Content Type
sdkerrors.GetServerCapabilitiesBadRequest 400 application/json
sdkerrors.GetServerCapabilitiesUnauthorized 401 application/json
sdkerrors.SDKError 4XX, 5XX */*
Example
package main

import (
	"context"
	"errors"
	"github.com/LukeHagar/plexgo"
	"github.com/LukeHagar/plexgo/models/sdkerrors"
	"log"
)

func main() {
	s := plexgo.New(
		plexgo.WithSecurity("<YOUR_API_KEY_HERE>"),
		plexgo.WithClientID("3381b62b-9ab7-4e37-827b-203e9809eb58"),
		plexgo.WithClientName("Plex for Roku"),
		plexgo.WithClientVersion("2.4.1"),
		plexgo.WithPlatform("Roku"),
		plexgo.WithDeviceNickname("Roku 3"),
	)

	ctx := context.Background()
	res, err := s.Server.GetServerCapabilities(ctx)
	if err != nil {

		var e *sdkerrors.GetServerCapabilitiesBadRequest
		if errors.As(err, &e) {
			// handle error
			log.Fatal(e.Error())
		}

		var e *sdkerrors.GetServerCapabilitiesUnauthorized
		if errors.As(err, &e) {
			// handle error
			log.Fatal(e.Error())
		}

		var e *sdkerrors.SDKError
		if errors.As(err, &e) {
			// handle error
			log.Fatal(e.Error())
		}
	}
}

Server Selection

Server Variables

The default server {protocol}://{ip}:{port} contains variables and is set to https://10.10.10.47:32400 by default. To override default values, the following options are available when initializing the SDK client instance:

  • WithProtocol(protocol ServerProtocol)
  • WithIP(ip string)
  • WithPort(port string)
Override Server URL Per-Client

The default server can also be overridden globally using the WithServerURL(serverURL string) option when initializing the SDK client instance. For example:

package main

import (
	"context"
	"github.com/LukeHagar/plexgo"
	"log"
)

func main() {
	s := plexgo.New(
		plexgo.WithServerURL("https://10.10.10.47:32400"),
		plexgo.WithSecurity("<YOUR_API_KEY_HERE>"),
		plexgo.WithClientID("3381b62b-9ab7-4e37-827b-203e9809eb58"),
		plexgo.WithClientName("Plex for Roku"),
		plexgo.WithClientVersion("2.4.1"),
		plexgo.WithPlatform("Roku"),
		plexgo.WithDeviceNickname("Roku 3"),
	)

	ctx := context.Background()
	res, err := s.Server.GetServerCapabilities(ctx)
	if err != nil {
		log.Fatal(err)
	}
	if res.Object != nil {
		// handle response
	}
}

Override Server URL Per-Operation

The server URL can also be overridden on a per-operation basis, provided a server list was specified for the operation. For example:

package main

import (
	"context"
	"github.com/LukeHagar/plexgo"
	"github.com/LukeHagar/plexgo/models/operations"
	"log"
)

func main() {
	s := plexgo.New(
		plexgo.WithSecurity("<YOUR_API_KEY_HERE>"),
		plexgo.WithClientID("3381b62b-9ab7-4e37-827b-203e9809eb58"),
		plexgo.WithClientName("Plex for Roku"),
		plexgo.WithClientVersion("2.4.1"),
		plexgo.WithPlatform("Roku"),
		plexgo.WithDeviceNickname("Roku 3"),
	)

	ctx := context.Background()
	res, err := s.Plex.GetCompanionsData(ctx, operations.WithServerURL("https://plex.tv/api/v2"))
	if err != nil {
		log.Fatal(err)
	}
	if res.ResponseBodies != nil {
		// handle response
	}
}

Custom HTTP Client

The Go SDK makes API calls that wrap an internal HTTP client. The requirements for the HTTP client are very simple. It must match this interface:

type HTTPClient interface {
	Do(req *http.Request) (*http.Response, error)
}

The built-in net/http client satisfies this interface and a default client based on the built-in is provided by default. To replace this default with a client of your own, you can implement this interface yourself or provide your own client configured as desired. Here's a simple example, which adds a client with a 30 second timeout.

import (
	"net/http"
	"time"
	"github.com/myorg/your-go-sdk"
)

var (
	httpClient = &http.Client{Timeout: 30 * time.Second}
	sdkClient  = sdk.New(sdk.WithClient(httpClient))
)

This can be a convenient way to configure timeouts, cookies, proxies, custom headers, and other low-level configuration.

Authentication

Per-Client Security Schemes

This SDK supports the following security scheme globally:

Name Type Scheme
AccessToken apiKey API key

You can configure it using the WithSecurity option when initializing the SDK client instance. For example:

package main

import (
	"context"
	"github.com/LukeHagar/plexgo"
	"log"
)

func main() {
	s := plexgo.New(
		plexgo.WithSecurity("<YOUR_API_KEY_HERE>"),
		plexgo.WithClientID("3381b62b-9ab7-4e37-827b-203e9809eb58"),
		plexgo.WithClientName("Plex for Roku"),
		plexgo.WithClientVersion("2.4.1"),
		plexgo.WithPlatform("Roku"),
		plexgo.WithDeviceNickname("Roku 3"),
	)

	ctx := context.Background()
	res, err := s.Server.GetServerCapabilities(ctx)
	if err != nil {
		log.Fatal(err)
	}
	if res.Object != nil {
		// handle response
	}
}

Special Types

This SDK defines the following custom types to assist with marshalling and unmarshalling data.

Date

types.Date is a wrapper around time.Time that allows for JSON marshaling a date string formatted as "2006-01-02".

Usage
d1 := types.NewDate(time.Now()) // returns *types.Date

d2 := types.DateFromTime(time.Now()) // returns types.Date

d3, err := types.NewDateFromString("2019-01-01") // returns *types.Date, error

d4, err := types.DateFromString("2019-01-01") // returns types.Date, error

d5 := types.MustNewDateFromString("2019-01-01") // returns *types.Date and panics on error

d6 := types.MustDateFromString("2019-01-01") // returns types.Date and panics on error

Development

Maturity

This SDK is in beta, and there may be breaking changes between versions without a major version update. Therefore, we recommend pinning usage to a specific package version. This way, you can install the same version each time without breaking changes unless you are intentionally looking for the latest version.

Contributions

While we value open-source contributions to this SDK, this library is generated programmatically. Feel free to open a PR or a Github issue as a proof of concept and we'll do our best to include it in a future release!

SDK Created by Speakeasy

Documentation

Index

Constants

This section is empty.

Variables

View Source
var ServerList = []string{

	"{protocol}://{ip}:{port}",
}

ServerList contains the list of servers available to the SDK

Functions

func Bool

func Bool(b bool) *bool

Bool provides a helper function to return a pointer to a bool

func Float32

func Float32(f float32) *float32

Float32 provides a helper function to return a pointer to a float32

func Float64

func Float64(f float64) *float64

Float64 provides a helper function to return a pointer to a float64

func Int

func Int(i int) *int

Int provides a helper function to return a pointer to an int

func Int64

func Int64(i int64) *int64

Int64 provides a helper function to return a pointer to an int64

func Pointer added in v0.11.6

func Pointer[T any](v T) *T

Pointer provides a helper function to return a pointer to a type

func String

func String(s string) *string

String provides a helper function to return a pointer to a string

Types

type Activities

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

Activities are awesome. They provide a way to monitor and control asynchronous operations on the server. In order to receive real-time updates for activities, a client would normally subscribe via either EventSource or Websocket endpoints. Activities are associated with HTTP replies via a special `X-Plex-Activity` header which contains the UUID of the activity. Activities are optional cancellable. If cancellable, they may be cancelled via the `DELETE` endpoint. Other details: - They can contain a `progress` (from 0 to 100) marking the percent completion of the activity. - They must contain an `type` which is used by clients to distinguish the specific activity. - They may contain a `Context` object with attributes which associate the activity with various specific entities (items, libraries, etc.) - The may contain a `Response` object which attributes which represent the result of the asynchronous operation.

func (*Activities) CancelServerActivities

func (s *Activities) CancelServerActivities(ctx context.Context, activityUUID string, opts ...operations.Option) (*operations.CancelServerActivitiesResponse, error)

CancelServerActivities - Cancel Server Activities Cancel Server Activities

func (*Activities) GetServerActivities

func (s *Activities) GetServerActivities(ctx context.Context, opts ...operations.Option) (*operations.GetServerActivitiesResponse, error)

GetServerActivities - Get Server Activities Get Server Activities

type Authentication added in v0.4.1

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

Authentication - API Calls regarding authentication for Plex Media Server

func (*Authentication) GetSourceConnectionInformation added in v0.4.1

func (s *Authentication) GetSourceConnectionInformation(ctx context.Context, source string, opts ...operations.Option) (*operations.GetSourceConnectionInformationResponse, error)

GetSourceConnectionInformation - Get Source Connection Information If a caller requires connection details and a transient token for a source that is known to the server, for example a cloud media provider or shared PMS, then this endpoint can be called. This endpoint is only accessible with either an admin token or a valid transient token generated from an admin token. Note: requires Plex Media Server >= 1.15.4.

func (*Authentication) GetTokenDetails added in v0.11.2

GetTokenDetails - Get Token Details Get the User data from the provided X-Plex-Token

func (*Authentication) GetTransientToken added in v0.4.1

GetTransientToken - Get a Transient Token This endpoint provides the caller with a temporary token with the same access level as the caller's token. These tokens are valid for up to 48 hours and are destroyed if the server instance is restarted.

func (*Authentication) PostUsersSignInData added in v0.11.1

PostUsersSignInData - Get User Sign In Data Sign in user with username and password and return user data with Plex authentication token

type Butler

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

Butler is the task manager of the Plex Media Server Ecosystem.

func (*Butler) GetButlerTasks

func (s *Butler) GetButlerTasks(ctx context.Context, opts ...operations.Option) (*operations.GetButlerTasksResponse, error)

GetButlerTasks - Get Butler tasks Returns a list of butler tasks

func (*Butler) StartAllTasks

func (s *Butler) StartAllTasks(ctx context.Context, opts ...operations.Option) (*operations.StartAllTasksResponse, error)

StartAllTasks - Start all Butler tasks This endpoint will attempt to start all Butler tasks that are enabled in the settings. Butler tasks normally run automatically during a time window configured on the server's Settings page but can be manually started using this endpoint. Tasks will run with the following criteria: 1. Any tasks not scheduled to run on the current day will be skipped. 2. If a task is configured to run at a random time during the configured window and we are outside that window, the task will start immediately. 3. If a task is configured to run at a random time during the configured window and we are within that window, the task will be scheduled at a random time within the window. 4. If we are outside the configured window, the task will start immediately.

func (*Butler) StartTask

func (s *Butler) StartTask(ctx context.Context, taskName operations.TaskName, opts ...operations.Option) (*operations.StartTaskResponse, error)

StartTask - Start a single Butler task This endpoint will attempt to start a single Butler task that is enabled in the settings. Butler tasks normally run automatically during a time window configured on the server's Settings page but can be manually started using this endpoint. Tasks will run with the following criteria: 1. Any tasks not scheduled to run on the current day will be skipped. 2. If a task is configured to run at a random time during the configured window and we are outside that window, the task will start immediately. 3. If a task is configured to run at a random time during the configured window and we are within that window, the task will be scheduled at a random time within the window. 4. If we are outside the configured window, the task will start immediately.

func (*Butler) StopAllTasks

func (s *Butler) StopAllTasks(ctx context.Context, opts ...operations.Option) (*operations.StopAllTasksResponse, error)

StopAllTasks - Stop all Butler tasks This endpoint will stop all currently running tasks and remove any scheduled tasks from the queue.

func (*Butler) StopTask

StopTask - Stop a single Butler task This endpoint will stop a currently running task by name, or remove it from the list of scheduled tasks if it exists. See the section above for a list of task names for this endpoint.

type HTTPClient

type HTTPClient interface {
	Do(req *http.Request) (*http.Response, error)
}

HTTPClient provides an interface for suplying the SDK with a custom HTTP client

type Hubs

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

Hubs are a structured two-dimensional container for media, generally represented by multiple horizontal rows.

func (*Hubs) GetGlobalHubs

func (s *Hubs) GetGlobalHubs(ctx context.Context, count *float64, onlyTransient *operations.OnlyTransient, opts ...operations.Option) (*operations.GetGlobalHubsResponse, error)

GetGlobalHubs - Get Global Hubs Get Global Hubs filtered by the parameters provided.

func (*Hubs) GetLibraryHubs

func (s *Hubs) GetLibraryHubs(ctx context.Context, sectionID float64, count *float64, onlyTransient *operations.QueryParamOnlyTransient, opts ...operations.Option) (*operations.GetLibraryHubsResponse, error)

GetLibraryHubs - Get library specific hubs This endpoint will return a list of library specific hubs

func (*Hubs) GetRecentlyAdded added in v0.13.0

GetRecentlyAdded - Get Recently Added This endpoint will return the recently added content.

type Library

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

Library - API Calls interacting with Plex Media Server Libraries

func (*Library) DeleteLibrary

func (s *Library) DeleteLibrary(ctx context.Context, sectionKey int, opts ...operations.Option) (*operations.DeleteLibraryResponse, error)

DeleteLibrary - Delete Library Section Delete a library using a specific section id

func (*Library) GetAllLibraries added in v0.11.1

func (s *Library) GetAllLibraries(ctx context.Context, opts ...operations.Option) (*operations.GetAllLibrariesResponse, error)

GetAllLibraries - Get All Libraries A library section (commonly referred to as just a library) is a collection of media. Libraries are typed, and depending on their type provide either a flat or a hierarchical view of the media. For example, a music library has an artist > albums > tracks structure, whereas a movie library is flat.

Libraries have features beyond just being a collection of media; for starters, they include information about supported types, filters and sorts. This allows a client to provide a rich interface around the media (e.g. allow sorting movies by release year).

func (*Library) GetFileHash

func (s *Library) GetFileHash(ctx context.Context, url_ string, type_ *float64, opts ...operations.Option) (*operations.GetFileHashResponse, error)

GetFileHash - Get Hash Value This resource returns hash values for local files

func (*Library) GetLibraryDetails added in v0.11.1

func (s *Library) GetLibraryDetails(ctx context.Context, sectionKey int, includeDetails *operations.IncludeDetails, opts ...operations.Option) (*operations.GetLibraryDetailsResponse, error)

GetLibraryDetails - Get Library Details ## Library Details Endpoint

This endpoint provides comprehensive details about the library, focusing on organizational aspects rather than the content itself.

The details include:

### Directories Organized into three categories:

- **Primary Directories**:

  • Used in some clients for quick access to media subsets (e.g., "All", "On Deck").
  • Most can be replicated via media queries.
  • Customizable by users.

- **Secondary Directories**:

  • Marked with `secondary="1"`.
  • Used in older clients for structured navigation.

- **Special Directories**:

  • Includes a "By Folder" entry for filesystem-based browsing.
  • Contains an obsolete `search="1"` entry for on-the-fly search dialog creation.

### Types Each type in the library comes with a set of filters and sorts, aiding in building dynamic media controls:

- **Type Object Attributes**:

  • `key`: Endpoint for the media list of this type.
  • `type`: Metadata type (if standard Plex type).
  • `title`: Title for this content type (e.g., "Movies").

- **Filter Objects**:

  • Subset of the media query language.
  • Attributes include `filter` (name), `filterType` (data type), `key` (endpoint for value range), and `title`.

- **Sort Objects**:

  • Description of sort fields.
  • Attributes include `defaultDirection` (asc/desc), `descKey` and `key` (sort parameters), and `title`.

> **Note**: Filters and sorts are optional; without them, no filtering controls are rendered.

func (*Library) GetLibraryItems

GetLibraryItems - Get Library Items Fetches details from a specific section of the library identified by a section key and a tag. The tag parameter accepts the following values: - `all`: All items in the section. - `unwatched`: Items that have not been played. - `newest`: Items that are recently released. - `recentlyAdded`: Items that are recently added to the library. - `recentlyViewed`: Items that were recently viewed. - `onDeck`: Items to continue watching. - `collection`: Items categorized by collection. - `edition`: Items categorized by edition. - `genre`: Items categorized by genre. - `year`: Items categorized by year of release. - `decade`: Items categorized by decade. - `director`: Items categorized by director. - `actor`: Items categorized by starring actor. - `country`: Items categorized by country of origin. - `contentRating`: Items categorized by content rating. - `rating`: Items categorized by rating. - `resolution`: Items categorized by resolution. - `firstCharacter`: Items categorized by the first letter. - `folder`: Items categorized by folder.

func (*Library) GetMetaDataByRatingKey added in v0.11.1

func (s *Library) GetMetaDataByRatingKey(ctx context.Context, ratingKey int64, opts ...operations.Option) (*operations.GetMetaDataByRatingKeyResponse, error)

GetMetaDataByRatingKey - Get Metadata by RatingKey This endpoint will return the metadata of a library item specified with the ratingKey.

func (*Library) GetMetadataChildren

func (s *Library) GetMetadataChildren(ctx context.Context, ratingKey float64, includeElements *string, opts ...operations.Option) (*operations.GetMetadataChildrenResponse, error)

GetMetadataChildren - Get Items Children This endpoint will return the children of of a library item specified with the ratingKey.

func (*Library) GetOnDeck

func (s *Library) GetOnDeck(ctx context.Context, opts ...operations.Option) (*operations.GetOnDeckResponse, error)

GetOnDeck - Get On Deck This endpoint will return the on deck content.

func (*Library) GetRecentlyAddedLibrary added in v0.13.0

GetRecentlyAddedLibrary - Get Recently Added This endpoint will return the recently added content.

func (*Library) GetRefreshLibraryMetadata added in v0.11.1

func (s *Library) GetRefreshLibraryMetadata(ctx context.Context, sectionKey int, force *operations.Force, opts ...operations.Option) (*operations.GetRefreshLibraryMetadataResponse, error)

GetRefreshLibraryMetadata - Refresh Metadata Of The Library This endpoint Refreshes all the Metadata of the library.

func (*Library) GetSearchAllLibraries added in v0.15.0

GetSearchAllLibraries - Search All Libraries Search the provided query across all library sections, or a single section, and return matches as hubs, split up by type.

func (*Library) GetSearchLibrary added in v0.11.1

GetSearchLibrary - Search Library Search for content within a specific section of the library.

### Types Each type in the library comes with a set of filters and sorts, aiding in building dynamic media controls:

- **Type Object Attributes**:

  • `type`: Metadata type (if standard Plex type).
  • `title`: Title for this content type (e.g., "Movies").

- **Filter Objects**:

  • Subset of the media query language.
  • Attributes include `filter` (name), `filterType` (data type), `key` (endpoint for value range), and `title`.

- **Sort Objects**:

  • Description of sort fields.
  • Attributes include `defaultDirection` (asc/desc), `descKey` and `key` (sort parameters), and `title`.

> **Note**: Filters and sorts are optional; without them, no filtering controls are rendered.

func (*Library) GetTopWatchedContent added in v0.10.0

GetTopWatchedContent - Get Top Watched Content This endpoint will return the top watched content from libraries of a certain type

type Log

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

Log - Submit logs to the Log Handler for Plex Media Server

func (*Log) EnablePaperTrail

func (s *Log) EnablePaperTrail(ctx context.Context, opts ...operations.Option) (*operations.EnablePaperTrailResponse, error)

EnablePaperTrail - Enabling Papertrail This endpoint will enable all Plex Media Serverlogs to be sent to the Papertrail networked logging site for a period of time.

func (*Log) LogLine

func (s *Log) LogLine(ctx context.Context, level operations.Level, message string, source string, opts ...operations.Option) (*operations.LogLineResponse, error)

LogLine - Logging a single line message. This endpoint will write a single-line log message, including a level and source to the main Plex Media Server log.

func (*Log) LogMultiLine

func (s *Log) LogMultiLine(ctx context.Context, request string, opts ...operations.Option) (*operations.LogMultiLineResponse, error)

LogMultiLine - Logging a multi-line message This endpoint allows for the batch addition of log entries to the main Plex Media Server log. It accepts a text/plain request body, where each line represents a distinct log entry. Each log entry consists of URL-encoded key-value pairs, specifying log attributes such as 'level', 'message', and 'source'.

Log entries are separated by a newline character (`\n`). Each entry's parameters should be URL-encoded to ensure accurate parsing and handling of special characters. This method is efficient for logging multiple entries in a single API call, reducing the overhead of multiple individual requests.

The 'level' parameter specifies the log entry's severity or importance, with the following integer values: - `0`: Error - Critical issues that require immediate attention. - `1`: Warning - Important events that are not critical but may indicate potential issues. - `2`: Info - General informational messages about system operation. - `3`: Debug - Detailed information useful for debugging purposes. - `4`: Verbose - Highly detailed diagnostic information for in-depth analysis.

The 'message' parameter contains the log text, and 'source' identifies the log message's origin (e.g., an application name or module).

Example of a single log entry format: `level=4&message=Sample%20log%20entry&source=applicationName`

Ensure each parameter is properly URL-encoded to avoid interpretation issues.

type Media

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

Media - API Calls interacting with Plex Media Server Media

func (*Media) GetBannerImage added in v0.11.1

GetBannerImage - Get Banner Image Gets the banner image of the media item

func (*Media) GetThumbImage added in v0.11.1

GetThumbImage - Get Thumb Image Gets the thumbnail image of the media item

func (*Media) MarkPlayed

func (s *Media) MarkPlayed(ctx context.Context, key float64, opts ...operations.Option) (*operations.MarkPlayedResponse, error)

MarkPlayed - Mark Media Played This will mark the provided media key as Played.

func (*Media) MarkUnplayed

func (s *Media) MarkUnplayed(ctx context.Context, key float64, opts ...operations.Option) (*operations.MarkUnplayedResponse, error)

MarkUnplayed - Mark Media Unplayed This will mark the provided media key as Unplayed.

func (*Media) UpdatePlayProgress

func (s *Media) UpdatePlayProgress(ctx context.Context, key string, time float64, state string, opts ...operations.Option) (*operations.UpdatePlayProgressResponse, error)

UpdatePlayProgress - Update Media Play Progress This API command can be used to update the play progress of a media item.

type Playlists

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

Playlists are ordered collections of media. They can be dumb (just a list of media) or smart (based on a media query, such as "all albums from 2017"). They can be organized in (optionally nesting) folders. Retrieving a playlist, or its items, will trigger a refresh of its metadata. This may cause the duration and number of items to change.

func (*Playlists) AddPlaylistContents

func (s *Playlists) AddPlaylistContents(ctx context.Context, playlistID float64, uri string, playQueueID *float64, opts ...operations.Option) (*operations.AddPlaylistContentsResponse, error)

AddPlaylistContents - Adding to a Playlist Adds a generator to a playlist, same parameters as the POST to create. With a dumb playlist, this adds the specified items to the playlist. With a smart playlist, passing a new `uri` parameter replaces the rules for the playlist. Returns the playlist.

func (*Playlists) ClearPlaylistContents

func (s *Playlists) ClearPlaylistContents(ctx context.Context, playlistID float64, opts ...operations.Option) (*operations.ClearPlaylistContentsResponse, error)

ClearPlaylistContents - Delete Playlist Contents Clears a playlist, only works with dumb playlists. Returns the playlist.

func (*Playlists) CreatePlaylist

CreatePlaylist - Create a Playlist Create a new playlist. By default the playlist is blank. To create a playlist along with a first item, pass: - `uri` - The content URI for what we're playing (e.g. `server://1234/com.plexapp.plugins.library/library/metadata/1`). - `playQueueID` - To create a playlist from an existing play queue.

func (*Playlists) DeletePlaylist

func (s *Playlists) DeletePlaylist(ctx context.Context, playlistID float64, opts ...operations.Option) (*operations.DeletePlaylistResponse, error)

DeletePlaylist - Deletes a Playlist This endpoint will delete a playlist

func (*Playlists) GetPlaylist

func (s *Playlists) GetPlaylist(ctx context.Context, playlistID float64, opts ...operations.Option) (*operations.GetPlaylistResponse, error)

GetPlaylist - Retrieve Playlist Gets detailed metadata for a playlist. A playlist for many purposes (rating, editing metadata, tagging), can be treated like a regular metadata item: Smart playlist details contain the `content` attribute. This is the content URI for the generator. This can then be parsed by a client to provide smart playlist editing.

func (*Playlists) GetPlaylistContents

GetPlaylistContents - Retrieve Playlist Contents Gets the contents of a playlist. Should be paged by clients via standard mechanisms. By default leaves are returned (e.g. episodes, movies). In order to return other types you can use the `type` parameter. For example, you could use this to display a list of recently added albums vis a smart playlist. Note that for dumb playlists, items have a `playlistItemID` attribute which is used for deleting or moving items.

func (*Playlists) GetPlaylists

GetPlaylists - Get All Playlists Get All Playlists given the specified filters.

func (*Playlists) UpdatePlaylist

func (s *Playlists) UpdatePlaylist(ctx context.Context, playlistID float64, title *string, summary *string, opts ...operations.Option) (*operations.UpdatePlaylistResponse, error)

UpdatePlaylist - Update a Playlist From PMS version 1.9.1 clients can also edit playlist metadata using this endpoint as they would via `PUT /library/metadata/{playlistID}`

func (*Playlists) UploadPlaylist

func (s *Playlists) UploadPlaylist(ctx context.Context, path string, force operations.QueryParamForce, sectionID int64, opts ...operations.Option) (*operations.UploadPlaylistResponse, error)

UploadPlaylist - Upload Playlist Imports m3u playlists by passing a path on the server to scan for m3u-formatted playlist files, or a path to a single playlist file.

type Plex added in v0.2.0

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

Plex - API Calls that perform operations directly against https://Plex.tv

func (*Plex) GetCompanionsData added in v0.11.1

func (s *Plex) GetCompanionsData(ctx context.Context, opts ...operations.Option) (*operations.GetCompanionsDataResponse, error)

GetCompanionsData - Get Companions Data Get Companions Data

func (*Plex) GetGeoData added in v0.11.1

func (s *Plex) GetGeoData(ctx context.Context, opts ...operations.Option) (*operations.GetGeoDataResponse, error)

GetGeoData - Get Geo Data Returns the geolocation and locale data of the caller

func (*Plex) GetHomeData added in v0.9.0

func (s *Plex) GetHomeData(ctx context.Context, opts ...operations.Option) (*operations.GetHomeDataResponse, error)

GetHomeData - Get Plex Home Data Retrieves the home data for the authenticated user, including details like home ID, name, guest access information, and subscription status.

func (*Plex) GetPin added in v0.3.0

GetPin - Get a Pin Retrieve a Pin ID from Plex.tv to use for authentication flows

func (*Plex) GetServerResources added in v0.11.1

func (s *Plex) GetServerResources(ctx context.Context, includeHTTPS *operations.IncludeHTTPS, includeRelay *operations.IncludeRelay, includeIPv6 *operations.IncludeIPv6, clientID *string, opts ...operations.Option) (*operations.GetServerResourcesResponse, error)

GetServerResources - Get Server Resources Get Plex server access tokens and server connections

func (*Plex) GetTokenByPinID added in v0.11.1

GetTokenByPinID - Get Access Token by PinId Retrieve an Access Token from Plex.tv after the Pin has been authenticated

func (*Plex) GetUserFriends added in v0.11.1

func (s *Plex) GetUserFriends(ctx context.Context, opts ...operations.Option) (*operations.GetUserFriendsResponse, error)

GetUserFriends - Get list of friends of the user logged in Get friends of provided auth token.

type PlexAPI

type PlexAPI struct {
	// Operations against the Plex Media Server System.
	//
	Server *Server
	// API Calls interacting with Plex Media Server Media
	//
	Media *Media
	// API Calls that perform operations with Plex Media Server Videos
	//
	Video *Video
	// Activities are awesome. They provide a way to monitor and control asynchronous operations on the server. In order to receive real-time updates for activities, a client would normally subscribe via either EventSource or Websocket endpoints.
	// Activities are associated with HTTP replies via a special `X-Plex-Activity` header which contains the UUID of the activity.
	// Activities are optional cancellable. If cancellable, they may be cancelled via the `DELETE` endpoint. Other details:
	// - They can contain a `progress` (from 0 to 100) marking the percent completion of the activity.
	// - They must contain an `type` which is used by clients to distinguish the specific activity.
	// - They may contain a `Context` object with attributes which associate the activity with various specific entities (items, libraries, etc.)
	// - The may contain a `Response` object which attributes which represent the result of the asynchronous operation.
	//
	Activities *Activities
	// Butler is the task manager of the Plex Media Server Ecosystem.
	//
	Butler *Butler
	// API Calls that perform operations directly against https://Plex.tv
	//
	Plex *Plex
	// Hubs are a structured two-dimensional container for media, generally represented by multiple horizontal rows.
	//
	Hubs *Hubs
	// API Calls that perform search operations with Plex Media Server
	//
	Search *Search
	// API Calls interacting with Plex Media Server Libraries
	//
	Library *Library
	// API Calls that perform operations with Plex Media Server Watchlists
	//
	Watchlist *Watchlist
	// Submit logs to the Log Handler for Plex Media Server
	//
	Log *Log
	// Playlists are ordered collections of media. They can be dumb (just a list of media) or smart (based on a media query, such as "all albums from 2017").
	// They can be organized in (optionally nesting) folders.
	// Retrieving a playlist, or its items, will trigger a refresh of its metadata.
	// This may cause the duration and number of items to change.
	//
	Playlists *Playlists
	// API Calls regarding authentication for Plex Media Server
	//
	Authentication *Authentication
	// API Calls that perform operations with Plex Media Server Statistics
	//
	Statistics *Statistics
	// API Calls that perform search operations with Plex Media Server Sessions
	//
	Sessions *Sessions
	// This describes the API for searching and applying updates to the Plex Media Server.
	// Updates to the status can be observed via the Event API.
	//
	Updater *Updater
	// contains filtered or unexported fields
}

PlexAPI - Plex-API: An Open API Spec for interacting with Plex.tv and Plex Media Server # Plex Media Server OpenAPI Specification

An Open Source OpenAPI Specification for Plex Media Server

Automation and SDKs provided by [Speakeasy](https://speakeasyapi.dev/)

## Documentation

[API Documentation](https://plexapi.dev)

## SDKs

The following SDKs are generated from the OpenAPI Specification. They are automatically generated and may not be fully tested. If you find any issues, please open an issue on the [main specification Repository](https://github.com/LukeHagar/plex-api-spec).

| Language | Repository | Releases | Other | | --------------------- | ------------------------------------------------- | ------------------------------------------------------------------------------------------------ | ------------------------------------------------------- | | Python | [GitHub](https://github.com/LukeHagar/plexpy) | [PyPI](https://pypi.org/project/plex-api-client/) | - | | JavaScript/TypeScript | [GitHub](https://github.com/LukeHagar/plexjs) | [NPM](https://www.npmjs.com/package/@lukehagar/plexjs) \ [JSR](https://jsr.io/@lukehagar/plexjs) | - | | Go | [GitHub](https://github.com/LukeHagar/plexgo) | [Releases](https://github.com/LukeHagar/plexgo/releases) | [GoDoc](https://pkg.go.dev/github.com/LukeHagar/plexgo) | | Ruby | [GitHub](https://github.com/LukeHagar/plexruby) | [Releases](https://github.com/LukeHagar/plexruby/releases) | - | | Swift | [GitHub](https://github.com/LukeHagar/plexswift) | [Releases](https://github.com/LukeHagar/plexswift/releases) | - | | PHP | [GitHub](https://github.com/LukeHagar/plexphp) | [Releases](https://github.com/LukeHagar/plexphp/releases) | - | | Java | [GitHub](https://github.com/LukeHagar/plexjava) | [Releases](https://github.com/LukeHagar/plexjava/releases) | - | | C# | [GitHub](https://github.com/LukeHagar/plexcsharp) | [Releases](https://github.com/LukeHagar/plexcsharp/releases) | -

func New

func New(opts ...SDKOption) *PlexAPI

New creates a new instance of the SDK with the provided options

type SDKOption

type SDKOption func(*PlexAPI)

func WithClient

func WithClient(client HTTPClient) SDKOption

WithClient allows the overriding of the default HTTP client used by the SDK

func WithClientID added in v0.11.11

func WithClientID(clientID string) SDKOption

WithClientID allows setting the ClientID parameter for all supported operations

func WithClientName added in v0.11.11

func WithClientName(clientName string) SDKOption

WithClientName allows setting the ClientName parameter for all supported operations

func WithClientVersion added in v0.11.11

func WithClientVersion(clientVersion string) SDKOption

WithClientVersion allows setting the ClientVersion parameter for all supported operations

func WithDeviceNickname added in v0.15.0

func WithDeviceNickname(deviceNickname string) SDKOption

WithDeviceNickname allows setting the DeviceNickname parameter for all supported operations

func WithIP

func WithIP(ip string) SDKOption

WithIP allows setting the ip variable for url substitution

func WithPlatform added in v0.15.0

func WithPlatform(platform string) SDKOption

WithPlatform allows setting the Platform parameter for all supported operations

func WithPort

func WithPort(port string) SDKOption

WithPort allows setting the port variable for url substitution

func WithProtocol

func WithProtocol(protocol ServerProtocol) SDKOption

WithProtocol allows setting the protocol variable for url substitution

func WithRetryConfig

func WithRetryConfig(retryConfig retry.Config) SDKOption

func WithSecurity

func WithSecurity(accessToken string) SDKOption

WithSecurity configures the SDK to use the provided security details

func WithSecuritySource added in v0.2.1

func WithSecuritySource(security func(context.Context) (components.Security, error)) SDKOption

WithSecuritySource configures the SDK to invoke the Security Source function on each method call to determine authentication

func WithServerIndex

func WithServerIndex(serverIndex int) SDKOption

WithServerIndex allows the overriding of the default server by index

func WithServerURL

func WithServerURL(serverURL string) SDKOption

WithServerURL allows the overriding of the default server URL

func WithTemplatedServerURL

func WithTemplatedServerURL(serverURL string, params map[string]string) SDKOption

WithTemplatedServerURL allows the overriding of the default server URL with a templated URL populated with the provided parameters

func WithTimeout added in v0.11.1

func WithTimeout(timeout time.Duration) SDKOption

WithTimeout Optional request timeout applied to each operation

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

Search - API Calls that perform search operations with Plex Media Server

func (*Search) GetSearchResults

func (s *Search) GetSearchResults(ctx context.Context, query string, opts ...operations.Option) (*operations.GetSearchResultsResponse, error)

GetSearchResults - Get Search Results This will search the database for the string provided.

func (*Search) PerformSearch

func (s *Search) PerformSearch(ctx context.Context, query string, sectionID *float64, limit *float64, opts ...operations.Option) (*operations.PerformSearchResponse, error)

PerformSearch - Perform a search This endpoint performs a search across all library sections, or a single section, and returns matches as hubs, split up by type. It performs spell checking, looks for partial matches, and orders the hubs based on quality of results. In addition, based on matches, it will return other related matches (e.g. for a genre match, it may return movies in that genre, or for an actor match, movies with that actor).

In the response's items, the following extra attributes are returned to further describe or disambiguate the result:

- `reason`: The reason for the result, if not because of a direct search term match; can be either:

  • `section`: There are multiple identical results from different sections.
  • `originalTitle`: There was a search term match from the original title field (sometimes those can be very different or in a foreign language).
  • `<hub identifier>`: If the reason for the result is due to a result in another hub, the source hub identifier is returned. For example, if the search is for "dylan" then Bob Dylan may be returned as an artist result, an a few of his albums returned as album results with a reason code of `artist` (the identifier of that particular hub). Or if the search is for "arnold", there might be movie results returned with a reason of `actor`

- `reasonTitle`: The string associated with the reason code. For a section reason, it'll be the section name; For a hub identifier, it'll be a string associated with the match (e.g. `Arnold Schwarzenegger` for movies which were returned because the search was for "arnold"). - `reasonID`: The ID of the item associated with the reason for the result. This might be a section ID, a tag ID, an artist ID, or a show ID.

This request is intended to be very fast, and called as the user types.

func (*Search) PerformVoiceSearch

func (s *Search) PerformVoiceSearch(ctx context.Context, query string, sectionID *float64, limit *float64, opts ...operations.Option) (*operations.PerformVoiceSearchResponse, error)

PerformVoiceSearch - Perform a voice search This endpoint performs a search specifically tailored towards voice or other imprecise input which may work badly with the substring and spell-checking heuristics used by the `/hubs/search` endpoint. It uses a [Levenshtein distance](https://en.wikipedia.org/wiki/Levenshtein_distance) heuristic to search titles, and as such is much slower than the other search endpoint. Whenever possible, clients should limit the search to the appropriate type. Results, as well as their containing per-type hubs, contain a `distance` attribute which can be used to judge result quality.

type Server

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

Server - Operations against the Plex Media Server System.

func (*Server) GetAvailableClients

func (s *Server) GetAvailableClients(ctx context.Context, opts ...operations.Option) (*operations.GetAvailableClientsResponse, error)

GetAvailableClients - Get Available Clients Get Available Clients

func (*Server) GetDevices

func (s *Server) GetDevices(ctx context.Context, opts ...operations.Option) (*operations.GetDevicesResponse, error)

GetDevices - Get Devices Get Devices

func (*Server) GetMediaProviders added in v0.11.1

func (s *Server) GetMediaProviders(ctx context.Context, xPlexToken string, opts ...operations.Option) (*operations.GetMediaProvidersResponse, error)

GetMediaProviders - Get Media Providers Retrieves media providers and their features from the Plex server.

func (*Server) GetMyPlexAccount

func (s *Server) GetMyPlexAccount(ctx context.Context, opts ...operations.Option) (*operations.GetMyPlexAccountResponse, error)

GetMyPlexAccount - Get MyPlex Account Returns MyPlex Account Information

func (*Server) GetResizedPhoto

GetResizedPhoto - Get a Resized Photo Plex's Photo transcoder is used throughout the service to serve images at specified sizes.

func (*Server) GetServerCapabilities

func (s *Server) GetServerCapabilities(ctx context.Context, opts ...operations.Option) (*operations.GetServerCapabilitiesResponse, error)

GetServerCapabilities - Get Server Capabilities Get Server Capabilities

func (*Server) GetServerIdentity

func (s *Server) GetServerIdentity(ctx context.Context, opts ...operations.Option) (*operations.GetServerIdentityResponse, error)

GetServerIdentity - Get Server Identity This request is useful to determine if the server is online or offline

func (*Server) GetServerList

func (s *Server) GetServerList(ctx context.Context, opts ...operations.Option) (*operations.GetServerListResponse, error)

GetServerList - Get Server List Get Server List

func (*Server) GetServerPreferences

func (s *Server) GetServerPreferences(ctx context.Context, opts ...operations.Option) (*operations.GetServerPreferencesResponse, error)

GetServerPreferences - Get Server Preferences Get Server Preferences

type ServerProtocol

type ServerProtocol string

ServerProtocol - The protocol to use for the server connection

const (
	ServerProtocolHTTP  ServerProtocol = "http"
	ServerProtocolHTTPS ServerProtocol = "https"
)

func (ServerProtocol) ToPointer

func (e ServerProtocol) ToPointer() *ServerProtocol

func (*ServerProtocol) UnmarshalJSON

func (e *ServerProtocol) UnmarshalJSON(data []byte) error

type Sessions

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

Sessions - API Calls that perform search operations with Plex Media Server Sessions

func (*Sessions) GetSessionHistory

func (s *Sessions) GetSessionHistory(ctx context.Context, sort *string, accountID *int64, filter *operations.QueryParamFilter, librarySectionID *int64, opts ...operations.Option) (*operations.GetSessionHistoryResponse, error)

GetSessionHistory - Get Session History This will Retrieve a listing of all history views.

func (*Sessions) GetSessions

func (s *Sessions) GetSessions(ctx context.Context, opts ...operations.Option) (*operations.GetSessionsResponse, error)

GetSessions - Get Active Sessions This will retrieve the "Now Playing" Information of the PMS.

func (*Sessions) GetTranscodeSessions

func (s *Sessions) GetTranscodeSessions(ctx context.Context, opts ...operations.Option) (*operations.GetTranscodeSessionsResponse, error)

GetTranscodeSessions - Get Transcode Sessions Get Transcode Sessions

func (*Sessions) StopTranscodeSession

func (s *Sessions) StopTranscodeSession(ctx context.Context, sessionKey string, opts ...operations.Option) (*operations.StopTranscodeSessionResponse, error)

StopTranscodeSession - Stop a Transcode Session Stop a Transcode Session

type Statistics added in v0.4.0

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

Statistics - API Calls that perform operations with Plex Media Server Statistics

func (*Statistics) GetBandwidthStatistics added in v0.10.0

func (s *Statistics) GetBandwidthStatistics(ctx context.Context, timespan *int64, opts ...operations.Option) (*operations.GetBandwidthStatisticsResponse, error)

GetBandwidthStatistics - Get Bandwidth Statistics This will return the bandwidth statistics for the server

func (*Statistics) GetResourcesStatistics added in v0.10.0

func (s *Statistics) GetResourcesStatistics(ctx context.Context, timespan *int64, opts ...operations.Option) (*operations.GetResourcesStatisticsResponse, error)

GetResourcesStatistics - Get Resources Statistics This will return the resources for the server

func (*Statistics) GetStatistics added in v0.4.0

func (s *Statistics) GetStatistics(ctx context.Context, timespan *int64, opts ...operations.Option) (*operations.GetStatisticsResponse, error)

GetStatistics - Get Media Statistics This will return the media statistics for the server

type Updater

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

Updater - This describes the API for searching and applying updates to the Plex Media Server. Updates to the status can be observed via the Event API.

func (*Updater) ApplyUpdates

func (s *Updater) ApplyUpdates(ctx context.Context, tonight *operations.Tonight, skip *operations.Skip, opts ...operations.Option) (*operations.ApplyUpdatesResponse, error)

ApplyUpdates - Apply Updates Note that these two parameters are effectively mutually exclusive. The `tonight` parameter takes precedence and `skip` will be ignored if `tonight` is also passed

func (*Updater) CheckForUpdates

func (s *Updater) CheckForUpdates(ctx context.Context, download *operations.Download, opts ...operations.Option) (*operations.CheckForUpdatesResponse, error)

CheckForUpdates - Checking for updates Checking for updates

func (*Updater) GetUpdateStatus

func (s *Updater) GetUpdateStatus(ctx context.Context, opts ...operations.Option) (*operations.GetUpdateStatusResponse, error)

GetUpdateStatus - Querying status of updates Querying status of updates

type Video

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

Video - API Calls that perform operations with Plex Media Server Videos

func (*Video) GetTimeline

GetTimeline - Get the timeline for a media item Get the timeline for a media item

func (*Video) StartUniversalTranscode

StartUniversalTranscode - Start Universal Transcode Begin a Universal Transcode Session

type Watchlist added in v0.9.0

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

Watchlist - API Calls that perform operations with Plex Media Server Watchlists

func (*Watchlist) GetWatchList added in v0.11.1

GetWatchList - Get User Watchlist Get User Watchlist

Directories

Path Synopsis
internal
models

Jump to

Keyboard shortcuts

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