Base plexapi.base

class plexapi.base.PlexObject(server, data, initpath=None, parent=None)[source]

Bases: object

Base class for all Plex objects.

Parameters:
  • server (PlexServer) – PlexServer this client is connected to (optional)

  • data (ElementTree) – Response from PlexServer used to build this object (optional).

  • initpath (str) – Relative path requested when retrieving specified data (optional).

  • parent (PlexObject) – The parent object that this object is built from (optional).

fetchItems(ekey, cls=None, container_start=None, container_size=None, maxresults=None, **kwargs)[source]

Load the specified key to find and build all items with the specified tag and attrs.

Parameters:
  • ekey (str or List<int>) – API URL path in Plex to fetch items from. If a list of ints is passed in, the key will be translated to /library/metadata/<key1,key2,key3>. This allows fetching multiple items only knowing their key-ids.

  • cls (PlexObject) – If you know the class of the items to be fetched, passing this in will help the parser ensure it only returns those items. By default we convert the xml elements with the best guess PlexObjects based on tag and type attrs.

  • etag (str) – Only fetch items with the specified tag.

  • container_start (None, int) – offset to get a subset of the data

  • container_size (None, int) – How many items in data

  • maxresults (int, optional) – Only return the specified number of results.

  • **kwargs (dict) – Optionally add XML attribute to filter the items. See the details below for more info.

Filtering XML Attributes

Any XML attribute can be filtered when fetching results. Filtering is done before the Python objects are built to help keep things speedy. For example, passing in viewCount=0 will only return matching items where the view count is 0. Note that case matters when specifying attributes. Attributes further down in the XML tree can be filtered by prepending the attribute with each element tag Tag__.

Examples

fetchItem(ekey, viewCount=0)
fetchItem(ekey, contentRating="PG")
fetchItem(ekey, Genre__tag="Animation")
fetchItem(ekey, Media__videoCodec="h265")
fetchItem(ekey, Media__Part__container="mp4)

Note that because some attribute names are already used as arguments to this function, such as tag, you may still reference the attr tag by prepending an underscore. For example, passing in _tag='foobar' will return all items where tag='foobar'.

Using PlexAPI Operators

Optionally, PlexAPI operators can be specified by appending it to the end of the attribute for more complex lookups. For example, passing in viewCount__gte=0 will return all items where viewCount >= 0.

List of Available Operators:

  • __contains: Value contains specified arg.

  • __endswith: Value ends with specified arg.

  • __exact: Value matches specified arg.

  • __exists (bool): Value is or is not present in the attrs.

  • __gt: Value is greater than specified arg.

  • __gte: Value is greater than or equal to specified arg.

  • __icontains: Case insensitive value contains specified arg.

  • __iendswith: Case insensitive value ends with specified arg.

  • __iexact: Case insensitive value matches specified arg.

  • __in: Value is in a specified list or tuple.

  • __iregex: Case insensitive value matches the specified regular expression.

  • __istartswith: Case insensitive value starts with specified arg.

  • __lt: Value is less than specified arg.

  • __lte: Value is less than or equal to specified arg.

  • __regex: Value matches the specified regular expression.

  • __startswith: Value starts with specified arg.

Examples

fetchItem(ekey, viewCount__gte=0)
fetchItem(ekey, Media__container__in=["mp4", "mkv"])
fetchItem(ekey, guid__iregex=r"(imdb://|themoviedb://)")
fetchItem(ekey, Media__Part__file__startswith="D:\Movies")
fetchItem(ekey, cls=None, **kwargs)[source]

Load the specified key to find and build the first item with the specified tag and attrs. If no tag or attrs are specified then the first item in the result set is returned.

Parameters:
  • ekey (str or int) – Path in Plex to fetch items from. If an int is passed in, the key will be translated to /library/metadata/<key>. This allows fetching an item only knowing its key-id.

  • cls (PlexObject) – If you know the class of the items to be fetched, passing this in will help the parser ensure it only returns those items. By default we convert the xml elements with the best guess PlexObjects based on tag and type attrs.

  • etag (str) – Only fetch items with the specified tag.

  • **kwargs (dict) – Optionally add XML attribute to filter the items. See fetchItems() for more details on how this is used.

findItems(data, cls=None, initpath=None, rtag=None, **kwargs)[source]

Load the specified data to find and build all items with the specified tag and attrs. See fetchItem() for more details on how this is used.

findItem(data, cls=None, initpath=None, rtag=None, **kwargs)[source]

Load the specified data to find and build the first items with the specified tag and attrs. See fetchItem() for more details on how this is used.

firstAttr(*attrs)[source]

Return the first attribute in attrs that is not None.

listAttrs(data, attr, rtag=None, **kwargs)[source]

Return a list of values from matching attribute.

reload(key=None, **kwargs)[source]

Reload the data for this object from self.key.

Parameters:
  • key (string, optional) – Override the key to reload.

  • **kwargs (dict) – A dictionary of XML include parameters to exclude or override. All parameters are included by default with the option to override each parameter or disable each parameter individually by setting it to False or 0. See PlexPartialObject for all the available include parameters.

Example

from plexapi.server import PlexServer
plex = PlexServer('http://localhost:32400', token='xxxxxxxxxxxxxxxxxxxx')
movie = plex.library.section('Movies').get('Cars')

# Partial reload of the movie without the `checkFiles` parameter.
# Excluding `checkFiles` will prevent the Plex server from reading the
# file to check if the file still exists and is accessible.
# The movie object will remain as a partial object.
movie.reload(checkFiles=False)
movie.isPartialObject()  # Returns True

# Full reload of the movie with all include parameters.
# The movie object will be a full object.
movie.reload()
movie.isFullObject()  # Returns True
class plexapi.base.PlexPartialObject(server, data, initpath=None, parent=None)[source]

Bases: PlexObject

Not all objects in the Plex listings return the complete list of elements for the object. This object will allow you to assume each object is complete, and if the specified value you request is None it will fetch the full object automatically and update itself.

analyze()[source]

Tell Plex Media Server to performs analysis on it this item to gather information. Analysis includes:

  • Gather Media Properties: All of the media you add to a Library has

    properties that are useful to know–whether it’s a video file, a music track, or one of your photos (container, codec, resolution, etc).

  • Generate Default Artwork: Artwork will automatically be grabbed from a

    video file. A background image will be pulled out as well as a smaller image to be used for poster/thumbnail type purposes.

  • Generate Video Preview Thumbnails: Video preview thumbnails are created,

    if you have that feature enabled. Video preview thumbnails allow graphical seeking in some Apps. It’s also used in the Plex Web App Now Playing screen to show a graphical representation of where playback is. Video preview thumbnails creation is a CPU-intensive process akin to transcoding the file.

  • Generate intro video markers: Detects show intros, exposing the

    ‘Skip Intro’ button in clients.

isFullObject()[source]

Returns True if this is already a full object. A full object means all attributes were populated from the api path representing only this item. For example, the search result for a movie often only contain a portion of the attributes a full object (main url) for that movie would contain.

isPartialObject()[source]

Returns True if this is not a full object.

isLocked(field: str)[source]

Returns True if the specified field is locked, otherwise False.

Parameters:

field (str) – The name of the field.

edit(**kwargs)[source]

Edit an object. Note: This is a low level method and you need to know all the field/tag keys. See EditFieldMixin and EditTagsMixin for individual field and tag editing methods.

Parameters:

kwargs (dict) – Dict of settings to edit.

Example

edits = {
    'type': 1,
    'id': movie.ratingKey,
    'title.value': 'A new title',
    'title.locked': 1,
    'summary.value': 'This is a summary.',
    'summary.locked': 1,
    'collection[0].tag.tag': 'A tag',
    'collection.locked': 1}
}
movie.edit(**edits)
batchEdits()[source]

Enable batch editing mode to save API calls. Must call saveEdits() at the end to save all the edits. See EditFieldMixin and EditTagsMixin for individual field and tag editing methods.

Example

# Batch editing multiple fields and tags in a single API call
Movie.batchEdits()
Movie.editTitle('A New Title').editSummary('A new summary').editTagline('A new tagline') \
    .addCollection('New Collection').removeGenre('Action').addLabel('Favorite')
Movie.saveEdits()
saveEdits()[source]

Save all the batch edits. The object needs to be reloaded manually, if required. See batchEdits() for details.

refresh()[source]

Refreshing a Library or individual item causes the metadata for the item to be refreshed, even if it already has metadata. You can think of refreshing as “update metadata for the requested item even if it already has some”. You should refresh a Library or individual item if:

  • You’ve changed the Library Metadata Agent.

  • You’ve added “Local Media Assets” (such as artwork, theme music, external

    subtitle files, etc.)

  • You want to freshen the item posters, summary, etc.

  • There’s a problem with the poster image that’s been downloaded.

  • Items are missing posters or other downloaded information. This is possible if

    the refresh process is interrupted (the Server is turned off, internet connection dies, etc).

section()[source]

Returns the LibrarySection this item belongs to.

delete()[source]

Delete a media element. This has to be enabled under settings > server > library in plex webui.

history(maxresults=None, mindate=None)[source]

Get Play History for a media item.

Parameters:
  • maxresults (int) – Only return the specified number of results (optional).

  • mindate (datetime) – Min datetime to return results from.

getWebURL(base=None)[source]

Returns the Plex Web URL for a media item.

Parameters:

base (str) – The base URL before the fragment (#!). Default is https://app.plex.tv/desktop.

playQueue(*args, **kwargs)[source]

Returns a new PlayQueue from this media item. See create() for available parameters.

class plexapi.base.Playable[source]

Bases: object

This is a general place to store functions specific to media that is Playable. Things were getting mixed up a bit when dealing with Shows, Season, Artists, Albums which are all not playable.

Variables:
  • playlistItemID (int) – Playlist item ID (only populated for Playlist items).

  • playQueueItemID (int) – PlayQueue item ID (only populated for PlayQueue items).

getStreamURL(**kwargs)[source]

Returns a stream url that may be used by external applications such as VLC.

Parameters:

**kwargs (dict) – optional parameters to manipulate the playback when accessing the stream. A few known parameters include: maxVideoBitrate, videoResolution offset, copyts, protocol, mediaIndex, partIndex, platform.

Raises:

Unsupported – When the item doesn’t support fetching a stream URL.

iterParts()[source]

Iterates over the parts of this media item.

videoStreams()[source]

Returns a list of videoStream objects for all MediaParts.

audioStreams()[source]

Returns a list of AudioStream objects for all MediaParts.

subtitleStreams()[source]

Returns a list of SubtitleStream objects for all MediaParts.

lyricStreams()[source]

Returns a list of LyricStream objects for all MediaParts.

play(client)[source]

Start playback on the specified client.

Parameters:

client (PlexClient) – Client to start playing on.

download(savepath=None, keep_original_name=False, **kwargs)[source]

Downloads the media item to the specified location. Returns a list of filepaths that have been saved to disk.

Parameters:
  • savepath (str) – Defaults to current working dir.

  • keep_original_name (bool) – True to keep the original filename otherwise a friendlier filename is generated. See filenames below.

  • **kwargs (dict) – Additional options passed into getStreamURL() to download a transcoded stream, otherwise the media item will be downloaded as-is and saved to disk.

Filenames

  • Movie: <title> (<year>)

  • Episode: <show title> - s00e00 - <episode title>

  • Track: <artist title> - <album title> - 00 - <track title>

  • Photo: <photoalbum title> - <photo/clip title> or <photo/clip title>

updateProgress(time, state='stopped')[source]

Set the watched progress for this video.

Note that setting the time to 0 will not work. Use markPlayed() or markUnplayed() to achieve that goal.

Parameters:
  • time (int) – milliseconds watched

  • state (string) – state of the video, default ‘stopped’

updateTimeline(time, state='stopped', duration=None)[source]

Set the timeline progress for this video.

Parameters:
  • time (int) – milliseconds watched

  • state (string) – state of the video, default ‘stopped’

  • duration (int) – duration of the item

class plexapi.base.PlexSession[source]

Bases: object

This is a general place to store functions specific to media that is a Plex Session.

Variables:
  • live (bool) – True if this is a live tv session.

  • player (PlexClient) – PlexClient object for the session.

  • session (Session) – Session object for the session if the session is using bandwidth (None otherwise).

  • sessionKey (int) – The session key for the session.

  • transcodeSession (TranscodeSession) – TranscodeSession object if item is being transcoded (None otherwise).

property user

Returns the MyPlexAccount object (for admin) or MyPlexUser object (for users) for this session.

reload()[source]

Reload the data for the session. Note: This will return the object as-is if the session is no longer active.

source()[source]

Return the source media object for the session.

stop(reason='')[source]

Stop playback for the session.

Parameters:

reason (str) – Message displayed to the user for stopping playback.

class plexapi.base.PlexHistory[source]

Bases: object

This is a general place to store functions specific to media that is a Plex history item.

Variables:
  • accountID (int) – The associated SystemAccount ID.

  • deviceID (int) – The associated SystemDevice ID.

  • historyKey (str) – API URL (/status/sessions/history/<historyID>).

  • viewedAt (datetime) – Datetime item was last watched.

source()[source]

Return the source media object for the history entry or None if the media no longer exists on the server.

delete()[source]

Delete the history entry.

class plexapi.base.MediaContainer(server, data, initpath=None, parent=None)[source]

Bases: PlexObject

Represents a single MediaContainer.

Variables:
  • TAG (str) – ‘MediaContainer’

  • allowSync (int) – Sync/Download is allowed/disallowed for feature.

  • augmentationKey (str) – API URL (/library/metadata/augmentations/<augmentationKey>).

  • identifier (str) – “com.plexapp.plugins.library”

  • librarySectionID (int) – LibrarySection ID.

  • librarySectionTitle (str) – LibrarySection title.

  • librarySectionUUID (str) – LibrarySection UUID.

  • mediaTagPrefix (str) – “/system/bundle/media/flags/”

  • mediaTagVersion (int) – Unknown

  • size (int) – The number of items in the hub.