2016-03-21 04:26:02 +00:00
|
|
|
# -*- coding: utf-8 -*-
|
2017-02-25 06:56:12 +00:00
|
|
|
import copy
|
2017-02-06 04:52:10 +00:00
|
|
|
import requests
|
2017-04-24 02:59:22 +00:00
|
|
|
import time
|
2017-02-06 04:52:10 +00:00
|
|
|
from requests.status_codes import _codes as codes
|
2018-09-14 18:28:35 +00:00
|
|
|
from plexapi import BASE_HEADERS, CONFIG, TIMEOUT, X_PLEX_IDENTIFIER, X_PLEX_ENABLE_FAST_CONNECT
|
2017-02-06 04:52:10 +00:00
|
|
|
from plexapi import log, logfilter, utils
|
|
|
|
from plexapi.base import PlexObject
|
|
|
|
from plexapi.exceptions import BadRequest, NotFound
|
2016-04-02 06:19:32 +00:00
|
|
|
from plexapi.client import PlexClient
|
2017-09-29 23:49:13 +00:00
|
|
|
from plexapi.compat import ElementTree
|
2019-12-06 05:37:31 +00:00
|
|
|
from plexapi.library import LibrarySection
|
2016-04-02 06:19:32 +00:00
|
|
|
from plexapi.server import PlexServer
|
2018-09-08 15:25:16 +00:00
|
|
|
from plexapi.sync import SyncList, SyncItem
|
2017-09-23 21:11:34 +00:00
|
|
|
from plexapi.utils import joinArgs
|
2014-12-29 03:21:58 +00:00
|
|
|
|
|
|
|
|
2017-02-06 04:52:10 +00:00
|
|
|
class MyPlexAccount(PlexObject):
|
2017-06-05 02:01:07 +00:00
|
|
|
""" MyPlex account and profile information. This object represents the data found Account on
|
|
|
|
the myplex.tv servers at the url https://plex.tv/users/account. You may create this object
|
|
|
|
directly by passing in your username & password (or token). There is also a convenience
|
|
|
|
method provided at :class:`~plexapi.server.PlexServer.myPlexAccount()` which will create
|
|
|
|
and return this object.
|
2017-01-09 06:35:29 +00:00
|
|
|
|
2017-04-24 02:59:22 +00:00
|
|
|
Parameters:
|
|
|
|
username (str): Your MyPlex username.
|
|
|
|
password (str): Your MyPlex password.
|
|
|
|
session (requests.Session, optional): Use your own session object if you want to
|
|
|
|
cache the http responses from PMS
|
|
|
|
timeout (int): timeout in seconds on initial connect to myplex (default config.TIMEOUT).
|
|
|
|
|
2017-01-09 06:35:29 +00:00
|
|
|
Attributes:
|
2018-01-11 21:48:23 +00:00
|
|
|
SIGNIN (str): 'https://plex.tv/users/sign_in.xml'
|
2017-02-14 04:32:27 +00:00
|
|
|
key (str): 'https://plex.tv/users/account'
|
2017-02-20 05:37:00 +00:00
|
|
|
authenticationToken (str): Unknown.
|
|
|
|
certificateVersion (str): Unknown.
|
|
|
|
cloudSyncDevice (str): Unknown.
|
2017-01-10 06:54:19 +00:00
|
|
|
email (str): Your current Plex email address.
|
|
|
|
entitlements (List<str>): List of devices your allowed to use with this account.
|
2017-02-20 05:37:00 +00:00
|
|
|
guest (bool): Unknown.
|
|
|
|
home (bool): Unknown.
|
|
|
|
homeSize (int): Unknown.
|
2017-01-10 06:54:19 +00:00
|
|
|
id (str): Your Plex account ID.
|
|
|
|
locale (str): Your Plex locale
|
|
|
|
mailing_list_status (str): Your current mailing list status.
|
2017-02-20 05:37:00 +00:00
|
|
|
maxHomeSize (int): Unknown.
|
2017-01-10 06:54:19 +00:00
|
|
|
queueEmail (str): Email address to add items to your `Watch Later` queue.
|
2017-02-20 05:37:00 +00:00
|
|
|
queueUid (str): Unknown.
|
|
|
|
restricted (bool): Unknown.
|
2017-01-10 06:54:19 +00:00
|
|
|
roles: (List<str>) Lit of account roles. Plexpass membership listed here.
|
|
|
|
scrobbleTypes (str): Description
|
|
|
|
secure (bool): Description
|
|
|
|
subscriptionActive (bool): True if your subsctiption is active.
|
|
|
|
subscriptionFeatures: (List<str>) List of features allowed on your subscription.
|
|
|
|
subscriptionPlan (str): Name of subscription plan.
|
|
|
|
subscriptionStatus (str): String representation of `subscriptionActive`.
|
|
|
|
thumb (str): URL of your account thumbnail.
|
2017-02-20 05:37:00 +00:00
|
|
|
title (str): Unknown. - Looks like an alias for `username`.
|
2017-01-10 06:54:19 +00:00
|
|
|
username (str): Your account username.
|
2017-02-20 05:37:00 +00:00
|
|
|
uuid (str): Unknown.
|
2017-06-05 02:01:07 +00:00
|
|
|
_token (str): Token used to access this client.
|
|
|
|
_session (obj): Requests session object used to access this client.
|
2017-01-02 21:06:40 +00:00
|
|
|
"""
|
2017-05-27 02:35:33 +00:00
|
|
|
FRIENDINVITE = 'https://plex.tv/api/servers/{machineId}/shared_servers' # post with data
|
2019-07-25 12:14:21 +00:00
|
|
|
HOMEUSERCREATE = 'https://plex.tv/api/home/users?title={title}' # post with data
|
2019-07-25 12:25:32 +00:00
|
|
|
EXISTINGUSER = 'https://plex.tv/api/home/users?invitedEmail={username}' # post with data
|
2017-05-27 02:35:33 +00:00
|
|
|
FRIENDSERVERS = 'https://plex.tv/api/servers/{machineId}/shared_servers/{serverId}' # put with data
|
|
|
|
PLEXSERVERS = 'https://plex.tv/api/servers/{machineId}' # get
|
|
|
|
FRIENDUPDATE = 'https://plex.tv/api/friends/{userId}' # put with args, delete
|
2019-07-25 12:33:56 +00:00
|
|
|
REMOVEHOMEUSER = 'https://plex.tv/api/home/users/{userId}' # delete
|
2017-05-27 02:35:33 +00:00
|
|
|
REMOVEINVITE = 'https://plex.tv/api/invites/requested/{userId}?friend=0&server=1&home=0' # delete
|
|
|
|
REQUESTED = 'https://plex.tv/api/invites/requested' # get
|
|
|
|
REQUESTS = 'https://plex.tv/api/invites/requests' # get
|
2018-01-11 21:48:23 +00:00
|
|
|
SIGNIN = 'https://plex.tv/users/sign_in.xml' # get with auth
|
2017-05-27 02:35:33 +00:00
|
|
|
WEBHOOKS = 'https://plex.tv/api/v2/user/webhooks' # get, post with data
|
2019-12-05 17:54:18 +00:00
|
|
|
# Hub sections
|
|
|
|
VOD = 'https://vod.provider.plex.tv/hubs/' # get
|
2019-12-05 17:55:39 +00:00
|
|
|
WEBSHOWS = 'https://webshows.provider.plex.tv/hubs/' # get
|
2019-12-05 17:57:27 +00:00
|
|
|
NEWS = 'https://news.provider.plex.tv/hubs/' # get
|
2019-12-05 18:00:29 +00:00
|
|
|
PODCASTS = 'https://podcasts.provider.plex.tv/hubs/' # get
|
2019-12-05 18:02:22 +00:00
|
|
|
MUSIC = 'https://music.provider.plex.tv/hubs/' # get
|
2017-05-27 02:35:33 +00:00
|
|
|
# Key may someday switch to the following url. For now the current value works.
|
|
|
|
# https://plex.tv/api/v2/user?X-Plex-Token={token}&X-Plex-Client-Identifier={clientId}
|
2017-02-06 04:52:10 +00:00
|
|
|
key = 'https://plex.tv/users/account'
|
2017-01-02 21:06:40 +00:00
|
|
|
|
2017-05-19 03:04:57 +00:00
|
|
|
def __init__(self, username=None, password=None, token=None, session=None, timeout=None):
|
|
|
|
self._token = token
|
2017-01-09 14:21:54 +00:00
|
|
|
self._session = session or requests.Session()
|
2017-05-19 03:04:57 +00:00
|
|
|
data, initpath = self._signin(username, password, timeout)
|
|
|
|
super(MyPlexAccount, self).__init__(self, data, initpath)
|
|
|
|
|
|
|
|
def _signin(self, username, password, timeout):
|
|
|
|
if self._token:
|
|
|
|
return self.query(self.key), self.key
|
2017-02-20 03:18:23 +00:00
|
|
|
username = username or CONFIG.get('auth.myplex_username')
|
|
|
|
password = password or CONFIG.get('auth.myplex_password')
|
2017-04-24 02:59:22 +00:00
|
|
|
data = self.query(self.SIGNIN, method=self._session.post, auth=(username, password), timeout=timeout)
|
2017-05-19 03:04:57 +00:00
|
|
|
return data, self.SIGNIN
|
2017-02-06 04:52:10 +00:00
|
|
|
|
|
|
|
def _loadData(self, data):
|
2017-02-14 04:32:27 +00:00
|
|
|
""" Load attribute values from Plex XML response. """
|
2017-02-06 04:52:10 +00:00
|
|
|
self._data = data
|
2017-02-13 06:37:23 +00:00
|
|
|
self._token = logfilter.add_secret(data.attrib.get('authenticationToken'))
|
2017-02-25 06:56:12 +00:00
|
|
|
self._webhooks = []
|
2017-02-06 04:52:10 +00:00
|
|
|
self.authenticationToken = self._token
|
2016-04-07 05:39:04 +00:00
|
|
|
self.certificateVersion = data.attrib.get('certificateVersion')
|
|
|
|
self.cloudSyncDevice = data.attrib.get('cloudSyncDevice')
|
2014-12-29 03:21:58 +00:00
|
|
|
self.email = data.attrib.get('email')
|
2016-04-07 05:39:04 +00:00
|
|
|
self.guest = utils.cast(bool, data.attrib.get('guest'))
|
|
|
|
self.home = utils.cast(bool, data.attrib.get('home'))
|
|
|
|
self.homeSize = utils.cast(int, data.attrib.get('homeSize'))
|
2014-12-29 03:21:58 +00:00
|
|
|
self.id = data.attrib.get('id')
|
2016-04-04 02:46:25 +00:00
|
|
|
self.locale = data.attrib.get('locale')
|
2016-04-07 05:39:04 +00:00
|
|
|
self.mailing_list_status = data.attrib.get('mailing_list_status')
|
|
|
|
self.maxHomeSize = utils.cast(int, data.attrib.get('maxHomeSize'))
|
2014-12-29 03:21:58 +00:00
|
|
|
self.queueEmail = data.attrib.get('queueEmail')
|
|
|
|
self.queueUid = data.attrib.get('queueUid')
|
2016-04-07 05:39:04 +00:00
|
|
|
self.restricted = utils.cast(bool, data.attrib.get('restricted'))
|
|
|
|
self.scrobbleTypes = data.attrib.get('scrobbleTypes')
|
|
|
|
self.secure = utils.cast(bool, data.attrib.get('secure'))
|
|
|
|
self.thumb = data.attrib.get('thumb')
|
|
|
|
self.title = data.attrib.get('title')
|
|
|
|
self.username = data.attrib.get('username')
|
|
|
|
self.uuid = data.attrib.get('uuid')
|
2018-09-08 15:28:26 +00:00
|
|
|
subscription = data.find('subscription')
|
|
|
|
|
|
|
|
self.subscriptionActive = utils.cast(bool, subscription.attrib.get('active'))
|
|
|
|
self.subscriptionStatus = subscription.attrib.get('status')
|
|
|
|
self.subscriptionPlan = subscription.attrib.get('plan')
|
|
|
|
|
|
|
|
self.subscriptionFeatures = []
|
|
|
|
for feature in subscription.iter('feature'):
|
|
|
|
self.subscriptionFeatures.append(feature.attrib.get('id'))
|
|
|
|
|
|
|
|
roles = data.find('roles')
|
|
|
|
self.roles = []
|
|
|
|
if roles:
|
|
|
|
for role in roles.iter('role'):
|
2018-09-08 17:59:10 +00:00
|
|
|
self.roles.append(role.attrib.get('id'))
|
2018-09-08 15:28:26 +00:00
|
|
|
|
|
|
|
entitlements = data.find('entitlements')
|
|
|
|
self.entitlements = []
|
|
|
|
for entitlement in entitlements.iter('entitlement'):
|
|
|
|
self.entitlements.append(entitlement.attrib.get('id'))
|
|
|
|
|
2017-02-02 03:53:05 +00:00
|
|
|
# TODO: Fetch missing MyPlexAccount attributes
|
2018-09-08 15:28:26 +00:00
|
|
|
self.profile_settings = None
|
|
|
|
self.services = None
|
|
|
|
self.joined_at = None
|
2017-01-02 21:06:40 +00:00
|
|
|
|
2016-04-02 06:19:32 +00:00
|
|
|
def device(self, name):
|
2017-01-22 05:19:52 +00:00
|
|
|
""" Returns the :class:`~plexapi.myplex.MyPlexDevice` that matches the name specified.
|
|
|
|
|
|
|
|
Parameters:
|
2017-01-22 04:06:55 +00:00
|
|
|
name (str): Name to match against.
|
2017-01-02 21:06:40 +00:00
|
|
|
"""
|
2017-02-06 04:52:10 +00:00
|
|
|
for device in self.devices():
|
|
|
|
if device.name.lower() == name.lower():
|
|
|
|
return device
|
|
|
|
raise NotFound('Unable to find device %s' % name)
|
2014-12-29 03:21:58 +00:00
|
|
|
|
2017-01-22 04:06:55 +00:00
|
|
|
def devices(self):
|
2017-01-22 05:19:52 +00:00
|
|
|
""" Returns a list of all :class:`~plexapi.myplex.MyPlexDevice` objects connected to the server. """
|
2017-02-09 04:29:17 +00:00
|
|
|
data = self.query(MyPlexDevice.key)
|
2017-02-06 04:52:10 +00:00
|
|
|
return [MyPlexDevice(self, elem) for elem in data]
|
2014-12-29 03:21:58 +00:00
|
|
|
|
2017-10-22 22:45:56 +00:00
|
|
|
def _headers(self, **kwargs):
|
|
|
|
""" Returns dict containing base headers for all requests to the server. """
|
|
|
|
headers = BASE_HEADERS.copy()
|
|
|
|
if self._token:
|
|
|
|
headers['X-Plex-Token'] = self._token
|
|
|
|
headers.update(kwargs)
|
|
|
|
return headers
|
|
|
|
|
2017-04-24 02:59:22 +00:00
|
|
|
def query(self, url, method=None, headers=None, timeout=None, **kwargs):
|
2017-02-09 04:29:17 +00:00
|
|
|
method = method or self._session.get
|
2017-04-24 02:59:22 +00:00
|
|
|
timeout = timeout or TIMEOUT
|
2017-05-27 02:53:06 +00:00
|
|
|
log.debug('%s %s %s', method.__name__.upper(), url, kwargs.get('json', ''))
|
2017-10-22 22:45:56 +00:00
|
|
|
headers = self._headers(**headers or {})
|
|
|
|
response = method(url, headers=headers, timeout=timeout, **kwargs)
|
2017-10-25 19:53:52 +00:00
|
|
|
if response.status_code not in (200, 201, 204): # pragma: no cover
|
2017-02-09 04:29:17 +00:00
|
|
|
codename = codes.get(response.status_code)[0]
|
2017-05-27 02:35:33 +00:00
|
|
|
errtext = response.text.replace('\n', ' ')
|
2017-09-23 21:11:34 +00:00
|
|
|
raise BadRequest('(%s) %s %s; %s' % (response.status_code, codename, response.url, errtext))
|
2017-02-25 07:37:30 +00:00
|
|
|
data = response.text.encode('utf8')
|
|
|
|
return ElementTree.fromstring(data) if data.strip() else None
|
2017-02-09 04:29:17 +00:00
|
|
|
|
2016-04-02 06:19:32 +00:00
|
|
|
def resource(self, name):
|
2017-01-22 05:19:52 +00:00
|
|
|
""" Returns the :class:`~plexapi.myplex.MyPlexResource` that matches the name specified.
|
2017-01-02 21:06:40 +00:00
|
|
|
|
2017-01-22 05:19:52 +00:00
|
|
|
Parameters:
|
|
|
|
name (str): Name to match against.
|
2017-01-02 21:06:40 +00:00
|
|
|
"""
|
2017-02-06 04:52:10 +00:00
|
|
|
for resource in self.resources():
|
|
|
|
if resource.name.lower() == name.lower():
|
|
|
|
return resource
|
|
|
|
raise NotFound('Unable to find resource %s' % name)
|
2017-01-02 21:06:40 +00:00
|
|
|
|
2017-02-06 04:52:10 +00:00
|
|
|
def resources(self):
|
|
|
|
""" Returns a list of all :class:`~plexapi.myplex.MyPlexResource` objects connected to the server. """
|
2017-02-09 04:29:17 +00:00
|
|
|
data = self.query(MyPlexResource.key)
|
2017-02-06 04:52:10 +00:00
|
|
|
return [MyPlexResource(self, elem) for elem in data]
|
2017-01-02 21:06:40 +00:00
|
|
|
|
2017-05-27 02:35:33 +00:00
|
|
|
def inviteFriend(self, user, server, sections=None, allowSync=False, allowCameraUpload=False,
|
2019-09-21 21:22:54 +00:00
|
|
|
allowChannels=False, filterMovies=None, filterTelevision=None, filterMusic=None):
|
2017-05-27 02:35:33 +00:00
|
|
|
""" Share library content with the specified user.
|
|
|
|
|
|
|
|
Parameters:
|
|
|
|
user (str): MyPlexUser, username, email of the user to be added.
|
2017-05-27 02:53:06 +00:00
|
|
|
server (PlexServer): PlexServer object or machineIdentifier containing the library sections to share.
|
2019-07-22 19:37:37 +00:00
|
|
|
sections ([Section]): Library sections, names or ids to be shared (default None).
|
|
|
|
[Section] must be defined in order to update shared sections.
|
2017-05-27 02:35:33 +00:00
|
|
|
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']}
|
|
|
|
"""
|
|
|
|
username = user.username if isinstance(user, MyPlexUser) else user
|
|
|
|
machineId = server.machineIdentifier if isinstance(server, PlexServer) else server
|
|
|
|
sectionIds = self._getSectionIds(machineId, sections)
|
|
|
|
params = {
|
|
|
|
'server_id': machineId,
|
2017-05-27 02:53:06 +00:00
|
|
|
'shared_server': {'library_section_ids': sectionIds, 'invited_email': username},
|
2017-05-27 02:35:33 +00:00
|
|
|
'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 {}),
|
|
|
|
},
|
|
|
|
}
|
|
|
|
headers = {'Content-Type': 'application/json'}
|
|
|
|
url = self.FRIENDINVITE.format(machineId=machineId)
|
|
|
|
return self.query(url, self._session.post, json=params, headers=headers)
|
|
|
|
|
2019-07-25 12:14:21 +00:00
|
|
|
def createHomeUser(self, user, server, sections=None, allowSync=False, allowCameraUpload=False,
|
2019-09-21 21:22:54 +00:00
|
|
|
allowChannels=False, filterMovies=None, filterTelevision=None, filterMusic=None):
|
2019-07-25 12:14:21 +00:00
|
|
|
""" Share library content with the specified user.
|
2019-09-21 21:22:54 +00:00
|
|
|
|
2019-07-25 12:14:21 +00:00
|
|
|
Parameters:
|
|
|
|
user (str): MyPlexUser, username, email of the user to be added.
|
|
|
|
server (PlexServer): PlexServer object or machineIdentifier containing the library sections to share.
|
|
|
|
sections ([Section]): Library sections, names or ids to be shared (default None shares all sections).
|
|
|
|
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
|
|
|
|
|
2019-07-25 12:25:32 +00:00
|
|
|
def createExistingUser(self, user, server, sections=None, allowSync=False, allowCameraUpload=False,
|
2019-09-21 21:22:54 +00:00
|
|
|
allowChannels=False, filterMovies=None, filterTelevision=None, filterMusic=None):
|
2019-07-25 12:25:32 +00:00
|
|
|
""" Share library content with the specified user.
|
|
|
|
|
|
|
|
Parameters:
|
|
|
|
user (str): MyPlexUser, username, email of the user to be added.
|
|
|
|
server (PlexServer): PlexServer object or machineIdentifier containing the library sections to share.
|
|
|
|
sections ([Section]): Library sections, names or ids to be shared (default None shares all sections).
|
|
|
|
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']}
|
|
|
|
"""
|
|
|
|
headers = {'Content-Type': 'application/json'}
|
|
|
|
# If user already exists, carry over sections and settings.
|
|
|
|
if isinstance(user, MyPlexUser):
|
|
|
|
username = user.username
|
|
|
|
elif user in [_user.username for _user in self.users()]:
|
|
|
|
username = self.user(user).username
|
|
|
|
else:
|
|
|
|
# If user does not already exists, treat request as new request and include sections and settings.
|
|
|
|
newUser = user
|
|
|
|
url = self.EXISTINGUSER.format(username=newUser)
|
|
|
|
user_creation = self.query(url, self._session.post, headers=headers)
|
|
|
|
machineId = server.machineIdentifier if isinstance(server, PlexServer) else server
|
|
|
|
sectionIds = self._getSectionIds(server, sections)
|
|
|
|
params = {
|
|
|
|
'server_id': machineId,
|
|
|
|
'shared_server': {'library_section_ids': sectionIds, 'invited_email': newUser},
|
|
|
|
'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
|
|
|
|
|
|
|
|
url = self.EXISTINGUSER.format(username=username)
|
|
|
|
return self.query(url, self._session.post, headers=headers)
|
|
|
|
|
2017-05-27 02:35:33 +00:00
|
|
|
def removeFriend(self, user):
|
|
|
|
""" Remove the specified user from all sharing.
|
|
|
|
|
|
|
|
Parameters:
|
|
|
|
user (str): MyPlexUser, username, email of the user to be added.
|
|
|
|
"""
|
|
|
|
user = self.user(user)
|
|
|
|
url = self.FRIENDUPDATE if user.friend else self.REMOVEINVITE
|
|
|
|
url = url.format(userId=user.id)
|
|
|
|
return self.query(url, self._session.delete)
|
|
|
|
|
2019-07-25 12:33:56 +00:00
|
|
|
def removeHomeUser(self, user):
|
|
|
|
""" Remove the specified managed user from home.
|
|
|
|
|
|
|
|
Parameters:
|
|
|
|
user (str): MyPlexUser, username, email of the user to be removed from home.
|
|
|
|
"""
|
|
|
|
user = self.user(user)
|
|
|
|
url = self.REMOVEHOMEUSER.format(userId=user.id)
|
|
|
|
return self.query(url, self._session.delete)
|
|
|
|
|
2017-09-23 21:11:34 +00:00
|
|
|
def updateFriend(self, user, server, sections=None, removeSections=False, allowSync=None, allowCameraUpload=None,
|
|
|
|
allowChannels=None, filterMovies=None, filterTelevision=None, filterMusic=None):
|
2017-05-27 02:35:33 +00:00
|
|
|
""" Update the specified user's share settings.
|
|
|
|
|
|
|
|
Parameters:
|
|
|
|
user (str): MyPlexUser, username, email of the user to be added.
|
2017-05-27 02:53:06 +00:00
|
|
|
server (PlexServer): PlexServer object or machineIdentifier containing the library sections to share.
|
2019-07-22 19:37:37 +00:00
|
|
|
sections: ([Section]): Library sections, names or ids to be shared (default None).
|
|
|
|
[Section] must be defined in order to update shared sections.
|
2017-09-14 20:53:11 +00:00
|
|
|
removeSections (Bool): Set True to remove all shares. Supersedes sections.
|
2017-05-27 02:35:33 +00:00
|
|
|
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']}
|
|
|
|
"""
|
|
|
|
# Update friend servers
|
2017-09-23 21:11:34 +00:00
|
|
|
response_filters = ''
|
|
|
|
response_servers = ''
|
2018-09-14 18:03:23 +00:00
|
|
|
user = user if isinstance(user, MyPlexUser) else self.user(user)
|
2017-05-27 02:35:33 +00:00
|
|
|
machineId = server.machineIdentifier if isinstance(server, PlexServer) else server
|
|
|
|
sectionIds = self._getSectionIds(machineId, sections)
|
|
|
|
headers = {'Content-Type': 'application/json'}
|
2017-09-23 21:11:34 +00:00
|
|
|
# Determine whether user has access to the shared server.
|
|
|
|
user_servers = [s for s in user.servers if s.machineIdentifier == machineId]
|
|
|
|
if user_servers and sectionIds:
|
|
|
|
serverId = user_servers[0].id
|
2017-09-08 18:17:39 +00:00
|
|
|
params = {'server_id': machineId, 'shared_server': {'library_section_ids': sectionIds}}
|
|
|
|
url = self.FRIENDSERVERS.format(machineId=machineId, serverId=serverId)
|
|
|
|
else:
|
2017-09-29 23:49:13 +00:00
|
|
|
params = {'server_id': machineId, 'shared_server': {'library_section_ids': sectionIds,
|
2019-09-21 21:22:54 +00:00
|
|
|
'invited_id': user.id}}
|
2017-09-08 18:17:39 +00:00
|
|
|
url = self.FRIENDINVITE.format(machineId=machineId)
|
2017-09-29 23:49:13 +00:00
|
|
|
# Remove share sections, add shares to user without shares, or update shares
|
2018-09-14 18:03:23 +00:00
|
|
|
if not user_servers or sectionIds:
|
2017-09-23 21:11:34 +00:00
|
|
|
if removeSections is True:
|
|
|
|
response_servers = self.query(url, self._session.delete, json=params, headers=headers)
|
|
|
|
elif 'invited_id' in params.get('shared_server', ''):
|
|
|
|
response_servers = self.query(url, self._session.post, json=params, headers=headers)
|
|
|
|
else:
|
|
|
|
response_servers = self.query(url, self._session.put, json=params, headers=headers)
|
2017-09-08 14:39:58 +00:00
|
|
|
else:
|
2017-09-23 21:11:34 +00:00
|
|
|
log.warning('Section name, number of section object is required changing library sections')
|
2017-05-27 02:35:33 +00:00
|
|
|
# Update friend filters
|
|
|
|
url = self.FRIENDUPDATE.format(userId=user.id)
|
2017-09-29 23:49:13 +00:00
|
|
|
params = {}
|
2017-09-23 21:11:34 +00:00
|
|
|
if isinstance(allowSync, bool):
|
2017-09-29 23:49:13 +00:00
|
|
|
params['allowSync'] = '1' if allowSync else '0'
|
2017-09-23 21:11:34 +00:00
|
|
|
if isinstance(allowCameraUpload, bool):
|
2017-09-29 23:49:13 +00:00
|
|
|
params['allowCameraUpload'] = '1' if allowCameraUpload else '0'
|
2017-09-23 21:11:34 +00:00
|
|
|
if isinstance(allowChannels, bool):
|
2017-09-29 23:49:13 +00:00
|
|
|
params['allowChannels'] = '1' if allowChannels else '0'
|
2017-09-23 21:11:34 +00:00
|
|
|
if isinstance(filterMovies, dict):
|
2017-09-29 23:49:13 +00:00
|
|
|
params['filterMovies'] = self._filterDictToStr(filterMovies or {}) # '1' if allowChannels else '0'
|
2017-09-23 21:11:34 +00:00
|
|
|
if isinstance(filterTelevision, dict):
|
2017-09-29 23:49:13 +00:00
|
|
|
params['filterTelevision'] = self._filterDictToStr(filterTelevision or {})
|
2017-09-23 21:11:34 +00:00
|
|
|
if isinstance(allowChannels, dict):
|
2017-09-29 23:49:13 +00:00
|
|
|
params['filterMusic'] = self._filterDictToStr(filterMusic or {})
|
|
|
|
if params:
|
|
|
|
url += joinArgs(params)
|
2017-09-23 21:11:34 +00:00
|
|
|
response_filters = self.query(url, self._session.put)
|
2017-05-27 02:35:33 +00:00
|
|
|
return response_servers, response_filters
|
|
|
|
|
|
|
|
def user(self, username):
|
2018-09-08 15:25:16 +00:00
|
|
|
""" Returns the :class:`~plexapi.myplex.MyPlexUser` that matches the email or username specified.
|
2017-01-02 21:06:40 +00:00
|
|
|
|
2017-01-22 05:19:52 +00:00
|
|
|
Parameters:
|
2017-05-27 02:35:33 +00:00
|
|
|
username (str): Username, email or id of the user to return.
|
2017-01-02 21:06:40 +00:00
|
|
|
"""
|
2017-02-06 04:52:10 +00:00
|
|
|
for user in self.users():
|
2017-09-23 21:11:34 +00:00
|
|
|
# Home users don't have email, username etc.
|
2017-09-08 22:49:55 +00:00
|
|
|
if username.lower() == user.title.lower():
|
2017-02-06 04:52:10 +00:00
|
|
|
return user
|
2017-09-23 22:21:29 +00:00
|
|
|
|
2017-07-17 00:59:53 +00:00
|
|
|
elif (user.username and user.email and user.id and username.lower() in
|
|
|
|
(user.username.lower(), user.email.lower(), str(user.id))):
|
|
|
|
return user
|
2017-09-23 21:11:34 +00:00
|
|
|
|
2017-05-27 02:35:33 +00:00
|
|
|
raise NotFound('Unable to find user %s' % username)
|
2015-09-29 18:14:30 +00:00
|
|
|
|
2017-02-06 04:52:10 +00:00
|
|
|
def users(self):
|
2017-05-27 02:35:33 +00:00
|
|
|
""" Returns a list of all :class:`~plexapi.myplex.MyPlexUser` objects connected to your account.
|
|
|
|
This includes both friends and pending invites. You can reference the user.friend to
|
|
|
|
distinguish between the two.
|
|
|
|
"""
|
|
|
|
friends = [MyPlexUser(self, elem) for elem in self.query(MyPlexUser.key)]
|
|
|
|
requested = [MyPlexUser(self, elem, self.REQUESTED) for elem in self.query(self.REQUESTED)]
|
|
|
|
return friends + requested
|
|
|
|
|
|
|
|
def _getSectionIds(self, server, sections):
|
|
|
|
""" Converts a list of section objects or names to sectionIds needed for library sharing. """
|
|
|
|
if not sections: return []
|
|
|
|
# Get a list of all section ids for looking up each section.
|
|
|
|
allSectionIds = {}
|
|
|
|
machineIdentifier = server.machineIdentifier if isinstance(server, PlexServer) else server
|
|
|
|
url = self.PLEXSERVERS.replace('{machineId}', machineIdentifier)
|
|
|
|
data = self.query(url, self._session.get)
|
|
|
|
for elem in data[0]:
|
2017-05-27 02:53:06 +00:00
|
|
|
allSectionIds[elem.attrib.get('id', '').lower()] = elem.attrib.get('id')
|
|
|
|
allSectionIds[elem.attrib.get('title', '').lower()] = elem.attrib.get('id')
|
|
|
|
allSectionIds[elem.attrib.get('key', '').lower()] = elem.attrib.get('id')
|
2017-09-23 21:11:34 +00:00
|
|
|
log.debug(allSectionIds)
|
2017-05-27 02:35:33 +00:00
|
|
|
# Convert passed in section items to section ids from above lookup
|
|
|
|
sectionIds = []
|
|
|
|
for section in sections:
|
|
|
|
sectionKey = section.key if isinstance(section, LibrarySection) else section
|
|
|
|
sectionIds.append(allSectionIds[sectionKey.lower()])
|
|
|
|
return sectionIds
|
|
|
|
|
|
|
|
def _filterDictToStr(self, filterDict):
|
|
|
|
""" Converts friend filters to a string representation for transport. """
|
|
|
|
values = []
|
|
|
|
for key, vals in filterDict.items():
|
|
|
|
if key not in ('contentRating', 'label'):
|
|
|
|
raise BadRequest('Unknown filter key: %s', key)
|
|
|
|
values.append('%s=%s' % (key, '%2C'.join(vals)))
|
|
|
|
return '|'.join(values)
|
2014-12-29 03:21:58 +00:00
|
|
|
|
2017-02-25 06:56:12 +00:00
|
|
|
def addWebhook(self, url):
|
2017-02-28 04:43:31 +00:00
|
|
|
# copy _webhooks and append url
|
|
|
|
urls = self._webhooks[:] + [url]
|
2017-02-25 06:56:12 +00:00
|
|
|
return self.setWebhooks(urls)
|
|
|
|
|
|
|
|
def deleteWebhook(self, url):
|
|
|
|
urls = copy.copy(self._webhooks)
|
|
|
|
if url not in urls:
|
|
|
|
raise BadRequest('Webhook does not exist: %s' % url)
|
|
|
|
urls.remove(url)
|
|
|
|
return self.setWebhooks(urls)
|
|
|
|
|
|
|
|
def setWebhooks(self, urls):
|
|
|
|
log.info('Setting webhooks: %s' % urls)
|
2018-09-14 18:03:23 +00:00
|
|
|
data = {'urls[]': urls} if len(urls) else {'urls': ''}
|
|
|
|
data = self.query(self.WEBHOOKS, self._session.post, data=data)
|
2017-02-25 06:56:12 +00:00
|
|
|
self._webhooks = self.listAttrs(data, 'url', etag='webhook')
|
|
|
|
return self._webhooks
|
|
|
|
|
|
|
|
def webhooks(self):
|
|
|
|
data = self.query(self.WEBHOOKS)
|
|
|
|
self._webhooks = self.listAttrs(data, 'url', etag='webhook')
|
|
|
|
return self._webhooks
|
|
|
|
|
2017-10-11 21:31:05 +00:00
|
|
|
def optOut(self, playback=None, library=None):
|
2017-10-12 03:30:58 +00:00
|
|
|
""" Opt in or out of sharing stuff with plex.
|
|
|
|
See: https://www.plex.tv/about/privacy-legal/
|
2017-10-03 19:23:47 +00:00
|
|
|
"""
|
|
|
|
params = {}
|
|
|
|
if playback is not None:
|
|
|
|
params['optOutPlayback'] = int(playback)
|
|
|
|
if library is not None:
|
|
|
|
params['optOutLibraryStats'] = int(library)
|
|
|
|
url = 'https://plex.tv/api/v2/user/privacy'
|
2018-09-14 18:03:23 +00:00
|
|
|
return self.query(url, method=self._session.put, data=params)
|
2017-10-03 19:23:47 +00:00
|
|
|
|
2018-09-08 15:25:16 +00:00
|
|
|
def syncItems(self, client=None, clientId=None):
|
|
|
|
""" Returns an instance of :class:`plexapi.sync.SyncList` for specified client.
|
|
|
|
|
|
|
|
Parameters:
|
|
|
|
client (:class:`~plexapi.myplex.MyPlexDevice`): a client to query SyncItems for.
|
|
|
|
clientId (str): an identifier of a client to query SyncItems for.
|
|
|
|
|
|
|
|
If both `client` and `clientId` provided the client would be preferred.
|
|
|
|
If neither `client` nor `clientId` provided the clientId would be set to current clients`s identifier.
|
|
|
|
"""
|
|
|
|
if client:
|
|
|
|
clientId = client.clientIdentifier
|
|
|
|
elif clientId is None:
|
|
|
|
clientId = X_PLEX_IDENTIFIER
|
|
|
|
|
|
|
|
data = self.query(SyncList.key.format(clientId=clientId))
|
|
|
|
|
|
|
|
return SyncList(self, data)
|
|
|
|
|
|
|
|
def sync(self, sync_item, client=None, clientId=None):
|
|
|
|
""" Adds specified sync item for the client. It's always easier to use methods defined directly in the media
|
|
|
|
objects, e.g. :func:`plexapi.video.Video.sync`, :func:`plexapi.audio.Audio.sync`.
|
|
|
|
|
|
|
|
Parameters:
|
|
|
|
client (:class:`~plexapi.myplex.MyPlexDevice`): a client for which you need to add SyncItem to.
|
|
|
|
clientId (str): an identifier of a client for which you need to add SyncItem to.
|
|
|
|
sync_item (:class:`plexapi.sync.SyncItem`): prepared SyncItem object with all fields set.
|
|
|
|
|
|
|
|
If both `client` and `clientId` provided the client would be preferred.
|
|
|
|
If neither `client` nor `clientId` provided the clientId would be set to current clients`s identifier.
|
|
|
|
|
|
|
|
Returns:
|
|
|
|
:class:`plexapi.sync.SyncItem`: an instance of created syncItem.
|
|
|
|
|
|
|
|
Raises:
|
2018-10-03 10:09:43 +00:00
|
|
|
:class:`plexapi.exceptions.BadRequest`: when client with provided clientId wasn`t found.
|
|
|
|
:class:`plexapi.exceptions.BadRequest`: provided client doesn`t provides `sync-target`.
|
2018-09-08 15:25:16 +00:00
|
|
|
"""
|
|
|
|
if not client and not clientId:
|
|
|
|
clientId = X_PLEX_IDENTIFIER
|
|
|
|
|
|
|
|
if not client:
|
|
|
|
for device in self.devices():
|
|
|
|
if device.clientIdentifier == clientId:
|
|
|
|
client = device
|
|
|
|
break
|
|
|
|
|
|
|
|
if not client:
|
|
|
|
raise BadRequest('Unable to find client by clientId=%s', clientId)
|
|
|
|
|
|
|
|
if 'sync-target' not in client.provides:
|
|
|
|
raise BadRequest('Received client doesn`t provides sync-target')
|
|
|
|
|
|
|
|
params = {
|
|
|
|
'SyncItem[title]': sync_item.title,
|
|
|
|
'SyncItem[rootTitle]': sync_item.rootTitle,
|
|
|
|
'SyncItem[metadataType]': sync_item.metadataType,
|
|
|
|
'SyncItem[machineIdentifier]': sync_item.machineIdentifier,
|
|
|
|
'SyncItem[contentType]': sync_item.contentType,
|
|
|
|
'SyncItem[Policy][scope]': sync_item.policy.scope,
|
|
|
|
'SyncItem[Policy][unwatched]': str(int(sync_item.policy.unwatched)),
|
|
|
|
'SyncItem[Policy][value]': str(sync_item.policy.value if hasattr(sync_item.policy, 'value') else 0),
|
|
|
|
'SyncItem[Location][uri]': sync_item.location,
|
|
|
|
'SyncItem[MediaSettings][audioBoost]': str(sync_item.mediaSettings.audioBoost),
|
|
|
|
'SyncItem[MediaSettings][maxVideoBitrate]': str(sync_item.mediaSettings.maxVideoBitrate),
|
|
|
|
'SyncItem[MediaSettings][musicBitrate]': str(sync_item.mediaSettings.musicBitrate),
|
|
|
|
'SyncItem[MediaSettings][photoQuality]': str(sync_item.mediaSettings.photoQuality),
|
|
|
|
'SyncItem[MediaSettings][photoResolution]': sync_item.mediaSettings.photoResolution,
|
|
|
|
'SyncItem[MediaSettings][subtitleSize]': str(sync_item.mediaSettings.subtitleSize),
|
|
|
|
'SyncItem[MediaSettings][videoQuality]': str(sync_item.mediaSettings.videoQuality),
|
|
|
|
'SyncItem[MediaSettings][videoResolution]': sync_item.mediaSettings.videoResolution,
|
|
|
|
}
|
|
|
|
|
|
|
|
url = SyncList.key.format(clientId=client.clientIdentifier)
|
|
|
|
data = self.query(url, method=self._session.post, headers={
|
|
|
|
'Content-type': 'x-www-form-urlencoded',
|
|
|
|
}, params=params)
|
|
|
|
|
|
|
|
return SyncItem(self, data, None, clientIdentifier=client.clientIdentifier)
|
|
|
|
|
2018-09-14 18:52:26 +00:00
|
|
|
def claimToken(self):
|
|
|
|
""" Returns a str, a new "claim-token", which you can use to register your new Plex Server instance to your
|
|
|
|
account.
|
|
|
|
See: https://hub.docker.com/r/plexinc/pms-docker/, https://www.plex.tv/claim/
|
|
|
|
"""
|
|
|
|
response = self._session.get('https://plex.tv/api/claim/token.json', headers=self._headers(), timeout=TIMEOUT)
|
|
|
|
if response.status_code not in (200, 201, 204): # pragma: no cover
|
|
|
|
codename = codes.get(response.status_code)[0]
|
|
|
|
errtext = response.text.replace('\n', ' ')
|
|
|
|
raise BadRequest('(%s) %s %s; %s' % (response.status_code, codename, response.url, errtext))
|
|
|
|
return response.json()['token']
|
|
|
|
|
2019-11-20 11:50:25 +00:00
|
|
|
def history(self, maxresults=9999999, mindate=None):
|
|
|
|
""" Get Play History for all library sections on all servers for the owner.
|
|
|
|
Parameters:
|
|
|
|
maxresults (int): Only return the specified number of results (optional).
|
|
|
|
mindate (datetime): Min datetime to return results from.
|
|
|
|
"""
|
2019-11-16 21:35:20 +00:00
|
|
|
servers = [x for x in self.resources() if x.provides == 'server' and x.owned]
|
|
|
|
hist = []
|
|
|
|
for server in servers:
|
|
|
|
conn = server.connect()
|
2019-11-20 11:50:25 +00:00
|
|
|
hist.extend(conn.history(maxresults=maxresults, mindate=mindate, accountID=1))
|
2019-11-16 21:35:20 +00:00
|
|
|
return hist
|
|
|
|
|
2019-12-05 17:54:18 +00:00
|
|
|
def videoOnDemand(self):
|
|
|
|
""" Returns a list of VOD Hub items :class:`~plexapi.library.Hub`
|
|
|
|
"""
|
|
|
|
items = []
|
|
|
|
data = self.query(url=self.VOD)
|
|
|
|
for elem in data:
|
|
|
|
items.append(Hub(server=self._server, data=elem))
|
|
|
|
|
|
|
|
return items
|
|
|
|
|
2019-12-05 17:55:39 +00:00
|
|
|
def webShows(self):
|
|
|
|
""" Returns a list of Webshow Hub items :class:`~plexapi.library.Hub`
|
|
|
|
"""
|
|
|
|
items = []
|
|
|
|
data = self.query(url=self.WEBSHOWS)
|
|
|
|
for elem in data:
|
|
|
|
items.append(Hub(server=self._server, data=elem))
|
|
|
|
|
|
|
|
return items
|
|
|
|
|
2019-12-05 17:57:27 +00:00
|
|
|
def news(self):
|
|
|
|
""" Returns a list of News Hub items :class:`~plexapi.library.Hub`
|
|
|
|
"""
|
|
|
|
items = []
|
|
|
|
data = self.query(url=self.NEWS)
|
|
|
|
for elem in data:
|
|
|
|
items.append(Hub(server=self._server, data=elem))
|
|
|
|
|
|
|
|
return items
|
|
|
|
|
2019-12-05 18:00:29 +00:00
|
|
|
def podcasts(self):
|
|
|
|
""" Returns a list of Podcasts Hub items :class:`~plexapi.library.Hub`
|
|
|
|
"""
|
|
|
|
items = []
|
|
|
|
data = self.query(url=self.PODCASTS)
|
|
|
|
for elem in data:
|
|
|
|
items.append(Hub(server=self._server, data=elem))
|
|
|
|
|
|
|
|
return items
|
|
|
|
|
2019-12-05 18:02:22 +00:00
|
|
|
def tidal(self):
|
|
|
|
""" Returns a list of tidal Hub items :class:`~plexapi.library.Hub`
|
|
|
|
"""
|
|
|
|
items = []
|
|
|
|
data = self.query(url=self.MUSIC)
|
|
|
|
for elem in data:
|
|
|
|
items.append(Hub(server=self._server, data=elem))
|
|
|
|
|
|
|
|
return items
|
|
|
|
|
2017-02-25 06:56:12 +00:00
|
|
|
|
2017-02-06 04:52:10 +00:00
|
|
|
class MyPlexUser(PlexObject):
|
2017-01-22 05:19:52 +00:00
|
|
|
""" This object represents non-signed in users such as friends and linked
|
|
|
|
accounts. NOTE: This should not be confused with the :class:`~myplex.MyPlexAccount`
|
|
|
|
which is your specific account. The raw xml for the data presented here
|
|
|
|
can be found at: https://plex.tv/api/users/
|
|
|
|
|
|
|
|
Attributes:
|
2017-02-14 04:32:27 +00:00
|
|
|
TAG (str): 'User'
|
|
|
|
key (str): 'https://plex.tv/api/users/'
|
|
|
|
allowCameraUpload (bool): True if this user can upload images.
|
|
|
|
allowChannels (bool): True if this user has access to channels.
|
|
|
|
allowSync (bool): True if this user can sync.
|
|
|
|
email (str): User's email address (user@gmail.com).
|
|
|
|
filterAll (str): Unknown.
|
|
|
|
filterMovies (str): Unknown.
|
|
|
|
filterMusic (str): Unknown.
|
|
|
|
filterPhotos (str): Unknown.
|
|
|
|
filterTelevision (str): Unknown.
|
|
|
|
home (bool): Unknown.
|
2017-01-22 05:19:52 +00:00
|
|
|
id (int): User's Plex account ID.
|
2017-02-14 04:32:27 +00:00
|
|
|
protected (False): Unknown (possibly SSL enabled?).
|
|
|
|
recommendationsPlaylistId (str): Unknown.
|
|
|
|
restricted (str): Unknown.
|
|
|
|
thumb (str): Link to the users avatar.
|
|
|
|
title (str): Seems to be an aliad for username.
|
|
|
|
username (str): User's username.
|
2019-07-16 17:21:56 +00:00
|
|
|
servers: Servers shared between user and friend
|
2017-01-02 21:06:40 +00:00
|
|
|
"""
|
2017-02-13 02:55:55 +00:00
|
|
|
TAG = 'User'
|
2017-02-06 04:52:10 +00:00
|
|
|
key = 'https://plex.tv/api/users/'
|
2017-01-02 21:06:40 +00:00
|
|
|
|
2017-02-06 04:52:10 +00:00
|
|
|
def _loadData(self, data):
|
2017-02-14 04:32:27 +00:00
|
|
|
""" Load attribute values from Plex XML response. """
|
2017-02-04 08:08:47 +00:00
|
|
|
self._data = data
|
2017-05-27 02:35:33 +00:00
|
|
|
self.friend = self._initpath == self.key
|
2017-01-22 05:19:52 +00:00
|
|
|
self.allowCameraUpload = utils.cast(bool, data.attrib.get('allowCameraUpload'))
|
2016-04-07 05:39:04 +00:00
|
|
|
self.allowChannels = utils.cast(bool, data.attrib.get('allowChannels'))
|
|
|
|
self.allowSync = utils.cast(bool, data.attrib.get('allowSync'))
|
|
|
|
self.email = data.attrib.get('email')
|
|
|
|
self.filterAll = data.attrib.get('filterAll')
|
|
|
|
self.filterMovies = data.attrib.get('filterMovies')
|
|
|
|
self.filterMusic = data.attrib.get('filterMusic')
|
|
|
|
self.filterPhotos = data.attrib.get('filterPhotos')
|
|
|
|
self.filterTelevision = data.attrib.get('filterTelevision')
|
|
|
|
self.home = utils.cast(bool, data.attrib.get('home'))
|
|
|
|
self.id = utils.cast(int, data.attrib.get('id'))
|
|
|
|
self.protected = utils.cast(bool, data.attrib.get('protected'))
|
2017-01-22 05:19:52 +00:00
|
|
|
self.recommendationsPlaylistId = data.attrib.get('recommendationsPlaylistId')
|
2016-04-07 05:39:04 +00:00
|
|
|
self.restricted = data.attrib.get('restricted')
|
|
|
|
self.thumb = data.attrib.get('thumb')
|
2017-10-28 20:58:47 +00:00
|
|
|
self.title = data.attrib.get('title', '')
|
|
|
|
self.username = data.attrib.get('username', '')
|
2017-05-27 02:35:33 +00:00
|
|
|
self.servers = self.findItems(data, MyPlexServerShare)
|
2019-11-16 21:35:20 +00:00
|
|
|
for server in self.servers:
|
|
|
|
server.accountID = self.id
|
2017-05-27 02:35:33 +00:00
|
|
|
|
2017-07-17 00:59:53 +00:00
|
|
|
def get_token(self, machineIdentifier):
|
|
|
|
try:
|
|
|
|
for item in self._server.query(self._server.FRIENDINVITE.format(machineId=machineIdentifier)):
|
|
|
|
if utils.cast(int, item.attrib.get('userID')) == self.id:
|
|
|
|
return item.attrib.get('accessToken')
|
2017-07-17 14:11:03 +00:00
|
|
|
except Exception:
|
|
|
|
log.exception('Failed to get access token for %s' % self.title)
|
2017-07-17 00:59:53 +00:00
|
|
|
|
2019-11-16 21:35:20 +00:00
|
|
|
def server(self, name):
|
|
|
|
""" Returns the :class:`~plexapi.myplex.MyPlexServerShare` that matches the name specified.
|
|
|
|
|
|
|
|
Parameters:
|
|
|
|
name (str): Name of the server to return.
|
|
|
|
"""
|
|
|
|
for server in self.servers:
|
|
|
|
if name.lower() == server.name.lower():
|
|
|
|
return server
|
|
|
|
|
|
|
|
raise NotFound('Unable to find server %s' % name)
|
|
|
|
|
2019-11-20 11:50:25 +00:00
|
|
|
def history(self, maxresults=9999999, mindate=None):
|
|
|
|
""" Get all Play History for a user in all shared servers.
|
|
|
|
Parameters:
|
|
|
|
maxresults (int): Only return the specified number of results (optional).
|
|
|
|
mindate (datetime): Min datetime to return results from.
|
|
|
|
"""
|
2019-11-16 21:35:20 +00:00
|
|
|
hist = []
|
|
|
|
for server in self.servers:
|
2019-11-20 11:50:25 +00:00
|
|
|
hist.extend(server.history(maxresults=maxresults, mindate=mindate))
|
2019-11-16 21:35:20 +00:00
|
|
|
return hist
|
|
|
|
|
2017-05-27 02:35:33 +00:00
|
|
|
|
2017-09-23 21:11:34 +00:00
|
|
|
class Section(PlexObject):
|
2017-10-24 19:41:07 +00:00
|
|
|
""" This refers to a shared section. The raw xml for the data presented here
|
|
|
|
can be found at: https://plex.tv/api/servers/{machineId}/shared_servers/{serverId}
|
|
|
|
|
|
|
|
Attributes:
|
|
|
|
TAG (str): section
|
|
|
|
id (int): shared section id
|
|
|
|
sectionKey (str): what key we use for this section
|
|
|
|
title (str): Title of the section
|
|
|
|
sectionId (str): shared section id
|
|
|
|
type (str): movie, tvshow, artist
|
|
|
|
shared (bool): If this section is shared with the user
|
|
|
|
|
|
|
|
"""
|
2017-09-23 21:11:34 +00:00
|
|
|
TAG = 'Section'
|
|
|
|
|
|
|
|
def _loadData(self, data):
|
|
|
|
self._data = data
|
2017-10-24 19:41:07 +00:00
|
|
|
# self.id = utils.cast(int, data.attrib.get('id')) # Havnt decided if this should be changed.
|
2017-09-23 21:11:34 +00:00
|
|
|
self.sectionKey = data.attrib.get('key')
|
|
|
|
self.title = data.attrib.get('title')
|
|
|
|
self.sectionId = data.attrib.get('id')
|
|
|
|
self.type = data.attrib.get('type')
|
|
|
|
self.shared = utils.cast(bool, data.attrib.get('shared'))
|
|
|
|
|
2019-11-20 11:50:25 +00:00
|
|
|
def history(self, maxresults=9999999, mindate=None):
|
|
|
|
""" Get all Play History for a user for this section in this shared server.
|
|
|
|
Parameters:
|
|
|
|
maxresults (int): Only return the specified number of results (optional).
|
|
|
|
mindate (datetime): Min datetime to return results from.
|
|
|
|
"""
|
2019-11-16 21:35:20 +00:00
|
|
|
server = self._server._server.resource(self._server.name).connect()
|
2019-11-20 11:50:25 +00:00
|
|
|
return server.history(maxresults=maxresults, mindate=mindate,
|
|
|
|
accountID=self._server.accountID, librarySectionID=self.sectionKey)
|
2019-11-16 21:35:20 +00:00
|
|
|
|
2017-05-27 02:35:33 +00:00
|
|
|
|
|
|
|
class MyPlexServerShare(PlexObject):
|
2017-10-24 19:41:07 +00:00
|
|
|
""" Represents a single user's server reference. Used for library sharing.
|
|
|
|
|
|
|
|
Attributes:
|
|
|
|
id (int): id for this share
|
|
|
|
serverId (str): what id plex uses for this.
|
|
|
|
machineIdentifier (str): The servers machineIdentifier
|
|
|
|
name (str): The servers name
|
|
|
|
lastSeenAt (datetime): Last connected to the server?
|
|
|
|
numLibraries (int): Total number of libraries
|
|
|
|
allLibraries (bool): True if all libraries is shared with this user.
|
|
|
|
owned (bool): 1 if the server is owned by the user
|
|
|
|
pending (bool): True if the invite is pending.
|
|
|
|
|
|
|
|
"""
|
2017-05-27 02:35:33 +00:00
|
|
|
TAG = 'Server'
|
|
|
|
|
|
|
|
def _loadData(self, data):
|
|
|
|
""" Load attribute values from Plex XML response. """
|
|
|
|
self._data = data
|
|
|
|
self.id = utils.cast(int, data.attrib.get('id'))
|
2019-11-16 21:35:20 +00:00
|
|
|
self.accountID = utils.cast(int, data.attrib.get('accountID'))
|
2017-05-27 02:35:33 +00:00
|
|
|
self.serverId = utils.cast(int, data.attrib.get('serverId'))
|
|
|
|
self.machineIdentifier = data.attrib.get('machineIdentifier')
|
|
|
|
self.name = data.attrib.get('name')
|
|
|
|
self.lastSeenAt = utils.toDatetime(data.attrib.get('lastSeenAt'))
|
|
|
|
self.numLibraries = utils.cast(int, data.attrib.get('numLibraries'))
|
2017-10-24 19:41:07 +00:00
|
|
|
self.allLibraries = utils.cast(bool, data.attrib.get('allLibraries'))
|
|
|
|
self.owned = utils.cast(bool, data.attrib.get('owned'))
|
|
|
|
self.pending = utils.cast(bool, data.attrib.get('pending'))
|
2017-01-02 21:06:40 +00:00
|
|
|
|
2019-11-16 21:35:20 +00:00
|
|
|
def section(self, name):
|
|
|
|
""" Returns the :class:`~plexapi.myplex.Section` that matches the name specified.
|
|
|
|
|
|
|
|
Parameters:
|
|
|
|
name (str): Name of the section to return.
|
|
|
|
"""
|
|
|
|
for section in self.sections():
|
|
|
|
if name.lower() == section.title.lower():
|
|
|
|
return section
|
|
|
|
|
|
|
|
raise NotFound('Unable to find section %s' % name)
|
|
|
|
|
2017-09-23 21:11:34 +00:00
|
|
|
def sections(self):
|
2019-11-16 21:35:20 +00:00
|
|
|
""" Returns a list of all :class:`~plexapi.myplex.Section` objects shared with this user.
|
|
|
|
"""
|
2017-09-23 21:11:34 +00:00
|
|
|
url = MyPlexAccount.FRIENDSERVERS.format(machineId=self.machineIdentifier, serverId=self.id)
|
|
|
|
data = self._server.query(url)
|
|
|
|
sections = []
|
2017-10-24 19:41:07 +00:00
|
|
|
|
2017-09-23 21:11:34 +00:00
|
|
|
for section in data.iter('Section'):
|
2017-10-25 16:22:10 +00:00
|
|
|
if ElementTree.iselement(section):
|
2017-09-23 21:11:34 +00:00
|
|
|
sections.append(Section(self, section, url))
|
2017-10-24 19:41:07 +00:00
|
|
|
|
2017-09-23 21:11:34 +00:00
|
|
|
return sections
|
|
|
|
|
2019-11-20 11:50:25 +00:00
|
|
|
def history(self, maxresults=9999999, mindate=None):
|
|
|
|
""" Get all Play History for a user in this shared server.
|
|
|
|
Parameters:
|
|
|
|
maxresults (int): Only return the specified number of results (optional).
|
|
|
|
mindate (datetime): Min datetime to return results from.
|
|
|
|
"""
|
2019-11-16 21:35:20 +00:00
|
|
|
server = self._server.resource(self.name).connect()
|
2019-11-20 11:50:25 +00:00
|
|
|
return server.history(maxresults=maxresults, mindate=mindate, accountID=self.accountID)
|
2019-11-16 21:35:20 +00:00
|
|
|
|
2014-12-29 03:21:58 +00:00
|
|
|
|
2017-02-06 04:52:10 +00:00
|
|
|
class MyPlexResource(PlexObject):
|
2017-01-22 05:19:52 +00:00
|
|
|
""" This object represents resources connected to your Plex server that can provide
|
|
|
|
content such as Plex Media Servers, iPhone or Android clients, etc. The raw xml
|
2018-03-02 18:11:43 +00:00
|
|
|
for the data presented here can be found at:
|
|
|
|
https://plex.tv/api/resources?includeHttps=1&includeRelay=1
|
2017-01-22 05:19:52 +00:00
|
|
|
|
|
|
|
Attributes:
|
2017-02-14 04:32:27 +00:00
|
|
|
TAG (str): 'Device'
|
2018-03-02 18:11:43 +00:00
|
|
|
key (str): 'https://plex.tv/api/resources?includeHttps=1&includeRelay=1'
|
2017-01-22 05:19:52 +00:00
|
|
|
accessToken (str): This resources accesstoken.
|
|
|
|
clientIdentifier (str): Unique ID for this resource.
|
|
|
|
connections (list): List of :class:`~myplex.ResourceConnection` objects
|
|
|
|
for this resource.
|
|
|
|
createdAt (datetime): Timestamp this resource first connected to your server.
|
|
|
|
device (str): Best guess on the type of device this is (PS, iPhone, Linux, etc).
|
|
|
|
home (bool): Unknown
|
|
|
|
lastSeenAt (datetime): Timestamp this resource last connected.
|
|
|
|
name (str): Descriptive name of this resource.
|
|
|
|
owned (bool): True if this resource is one of your own (you logged into it).
|
|
|
|
platform (str): OS the resource is running (Linux, Windows, Chrome, etc.)
|
|
|
|
platformVersion (str): Version of the platform.
|
|
|
|
presence (bool): True if the resource is online
|
|
|
|
product (str): Plex product (Plex Media Server, Plex for iOS, Plex Web, etc.)
|
|
|
|
productVersion (str): Version of the product.
|
|
|
|
provides (str): List of services this resource provides (client, server,
|
|
|
|
player, pubsub-player, etc.)
|
|
|
|
synced (bool): Unknown (possibly True if the resource has synced content?)
|
2017-01-02 21:06:40 +00:00
|
|
|
"""
|
2017-02-13 02:55:55 +00:00
|
|
|
TAG = 'Device'
|
2018-03-02 18:02:22 +00:00
|
|
|
key = 'https://plex.tv/api/resources?includeHttps=1&includeRelay=1'
|
2014-12-29 03:21:58 +00:00
|
|
|
|
2017-02-06 04:52:10 +00:00
|
|
|
def _loadData(self, data):
|
2017-02-04 08:08:47 +00:00
|
|
|
self._data = data
|
2014-12-29 03:21:58 +00:00
|
|
|
self.name = data.attrib.get('name')
|
2017-02-13 06:37:23 +00:00
|
|
|
self.accessToken = logfilter.add_secret(data.attrib.get('accessToken'))
|
2015-06-08 16:41:47 +00:00
|
|
|
self.product = data.attrib.get('product')
|
|
|
|
self.productVersion = data.attrib.get('productVersion')
|
|
|
|
self.platform = data.attrib.get('platform')
|
|
|
|
self.platformVersion = data.attrib.get('platformVersion')
|
|
|
|
self.device = data.attrib.get('device')
|
|
|
|
self.clientIdentifier = data.attrib.get('clientIdentifier')
|
2016-04-07 05:39:04 +00:00
|
|
|
self.createdAt = utils.toDatetime(data.attrib.get('createdAt'))
|
|
|
|
self.lastSeenAt = utils.toDatetime(data.attrib.get('lastSeenAt'))
|
2015-06-08 16:41:47 +00:00
|
|
|
self.provides = data.attrib.get('provides')
|
2016-04-07 05:39:04 +00:00
|
|
|
self.owned = utils.cast(bool, data.attrib.get('owned'))
|
|
|
|
self.home = utils.cast(bool, data.attrib.get('home'))
|
|
|
|
self.synced = utils.cast(bool, data.attrib.get('synced'))
|
|
|
|
self.presence = utils.cast(bool, data.attrib.get('presence'))
|
2017-02-13 02:55:55 +00:00
|
|
|
self.connections = self.findItems(data, ResourceConnection)
|
2018-03-02 18:11:43 +00:00
|
|
|
self.publicAddressMatches = utils.cast(bool, data.attrib.get('publicAddressMatches'))
|
|
|
|
# This seems to only be available if its not your device (say are shared server)
|
|
|
|
self.httpsRequired = utils.cast(bool, data.attrib.get('httpsRequired'))
|
|
|
|
self.ownerid = utils.cast(int, data.attrib.get('ownerId', 0))
|
|
|
|
self.sourceTitle = data.attrib.get('sourceTitle') # owners plex username.
|
2014-12-29 03:21:58 +00:00
|
|
|
|
2017-04-24 02:59:22 +00:00
|
|
|
def connect(self, ssl=None, timeout=None):
|
2017-07-26 23:28:14 +00:00
|
|
|
""" Returns a new :class:`~server.PlexServer` or :class:`~client.PlexClient` object.
|
|
|
|
Often times there is more than one address specified for a server or client.
|
|
|
|
This function will prioritize local connections before remote and HTTPS before HTTP.
|
|
|
|
After trying to connect to all available addresses for this resource and
|
|
|
|
assuming at least one connection was successful, the PlexServer object is built and returned.
|
2017-01-22 05:19:52 +00:00
|
|
|
|
|
|
|
Parameters:
|
|
|
|
ssl (optional): Set True to only connect to HTTPS connections. Set False to
|
|
|
|
only connect to HTTP connections. Set None (default) to connect to any
|
|
|
|
HTTP or HTTPS connection.
|
|
|
|
|
|
|
|
Raises:
|
2018-10-03 10:09:43 +00:00
|
|
|
:class:`plexapi.exceptions.NotFound`: When unable to connect to any addresses for this resource.
|
2017-01-02 21:06:40 +00:00
|
|
|
"""
|
2016-04-02 06:19:32 +00:00
|
|
|
# Sort connections from (https, local) to (http, remote)
|
2015-06-08 16:41:47 +00:00
|
|
|
# Only check non-local connections unless we own the resource
|
2017-01-22 05:19:52 +00:00
|
|
|
connections = sorted(self.connections, key=lambda c: c.local, reverse=True)
|
2017-06-05 22:10:46 +00:00
|
|
|
owned_or_unowned_non_local = lambda x: self.owned or (not self.owned and not x.local)
|
|
|
|
https = [c.uri for c in connections if owned_or_unowned_non_local(c)]
|
|
|
|
http = [c.httpuri for c in connections if owned_or_unowned_non_local(c)]
|
2017-07-30 04:54:13 +00:00
|
|
|
cls = PlexServer if 'server' in self.provides else PlexClient
|
2017-01-22 05:19:52 +00:00
|
|
|
# Force ssl, no ssl, or any (default)
|
|
|
|
if ssl is True: connections = https
|
|
|
|
elif ssl is False: connections = http
|
|
|
|
else: connections = https + http
|
2015-06-08 16:41:47 +00:00
|
|
|
# Try connecting to all known resource connections in parellel, but
|
2014-12-29 03:21:58 +00:00
|
|
|
# only return the first server (in order) that provides a response.
|
2017-07-30 04:54:13 +00:00
|
|
|
listargs = [[cls, url, self.accessToken, timeout] for url in connections]
|
2017-04-24 02:59:22 +00:00
|
|
|
log.info('Testing %s resource connections..', len(listargs))
|
|
|
|
results = utils.threaded(_connect, listargs)
|
|
|
|
return _chooseConnection('Resource', self.name, results)
|
2015-06-08 16:41:47 +00:00
|
|
|
|
|
|
|
|
2017-02-06 04:52:10 +00:00
|
|
|
class ResourceConnection(PlexObject):
|
2017-01-22 05:19:52 +00:00
|
|
|
""" Represents a Resource Connection object found within the
|
|
|
|
:class:`~myplex.MyPlexResource` objects.
|
|
|
|
|
|
|
|
Attributes:
|
2017-02-14 04:32:27 +00:00
|
|
|
TAG (str): 'Connection'
|
2017-01-22 05:19:52 +00:00
|
|
|
address (str): Local IP address
|
|
|
|
httpuri (str): Full local address
|
|
|
|
local (bool): True if local
|
|
|
|
port (int): 32400
|
|
|
|
protocol (str): HTTP or HTTPS
|
|
|
|
uri (str): External address
|
2017-01-02 21:06:40 +00:00
|
|
|
"""
|
2017-02-13 02:55:55 +00:00
|
|
|
TAG = 'Connection'
|
2017-02-06 04:52:10 +00:00
|
|
|
|
|
|
|
def _loadData(self, data):
|
2017-02-04 08:08:47 +00:00
|
|
|
self._data = data
|
2015-06-08 16:41:47 +00:00
|
|
|
self.protocol = data.attrib.get('protocol')
|
|
|
|
self.address = data.attrib.get('address')
|
2016-04-07 05:39:04 +00:00
|
|
|
self.port = utils.cast(int, data.attrib.get('port'))
|
2015-06-08 16:41:47 +00:00
|
|
|
self.uri = data.attrib.get('uri')
|
2016-04-07 05:39:04 +00:00
|
|
|
self.local = utils.cast(bool, data.attrib.get('local'))
|
2016-04-02 06:19:32 +00:00
|
|
|
self.httpuri = 'http://%s:%s' % (self.address, self.port)
|
2018-03-02 18:02:22 +00:00
|
|
|
self.relay = utils.cast(bool, data.attrib.get('relay'))
|
2015-06-09 04:17:55 +00:00
|
|
|
|
2015-02-20 20:06:41 +00:00
|
|
|
|
2017-02-06 04:52:10 +00:00
|
|
|
class MyPlexDevice(PlexObject):
|
2017-01-22 05:19:52 +00:00
|
|
|
""" This object represents resources connected to your Plex server that provide
|
|
|
|
playback ability from your Plex Server, iPhone or Android clients, Plex Web,
|
|
|
|
this API, etc. The raw xml for the data presented here can be found at:
|
|
|
|
https://plex.tv/devices.xml
|
|
|
|
|
|
|
|
Attributes:
|
2017-02-14 04:32:27 +00:00
|
|
|
TAG (str): 'Device'
|
|
|
|
key (str): 'https://plex.tv/devices.xml'
|
2017-01-22 05:19:52 +00:00
|
|
|
clientIdentifier (str): Unique ID for this resource.
|
|
|
|
connections (list): List of connection URIs for the device.
|
|
|
|
device (str): Best guess on the type of device this is (Linux, iPad, AFTB, etc).
|
|
|
|
id (str): MyPlex ID of the device.
|
|
|
|
model (str): Model of the device (bueller, Linux, x86_64, etc.)
|
|
|
|
name (str): Hostname of the device.
|
|
|
|
platform (str): OS the resource is running (Linux, Windows, Chrome, etc.)
|
|
|
|
platformVersion (str): Version of the platform.
|
|
|
|
product (str): Plex product (Plex Media Server, Plex for iOS, Plex Web, etc.)
|
|
|
|
productVersion (string): Version of the product.
|
|
|
|
provides (str): List of services this resource provides (client, controller,
|
|
|
|
sync-target, player, pubsub-player).
|
|
|
|
publicAddress (str): Public IP address.
|
|
|
|
screenDensity (str): Unknown
|
|
|
|
screenResolution (str): Screen resolution (750x1334, 1242x2208, etc.)
|
|
|
|
token (str): Plex authentication token for the device.
|
|
|
|
vendor (str): Device vendor (ubuntu, etc).
|
|
|
|
version (str): Unknown (1, 2, 1.3.3.3148-b38628e, 1.3.15, etc.)
|
2017-01-02 21:06:40 +00:00
|
|
|
"""
|
2017-02-13 02:55:55 +00:00
|
|
|
TAG = 'Device'
|
2017-02-06 04:52:10 +00:00
|
|
|
key = 'https://plex.tv/devices.xml'
|
2015-09-29 18:14:30 +00:00
|
|
|
|
2017-02-06 04:52:10 +00:00
|
|
|
def _loadData(self, data):
|
2017-02-04 08:08:47 +00:00
|
|
|
self._data = data
|
2015-09-29 18:14:30 +00:00
|
|
|
self.name = data.attrib.get('name')
|
|
|
|
self.publicAddress = data.attrib.get('publicAddress')
|
|
|
|
self.product = data.attrib.get('product')
|
|
|
|
self.productVersion = data.attrib.get('productVersion')
|
|
|
|
self.platform = data.attrib.get('platform')
|
|
|
|
self.platformVersion = data.attrib.get('platformVersion')
|
|
|
|
self.device = data.attrib.get('device')
|
|
|
|
self.model = data.attrib.get('model')
|
|
|
|
self.vendor = data.attrib.get('vendor')
|
2016-04-07 05:39:04 +00:00
|
|
|
self.provides = data.attrib.get('provides')
|
2015-09-29 18:14:30 +00:00
|
|
|
self.clientIdentifier = data.attrib.get('clientIdentifier')
|
|
|
|
self.version = data.attrib.get('version')
|
|
|
|
self.id = data.attrib.get('id')
|
2017-02-13 06:37:23 +00:00
|
|
|
self.token = logfilter.add_secret(data.attrib.get('token'))
|
2015-09-29 18:14:30 +00:00
|
|
|
self.screenResolution = data.attrib.get('screenResolution')
|
|
|
|
self.screenDensity = data.attrib.get('screenDensity')
|
2017-02-25 07:37:30 +00:00
|
|
|
self.createdAt = utils.toDatetime(data.attrib.get('createdAt'))
|
|
|
|
self.lastSeenAt = utils.toDatetime(data.attrib.get('lastSeenAt'))
|
2017-01-22 05:19:52 +00:00
|
|
|
self.connections = [connection.attrib.get('uri') for connection in data.iter('Connection')]
|
2015-09-29 18:14:30 +00:00
|
|
|
|
2017-04-24 02:59:22 +00:00
|
|
|
def connect(self, timeout=None):
|
2017-07-26 23:28:14 +00:00
|
|
|
""" Returns a new :class:`~plexapi.client.PlexClient` or :class:`~plexapi.server.PlexServer`
|
|
|
|
Sometimes there is more than one address specified for a server or client.
|
|
|
|
After trying to connect to all available addresses for this client and assuming
|
|
|
|
at least one connection was successful, the PlexClient object is built and returned.
|
2017-01-02 21:06:40 +00:00
|
|
|
|
2017-01-22 05:19:52 +00:00
|
|
|
Raises:
|
2018-10-03 10:09:43 +00:00
|
|
|
:class:`plexapi.exceptions.NotFound`: When unable to connect to any addresses for this device.
|
2017-01-02 21:06:40 +00:00
|
|
|
"""
|
2017-07-30 04:54:13 +00:00
|
|
|
cls = PlexServer if 'server' in self.provides else PlexClient
|
|
|
|
listargs = [[cls, url, self.token, timeout] for url in self.connections]
|
2017-04-24 02:59:22 +00:00
|
|
|
log.info('Testing %s device connections..', len(listargs))
|
|
|
|
results = utils.threaded(_connect, listargs)
|
2018-04-03 21:08:17 +00:00
|
|
|
return _chooseConnection('Device', self.name, results)
|
2017-02-25 07:37:30 +00:00
|
|
|
|
|
|
|
def delete(self):
|
|
|
|
""" Remove this device from your account. """
|
|
|
|
key = 'https://plex.tv/devices/%s.xml' % self.id
|
|
|
|
self._server.query(key, self._server._session.delete)
|
2017-04-24 02:59:22 +00:00
|
|
|
|
2018-09-08 15:25:16 +00:00
|
|
|
def syncItems(self):
|
|
|
|
""" Returns an instance of :class:`plexapi.sync.SyncList` for current device.
|
|
|
|
|
|
|
|
Raises:
|
2018-10-03 10:09:43 +00:00
|
|
|
:class:`plexapi.exceptions.BadRequest`: when the device doesn`t provides `sync-target`.
|
2018-09-08 15:25:16 +00:00
|
|
|
"""
|
|
|
|
if 'sync-target' not in self.provides:
|
|
|
|
raise BadRequest('Requested syncList for device which do not provides sync-target')
|
|
|
|
|
|
|
|
return self._server.syncItems(client=self)
|
|
|
|
|
2017-04-24 02:59:22 +00:00
|
|
|
|
2018-09-14 18:28:35 +00:00
|
|
|
def _connect(cls, url, token, timeout, results, i, job_is_done_event=None):
|
2017-04-24 02:59:22 +00:00
|
|
|
""" Connects to the specified cls with url and token. Stores the connection
|
|
|
|
information to results[i] in a threadsafe way.
|
2018-09-14 18:28:35 +00:00
|
|
|
|
|
|
|
Arguments:
|
|
|
|
cls: the class which is responsible for establishing connection, basically it's
|
|
|
|
:class:`~plexapi.client.PlexClient` or :class:`~plexapi.server.PlexServer`
|
|
|
|
url (str): url which should be passed as `baseurl` argument to cls.__init__()
|
|
|
|
token (str): authentication token which should be passed as `baseurl` argument to cls.__init__()
|
|
|
|
timeout (int): timeout which should be passed as `baseurl` argument to cls.__init__()
|
|
|
|
results (list): pre-filled list for results
|
|
|
|
i (int): index of current job, should be less than len(results)
|
|
|
|
job_is_done_event (:class:`~threading.Event`): is X_PLEX_ENABLE_FAST_CONNECT is True then the
|
|
|
|
event would be set as soon the connection is established
|
2017-04-24 02:59:22 +00:00
|
|
|
"""
|
|
|
|
starttime = time.time()
|
|
|
|
try:
|
|
|
|
device = cls(baseurl=url, token=token, timeout=timeout)
|
|
|
|
runtime = int(time.time() - starttime)
|
|
|
|
results[i] = (url, token, device, runtime)
|
2018-09-14 18:28:35 +00:00
|
|
|
if X_PLEX_ENABLE_FAST_CONNECT and job_is_done_event:
|
|
|
|
job_is_done_event.set()
|
2017-04-24 02:59:22 +00:00
|
|
|
except Exception as err:
|
|
|
|
runtime = int(time.time() - starttime)
|
|
|
|
log.error('%s: %s', url, err)
|
|
|
|
results[i] = (url, token, None, runtime)
|
|
|
|
|
|
|
|
|
|
|
|
def _chooseConnection(ctype, name, results):
|
|
|
|
""" Chooses the first (best) connection from the given _connect results. """
|
|
|
|
# At this point we have a list of result tuples containing (url, token, PlexServer, runtime)
|
|
|
|
# or (url, token, None, runtime) in the case a connection could not be established.
|
|
|
|
for url, token, result, runtime in results:
|
|
|
|
okerr = 'OK' if result else 'ERR'
|
|
|
|
log.info('%s connection %s (%ss): %s?X-Plex-Token=%s', ctype, okerr, runtime, url, token)
|
|
|
|
results = [r[2] for r in results if r and r[2] is not None]
|
|
|
|
if results:
|
|
|
|
log.info('Connecting to %s: %s?X-Plex-Token=%s', ctype, results[0]._baseurl, results[0]._token)
|
|
|
|
return results[0]
|
|
|
|
raise NotFound('Unable to connect to %s: %s' % (ctype.lower(), name))
|