2016-01-23 01:37:20 +11:00
|
|
|
# -*- coding: utf-8 -*-
|
2016-09-03 01:20:19 +10:00
|
|
|
import logging
|
2016-12-21 02:38:04 +11:00
|
|
|
from threading import Thread
|
2016-07-22 23:04:42 +10:00
|
|
|
import Queue
|
2016-12-21 02:38:04 +11:00
|
|
|
from socket import SHUT_RDWR
|
2017-03-14 07:39:07 +11:00
|
|
|
from urllib import urlencode
|
2016-01-23 01:37:20 +11:00
|
|
|
|
2017-03-14 07:39:07 +11:00
|
|
|
from xbmc import sleep, executebuiltin
|
2016-01-23 01:37:20 +11:00
|
|
|
|
2017-05-17 21:55:24 +10:00
|
|
|
from utils import settings, thread_methods
|
2016-04-03 01:46:23 +11:00
|
|
|
from plexbmchelper import listener, plexgdm, subscribers, functions, \
|
2016-09-03 01:20:19 +10:00
|
|
|
httppersist, plexsettings
|
2017-02-19 03:15:37 +11:00
|
|
|
from PlexFunctions import ParseContainerKey, GetPlexMetadata
|
|
|
|
from PlexAPI import API
|
2016-08-07 23:33:36 +10:00
|
|
|
import player
|
2017-03-06 02:51:13 +11:00
|
|
|
import variables as v
|
2017-03-05 03:54:24 +11:00
|
|
|
|
2016-09-03 01:20:19 +10:00
|
|
|
###############################################################################
|
2016-01-23 01:37:20 +11:00
|
|
|
|
2016-09-03 01:20:19 +10:00
|
|
|
log = logging.getLogger("PLEX."+__name__)
|
|
|
|
|
|
|
|
###############################################################################
|
|
|
|
|
|
|
|
|
2017-05-17 21:55:24 +10:00
|
|
|
@thread_methods(add_suspends=['PMS_STATUS'])
|
2016-12-21 02:38:04 +11:00
|
|
|
class PlexCompanion(Thread):
|
2016-07-21 02:36:31 +10:00
|
|
|
"""
|
|
|
|
"""
|
2016-12-28 03:33:52 +11:00
|
|
|
def __init__(self, callback=None):
|
2016-09-03 01:20:19 +10:00
|
|
|
log.info("----===## Starting PlexCompanion ##===----")
|
2016-12-28 03:33:52 +11:00
|
|
|
if callback is not None:
|
|
|
|
self.mgr = callback
|
2016-09-03 01:20:19 +10:00
|
|
|
self.settings = plexsettings.getSettings()
|
2016-01-23 01:37:20 +11:00
|
|
|
# Start GDM for server/client discovery
|
2016-04-05 18:57:30 +10:00
|
|
|
self.client = plexgdm.plexgdm()
|
|
|
|
self.client.clientDetails(self.settings)
|
2017-02-20 03:07:42 +11:00
|
|
|
log.debug("Registration string is:\n%s"
|
2016-09-03 01:20:19 +10:00
|
|
|
% self.client.getClientDetails())
|
2016-07-24 02:06:47 +10:00
|
|
|
# kodi player instance
|
2016-08-07 23:33:36 +10:00
|
|
|
self.player = player.Player()
|
2016-07-24 02:06:47 +10:00
|
|
|
|
2016-12-21 02:38:04 +11:00
|
|
|
Thread.__init__(self)
|
2016-01-23 01:37:20 +11:00
|
|
|
|
2016-07-22 23:04:42 +10:00
|
|
|
def _getStartItem(self, string):
|
|
|
|
"""
|
|
|
|
Grabs the Plex id from e.g. '/library/metadata/12987'
|
|
|
|
|
|
|
|
and returns the tuple (typus, id) where typus is either 'queueId' or
|
|
|
|
'plexId' and id is the corresponding id as a string
|
|
|
|
"""
|
|
|
|
typus = 'plexId'
|
|
|
|
if string.startswith('/library/metadata'):
|
|
|
|
try:
|
|
|
|
string = string.split('/')[3]
|
|
|
|
except IndexError:
|
|
|
|
string = ''
|
|
|
|
else:
|
2016-09-03 01:20:19 +10:00
|
|
|
log.error('Unknown string! %s' % string)
|
2016-07-22 23:04:42 +10:00
|
|
|
return typus, string
|
|
|
|
|
|
|
|
def processTasks(self, task):
|
|
|
|
"""
|
2016-12-28 23:14:21 +11:00
|
|
|
Processes tasks picked up e.g. by Companion listener, e.g.
|
|
|
|
{'action': 'playlist',
|
|
|
|
'data': {'address': 'xyz.plex.direct',
|
|
|
|
'commandID': '7',
|
|
|
|
'containerKey': '/playQueues/6669?own=1&repeat=0&window=200',
|
|
|
|
'key': '/library/metadata/220493',
|
|
|
|
'machineIdentifier': 'xyz',
|
|
|
|
'offset': '0',
|
|
|
|
'port': '32400',
|
|
|
|
'protocol': 'https',
|
|
|
|
'token': 'transient-cd2527d1-0484-48e0-a5f7-f5caa7d591bd',
|
|
|
|
'type': 'video'}}
|
2016-07-22 23:04:42 +10:00
|
|
|
"""
|
2016-09-03 01:20:19 +10:00
|
|
|
log.debug('Processing: %s' % task)
|
2016-07-22 23:04:42 +10:00
|
|
|
data = task['data']
|
|
|
|
|
2017-03-06 03:51:58 +11:00
|
|
|
if task['action'] == 'alexa':
|
|
|
|
# e.g. Alexa
|
|
|
|
xml = GetPlexMetadata(data['key'])
|
|
|
|
try:
|
|
|
|
xml[0].attrib
|
|
|
|
except (AttributeError, IndexError, TypeError):
|
|
|
|
log.error('Could not download Plex metadata')
|
|
|
|
return
|
|
|
|
api = API(xml[0])
|
|
|
|
if api.getType() == v.PLEX_TYPE_ALBUM:
|
|
|
|
log.debug('Plex music album detected')
|
|
|
|
self.mgr.playqueue.init_playqueue_from_plex_children(
|
|
|
|
api.getRatingKey())
|
|
|
|
else:
|
2017-03-14 07:39:07 +11:00
|
|
|
params = {
|
|
|
|
'mode': 'plex_node',
|
|
|
|
'key': '{server}%s' % data.get('key'),
|
|
|
|
'view_offset': data.get('offset'),
|
|
|
|
'play_directly': 'true',
|
|
|
|
'node': 'false'
|
|
|
|
}
|
|
|
|
executebuiltin('RunPlugin(plugin://%s?%s)'
|
|
|
|
% (v.ADDON_ID, urlencode(params)))
|
2017-03-06 03:51:58 +11:00
|
|
|
|
|
|
|
elif (task['action'] == 'playlist' and
|
2017-01-03 01:41:38 +11:00
|
|
|
data.get('address') == 'node.plexapp.com'):
|
|
|
|
# E.g. watch later initiated by Companion
|
2017-03-14 07:39:07 +11:00
|
|
|
params = {
|
|
|
|
'mode': 'plex_node',
|
|
|
|
'key': '{server}%s' % data.get('key'),
|
|
|
|
'view_offset': data.get('offset'),
|
|
|
|
'play_directly': 'true'
|
|
|
|
}
|
|
|
|
executebuiltin('RunPlugin(plugin://%s?%s)'
|
|
|
|
% (v.ADDON_ID, urlencode(params)))
|
2017-03-06 03:51:58 +11:00
|
|
|
|
2017-01-03 01:41:38 +11:00
|
|
|
elif task['action'] == 'playlist':
|
2016-12-28 03:33:52 +11:00
|
|
|
# Get the playqueue ID
|
2016-07-22 23:04:42 +10:00
|
|
|
try:
|
2017-03-05 03:54:24 +11:00
|
|
|
typus, ID, query = ParseContainerKey(data['containerKey'])
|
2016-07-22 23:04:42 +10:00
|
|
|
except Exception as e:
|
2016-09-03 01:20:19 +10:00
|
|
|
log.error('Exception while processing: %s' % e)
|
2016-07-22 23:04:42 +10:00
|
|
|
import traceback
|
2016-09-03 01:20:19 +10:00
|
|
|
log.error("Traceback:\n%s" % traceback.format_exc())
|
2016-07-22 23:04:42 +10:00
|
|
|
return
|
2017-02-19 03:15:37 +11:00
|
|
|
try:
|
|
|
|
playqueue = self.mgr.playqueue.get_playqueue_from_type(
|
2017-03-06 02:51:13 +11:00
|
|
|
v.KODI_PLAYLIST_TYPE_FROM_PLEX_TYPE[data['type']])
|
2017-02-19 03:15:37 +11:00
|
|
|
except KeyError:
|
|
|
|
# E.g. Plex web does not supply the media type
|
|
|
|
# Still need to figure out the type (video vs. music vs. pix)
|
|
|
|
xml = GetPlexMetadata(data['key'])
|
2017-03-06 02:51:13 +11:00
|
|
|
try:
|
|
|
|
xml[0].attrib
|
|
|
|
except (AttributeError, IndexError, TypeError):
|
|
|
|
log.error('Could not download Plex metadata')
|
|
|
|
return
|
2017-02-19 03:15:37 +11:00
|
|
|
api = API(xml[0])
|
|
|
|
playqueue = self.mgr.playqueue.get_playqueue_from_type(
|
2017-03-06 02:51:13 +11:00
|
|
|
v.KODI_PLAYLIST_TYPE_FROM_PLEX_TYPE[api.getType()])
|
2017-01-03 00:07:24 +11:00
|
|
|
self.mgr.playqueue.update_playqueue_from_PMS(
|
|
|
|
playqueue,
|
|
|
|
ID,
|
|
|
|
repeat=query.get('repeat'),
|
|
|
|
offset=data.get('offset'))
|
2016-07-22 23:04:42 +10:00
|
|
|
|
2016-01-23 01:37:20 +11:00
|
|
|
def run(self):
|
2017-05-12 16:22:36 +10:00
|
|
|
# Ensure that sockets will be closed no matter what
|
|
|
|
try:
|
|
|
|
self.__run()
|
|
|
|
finally:
|
|
|
|
try:
|
|
|
|
self.httpd.socket.shutdown(SHUT_RDWR)
|
|
|
|
except AttributeError:
|
|
|
|
pass
|
|
|
|
finally:
|
|
|
|
try:
|
|
|
|
self.httpd.socket.close()
|
|
|
|
except AttributeError:
|
|
|
|
pass
|
|
|
|
log.info("----===## Plex Companion stopped ##===----")
|
|
|
|
|
|
|
|
def __run(self):
|
|
|
|
self.httpd = False
|
|
|
|
httpd = self.httpd
|
2016-04-03 01:46:23 +11:00
|
|
|
# Cache for quicker while loops
|
|
|
|
client = self.client
|
2017-05-17 18:09:50 +10:00
|
|
|
thread_stopped = self.thread_stopped
|
|
|
|
thread_suspended = self.thread_suspended
|
2016-04-03 01:46:23 +11:00
|
|
|
|
|
|
|
# Start up instances
|
|
|
|
requestMgr = httppersist.RequestMgr()
|
2016-04-05 18:57:30 +10:00
|
|
|
jsonClass = functions.jsonClass(requestMgr, self.settings)
|
2016-04-03 01:46:23 +11:00
|
|
|
subscriptionManager = subscribers.SubscriptionManager(
|
2016-12-28 23:14:21 +11:00
|
|
|
jsonClass, requestMgr, self.player, self.mgr)
|
2016-04-03 01:46:23 +11:00
|
|
|
|
2016-07-22 23:04:42 +10:00
|
|
|
queue = Queue.Queue(maxsize=100)
|
2017-03-05 03:54:24 +11:00
|
|
|
self.queue = queue
|
2016-07-22 23:04:42 +10:00
|
|
|
|
2016-09-03 01:20:19 +10:00
|
|
|
if settings('plexCompanion') == 'true':
|
2016-04-27 01:15:05 +10:00
|
|
|
# Start up httpd
|
|
|
|
start_count = 0
|
|
|
|
while True:
|
|
|
|
try:
|
|
|
|
httpd = listener.ThreadedHTTPServer(
|
|
|
|
client,
|
|
|
|
subscriptionManager,
|
|
|
|
jsonClass,
|
|
|
|
self.settings,
|
2016-07-22 23:04:42 +10:00
|
|
|
queue,
|
2016-04-27 01:15:05 +10:00
|
|
|
('', self.settings['myport']),
|
|
|
|
listener.MyHandler)
|
|
|
|
httpd.timeout = 0.95
|
|
|
|
break
|
|
|
|
except:
|
2016-09-03 01:20:19 +10:00
|
|
|
log.error("Unable to start PlexCompanion. Traceback:")
|
2016-12-21 02:38:04 +11:00
|
|
|
import traceback
|
2016-09-03 01:20:19 +10:00
|
|
|
log.error(traceback.print_exc())
|
2016-01-23 01:37:20 +11:00
|
|
|
|
2016-12-21 02:38:04 +11:00
|
|
|
sleep(3000)
|
2016-04-27 01:10:11 +10:00
|
|
|
|
2016-04-27 01:15:05 +10:00
|
|
|
if start_count == 3:
|
2016-09-03 01:20:19 +10:00
|
|
|
log.error("Error: Unable to start web helper.")
|
2016-04-27 01:15:05 +10:00
|
|
|
httpd = False
|
|
|
|
break
|
2016-01-23 01:37:20 +11:00
|
|
|
|
2016-04-27 01:15:05 +10:00
|
|
|
start_count += 1
|
|
|
|
else:
|
2016-09-03 01:20:19 +10:00
|
|
|
log.info('User deactivated Plex Companion')
|
2016-01-23 01:37:20 +11:00
|
|
|
|
2016-04-03 01:46:23 +11:00
|
|
|
client.start_all()
|
|
|
|
|
2016-01-23 01:37:20 +11:00
|
|
|
message_count = 0
|
2016-08-08 04:52:49 +10:00
|
|
|
if httpd:
|
2016-12-21 02:38:04 +11:00
|
|
|
t = Thread(target=httpd.handle_request)
|
2016-08-08 04:52:49 +10:00
|
|
|
|
2017-05-17 18:09:50 +10:00
|
|
|
while not thread_stopped():
|
2016-03-11 02:02:46 +11:00
|
|
|
# If we are not authorized, sleep
|
|
|
|
# Otherwise, we trigger a download which leads to a
|
|
|
|
# re-authorizations
|
2017-05-17 18:09:50 +10:00
|
|
|
while thread_suspended():
|
|
|
|
if thread_stopped():
|
2016-03-24 02:07:09 +11:00
|
|
|
break
|
2016-12-21 02:38:04 +11:00
|
|
|
sleep(1000)
|
2016-01-23 01:37:20 +11:00
|
|
|
try:
|
2016-08-08 04:52:49 +10:00
|
|
|
message_count += 1
|
2016-04-27 01:15:05 +10:00
|
|
|
if httpd:
|
2016-08-08 04:52:49 +10:00
|
|
|
if not t.isAlive():
|
2016-08-11 03:03:37 +10:00
|
|
|
# Use threads cause the method will stall
|
2016-12-21 02:38:04 +11:00
|
|
|
t = Thread(target=httpd.handle_request)
|
2016-08-08 04:52:49 +10:00
|
|
|
t.start()
|
2016-04-27 01:15:05 +10:00
|
|
|
|
2016-08-08 04:52:49 +10:00
|
|
|
if message_count == 3000:
|
|
|
|
message_count = 0
|
2016-04-27 01:15:05 +10:00
|
|
|
if client.check_client_registration():
|
2016-09-03 01:20:19 +10:00
|
|
|
log.debug("Client is still registered")
|
2016-04-27 01:15:05 +10:00
|
|
|
else:
|
2017-02-03 22:27:59 +11:00
|
|
|
log.debug("Client is no longer registered. "
|
|
|
|
"Plex Companion still running on port %s"
|
|
|
|
% self.settings['myport'])
|
2017-02-20 03:07:42 +11:00
|
|
|
client.register_as_client()
|
2016-04-03 01:46:23 +11:00
|
|
|
# Get and set servers
|
2016-08-08 04:52:49 +10:00
|
|
|
if message_count % 30 == 0:
|
|
|
|
subscriptionManager.serverlist = client.getServerList()
|
|
|
|
subscriptionManager.notify()
|
|
|
|
if not httpd:
|
|
|
|
message_count = 0
|
2016-01-23 01:37:20 +11:00
|
|
|
except:
|
2016-09-03 01:20:19 +10:00
|
|
|
log.warn("Error in loop, continuing anyway. Traceback:")
|
2016-12-21 02:38:04 +11:00
|
|
|
import traceback
|
2016-09-03 01:20:19 +10:00
|
|
|
log.warn(traceback.format_exc())
|
2016-07-22 23:04:42 +10:00
|
|
|
# See if there's anything we need to process
|
|
|
|
try:
|
|
|
|
task = queue.get(block=False)
|
|
|
|
except Queue.Empty:
|
|
|
|
pass
|
|
|
|
else:
|
|
|
|
# Got instructions, process them
|
|
|
|
self.processTasks(task)
|
|
|
|
queue.task_done()
|
2016-08-08 04:52:49 +10:00
|
|
|
# Don't sleep
|
|
|
|
continue
|
2017-03-06 02:43:06 +11:00
|
|
|
sleep(50)
|
2016-01-23 01:37:20 +11:00
|
|
|
|
2016-04-03 01:46:23 +11:00
|
|
|
client.stop_all()
|