python-plexapi/plexapi/myplex.py

169 lines
7 KiB
Python
Raw Normal View History

2014-12-29 03:21:58 +00:00
"""
PlexAPI MyPlex
"""
import plexapi, requests
2015-02-17 20:35:17 +00:00
from plexapi import TIMEOUT, log
2015-02-24 03:42:29 +00:00
from plexapi.exceptions import BadRequest, NotFound, Unauthorized
2015-06-08 16:41:47 +00:00
from plexapi.utils import cast, toDatetime
2014-12-29 03:21:58 +00:00
from requests.status_codes import _codes as codes
from threading import Thread
from xml.etree import ElementTree
class MyPlexUser:
""" Logs into my.plexapp.com to fetch account and token information. This
useful to get a token if not on the local network.
"""
SIGNIN = 'https://my.plexapp.com/users/sign_in.xml'
2015-02-17 20:35:17 +00:00
def __init__(self, data, initpath=None):
self.initpath = initpath
2014-12-29 03:21:58 +00:00
self.email = data.attrib.get('email')
self.id = data.attrib.get('id')
self.thumb = data.attrib.get('thumb')
self.username = data.attrib.get('username')
self.title = data.attrib.get('title')
self.cloudSyncDevice = data.attrib.get('cloudSyncDevice')
self.authenticationToken = data.attrib.get('authenticationToken')
self.queueEmail = data.attrib.get('queueEmail')
self.queueUid = data.attrib.get('queueUid')
2015-06-08 16:41:47 +00:00
def resources(self):
return MyPlexResource.fetch_resources(self.authenticationToken)
2014-12-29 03:21:58 +00:00
2015-06-08 16:41:47 +00:00
def getResource(self, search, port=32400):
2015-02-20 20:06:41 +00:00
""" Searches server.name, server.sourceTitle and server.host:server.port
from the list of available for this PlexUser.
"""
2015-06-08 16:41:47 +00:00
return _findResource(self.resources(), search, port)
2014-12-29 03:21:58 +00:00
2015-02-17 20:35:17 +00:00
@classmethod
def signin(cls, username, password):
2015-02-24 03:42:29 +00:00
if 'X-Plex-Token' in plexapi.BASE_HEADERS:
del plexapi.BASE_HEADERS['X-Plex-Token']
2015-02-17 20:35:17 +00:00
auth = (username, password)
log.info('POST %s', cls.SIGNIN)
response = requests.post(cls.SIGNIN, headers=plexapi.BASE_HEADERS, auth=auth, timeout=TIMEOUT)
if response.status_code != requests.codes.created:
codename = codes.get(response.status_code)[0]
2015-02-24 03:42:29 +00:00
if response.status_code == 401:
raise Unauthorized('(%s) %s' % (response.status_code, codename))
2015-02-17 20:35:17 +00:00
raise BadRequest('(%s) %s' % (response.status_code, codename))
data = ElementTree.fromstring(response.text.encode('utf8'))
return cls(data)
2014-12-29 03:21:58 +00:00
class MyPlexAccount:
""" Represents myPlex account if you already have a connection to a server. """
def __init__(self, server, data):
self.authToken = data.attrib.get('authToken')
self.username = data.attrib.get('username')
self.mappingState = data.attrib.get('mappingState')
self.mappingError = data.attrib.get('mappingError')
self.mappingErrorMessage = data.attrib.get('mappingErrorMessage')
self.signInState = data.attrib.get('signInState')
self.publicAddress = data.attrib.get('publicAddress')
self.publicPort = data.attrib.get('publicPort')
self.privateAddress = data.attrib.get('privateAddress')
self.privatePort = data.attrib.get('privatePort')
self.subscriptionFeatures = data.attrib.get('subscriptionFeatures')
self.subscriptionActive = data.attrib.get('subscriptionActive')
self.subscriptionState = data.attrib.get('subscriptionState')
2015-06-08 16:41:47 +00:00
def resources(self):
return MyPlexResource.fetch_resources(self.authToken)
2014-12-29 03:21:58 +00:00
2015-06-08 16:41:47 +00:00
def getResource(self, search, port=32400):
2015-02-20 20:06:41 +00:00
""" Searches server.name, server.sourceTitle and server.host:server.port
from the list of available for this PlexAccount.
"""
2015-06-08 16:41:47 +00:00
return _findResource(self.resources(), search, port)
2014-12-29 03:21:58 +00:00
2015-06-08 16:41:47 +00:00
class MyPlexResource:
RESOURCES = 'https://plex.tv/api/resources?includeHttps=1'
2014-12-29 03:21:58 +00:00
def __init__(self, data):
self.name = data.attrib.get('name')
2015-06-08 16:41:47 +00:00
self.accessToken = data.attrib.get('accessToken')
self.product = data.attrib.get('product')
self.productVersion = data.attrib.get('productVersion')
self.platform = data.attrib.get('platform')
self.platformVersion = data.attrib.get('platformVersion')
self.device = data.attrib.get('device')
self.clientIdentifier = data.attrib.get('clientIdentifier')
2014-12-29 03:21:58 +00:00
self.createdAt = toDatetime(data.attrib.get('createdAt'))
2015-06-08 16:41:47 +00:00
self.lastSeenAt = toDatetime(data.attrib.get('lastSeenAt'))
self.provides = data.attrib.get('provides')
2014-12-29 03:21:58 +00:00
self.owned = cast(bool, data.attrib.get('owned'))
2015-06-08 16:41:47 +00:00
self.home = cast(bool, data.attrib.get('home'))
2014-12-29 03:21:58 +00:00
self.synced = cast(bool, data.attrib.get('synced'))
2015-06-08 16:41:47 +00:00
self.presence = cast(bool, data.attrib.get('presence'))
self.connections = [ResourceConnection(elem) for elem in data if elem.tag == 'Connection']
2014-12-29 03:21:58 +00:00
def __repr__(self):
return '<%s:%s>' % (self.__class__.__name__, self.name.encode('utf8'))
def connect(self):
2015-06-08 16:41:47 +00:00
# Only check non-local connections unless we own the resource
connections = sorted(self.connections, key=lambda c:c.local, reverse=True)
if not self.owned:
connections = [c for c in connections if c.local is False]
# Try connecting to all known resource connections in parellel, but
2014-12-29 03:21:58 +00:00
# only return the first server (in order) that provides a response.
2015-06-08 16:41:47 +00:00
threads = [None] * len(connections)
results = [None] * len(connections)
for i in range(len(connections)):
args = (connections[i].uri, results, i)
2014-12-29 03:21:58 +00:00
threads[i] = Thread(target=self._connect, args=args)
threads[i].start()
for thread in threads:
thread.join()
2015-06-08 16:41:47 +00:00
results = [r for r in results if r]
if not results:
raise NotFound('Unable to connect to resource: %s' % self.name)
log.info('Connecting to server: %s', results[0])
return results[0]
def _connect(self, uri, results, i):
2014-12-29 03:21:58 +00:00
try:
2015-06-08 16:41:47 +00:00
from plexapi.server import PlexServer
results[i] = PlexServer(uri, self.accessToken)
2014-12-29 03:21:58 +00:00
except NotFound:
results[i] = None
@classmethod
2015-06-08 16:41:47 +00:00
def fetch_resources(cls, token):
2014-12-29 03:21:58 +00:00
headers = plexapi.BASE_HEADERS
headers['X-Plex-Token'] = token
2015-06-08 16:41:47 +00:00
log.info('GET %s?X-Plex-Token=%s', cls.RESOURCES, token)
response = requests.get(cls.RESOURCES, headers=headers, timeout=TIMEOUT)
2014-12-29 03:21:58 +00:00
data = ElementTree.fromstring(response.text.encode('utf8'))
2015-06-08 16:41:47 +00:00
return [MyPlexResource(elem) for elem in data]
class ResourceConnection:
def __init__(self, data):
self.protocol = data.attrib.get('protocol')
self.address = data.attrib.get('address')
self.port = cast(int, data.attrib.get('port'))
self.uri = data.attrib.get('uri')
self.local = cast(bool, data.attrib.get('local'))
def __repr__(self):
return '<%s:%s>' % (self.__class__.__name__, self.uri.encode('utf8'))
2015-02-20 20:06:41 +00:00
2015-06-08 16:41:47 +00:00
def _findResource(resources, search, port=32400):
""" Searches server.name """
2015-02-20 20:06:41 +00:00
search = search.lower()
2015-06-08 16:41:47 +00:00
log.info('Looking for server: %s', search)
for server in resources:
if search == server.name.lower():
2015-02-20 20:06:41 +00:00
log.info('Server found: %s', server)
return server
2015-06-08 16:41:47 +00:00
log.info('Unable to find server: %s', search)
raise NotFound('Unable to find server: %s' % search)