Cleanup Plex Companion

This commit is contained in:
tomkat83 2016-04-11 12:34:38 +02:00
parent 18ff3715ac
commit 8be55d898c

View file

@ -27,118 +27,120 @@ class MyHandler(BaseHTTPRequestHandler):
return server return server
return {} return {}
def do_HEAD(s): def do_HEAD(self):
s.logMsg("Serving HEAD request...", 2) self.logMsg("Serving HEAD request...", 2)
s.answer_request(0) self.answer_request(0)
def do_GET(s): def do_GET(self):
s.logMsg("Serving GET request...", 2) self.logMsg("Serving GET request...", 2)
s.answer_request(1) self.answer_request(1)
def do_OPTIONS(s): def do_OPTIONS(self):
s.send_response(200) self.send_response(200)
s.send_header('Content-Length', '0') self.send_header('Content-Length', '0')
s.send_header('X-Plex-Client-Identifier', s.server.settings['uuid']) self.send_header('X-Plex-Client-Identifier', self.server.settings['uuid'])
s.send_header('Content-Type', 'text/plain') self.send_header('Content-Type', 'text/plain')
s.send_header('Connection', 'close') self.send_header('Connection', 'close')
s.send_header('Access-Control-Max-Age', '1209600') self.send_header('Access-Control-Max-Age', '1209600')
s.send_header('Access-Control-Allow-Origin', '*') self.send_header('Access-Control-Allow-Origin', '*')
s.send_header('Access-Control-Allow-Methods', self.send_header('Access-Control-Allow-Methods',
'POST, GET, OPTIONS, DELETE, PUT, HEAD') 'POST, GET, OPTIONS, DELETE, PUT, HEAD')
s.send_header('Access-Control-Allow-Headers', self.send_header('Access-Control-Allow-Headers',
'x-plex-version, x-plex-platform-version, ' 'x-plex-version, x-plex-platform-version, '
'x-plex-username, x-plex-client-identifier, ' 'x-plex-username, x-plex-client-identifier, '
'x-plex-target-client-identifier, x-plex-device-name, ' 'x-plex-target-client-identifier, x-plex-device-name, '
'x-plex-platform, x-plex-product, accept, x-plex-device') 'x-plex-platform, x-plex-product, accept, x-plex-device')
s.end_headers() self.end_headers()
s.wfile.close() self.wfile.close()
def response(s, body, headers={}, code=200): def sendOK(self):
self.send_response(200)
def response(self, body, headers={}, code=200):
try: try:
s.send_response(code) self.send_response(code)
for key in headers: for key in headers:
s.send_header(key, headers[key]) self.send_header(key, headers[key])
s.send_header('Content-Length', len(body)) self.send_header('Content-Length', len(body))
s.send_header('Connection', "close") self.send_header('Connection', "close")
s.end_headers() self.end_headers()
s.wfile.write(body) self.wfile.write(body)
s.wfile.close() self.wfile.close()
except: except:
pass pass
def answer_request(s, sendData): def answer_request(self, sendData):
s.serverlist = s.server.client.getServerList() self.serverlist = self.server.client.getServerList()
s.subMgr = s.server.subscriptionManager self.subMgr = self.server.subscriptionManager
s.js = s.server.jsonClass self.js = self.server.jsonClass
s.settings = s.server.settings self.settings = self.server.settings
try: try:
request_path = s.path[1:] request_path = self.path[1:]
request_path = re.sub(r"\?.*", "", request_path) request_path = re.sub(r"\?.*", "", request_path)
url = urlparse(s.path) url = urlparse(self.path)
paramarrays = parse_qs(url.query) paramarrays = parse_qs(url.query)
params = {} params = {}
for key in paramarrays: for key in paramarrays:
params[key] = paramarrays[key][0] params[key] = paramarrays[key][0]
s.logMsg("request path is: [%s]" % (request_path,), 2) self.logMsg("params received from remote: %s" % params, 2)
s.logMsg("params are: %s" % params, 2) self.subMgr.updateCommandID(self.headers.get('X-Plex-Client-Identifier', self.client_address[0]), params.get('commandID', False))
s.subMgr.updateCommandID(s.headers.get('X-Plex-Client-Identifier', s.client_address[0]), params.get('commandID', False))
if request_path=="version": if request_path=="version":
s.response("PleXBMC Helper Remote Redirector: Running\r\nVersion: %s" % s.settings['version']) self.response("PleXBMC Helper Remote Redirector: Running\r\nVersion: %s" % self.settings['version'])
elif request_path=="verify": elif request_path=="verify":
result=s.js.jsonrpc("ping") result=self.js.jsonrpc("ping")
s.response("XBMC JSON connection test:\r\n"+result) self.response("XBMC JSON connection test:\r\n"+result)
elif "resources" == request_path: elif "resources" == request_path:
resp = getXMLHeader() resp = getXMLHeader()
resp += "<MediaContainer>" resp += "<MediaContainer>"
resp += "<Player" resp += "<Player"
resp += ' title="%s"' % s.settings['client_name'] resp += ' title="%s"' % self.settings['client_name']
resp += ' protocol="plex"' resp += ' protocol="plex"'
resp += ' protocolVersion="1"' resp += ' protocolVersion="1"'
resp += ' protocolCapabilities="navigation,playback,timeline"' resp += ' protocolCapabilities="navigation,playback,timeline"'
resp += ' machineIdentifier="%s"' % s.settings['uuid'] resp += ' machineIdentifier="%s"' % self.settings['uuid']
resp += ' product="PlexKodiConnect"' resp += ' product="PlexKodiConnect"'
resp += ' platform="%s"' % s.settings['platform'] resp += ' platform="%s"' % self.settings['platform']
resp += ' platformVersion="%s"' % s.settings['plexbmc_version'] resp += ' platformVersion="%s"' % self.settings['plexbmc_version']
resp += ' deviceClass="pc"' resp += ' deviceClass="pc"'
resp += "/>" resp += "/>"
resp += "</MediaContainer>" resp += "</MediaContainer>"
s.logMsg("crafted resources response: %s" % resp, 2) self.logMsg("crafted resources response: %s" % resp, 2)
s.response(resp, s.js.getPlexHeaders()) self.response(resp, self.js.getPlexHeaders())
elif "/subscribe" in request_path: elif "/subscribe" in request_path:
s.response(getOKMsg(), s.js.getPlexHeaders()) self.response(getOKMsg(), self.js.getPlexHeaders())
protocol = params.get('protocol', False) protocol = params.get('protocol', False)
host = s.client_address[0] host = self.client_address[0]
port = params.get('port', False) port = params.get('port', False)
uuid = s.headers.get('X-Plex-Client-Identifier', "") uuid = self.headers.get('X-Plex-Client-Identifier', "")
commandID = params.get('commandID', 0) commandID = params.get('commandID', 0)
s.subMgr.addSubscriber(protocol, host, port, uuid, commandID) self.subMgr.addSubscriber(protocol, host, port, uuid, commandID)
elif "/poll" in request_path: elif "/poll" in request_path:
if params.get('wait', False) == '1': if params.get('wait', False) == '1':
sleep(950) sleep(950)
commandID = params.get('commandID', 0) commandID = params.get('commandID', 0)
s.response(re.sub(r"INSERTCOMMANDID", str(commandID), s.subMgr.msg(s.js.getPlayers())), { self.response(re.sub(r"INSERTCOMMANDID", str(commandID), self.subMgr.msg(self.js.getPlayers())), {
'X-Plex-Client-Identifier': s.settings['uuid'], 'X-Plex-Client-Identifier': self.settings['uuid'],
'Access-Control-Expose-Headers': 'X-Plex-Client-Identifier', 'Access-Control-Expose-Headers': 'X-Plex-Client-Identifier',
'Access-Control-Allow-Origin': '*', 'Access-Control-Allow-Origin': '*',
'Content-Type': 'text/xml' 'Content-Type': 'text/xml'
}) })
elif "/unsubscribe" in request_path: elif "/unsubscribe" in request_path:
s.response(getOKMsg(), s.js.getPlexHeaders()) self.response(getOKMsg(), self.js.getPlexHeaders())
uuid = s.headers.get('X-Plex-Client-Identifier', False) or s.client_address[0] uuid = self.headers.get('X-Plex-Client-Identifier', False) or self.client_address[0]
s.subMgr.removeSubscriber(uuid) self.subMgr.removeSubscriber(uuid)
elif request_path == "player/playback/setParameters": elif request_path == "player/playback/setParameters":
s.response(getOKMsg(), s.js.getPlexHeaders()) self.response(getOKMsg(), self.js.getPlexHeaders())
if 'volume' in params: if 'volume' in params:
volume = int(params['volume']) volume = int(params['volume'])
s.logMsg("adjusting the volume to %s%%" % volume, 2) self.logMsg("adjusting the volume to %s%%" % volume, 2)
s.js.jsonrpc("Application.SetVolume", {"volume": volume}) self.js.jsonrpc("Application.SetVolume", {"volume": volume})
elif "/playMedia" in request_path: elif "/playMedia" in request_path:
s.response(getOKMsg(), s.js.getPlexHeaders()) self.response(getOKMsg(), self.js.getPlexHeaders())
offset = params.get('viewOffset', params.get('offset', "0")) offset = params.get('viewOffset', params.get('offset', "0"))
protocol = params.get('protocol', "http") protocol = params.get('protocol', "http")
address = params.get('address', s.client_address[0]) address = params.get('address', self.client_address[0])
server = s.getServerByHost(address) server = self.getServerByHost(address)
port = params.get('port', server.get('port', '32400')) port = params.get('port', server.get('port', '32400'))
try: try:
containerKey = urlparse(params.get('containerKey')).path containerKey = urlparse(params.get('containerKey')).path
@ -150,76 +152,95 @@ class MyHandler(BaseHTTPRequestHandler):
except IndexError: except IndexError:
playQueueID = '' playQueueID = ''
s.js.jsonrpc("playmedia", params) self.js.jsonrpc("playmedia", params)
s.subMgr.lastkey = params['key'] self.subMgr.lastkey = params['key']
s.subMgr.containerKey = containerKey self.subMgr.containerKey = containerKey
s.subMgr.playQueueID = playQueueID self.subMgr.playQueueID = playQueueID
s.subMgr.server = server.get('server', 'localhost') self.subMgr.server = server.get('server', 'localhost')
s.subMgr.port = port self.subMgr.port = port
s.subMgr.protocol = protocol self.subMgr.protocol = protocol
s.subMgr.notify() self.subMgr.notify()
elif request_path == "player/playback/play": elif request_path == "player/playback/play":
s.response(getOKMsg(), s.js.getPlexHeaders()) self.response(getOKMsg(), self.js.getPlexHeaders())
for playerid in s.js.getPlayerIds(): for playerid in self.js.getPlayerIds():
s.js.jsonrpc("Player.PlayPause", {"playerid" : playerid, "play": True}) self.js.jsonrpc("Player.PlayPause", {"playerid" : playerid, "play": True})
elif request_path == "player/playback/pause": elif request_path == "player/playback/pause":
s.response(getOKMsg(), s.js.getPlexHeaders()) self.response(getOKMsg(), self.js.getPlexHeaders())
for playerid in s.js.getPlayerIds(): for playerid in self.js.getPlayerIds():
s.js.jsonrpc("Player.PlayPause", {"playerid" : playerid, "play": False}) self.js.jsonrpc("Player.PlayPause", {"playerid" : playerid, "play": False})
elif request_path == "player/playback/stop": elif request_path == "player/playback/stop":
s.response(getOKMsg(), s.js.getPlexHeaders()) self.response(getOKMsg(), self.js.getPlexHeaders())
for playerid in s.js.getPlayerIds(): for playerid in self.js.getPlayerIds():
s.js.jsonrpc("Player.Stop", {"playerid" : playerid}) self.js.jsonrpc("Player.Stop", {"playerid" : playerid})
elif request_path == "player/playback/seekTo": elif request_path == "player/playback/seekTo":
s.response(getOKMsg(), s.js.getPlexHeaders()) self.response(getOKMsg(), self.js.getPlexHeaders())
for playerid in s.js.getPlayerIds(): for playerid in self.js.getPlayerIds():
s.js.jsonrpc("Player.Seek", {"playerid":playerid, "value":millisToTime(params.get('offset', 0))}) self.js.jsonrpc("Player.Seek", {"playerid":playerid, "value":millisToTime(params.get('offset', 0))})
s.subMgr.notify() self.subMgr.notify()
elif request_path == "player/playback/stepForward": elif request_path == "player/playback/stepForward":
s.response(getOKMsg(), s.js.getPlexHeaders()) self.response(getOKMsg(), self.js.getPlexHeaders())
for playerid in s.js.getPlayerIds(): for playerid in self.js.getPlayerIds():
s.js.jsonrpc("Player.Seek", {"playerid":playerid, "value":"smallforward"}) self.js.jsonrpc("Player.Seek", {"playerid":playerid, "value":"smallforward"})
s.subMgr.notify() self.subMgr.notify()
elif request_path == "player/playback/stepBack": elif request_path == "player/playback/stepBack":
s.response(getOKMsg(), s.js.getPlexHeaders()) self.response(getOKMsg(), self.js.getPlexHeaders())
for playerid in s.js.getPlayerIds(): for playerid in self.js.getPlayerIds():
s.js.jsonrpc("Player.Seek", {"playerid":playerid, "value":"smallbackward"}) self.js.jsonrpc("Player.Seek", {"playerid":playerid, "value":"smallbackward"})
s.subMgr.notify() self.subMgr.notify()
elif request_path == "player/playback/skipNext": elif request_path == "player/playback/skipNext":
s.response(getOKMsg(), s.js.getPlexHeaders()) self.response(getOKMsg(), self.js.getPlexHeaders())
for playerid in s.js.getPlayerIds(): for playerid in self.js.getPlayerIds():
s.js.jsonrpc("Player.Seek", {"playerid":playerid, "value":"bigforward"}) self.js.jsonrpc("Player.Seek", {"playerid":playerid, "value":"bigforward"})
s.subMgr.notify() self.subMgr.notify()
elif request_path == "player/playback/skipPrevious": elif request_path == "player/playback/skipPrevious":
s.response(getOKMsg(), s.js.getPlexHeaders()) self.response(getOKMsg(), self.js.getPlexHeaders())
for playerid in s.js.getPlayerIds(): for playerid in self.js.getPlayerIds():
s.js.jsonrpc("Player.Seek", {"playerid":playerid, "value":"bigbackward"}) self.js.jsonrpc("Player.Seek", {"playerid":playerid, "value":"bigbackward"})
s.subMgr.notify() self.subMgr.notify()
elif request_path == "player/navigation/moveUp": elif request_path == "player/navigation/moveUp":
s.response(getOKMsg(), s.js.getPlexHeaders()) self.response(getOKMsg(), self.js.getPlexHeaders())
s.js.jsonrpc("Input.Up") self.js.jsonrpc("Input.Up")
elif request_path == "player/navigation/moveDown": elif request_path == "player/navigation/moveDown":
s.response(getOKMsg(), s.js.getPlexHeaders()) self.response(getOKMsg(), self.js.getPlexHeaders())
s.js.jsonrpc("Input.Down") self.js.jsonrpc("Input.Down")
elif request_path == "player/navigation/moveLeft": elif request_path == "player/navigation/moveLeft":
s.response(getOKMsg(), s.js.getPlexHeaders()) self.response(getOKMsg(), self.js.getPlexHeaders())
s.js.jsonrpc("Input.Left") self.js.jsonrpc("Input.Left")
elif request_path == "player/navigation/moveRight": elif request_path == "player/navigation/moveRight":
s.response(getOKMsg(), s.js.getPlexHeaders()) self.response(getOKMsg(), self.js.getPlexHeaders())
s.js.jsonrpc("Input.Right") self.js.jsonrpc("Input.Right")
elif request_path == "player/navigation/select": elif request_path == "player/navigation/select":
s.response(getOKMsg(), s.js.getPlexHeaders()) self.response(getOKMsg(), self.js.getPlexHeaders())
s.js.jsonrpc("Input.Select") self.js.jsonrpc("Input.Select")
elif request_path == "player/navigation/home": elif request_path == "player/navigation/home":
s.response(getOKMsg(), s.js.getPlexHeaders()) self.response(getOKMsg(), self.js.getPlexHeaders())
s.js.jsonrpc("Input.Home") self.js.jsonrpc("Input.Home")
elif request_path == "player/navigation/back": elif request_path == "player/navigation/back":
s.response(getOKMsg(), s.js.getPlexHeaders()) self.response(getOKMsg(), self.js.getPlexHeaders())
s.js.jsonrpc("Input.Back") self.js.jsonrpc("Input.Back")
# elif 'player/mirror/details' in request_path:
# # Detailed e.g. Movie information page was opened
# # CURRENTLY NOT POSSIBLE DUE TO KODI RESTRICTIONS
# plexId = params.get('key', params.get('ratingKey'))
# if plexId is None:
# self.logMsg('Could not get plex id from params: %s'
# % params, -1)
# return
# if 'library/metadata' in plexId:
# plexId = plexId.rsplit('/', 1)[1]
# with embydb.GetEmbyDB() as emby_db:
# emby_dbitem = emby_db.getItem_byId(plexId)
# try:
# kodiid = emby_dbitem[0]
# mediatype = emby_dbitem[4]
# except TypeError:
# self.log("No Plex id returned for plexId %s" % plexId, 0)
# return
# getDBfromPlexType(mediatype)
except: except:
s.logMsg('Error encountered. Traceback:', -1) self.logMsg('Error encountered. Traceback:', -1)
s.logMsg(traceback.print_exc(), -1) self.logMsg(traceback.print_exc(), -1)
class ThreadedHTTPServer(ThreadingMixIn, HTTPServer): class ThreadedHTTPServer(ThreadingMixIn, HTTPServer):