### Install PlexAPI
Source: https://python-plexapi.readthedocs.io/en/latest/introduction
Installs the core PlexAPI library using pip. This is the primary method for getting started with the library.
```bash
pip install plexapi
```
--------------------------------
### Create PlayQueue from Station Key Example
Source: https://python-plexapi.readthedocs.io/en/latest/modules/playqueue
Example demonstrating how to create a PlayQueue from a Plex station key and play it on a client.
```python
from plexapi.playqueue import PlayQueue
# Assuming 'server' is an authenticated PlexServer object
# music = server.library.section("Music")
# artist = music.get("Artist Name")
# station = artist.station()
# key = station.key # Example: "/library/metadata/12855/station/8bd39616-dbdb-459e-b8da-f46d0b170af4?type=10"
# For demonstration, using a placeholder key
server = None # Replace with your PlexServer instance
key = "/library/metadata/12855/station/example-key-string?type=10"
# Create PlayQueue from station key
pq = PlayQueue.fromStationKey(server, key)
# Assuming 'client' is an authenticated PlexClient object
# client = server.clients()[0]
# client.playMedia(pq)
print("PlayQueue created successfully.")
# print(f"PlayQueue items: {pq.items()}") # Uncomment to see items if server/client are configured
```
--------------------------------
### Sync Music Library Example
Source: https://python-plexapi.readthedocs.io/en/latest/modules/library
Example demonstrating how to sync music from a Plex library section to a specified device using plexapi.
```python
from plexapi import myplex
from plexapi.sync import AUDIO_BITRATE_320_KBPS
c = myplex.MyPlexAccount()
target = c.device('Plex Client')
sync_items_wd = c.syncItems(target.clientIdentifier)
srv = c.resource('Server Name').connect()
section = srv.library.section('Music')
section.sync(AUDIO_BITRATE_320_KBPS, client=target, limit=100, sort='addedAt:desc',
title='New music')
```
--------------------------------
### Install PlexAPI with Extras
Source: https://python-plexapi.readthedocs.io/en/latest/introduction
Installs the PlexAPI library along with optional dependencies for specific features, such as the alert module. Use this if you need extended functionality.
```bash
pip install plexapi[alert]
```
--------------------------------
### GDM Discovery Usage Example
Source: https://python-plexapi.readthedocs.io/en/latest/_modules/plexapi/gdm
A simple example demonstrating how to instantiate the GDM class and use its methods to scan for both Plex servers and clients on the network, then print the discovered entries.
```python
def main():
"""Test GDM discovery."""
from pprint import pprint
gdm = GDM()
pprint("Scanning GDM for servers...")
gdm.scan()
pprint(gdm.entries)
pprint("Scanning GDM for clients...")
gdm.scan(scan_for_clients=True)
pprint(gdm.entries)
if __name__ == "__main__":
main()
```
--------------------------------
### Start Alert Listener
Source: https://python-plexapi.readthedocs.io/en/latest/modules/server
Establishes a websocket connection to the Plex Server to receive real-time notifications, such as media scan updates or transcode session changes. Requires the 'websocket-client' library to be installed.
```python
from plexapi.server import PlexServer
# Assuming plex is an authenticated PlexServer object
# plex = PlexServer(baseurl, token)
def handle_message(message):
print(f"Received message: {message}")
def handle_error(error):
print(f"Error occurred: {error}")
try:
listener = plex.startAlertListener(callback=handle_message, callbackError=handle_error)
print("Alert listener started. Waiting for notifications...")
# Keep the script running to listen for alerts
# For a long-running service, you might use a loop or a more robust mechanism
# listener.join() # This would block until the listener stops
except Exception as e:
print(f"Failed to start alert listener: {e}")
print("Ensure 'websocket-client' is installed: pip install websocket-client")
```
```shell
pip install websocket-client
```
--------------------------------
### PlexAPI Configuration File Example
Source: https://python-plexapi.readthedocs.io/en/latest/configuration
An example of the plexapi configuration file (config.ini) showing all possible options for customizing library behavior, authentication, headers, and logging.
```ini
# ~/.config/plexapi/config.ini
[plexapi]
container_size = 50
timeout = 30
[auth]
myplex_username = johndoe
myplex_password = kodi-stinks
server_baseurl = http://127.0.0.1:32400
server_token = XBHSMSJSDJ763JSm
client_baseurl = http://127.0.0.1:32433
client_token = BDFSLCNSNL789FH7
[header]
identifier = 0x485b314307f3L
platorm = Linux
platform_version = 4.4.0-62-generic
product = PlexAPI
version = 3.0.0
[log]
backup_count = 3
format = %(asctime)s %(module)12s:%(lineno)-4s %(levelname)-9s %(message)s
level = INFO
path = ~/.config/plexapi/plexapi.log
rotate_bytes = 512000
show_secrets = false
```
--------------------------------
### Start Alert Listener
Source: https://python-plexapi.readthedocs.io/en/latest/_modules/plexapi/server
Establishes a websocket connection to the Plex Server to receive real-time notifications, such as media scan updates or transcode session changes. Requires 'websocket-client' to be installed.
```python
def startAlertListener(self, callback=None, callbackError=None):
""" Creates a websocket connection to the Plex Server to optionally receive
notifications. These often include messages from Plex about media scans
as well as updates to currently running Transcode Sessions.
Returns a new :class:`~plexapi.alert.AlertListener` object.
Note: ``websocket-client`` must be installed in order to use this feature.
.. code-block:: python
>> pip install websocket-client
Parameters:
callback (func): Callback function to call on received messages.
callbackError (func): Callback function to call on errors.
Raises:
:exc:`~plexapi.exception.Unsupported`: Websocket-client not installed.
"""
notifier = AlertListener(self, callback, callbackError)
notifier.start()
return notifier
```
--------------------------------
### PlexAPI GUID Lookup Examples
Source: https://python-plexapi.readthedocs.io/en/latest/modules/library
Demonstrates how to retrieve items from a Plex library using various global identifiers (GUIDs) like Plex, IMDB, TMDB, and TVDB. It also shows an efficient method for creating a lookup dictionary for faster access to library items based on their GUIDs.
```python
from plexapi.server import PlexServer
# Assuming you have your Plex server details
# PLEX_URL = 'YOUR_PLEX_URL'
# PLEX_TOKEN = 'YOUR_PLEX_TOKEN'
# plex = PlexServer(PLEX_URL, PLEX_TOKEN)
# Example usage with library.getGuid
# result1 = library.getGuid('plex://show/5d9c086c46115600200aa2fe')
# result2 = library.getGuid('imdb://tt0944947')
# result3 = library.getGuid('tmdb://1399')
# result4 = library.getGuid('tvdb://121361')
# Alternatively, create your own guid lookup dictionary for faster performance
# guidLookup = {}
# for item in library.all():
# guidLookup[item.guid] = item
# guidLookup.update({guid.id: item for guid in item.guids})
# result1 = guidLookup['plex://show/5d9c086c46115600200aa2fe']
# result2 = guidLookup['imdb://tt0944947']
# result3 = guidLookup['tmdb://1399']
# result4 = guidLookup['tvdb://121361']
```
--------------------------------
### PlexAPI Configuration File Example
Source: https://python-plexapi.readthedocs.io/en/latest/_sources/configuration.rst
An example of the plexapi configuration file (config.ini) showing all possible options across different sections like [plexapi], [auth], [header], and [log]. This file allows customization of default behaviors, authentication details, and logging settings.
```ini
# ~/.config/plexapi/config.ini
[plexapi]
container_size = 50
timeout = 30
[auth]
myplex_username = johndoe
myplex_password = kodi-stinks
server_baseurl = http://127.0.0.1:32400
server_token = XBHSMSJSDJ763JSm
client_baseurl = http://127.0.0.1:32433
client_token = BDFSLCNSNL789FH7
[header]
identifier = 0x485b314307f3L
platorm = Linux
platform_version = 4.4.0-62-generic
product = PlexAPI
version = 3.0.0
[log]
backup_count = 3
format = %(asctime)s %(module)12s:%(lineno)-4s %(levelname)-9s %(message)s
level = INFO
path = ~/.config/plexapi/plexapi.log
rotate_bytes = 512000
show_secrets = false
```
--------------------------------
### plexapi.audio.Artist Methods and Properties
Source: https://python-plexapi.readthedocs.io/en/latest/modules/audio
Documentation for the Artist class in plexapi.audio, including methods to retrieve tracks, download music, get popular tracks, create radio stations, and access metadata directory. It also details the alias for the get method.
```APIDOC
plexapi.audio.Artist.tracks(*kwargs)
Returns a list of [`Track`](#plexapi.audio.Track "plexapi.audio.Track") objects by the artist.
plexapi.audio.Artist.get(title=None, album=None, track=None)
Alias of [`track()`](#plexapi.audio.Artist.track "plexapi.audio.Artist.track").
plexapi.audio.Artist.download(savepath=None, keep_original_name=False, subfolders=False, **kwargs)
Download all tracks from the artist. See [`download()`](base.html#plexapi.base.Playable.download "plexapi.base.Playable.download") for details.
Parameters:
savepath (str): Defaults to current working dir.
keep_original_name (bool): True to keep the original filename otherwise a friendlier filename is generated.
subfolders (bool): True to separate tracks in to album folders.
**kwargs: Additional options passed into `getStreamURL()`.
plexapi.audio.Artist.popularTracks()
Returns a list of [`Track`](#plexapi.audio.Track "plexapi.audio.Track") popular tracks by the artist.
plexapi.audio.Artist.station()
Returns a [`Playlist`](playlist.html#plexapi.playlist.Playlist "plexapi.playlist.Playlist") artist radio station or None.
plexapi.audio.Artist.metadataDirectory (property)
Returns the Plex Media Server data directory where the metadata is stored.
```
--------------------------------
### PlexAPI Movie Reloading Examples
Source: https://python-plexapi.readthedocs.io/en/latest/_modules/plexapi/base
Demonstrates how to reload movie objects in PlexAPI. Includes examples for partial reloads, full reloads with default parameters, and full reloads with additional parameters like `checkFiles` to verify file accessibility.
```python
movie = plex.library.section('Movies').get('Cars')
movie.isPartialObject() # Returns True
# Partial reload of the movie without a default include parameter.
# The movie object will remain as a partial object.
movie.reload(includeMarkers=False)
movie.isPartialObject() # Returns True
# Full reload of the movie with all default include parameters.
# The movie object will be a full object.
movie.reload()
movie.isFullObject() # Returns True
# Full reload of the movie with all default and extra include parameter.
# Including `checkFiles` will tell the Plex server to check if the file
# still exists and is accessible.
# The movie object will be a full object.
movie.reload(checkFiles=True)
movie.isFullObject() # Returns True
```
--------------------------------
### Get Media GUIDs
Source: https://python-plexapi.readthedocs.io/en/latest/_modules/plexapi/library
Retrieves a list of Global Unique Identifiers (GUIDs) for a media item. This property is optimized with cached data.
```python
@cached_data_property
def guids(self):
return self.findItems(self._data, media.Guid)
```
--------------------------------
### Get Media Item by GUID
Source: https://python-plexapi.readthedocs.io/en/latest/_modules/plexapi/library
Retrieves a media item using its external identifier (e.g., Plex, IMDB, TMDB, TVDB GUID). This method is primarily for agents like Plex Movie and Plex TV Series. It handles different GUID formats and raises `NotFound` if the GUID is not found.
```python
def getGuid(self, guid):
""" Returns the media item with the specified external Plex, IMDB, TMDB, or TVDB ID.
Note: Only available for the Plex Movie and Plex TV Series agents.
Parameters:
guid (str): The external guid of the item to return.
Examples: Plex ``plex://show/5d9c086c46115600200aa2fe``
IMDB ``imdb://tt0944947``, TMDB ``tmdb://1399``, TVDB ``tvdb://121361``.
Raises:
:exc:`~plexapi.exceptions.NotFound`: The guid is not found in the library.
Example:
.. code-block:: python
result1 = library.getGuid('plex://show/5d9c086c46115600200aa2fe')
result2 = library.getGuid('imdb://tt0944947')
result3 = library.getGuid('tmdb://1399')
result4 = library.getGuid('tvdb://121361')
# Alternatively, create your own guid lookup dictionary for faster performance
guidLookup = {}
for item in library.all():
guidLookup[item.guid] = item
guidLookup.update({guid.id: item for guid in item.guids})
result1 = guidLookup['plex://show/5d9c086c46115600200aa2fe']
result2 = guidLookup['imdb://tt0944947']
result3 = guidLookup['tmdb://1399']
result4 = guidLookup['tvdb://121361']
"""
try:
if guid.startswith('plex://'):
result = self.search(guid=guid)[0]
return result
else:
dummy = self.search(maxresults=1)[0]
match = dummy.matches(agent=self.agent, title=guid.replace('://', '-'))
return self.search(guid=match[0].guid)[0]
except IndexError:
raise NotFound(f"Guid '{guid}' is not found in the library") from None
```
--------------------------------
### Get Metadata Directory Path
Source: https://python-plexapi.readthedocs.io/en/latest/_modules/plexapi/video
Returns the file system path on the Plex Media Server where the metadata for this item is stored. It constructs the path using a SHA1 hash of the item's GUID.
```Python
@property
def metadataDirectory(self):
""" Returns the Plex Media Server data directory where the metadata is stored. """
guid_hash = utils.sha1hash(self.guid)
return str(Path('Metadata') / 'Movies' / guid_hash[0] / f'{guid_hash[1:]}.bundle')
```
--------------------------------
### PlexServer Class Methods and Properties
Source: https://python-plexapi.readthedocs.io/en/latest/modules/server
Provides comprehensive documentation for the PlexServer class, including its properties like library and settings, and methods for identity, account management, claiming/unclaiming servers, retrieving activities, agents, creating tokens, and switching users. It details parameters, return types, and usage examples where available.
```APIDOC
PlexServer Properties:
* **version** (*str*): Current Plex version (ex: 1.3.2.3112-1751929)
* **voiceSearch** (*bool*): True if voice search is enabled.
* **_baseurl** (*str*): HTTP address of the client.
* **_token** (*str*): Token used to access this client.
* **_session** (*obj*): Requests session object used to access this client.
* **library**: Library to browse or search your media.
* **settings**: Returns a list of all server settings.
* **activities**: Returns all current PMS activities.
PlexServer Methods:
* **identity()**: Returns the Plex server identity.
* **account()**: Returns the Account object this server belongs to.
* **claim(account)**:
Claim the Plex server using a MyPlexAccount. This will only work with an unclaimed server on localhost or the same subnet.
Parameters:
account ([`MyPlexAccount`]): The account used to claim the server.
* **unclaim()**: Unclaim the Plex server. This will remove the server from your MyPlexAccount.
* **agents(mediaType=None)**:
Returns a list of Agent objects this server has available.
Parameters:
mediaType (*str*, optional): Filter agents by media type.
* **createToken(type='delegation', scope='all')**: Create a temp access token for the server.
Parameters:
type (*str*, optional): The type of token to create (default: 'delegation').
scope (*str*, optional): The scope of the token (default: 'all').
* **switchUser(user, session=None, timeout=None)**:
Returns a new PlexServer object logged in as the given username. Only the admin account can switch to other users.
Parameters:
user ([`MyPlexUser`] or str): MyPlexUser object, username, email, or user id of the user to log in to the server.
session (*requests.Session*, optional): Use your own session object to cache http responses.
timeout (*int*, optional): Timeout in seconds on initial connection to the server.
Example:
```python
from plexapi.server import PlexServer
plex = PlexServer('http://plexserver:32400', token='2ffLuB84dqLswk9skLos')
userPlex = plex.switchUser("Username")
```
* **systemAccounts()**: Returns a list of SystemAccount objects this server contains.
* **systemAccount(accountID)**:
Returns the SystemAccount object for the specified account ID.
Parameters:
accountID (*int*): The SystemAccount ID.
* **systemDevices()**: Returns a list of system devices associated with the server.
```
--------------------------------
### Get Metadata Directory Path
Source: https://python-plexapi.readthedocs.io/en/latest/_modules/plexapi/collection
Retrieves the server's data directory path where metadata for a specific item is stored. It constructs the path using a SHA1 hash of the item's GUID.
```python
@property
def metadataDirectory(self):
""" Returns the Plex Media Server data directory where the metadata is stored. """
guid_hash = utils.sha1hash(self.guid)
return str(Path('Metadata') / 'Collections' / guid_hash[0] / f'{guid_hash[1:]}.bundle')
```
--------------------------------
### List Filter Choices Example
Source: https://python-plexapi.readthedocs.io/en/latest/_modules/plexapi/library
Demonstrates how to retrieve and display available choices for a specific filter field within a Plex library. It shows how to use `listFilterChoices` to get filter options and extract their titles.
```python
field = 'genre' # Available filter field from listFilters()
availableChoices = [f.title for f in library.listFilterChoices(field)]
print(f"Available choices for {field}:", availableChoices)
```
--------------------------------
### Create Playlist Methods
Source: https://python-plexapi.readthedocs.io/en/latest/_modules/plexapi/playlist
Handles the creation of playlists, supporting creation from M3U files, smart playlists, or by providing a list of items. It includes logic to prevent creating smart playlists with items and raises a BadRequest for invalid configurations.
```python
def create(cls, server, title, section=None, m3ufilepath=None, smart=False, items=None, limit=None, libtype=None, sort=None, filters=None, **kwargs):
""" Create a new playlist.
Parameters:
server (:class:`~plexapi.server.PlexServer`): Plex server to connect to.
title (str): Title of the playlist.
section (str): Name of the library section to create the playlist in.
m3ufilepath (str): Path to an M3U file to import.
smart (bool): Create a smart playlist.
items (list): List of media items to add to the playlist.
limit (int): Limit for smart playlists.
libtype (str): Library type for smart playlists.
sort (str): Sort criteria for smart playlists.
filters (dict): Filter criteria for smart playlists.
Returns:
:class:`~plexapi.playlist.Playlist`: A new instance of the created Playlist.
"""
if m3ufilepath:
return cls._createFromM3U(server, title, section, m3ufilepath)
elif smart:
if items:
raise BadRequest('Cannot create a smart playlist with items.')
return cls._createSmart(server, title, section, limit, libtype, sort, filters, **kwargs)
else:
return cls._create(server, title, items)
```
--------------------------------
### PlexServer Class Documentation
Source: https://python-plexapi.readthedocs.io/en/latest/_modules/plexapi/server
Documentation for the PlexServer class, the main entry point for interacting with a Plex Media Server. It covers initialization parameters like baseurl and token, and lists various server attributes such as friendlyName, version, and transcoding status.
```APIDOC
PlexServer(baseurl='http://localhost:32400', token=None, session=None, timeout=None)
This is the main entry point to interacting with a Plex server. It allows you to
list connected clients, browse your library sections and perform actions such as
emptying trash. If you do not know the auth token required to access your Plex
server, or simply want to access your server with your username and password,
you can also create an PlexServer instance from :class:`~plexapi.myplex.MyPlexAccount`.
Parameters:
baseurl (str): Base url for to access the Plex Media Server (default: 'http://localhost:32400').
token (str): Required Plex authentication token to access the server.
session (requests.Session, optional): Use your own session object if you want to
cache the http responses from the server.
timeout (int, optional): Timeout in seconds on initial connection to the server
(default config.TIMEOUT).
Attributes:
allowCameraUpload (bool): True if server allows camera upload.
allowChannelAccess (bool): True if server allows channel access (iTunes?).
allowMediaDeletion (bool): True is server allows media to be deleted.
allowSharing (bool): True is server allows sharing.
allowSync (bool): True is server allows sync.
backgroundProcessing (bool): Unknown
certificate (bool): True if server has an HTTPS certificate.
companionProxy (bool): Unknown
diagnostics (bool): Unknown
eventStream (bool): Unknown
friendlyName (str): Human friendly name for this server.
hubSearch (bool): True if `Hub Search `_ is enabled. I believe this
is enabled for everyone
machineIdentifier (str): Unique ID for this server (looks like an md5).
multiuser (bool): True if `multiusers `_ are enabled.
myPlex (bool): Unknown (True if logged into myPlex?).
myPlexMappingState (str): Unknown (ex: mapped).
myPlexSigninState (str): Unknown (ex: ok).
myPlexSubscription (bool): True if you have a myPlex subscription.
myPlexUsername (str): Email address if signed into myPlex (user@example.com)
ownerFeatures (list): List of features allowed by the server owner. This may be based
on your PlexPass subscription. Features include: camera_upload, cloudsync,
content_filter, dvr, hardware_transcoding, home, lyrics, music_videos, pass,
photo_autotags, premium_music_metadata, session_bandwidth_restrictions, sync,
trailers, webhooks (and maybe more).
photoAutoTag (bool): True if photo `auto-tagging `_ is enabled.
platform (str): Platform the server is hosted on (ex: Linux)
platformVersion (str): Platform version (ex: '6.1 (Build 7601)', '4.4.0-59-generic').
pluginHost (bool): Unknown
readOnlyLibraries (bool): Unknown
requestParametersInCookie (bool): Unknown
streamingBrainVersion (bool): Current `Streaming Brain `_ version.
sync (bool): True if `syncing to a device `_ is enabled.
transcoderActiveVideoSessions (int): Number of active video transcoding sessions.
transcoderAudio (bool): True if audio transcoding audio is available.
transcoderLyrics (bool): True if audio transcoding lyrics is available.
transcoderPhoto (bool): True if audio transcoding photos is available.
transcoderSubtitles (bool): True if audio transcoding subtitles is available.
transcoderVideo (bool): True if audio transcoding video is available.
transcoderVideoBitrates (bool): List of video bitrates.
transcoderVideoQualities (bool): List of video qualities.
transcoderVideoResolutions (bool): List of video resolutions.
updatedAt (int): Datetime the server was updated.
updater (bool): Unknown
version (str): Current Plex version (ex: 1.3.2.3112-1751929)
```
--------------------------------
### Get Metadata Directory Path
Source: https://python-plexapi.readthedocs.io/en/latest/_modules/plexapi/video
Calculates and returns the file system path where the Plex Media Server stores metadata for the show. It uses a SHA1 hash of the show's GUID to construct the path.
```python
@property
def metadataDirectory(self):
""" Returns the Plex Media Server data directory where the metadata is stored. """
guid_hash = utils.sha1hash(self.guid)
return str(Path('Metadata') / 'TV Shows' / guid_hash[0] / f'{guid_hash[1:]}.bundle')
```
--------------------------------
### Get Metadata Directory Path
Source: https://python-plexapi.readthedocs.io/en/latest/_modules/plexapi/photo
Returns the file system path where Plex Media Server stores metadata for a given item. It calculates a hash from the item's parent GUID to construct a unique directory path within the Plex metadata structure. This is primarily for internal use or advanced debugging.
```python
@property
def metadataDirectory(self):
""" Returns the Plex Media Server data directory where the metadata is stored. """
guid_hash = utils.sha1hash(self.parentGuid)
return str(Path('Metadata') / 'Photos' / guid_hash[0] / f'{guid_hash[1:]}.bundle')
```
--------------------------------
### MyPlexAccount Parameters and Variables
Source: https://python-plexapi.readthedocs.io/en/latest/modules/server
Documentation for the MyPlexAccount object, detailing its parameters for initialization and its available variables.
```APIDOC
MyPlexAccount
Parameters:
server (PlexServer): PlexServer this account is connected to (optional)
data (ElementTree): Response from PlexServer used to build this object (optional).
Variables:
authToken (str): Plex authentication token to access the server.
mappingError (str): Unknown
mappingErrorMessage (str): Unknown
mappingState (str): Unknown
privateAddress (str): Local IP address of the Plex server.
privatePort (str): Local port of the Plex server.
publicAddress (str): Public IP address of the Plex server.
publicPort (str): Public port of the Plex server.
signInState (str): Signin state for this account (ex: ok).
subscriptionActive (str): True if the account subscription is active.
subscriptionFeatures (str): List of features allowed by the server for this account. This may be based on your PlexPass subscription. Features include: camera_upload, cloudsync, content_filter, dvr, hardware_transcoding, home, lyrics, music_videos, pass, photo_autotags, premium_music_metadata, session_bandwidth_restrictions, sync, trailers, webhooks’ (and maybe more).
subscriptionState (str): ‘Active’ if this subscription is active.
username (str): Plex account username (user@example.com).
```
--------------------------------
### Define Guid Class
Source: https://python-plexapi.readthedocs.io/en/latest/_modules/plexapi/media
Represents a single Guid media tag. It inherits from PlexObject and stores the unique identifier (GUID) for external metadata sources.
```python
@utils.registerPlexObject
class Guid(PlexObject):
""" Represents a single Guid media tag.
Attributes:
TAG (str): 'Guid'
id (id): The guid for external metadata sources (e.g. IMDB, TMDB, TVDB, MBID).
"""
TAG = 'Guid'
def _loadData(self, data):
""" Load attribute values from Plex XML response. """
self.id = data.attrib.get('id')
```
--------------------------------
### PlexClient Navigation Commands
Source: https://python-plexapi.readthedocs.io/en/latest/modules/client
Provides methods for navigating the Plex client interface, including moving selections, going back, returning to home, and interacting with menus.
```APIDOC
contextMenu()
: Open the context menu on the client.
goBack()
: Navigate back one position.
goToHome()
: Go directly to the home screen.
goToMusic()
: Go directly to the playing music panel.
moveDown()
: Move selection down a position.
moveLeft()
: Move selection left a position.
moveRight()
: Move selection right a position.
moveUp()
: Move selection up a position.
nextLetter()
: Jump to next letter in the alphabet.
pageDown()
: Move selection down a full page.
pageUp()
: Move selection up a full page.
previousLetter()
: Jump to previous letter in the alphabet.
select()
: Select element at the current position.
toggleOSD()
: Toggle the on screen display during playback.
```
--------------------------------
### LibraryMediaTag: Guid
Source: https://python-plexapi.readthedocs.io/en/latest/_modules/plexapi/library
Defines the Guid class, inheriting from LibraryMediaTag. This class represents a media tag for a Globally Unique Identifier (GUID). It is registered using the @utils.registerPlexObject decorator and has a TAGTYPE of 314.
```python
@utils.registerPlexObject
class Guid(LibraryMediaTag):
""" Represents a single Guid library media tag.
Attributes:
TAGTYPE (int): 314
"""
TAGTYPE = 314
```
--------------------------------
### Unified Playlist Creation (plexapi)
Source: https://python-plexapi.readthedocs.io/en/latest/_modules/plexapi/playlist
A unified method to create playlists, acting as a dispatcher for regular, smart, or M3U-based playlist creation based on provided arguments. It handles various parameters for customization and includes error handling for invalid operations.
```APIDOC
create(server, title, section=None, items=None, smart=False, limit=None,
libtype=None, sort=None, filters=None, m3ufilepath=None, **kwargs)
Creates a playlist on the Plex server.
Parameters:
server (:class:`~plexapi.server.PlexServer`): The Plex server instance.
title (str): The desired title for the playlist.
section (:class:`~plexapi.library.LibrarySection`, str, optional): Required for smart playlists and M3U imports. Specifies the library section.
items (List, optional): For regular playlists, a list of media objects (e.g., :class:`~plexapi.audio.Audio`, :class:`~plexapi.video.Video`) to include.
smart (bool, optional): If True, creates a smart playlist. Defaults to False.
limit (int, optional): For smart playlists, the maximum number of items to include.
libtype (str, optional): For smart playlists, filters content by type (e.g., 'movie', 'episode').
sort (str or list, optional): For smart playlists, defines sorting criteria (e.g., 'title:asc').
filters (dict, optional): For smart playlists, a dictionary of advanced filters.
m3ufilepath (str, optional): For music playlists, the file path to an M3U file for import.
**kwargs (dict, optional): Additional custom filters for smart playlists.
Raises:
:class:`plexapi.exceptions.BadRequest`: If no items are provided for a regular playlist.
:class:`plexapi.exceptions.BadRequest`: If media types are mixed within a playlist.
:class:`plexapi.exceptions.BadRequest`: If attempting to import M3U into a non-music library.
:class:`plexapi.exceptions.BadRequest`: If M3U import fails.
Returns:
:class:`~plexapi.playlist.Playlist`: The newly created playlist object.
```
--------------------------------
### Sync Plex Item with Policy and Media Settings
Source: https://python-plexapi.readthedocs.io/en/latest/_modules/plexapi/photo
This snippet demonstrates how to create and sync a Plex item with specific policies and media settings. It prepares a sync item with location, policy, and media settings before initiating the sync process with the Plex server. Dependencies include `plexapi.server.PlexServer`, `plexapi.sync.Policy`, and `plexapi.sync.MediaSettings`.
```python
sync_item.location = f'library://{section.uuid}/item/{quote_plus(self.key)}'
sync_item.policy = Policy.create(limit)
sync_item.mediaSettings = MediaSettings.createPhoto(resolution)
return myplex.sync(sync_item, client=client, clientId=clientId)
```
--------------------------------
### Plex Server Update Management
Source: https://python-plexapi.readthedocs.io/en/latest/_modules/plexapi/server
Provides methods to check for, determine installability of, and install updates for the Plex Media Server. It includes checking the latest version, verifying automatic installation capabilities, and initiating the update process.
```APIDOC
checkForUpdate(force: bool = True, download: bool = False)
Checks for new Plex Media Server releases.
Parameters:
force (bool): Forces the server to check for new releases. Defaults to True.
download (bool): If True, downloads the update if available. Defaults to False.
Returns:
plexapi.server.Release: An object containing release information if an update is available, otherwise None.
isLatest()
Determines if the installed Plex Media Server version is the latest available.
Returns:
bool: True if the installed version is the latest, False otherwise.
canInstallUpdate()
Checks if the newest Plex Media Server version can be installed automatically.
This depends on the operating system (e.g., Windows and Mac can, Docker and NAS devices cannot).
Returns:
bool: True if automatic installation is supported, False otherwise.
installUpdate()
Initiates the automatic installation of the newest Plex Media Server version.
Note: This method might require user interaction via a GUI in some environments.
Returns:
The result of the query to apply the update, or None if no update is available or applicable.
```
--------------------------------
### Run PlexAPI Tests (Docker)
Source: https://python-plexapi.readthedocs.io/en/latest/introduction
Instructions for running PlexAPI tests using a Dockerized Plex Media Server instance. Requires setting up a shared user and providing necessary environment variables for authentication.
```bash
tools/plex-boostraptest.py
# Environment variable SHARED_USERNAME must be set
```
--------------------------------
### PlexServer Class and Constructor
Source: https://python-plexapi.readthedocs.io/en/latest/modules/server
Documentation for the PlexServer class, including its constructor parameters and instance variables. This class is the primary interface for connecting to and managing a Plex Media Server, allowing access to server details and features.
```APIDOC
plexapi.server.PlexServer
__init__(baseurl=None, token=None, session=None, timeout=None)
Parameters:
baseurl (str): Base url for to access the Plex Media Server (default: ‘http://localhost:32400’).
token (str): Required Plex authentication token to access the server.
session (requests.Session, optional): Use your own session object if you want to cache the http responses from the server.
timeout (int, optional): Timeout in seconds on initial connection to the server (default config.TIMEOUT).
Variables:
allowCameraUpload (bool): True if server allows camera upload.
allowChannelAccess (bool): True if server allows channel access (iTunes?).
allowMediaDeletion (bool): True is server allows media to be deleted.
allowSharing (bool): True is server allows sharing.
allowSync (bool): True if server allows sync.
backgroundProcessing (bool): Unknown
certificate (bool): True if server has an HTTPS certificate.
companionProxy (bool): Unknown
diagnostics (bool): Unknown
eventStream (bool): Unknown
friendlyName (str): Human friendly name for this server.
hubSearch (bool): True if [Hub Search](https://www.plex.tv/blog/seek-plex-shall-find-leveling-web-app/) is enabled.
machineIdentifier (str): Unique ID for this server (looks like an md5).
multiuser (bool): True if [multiusers](https://support.plex.tv/hc/en-us/articles/200250367-Multi-User-Support) are enabled.
myPlex (bool): Unknown (True if logged into myPlex?).
myPlexMappingState (str): Unknown (ex: mapped).
myPlexSigninState (str): Unknown (ex: ok).
myPlexSubscription (bool): True if you have a myPlex subscription.
myPlexUsername (str): Email address if signed into myPlex (user@example.com).
ownerFeatures (list): List of features allowed by the server owner. This may be based on your PlexPass subscription.
photoAutoTag (bool): True if photo [auto-tagging](https://support.plex.tv/hc/en-us/articles/234976627-Auto-Tagging-of-Photos) is enabled.
platform (str): Platform the server is hosted on (ex: Linux).
platformVersion (str): Platform version (ex: ‘6.1 (Build 7601)’, ‘4.4.0-59-generic’).
pluginHost (bool): Unknown
readOnlyLibraries (bool): Unknown
requestParametersInCookie (bool): Unknown
streamingBrainVersion (bool): Current [Streaming Brain](https://www.plex.tv/blog/mcstreamy-brain-take-world-two-easy-steps/) version.
sync (bool): True if [syncing to a device](https://support.plex.tv/hc/en-us/articles/201053678-Sync-Media-to-a-Device) is enabled.
transcoderActiveVideoSessions (int): Number of active video transcoding sessions.
transcoderAudio (bool): True if audio transcoding audio is available.
transcoderLyrics (bool): True if audio transcoding lyrics is available.
transcoderPhoto (bool): True if audio transcoding photos is available.
transcoderSubtitles (bool): True if audio transcoding subtitles is available.
transcoderVideo (bool): True if audio transcoding video is available.
transcoderVideoBitrates (bool): List of video bitrates.
transcoderVideoQualities (bool): List of video qualities.
transcoderVideoResolutions (bool): List of video resolutions.
updatedAt (int): Datetime the server was updated.
updater (bool): Unknown
```
--------------------------------
### Playlist: item and get
Source: https://python-plexapi.readthedocs.io/en/latest/_modules/plexapi/playlist
Finds and returns a playlist item by its title (case-insensitive). The 'get' method is an alias for this functionality. Raises NotFound if the item is not found.
```python
[docs]
def item(self, title):
""" Returns the item in the playlist that matches the specified title.
Parameters:
title (str): Title of the item to return.
Raises:
:class:`plexapi.exceptions.NotFound`: When the item is not found in the playlist.
"""
for item in self.items():
if item.title.lower() == title.lower():
return item
raise NotFound(f'Item with title "{title}" not found in the playlist')
[docs]
def get(self, title):
""" Alias to :func:`~plexapi.playlist.Playlist.item`. """
return self.item(title)
```
--------------------------------
### MyPlexAccount Initialization
Source: https://python-plexapi.readthedocs.io/en/latest/_modules/plexapi/myplex
Initializes a MyPlexAccount object, handling authentication via token, username/password, or a verification code. It sets up the session and performs the initial sign-in process.
```python
def __init__(self, username=None, password=None, token=None, session=None, timeout=None, code=None, remember=True):
self._token = logfilter.add_secret(token or CONFIG.get('auth.server_token'))
self._session = session or requests.Session()
self._timeout = timeout or TIMEOUT
self._sonos_cache = []
self._sonos_cache_timestamp = 0
data, initpath = self._signin(username, password, code, remember, timeout)
super(MyPlexAccount, self).__init__(self, data, initpath)
```
--------------------------------
### Get Single Clip
Source: https://python-plexapi.readthedocs.io/en/latest/_modules/plexapi/photo
Retrieves a specific clip from a Plex album by its title. It constructs the API key and uses fetchItem to get the clip object.
```python
def clip(self, title):
""" Returns the :class:`~plexapi.video.Clip` that matches the specified title.
Parameters:
title (str): Title of the clip to return.
"""
key = f'{self.key}/children'
return self.fetchItem(key, video.Clip, title__iexact=title)
```
--------------------------------
### Get Albums from Library Section
Source: https://python-plexapi.readthedocs.io/en/latest/_modules/plexapi/library
Retrieves a list of Album objects from the current library section. It constructs the API key and uses the fetchItems method to get the data.
```python
def albums(self):
""" Returns a list of :class:`~plexapi.audio.Album` objects in this section. """
key = f'/library/sections/{self.key}/albums'
return self.fetchItems(key)
```
--------------------------------
### Create Plex Playlists
Source: https://python-plexapi.readthedocs.io/en/latest/modules/server
Demonstrates how to create various types of playlists within Plex Media Server using the plexapi library. Supports regular playlists from media items, smart playlists with custom filters and sorting, and music playlists from m3u files.
```python
# Create a regular playlist
episodes = plex.library.section("TV Shows").get("Game of Thrones").episodes()
playlist = plex.createPlaylist(
title="GoT Episodes",
items=episodes
)
# Create a smart playlist
playlist = plex.createPlaylist(
title="Top 10 Unwatched Movies",
section="Movies",
smart=True,
limit=10,
sort="audienceRating:desc",
filters={"audienceRating>>": 8.0, "unwatched": True}
)
# Create a music playlist from an m3u file
playlist = plex.createPlaylist(
title="Favorite Tracks",
section="Music",
m3ufilepath="/path/to/playlist.m3u"
)
```
--------------------------------
### Create Plex Home User and Share Libraries
Source: https://python-plexapi.readthedocs.io/en/latest/_modules/plexapi/myplex
Creates a new Plex Home user and shares specified library sections with them. It allows configuration of sync, camera upload, channel access, and content filtering based on rating or labels. The function returns results from user creation and library assignment API calls.
```python
def createHomeUser(self, user, server, sections=None, allowSync=False, allowCameraUpload=False,
allowChannels=False, filterMovies=None, filterTelevision=None, filterMusic=None):
""" Share library content with the specified user.
Parameters:
user (:class:`~plexapi.myplex.MyPlexUser`): `MyPlexUser` object, username, or email
of the user to be added.
server (:class:`~plexapi.server.PlexServer`): `PlexServer` object, or machineIdentifier
containing the library sections to share.
sections (List<:class:`~plexapi.library.LibrarySection`>): List of `LibrarySection` objects, or names
to be shared (default None). `sections` must be defined in order to update shared libraries.
allowSync (Bool): Set True to allow user to sync content.
allowCameraUpload (Bool): Set True to allow user to upload photos.
allowChannels (Bool): Set True to allow user to utilize installed channels.
filterMovies (Dict): Dict containing key 'contentRating' and/or 'label' each set to a list of
values to be filtered. ex: `{'contentRating':['G'], 'label':['foo']}`
filterTelevision (Dict): Dict containing key 'contentRating' and/or 'label' each set to a list of
values to be filtered. ex: `{'contentRating':['G'], 'label':['foo']}`
filterMusic (Dict): Dict containing key 'label' set to a list of values to be filtered.
ex: `{'label':['foo']}`
"""
machineId = server.machineIdentifier if isinstance(server, PlexServer) else server
sectionIds = self._getSectionIds(server, sections)
headers = {'Content-Type': 'application/json'}
url = self.HOMEUSERCREATE.format(title=user)
# UserID needs to be created and referenced when adding sections
user_creation = self.query(url, self._session.post, headers=headers)
userIds = {}
for elem in user_creation.findall("."):
# Find userID
userIds['id'] = elem.attrib.get('id')
log.debug(userIds)
params = {
'server_id': machineId,
'shared_server': {'library_section_ids': sectionIds, 'invited_id': userIds['id']},
'sharing_settings': {
'allowSync': ('1' if allowSync else '0'),
'allowCameraUpload': ('1' if allowCameraUpload else '0'),
'allowChannels': ('1' if allowChannels else '0'),
'filterMovies': self._filterDictToStr(filterMovies or {}),
'filterTelevision': self._filterDictToStr(filterTelevision or {}),
'filterMusic': self._filterDictToStr(filterMusic or {}),
},
}
url = self.FRIENDINVITE.format(machineId=machineId)
library_assignment = self.query(url, self._session.post, json=params, headers=headers)
return user_creation, library_assignment
```