plex

package module
v2.0.0 Latest Latest
Warning

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

Go to latest
Published: Jun 9, 2026 License: Apache-2.0 Imports: 21 Imported by: 0

README

Plex.tv and Plex Media Server client written in Go

godoc

go get -u github.com/jrudio/go-plex-client/v2

Version 2

Version 2 brings the library into alignment with the Plex OpenAPI specification (PMS v1.43+).

Major changes include:

  • HubSearch: Switched from legacy /search to the modern /hubs/search endpoint. Use plexConnection.HubSearch("Title") to retrieve results categorized by hubs (Movies, Shows, etc). Legacy search points are still accessible via Search().
  • Accurate Data Models: Models now properly account for the dynamic and polymophic nature of Plex API payloads (e.g. rating values changing from float on searches to array of PlexRating evaluation objects on metadata requests).
CLI

You can tinker with this library using the command-line over here

Get a Plex Token

To interact with the Plex API, you often need an authentication token. You can obtain one by using the plex.tv/link flow, which allows a user to authorize your application using a 4-character code.

import (
	"fmt"
	"time"

	"github.com/jrudio/go-plex-client/v2"
)

func getToken() {
	// 1. Get a PIN code from plex.tv
	// Note: It is recommended to provide your own Headers with a unique ClientIdentifier
	pin, err := plex.RequestPIN(plex.DefaultHeaders(), nil)
	if err != nil {
		panic(err)
	}

	fmt.Printf("Go to https://plex.tv/link and enter the code: %s\n", pin.Code)

	// 2. Poll plex.tv to see if the user has authorized the code
	for {
		// Use the ID from the pin request and your client identifier
		auth, err := plex.CheckPIN(pin.ID, "your-client-id", nil)
		if err != nil {
			// Check if it's just waiting for authorization
			if err.Error() == plex.ErrorPINNotAuthorized {
				time.Sleep(2 * time.Second)
				continue
			}
			panic(err)
		}

		if auth.AuthToken != "" {
			fmt.Printf("Success! Your Plex token is: %s\n", auth.AuthToken)
			break
		}

		time.Sleep(2 * time.Second)
	}
}
Usage

For comprehensive examples, please check the example/ directory. It contains code for connecting to a Plex server, utilizing the webhook receiver, interacting with search hubs, and setting up WebSocket notifications.

Basic Initialization:

import "github.com/jrudio/go-plex-client/v2"

plexConnection, err := plex.New("http://192.168.1.2:32400", "myPlexToken")
if err != nil {
	panic(err)
}

// Test your connection to your Plex server
result, err := plexConnection.Test()

// Search for media in your plex server using the modern Hubs endpoint
results, err := plexConnection.HubSearch("The Walking Dead")

// ... Please checkout plex.go or the example folder for more methods

Documentation

Index

Constants

View Source
const (
	ErrorInvalidToken       = "invalid token"
	ErrorNotAuthorized      = "you are not authorized to access that server"
	ErrorCommon             = "error: %s"
	ErrorKeyIsRequired      = "key is required"
	ErrorTitleRequired      = "a title is required"
	ErrorServerReplied      = "server replied with %d status code"
	ErrorMissingSessionKey  = "missing sessionKey"
	ErrorUrlTokenRequired   = "url or a token is required"
	ErrorServer             = "server error: %s"
	ErrorPINNotAuthorized   = "pin is not authorized yet"
	ErrorLinkAccount        = "failed to link account: %s"
	ErrorFailedToSetWebhook = "failed to set webhook"
	ErrorWebhook            = "webhook error: %s"
)

ErrorInvalidToken a constant to help check invalid token errors

Variables

This section is empty.

Functions

func GetMediaType

func GetMediaType(info MediaMetadata) string

GetMediaType is a helper function that returns the media type. Usually, used after GetMetadata().

func GetMediaTypeID

func GetMediaTypeID(mediaType string) string

GetMediaTypeID returns plex's media type id

Types

type ActivityNotification

type ActivityNotification struct {
	Activity struct {
		Cancellable bool   `json:"cancellable"`
		Progress    int64  `json:"progress"`
		Subtitle    string `json:"subtitle"`
		Title       string `json:"title"`
		Type        string `json:"type"`
		UserID      int64  `json:"userID"`
		UUID        string `json:"uuid"`
	} `json:"Activity"`
	Event string `json:"event"`
	UUID  string `json:"uuid"`
}

ActivityNotification ...

type AltGUID

type AltGUID struct {
	ID string `json:"id"`
}

AltGUID represents a Globally Unique Identifier for a metadata provider that is not actively being used.

type BackgroundProcessingQueueEventNotification

type BackgroundProcessingQueueEventNotification struct {
	Event   string `json:"event"`
	QueueID int64  `json:"queueID"`
}

BackgroundProcessingQueueEventNotification ...

type BackgroundProcessingResponse

type BackgroundProcessingResponse struct {
	MediaContainer struct {
		Size int `json:"size"`
	} `json:"MediaContainer"`
}

BackgroundProcessingResponse holds details of running background transcoder/optimization tasks

type BaseAPIResponse

type BaseAPIResponse struct {
	MediaContainer struct {
		Directory []struct {
			Count int64  `json:"count"`
			Key   string `json:"key"`
			Title string `json:"title"`
		} `json:"Directory"`
		AllowCameraUpload             bool   `json:"allowCameraUpload"`
		AllowChannelAccess            bool   `json:"allowChannelAccess"`
		AllowSharing                  bool   `json:"allowSharing"`
		AllowSync                     bool   `json:"allowSync"`
		BackgroundProcessing          bool   `json:"backgroundProcessing"`
		Certificate                   bool   `json:"certificate"`
		CompanionProxy                bool   `json:"companionProxy"`
		CountryCode                   string `json:"countryCode"`
		Diagnostics                   string `json:"diagnostics"`
		EventStream                   bool   `json:"eventStream"`
		FriendlyName                  string `json:"friendlyName"`
		HubSearch                     bool   `json:"hubSearch"`
		ItemClusters                  bool   `json:"itemClusters"`
		Livetv                        int64  `json:"livetv"`
		MachineIdentifier             string `json:"machineIdentifier"`
		MediaProviders                bool   `json:"mediaProviders"`
		Multiuser                     bool   `json:"multiuser"`
		MyPlex                        bool   `json:"myPlex"`
		MyPlexMappingState            string `json:"myPlexMappingState"`
		MyPlexSigninState             string `json:"myPlexSigninState"`
		MyPlexSubscription            bool   `json:"myPlexSubscription"`
		MyPlexUsername                string `json:"myPlexUsername"`
		OwnerFeatures                 string `json:"ownerFeatures"`
		PhotoAutoTag                  bool   `json:"photoAutoTag"`
		Platform                      string `json:"platform"`
		PlatformVersion               string `json:"platformVersion"`
		PluginHost                    bool   `json:"pluginHost"`
		ReadOnlyLibraries             bool   `json:"readOnlyLibraries"`
		RequestParametersInCookie     bool   `json:"requestParametersInCookie"`
		Size                          int64  `json:"size"`
		StreamingBrainABRVersion      int64  `json:"streamingBrainABRVersion"`
		StreamingBrainVersion         int64  `json:"streamingBrainVersion"`
		Sync                          bool   `json:"sync"`
		TranscoderActiveVideoSessions int64  `json:"transcoderActiveVideoSessions"`
		TranscoderAudio               bool   `json:"transcoderAudio"`
		TranscoderLyrics              bool   `json:"transcoderLyrics"`
		TranscoderPhoto               bool   `json:"transcoderPhoto"`
		TranscoderSubtitles           bool   `json:"transcoderSubtitles"`
		TranscoderVideo               bool   `json:"transcoderVideo"`
		TranscoderVideoBitrates       string `json:"transcoderVideoBitrates"`
		TranscoderVideoQualities      string `json:"transcoderVideoQualities"`
		TranscoderVideoResolutions    string `json:"transcoderVideoResolutions"`
		UpdatedAt                     int64  `json:"updatedAt"`
		Updater                       bool   `json:"updater"`
		Version                       string `json:"version"`
		VoiceSearch                   bool   `json:"voiceSearch"`
	} `json:"MediaContainer"`
}

BaseAPIResponse info about the Plex Media Server

type Connection

type Connection struct {
	Protocol string `json:"protocol" xml:"protocol,attr"`
	Address  string `json:"address" xml:"address,attr"`
	Port     string `json:"port" xml:"port,attr"`
	URI      string `json:"uri" xml:"uri,attr"`
	Local    int    `json:"local" xml:"local,attr"`
}

Connection lists options to connect to a device

type CreateLibraryParams

type CreateLibraryParams struct {
	Name        string
	Location    string
	LibraryType string
	Agent       string
	Scanner     string
	Language    string
}

CreateLibraryParams params required to create a library

func LibraryParamsFromMediaType

func LibraryParamsFromMediaType(mediaType string) (CreateLibraryParams, error)

LibraryParamsFromMediaType is a helper for CreateLibraryParams

type CurrentSessions

type CurrentSessions struct {
	MediaContainer struct {
		Metadata []Metadata `json:"Metadata"`
		Size     int        `json:"size"`
	} `json:"MediaContainer"`
}

CurrentSessions metadata of users consuming media

type DevicesResponse

type DevicesResponse struct {
	ID         int    `json:"id"`
	LastSeenAt string `json:"lastSeenAt"`
	Name       string `json:"name"`
	Product    string `json:"product"`
	Version    string `json:"version"`
}

DevicesResponse metadata of a device that has connected to your server

type Directory

type Directory struct {
	Location   []Location `json:"Location"`
	Agent      string     `json:"agent"`
	AllowSync  bool       `json:"allowSync"`
	Art        string     `json:"art"`
	Composite  string     `json:"composite"`
	CreatedAt  int        `json:"createdAt"`
	Filter     bool       `json:"filters"`
	Key        string     `json:"key"`
	Language   string     `json:"language"`
	Refreshing bool       `json:"refreshing"`
	Scanner    string     `json:"scanner"`
	Thumb      string     `json:"thumb"`
	Title      string     `json:"title"`
	Type       string     `json:"type"`
	UpdatedAt  int        `json:"updatedAt"`
	UUID       string     `json:"uuid"`
}

Directory shows plex directory metadata

type ErrorResponse

type ErrorResponse struct {
	Code    int    `json:"code"`
	Message string `json:"message"`
}

ErrorResponse contains a code and an error message

type FlexibleBool

type FlexibleBool bool

FlexibleBool is a custom type that handles Plex's inconsistent JSON boolean representations. Plex sometimes returns booleans as literals (true/false), strings ("true"/"false"), integers (1/0), or quoted integers ("1"/"0"). This type ensures robust unmarshaling by supporting all representations.

func (FlexibleBool) MarshalJSON

func (fb FlexibleBool) MarshalJSON() ([]byte, error)

MarshalJSON implements the json.Marshaler interface.

func (*FlexibleBool) UnmarshalJSON

func (fb *FlexibleBool) UnmarshalJSON(data []byte) error

UnmarshalJSON implements the json.Unmarshaler interface.

type FlexibleFloat64

type FlexibleFloat64 float64

FlexibleFloat64 is a custom type that handles Plex's inconsistent JSON numeric representations. Plex sometimes returns numbers as literals, but other times as strings (e.g., "8.5"). This type ensures robust unmarshaling by supporting both.

func (FlexibleFloat64) MarshalJSON

func (ff FlexibleFloat64) MarshalJSON() ([]byte, error)

MarshalJSON implements the json.Marshaler interface.

func (*FlexibleFloat64) UnmarshalJSON

func (ff *FlexibleFloat64) UnmarshalJSON(data []byte) error

UnmarshalJSON implements the json.Unmarshaler interface.

type Friends

type Friends struct {
	ID                        int    `xml:"id,attr" json:"id"`
	Title                     string `xml:"title,attr" json:"title"`
	Thumb                     string `xml:"thumb,attr" json:"thumb"`
	Protected                 string `xml:"protected,attr" json:"protected"`
	Home                      string `xml:"home,attr" json:"home"`
	AllowSync                 string `xml:"allowSync,attr" json:"allowSync"`
	AllowCameraUpload         string `xml:"allowCameraUpload,attr" json:"allowCameraUpload"`
	AllowChannels             string `xml:"allowChannels,attr" json:"allowChannels"`
	FilterAll                 string `xml:"filterAll,attr" json:"filterAll"`
	FilterMovies              string `xml:"filterMovies,attr" json:"filterMovies"`
	FilterMusic               string `xml:"filterMusic,attr" json:"filterMusic"`
	FilterPhotos              string `xml:"filterPhotos,attr" json:"filterPhotos"`
	FilterTelevision          string `xml:"filterTelevision,attr" json:"filterTelevision"`
	Restricted                string `xml:"restricted,attr" json:"restricted"`
	Username                  string `xml:"username,attr" json:"username"`
	Email                     string `xml:"email,attr" json:"email"`
	RecommendationsPlaylistID string `xml:"recommendationsPlaylistId,attr" json:"recommendationsPlaylistId"`
	Server                    struct {
		ID                string `xml:"id,attr" json:"id"`
		ServerID          string `xml:"serverId,attr" json:"serverId"`
		MachineIdentifier string `xml:"machineIdentifier,attr" json:"machineIdentifier"`
		Name              string `xml:"name,attr" json:"name"`
		LastSeenAt        string `xml:"lastSeenAt,attr" json:"lastSeenAt"`
		NumLibraries      string `xml:"numLibraries,attr" json:"numLibraries"`
		AllLibraries      string `xml:"allLibraries,attr" json:"allLibraries"`
		Owned             string `xml:"owned,attr" json:"owned"`
		Pending           string `xml:"pending,attr" json:"pending"`
	} `xml:"Server" json:"Server"`
}

Friends are the plex accounts that have access to your server

type Headers

type Headers struct {
	Platform               string
	PlatformVersion        string
	Provides               string
	Product                string
	Version                string
	Device                 string
	ContainerSize          string
	ContainerStart         string
	Token                  string
	Accept                 string
	ContentType            string
	ClientIdentifier       string
	TargetClientIdentifier string
}

func DefaultHeaders

func DefaultHeaders() Headers

DefaultHeaders returns the default headers for used when making requests to Plex

type Hub

type Hub struct {
	Key           string      `json:"key"`
	Type          string      `json:"type"`
	Title         string      `json:"title"`
	HubIdentifier string      `json:"hubIdentifier"`
	Context       string      `json:"context"`
	Size          int         `json:"size"`
	More          bool        `json:"more"`
	Style         string      `json:"style"`
	Metadata      []Metadata  `json:"Metadata"`
	Directory     []Directory `json:"Directory,omitempty"` // Sometimes hubs return directories
}

Hub represents a hub in the Plex API (e.g. for search results)

type InviteFriendParams

type InviteFriendParams struct {
	UsernameOrEmail string
	MachineID       string
	Label           string
	LibraryIDs      []int
}

InviteFriendParams are the params to invite a friend

type InvitedFriend

type InvitedFriend struct {
	ID           string `xml:"id,attr" json:"id"`
	CreatedAt    string `xml:"createdAt,attr" json:"createdAt"`
	IsFriend     bool   `xml:"friend,attr" json:"friend"`
	IsHome       bool   `xml:"home,attr" json:"home"`
	IsServer     bool   `xml:"server,attr" json:"server"`
	Username     string `xml:"username,attr" json:"username"`
	Email        string `xml:"email,attr" json:"email"`
	Thumb        string `xml:"thumb,attr" json:"thumb"`
	FriendlyName string `xml:"friendlyName,attr" json:"friendlyName"`
	Server       struct {
		Name         string `xml:"name,attr" json:"name"`
		NumLibraries string `xml:"numLibraries,attr" json:"numLibraries"`
	} `xml:"Server" json:"Server"`
}

type JWK

type JWK struct {
	Kty string `json:"kty"`
	Crv string `json:"crv"`
	X   string `json:"x"`
	Kid string `json:"kid"`
	Alg string `json:"alg"`
	Use string `json:"use,omitempty"`
}

JWK represents a JSON Web Key

type KeyPair

type KeyPair struct {
	Public  ed25519.PublicKey
	Private ed25519.PrivateKey
}

KeyPair holds the private and public keys for a device

func GenerateKeyPair

func GenerateKeyPair() (*KeyPair, error)

GenerateKeyPair creates a new random Ed25519 key pair

func (*KeyPair) JWK

func (k *KeyPair) JWK() JWK

JWK returns the public key in JWK format

func (*KeyPair) Kid

func (k *KeyPair) Kid() string

Kid returns the Key ID (base64 encoded public key)

func (*KeyPair) SignJWT

func (k *KeyPair) SignJWT(claims jwt.MapClaims) (string, error)

SignJWT creates a signed JWT for the device

type LibraryLabels

type LibraryLabels struct {
	ElementType     string `json:"_elementType"`
	AllowSync       string `json:"allowSync"`
	Art             string `json:"art"`
	Content         string `json:"content"`
	Identifier      string `json:"identifier"`
	MediaTagPrefix  string `json:"mediaTagPrefix"`
	MediaTagVersion string `json:"mediaTagVersion"`
	Thumb           string `json:"thumb"`
	Title1          string `json:"title1"`
	Title2          string `json:"title2"`
	ViewGroup       string `json:"viewGroup"`
	ViewMode        string `json:"viewMode"`
	Children        []struct {
		ElementType string `json:"_elementType"`
		FastKey     string `json:"fastKey"`
		Key         string `json:"key"`
		Title       string `json:"title"`
	} `json:"_children"`
}

LibraryLabels are the existing labels set on your server

type LibrarySections

type LibrarySections struct {
	MediaContainer struct {
		Directory []Directory `json:"Directory"`
	} `json:"MediaContainer"`
}

LibrarySections metadata of your library contents

type Location

type Location struct {
	ID   int    `json:"id"`
	Path string `json:"path"`
}

Location is the path of a plex server directory

type Media

type Media struct {
	AspectRatio           json.Number  `json:"aspectRatio"`
	AudioChannels         int          `json:"audioChannels"`
	AudioCodec            string       `json:"audioCodec"`
	AudioProfile          string       `json:"audioProfile"`
	Bitrate               int          `json:"bitrate"`
	Container             string       `json:"container"`
	Duration              int          `json:"duration"`
	Has64bitOffsets       FlexibleBool `json:"has64bitOffsets"`
	HasVoiceActivity      FlexibleBool `json:"hasVoiceActivity"`
	Height                int          `json:"height"`
	ID                    json.Number  `json:"id"`
	OptimizedForStreaming boolOrInt    `json:"optimizedForStreaming"`
	Selected              FlexibleBool `json:"selected"`
	VideoCodec            string       `json:"videoCodec"`
	VideoFrameRate        string       `json:"videoFrameRate"`
	VideoProfile          string       `json:"videoProfile"`
	VideoResolution       string       `json:"videoResolution"`
	Width                 int          `json:"width"`
	Part                  []Part       `json:"Part"`
}

Media media info

type MediaContainer

type MediaContainer struct {
	Metadata            []Metadata `json:"Metadata"`
	AllowSync           bool       `json:"allowSync"`
	Identifier          string     `json:"identifier"`
	LibrarySectionID    int        `json:"librarySectionID"`
	LibrarySectionTitle string     `json:"librarySectionTitle"`
	LibrarySectionUUID  string     `json:"librarySectionUUID"`
	MediaTagPrefix      string     `json:"mediaTagPrefix"`
	MediaTagVersion     int        `json:"mediaTagVersion"`
	Size                int        `json:"size"`
}

MediaContainer contains media info

type MediaMetadata

type MediaMetadata struct {
	MediaContainer MediaContainer `json:"MediaContainer"`
}

MediaMetadata ...

type Metadata

type Metadata struct {
	AddedAt               int64           `json:"addedAt"`
	Art                   string          `json:"art"`
	Banner                string          `json:"banner,omitempty"`
	AudienceRating        FlexibleFloat64 `json:"audienceRating,omitempty"`
	AudienceRatingImage   string          `json:"audienceRatingImage,omitempty"`
	ChapterSource         string          `json:"chapterSource,omitempty"`
	ChildCount            int             `json:"childCount,omitempty"`
	ContentRating         string          `json:"contentRating"`
	Duration              int             `json:"duration"`
	GrandparentArt        string          `json:"grandparentArt"`
	GrandparentKey        string          `json:"grandparentKey"`
	GrandparentRatingKey  string          `json:"grandparentRatingKey"`
	GrandparentTheme      string          `json:"grandparentTheme"`
	GrandparentThumb      string          `json:"grandparentThumb"`
	GrandparentTitle      string          `json:"grandparentTitle"`
	GUID                  string          `json:"guid"`
	AltGUIDs              []AltGUID       `json:"Guid"`
	Hero                  string          `json:"hero,omitempty"`
	Index                 int64           `json:"index"`
	Key                   string          `json:"key"`
	LastViewedAt          int64           `json:"lastViewedAt"`
	LeafCount             int             `json:"leafCount,omitempty"`
	LibrarySectionID      json.Number     `json:"librarySectionID"`
	LibrarySectionKey     string          `json:"librarySectionKey"`
	LibrarySectionTitle   string          `json:"librarySectionTitle"`
	OriginallyAvailableAt string          `json:"originallyAvailableAt"`
	OriginalTitle         string          `json:"originalTitle,omitempty"`
	ParentIndex           int64           `json:"parentIndex"`
	ParentKey             string          `json:"parentKey"`
	ParentRatingKey       string          `json:"parentRatingKey"`
	ParentThumb           string          `json:"parentThumb"`
	ParentTitle           string          `json:"parentTitle"`
	PrimaryExtraKey       string          `json:"primaryExtraKey,omitempty"`
	Rating                FlexibleFloat64 `json:"rating"`
	Ratings               []PlexRating    `json:"-"` // Populated via UnmarshalJSON
	RatingCount           int             `json:"ratingCount"`
	RatingImage           string          `json:"ratingImage,omitempty"`
	RatingKey             string          `json:"ratingKey"`
	PlaylistItemID        string          `json:"playlistItemId,omitempty"`
	SessionKey            string          `json:"sessionKey"`
	SkipChildren          bool            `json:"skipChildren,omitempty"`
	SkipParent            bool            `json:"skipParent,omitempty"`
	SquareArt             string          `json:"squareArt,omitempty"`
	Studio                string          `json:"studio,omitempty"`
	Summary               string          `json:"summary"`
	Tagline               string          `json:"tagline,omitempty"`
	Theme                 string          `json:"theme,omitempty"`
	Thumb                 string          `json:"thumb"`
	Title                 string          `json:"title"`
	TitleSort             string          `json:"titleSort"`
	Type                  string          `json:"type"`
	UpdatedAt             int64           `json:"updatedAt"`
	UserRating            FlexibleFloat64 `json:"userRating"`
	ViewCount             json.Number     `json:"viewCount"`
	ViewedLeafCount       int             `json:"viewedLeafCount,omitempty"`
	ViewOffset            int             `json:"viewOffset"`
	Year                  int             `json:"year"`
	Media                 []Media         `json:"Media"`
	Director              []TaggedData    `json:"Director"`
	Writer                []TaggedData    `json:"Writer"`
	Genre                 []TaggedData    `json:"Genre"`
	Country               []TaggedData    `json:"Country"`
	Role                  []Role          `json:"Role"`
	Player                Player          `json:"Player"`
	Session               Session         `json:"Session"`
	User                  User            `json:"User"`
}

Metadata ...

func (*Metadata) UnmarshalJSON

func (m *Metadata) UnmarshalJSON(data []byte) error

UnmarshalJSON implements custom unmarshaling for Metadata to handle polymorphic 'rating' field

type MetadataAgentProvider

type MetadataAgentProvider struct {
	Identifier   string         `json:"identifier"`
	Title        string         `json:"title"`
	Type         string         `json:"type"`
	MetadataType []MetadataType `json:"MetadataType"`
	Online       bool           `json:"online"`
}

MetadataAgentProvider represents a metadata provider in Plex.

type MetadataChildren

type MetadataChildren struct {
	MediaContainer MediaContainer `json:"MediaContainer"`
}

MetadataChildren returns metadata about a piece of media (tv show, movie, music, etc)

type MetadataProviderResponse

type MetadataProviderResponse struct {
	MediaContainer struct {
		MediaContainer
		MetadataAgentProvider []MetadataAgentProvider `json:"MetadataAgentProvider"`
	} `json:"MediaContainer"`
}

MetadataProviderResponse represents the response from the Metadata Providers API.

type MetadataType

type MetadataType struct {
	Type int `json:"type"`
}

MetadataType represents a metadata type supported by a provider.

type NotificationContainer

type NotificationContainer struct {
	TimelineEntry []TimelineEntry `json:"TimelineEntry"`

	ActivityNotification []ActivityNotification `json:"ActivityNotification"`

	StatusNotification []StatusNotification `json:"StatusNotification"`

	PlaySessionStateNotification []PlaySessionStateNotification `json:"PlaySessionStateNotification"`

	ReachabilityNotification []ReachabilityNotification `json:"ReachabilityNotification"`

	BackgroundProcessingQueueEventNotification []BackgroundProcessingQueueEventNotification `json:"BackgroundProcessingQueueEventNotification"`

	TranscodeSession []TranscodeSession `json:"TranscodeSession"`

	Setting []Setting `json:"Setting"`

	ProgressNotification []ProgressNotification `json:"ProgressNotification"`

	Size int64 `json:"size"`
	// Type can be one of:
	// playing,
	// reachability,
	// transcode.end,
	// preference,
	// update.statechange,
	// activity,
	// backgroundProcessingQueue,
	// transcodeSession.update
	// transcodeSession.end
	Type string `json:"type"`
}

NotificationContainer read pms notifications

type NotificationEvents

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

NotificationEvents hold callbacks that correspond to notifications

func NewNotificationEvents

func NewNotificationEvents() *NotificationEvents

NewNotificationEvents initializes the event callbacks

func (*NotificationEvents) OnPlaying

func (e *NotificationEvents) OnPlaying(fn func(n NotificationContainer))

OnPlaying shows state information (resume, stop, pause) on a user consuming media in plex

func (*NotificationEvents) OnProgress

func (e *NotificationEvents) OnProgress(fn func(n NotificationContainer))

OnProgress shows background activities/scans progress information

func (*NotificationEvents) OnTranscodeEnd

func (e *NotificationEvents) OnTranscodeEnd(fn func(n NotificationContainer))

OnTranscodeEnd is called when a transcode session ends

func (*NotificationEvents) OnTranscodeStart

func (e *NotificationEvents) OnTranscodeStart(fn func(n NotificationContainer))

OnTranscodeStart is called when a new transcode session begins

func (*NotificationEvents) OnTranscodeUpdate

func (e *NotificationEvents) OnTranscodeUpdate(fn func(n NotificationContainer))

OnTranscodeUpdate shows transcode information when a transcoding stream changes parameters

type PMSDevices

type PMSDevices struct {
	Name                 string       `json:"name" xml:"name,attr"`
	Product              string       `json:"product" xml:"product,attr"`
	ProductVersion       string       `json:"productVersion" xml:"productVersion,attr"`
	Platform             string       `json:"platform" xml:"platform,attr"`
	PlatformVersion      string       `json:"platformVersion" xml:"platformVersion,attr"`
	Device               string       `json:"device" xml:"device,attr"`
	ClientIdentifier     string       `json:"clientIdentifier" xml:"clientIdentifier,attr"`
	CreatedAt            string       `json:"createdAt" xml:"createdAt,attr"`
	LastSeenAt           string       `json:"lastSeenAt" xml:"lastSeenAt,attr"`
	Provides             string       `json:"provides" xml:"provides,attr"`
	Owned                string       `json:"owned" xml:"owned,attr"`
	AccessToken          string       `json:"accessToken" xml:"accessToken,attr"`
	HTTPSRequired        int          `json:"httpsRequired" xml:"httpsRequired,attr"`
	Synced               string       `json:"synced" xml:"synced,attr"`
	Relay                int          `json:"relay" xml:"relay,attr"`
	PublicAddressMatches string       `json:"publicAddressMatches" xml:"publicAddressMatches,attr"`
	PublicAddress        string       `json:"publicAddress" xml:"publicAddress,attr"`
	Presence             string       `json:"presence" xml:"presence,attr"`
	Connection           []Connection `json:"connection" xml:"Connection"`
}

PMSDevices is the result of the https://plex.tv/pms/resources endpoint

type Part

type Part struct {
	AudioProfile          string       `json:"audioProfile"`
	Container             string       `json:"container"`
	Decision              string       `json:"decision"`
	Duration              int          `json:"duration"`
	File                  string       `json:"file"`
	Has64bitOffsets       FlexibleBool `json:"has64bitOffsets"`
	HasThumbnail          string       `json:"hasThumbnail"`
	ID                    json.Number  `json:"id"`
	Key                   string       `json:"key"`
	OptimizedForStreaming boolOrInt    `json:"optimizedForStreaming"`
	Selected              FlexibleBool `json:"selected"`
	Size                  int64        `json:"size"`
	Stream                []Stream     `json:"Stream"`
	VideoProfile          string       `json:"videoProfile"`
}

Part ...

type PinResponse

type PinResponse struct {
	ID               int             `json:"id"`
	Code             string          `json:"code"`
	ClientIdentifier string          `json:"clientIdentifier"`
	CreatedAt        string          `json:"createdAt"`
	ExpiresAt        string          `json:"expiresAt"`
	ExpiresIn        json.Number     `json:"expiresIn"`
	AuthToken        string          `json:"authToken"`
	Errors           []ErrorResponse `json:"errors"`
	Trusted          bool            `json:"trusted"`
	Location         struct {
		Code         string `json:"code"`
		Country      string `json:"country"`
		City         string `json:"city"`
		Subdivisions string `json:"subdivisions"`
		Coordinates  string `json:"coordinates"`
	}
}

PinResponse holds information to successfully check a pin when linking an account

func CheckPIN

func CheckPIN(id int, clientIdentifier string, keyPair *KeyPair) (PinResponse, error)

CheckPIN will return information related to the pin such as the auth token if your code has been approved. will return an error if code expired or still not linked clientIdentifier must be the same when requesting a pin

func RequestPIN

func RequestPIN(requestHeaders Headers, keyPair *KeyPair) (PinResponse, error)

RequestPIN will retrieve a code (valid for 15 minutes) from plex.tv to link an app to your plex account

type PlaySessionStateNotification

type PlaySessionStateNotification struct {
	GUID             string `json:"guid"`
	Key              string `json:"key"`
	PlayQueueItemID  int64  `json:"playQueueItemID"`
	RatingKey        string `json:"ratingKey"`
	SessionKey       string `json:"sessionKey"`
	State            string `json:"state"`
	URL              string `json:"url"`
	ViewOffset       int64  `json:"viewOffset"`
	TranscodeSession string `json:"transcodeSession"`
}

PlaySessionStateNotification ...

type Player

type Player struct {
	Address             string `json:"address"`
	Device              string `json:"device"`
	Local               bool   `json:"local"`
	MachineIdentifier   string `json:"machineIdentifier"`
	Model               string `json:"model"`
	Platform            string `json:"platform"`
	PlatformVersion     string `json:"platformVersion"`
	Product             string `json:"product"`
	Profile             string `json:"profile"`
	RemotePublicAddress string `json:"remotePublicAddress"`
	State               string `json:"state"`
	Title               string `json:"title"`
	UserID              int    `json:"userID"`
	Vendor              string `json:"vendor"`
	Version             string `json:"version"`
}

Player ...

type PlaylistMetadata

type PlaylistMetadata struct {
	MediaContainer struct {
		Size     int        `json:"size"`
		Metadata []Metadata `json:"Metadata"`
	} `json:"MediaContainer"`
}

PlaylistMetadata represents Plex's playlists container JSON structure

type Plex

type Plex struct {
	URL              string
	Token            string
	ClientIdentifier string
	Headers          Headers
	HTTPClient       http.Client
	DownloadClient   http.Client
}

Plex contains fields that are required to make an api call to your plex server

func New

func New(baseURL, token string) (*Plex, error)

New creates a new plex instance that is required to to make requests to your Plex Media Server

func SignIn

func SignIn(username, password string) (*Plex, error)

SignIn creates a plex instance using a user name and password instead of an auth token.

func (*Plex) AddCollectionItem

func (p *Plex) AddCollectionItem(collectionID, ratingKey string) error

AddCollectionItem adds a media item (by ratingKey) to a manual collection.

func (*Plex) AddLabelToMedia

func (p *Plex) AddLabelToMedia(mediaType, sectionID, id, label, locked string) (bool, error)

AddLabelToMedia restrict access to certain media. Requires a Plex Pass. mediaType is the media type (1), id is the ratingKey or media id, label is your label, locked is unknown 1. A reference to the plex media types: https://github.com/Arcanemagus/plex-api/wiki/MediaTypes XXX: Currently plex is capitalizing the first letter

func (*Plex) AddPlaylistItems

func (p *Plex) AddPlaylistItems(playlistID, ratingKey string) error

AddPlaylistItems adds a media item to an existing playlist

func (Plex) AddWebhook

func (p Plex) AddWebhook(webhook string) error

AddWebhook creates a new webhook for your plex server to send metadata - requires plex pass

func (*Plex) CheckUsernameOrEmail

func (p *Plex) CheckUsernameOrEmail(usernameOrEmail string) (bool, error)

CheckUsernameOrEmail will check if the username is a Plex user or will verify an email is valid

func (*Plex) CreateCollection

func (p *Plex) CreateCollection(sectionID, title string) (MediaMetadata, error)

CreateCollection creates a new manual collection in a specific library section.

func (*Plex) CreateLibrary

func (p *Plex) CreateLibrary(params CreateLibraryParams) error

CreateLibrary will create a new library on your Plex server

func (*Plex) CreatePlaylist

func (p *Plex) CreatePlaylist(title, ratingKey string) (PlaylistMetadata, error)

CreatePlaylist creates a new custom playlist with an initial media item

func (*Plex) DeleteLibrary

func (p *Plex) DeleteLibrary(key string) error

DeleteLibrary removes the library from your Plex server via library key (or id)

func (*Plex) DeleteMediaByID

func (p *Plex) DeleteMediaByID(id string) error

DeleteMediaByID removes the media from your Plex server via media key (or id)

func (*Plex) DeleteMetadataElement

func (p *Plex) DeleteMetadataElement(key, elementID string) error

DeleteMetadataElement removes a metadata element (like a tag, or a poster) from a piece of media.

func (*Plex) DeletePlexToken

func (p *Plex) DeletePlexToken(token string) (bool, error)

DeletePlexToken is currently not tested

func (*Plex) Download

func (p *Plex) Download(meta Metadata, path string, createFolders bool, skipIfExists bool) error

Download media associated with metadata

func (*Plex) ExtractKeyAndThumbFromURL

func (p *Plex) ExtractKeyAndThumbFromURL(_url string) (string, string)

ExtractKeyAndThumbFromURL extracts the rating key and thumbnail id from the url

func (*Plex) ExtractKeyFromRatingKey

func (*Plex) ExtractKeyFromRatingKey(key string) string

ExtractKeyFromRatingKey extracts the key from the rating key url

func (*Plex) ExtractKeyFromRatingKeyRegex

func (p *Plex) ExtractKeyFromRatingKeyRegex(key string) string

ExtractKeyFromRatingKeyRegex extracts the key from a rating key url via regex

func (*Plex) GetBackgroundProcessing

func (p *Plex) GetBackgroundProcessing() (string, error)

GetBackgroundProcessing retrieves running background transcoding or optimization processes

func (*Plex) GetCollections

func (p *Plex) GetCollections(sectionID string) (MediaMetadata, error)

GetCollections lists all collections within a specific library section.

func (*Plex) GetDevices

func (p *Plex) GetDevices() ([]PMSDevices, error)

GetDevices returns a list of your Plex devices (servers, players, controllers, etc)

func (*Plex) GetEpisode

func (p *Plex) GetEpisode(key string) (SearchResultsEpisode, error)

GetEpisode returns a single episode of a show.

func (*Plex) GetEpisodes

func (p *Plex) GetEpisodes(key string) (SearchResultsEpisode, error)

GetEpisodes returns episodes of a season of a show

func (*Plex) GetFriends

func (p *Plex) GetFriends() ([]Friends, error)

GetFriends returns all of your plex friends

func (*Plex) GetInvitedFriends

func (p *Plex) GetInvitedFriends() ([]InvitedFriend, error)

GetInvitedFriends get all invited friends with request still pending

func (*Plex) GetLibraries

func (p *Plex) GetLibraries() (LibrarySections, error)

GetLibraries of your Plex server. My ideal use-case would be to get library count to determine label index

func (*Plex) GetLibraryContent

func (p *Plex) GetLibraryContent(sectionKey string, filter string) (SearchResults, error)

GetLibraryContent retrieve the content inside a library

func (*Plex) GetLibraryLabels

func (p *Plex) GetLibraryLabels(sectionKey, sectionIndex string) (LibraryLabels, error)

GetLibraryLabels of your plex server

func (*Plex) GetMachineID

func (p *Plex) GetMachineID() (string, error)

GetMachineID returns the machine id of the server with the associated access token

func (*Plex) GetMachineIDLocal

func (p *Plex) GetMachineIDLocal() (string, error)

GetMachineIDLocal fetches the local Plex server's machine identifier directly from the server root.

func (*Plex) GetMetadata

func (p *Plex) GetMetadata(key string) (MediaMetadata, error)

GetMetadata can get some media info

func (*Plex) GetMetadataChildren

func (p *Plex) GetMetadataChildren(key string) (MetadataChildren, error)

GetMetadataChildren can get a show's season titles. My use-case would be getting the season titles after using Search()

func (*Plex) GetMetadataProviders

func (p *Plex) GetMetadataProviders() (MetadataProviderResponse, error)

GetMetadataProviders returns a list of metadata providers available on the server.

func (*Plex) GetOnDeck

func (p *Plex) GetOnDeck() (SearchResultsEpisode, error)

GetOnDeck gets the on-deck videos.

func (*Plex) GetPlaylist

func (p *Plex) GetPlaylist(key int) (SearchResultsEpisode, error)

GetPlaylist gets all videos in a playlist.

func (*Plex) GetPlaylists

func (p *Plex) GetPlaylists() (PlaylistMetadata, error)

GetPlaylists retrieves all custom playlists from the Plex server

func (*Plex) GetPlexTokens

func (p *Plex) GetPlexTokens(token string) (DevicesResponse, error)

GetPlexTokens not sure if it works

func (*Plex) GetSections

func (p *Plex) GetSections(machineID string) ([]ServerSections, error)

GetSections of your plex server. This is useful when inviting a user as you can restrict the invited user to a library (i.e. Movie's, TV Shows)

func (*Plex) GetServerInfo

func (p *Plex) GetServerInfo() (BaseAPIResponse, error)

GetServerInfo retrieves base API information from the Plex Media Server.

func (*Plex) GetServers

func (p *Plex) GetServers() ([]PMSDevices, error)

GetServers returns a list of your Plex servers

func (*Plex) GetServersInfo

func (p *Plex) GetServersInfo() (ServerInfo, error)

GetServersInfo returns info about all of your Plex servers

func (*Plex) GetSessions

func (p *Plex) GetSessions() (CurrentSessions, error)

GetSessions of devices currently consuming media

func (*Plex) GetThumbnail

func (p *Plex) GetThumbnail(key, thumbnailID string) (*http.Response, error)

GetThumbnail returns the response of a request to pms thumbnail My ideal use case would be to proxy a request to pms without exposing the plex token

func (*Plex) GetTranscodeSessions

func (p *Plex) GetTranscodeSessions() (TranscodeSessionsResponse, error)

GetTranscodeSessions retrieves a list of all active transcode sessions

func (Plex) GetWebhooks

func (p Plex) GetWebhooks() ([]string, error)

GetWebhooks fetches all webhooks - requires plex pass

func (*Plex) HubSearch

func (p *Plex) HubSearch(title string) (SearchHubContainer, error)

HubSearch your Plex Server for media using hubs (modern search)

func (*Plex) InviteFriend

func (p *Plex) InviteFriend(params InviteFriendParams) error

InviteFriend to access your Plex server. Add restrictions to media or give them full access.

func (*Plex) KillTranscodeSession

func (p *Plex) KillTranscodeSession(sessionKey string) (bool, error)

KillTranscodeSession stops a transcode session

func (Plex) LinkAccount

func (p Plex) LinkAccount(code string) error

LinkAccount allows you to authorize an app via a 4 character pin. returns nil on success

func (Plex) MyAccount

func (p Plex) MyAccount() (UserPlexTV, error)

MyAccount gets account info (i.e. plex pass, servers, username, etc) from plex tv

func (*Plex) OptimizeMedia

func (p *Plex) OptimizeMedia(ratingKey, profile string) error

OptimizeMedia starts a background media optimization job for a specific profile (e.g. mobile, tv)

func (*Plex) PausePlayback

func (p *Plex) PausePlayback(machineID string) error

PausePlayback sends the 'pause' command to a player client.

func (*Plex) RefreshSection

func (p *Plex) RefreshSection(sectionID string) error

RefreshSection triggers a library scan for a specific library section ID.

func (*Plex) RefreshToken

func (p *Plex) RefreshToken(keyPair *KeyPair) error

RefreshToken refreshes the authentication token using device JWT

func (*Plex) RemoveCollectionItem

func (p *Plex) RemoveCollectionItem(collectionID, ratingKey string) error

RemoveCollectionItem removes a media item (by ratingKey) from a manual collection.

func (*Plex) RemoveFriend

func (p *Plex) RemoveFriend(id string) (bool, error)

RemoveFriend from your friend's list which stops access to your Plex server

func (*Plex) RemoveFriendAccessToLibrary

func (p *Plex) RemoveFriendAccessToLibrary(userID, machineID, serverID string) (bool, error)

RemoveFriendAccessToLibrary you can individually revoke access to a library on your server. Such as movies, tv shows, music, etc

func (*Plex) RemoveInvitedFriend

func (p *Plex) RemoveInvitedFriend(inviteID string, isFriend, isServer, isHome bool) (bool, error)

RemoveInvitedFriend cancel pending friend invite

func (*Plex) RemoveLabelFromMedia

func (p *Plex) RemoveLabelFromMedia(mediaType, sectionID, id, label, locked string) (bool, error)

RemoveLabelFromMedia to remove a label from a piece of media Requires a Plex Pass.

func (*Plex) RemovePlaylistItems

func (p *Plex) RemovePlaylistItems(playlistID, ratingKey string) error

RemovePlaylistItems resolves a ratingKey within a playlist and deletes the corresponding item

func (*Plex) ResumePlayback

func (p *Plex) ResumePlayback(machineID string) error

ResumePlayback sends the 'play' command to a player client to resume playback.

func (*Plex) Search

func (p *Plex) Search(title string) (SearchResults, error)

Search your Plex Server for media (legacy substring search)

func (*Plex) SearchPlex

func (p *Plex) SearchPlex(searchTerm string) (SearchHubContainer, error)

SearchPlex searches just like Search, but omits the last 4 results which are not relevant

func (*Plex) SeekToPlayback

func (p *Plex) SeekToPlayback(machineID string, offsetMs int) error

SeekToPlayback sends the 'seekTo' command to jump to a specific offset in milliseconds.

func (*Plex) SetVolumePlayback

func (p *Plex) SetVolumePlayback(machineID string, volume int) error

SetVolumePlayback sends the 'setParameters' command with a volume percentage (0-100).

func (Plex) SetWebhooks

func (p Plex) SetWebhooks(webhooks []string) error

SetWebhooks will set your webhooks to whatever you pass as an argument webhooks with a length of 0 will remove all webhooks

func (*Plex) SkipNextPlayback

func (p *Plex) SkipNextPlayback(machineID string) error

SkipNextPlayback sends the 'skipNext' command to skip to the next item.

func (*Plex) SkipPreviousPlayback

func (p *Plex) SkipPreviousPlayback(machineID string) error

SkipPreviousPlayback sends the 'skipPrevious' command to skip to the previous item.

func (*Plex) StepBackPlayback

func (p *Plex) StepBackPlayback(machineID string) error

StepBackPlayback sends the 'stepBack' command to skip backward.

func (*Plex) StepForwardPlayback

func (p *Plex) StepForwardPlayback(machineID string) error

StepForwardPlayback sends the 'stepForward' command to skip forward.

func (*Plex) StopPlayback

func (p *Plex) StopPlayback(machineID string) error

StopPlayback acts as a remote controller and sends the 'stop' command

func (*Plex) SubscribeToNotifications

func (p *Plex) SubscribeToNotifications(events *NotificationEvents, interrupt <-chan os.Signal, fn func(error))

SubscribeToNotifications connects to your server via websockets listening for events

func (*Plex) TerminateSession

func (p *Plex) TerminateSession(sessionID string, reason string) error

TerminateSession will end a streaming session - plex pass feature

func (*Plex) Test

func (p *Plex) Test() (bool, error)

Test your connection to your Plex Media Server

func (*Plex) UpdateFriendAccess

func (p *Plex) UpdateFriendAccess(userID string, params UpdateFriendParams) (bool, error)

UpdateFriendAccess limit your friends access to your plex server

type PlexRating

type PlexRating struct {
	Image string          `json:"image"`
	Type  string          `json:"type"`
	Value FlexibleFloat64 `json:"value"`
}

PlexRating represents a rating object in the Plex API (found in GetMetadata responses)

type ProgressNotification

type ProgressNotification struct {
	Message string `json:"message"`
}

ProgressNotification ...

type Provider

type Provider struct {
	Key   string `json:"key"`
	Title string `json:"title"`
	Type  string `json:"type"`
}

Provider ...

type ReachabilityNotification

type ReachabilityNotification struct {
	Reachability bool `json:"reachability"`
}

ReachabilityNotification ...

type Role

type Role struct {
	TaggedData
	Role  string `json:"role"`
	Thumb string `json:"thumb"`
}

Role ...

type SearchHubContainer

type SearchHubContainer struct {
	MediaContainer struct {
		Size       int    `json:"size"`
		AllowSync  bool   `json:"allowSync"`
		Identifier string `json:"identifier"`
		Hub        []Hub  `json:"Hub"`
	} `json:"MediaContainer"`
}

SearchHubContainer is the container for search results from /hubs/search

type SearchMediaContainer

type SearchMediaContainer struct {
	MediaContainer
	Provider []Provider
}

SearchMediaContainer ...

type SearchResults

type SearchResults struct {
	MediaContainer SearchMediaContainer `json:"MediaContainer"`
}

SearchResults ...

type SearchResultsEpisode

type SearchResultsEpisode struct {
	MediaContainer MediaContainer `json:"MediaContainer"`
}

SearchResultsEpisode contains metadata about an episode

type SectionIDResponse

type SectionIDResponse struct {
	XMLName           xml.Name `xml:"MediaContainer" json:"-"`
	FriendlyName      string   `xml:"friendlyName,attr" json:"friendlyName"`
	Identifier        string   `xml:"identifier,attr" json:"identifier"`
	MachineIdentifier string   `xml:"machineIdentifier,attr" json:"machineIdentifier"`
	Size              int      `xml:"size,attr" json:"size"`
	Server            []struct {
		Name              string           `xml:"name,attr" json:"name"`
		Address           string           `xml:"address,attr" json:"address"`
		Port              string           `xml:"port,attr" json:"port"`
		Version           string           `xml:"version,attr" json:"version"`
		Scheme            string           `xml:"scheme,attr" json:"scheme"`
		Host              string           `xml:"host,attr" json:"host"`
		LocalAddresses    string           `xml:"localAddresses,attr" json:"localAddresses"`
		MachineIdentifier string           `xml:"machineIdentifier,attr" json:"machineIdentifier"`
		CreatedAt         int              `xml:"createdAt,attr" json:"createdAt"`
		UpdatedAt         int              `xml:"updatedAt,attr" json:"updatedAt"`
		Owned             int              `xml:"owned,attr" json:"owned"`
		Synced            string           `xml:"synced,attr" json:"synced"`
		Section           []ServerSections `xml:"Section" json:"Section"`
	} `xml:"Server" json:"Server"`
}

SectionIDResponse the section id (or library id) of your server useful when inviting a user to the server

type ServerInfo

type ServerInfo struct {
	XMLName           xml.Name `xml:"MediaContainer"`
	FriendlyName      string   `xml:"friendlyName,attr"`
	Identifier        string   `xml:"identifier,attr"`
	MachineIdentifier string   `xml:"machineIdentifier,attr"`
	Size              int      `xml:"size,attr"`
	Server            []struct {
		AccessToken       string `xml:"accessToken,attr"`
		Name              string `xml:"name,attr"`
		Address           string `xml:"address,attr"`
		Port              string `xml:"port,attr"`
		Version           string `xml:"version,attr"`
		Scheme            string `xml:"scheme,attr"`
		Host              string `xml:"host,attr"`
		LocalAddresses    string `xml:"localAddresses,attr"`
		MachineIdentifier string `xml:"machineIdentifier,attr"`
		CreatedAt         string `xml:"createdAt,attr"`
		UpdatedAt         string `xml:"updatedAt,attr"`
		Owned             string `xml:"owned,attr"`
		Synced            string `xml:"synced,attr"`
	} `xml:"Server"`
}

ServerInfo is the result of the https://plex.tv/api/servers endpoint

type ServerSections

type ServerSections struct {
	ID    int    `xml:"id,attr" json:"id"`
	Key   string `xml:"key,attr" json:"key"`
	Type  string `xml:"type,attr" json:"type"`
	Title string `xml:"title,attr" json:"title"`
}

ServerSections contains information of your library sections

type Services

type Services struct {
	Identifier string `json:"identifier"`
	Endpoint   string `json:"endpoint"`
	Token      string `json:"token"`
	Status     string `json:"status"`
}

type Session

type Session struct {
	Bandwidth int    `json:"bandwidth"`
	ID        string `json:"id"`
	Location  string `json:"location"`
}

Session ...

type Setting

type Setting struct {
	Advanced bool   `json:"advanced"`
	Default  string `json:"default"`
	Group    string `json:"group"`
	Hidden   bool   `json:"hidden"`
	ID       string `json:"id"`
	Label    string `json:"label"`
	Summary  string `json:"summary"`
	Type     string `json:"type"`
	Value    int64  `json:"value"`
}

Setting ...

type SignInResponse

type SignInResponse UserPlexTV

SignInResponse response from plex.tv sign in

type StatusNotification

type StatusNotification struct {
	Description      string `json:"description"`
	NotificationName string `json:"notificationName"`
	Title            string `json:"title"`
}

StatusNotification ...

type Stream

type Stream struct {
	AlbumGain          string      `json:"albumGain"`
	AlbumPeak          string      `json:"albumPeak"`
	AlbumRange         string      `json:"albumRange"`
	Anamorphic         bool        `json:"anamorphic"`
	AudioChannelLayout string      `json:"audioChannelLayout"`
	BitDepth           int         `json:"bitDepth"`
	Bitrate            int         `json:"bitrate"`
	BitrateMode        string      `json:"bitrateMode"`
	Cabac              string      `json:"cabac"`
	Channels           int         `json:"channels"`
	ChromaLocation     string      `json:"chromaLocation"`
	ChromaSubsampling  string      `json:"chromaSubsampling"`
	Codec              string      `json:"codec"`
	CodecID            string      `json:"codecID"`
	ColorRange         string      `json:"colorRange"`
	ColorSpace         string      `json:"colorSpace"`
	Default            bool        `json:"default"`
	DisplayTitle       string      `json:"displayTitle"`
	Duration           int         `json:"duration"`
	FrameRate          float64     `json:"frameRate"`
	FrameRateMode      string      `json:"frameRateMode"`
	Gain               string      `json:"gain"`
	HasScalingMatrix   bool        `json:"hasScalingMatrix"`
	Height             int         `json:"height"`
	ID                 json.Number `json:"id"`
	Index              int         `json:"index"`
	Language           string      `json:"language"`
	LanguageCode       string      `json:"languageCode"`
	Level              int         `json:"level"`
	Location           string      `json:"location"`
	Loudness           string      `json:"loudness"`
	Lra                string      `json:"lra"`
	Peak               string      `json:"peak"`
	PixelAspectRatio   string      `json:"pixelAspectRatio"`
	PixelFormat        string      `json:"pixelFormat"`
	Profile            string      `json:"profile"`
	RefFrames          int         `json:"refFrames"`
	SamplingRate       int         `json:"samplingRate"`
	ScanType           string      `json:"scanType"`
	Selected           bool        `json:"selected"`
	StreamIdentifier   string      `json:"streamIdentifier"`
	StreamType         int         `json:"streamType"`
	Width              int         `json:"width"`
}

Stream ...

type TaggedData

type TaggedData struct {
	Tag    string      `json:"tag"`
	Filter string      `json:"filter"`
	ID     json.Number `json:"id"`
}

TaggedData ...

type TimelineEntry

type TimelineEntry struct {
	Identifier    string `json:"identifier"`
	ItemID        int64  `json:"itemID"`
	MetadataState string `json:"metadataState"`
	SectionID     int64  `json:"sectionID"`
	State         int64  `json:"state"`
	Title         string `json:"title"`
	Type          int64  `json:"type"`
	UpdatedAt     int64  `json:"updatedAt"`
}

TimelineEntry ...

type TranscodeSession

type TranscodeSession struct {
	AudioChannels        int64           `json:"audioChannels"`
	AudioCodec           string          `json:"audioCodec"`
	AudioDecision        string          `json:"audioDecision"`
	Complete             bool            `json:"complete"`
	Container            string          `json:"container"`
	Context              string          `json:"context"`
	Duration             int64           `json:"duration"`
	Key                  string          `json:"key"`
	Progress             FlexibleFloat64 `json:"progress"`
	Protocol             string          `json:"protocol"`
	Remaining            int64           `json:"remaining"`
	SourceAudioCodec     string          `json:"sourceAudioCodec"`
	SourceVideoCodec     string          `json:"sourceVideoCodec"`
	Speed                FlexibleFloat64 `json:"speed"`
	Throttled            bool            `json:"throttled"`
	TranscodeHwRequested bool            `json:"transcodeHwRequested"`
	VideoCodec           string          `json:"videoCodec"`
	VideoDecision        string          `json:"videoDecision"`
}

TranscodeSession ...

type TranscodeSessionsResponse

type TranscodeSessionsResponse struct {
	Children []struct {
		ElementType   string  `json:"_elementType"`
		AudioChannels int     `json:"audioChannels"`
		AudioCodec    string  `json:"audioCodec"`
		AudioDecision string  `json:"audioDecision"`
		Container     string  `json:"container"`
		Context       string  `json:"context"`
		Duration      int     `json:"duration"`
		Height        int     `json:"height"`
		Key           string  `json:"key"`
		Progress      float64 `json:"progress"`
		Protocol      string  `json:"protocol"`
		Remaining     int     `json:"remaining"`
		Speed         float64 `json:"speed"`
		Throttled     bool    `json:"throttled"`
		VideoCodec    string  `json:"videoCodec"`
		VideoDecision string  `json:"videoDecision"`
		Width         int     `json:"width"`
	} `json:"_children"`
	ElementType string `json:"_elementType"`
}

TranscodeSessionsResponse is the result for transcode session endpoint /transcode/sessions

type UpdateFriendParams

type UpdateFriendParams struct {
	AllowSync         string
	AllowCameraUpload string
	AllowChannels     string
	FilterMovies      string
	FilterTelevision  string
	FilterMusic       string
	FilterPhotos      string
}

UpdateFriendParams optional parameters to update your friends access to your server

type User

type User struct {
	// ID is an int when signing in to Plex.tv but a string when access own server
	ID                  string `json:"id"`
	UUID                string `json:"uuid"`
	Email               string `json:"email"`
	JoinedAt            string `json:"joined_at"`
	Username            string `json:"username"`
	Thumb               string `json:"thumb"`
	HasPassword         bool   `json:"hasPassword"`
	AuthToken           string `json:"authToken"`
	AuthenticationToken string `json:"authenticationToken"`
	Subscription        struct {
		Active   bool     `json:"active"`
		Status   string   `json:"Active"`
		Plan     string   `json:"lifetime"`
		Features []string `json:"features"`
	} `json:"subscription"`
	Roles struct {
		Roles []string `json:"roles"`
	} `json:"roles"`
	Entitlements []string `json:"entitlements"`
	ConfirmedAt  string   `json:"confirmedAt"`
	ForumID      string   `json:"forumId"`
	RememberMe   bool     `json:"rememberMe"`
	Title        string   `json:"title"`
}

User plex server user. only difference is id is a string

type UserPlexTV

type UserPlexTV struct {
	// ID is an int when signing in to Plex.tv but a string when access own server
	ID                int    `json:"id"`
	UUID              string `json:"uuid"`
	Email             string `json:"email"`
	FriendlyName      string `json:"friendlyName"`
	Locale            string `json:"locale"` // can be null
	Confirmed         bool   `json:"confirmed"`
	EmailOnlyAuth     bool   `json:"emailOnlyAuth"`
	Protected         bool   `json:"protected"`
	MailingListStatus string `json:"mailingListStatus"`
	MailingListActive bool   `json:"mailingListActive"`
	ScrobbleTypes     string `json:"scrobbleTypes"`
	Country           string `json:"country"`
	JoinedAt          string `json:"joined_at"`
	Username          string `json:"username"`
	Thumb             string `json:"thumb"`
	HasPassword       bool   `json:"hasPassword"`
	AuthToken         string `json:"authToken"`
	// AuthenticationToken string `json:"authenticationToken"`
	Subscription struct {
		Active         bool     `json:"active"`
		Status         string   `json:"Active"`
		Plan           string   `json:"lifetime"`       // can be null
		SubscribedAt   string   `json:"subscribedAt"`   // can be null
		PaymentService string   `json:"paymentService"` // can be null
		Features       []string `json:"features"`
	} `json:"subscription"`
	SubscriptionDescription string `json:"subscriptionDescription"` // can be null
	Restricted              bool   `json:"restricted"`
	Anonymous               string `json:"anonymous"` // can be null
	Home                    bool   `json:"home"`
	Guest                   bool   `json:"guest"`
	HomeSize                int64  `json:"homeSize"` // type may be wrong
	HomeAdmin               bool   `json:"homeAdmin"`
	MaxHomeSize             int64  `json:"maxHomeSize"` // type may be wrong
	CertificateVersion      int64  `json:"certificateVersion"`
	RememberExpiresAt       int64  `json:"rememberExpiresAt"`
	Profile                 struct {
		AutoSelectAudio              bool   `json:"autoSelectAudio"`
		DefaultAudioLanguage         string `json:"defaultAudioLanguage"`
		DefaultSubtitleLanguage      string `json:"defaultSubtitleLanguage"`
		AutoSelectSubtitle           int64  `json:"autoSelectSubtitle"`
		DefaultSubtitleAccessibility int64  `json:"defaultSubtitleAccessibility"`
		DefaultSubtitleForced        int64  `json:"defaultSubtitleForced"`
	} `json:"profile"`
	Subscriptions []struct {
		ID       int64  `json:"id"`
		Mode     string `json:"mode"`
		RenewsAt string `json:"renewsAt"` // can be null; not sure of type as I have lifetime membership
		EndsAt   string `json:"endsAt"`   // can be null; not sure of type as I have lifetime membership
		Type     string `json:"type"`
		Transfer string `json:"transfer"` // can be null; not sure of type
		State    string `json:"state"`
	} `json:"subscriptions"`
	PastSubscriptions []struct {
		Billing struct {
			InternalPaymentMethod map[string]interface{} `json:"internalPaymentMethod"`
			PaymentMethodId       string                 `json:"paymentMethodId"` // can be null; not sure of type
		}
		CanConvert    bool   `json:"canConvert"`
		CanDowngrade  bool   `json:"canDowngrade"`
		CanReactivate bool   `json:"canReactivate"`
		CanUpgrade    bool   `json:"canUpgrade"`
		Cancelled     bool   `json:"cancelled"`
		EndsAt        int64  `json:"endsAt"`
		GracePeriod   bool   `json:"gracePeriod"`
		ID            string `json:"id"`   // can be null; not sure of type
		Mode          string `json:"mode"` // can be null; not sure of type
		OnHold        bool   `json:"onHold"`
		RenewsAt      string `json:"renewsAt"` // can be null; not sure of type
		State         string `json:"state"`
		Transfer      string `json:"transfer"` // can be null; not sure of type
		Type          string `json:"type"`
	} `json:"pastSubscriptions"`
	Trials               []string   `json:"trials"`
	Services             []Services `json:"services"`
	AdsConsent           bool       `json:"adsConsent"`           // can be null
	AdsConsentSetAt      int        `json:"adsConsentSetAt"`      // can be null
	AdsConsentReminderAt int        `json:"adsConsentReminderAt"` // can be null
	ExperimentalFeatures bool       `json:"experimentalFeatures"`
	TwoFactorEnabled     bool       `json:"twoFactorEnabled"`
	BackupCodesCreated   bool       `json:"backupCodesCreated"`
	// Roles                struct {
	// 	Roles []string `json:"roles"`
	// } `json:"roles"`
	Entitlements []string `json:"entitlements"`
	// ConfirmedAt  string      `json:"confirmedAt"`
	// ForumID    json.Number `json:"forumId"`
	// RememberMe bool   `json:"rememberMe"`
	Title string `json:"title"`
}

UserPlexTV plex.tv user. should be used when interacting with plex.tv as the id is an int

type Webhook

type Webhook struct {
	Event   string `json:"event"`
	User    bool   `json:"user"`
	Owner   bool   `json:"owner"`
	Account struct {
		ID    int    `json:"id"`
		Thumb string `json:"thumb"`
		Title string `json:"title"`
	} `json:"Account"`
	Server struct {
		Title string `json:"title"`
		UUID  string `json:"uuid"`
	} `json:"Server"`
	Player struct {
		Local         bool   `json:"local"`
		PublicAddress string `json:"PublicAddress"`
		Title         string `json:"title"`
		UUID          string `json:"uuid"`
	} `json:"Player"`
	Metadata struct {
		LibrarySectionType   string `json:"librarySectionType"`
		RatingKey            string `json:"ratingKey"`
		Key                  string `json:"key"`
		ParentRatingKey      string `json:"parentRatingKey"`
		GrandparentRatingKey string `json:"grandparentRatingKey"`
		GUID                 string `json:"guid"`
		LibrarySectionID     int    `json:"librarySectionID"`
		MediaType            string `json:"type"`
		Title                string `json:"title"`
		GrandparentKey       string `json:"grandparentKey"`
		ParentKey            string `json:"parentKey"`
		GrandparentTitle     string `json:"grandparentTitle"`
		ParentTitle          string `json:"parentTitle"`
		Summary              string `json:"summary"`
		Index                int    `json:"index"`
		ParentIndex          int    `json:"parentIndex"`
		RatingCount          int    `json:"ratingCount"`
		Thumb                string `json:"thumb"`
		Art                  string `json:"art"`
		ParentThumb          string `json:"parentThumb"`
		GrandparentThumb     string `json:"grandparentThumb"`
		GrandparentArt       string `json:"grandparentArt"`
		AddedAt              int    `json:"addedAt"`
		UpdatedAt            int    `json:"updatedAt"`
	} `json:"Metadata"`
}

Webhook contains a webhooks information

type WebhookEvents

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

WebhookEvents holds the actions for each webhook events

func NewWebhook

func NewWebhook() *WebhookEvents

NewWebhook inits and returns a webhook event

func (*WebhookEvents) Handler

func (wh *WebhookEvents) Handler(w http.ResponseWriter, r *http.Request)

Handler listens for plex webhooks and executes the corresponding function

func (*WebhookEvents) OnPause

func (wh *WebhookEvents) OnPause(fn func(w Webhook)) error

OnPause executes when the webhook receives a pause event

func (*WebhookEvents) OnPlay

func (wh *WebhookEvents) OnPlay(fn func(w Webhook)) error

OnPlay executes when the webhook receives a play event

func (*WebhookEvents) OnRate

func (wh *WebhookEvents) OnRate(fn func(w Webhook)) error

OnRate executes when the webhook receives a rate event

func (*WebhookEvents) OnResume

func (wh *WebhookEvents) OnResume(fn func(w Webhook)) error

OnResume executes when the webhook receives a resume event

func (*WebhookEvents) OnScrobble

func (wh *WebhookEvents) OnScrobble(fn func(w Webhook)) error

OnScrobble executes when the webhook receives a scrobble event

func (*WebhookEvents) OnStop

func (wh *WebhookEvents) OnStop(fn func(w Webhook)) error

OnStop executes when the webhook receives a stop event

type WebsocketNotification

type WebsocketNotification struct {
	NotificationContainer `json:"NotificationContainer"`
}

WebsocketNotification websocket payload of notifications from a plex media server

Directories

Path Synopsis
cmd
plex-cli command
validation command
example
search command
webhooks command

Jump to

Keyboard shortcuts

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