python-plexapi/plexapi/server.py

122 lines
4.4 KiB
Python
Raw Normal View History

2014-12-29 03:21:58 +00:00
"""
PlexServer
"""
import requests
2014-12-29 03:21:58 +00:00
from requests.status_codes import _codes as codes
from plexapi import BASE_HEADERS, TIMEOUT
from plexapi import log, audio, video, utils
2014-12-29 03:21:58 +00:00
from plexapi.client import Client
from plexapi.exceptions import BadRequest, NotFound
from plexapi.library import Library
from plexapi.myplex import MyPlexAccount
from plexapi.playqueue import PlayQueue
from xml.etree import ElementTree
try:
from urllib import quote # Python2
except ImportError:
from urllib.parse import quote # Python3
2014-12-29 03:21:58 +00:00
TOTAL_QUERIES = 0
2015-06-08 16:41:47 +00:00
DEFAULT_BASEURI = 'http://localhost:32400'
2014-12-29 03:21:58 +00:00
class PlexServer(object):
2015-06-08 16:41:47 +00:00
2016-01-29 23:13:57 +00:00
def __init__(self, baseuri=None, token=None, session=None):
2015-06-08 16:41:47 +00:00
self.baseuri = baseuri or DEFAULT_BASEURI
2014-12-29 03:21:58 +00:00
self.token = token
2016-03-16 03:53:04 +00:00
self.session = session or requests.Session()
2014-12-29 03:21:58 +00:00
data = self._connect()
self.friendlyName = data.attrib.get('friendlyName')
self.machineIdentifier = data.attrib.get('machineIdentifier')
self.myPlex = bool(data.attrib.get('myPlex'))
self.myPlexMappingState = data.attrib.get('myPlexMappingState')
self.myPlexSigninState = data.attrib.get('myPlexSigninState')
self.myPlexSubscription = data.attrib.get('myPlexSubscription')
self.myPlexUsername = data.attrib.get('myPlexUsername')
self.platform = data.attrib.get('platform')
self.platformVersion = data.attrib.get('platformVersion')
self.transcoderActiveVideoSessions = int(data.attrib.get('transcoderActiveVideoSessions', 0))
self.updatedAt = int(data.attrib.get('updatedAt', 0))
2014-12-29 03:21:58 +00:00
self.version = data.attrib.get('version')
def __repr__(self):
2015-06-08 16:41:47 +00:00
return '<%s:%s>' % (self.__class__.__name__, self.baseuri)
2014-12-29 03:21:58 +00:00
def _connect(self):
try:
return self.query('/')
2015-02-17 20:35:17 +00:00
except Exception as err:
2015-06-08 16:41:47 +00:00
log.error('%s: %s', self.baseuri, err)
raise NotFound('No server found at: %s' % self.baseuri)
2014-12-29 03:21:58 +00:00
@property
def library(self):
return Library(self, self.query('/library/'))
def account(self):
data = self.query('/myplex/account')
return MyPlexAccount(self, data)
def clients(self):
items = []
for elem in self.query('/clients'):
items.append(Client(self, elem))
return items
def client(self, name):
for elem in self.query('/clients'):
if elem.attrib.get('name').lower() == name.lower():
return Client(self, elem)
raise NotFound('Unknown client name: %s' % name)
def createPlayQueue(self, video):
return PlayQueue.create(self, video)
def headers(self):
headers = BASE_HEADERS
if self.token:
headers['X-Plex-Token'] = self.token
return headers
2016-01-29 23:13:57 +00:00
def query(self, path, method=None, **kwargs):
2015-02-24 03:42:29 +00:00
global TOTAL_QUERIES
TOTAL_QUERIES += 1
2014-12-29 03:21:58 +00:00
url = self.url(path)
2016-03-16 03:53:04 +00:00
method = method or self.session.get
2015-02-24 03:42:29 +00:00
log.info('%s %s', method.__name__.upper(), url)
response = method(url, headers=self.headers(), timeout=TIMEOUT, **kwargs)
2014-12-29 03:21:58 +00:00
if response.status_code not in [200, 201]:
codename = codes.get(response.status_code)[0]
raise BadRequest('(%s) %s' % (response.status_code, codename))
data = response.text.encode('utf8')
return ElementTree.fromstring(data) if data else None
def search(self, query, mediatype=None):
# Searching at this level is meant to be quick and dirty, if you're looking
# for more in-depth search filters look at plex.library.search().
_audio = lambda: self._search(audio, query, mediatype)
_video = lambda: self._search(video, query, mediatype)
results = []
qresults = utils.threaded([_audio, _video])
for item in iter(qresults.get_nowait, None):
results += item
return results
def _search(self, module, query, mediatype=None):
items = module.list_items(self, '/search?query=%s' % quote(query))
if mediatype:
return [item for item in items if item.type == mediatype]
return items
2015-02-17 20:35:17 +00:00
def sessions(self):
return video.list_items(self, '/status/sessions')
2014-12-29 03:21:58 +00:00
def url(self, path):
2015-06-08 16:41:47 +00:00
if self.token:
delim = '&' if '?' in path else '?'
return '%s%s%sX-Plex-Token=%s' % (self.baseuri, path, delim, self.token)
return '%s%s' % (self.baseuri, path)