PlexKodiConnect/resources/lib/PlexCompanion.py

228 lines
8.1 KiB
Python
Raw Normal View History

# -*- coding: utf-8 -*-
2016-09-03 01:20:19 +10:00
import logging
import threading
import traceback
import socket
import Queue
import xbmc
2016-09-03 01:20:19 +10:00
from utils import settings, ThreadMethodsAdditionalSuspend, ThreadMethods
from plexbmchelper import listener, plexgdm, subscribers, functions, \
2016-09-03 01:20:19 +10:00
httppersist, plexsettings
from PlexFunctions import ParseContainerKey, GetPlayQueue, \
ConvertPlexToKodiTime
import playlist
2016-08-07 23:33:36 +10:00
import player
2016-09-03 01:20:19 +10:00
###############################################################################
2016-09-03 01:20:19 +10:00
log = logging.getLogger("PLEX."+__name__)
###############################################################################
@ThreadMethodsAdditionalSuspend('plex_serverStatus')
@ThreadMethods
class PlexCompanion(threading.Thread):
2016-07-21 02:36:31 +10:00
"""
Initialize with a Queue for callbacks
"""
2016-08-07 23:33:36 +10:00
def __init__(self):
2016-09-03 01:20:19 +10:00
log.info("----===## Starting PlexCompanion ##===----")
self.settings = plexsettings.getSettings()
# Start GDM for server/client discovery
self.client = plexgdm.plexgdm()
self.client.clientDetails(self.settings)
2016-09-03 01:20:19 +10:00
log.debug("Registration string is: %s "
% self.client.getClientDetails())
# Initialize playlist/queue stuff
2016-08-12 06:11:00 +10:00
self.playlist = playlist.Playlist('video')
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
threading.Thread.__init__(self)
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)
return typus, string
def processTasks(self, task):
"""
Processes tasks picked up e.g. by Companion listener
task = {
'action': 'playlist'
'data': as received from Plex companion
}
"""
2016-09-03 01:20:19 +10:00
log.debug('Processing: %s' % task)
data = task['data']
if task['action'] == 'playlist':
try:
_, queueId, query = ParseContainerKey(data['containerKey'])
except Exception as e:
2016-09-03 01:20:19 +10:00
log.error('Exception while processing: %s' % e)
import traceback
2016-09-03 01:20:19 +10:00
log.error("Traceback:\n%s" % traceback.format_exc())
return
if self.playlist is not None:
2016-08-12 06:11:00 +10:00
if self.playlist.Typus() != data.get('type'):
2016-09-03 01:20:19 +10:00
log.debug('Switching to Kodi playlist of type %s'
% data.get('type'))
self.playlist = None
if self.playlist is None:
if data.get('type') == 'music':
2016-08-08 00:31:07 +10:00
self.playlist = playlist.Playlist('music')
else:
2016-09-03 01:20:19 +10:00
self.playlist = playlist.Playlist('video')
2016-08-12 06:11:00 +10:00
if queueId != self.playlist.QueueId():
2016-09-03 01:20:19 +10:00
log.info('New playlist received, updating!')
xml = GetPlayQueue(queueId)
if xml in (None, 401):
2016-09-03 01:20:19 +10:00
log.error('Could not download Plex playlist.')
return
# Clear existing playlist on the Kodi side
self.playlist.clear()
2016-08-12 06:11:00 +10:00
# Set new values
self.playlist.QueueId(queueId)
self.playlist.PlayQueueVersion(int(
xml.attrib.get('playQueueVersion')))
self.playlist.Guid(xml.attrib.get('guid'))
items = []
for item in xml:
items.append({
2016-08-12 06:11:00 +10:00
'playQueueItemID': item.get('playQueueItemID'),
'plexId': item.get('ratingKey'),
2016-08-12 06:11:00 +10:00
'kodiId': None})
self.playlist.playAll(
items,
startitem=self._getStartItem(data.get('key', '')),
offset=ConvertPlexToKodiTime(data.get('offset', 0)))
2016-09-03 01:20:19 +10:00
log.info('Initiated playlist no %s with version %s'
% (self.playlist.QueueId(),
self.playlist.PlayQueueVersion()))
else:
2016-09-03 01:20:19 +10:00
log.error('This has never happened before!')
def run(self):
httpd = False
# Cache for quicker while loops
client = self.client
threadStopped = self.threadStopped
threadSuspended = self.threadSuspended
# Start up instances
requestMgr = httppersist.RequestMgr()
jsonClass = functions.jsonClass(requestMgr, self.settings)
subscriptionManager = subscribers.SubscriptionManager(
2016-08-12 06:11:00 +10:00
jsonClass, requestMgr, self.player, self.playlist)
queue = Queue.Queue(maxsize=100)
2016-09-03 01:20:19 +10:00
if settings('plexCompanion') == 'true':
# Start up httpd
start_count = 0
while True:
try:
httpd = listener.ThreadedHTTPServer(
client,
subscriptionManager,
jsonClass,
self.settings,
queue,
('', 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:")
log.error(traceback.print_exc())
xbmc.sleep(3000)
if start_count == 3:
2016-09-03 01:20:19 +10:00
log.error("Error: Unable to start web helper.")
httpd = False
break
start_count += 1
else:
2016-09-03 01:20:19 +10:00
log.info('User deactivated Plex Companion')
client.start_all()
message_count = 0
if httpd:
t = threading.Thread(target=httpd.handle_request)
while not threadStopped():
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
while threadSuspended():
if threadStopped():
break
xbmc.sleep(1000)
try:
message_count += 1
if httpd:
if not t.isAlive():
2016-08-11 03:03:37 +10:00
# Use threads cause the method will stall
t = threading.Thread(target=httpd.handle_request)
t.start()
if message_count == 3000:
message_count = 0
if client.check_client_registration():
2016-09-03 01:20:19 +10:00
log.debug("Client is still registered")
else:
2016-09-03 01:20:19 +10:00
log.info("Client is no longer registered"
"Plex Companion still running on port %s"
% self.settings['myport'])
# Get and set servers
if message_count % 30 == 0:
subscriptionManager.serverlist = client.getServerList()
subscriptionManager.notify()
if not httpd:
message_count = 0
except:
2016-09-03 01:20:19 +10:00
log.warn("Error in loop, continuing anyway. Traceback:")
log.warn(traceback.format_exc())
# 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()
# Don't sleep
continue
xbmc.sleep(20)
client.stop_all()
if httpd:
try:
httpd.socket.shutdown(socket.SHUT_RDWR)
except:
pass
finally:
httpd.socket.close()
2016-09-03 01:20:19 +10:00
log.info("----===## Plex Companion stopped ##===----")