2016-03-21 04:26:02 +00:00
|
|
|
# -*- coding: utf-8 -*-
|
2017-02-25 06:56:12 +00:00
|
|
|
import copy
|
2022-05-18 18:04:18 +00:00
|
|
|
import html
|
2019-12-06 14:36:32 +00:00
|
|
|
import threading
|
2017-04-24 02:59:22 +00:00
|
|
|
import time
|
2022-07-21 02:37:48 +00:00
|
|
|
from urllib.parse import parse_qsl, urlencode, urlsplit, urlunsplit
|
2020-05-12 21:15:16 +00:00
|
|
|
from xml.etree import ElementTree
|
2020-03-14 14:52:54 +00:00
|
|
|
|
|
|
|
import requests
|
2023-05-24 21:50:30 +00:00
|
|
|
|
|
|
|
from plexapi import (BASE_HEADERS, CONFIG, TIMEOUT, X_PLEX_ENABLE_FAST_CONNECT, X_PLEX_IDENTIFIER,
|
|
|
|
log, logfilter, utils)
|
2017-02-06 04:52:10 +00:00
|
|
|
from plexapi.base import PlexObject
|
2016-04-02 06:19:32 +00:00
|
|
|
from plexapi.client import PlexClient
|
2020-05-12 21:15:16 +00:00
|
|
|
from plexapi.exceptions import BadRequest, NotFound, Unauthorized
|
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
|
2020-04-28 16:52:09 +00:00
|
|
|
from plexapi.sonos import PlexSonosClient
|
2020-03-14 14:52:54 +00:00
|
|
|
from plexapi.sync import SyncItem, SyncList
|
|
|
|
from requests.status_codes import _codes as codes
|
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
|
2023-07-27 21:00:46 +00:00
|
|
|
the myplex.tv servers at the url https://plex.tv/api/v2/user. You may create this object
|
2017-06-05 02:01:07 +00:00
|
|
|
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:
|
2023-07-27 21:00:46 +00:00
|
|
|
username (str): Plex login username if not using a token.
|
|
|
|
password (str): Plex login password if not using a token.
|
|
|
|
token (str): Plex authentication token instead of username and password.
|
2017-04-24 02:59:22 +00:00
|
|
|
session (requests.Session, optional): Use your own session object if you want to
|
2023-07-27 21:00:46 +00:00
|
|
|
cache the http responses from PMS.
|
2017-04-24 02:59:22 +00:00
|
|
|
timeout (int): timeout in seconds on initial connect to myplex (default config.TIMEOUT).
|
2023-07-27 21:00:46 +00:00
|
|
|
code (str): Two-factor authentication code to use when logging in with username and password.
|
|
|
|
remember (bool): Remember the account token for 14 days (Default True).
|
2017-04-24 02:59:22 +00:00
|
|
|
|
2017-01-09 06:35:29 +00:00
|
|
|
Attributes:
|
2023-07-27 21:00:46 +00:00
|
|
|
key (str): 'https://plex.tv/api/v2/user'
|
|
|
|
adsConsent (str): Unknown.
|
|
|
|
adsConsentReminderAt (str): Unknown.
|
|
|
|
adsConsentSetAt (str): Unknown.
|
|
|
|
anonymous (str): Unknown.
|
|
|
|
authToken (str): The account token.
|
|
|
|
backupCodesCreated (bool): If the two-factor authentication backup codes have been created.
|
|
|
|
confirmed (bool): If the account has been confirmed.
|
|
|
|
country (str): The account country.
|
|
|
|
email (str): The account email address.
|
|
|
|
emailOnlyAuth (bool): If login with email only is enabled.
|
|
|
|
experimentalFeatures (bool): If experimental features are enabled.
|
|
|
|
friendlyName (str): Your account full name.
|
2017-01-10 06:54:19 +00:00
|
|
|
entitlements (List<str>): List of devices your allowed to use with this account.
|
2023-07-27 21:00:46 +00:00
|
|
|
guest (bool): If the account is a Plex Home guest user.
|
|
|
|
hasPassword (bool): If the account has a password.
|
|
|
|
home (bool): If the account is a Plex Home user.
|
|
|
|
homeAdmin (bool): If the account is the Plex Home admin.
|
|
|
|
homeSize (int): The number of accounts in the Plex Home.
|
|
|
|
id (int): The Plex account ID.
|
|
|
|
joinedAt (datetime): Date the account joined Plex.
|
|
|
|
locale (str): the account locale
|
|
|
|
mailingListActive (bool): If you are subscribed to the Plex newsletter.
|
|
|
|
mailingListStatus (str): Your current mailing list status.
|
|
|
|
maxHomeSize (int): The maximum number of accounts allowed in the Plex Home.
|
2022-11-08 23:57:54 +00:00
|
|
|
pin (str): The hashed Plex Home PIN.
|
2023-07-27 21:00:46 +00:00
|
|
|
profileAutoSelectAudio (bool): If the account has automatically select audio and subtitle tracks enabled.
|
|
|
|
profileDefaultAudioLanguage (str): The preferred audio language for the account.
|
|
|
|
profileDefaultSubtitleLanguage (str): The preferred subtitle language for the account.
|
|
|
|
profileAutoSelectSubtitle (int): The auto-select subtitle mode
|
|
|
|
(0 = Manually selected, 1 = Shown with foreign audio, 2 = Always enabled).
|
|
|
|
profileDefaultSubtitleAccessibility (int): The subtitles for the deaf or hard-of-hearing (SDH) searches mode
|
|
|
|
(0 = Prefer non-SDH subtitles, 1 = Prefer SDH subtitles, 2 = Only show SDH subtitles,
|
|
|
|
3 = Only shown non-SDH subtitles).
|
|
|
|
profileDefaultSubtitleForced (int): The forced subtitles searches mode
|
|
|
|
(0 = Prefer non-forced subtitles, 1 = Prefer forced subtitles, 2 = Only show forced subtitles,
|
|
|
|
3 = Only show non-forced subtitles).
|
|
|
|
protected (bool): If the account has a Plex Home PIN enabled.
|
|
|
|
rememberExpiresAt (datetime): Date the token expires.
|
|
|
|
restricted (bool): If the account is a Plex Home managed user.
|
2017-01-10 06:54:19 +00:00
|
|
|
roles: (List<str>) Lit of account roles. Plexpass membership listed here.
|
2023-07-27 21:00:46 +00:00
|
|
|
scrobbleTypes (List<int>): Unknown.
|
|
|
|
subscriptionActive (bool): If the account's Plex Pass subscription is active.
|
|
|
|
subscriptionDescription (str): Description of the Plex Pass subscription.
|
|
|
|
subscriptionFeatures: (List<str>) List of features allowed on your Plex Pass subscription.
|
|
|
|
subscriptionPaymentService (str): Payment service used for your Plex Pass subscription.
|
|
|
|
subscriptionPlan (str): Name of Plex Pass subscription plan.
|
|
|
|
subscriptionStatus (str): String representation of ``subscriptionActive``.
|
|
|
|
subscriptionSubscribedAt (datetime): Date the account subscribed to Plex Pass.
|
|
|
|
thumb (str): URL of the account thumbnail.
|
|
|
|
title (str): The title of the account (username or friendly name).
|
|
|
|
twoFactorEnabled (bool): If two-factor authentication is enabled.
|
|
|
|
username (str): The account username.
|
|
|
|
uuid (str): The account UUID.
|
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
|
2022-07-21 02:05:29 +00:00
|
|
|
HOMEUSERS = 'https://plex.tv/api/home/users'
|
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
|
2022-11-08 23:57:54 +00:00
|
|
|
HOMEUSER = 'https://plex.tv/api/home/users/{userId}' # delete, put
|
|
|
|
MANAGEDHOMEUSER = 'https://plex.tv/api/v2/home/users/restricted/{userId}' # put
|
2023-07-27 21:00:46 +00:00
|
|
|
SIGNIN = 'https://plex.tv/api/v2/users/signin' # post with auth
|
|
|
|
SIGNOUT = 'https://plex.tv/api/v2/users/signout' # delete
|
2017-05-27 02:35:33 +00:00
|
|
|
WEBHOOKS = 'https://plex.tv/api/v2/user/webhooks' # get, post with data
|
2022-05-18 18:04:18 +00:00
|
|
|
OPTOUTS = 'https://plex.tv/api/v2/user/{userUUID}/settings/opt_outs' # get
|
2020-12-16 04:41:04 +00:00
|
|
|
LINK = 'https://plex.tv/api/v2/pins/link' # put
|
2022-08-26 19:00:46 +00:00
|
|
|
VIEWSTATESYNC = 'https://plex.tv/api/v2/user/view_state_sync' # put
|
2019-12-05 17:54:18 +00:00
|
|
|
# Hub sections
|
2022-05-18 18:04:18 +00:00
|
|
|
VOD = 'https://vod.provider.plex.tv' # get
|
|
|
|
MUSIC = 'https://music.provider.plex.tv' # get
|
|
|
|
METADATA = 'https://metadata.provider.plex.tv'
|
2023-07-27 21:00:46 +00:00
|
|
|
key = 'https://plex.tv/api/v2/user'
|
2017-01-02 21:06:40 +00:00
|
|
|
|
2023-07-27 21:00:46 +00:00
|
|
|
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'))
|
2017-01-09 14:21:54 +00:00
|
|
|
self._session = session or requests.Session()
|
2020-04-28 20:17:59 +00:00
|
|
|
self._sonos_cache = []
|
|
|
|
self._sonos_cache_timestamp = 0
|
2023-07-27 21:00:46 +00:00
|
|
|
data, initpath = self._signin(username, password, code, remember, timeout)
|
2017-05-19 03:04:57 +00:00
|
|
|
super(MyPlexAccount, self).__init__(self, data, initpath)
|
|
|
|
|
2023-07-27 21:00:46 +00:00
|
|
|
def _signin(self, username, password, code, remember, timeout):
|
2017-05-19 03:04:57 +00:00
|
|
|
if self._token:
|
|
|
|
return self.query(self.key), self.key
|
2023-07-27 21:00:46 +00:00
|
|
|
payload = {
|
|
|
|
'login': username or CONFIG.get('auth.myplex_username'),
|
|
|
|
'password': password or CONFIG.get('auth.myplex_password'),
|
|
|
|
'rememberMe': remember
|
|
|
|
}
|
2022-12-21 19:44:34 +00:00
|
|
|
if code:
|
2023-07-27 21:00:46 +00:00
|
|
|
payload['verificationCode'] = code
|
|
|
|
data = self.query(self.SIGNIN, method=self._session.post, data=payload, timeout=timeout)
|
2017-05-19 03:04:57 +00:00
|
|
|
return data, self.SIGNIN
|
2017-02-06 04:52:10 +00:00
|
|
|
|
2023-07-27 21:00:46 +00:00
|
|
|
def signout(self):
|
|
|
|
""" Sign out of the Plex account. Invalidates the authentication token. """
|
|
|
|
return self.query(self.SIGNOUT, method=self._session.delete)
|
|
|
|
|
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
|
2023-07-27 21:00:46 +00:00
|
|
|
self._token = logfilter.add_secret(data.attrib.get('authToken'))
|
2017-02-25 06:56:12 +00:00
|
|
|
self._webhooks = []
|
2023-07-27 21:00:46 +00:00
|
|
|
|
|
|
|
self.adsConsent = data.attrib.get('adsConsent')
|
|
|
|
self.adsConsentReminderAt = data.attrib.get('adsConsentReminderAt')
|
|
|
|
self.adsConsentSetAt = data.attrib.get('adsConsentSetAt')
|
|
|
|
self.anonymous = data.attrib.get('anonymous')
|
|
|
|
self.authToken = self._token
|
|
|
|
self.backupCodesCreated = utils.cast(bool, data.attrib.get('backupCodesCreated'))
|
|
|
|
self.confirmed = utils.cast(bool, data.attrib.get('confirmed'))
|
|
|
|
self.country = data.attrib.get('country')
|
2014-12-29 03:21:58 +00:00
|
|
|
self.email = data.attrib.get('email')
|
2023-07-27 21:00:46 +00:00
|
|
|
self.emailOnlyAuth = utils.cast(bool, data.attrib.get('emailOnlyAuth'))
|
|
|
|
self.experimentalFeatures = utils.cast(bool, data.attrib.get('experimentalFeatures'))
|
|
|
|
self.friendlyName = data.attrib.get('friendlyName')
|
2016-04-07 05:39:04 +00:00
|
|
|
self.guest = utils.cast(bool, data.attrib.get('guest'))
|
2023-07-27 21:00:46 +00:00
|
|
|
self.hasPassword = utils.cast(bool, data.attrib.get('hasPassword'))
|
2016-04-07 05:39:04 +00:00
|
|
|
self.home = utils.cast(bool, data.attrib.get('home'))
|
2023-07-27 21:00:46 +00:00
|
|
|
self.homeAdmin = utils.cast(bool, data.attrib.get('homeAdmin'))
|
2016-04-07 05:39:04 +00:00
|
|
|
self.homeSize = utils.cast(int, data.attrib.get('homeSize'))
|
2021-01-03 00:44:02 +00:00
|
|
|
self.id = utils.cast(int, data.attrib.get('id'))
|
2023-07-27 21:00:46 +00:00
|
|
|
self.joinedAt = utils.toDatetime(data.attrib.get('joinedAt'))
|
2016-04-04 02:46:25 +00:00
|
|
|
self.locale = data.attrib.get('locale')
|
2023-07-27 21:00:46 +00:00
|
|
|
self.mailingListActive = utils.cast(bool, data.attrib.get('mailingListActive'))
|
|
|
|
self.mailingListStatus = data.attrib.get('mailingListStatus')
|
2016-04-07 05:39:04 +00:00
|
|
|
self.maxHomeSize = utils.cast(int, data.attrib.get('maxHomeSize'))
|
2022-11-08 23:57:54 +00:00
|
|
|
self.pin = data.attrib.get('pin')
|
2023-07-27 21:00:46 +00:00
|
|
|
self.protected = utils.cast(bool, data.attrib.get('protected'))
|
|
|
|
self.rememberExpiresAt = utils.toDatetime(data.attrib.get('rememberExpiresAt'))
|
2016-04-07 05:39:04 +00:00
|
|
|
self.restricted = utils.cast(bool, data.attrib.get('restricted'))
|
2023-07-27 21:00:46 +00:00
|
|
|
self.scrobbleTypes = [utils.cast(int, x) for x in data.attrib.get('scrobbleTypes').split(',')]
|
2016-04-07 05:39:04 +00:00
|
|
|
self.thumb = data.attrib.get('thumb')
|
|
|
|
self.title = data.attrib.get('title')
|
2023-07-27 21:00:46 +00:00
|
|
|
self.twoFactorEnabled = utils.cast(bool, data.attrib.get('twoFactorEnabled'))
|
2016-04-07 05:39:04 +00:00
|
|
|
self.username = data.attrib.get('username')
|
|
|
|
self.uuid = data.attrib.get('uuid')
|
2018-09-08 15:28:26 +00:00
|
|
|
|
2021-05-25 00:37:37 +00:00
|
|
|
subscription = data.find('subscription')
|
2018-09-08 15:28:26 +00:00
|
|
|
self.subscriptionActive = utils.cast(bool, subscription.attrib.get('active'))
|
2023-07-27 21:00:46 +00:00
|
|
|
self.subscriptionDescription = data.attrib.get('subscriptionDescription')
|
|
|
|
self.subscriptionFeatures = self.listAttrs(subscription, 'id', rtag='features', etag='feature')
|
|
|
|
self.subscriptionPaymentService = subscription.attrib.get('paymentService')
|
2018-09-08 15:28:26 +00:00
|
|
|
self.subscriptionPlan = subscription.attrib.get('plan')
|
2023-07-27 21:00:46 +00:00
|
|
|
self.subscriptionStatus = subscription.attrib.get('status')
|
|
|
|
self.subscriptionSubscribedAt = utils.toDatetime(subscription.attrib.get('subscribedAt'), '%Y-%m-%d %H:%M:%S %Z')
|
2018-09-08 15:28:26 +00:00
|
|
|
|
2023-07-27 21:00:46 +00:00
|
|
|
profile = data.find('profile')
|
|
|
|
self.profileAutoSelectAudio = utils.cast(bool, profile.attrib.get('autoSelectAudio'))
|
|
|
|
self.profileDefaultAudioLanguage = profile.attrib.get('defaultAudioLanguage')
|
|
|
|
self.profileDefaultSubtitleLanguage = profile.attrib.get('defaultSubtitleLanguage')
|
|
|
|
self.profileAutoSelectSubtitle = utils.cast(int, profile.attrib.get('autoSelectSubtitle'))
|
|
|
|
self.profileDefaultSubtitleAccessibility = utils.cast(int, profile.attrib.get('defaultSubtitleAccessibility'))
|
|
|
|
self.profileDefaultSubtitleForces = utils.cast(int, profile.attrib.get('defaultSubtitleForces'))
|
2018-09-08 15:28:26 +00:00
|
|
|
|
2021-06-14 04:58:13 +00:00
|
|
|
self.entitlements = self.listAttrs(data, 'id', rtag='entitlements', etag='entitlement')
|
2023-07-27 21:00:46 +00:00
|
|
|
self.roles = self.listAttrs(data, 'id', rtag='roles', etag='role')
|
2018-09-08 15:28:26 +00:00
|
|
|
|
2023-07-27 21:00:46 +00:00
|
|
|
# TODO: Fetch missing MyPlexAccount services
|
2018-09-08 15:28:26 +00:00
|
|
|
self.services = None
|
2017-01-02 21:06:40 +00:00
|
|
|
|
2023-07-27 21:00:46 +00:00
|
|
|
@property
|
|
|
|
def authenticationToken(self):
|
|
|
|
""" Returns the authentication token for the account. Alias for ``authToken``. """
|
|
|
|
return self.authToken
|
2017-01-22 05:19:52 +00:00
|
|
|
|
2023-07-27 21:00:46 +00:00
|
|
|
def _reload(self, key=None, **kwargs):
|
|
|
|
""" Perform the actual reload. """
|
|
|
|
data = self.query(self.key)
|
|
|
|
self._loadData(data)
|
|
|
|
return self
|
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', ' ')
|
2022-08-28 05:56:01 +00:00
|
|
|
message = f'({response.status_code}) {codename}; {response.url} {errtext}'
|
2020-04-09 20:56:26 +00:00
|
|
|
if response.status_code == 401:
|
|
|
|
raise Unauthorized(message)
|
2020-04-15 22:09:27 +00:00
|
|
|
elif response.status_code == 404:
|
|
|
|
raise NotFound(message)
|
2023-05-24 19:04:32 +00:00
|
|
|
elif response.status_code == 422 and "Invalid token" in response.text:
|
|
|
|
raise Unauthorized(message)
|
2020-04-09 20:56:26 +00:00
|
|
|
else:
|
|
|
|
raise BadRequest(message)
|
2023-08-27 19:34:52 +00:00
|
|
|
if 'application/json' in response.headers.get('Content-Type', ''):
|
2022-05-18 18:04:18 +00:00
|
|
|
return response.json()
|
2023-08-27 19:34:52 +00:00
|
|
|
elif 'text/plain' in response.headers.get('Content-Type', ''):
|
|
|
|
return response.text.strip()
|
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
|
|
|
|
2023-07-27 21:00:46 +00:00
|
|
|
def device(self, name=None, clientId=None):
|
|
|
|
""" Returns the :class:`~plexapi.myplex.MyPlexDevice` that matches the name specified.
|
|
|
|
|
|
|
|
Parameters:
|
|
|
|
name (str): Name to match against.
|
|
|
|
clientId (str): clientIdentifier to match against.
|
|
|
|
"""
|
|
|
|
for device in self.devices():
|
|
|
|
if (name and device.name.lower() == name.lower() or device.clientIdentifier == clientId):
|
|
|
|
return device
|
|
|
|
raise NotFound(f'Unable to find device {name}')
|
|
|
|
|
|
|
|
def devices(self):
|
|
|
|
""" Returns a list of all :class:`~plexapi.myplex.MyPlexDevice` objects connected to the server. """
|
|
|
|
data = self.query(MyPlexDevice.key)
|
|
|
|
return [MyPlexDevice(self, elem) for elem in data]
|
|
|
|
|
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
|
2022-08-28 05:56:01 +00:00
|
|
|
raise NotFound(f'Unable to find resource {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
|
|
|
|
2020-04-28 16:52:09 +00:00
|
|
|
def sonos_speakers(self):
|
|
|
|
if 'companions_sonos' not in self.subscriptionFeatures:
|
|
|
|
return []
|
2020-04-28 20:17:59 +00:00
|
|
|
|
|
|
|
t = time.time()
|
2020-05-27 14:36:55 +00:00
|
|
|
if t - self._sonos_cache_timestamp > 5:
|
2020-04-28 20:17:59 +00:00
|
|
|
self._sonos_cache_timestamp = t
|
|
|
|
data = self.query('https://sonos.plex.tv/resources')
|
|
|
|
self._sonos_cache = [PlexSonosClient(self, elem) for elem in data]
|
|
|
|
|
|
|
|
return self._sonos_cache
|
|
|
|
|
|
|
|
def sonos_speaker(self, name):
|
2020-05-15 13:45:46 +00:00
|
|
|
return next((x for x in self.sonos_speakers() if x.title.split("+")[0].strip() == name), None)
|
2020-04-28 20:17:59 +00:00
|
|
|
|
|
|
|
def sonos_speaker_by_id(self, identifier):
|
2020-05-26 20:09:39 +00:00
|
|
|
return next((x for x in self.sonos_speakers() if x.machineIdentifier.startswith(identifier)), None)
|
2020-04-28 16:52:09 +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:
|
2021-02-27 06:51:22 +00:00
|
|
|
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.
|
2022-05-16 20:39:42 +00:00
|
|
|
sections (List<:class:`~plexapi.library.LibrarySection`>): List of `LibrarySection` objects, or names
|
2021-02-27 06:51:22 +00:00
|
|
|
to be shared (default None). `sections` must be defined in order to update shared libraries.
|
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
|
2021-02-27 06:51:22 +00:00
|
|
|
values to be filtered. ex: `{'contentRating':['G'], 'label':['foo']}`
|
2017-05-27 02:35:33 +00:00
|
|
|
filterTelevision (Dict): Dict containing key 'contentRating' and/or 'label' each set to a list of
|
2021-02-27 06:51:22 +00:00
|
|
|
values to be filtered. ex: `{'contentRating':['G'], 'label':['foo']}`
|
2017-05-27 02:35:33 +00:00
|
|
|
filterMusic (Dict): Dict containing key 'label' set to a list of values to be filtered.
|
2021-02-27 06:51:22 +00:00
|
|
|
ex: `{'label':['foo']}`
|
2017-05-27 02:35:33 +00:00
|
|
|
"""
|
|
|
|
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:
|
2021-02-27 06:51:22 +00:00
|
|
|
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.
|
2022-05-16 20:39:42 +00:00
|
|
|
sections (List<:class:`~plexapi.library.LibrarySection`>): List of `LibrarySection` objects, or names
|
2021-02-27 06:51:22 +00:00
|
|
|
to be shared (default None). `sections` must be defined in order to update shared libraries.
|
2019-07-25 12:14:21 +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
|
2021-02-27 06:51:22 +00:00
|
|
|
values to be filtered. ex: `{'contentRating':['G'], 'label':['foo']}`
|
2019-07-25 12:14:21 +00:00
|
|
|
filterTelevision (Dict): Dict containing key 'contentRating' and/or 'label' each set to a list of
|
2021-02-27 06:51:22 +00:00
|
|
|
values to be filtered. ex: `{'contentRating':['G'], 'label':['foo']}`
|
2019-07-25 12:14:21 +00:00
|
|
|
filterMusic (Dict): Dict containing key 'label' set to a list of values to be filtered.
|
2021-02-27 06:51:22 +00:00
|
|
|
ex: `{'label':['foo']}`
|
2019-07-25 12:14:21 +00:00
|
|
|
"""
|
|
|
|
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:
|
2021-02-27 06:51:22 +00:00
|
|
|
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.
|
2022-05-16 20:39:42 +00:00
|
|
|
sections (List<:class:`~plexapi.library.LibrarySection`>): List of `LibrarySection` objects, or names
|
2021-02-27 06:51:22 +00:00
|
|
|
to be shared (default None). `sections` must be defined in order to update shared libraries.
|
2019-07-25 12:25:32 +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
|
2021-02-27 06:51:22 +00:00
|
|
|
values to be filtered. ex: `{'contentRating':['G'], 'label':['foo']}`
|
2019-07-25 12:25:32 +00:00
|
|
|
filterTelevision (Dict): Dict containing key 'contentRating' and/or 'label' each set to a list of
|
2021-02-27 06:51:22 +00:00
|
|
|
values to be filtered. ex: `{'contentRating':['G'], 'label':['foo']}`
|
2019-07-25 12:25:32 +00:00
|
|
|
filterMusic (Dict): Dict containing key 'label' set to a list of values to be filtered.
|
2021-02-27 06:51:22 +00:00
|
|
|
ex: `{'label':['foo']}`
|
2019-07-25 12:25:32 +00:00
|
|
|
"""
|
|
|
|
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):
|
2021-11-21 00:16:01 +00:00
|
|
|
""" Remove the specified user from your friends.
|
2017-05-27 02:35:33 +00:00
|
|
|
|
|
|
|
Parameters:
|
2022-07-21 02:05:29 +00:00
|
|
|
user (:class:`~plexapi.myplex.MyPlexUser` or str): :class:`~plexapi.myplex.MyPlexUser`,
|
|
|
|
username, or email of the user to be removed.
|
2017-05-27 02:35:33 +00:00
|
|
|
"""
|
2021-11-21 00:16:01 +00:00
|
|
|
user = user if isinstance(user, MyPlexUser) else self.user(user)
|
|
|
|
url = self.FRIENDUPDATE.format(userId=user.id)
|
2017-05-27 02:35:33 +00:00
|
|
|
return self.query(url, self._session.delete)
|
|
|
|
|
2019-07-25 12:33:56 +00:00
|
|
|
def removeHomeUser(self, user):
|
2021-11-21 00:16:01 +00:00
|
|
|
""" Remove the specified user from your home users.
|
2019-07-25 12:33:56 +00:00
|
|
|
|
|
|
|
Parameters:
|
2022-07-21 02:05:29 +00:00
|
|
|
user (:class:`~plexapi.myplex.MyPlexUser` or str): :class:`~plexapi.myplex.MyPlexUser`,
|
|
|
|
username, or email of the user to be removed.
|
2019-07-25 12:33:56 +00:00
|
|
|
"""
|
2021-11-21 00:16:01 +00:00
|
|
|
user = user if isinstance(user, MyPlexUser) else self.user(user)
|
2022-11-08 23:57:54 +00:00
|
|
|
url = self.HOMEUSER.format(userId=user.id)
|
2019-07-25 12:33:56 +00:00
|
|
|
return self.query(url, self._session.delete)
|
|
|
|
|
2022-12-21 21:57:23 +00:00
|
|
|
def switchHomeUser(self, user, pin=None):
|
2022-07-21 02:05:29 +00:00
|
|
|
""" Returns a new :class:`~plexapi.myplex.MyPlexAccount` object switched to the given home user.
|
|
|
|
|
|
|
|
Parameters:
|
|
|
|
user (:class:`~plexapi.myplex.MyPlexUser` or str): :class:`~plexapi.myplex.MyPlexUser`,
|
|
|
|
username, or email of the home user to switch to.
|
2022-12-21 21:57:23 +00:00
|
|
|
pin (str): PIN for the home user (required if the home user has a PIN set).
|
2022-07-21 02:05:29 +00:00
|
|
|
|
|
|
|
Example:
|
|
|
|
|
|
|
|
.. code-block:: python
|
|
|
|
|
|
|
|
from plexapi.myplex import MyPlexAccount
|
|
|
|
# Login to a Plex Home account
|
|
|
|
account = MyPlexAccount('<USERNAME>', '<PASSWORD>')
|
|
|
|
# Switch to a different Plex Home user
|
|
|
|
userAccount = account.switchHomeUser('Username')
|
|
|
|
|
|
|
|
"""
|
|
|
|
user = user if isinstance(user, MyPlexUser) else self.user(user)
|
|
|
|
url = f'{self.HOMEUSERS}/{user.id}/switch'
|
2022-12-21 21:57:23 +00:00
|
|
|
params = {}
|
|
|
|
if pin:
|
|
|
|
params['pin'] = pin
|
|
|
|
data = self.query(url, self._session.post, params=params)
|
2022-07-21 02:05:29 +00:00
|
|
|
userToken = data.attrib.get('authenticationToken')
|
2022-12-21 21:57:23 +00:00
|
|
|
return MyPlexAccount(token=userToken, session=self._session)
|
2022-07-21 02:05:29 +00:00
|
|
|
|
2022-11-08 23:57:54 +00:00
|
|
|
def setPin(self, newPin, currentPin=None):
|
|
|
|
""" Set a new Plex Home PIN for the account.
|
|
|
|
|
|
|
|
Parameters:
|
|
|
|
newPin (str): New PIN to set for the account.
|
|
|
|
currentPin (str): Current PIN for the account (required to change the PIN).
|
|
|
|
"""
|
|
|
|
url = self.HOMEUSER.format(userId=self.id)
|
|
|
|
params = {'pin': newPin}
|
|
|
|
if currentPin:
|
|
|
|
params['currentPin'] = currentPin
|
|
|
|
return self.query(url, self._session.put, params=params)
|
|
|
|
|
|
|
|
def removePin(self, currentPin):
|
|
|
|
""" Remove the Plex Home PIN for the account.
|
|
|
|
|
|
|
|
Parameters:
|
|
|
|
currentPin (str): Current PIN for the account (required to remove the PIN).
|
|
|
|
"""
|
|
|
|
return self.setPin('', currentPin)
|
|
|
|
|
|
|
|
def setManagedUserPin(self, user, newPin):
|
|
|
|
""" Set a new Plex Home PIN for a managed home user. This must be done from the Plex Home admin account.
|
|
|
|
|
|
|
|
Parameters:
|
|
|
|
user (:class:`~plexapi.myplex.MyPlexUser` or str): :class:`~plexapi.myplex.MyPlexUser`
|
|
|
|
or username of the managed home user.
|
|
|
|
newPin (str): New PIN to set for the managed home user.
|
|
|
|
"""
|
|
|
|
user = user if isinstance(user, MyPlexUser) else self.user(user)
|
|
|
|
url = self.MANAGEDHOMEUSER.format(userId=user.id)
|
|
|
|
params = {'pin': newPin}
|
|
|
|
return self.query(url, self._session.post, params=params)
|
|
|
|
|
|
|
|
def removeManagedUserPin(self, user):
|
|
|
|
""" Remove the Plex Home PIN for a managed home user. This must be done from the Plex Home admin account.
|
|
|
|
|
|
|
|
Parameters:
|
|
|
|
user (:class:`~plexapi.myplex.MyPlexUser` or str): :class:`~plexapi.myplex.MyPlexUser`
|
|
|
|
or username of the managed home user.
|
|
|
|
"""
|
|
|
|
user = user if isinstance(user, MyPlexUser) else self.user(user)
|
|
|
|
url = self.MANAGEDHOMEUSER.format(userId=user.id)
|
|
|
|
params = {'removePin': 1}
|
|
|
|
return self.query(url, self._session.post, params=params)
|
|
|
|
|
2021-11-21 00:16:01 +00:00
|
|
|
def acceptInvite(self, user):
|
2022-11-08 23:57:30 +00:00
|
|
|
""" Accept a pending friend invite from the specified user.
|
2021-11-21 00:16:01 +00:00
|
|
|
|
|
|
|
Parameters:
|
2022-07-21 02:05:29 +00:00
|
|
|
user (:class:`~plexapi.myplex.MyPlexInvite` or str): :class:`~plexapi.myplex.MyPlexInvite`,
|
|
|
|
username, or email of the friend invite to accept.
|
2021-11-21 00:16:01 +00:00
|
|
|
"""
|
|
|
|
invite = user if isinstance(user, MyPlexInvite) else self.pendingInvite(user, includeSent=False)
|
|
|
|
params = {
|
|
|
|
'friend': int(invite.friend),
|
|
|
|
'home': int(invite.home),
|
|
|
|
'server': int(invite.server)
|
|
|
|
}
|
2022-08-28 05:56:01 +00:00
|
|
|
url = MyPlexInvite.REQUESTS + f'/{invite.id}' + utils.joinArgs(params)
|
2021-11-21 00:16:01 +00:00
|
|
|
return self.query(url, self._session.put)
|
|
|
|
|
|
|
|
def cancelInvite(self, user):
|
|
|
|
""" Cancel a pending firend invite for the specified user.
|
|
|
|
|
|
|
|
Parameters:
|
2022-07-21 02:05:29 +00:00
|
|
|
user (:class:`~plexapi.myplex.MyPlexInvite` or str): :class:`~plexapi.myplex.MyPlexInvite`,
|
|
|
|
username, or email of the friend invite to cancel.
|
2021-11-21 00:16:01 +00:00
|
|
|
"""
|
|
|
|
invite = user if isinstance(user, MyPlexInvite) else self.pendingInvite(user, includeReceived=False)
|
|
|
|
params = {
|
|
|
|
'friend': int(invite.friend),
|
|
|
|
'home': int(invite.home),
|
|
|
|
'server': int(invite.server)
|
|
|
|
}
|
2022-08-28 05:56:01 +00:00
|
|
|
url = MyPlexInvite.REQUESTED + f'/{invite.id}' + utils.joinArgs(params)
|
2021-11-21 00:16:01 +00:00
|
|
|
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:
|
2021-02-27 06:51:22 +00:00
|
|
|
user (:class:`~plexapi.myplex.MyPlexUser`): `MyPlexUser` object, username, or email
|
|
|
|
of the user to be updated.
|
|
|
|
server (:class:`~plexapi.server.PlexServer`): `PlexServer` object, or machineIdentifier
|
|
|
|
containing the library sections to share.
|
2022-05-16 20:39:42 +00:00
|
|
|
sections (List<:class:`~plexapi.library.LibrarySection`>): List of `LibrarySection` objects, or names
|
2021-02-27 06:51:22 +00:00
|
|
|
to be shared (default None). `sections` must be defined in order to update shared libraries.
|
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
|
2021-02-27 06:51:22 +00:00
|
|
|
values to be filtered. ex: `{'contentRating':['G'], 'label':['foo']}`
|
2017-05-27 02:35:33 +00:00
|
|
|
filterTelevision (Dict): Dict containing key 'contentRating' and/or 'label' each set to a list of
|
2021-02-27 06:51:22 +00:00
|
|
|
values to be filtered. ex: `{'contentRating':['G'], 'label':['foo']}`
|
2017-05-27 02:35:33 +00:00
|
|
|
filterMusic (Dict): Dict containing key 'label' set to a list of values to be filtered.
|
2021-02-27 06:51:22 +00:00
|
|
|
ex: `{'label':['foo']}`
|
2017-05-27 02:35:33 +00:00
|
|
|
"""
|
|
|
|
# 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:
|
2020-04-13 17:30:54 +00:00
|
|
|
params = {'server_id': machineId,
|
|
|
|
'shared_server': {'library_section_ids': sectionIds, '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:
|
2021-05-27 02:45:12 +00:00
|
|
|
url += utils.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):
|
2021-11-21 00:16:01 +00:00
|
|
|
""" Returns the :class:`~plexapi.myplex.MyPlexUser` that matches the specified username or email.
|
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
|
|
|
"""
|
2021-05-11 23:38:50 +00:00
|
|
|
username = str(username)
|
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
|
2021-11-21 00:16:01 +00:00
|
|
|
(user.username.lower(), user.email.lower(), str(user.id))):
|
2017-07-17 00:59:53 +00:00
|
|
|
return user
|
2017-09-23 21:11:34 +00:00
|
|
|
|
2022-08-28 05:56:01 +00:00
|
|
|
raise NotFound(f'Unable to find user {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.
|
|
|
|
"""
|
2021-11-21 00:16:01 +00:00
|
|
|
elem = self.query(MyPlexUser.key)
|
|
|
|
return self.findItems(elem, cls=MyPlexUser)
|
|
|
|
|
|
|
|
def pendingInvite(self, username, includeSent=True, includeReceived=True):
|
|
|
|
""" Returns the :class:`~plexapi.myplex.MyPlexInvite` that matches the specified username or email.
|
|
|
|
Note: This can be a pending invite sent from your account or received to your account.
|
|
|
|
|
|
|
|
Parameters:
|
|
|
|
username (str): Username, email or id of the user to return.
|
|
|
|
includeSent (bool): True to include sent invites.
|
|
|
|
includeReceived (bool): True to include received invites.
|
|
|
|
"""
|
|
|
|
username = str(username)
|
|
|
|
for invite in self.pendingInvites(includeSent, includeReceived):
|
|
|
|
if (invite.username and invite.email and invite.id and username.lower() in
|
|
|
|
(invite.username.lower(), invite.email.lower(), str(invite.id))):
|
|
|
|
return invite
|
|
|
|
|
2022-08-28 05:56:01 +00:00
|
|
|
raise NotFound(f'Unable to find invite {username}')
|
2021-11-21 00:16:01 +00:00
|
|
|
|
|
|
|
def pendingInvites(self, includeSent=True, includeReceived=True):
|
|
|
|
""" Returns a list of all :class:`~plexapi.myplex.MyPlexInvite` objects connected to your account.
|
|
|
|
Note: This includes all pending invites sent from your account and received to your account.
|
|
|
|
|
|
|
|
Parameters:
|
|
|
|
includeSent (bool): True to include sent invites.
|
|
|
|
includeReceived (bool): True to include received invites.
|
|
|
|
"""
|
|
|
|
invites = []
|
|
|
|
if includeSent:
|
|
|
|
elem = self.query(MyPlexInvite.REQUESTED)
|
|
|
|
invites += self.findItems(elem, cls=MyPlexInvite)
|
|
|
|
if includeReceived:
|
|
|
|
elem = self.query(MyPlexInvite.REQUESTS)
|
|
|
|
invites += self.findItems(elem, cls=MyPlexInvite)
|
|
|
|
return invites
|
2017-05-27 02:35:33 +00:00
|
|
|
|
|
|
|
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
|
2022-08-28 05:56:01 +00:00
|
|
|
url = self.PLEXSERVERS.format(machineId=machineIdentifier)
|
2017-05-27 02:35:33 +00:00
|
|
|
data = self.query(url, self._session.get)
|
|
|
|
for elem in data[0]:
|
2021-03-22 19:31:54 +00:00
|
|
|
_id = utils.cast(int, elem.attrib.get('id'))
|
|
|
|
_key = utils.cast(int, elem.attrib.get('key'))
|
|
|
|
_title = elem.attrib.get('title', '').lower()
|
|
|
|
allSectionIds[_id] = _id
|
|
|
|
allSectionIds[_key] = _id
|
|
|
|
allSectionIds[_title] = _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:
|
2021-03-22 19:31:54 +00:00
|
|
|
sectionKey = section.key if isinstance(section, LibrarySection) else section.lower()
|
|
|
|
sectionIds.append(allSectionIds[sectionKey])
|
2017-05-27 02:35:33 +00:00
|
|
|
return sectionIds
|
|
|
|
|
|
|
|
def _filterDictToStr(self, filterDict):
|
|
|
|
""" Converts friend filters to a string representation for transport. """
|
|
|
|
values = []
|
|
|
|
for key, vals in filterDict.items():
|
2022-03-17 21:54:27 +00:00
|
|
|
if key not in ('contentRating', 'label', 'contentRating!', 'label!'):
|
2022-11-08 21:40:18 +00:00
|
|
|
raise BadRequest(f'Unknown filter key: {key}')
|
2022-08-28 05:56:01 +00:00
|
|
|
values.append(f"{key}={'%2C'.join(vals)}")
|
2017-05-27 02:35:33 +00:00
|
|
|
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:
|
2022-08-28 05:56:01 +00:00
|
|
|
raise BadRequest(f'Webhook does not exist: {url}')
|
2017-02-25 06:56:12 +00:00
|
|
|
urls.remove(url)
|
|
|
|
return self.setWebhooks(urls)
|
|
|
|
|
|
|
|
def setWebhooks(self, urls):
|
2022-11-08 21:40:18 +00:00
|
|
|
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):
|
2020-11-23 03:06:30 +00:00
|
|
|
""" Returns an instance of :class:`~plexapi.sync.SyncList` for specified client.
|
2018-09-08 15:25:16 +00:00
|
|
|
|
|
|
|
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.
|
2022-02-27 03:26:08 +00:00
|
|
|
If neither `client` nor `clientId` provided the clientId would be set to current clients's identifier.
|
2018-09-08 15:25:16 +00:00
|
|
|
"""
|
|
|
|
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
|
2020-11-23 03:06:30 +00:00
|
|
|
objects, e.g. :func:`~plexapi.video.Video.sync`, :func:`~plexapi.audio.Audio.sync`.
|
2018-09-08 15:25:16 +00:00
|
|
|
|
|
|
|
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.
|
2020-11-23 03:06:30 +00:00
|
|
|
sync_item (:class:`~plexapi.sync.SyncItem`): prepared SyncItem object with all fields set.
|
2018-09-08 15:25:16 +00:00
|
|
|
|
|
|
|
If both `client` and `clientId` provided the client would be preferred.
|
2022-02-27 03:26:08 +00:00
|
|
|
If neither `client` nor `clientId` provided the clientId would be set to current clients's identifier.
|
2018-09-08 15:25:16 +00:00
|
|
|
|
|
|
|
Returns:
|
2020-11-23 03:06:30 +00:00
|
|
|
:class:`~plexapi.sync.SyncItem`: an instance of created syncItem.
|
2018-09-08 15:25:16 +00:00
|
|
|
|
|
|
|
Raises:
|
2022-02-27 03:26:08 +00:00
|
|
|
:exc:`~plexapi.exceptions.BadRequest`: When client with provided clientId wasn't found.
|
|
|
|
:exc:`~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:
|
2022-11-08 21:40:18 +00:00
|
|
|
raise BadRequest(f'Unable to find client by clientId={clientId}')
|
2018-09-08 15:25:16 +00:00
|
|
|
|
|
|
|
if 'sync-target' not in client.provides:
|
2022-02-27 03:26:08 +00:00
|
|
|
raise BadRequest("Received client doesn't provides sync-target")
|
2018-09-08 15:25:16 +00:00
|
|
|
|
|
|
|
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)
|
2021-07-16 16:55:07 +00:00
|
|
|
data = self.query(url, method=self._session.post, params=params)
|
2018-09-08 15:25:16 +00:00
|
|
|
|
|
|
|
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', ' ')
|
2022-08-28 05:56:01 +00:00
|
|
|
raise BadRequest(f'({response.status_code}) {codename} {response.url}; {errtext}')
|
2018-09-14 18:52:26 +00:00
|
|
|
return response.json()['token']
|
|
|
|
|
2023-05-24 21:50:30 +00:00
|
|
|
def history(self, maxresults=None, mindate=None):
|
2019-11-20 11:50:25 +00:00
|
|
|
""" Get Play History for all library sections on all servers for the owner.
|
2022-05-18 18:04:18 +00:00
|
|
|
|
2019-11-20 11:50:25 +00:00
|
|
|
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
|
|
|
|
|
2022-05-18 18:04:18 +00:00
|
|
|
def onlineMediaSources(self):
|
|
|
|
""" Returns a list of user account Online Media Sources settings :class:`~plexapi.myplex.AccountOptOut`
|
|
|
|
"""
|
|
|
|
url = self.OPTOUTS.format(userUUID=self.uuid)
|
|
|
|
elem = self.query(url)
|
|
|
|
return self.findItems(elem, cls=AccountOptOut, etag='optOut')
|
|
|
|
|
2020-02-06 18:05:19 +00:00
|
|
|
def videoOnDemand(self):
|
2019-12-05 17:54:18 +00:00
|
|
|
""" Returns a list of VOD Hub items :class:`~plexapi.library.Hub`
|
|
|
|
"""
|
2022-05-18 18:04:18 +00:00
|
|
|
data = self.query(f'{self.VOD}/hubs')
|
|
|
|
return self.findItems(data)
|
2019-12-05 17:54:18 +00:00
|
|
|
|
2022-05-18 18:04:18 +00:00
|
|
|
def tidal(self):
|
|
|
|
""" Returns a list of tidal Hub items :class:`~plexapi.library.Hub`
|
2020-03-14 14:52:54 +00:00
|
|
|
"""
|
2022-05-18 18:04:18 +00:00
|
|
|
data = self.query(f'{self.MUSIC}/hubs')
|
|
|
|
return self.findItems(data)
|
|
|
|
|
2023-05-24 21:50:30 +00:00
|
|
|
def watchlist(self, filter=None, sort=None, libtype=None, maxresults=None, **kwargs):
|
2022-05-18 18:04:18 +00:00
|
|
|
""" Returns a list of :class:`~plexapi.video.Movie` and :class:`~plexapi.video.Show` items in the user's watchlist.
|
|
|
|
Note: The objects returned are from Plex's online metadata. To get the matching item on a Plex server,
|
|
|
|
search for the media using the guid.
|
|
|
|
|
|
|
|
Parameters:
|
|
|
|
filter (str, optional): 'available' or 'released' to only return items that are available or released,
|
|
|
|
otherwise return all items.
|
|
|
|
sort (str, optional): In the format ``field:dir``. Available fields are ``watchlistedAt`` (Added At),
|
|
|
|
``titleSort`` (Title), ``originallyAvailableAt`` (Release Date), or ``rating`` (Critic Rating).
|
|
|
|
``dir`` can be ``asc`` or ``desc``.
|
|
|
|
libtype (str, optional): 'movie' or 'show' to only return movies or shows, otherwise return all items.
|
2022-08-27 07:20:11 +00:00
|
|
|
maxresults (int, optional): Only return the specified number of results.
|
2022-05-18 18:04:18 +00:00
|
|
|
**kwargs (dict): Additional custom filters to apply to the search results.
|
|
|
|
|
|
|
|
|
|
|
|
Example:
|
|
|
|
|
|
|
|
.. code-block:: python
|
|
|
|
|
|
|
|
# Watchlist for released movies sorted by critic rating in descending order
|
|
|
|
watchlist = account.watchlist(filter='released', sort='rating:desc', libtype='movie')
|
|
|
|
item = watchlist[0] # First item in the watchlist
|
|
|
|
|
|
|
|
# Search for the item on a Plex server
|
|
|
|
result = plex.library.search(guid=item.guid, libtype=item.type)
|
2019-12-05 17:55:39 +00:00
|
|
|
|
2020-03-14 14:52:54 +00:00
|
|
|
"""
|
2022-05-18 18:04:18 +00:00
|
|
|
params = {
|
|
|
|
'includeCollections': 1,
|
|
|
|
'includeExternalMedia': 1
|
|
|
|
}
|
2019-12-05 17:57:27 +00:00
|
|
|
|
2022-05-18 18:04:18 +00:00
|
|
|
if not filter:
|
|
|
|
filter = 'all'
|
|
|
|
if sort:
|
|
|
|
params['sort'] = sort
|
|
|
|
if libtype:
|
|
|
|
params['type'] = utils.searchType(libtype)
|
|
|
|
|
|
|
|
params.update(kwargs)
|
2022-08-27 07:20:11 +00:00
|
|
|
|
2023-05-24 21:50:30 +00:00
|
|
|
key = f'{self.METADATA}/library/sections/watchlist/{filter}{utils.joinArgs(params)}'
|
|
|
|
return self._toOnlineMetadata(self.fetchItems(key, maxresults=maxresults), **kwargs)
|
2022-05-18 18:04:18 +00:00
|
|
|
|
|
|
|
def onWatchlist(self, item):
|
|
|
|
""" Returns True if the item is on the user's watchlist.
|
|
|
|
|
|
|
|
Parameters:
|
|
|
|
item (:class:`~plexapi.video.Movie` or :class:`~plexapi.video.Show`): Item to check
|
|
|
|
if it is on the user's watchlist.
|
2019-12-05 18:00:29 +00:00
|
|
|
"""
|
2022-07-21 02:37:48 +00:00
|
|
|
return bool(self.userState(item).watchlistedAt)
|
2019-12-05 18:00:29 +00:00
|
|
|
|
2022-05-18 18:04:18 +00:00
|
|
|
def addToWatchlist(self, items):
|
|
|
|
""" Add media items to the user's watchlist
|
|
|
|
|
|
|
|
Parameters:
|
|
|
|
items (List): List of :class:`~plexapi.video.Movie` or :class:`~plexapi.video.Show`
|
|
|
|
objects to be added to the watchlist.
|
|
|
|
|
|
|
|
Raises:
|
|
|
|
:exc:`~plexapi.exceptions.BadRequest`: When trying to add invalid or existing
|
|
|
|
media to the watchlist.
|
2019-12-05 18:02:22 +00:00
|
|
|
"""
|
2022-05-18 18:04:18 +00:00
|
|
|
if not isinstance(items, list):
|
|
|
|
items = [items]
|
|
|
|
|
|
|
|
for item in items:
|
|
|
|
if self.onWatchlist(item):
|
2022-08-28 05:56:01 +00:00
|
|
|
raise BadRequest(f'"{item.title}" is already on the watchlist')
|
2022-05-18 18:04:18 +00:00
|
|
|
ratingKey = item.guid.rsplit('/', 1)[-1]
|
|
|
|
self.query(f'{self.METADATA}/actions/addToWatchlist?ratingKey={ratingKey}', method=self._session.put)
|
2022-08-26 21:44:50 +00:00
|
|
|
return self
|
2019-12-05 18:02:22 +00:00
|
|
|
|
2022-05-18 18:04:18 +00:00
|
|
|
def removeFromWatchlist(self, items):
|
|
|
|
""" Remove media items from the user's watchlist
|
|
|
|
|
|
|
|
Parameters:
|
|
|
|
items (List): List of :class:`~plexapi.video.Movie` or :class:`~plexapi.video.Show`
|
|
|
|
objects to be added to the watchlist.
|
|
|
|
|
|
|
|
Raises:
|
|
|
|
:exc:`~plexapi.exceptions.BadRequest`: When trying to remove invalid or non-existing
|
|
|
|
media to the watchlist.
|
2020-07-17 01:00:45 +00:00
|
|
|
"""
|
2022-05-18 18:04:18 +00:00
|
|
|
if not isinstance(items, list):
|
|
|
|
items = [items]
|
|
|
|
|
|
|
|
for item in items:
|
|
|
|
if not self.onWatchlist(item):
|
2022-08-28 05:56:01 +00:00
|
|
|
raise BadRequest(f'"{item.title}" is not on the watchlist')
|
2022-05-18 18:04:18 +00:00
|
|
|
ratingKey = item.guid.rsplit('/', 1)[-1]
|
|
|
|
self.query(f'{self.METADATA}/actions/removeFromWatchlist?ratingKey={ratingKey}', method=self._session.put)
|
2022-08-26 21:44:50 +00:00
|
|
|
return self
|
2022-05-18 18:04:18 +00:00
|
|
|
|
2022-07-21 02:37:48 +00:00
|
|
|
def userState(self, item):
|
|
|
|
""" Returns a :class:`~plexapi.myplex.UserState` object for the specified item.
|
|
|
|
|
|
|
|
Parameters:
|
|
|
|
item (:class:`~plexapi.video.Movie` or :class:`~plexapi.video.Show`): Item to return the user state.
|
|
|
|
"""
|
|
|
|
ratingKey = item.guid.rsplit('/', 1)[-1]
|
|
|
|
data = self.query(f"{self.METADATA}/library/metadata/{ratingKey}/userState")
|
2022-07-21 03:12:30 +00:00
|
|
|
return self.findItem(data, cls=UserState)
|
2022-07-21 02:37:48 +00:00
|
|
|
|
2023-05-24 18:37:13 +00:00
|
|
|
def isPlayed(self, item):
|
|
|
|
""" Return True if the item is played on Discover.
|
|
|
|
|
|
|
|
Parameters:
|
|
|
|
item (:class:`~plexapi.video.Movie`,
|
|
|
|
:class:`~plexapi.video.Show`, :class:`~plexapi.video.Season` or
|
|
|
|
:class:`~plexapi.video.Episode`): Object from searchDiscover().
|
|
|
|
Can be also result from Plex Movie or Plex TV Series agent.
|
|
|
|
"""
|
|
|
|
userState = self.userState(item)
|
|
|
|
return bool(userState.viewCount > 0) if userState.viewCount else False
|
|
|
|
|
|
|
|
def markPlayed(self, item):
|
|
|
|
""" Mark the Plex object as played on Discover.
|
|
|
|
|
|
|
|
Parameters:
|
|
|
|
item (:class:`~plexapi.video.Movie`,
|
|
|
|
:class:`~plexapi.video.Show`, :class:`~plexapi.video.Season` or
|
|
|
|
:class:`~plexapi.video.Episode`): Object from searchDiscover().
|
|
|
|
Can be also result from Plex Movie or Plex TV Series agent.
|
|
|
|
"""
|
|
|
|
key = f'{self.METADATA}/actions/scrobble'
|
|
|
|
ratingKey = item.guid.rsplit('/', 1)[-1]
|
|
|
|
params = {'key': ratingKey, 'identifier': 'com.plexapp.plugins.library'}
|
|
|
|
self.query(key, params=params)
|
|
|
|
return self
|
|
|
|
|
|
|
|
def markUnplayed(self, item):
|
|
|
|
""" Mark the Plex object as unplayed on Discover.
|
|
|
|
|
|
|
|
Parameters:
|
|
|
|
item (:class:`~plexapi.video.Movie`,
|
|
|
|
:class:`~plexapi.video.Show`, :class:`~plexapi.video.Season` or
|
|
|
|
:class:`~plexapi.video.Episode`): Object from searchDiscover().
|
|
|
|
Can be also result from Plex Movie or Plex TV Series agent.
|
|
|
|
"""
|
|
|
|
key = f'{self.METADATA}/actions/unscrobble'
|
|
|
|
ratingKey = item.guid.rsplit('/', 1)[-1]
|
|
|
|
params = {'key': ratingKey, 'identifier': 'com.plexapp.plugins.library'}
|
|
|
|
self.query(key, params=params)
|
|
|
|
return self
|
|
|
|
|
2022-07-21 02:37:48 +00:00
|
|
|
def searchDiscover(self, query, limit=30, libtype=None):
|
2022-05-18 18:04:18 +00:00
|
|
|
""" Search for movies and TV shows in Discover.
|
|
|
|
Returns a list of :class:`~plexapi.video.Movie` and :class:`~plexapi.video.Show` objects.
|
|
|
|
|
|
|
|
Parameters:
|
|
|
|
query (str): Search query.
|
|
|
|
limit (int, optional): Limit to the specified number of results. Default 30.
|
2022-07-21 02:37:48 +00:00
|
|
|
libtype (str, optional): 'movie' or 'show' to only return movies or shows, otherwise return all items.
|
2022-05-18 18:04:18 +00:00
|
|
|
"""
|
2022-07-21 02:37:48 +00:00
|
|
|
libtypes = {'movie': 'movies', 'show': 'tv'}
|
|
|
|
libtype = libtypes.get(libtype, 'movies,tv')
|
|
|
|
|
2022-05-18 18:04:18 +00:00
|
|
|
headers = {
|
|
|
|
'Accept': 'application/json'
|
|
|
|
}
|
|
|
|
params = {
|
|
|
|
'query': query,
|
2022-12-21 21:10:48 +00:00
|
|
|
'limit': limit,
|
2022-07-21 02:37:48 +00:00
|
|
|
'searchTypes': libtype,
|
2022-05-18 18:04:18 +00:00
|
|
|
'includeMetadata': 1
|
|
|
|
}
|
|
|
|
|
|
|
|
data = self.query(f'{self.METADATA}/library/search', headers=headers, params=params)
|
2022-07-21 02:37:48 +00:00
|
|
|
searchResults = data['MediaContainer'].get('SearchResults', [])
|
2022-08-27 13:24:10 +00:00
|
|
|
searchResult = next((s.get('SearchResult', []) for s in searchResults if s.get('id') == 'external'), [])
|
2022-05-18 18:04:18 +00:00
|
|
|
|
|
|
|
results = []
|
2022-07-21 02:37:48 +00:00
|
|
|
for result in searchResult:
|
2022-05-18 18:04:18 +00:00
|
|
|
metadata = result['Metadata']
|
|
|
|
type = metadata['type']
|
|
|
|
if type == 'movie':
|
|
|
|
tag = 'Video'
|
|
|
|
elif type == 'show':
|
|
|
|
tag = 'Directory'
|
|
|
|
else:
|
|
|
|
continue
|
|
|
|
attrs = ''.join(f'{k}="{html.escape(str(v))}" ' for k, v in metadata.items())
|
|
|
|
xml = f'<{tag} {attrs}/>'
|
|
|
|
results.append(self._manuallyLoadXML(xml))
|
|
|
|
|
2022-07-21 02:37:48 +00:00
|
|
|
return self._toOnlineMetadata(results)
|
2017-02-25 06:56:12 +00:00
|
|
|
|
2022-08-26 19:00:46 +00:00
|
|
|
@property
|
|
|
|
def viewStateSync(self):
|
|
|
|
""" Returns True or False if syncing of watch state and ratings
|
|
|
|
is enabled or disabled, respectively, for the account.
|
|
|
|
"""
|
|
|
|
headers = {'Accept': 'application/json'}
|
|
|
|
data = self.query(self.VIEWSTATESYNC, headers=headers)
|
|
|
|
return data.get('consent')
|
|
|
|
|
|
|
|
def enableViewStateSync(self):
|
|
|
|
""" Enable syncing of watch state and ratings for the account. """
|
|
|
|
self._updateViewStateSync(True)
|
|
|
|
|
|
|
|
def disableViewStateSync(self):
|
|
|
|
""" Disable syncing of watch state and ratings for the account. """
|
|
|
|
self._updateViewStateSync(False)
|
|
|
|
|
|
|
|
def _updateViewStateSync(self, consent):
|
|
|
|
""" Enable or disable syncing of watch state and ratings for the account.
|
|
|
|
|
|
|
|
Parameters:
|
|
|
|
consent (bool): True to enable, False to disable.
|
|
|
|
"""
|
|
|
|
params = {'consent': consent}
|
|
|
|
self.query(self.VIEWSTATESYNC, method=self._session.put, params=params)
|
|
|
|
|
2020-12-16 04:41:04 +00:00
|
|
|
def link(self, pin):
|
|
|
|
""" Link a device to the account using a pin code.
|
|
|
|
|
|
|
|
Parameters:
|
|
|
|
pin (str): The 4 digit link pin code.
|
|
|
|
"""
|
|
|
|
headers = {
|
|
|
|
'Content-Type': 'application/x-www-form-urlencoded',
|
|
|
|
'X-Plex-Product': 'Plex SSO'
|
|
|
|
}
|
|
|
|
data = {'code': pin}
|
|
|
|
self.query(self.LINK, self._session.put, headers=headers, data=data)
|
|
|
|
|
2022-12-21 21:10:09 +00:00
|
|
|
def _toOnlineMetadata(self, objs, **kwargs):
|
2022-07-21 02:37:48 +00:00
|
|
|
""" Convert a list of media objects to online metadata objects. """
|
|
|
|
# TODO: Add proper support for metadata.provider.plex.tv
|
|
|
|
# Temporary workaround to allow reloading and browsing of online media objects
|
2022-12-21 21:01:37 +00:00
|
|
|
server = PlexServer(self.METADATA, self._token, session=self._session)
|
2022-11-08 23:57:16 +00:00
|
|
|
|
2022-12-21 21:10:09 +00:00
|
|
|
includeUserState = int(bool(kwargs.pop('includeUserState', True)))
|
|
|
|
|
2022-07-21 02:37:48 +00:00
|
|
|
if not isinstance(objs, list):
|
|
|
|
objs = [objs]
|
2022-12-21 21:10:09 +00:00
|
|
|
|
2022-07-21 02:37:48 +00:00
|
|
|
for obj in objs:
|
2022-11-08 23:57:16 +00:00
|
|
|
obj._server = server
|
2022-07-21 02:37:48 +00:00
|
|
|
|
|
|
|
# Parse details key to modify query string
|
|
|
|
url = urlsplit(obj._details_key)
|
|
|
|
query = dict(parse_qsl(url.query))
|
2022-12-21 21:10:09 +00:00
|
|
|
query['includeUserState'] = includeUserState
|
2022-07-21 02:37:48 +00:00
|
|
|
query.pop('includeFields', None)
|
|
|
|
obj._details_key = urlunsplit((url.scheme, url.netloc, url.path, urlencode(query), url.fragment))
|
|
|
|
|
|
|
|
return objs
|
|
|
|
|
2023-08-27 19:34:52 +00:00
|
|
|
def publicIP(self):
|
|
|
|
""" Returns your public IP address. """
|
|
|
|
return self.query('https://plex.tv/:/ip')
|
|
|
|
|
|
|
|
def geoip(self, ip_address):
|
|
|
|
""" Returns a :class:`~plexapi.myplex.GeoLocation` object with geolocation information
|
|
|
|
for an IP address using Plex's GeoIP database.
|
|
|
|
|
|
|
|
Parameters:
|
|
|
|
ip_address (str): IP address to lookup.
|
|
|
|
"""
|
|
|
|
params = {'ip_address': ip_address}
|
|
|
|
data = self.query('https://plex.tv/api/v2/geoip', params=params)
|
|
|
|
return GeoLocation(self, data)
|
|
|
|
|
2020-08-30 05:18:26 +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
|
2020-11-23 03:06:30 +00:00
|
|
|
accounts. NOTE: This should not be confused with the :class:`~plexapi.myplex.MyPlexAccount`
|
2017-01-22 05:19:52 +00:00
|
|
|
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.
|
2021-11-21 00:16:01 +00:00
|
|
|
servers (List<:class:`~plexapi.myplex.<MyPlexServerShare`>)): Servers shared with the user.
|
2017-02-14 04:32:27 +00:00
|
|
|
thumb (str): Link to the users avatar.
|
2022-02-27 03:26:08 +00:00
|
|
|
title (str): Seems to be an alias for username.
|
2017-02-14 04:32:27 +00:00
|
|
|
username (str): User's username.
|
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:
|
2022-11-08 21:40:18 +00:00
|
|
|
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
|
|
|
|
|
2022-08-28 05:56:01 +00:00
|
|
|
raise NotFound(f'Unable to find server {name}')
|
2019-11-16 21:35:20 +00:00
|
|
|
|
2023-05-24 21:50:30 +00:00
|
|
|
def history(self, maxresults=None, mindate=None):
|
2019-11-20 11:50:25 +00:00
|
|
|
""" 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
|
|
|
|
2021-11-21 00:16:01 +00:00
|
|
|
class MyPlexInvite(PlexObject):
|
|
|
|
""" This object represents pending friend invites.
|
|
|
|
|
|
|
|
Attributes:
|
|
|
|
TAG (str): 'Invite'
|
|
|
|
createdAt (datetime): Datetime the user was invited.
|
|
|
|
email (str): User's email address (user@gmail.com).
|
|
|
|
friend (bool): True or False if the user is invited as a friend.
|
|
|
|
friendlyName (str): The user's friendly name.
|
|
|
|
home (bool): True or False if the user is invited to a Plex Home.
|
|
|
|
id (int): User's Plex account ID.
|
|
|
|
server (bool): True or False if the user is invited to any servers.
|
|
|
|
servers (List<:class:`~plexapi.myplex.<MyPlexServerShare`>)): Servers shared with the user.
|
|
|
|
thumb (str): Link to the users avatar.
|
|
|
|
username (str): User's username.
|
|
|
|
"""
|
|
|
|
TAG = 'Invite'
|
|
|
|
REQUESTS = 'https://plex.tv/api/invites/requests'
|
|
|
|
REQUESTED = 'https://plex.tv/api/invites/requested'
|
|
|
|
|
|
|
|
def _loadData(self, data):
|
|
|
|
""" Load attribute values from Plex XML response. """
|
|
|
|
self._data = data
|
|
|
|
self.createdAt = utils.toDatetime(data.attrib.get('createdAt'))
|
|
|
|
self.email = data.attrib.get('email')
|
|
|
|
self.friend = utils.cast(bool, data.attrib.get('friend'))
|
|
|
|
self.friendlyName = data.attrib.get('friendlyName')
|
|
|
|
self.home = utils.cast(bool, data.attrib.get('home'))
|
|
|
|
self.id = utils.cast(int, data.attrib.get('id'))
|
|
|
|
self.server = utils.cast(bool, data.attrib.get('server'))
|
|
|
|
self.servers = self.findItems(data, MyPlexServerShare)
|
|
|
|
self.thumb = data.attrib.get('thumb')
|
|
|
|
self.username = data.attrib.get('username', '')
|
|
|
|
for server in self.servers:
|
|
|
|
server.accountID = self.id
|
|
|
|
|
|
|
|
|
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
|
2021-03-25 01:58:12 +00:00
|
|
|
can be found at: https://plex.tv/api/servers/{machineId}/shared_servers
|
2017-10-24 19:41:07 +00:00
|
|
|
|
|
|
|
Attributes:
|
|
|
|
TAG (str): section
|
2021-03-25 01:58:12 +00:00
|
|
|
id (int): The shared section ID
|
|
|
|
key (int): The shared library section key
|
|
|
|
shared (bool): If this section is shared with the user
|
2017-10-24 19:41:07 +00:00
|
|
|
title (str): Title of the section
|
|
|
|
type (str): movie, tvshow, artist
|
|
|
|
|
|
|
|
"""
|
2017-09-23 21:11:34 +00:00
|
|
|
TAG = 'Section'
|
|
|
|
|
|
|
|
def _loadData(self, data):
|
|
|
|
self._data = data
|
2021-03-25 01:58:12 +00:00
|
|
|
self.id = utils.cast(int, data.attrib.get('id'))
|
|
|
|
self.key = utils.cast(int, data.attrib.get('key'))
|
|
|
|
self.shared = utils.cast(bool, data.attrib.get('shared', '0'))
|
2017-09-23 21:11:34 +00:00
|
|
|
self.title = data.attrib.get('title')
|
|
|
|
self.type = data.attrib.get('type')
|
2021-03-25 01:58:12 +00:00
|
|
|
self.sectionId = self.id # For backwards compatibility
|
|
|
|
self.sectionKey = self.key # For backwards compatibility
|
2017-09-23 21:11:34 +00:00
|
|
|
|
2023-05-24 21:50:30 +00:00
|
|
|
def history(self, maxresults=None, mindate=None):
|
2019-11-20 11:50:25 +00:00
|
|
|
""" 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
|
|
|
|
|
2022-08-28 05:56:01 +00:00
|
|
|
raise NotFound(f'Unable to find section {name}')
|
2019-11-16 21:35:20 +00:00
|
|
|
|
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)
|
2021-05-25 00:28:11 +00:00
|
|
|
return self.findItems(data, Section, rtag='SharedServer')
|
2017-09-23 21:11:34 +00:00
|
|
|
|
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:
|
2023-07-27 21:01:18 +00:00
|
|
|
https://plex.tv/api/v2/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'
|
2023-07-27 21:01:18 +00:00
|
|
|
key (str): 'https://plex.tv/api/v2/resources?includeHttps=1&includeRelay=1'
|
|
|
|
accessToken (str): This resource's Plex access token.
|
2017-01-22 05:19:52 +00:00
|
|
|
clientIdentifier (str): Unique ID for this resource.
|
2020-11-23 03:06:30 +00:00
|
|
|
connections (list): List of :class:`~plexapi.myplex.ResourceConnection` objects
|
2017-01-22 05:19:52 +00:00
|
|
|
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).
|
2023-07-27 21:01:18 +00:00
|
|
|
dnsRebindingProtection (bool): True if the server had DNS rebinding protection.
|
2017-01-22 05:19:52 +00:00
|
|
|
home (bool): Unknown
|
2023-07-27 21:01:18 +00:00
|
|
|
httpsRequired (bool): True if the resource requires https.
|
2017-01-22 05:19:52 +00:00
|
|
|
lastSeenAt (datetime): Timestamp this resource last connected.
|
|
|
|
name (str): Descriptive name of this resource.
|
2023-07-27 21:01:18 +00:00
|
|
|
natLoopbackSupported (bool): True if the resource supports NAT loopback.
|
2017-01-22 05:19:52 +00:00
|
|
|
owned (bool): True if this resource is one of your own (you logged into it).
|
2023-07-27 21:01:18 +00:00
|
|
|
ownerId (int): ID of the user that owns this resource (shared resources only).
|
2017-01-22 05:19:52 +00:00
|
|
|
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.)
|
2023-07-27 21:01:18 +00:00
|
|
|
publicAddressMatches (bool): True if the public IP address matches the client's public IP address.
|
|
|
|
relay (bool): True if this resource has the Plex Relay enabled.
|
|
|
|
sourceTitle (str): Username of the user that owns this resource (shared resources only).
|
2017-01-22 05:19:52 +00:00
|
|
|
synced (bool): Unknown (possibly True if the resource has synced content?)
|
2017-01-02 21:06:40 +00:00
|
|
|
"""
|
2023-07-27 21:01:18 +00:00
|
|
|
TAG = 'resource'
|
|
|
|
key = 'https://plex.tv/api/v2/resources?includeHttps=1&includeRelay=1'
|
2014-12-29 03:21:58 +00:00
|
|
|
|
2021-07-27 01:38:16 +00:00
|
|
|
# Default order to prioritize available resource connections
|
|
|
|
DEFAULT_LOCATION_ORDER = ['local', 'remote', 'relay']
|
|
|
|
DEFAULT_SCHEME_ORDER = ['https', 'http']
|
|
|
|
|
2017-02-06 04:52:10 +00:00
|
|
|
def _loadData(self, data):
|
2017-02-04 08:08:47 +00:00
|
|
|
self._data = data
|
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.clientIdentifier = data.attrib.get('clientIdentifier')
|
2023-07-27 21:01:18 +00:00
|
|
|
self.connections = self.findItems(data, ResourceConnection, rtag='connections')
|
|
|
|
self.createdAt = utils.toDatetime(data.attrib.get('createdAt'), "%Y-%m-%dT%H:%M:%SZ")
|
|
|
|
self.device = data.attrib.get('device')
|
|
|
|
self.dnsRebindingProtection = utils.cast(bool, data.attrib.get('dnsRebindingProtection'))
|
2016-04-07 05:39:04 +00:00
|
|
|
self.home = utils.cast(bool, data.attrib.get('home'))
|
2023-07-27 21:01:18 +00:00
|
|
|
self.httpsRequired = utils.cast(bool, data.attrib.get('httpsRequired'))
|
|
|
|
self.lastSeenAt = utils.toDatetime(data.attrib.get('lastSeenAt'), "%Y-%m-%dT%H:%M:%SZ")
|
|
|
|
self.name = data.attrib.get('name')
|
|
|
|
self.natLoopbackSupported = utils.cast(bool, data.attrib.get('natLoopbackSupported'))
|
|
|
|
self.owned = utils.cast(bool, data.attrib.get('owned'))
|
|
|
|
self.ownerId = utils.cast(int, data.attrib.get('ownerId', 0))
|
|
|
|
self.platform = data.attrib.get('platform')
|
|
|
|
self.platformVersion = data.attrib.get('platformVersion')
|
2016-04-07 05:39:04 +00:00
|
|
|
self.presence = utils.cast(bool, data.attrib.get('presence'))
|
2023-07-27 21:01:18 +00:00
|
|
|
self.product = data.attrib.get('product')
|
|
|
|
self.productVersion = data.attrib.get('productVersion')
|
|
|
|
self.provides = data.attrib.get('provides')
|
2018-03-02 18:11:43 +00:00
|
|
|
self.publicAddressMatches = utils.cast(bool, data.attrib.get('publicAddressMatches'))
|
2023-07-27 21:01:18 +00:00
|
|
|
self.relay = utils.cast(bool, data.attrib.get('relay'))
|
|
|
|
self.sourceTitle = data.attrib.get('sourceTitle')
|
|
|
|
self.synced = utils.cast(bool, data.attrib.get('synced'))
|
2014-12-29 03:21:58 +00:00
|
|
|
|
2021-07-27 01:38:16 +00:00
|
|
|
def preferred_connections(
|
|
|
|
self,
|
|
|
|
ssl=None,
|
2023-05-24 20:55:50 +00:00
|
|
|
locations=None,
|
|
|
|
schemes=None,
|
2021-07-27 01:38:16 +00:00
|
|
|
):
|
|
|
|
""" Returns a sorted list of the available connection addresses for this resource.
|
2017-07-26 23:28:14 +00:00
|
|
|
Often times there is more than one address specified for a server or client.
|
2021-07-27 01:38:16 +00:00
|
|
|
Default behavior will prioritize local connections before remote or relay and HTTPS before HTTP.
|
2017-01-22 05:19:52 +00:00
|
|
|
|
|
|
|
Parameters:
|
2021-02-02 02:59:34 +00:00
|
|
|
ssl (bool, optional): Set True to only connect to HTTPS connections. Set False to
|
2017-01-22 05:19:52 +00:00
|
|
|
only connect to HTTP connections. Set None (default) to connect to any
|
|
|
|
HTTP or HTTPS connection.
|
2017-01-02 21:06:40 +00:00
|
|
|
"""
|
2023-05-24 20:55:50 +00:00
|
|
|
if locations is None:
|
|
|
|
locations = self.DEFAULT_LOCATION_ORDER[:]
|
|
|
|
if schemes is None:
|
|
|
|
schemes = self.DEFAULT_SCHEME_ORDER[:]
|
|
|
|
|
2021-02-02 02:59:34 +00:00
|
|
|
connections_dict = {location: {scheme: [] for scheme in schemes} for location in locations}
|
|
|
|
for connection in self.connections:
|
|
|
|
# Only check non-local connections unless we own the resource
|
|
|
|
if self.owned or (not self.owned and not connection.local):
|
|
|
|
location = 'relay' if connection.relay else ('local' if connection.local else 'remote')
|
2021-07-27 01:38:16 +00:00
|
|
|
if location not in locations:
|
|
|
|
continue
|
|
|
|
if 'http' in schemes:
|
|
|
|
connections_dict[location]['http'].append(connection.httpuri)
|
|
|
|
if 'https' in schemes:
|
|
|
|
connections_dict[location]['https'].append(connection.uri)
|
2021-02-02 02:59:34 +00:00
|
|
|
if ssl is True: schemes.remove('http')
|
|
|
|
elif ssl is False: schemes.remove('https')
|
|
|
|
connections = []
|
|
|
|
for location in locations:
|
|
|
|
for scheme in schemes:
|
|
|
|
connections.extend(connections_dict[location][scheme])
|
2021-07-27 01:38:16 +00:00
|
|
|
return connections
|
|
|
|
|
|
|
|
def connect(
|
|
|
|
self,
|
|
|
|
ssl=None,
|
|
|
|
timeout=None,
|
2023-05-24 20:55:50 +00:00
|
|
|
locations=None,
|
|
|
|
schemes=None,
|
2021-07-27 01:38:16 +00:00
|
|
|
):
|
|
|
|
""" Returns a new :class:`~plexapi.server.PlexServer` or :class:`~plexapi.client.PlexClient` object.
|
|
|
|
Uses `MyPlexResource.preferred_connections()` to generate the priority order of connection addresses.
|
|
|
|
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.
|
|
|
|
|
|
|
|
Parameters:
|
|
|
|
ssl (bool, 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.
|
|
|
|
timeout (int, optional): The timeout in seconds to attempt each connection.
|
|
|
|
|
|
|
|
Raises:
|
|
|
|
:exc:`~plexapi.exceptions.NotFound`: When unable to connect to any addresses for this resource.
|
|
|
|
"""
|
2023-05-24 20:55:50 +00:00
|
|
|
if locations is None:
|
|
|
|
locations = self.DEFAULT_LOCATION_ORDER[:]
|
|
|
|
if schemes is None:
|
|
|
|
schemes = self.DEFAULT_SCHEME_ORDER[:]
|
|
|
|
|
2022-08-06 03:16:29 +00:00
|
|
|
connections = self.preferred_connections(ssl, locations, schemes)
|
2022-02-27 03:26:08 +00:00
|
|
|
# Try connecting to all known resource connections in parallel, but
|
2014-12-29 03:21:58 +00:00
|
|
|
# only return the first server (in order) that provides a response.
|
2021-02-02 02:59:34 +00:00
|
|
|
cls = PlexServer if 'server' in self.provides else PlexClient
|
2023-05-25 00:44:28 +00:00
|
|
|
listargs = [[cls, url, self.accessToken, self._server._session, timeout] for url in connections]
|
2021-01-20 18:07:03 +00:00
|
|
|
log.debug('Testing %s resource connections..', len(listargs))
|
2017-04-24 02:59:22 +00:00
|
|
|
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
|
2020-11-23 03:06:30 +00:00
|
|
|
:class:`~plexapi.myplex.MyPlexResource` objects.
|
2017-01-22 05:19:52 +00:00
|
|
|
|
|
|
|
Attributes:
|
2017-02-14 04:32:27 +00:00
|
|
|
TAG (str): 'Connection'
|
2023-07-27 21:01:18 +00:00
|
|
|
address (str): The connection IP address
|
|
|
|
httpuri (str): Full HTTP URL
|
|
|
|
ipv6 (bool): True if the address is IPv6
|
|
|
|
local (bool): True if the address is local
|
|
|
|
port (int): The connection port
|
2017-01-22 05:19:52 +00:00
|
|
|
protocol (str): HTTP or HTTPS
|
2023-07-27 21:01:18 +00:00
|
|
|
relay (bool): True if the address uses the Plex Relay
|
|
|
|
uri (str): Full connetion URL
|
2017-01-02 21:06:40 +00:00
|
|
|
"""
|
2023-07-27 21:01:18 +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.address = data.attrib.get('address')
|
2023-07-27 21:01:18 +00:00
|
|
|
self.ipv6 = utils.cast(bool, data.attrib.get('IPv6'))
|
|
|
|
self.local = utils.cast(bool, data.attrib.get('local'))
|
2016-04-07 05:39:04 +00:00
|
|
|
self.port = utils.cast(int, data.attrib.get('port'))
|
2023-07-27 21:01:18 +00:00
|
|
|
self.protocol = data.attrib.get('protocol')
|
|
|
|
self.relay = utils.cast(bool, data.attrib.get('relay'))
|
2015-06-08 16:41:47 +00:00
|
|
|
self.uri = data.attrib.get('uri')
|
2022-08-28 05:56:01 +00:00
|
|
|
self.httpuri = f'http://{self.address}:{self.port}'
|
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'))
|
2021-05-25 00:37:37 +00:00
|
|
|
self.connections = self.listAttrs(data, 'uri', etag='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:
|
2020-11-23 20:20:56 +00:00
|
|
|
:exc:`~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
|
2023-05-25 00:44:28 +00:00
|
|
|
listargs = [[cls, url, self.token, self._server._session, timeout] for url in self.connections]
|
2021-01-20 18:07:03 +00:00
|
|
|
log.debug('Testing %s device connections..', len(listargs))
|
2017-04-24 02:59:22 +00:00
|
|
|
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. """
|
2022-08-28 05:56:01 +00:00
|
|
|
key = f'https://plex.tv/devices/{self.id}.xml'
|
2017-02-25 07:37:30 +00:00
|
|
|
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):
|
2020-11-23 03:06:30 +00:00
|
|
|
""" Returns an instance of :class:`~plexapi.sync.SyncList` for current device.
|
2018-09-08 15:25:16 +00:00
|
|
|
|
|
|
|
Raises:
|
2022-02-27 03:26:08 +00:00
|
|
|
:exc:`~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
|
|
|
|
2022-05-30 16:05:00 +00:00
|
|
|
class MyPlexPinLogin:
|
2019-12-06 14:36:32 +00:00
|
|
|
"""
|
|
|
|
MyPlex PIN login class which supports getting the four character PIN which the user must
|
|
|
|
enter on https://plex.tv/link to authenticate the client and provide an access token to
|
|
|
|
create a :class:`~plexapi.myplex.MyPlexAccount` instance.
|
|
|
|
This helper class supports a polling, threaded and callback approach.
|
|
|
|
|
|
|
|
- The polling approach expects the developer to periodically check if the PIN login was
|
2020-11-23 03:06:30 +00:00
|
|
|
successful using :func:`~plexapi.myplex.MyPlexPinLogin.checkLogin`.
|
2019-12-06 14:36:32 +00:00
|
|
|
- The threaded approach expects the developer to call
|
2020-11-23 03:06:30 +00:00
|
|
|
:func:`~plexapi.myplex.MyPlexPinLogin.run` and then at a later time call
|
|
|
|
:func:`~plexapi.myplex.MyPlexPinLogin.waitForLogin` to wait for and check the result.
|
2019-12-06 14:36:32 +00:00
|
|
|
- The callback approach is an extension of the threaded approach and expects the developer
|
2020-11-23 03:06:30 +00:00
|
|
|
to pass the `callback` parameter to the call to :func:`~plexapi.myplex.MyPlexPinLogin.run`.
|
2019-12-06 14:36:32 +00:00
|
|
|
The callback will be called when the thread waiting for the PIN login to succeed either
|
|
|
|
finishes or expires. The parameter passed to the callback is the received authentication
|
|
|
|
token or `None` if the login expired.
|
|
|
|
|
|
|
|
Parameters:
|
|
|
|
session (requests.Session, optional): Use your own session object if you want to
|
|
|
|
cache the http responses from PMS
|
|
|
|
requestTimeout (int): timeout in seconds on initial connect to plex.tv (default config.TIMEOUT).
|
2022-07-21 02:48:52 +00:00
|
|
|
headers (dict): A dict of X-Plex headers to send with requests.
|
|
|
|
oauth (bool): True to use Plex OAuth instead of PIN login.
|
2019-12-06 14:36:32 +00:00
|
|
|
|
|
|
|
Attributes:
|
2020-12-06 22:00:35 +00:00
|
|
|
PINS (str): 'https://plex.tv/api/v2/pins'
|
|
|
|
CHECKPINS (str): 'https://plex.tv/api/v2/pins/{pinid}'
|
2019-12-06 14:36:32 +00:00
|
|
|
POLLINTERVAL (int): 1
|
|
|
|
finished (bool): Whether the pin login has finished or not.
|
|
|
|
expired (bool): Whether the pin login has expired or not.
|
|
|
|
token (str): Token retrieved through the pin login.
|
|
|
|
pin (str): Pin to use for the login on https://plex.tv/link.
|
|
|
|
"""
|
2020-12-06 22:00:35 +00:00
|
|
|
PINS = 'https://plex.tv/api/v2/pins' # get
|
|
|
|
CHECKPINS = 'https://plex.tv/api/v2/pins/{pinid}' # get
|
2019-12-06 14:36:32 +00:00
|
|
|
POLLINTERVAL = 1
|
|
|
|
|
2022-07-21 02:48:52 +00:00
|
|
|
def __init__(self, session=None, requestTimeout=None, headers=None, oauth=False):
|
2019-12-06 14:36:32 +00:00
|
|
|
super(MyPlexPinLogin, self).__init__()
|
|
|
|
self._session = session or requests.Session()
|
|
|
|
self._requestTimeout = requestTimeout or TIMEOUT
|
2020-12-06 23:54:48 +00:00
|
|
|
self.headers = headers
|
2019-12-06 14:36:32 +00:00
|
|
|
|
2022-07-21 02:48:52 +00:00
|
|
|
self._oauth = oauth
|
2019-12-06 14:36:32 +00:00
|
|
|
self._loginTimeout = None
|
|
|
|
self._callback = None
|
|
|
|
self._thread = None
|
|
|
|
self._abort = False
|
|
|
|
self._id = None
|
2020-12-06 22:00:35 +00:00
|
|
|
self._code = None
|
2020-12-16 04:41:04 +00:00
|
|
|
self._getCode()
|
2019-12-06 14:36:32 +00:00
|
|
|
|
|
|
|
self.finished = False
|
|
|
|
self.expired = False
|
|
|
|
self.token = None
|
2020-12-06 22:00:35 +00:00
|
|
|
|
|
|
|
@property
|
|
|
|
def pin(self):
|
2022-07-21 02:48:52 +00:00
|
|
|
""" Return the 4 character PIN used for linking a device at https://plex.tv/link. """
|
|
|
|
if self._oauth:
|
|
|
|
raise BadRequest('Cannot use PIN for Plex OAuth login')
|
2020-12-06 22:00:35 +00:00
|
|
|
return self._code
|
2019-12-06 14:36:32 +00:00
|
|
|
|
2022-07-21 02:48:52 +00:00
|
|
|
def oauthUrl(self, forwardUrl=None):
|
|
|
|
""" Return the Plex OAuth url for login.
|
|
|
|
|
|
|
|
Parameters:
|
|
|
|
forwardUrl (str, optional): The url to redirect the client to after login.
|
|
|
|
"""
|
|
|
|
if not self._oauth:
|
|
|
|
raise BadRequest('Must use "MyPlexPinLogin(oauth=True)" for Plex OAuth login.')
|
|
|
|
|
|
|
|
headers = self._headers()
|
|
|
|
params = {
|
|
|
|
'clientID': headers['X-Plex-Client-Identifier'],
|
|
|
|
'context[device][product]': headers['X-Plex-Product'],
|
|
|
|
'context[device][version]': headers['X-Plex-Version'],
|
|
|
|
'context[device][platform]': headers['X-Plex-Platform'],
|
|
|
|
'context[device][platformVersion]': headers['X-Plex-Platform-Version'],
|
|
|
|
'context[device][device]': headers['X-Plex-Device'],
|
|
|
|
'context[device][deviceName]': headers['X-Plex-Device-Name'],
|
|
|
|
'code': self._code
|
|
|
|
}
|
|
|
|
if forwardUrl:
|
|
|
|
params['forwardUrl'] = forwardUrl
|
|
|
|
|
|
|
|
return f'https://app.plex.tv/auth/#!?{urlencode(params)}'
|
|
|
|
|
2019-12-06 14:36:32 +00:00
|
|
|
def run(self, callback=None, timeout=None):
|
|
|
|
""" Starts the thread which monitors the PIN login state.
|
|
|
|
Parameters:
|
|
|
|
callback (Callable[str]): Callback called with the received authentication token (optional).
|
|
|
|
timeout (int): Timeout in seconds waiting for the PIN login to succeed (optional).
|
|
|
|
|
|
|
|
Raises:
|
2021-01-03 00:44:18 +00:00
|
|
|
:class:`RuntimeError`: If the thread is already running.
|
|
|
|
:class:`RuntimeError`: If the PIN login for the current PIN has expired.
|
2019-12-06 14:36:32 +00:00
|
|
|
"""
|
|
|
|
if self._thread and not self._abort:
|
|
|
|
raise RuntimeError('MyPlexPinLogin thread is already running')
|
|
|
|
if self.expired:
|
|
|
|
raise RuntimeError('MyPlexPinLogin has expired')
|
|
|
|
|
|
|
|
self._loginTimeout = timeout
|
|
|
|
self._callback = callback
|
|
|
|
self._abort = False
|
|
|
|
self.finished = False
|
|
|
|
self._thread = threading.Thread(target=self._pollLogin, name='plexapi.myplex.MyPlexPinLogin')
|
|
|
|
self._thread.start()
|
|
|
|
|
|
|
|
def waitForLogin(self):
|
|
|
|
""" Waits for the PIN login to succeed or expire.
|
|
|
|
Parameters:
|
|
|
|
callback (Callable[str]): Callback called with the received authentication token (optional).
|
|
|
|
timeout (int): Timeout in seconds waiting for the PIN login to succeed (optional).
|
|
|
|
|
|
|
|
Returns:
|
|
|
|
`True` if the PIN login succeeded or `False` otherwise.
|
|
|
|
"""
|
|
|
|
if not self._thread or self._abort:
|
|
|
|
return False
|
|
|
|
|
|
|
|
self._thread.join()
|
|
|
|
if self.expired or not self.token:
|
|
|
|
return False
|
|
|
|
|
|
|
|
return True
|
|
|
|
|
|
|
|
def stop(self):
|
|
|
|
""" Stops the thread monitoring the PIN login state. """
|
|
|
|
if not self._thread or self._abort:
|
|
|
|
return
|
|
|
|
|
|
|
|
self._abort = True
|
|
|
|
self._thread.join()
|
|
|
|
|
|
|
|
def checkLogin(self):
|
|
|
|
""" Returns `True` if the PIN login has succeeded. """
|
|
|
|
if self._thread:
|
|
|
|
return False
|
|
|
|
|
|
|
|
try:
|
|
|
|
return self._checkLogin()
|
|
|
|
except Exception:
|
|
|
|
self.expired = True
|
|
|
|
self.finished = True
|
|
|
|
|
|
|
|
return False
|
|
|
|
|
2020-12-06 22:00:35 +00:00
|
|
|
def _getCode(self):
|
2019-12-06 14:36:32 +00:00
|
|
|
url = self.PINS
|
2022-07-21 02:48:52 +00:00
|
|
|
|
|
|
|
if self._oauth:
|
|
|
|
params = {'strong': True}
|
|
|
|
else:
|
|
|
|
params = None
|
|
|
|
|
|
|
|
response = self._query(url, self._session.post, params=params)
|
2023-08-27 20:09:27 +00:00
|
|
|
if response is None:
|
2019-12-06 14:36:32 +00:00
|
|
|
return None
|
|
|
|
|
2020-12-06 22:00:35 +00:00
|
|
|
self._id = response.attrib.get('id')
|
|
|
|
self._code = response.attrib.get('code')
|
2019-12-06 14:36:32 +00:00
|
|
|
|
2020-12-06 22:00:35 +00:00
|
|
|
return self._code
|
2019-12-06 14:36:32 +00:00
|
|
|
|
|
|
|
def _checkLogin(self):
|
|
|
|
if not self._id:
|
|
|
|
return False
|
|
|
|
|
|
|
|
if self.token:
|
|
|
|
return True
|
|
|
|
|
|
|
|
url = self.CHECKPINS.format(pinid=self._id)
|
|
|
|
response = self._query(url)
|
2023-08-27 20:09:27 +00:00
|
|
|
if response is None:
|
2019-12-06 14:36:32 +00:00
|
|
|
return False
|
|
|
|
|
2020-12-06 22:00:35 +00:00
|
|
|
token = response.attrib.get('authToken')
|
2019-12-06 14:36:32 +00:00
|
|
|
if not token:
|
|
|
|
return False
|
|
|
|
|
|
|
|
self.token = token
|
|
|
|
self.finished = True
|
|
|
|
return True
|
|
|
|
|
|
|
|
def _pollLogin(self):
|
|
|
|
try:
|
|
|
|
start = time.time()
|
|
|
|
while not self._abort and (not self._loginTimeout or (time.time() - start) < self._loginTimeout):
|
|
|
|
try:
|
|
|
|
result = self._checkLogin()
|
|
|
|
except Exception:
|
|
|
|
self.expired = True
|
|
|
|
break
|
|
|
|
|
|
|
|
if result:
|
|
|
|
break
|
|
|
|
|
|
|
|
time.sleep(self.POLLINTERVAL)
|
|
|
|
|
|
|
|
if self.token and self._callback:
|
|
|
|
self._callback(self.token)
|
|
|
|
finally:
|
|
|
|
self.finished = True
|
|
|
|
|
2020-12-06 23:54:48 +00:00
|
|
|
def _headers(self, **kwargs):
|
|
|
|
""" Returns dict containing base headers for all requests for pin login. """
|
|
|
|
headers = BASE_HEADERS.copy()
|
|
|
|
if self.headers:
|
|
|
|
headers.update(self.headers)
|
|
|
|
headers.update(kwargs)
|
|
|
|
return headers
|
|
|
|
|
2020-12-06 22:00:35 +00:00
|
|
|
def _query(self, url, method=None, headers=None, **kwargs):
|
2019-12-06 14:36:32 +00:00
|
|
|
method = method or self._session.get
|
|
|
|
log.debug('%s %s', method.__name__.upper(), url)
|
2020-12-06 23:54:48 +00:00
|
|
|
headers = headers or self._headers()
|
2020-12-06 22:00:35 +00:00
|
|
|
response = method(url, headers=headers, timeout=self._requestTimeout, **kwargs)
|
2019-12-06 14:36:32 +00:00
|
|
|
if not response.ok: # pragma: no cover
|
|
|
|
codename = codes.get(response.status_code)[0]
|
|
|
|
errtext = response.text.replace('\n', ' ')
|
2022-08-28 05:56:01 +00:00
|
|
|
raise BadRequest(f'({response.status_code}) {codename} {response.url}; {errtext}')
|
2019-12-06 14:36:32 +00:00
|
|
|
data = response.text.encode('utf8')
|
|
|
|
return ElementTree.fromstring(data) if data.strip() else None
|
|
|
|
|
|
|
|
|
2023-05-25 00:44:28 +00:00
|
|
|
def _connect(cls, url, token, session, 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__()
|
2023-05-25 00:44:28 +00:00
|
|
|
session (requests.Session): session which sould be passed as `session` argument to cls.__init()
|
2018-09-14 18:28:35 +00:00
|
|
|
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:
|
2023-05-25 00:44:28 +00:00
|
|
|
device = cls(baseurl=url, token=token, session=session, timeout=timeout)
|
2017-04-24 02:59:22 +00:00
|
|
|
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'
|
2021-01-20 18:07:03 +00:00
|
|
|
log.debug('%s connection %s (%ss): %s?X-Plex-Token=%s', ctype, okerr, runtime, url, token)
|
2017-04-24 02:59:22 +00:00
|
|
|
results = [r[2] for r in results if r and r[2] is not None]
|
|
|
|
if results:
|
2021-01-20 18:07:03 +00:00
|
|
|
log.debug('Connecting to %s: %s?X-Plex-Token=%s', ctype, results[0]._baseurl, results[0]._token)
|
2017-04-24 02:59:22 +00:00
|
|
|
return results[0]
|
2022-08-28 05:56:01 +00:00
|
|
|
raise NotFound(f'Unable to connect to {ctype.lower()}: {name}')
|
2020-07-17 01:01:49 +00:00
|
|
|
|
|
|
|
|
|
|
|
class AccountOptOut(PlexObject):
|
2020-07-17 01:21:26 +00:00
|
|
|
""" Represents a single AccountOptOut
|
|
|
|
'https://plex.tv/api/v2/user/{userUUID}/settings/opt_outs'
|
|
|
|
|
|
|
|
Attributes:
|
2021-06-06 23:42:43 +00:00
|
|
|
TAG (str): optOut
|
2020-07-17 01:21:26 +00:00
|
|
|
key (str): Online Media Source key
|
2021-06-06 23:42:43 +00:00
|
|
|
value (str): Online Media Source opt_in, opt_out, or opt_out_managed
|
2020-07-17 01:21:26 +00:00
|
|
|
"""
|
2021-06-06 23:42:43 +00:00
|
|
|
TAG = 'optOut'
|
|
|
|
CHOICES = {'opt_in', 'opt_out', 'opt_out_managed'}
|
2020-09-01 01:12:36 +00:00
|
|
|
|
2020-07-17 01:01:49 +00:00
|
|
|
def _loadData(self, data):
|
|
|
|
self.key = data.attrib.get('key')
|
|
|
|
self.value = data.attrib.get('value')
|
2020-08-30 06:02:07 +00:00
|
|
|
|
2021-06-06 23:42:43 +00:00
|
|
|
def _updateOptOut(self, option):
|
|
|
|
""" Sets the Online Media Sources option.
|
|
|
|
|
2021-05-28 14:02:17 +00:00
|
|
|
Parameters:
|
|
|
|
option (str): see CHOICES
|
|
|
|
|
|
|
|
Raises:
|
2021-06-06 23:42:43 +00:00
|
|
|
:exc:`~plexapi.exceptions.NotFound`: ``option`` str not found in CHOICES.
|
2021-05-28 14:02:17 +00:00
|
|
|
"""
|
2020-08-30 06:02:07 +00:00
|
|
|
if option not in self.CHOICES:
|
2022-08-28 05:56:01 +00:00
|
|
|
raise NotFound(f'{option} not found in available choices: {self.CHOICES}')
|
|
|
|
url = self._server.OPTOUTS.format(userUUID=self._server.uuid)
|
2021-06-06 23:42:43 +00:00
|
|
|
params = {'key': self.key, 'value': option}
|
|
|
|
self._server.query(url, method=self._server._session.post, params=params)
|
|
|
|
self.value = option # assume query successful and set the value to option
|
|
|
|
|
|
|
|
def optIn(self):
|
|
|
|
""" Sets the Online Media Source to "Enabled". """
|
|
|
|
self._updateOptOut('opt_in')
|
|
|
|
|
|
|
|
def optOut(self):
|
|
|
|
""" Sets the Online Media Source to "Disabled". """
|
|
|
|
self._updateOptOut('opt_out')
|
|
|
|
|
|
|
|
def optOutManaged(self):
|
|
|
|
""" Sets the Online Media Source to "Disabled for Managed Users".
|
|
|
|
|
|
|
|
Raises:
|
|
|
|
:exc:`~plexapi.exceptions.BadRequest`: When trying to opt out music.
|
|
|
|
"""
|
|
|
|
if self.key == 'tv.plex.provider.music':
|
2022-08-28 05:56:01 +00:00
|
|
|
raise BadRequest(f'{self.key} does not have the option to opt out managed users.')
|
2021-06-06 23:42:43 +00:00
|
|
|
self._updateOptOut('opt_out_managed')
|
2022-07-21 02:37:48 +00:00
|
|
|
|
|
|
|
|
|
|
|
class UserState(PlexObject):
|
|
|
|
""" Represents a single UserState
|
|
|
|
|
|
|
|
Attributes:
|
|
|
|
TAG (str): UserState
|
|
|
|
lastViewedAt (datetime): Datetime the item was last played.
|
|
|
|
ratingKey (str): Unique key identifying the item.
|
|
|
|
type (str): The media type of the item.
|
|
|
|
viewCount (int): Count of times the item was played.
|
|
|
|
viewedLeafCount (int): Number of items marked as played in the show/season.
|
|
|
|
viewOffset (int): Time offset in milliseconds from the start of the content
|
|
|
|
viewState (bool): True or False if the item has been played.
|
|
|
|
watchlistedAt (datetime): Datetime the item was added to the watchlist.
|
|
|
|
"""
|
|
|
|
TAG = 'UserState'
|
|
|
|
|
|
|
|
def __repr__(self):
|
|
|
|
return f'<{self.__class__.__name__}:{self.ratingKey}>'
|
|
|
|
|
|
|
|
def _loadData(self, data):
|
|
|
|
self.lastViewedAt = utils.toDatetime(data.attrib.get('lastViewedAt'))
|
|
|
|
self.ratingKey = data.attrib.get('ratingKey')
|
|
|
|
self.type = data.attrib.get('type')
|
|
|
|
self.viewCount = utils.cast(int, data.attrib.get('viewCount', 0))
|
|
|
|
self.viewedLeafCount = utils.cast(int, data.attrib.get('viewedLeafCount', 0))
|
|
|
|
self.viewOffset = utils.cast(int, data.attrib.get('viewOffset', 0))
|
|
|
|
self.viewState = data.attrib.get('viewState') == 'complete'
|
|
|
|
self.watchlistedAt = utils.toDatetime(data.attrib.get('watchlistedAt'))
|
2023-08-27 19:34:52 +00:00
|
|
|
|
|
|
|
|
|
|
|
class GeoLocation(PlexObject):
|
|
|
|
""" Represents a signle IP address geolocation
|
|
|
|
|
|
|
|
Attributes:
|
|
|
|
TAG (str): location
|
|
|
|
city (str): City name
|
|
|
|
code (str): Country code
|
|
|
|
continentCode (str): Continent code
|
|
|
|
coordinates (Tuple<float>): Latitude and longitude
|
|
|
|
country (str): Country name
|
|
|
|
europeanUnionMember (bool): True if the country is a member of the European Union
|
|
|
|
inPrivacyRestrictedCountry (bool): True if the country is privacy restricted
|
|
|
|
postalCode (str): Postal code
|
|
|
|
subdivisions (str): Subdivision name
|
|
|
|
timezone (str): Timezone
|
|
|
|
"""
|
|
|
|
TAG = 'location'
|
|
|
|
|
|
|
|
def _loadData(self, data):
|
|
|
|
self._data = data
|
|
|
|
self.city = data.attrib.get('city')
|
|
|
|
self.code = data.attrib.get('code')
|
|
|
|
self.continentCode = data.attrib.get('continent_code')
|
|
|
|
self.coordinates = tuple(
|
|
|
|
utils.cast(float, coord) for coord in (data.attrib.get('coordinates') or ',').split(','))
|
|
|
|
self.country = data.attrib.get('country')
|
|
|
|
self.postalCode = data.attrib.get('postal_code')
|
|
|
|
self.subdivisions = data.attrib.get('subdivisions')
|
|
|
|
self.timezone = data.attrib.get('time_zone')
|
|
|
|
|
|
|
|
europeanUnionMember = data.attrib.get('european_union_member')
|
|
|
|
self.europeanUnionMember = (
|
|
|
|
False if europeanUnionMember == 'Unknown' else utils.cast(bool, europeanUnionMember))
|
|
|
|
|
|
|
|
inPrivacyRestrictedCountry = data.attrib.get('in_privacy_restricted_country')
|
|
|
|
self.inPrivacyRestrictedCountry = (
|
|
|
|
False if inPrivacyRestrictedCountry == 'Unknown' else utils.cast(bool, inPrivacyRestrictedCountry))
|