2015-03-14 08:24:59 +11:00
|
|
|
import xbmc
|
|
|
|
import xbmcgui
|
|
|
|
import xbmcaddon
|
|
|
|
import urllib
|
|
|
|
import urllib2
|
|
|
|
import httplib
|
|
|
|
import hashlib
|
|
|
|
import StringIO
|
|
|
|
import gzip
|
|
|
|
import sys
|
|
|
|
import inspect
|
|
|
|
import json as json
|
|
|
|
from random import randrange
|
|
|
|
from uuid import uuid4 as uuid4
|
|
|
|
from ClientInformation import ClientInformation
|
|
|
|
import encodings
|
|
|
|
import time
|
|
|
|
import traceback
|
|
|
|
|
|
|
|
class DownloadUtils():
|
|
|
|
|
2015-04-03 21:13:01 +11:00
|
|
|
WINDOW = xbmcgui.Window(10000)
|
2015-03-14 08:24:59 +11:00
|
|
|
logLevel = 0
|
2015-03-14 13:37:03 +11:00
|
|
|
addonSettings = None
|
2015-03-14 08:24:59 +11:00
|
|
|
getString = None
|
|
|
|
LogCalls = False
|
|
|
|
TrackLog = ""
|
|
|
|
TotalUrlCalls = 0
|
2015-03-14 13:37:03 +11:00
|
|
|
|
2015-03-14 08:24:59 +11:00
|
|
|
def __init__(self, *args):
|
2015-03-22 21:58:02 +11:00
|
|
|
addonId = ClientInformation().getAddonId()
|
|
|
|
self.addonSettings = xbmcaddon.Addon(id=addonId)
|
|
|
|
self.addon = xbmcaddon.Addon(id=addonId)
|
2015-03-14 13:37:03 +11:00
|
|
|
self.getString = self.addonSettings.getLocalizedString
|
|
|
|
level = self.addonSettings.getSetting('logLevel')
|
|
|
|
self.logLevel = 0
|
|
|
|
if(level != None and level != ""):
|
|
|
|
self.logLevel = int(level)
|
|
|
|
if(self.logLevel == 2):
|
|
|
|
self.LogCalls = True
|
|
|
|
|
|
|
|
def logMsg(self, msg, level = 1):
|
|
|
|
if(self.logLevel >= level):
|
|
|
|
try:
|
2015-03-26 04:37:21 +11:00
|
|
|
xbmc.log("emby DownloadUtils -> " + str(msg))
|
2015-03-14 13:37:03 +11:00
|
|
|
except UnicodeEncodeError:
|
|
|
|
try:
|
2015-03-26 04:37:21 +11:00
|
|
|
xbmc.log("emby DownloadUtils -> " + str(msg.encode('utf-8')))
|
2015-03-14 13:37:03 +11:00
|
|
|
except: pass
|
2015-03-14 08:24:59 +11:00
|
|
|
|
2015-03-22 21:58:02 +11:00
|
|
|
def getServer(self, prefix=True):
|
|
|
|
|
2015-04-03 21:13:01 +11:00
|
|
|
WINDOW = self.WINDOW
|
|
|
|
username = WINDOW.getProperty("currUser")
|
|
|
|
|
|
|
|
if prefix:
|
|
|
|
server = WINDOW.getProperty("server%s" % username)
|
|
|
|
else:
|
|
|
|
server = WINDOW.getProperty("server_%s" % username)
|
|
|
|
|
2015-03-23 15:54:16 +11:00
|
|
|
return server
|
2015-03-22 21:58:02 +11:00
|
|
|
|
2015-03-14 08:24:59 +11:00
|
|
|
def getUserId(self, suppress=True):
|
|
|
|
|
|
|
|
WINDOW = xbmcgui.Window( 10000 )
|
2015-03-26 04:37:21 +11:00
|
|
|
self.addonSettings = xbmcaddon.Addon(id='plugin.video.emby')
|
2015-03-14 13:37:03 +11:00
|
|
|
port = self.addonSettings.getSetting('port')
|
|
|
|
host = self.addonSettings.getSetting('ipaddress')
|
|
|
|
userName = self.addonSettings.getSetting('username')
|
2015-03-14 08:24:59 +11:00
|
|
|
|
|
|
|
userid = WINDOW.getProperty("userid" + userName)
|
|
|
|
|
|
|
|
if(userid != None and userid != ""):
|
2015-03-20 08:50:33 +11:00
|
|
|
self.logMsg("DownloadUtils -> Returning saved (WINDOW) UserID : " + userid + "UserName: " + userName,2)
|
2015-03-14 13:37:03 +11:00
|
|
|
return userid
|
|
|
|
|
|
|
|
userid = self.addonSettings.getSetting("userid" + userName)
|
|
|
|
if(userid != None and userid != ""):
|
|
|
|
WINDOW.setProperty("userid" + userName, userid)
|
2015-03-20 08:50:33 +11:00
|
|
|
self.logMsg("DownloadUtils -> Returning saved (SETTING) UserID : " + userid + "UserName: " + userName,2)
|
2015-03-14 08:24:59 +11:00
|
|
|
return userid
|
|
|
|
|
2015-03-14 13:37:03 +11:00
|
|
|
self.logMsg("Looking for user name: " + userName)
|
2015-03-14 08:24:59 +11:00
|
|
|
|
|
|
|
authOk = self.authenticate()
|
|
|
|
if(authOk == ""):
|
|
|
|
if(suppress == False):
|
2015-03-14 13:37:03 +11:00
|
|
|
xbmcgui.Dialog().ok(self.getString(30044), self.getString(30044))
|
2015-03-14 08:24:59 +11:00
|
|
|
return ""
|
|
|
|
|
2015-03-14 13:37:03 +11:00
|
|
|
userid = WINDOW.getProperty("userid" + userName)
|
2015-03-14 08:24:59 +11:00
|
|
|
if(userid == "" and suppress == False):
|
2015-03-14 13:37:03 +11:00
|
|
|
xbmcgui.Dialog().ok(self.getString(30045),self.getString(30045))
|
2015-03-14 08:24:59 +11:00
|
|
|
|
2015-03-14 13:37:03 +11:00
|
|
|
self.logMsg("userid : " + userid)
|
2015-03-14 08:24:59 +11:00
|
|
|
self.postcapabilities()
|
|
|
|
|
|
|
|
return userid
|
|
|
|
|
|
|
|
def postcapabilities(self):
|
2015-03-14 13:37:03 +11:00
|
|
|
self.logMsg("postcapabilities called")
|
2015-03-14 08:24:59 +11:00
|
|
|
|
|
|
|
# Set Capabilities
|
2015-04-14 04:56:36 +10:00
|
|
|
server = self.getServer()
|
2015-03-14 08:24:59 +11:00
|
|
|
clientInfo = ClientInformation()
|
|
|
|
machineId = clientInfo.getMachineId()
|
|
|
|
|
|
|
|
# get session id
|
2015-04-14 04:56:36 +10:00
|
|
|
url = "%s/mediabrowser/Sessions?DeviceId=%s&format=json" % (server, machineId)
|
2015-03-14 13:37:03 +11:00
|
|
|
self.logMsg("Session URL : " + url);
|
2015-03-14 08:24:59 +11:00
|
|
|
jsonData = self.downloadUrl(url)
|
2015-03-14 13:37:03 +11:00
|
|
|
self.logMsg("Session JsonData : " + jsonData)
|
2015-03-14 08:24:59 +11:00
|
|
|
result = json.loads(jsonData)
|
2015-03-14 13:37:03 +11:00
|
|
|
self.logMsg("Session JsonData : " + str(result))
|
2015-03-14 08:24:59 +11:00
|
|
|
sessionId = result[0].get("Id")
|
2015-03-14 13:37:03 +11:00
|
|
|
self.logMsg("Session Id : " + str(sessionId))
|
2015-03-14 08:24:59 +11:00
|
|
|
|
|
|
|
# post capability data
|
2015-03-23 19:44:16 +11:00
|
|
|
#playableMediaTypes = "Audio,Video,Photo"
|
|
|
|
playableMediaTypes = "Audio,Video"
|
|
|
|
#supportedCommands = "Play,Playstate,DisplayContent,GoHome,SendString,GoToSettings,DisplayMessage,PlayNext"
|
|
|
|
supportedCommands = "Play,Playstate,SendString,DisplayMessage,PlayNext"
|
2015-03-14 08:24:59 +11:00
|
|
|
|
2015-04-14 04:56:36 +10:00
|
|
|
url = "%s/mediabrowser/Sessions/Capabilities?Id=%s&PlayableMediaTypes=%s&SupportedCommands=%s&SupportsMediaControl=True" % (server, sessionId, playableMediaTypes, supportedCommands)
|
2015-03-14 08:24:59 +11:00
|
|
|
postData = {}
|
|
|
|
#postData["Id"] = sessionId;
|
|
|
|
#postData["PlayableMediaTypes"] = "Video";
|
|
|
|
#postData["SupportedCommands"] = "MoveUp";
|
|
|
|
stringdata = json.dumps(postData)
|
2015-03-14 13:37:03 +11:00
|
|
|
self.logMsg("Capabilities URL : " + url);
|
|
|
|
self.logMsg("Capabilities Data : " + stringdata)
|
2015-03-14 08:24:59 +11:00
|
|
|
|
|
|
|
self.downloadUrl(url, postBody=stringdata, type="POST")
|
|
|
|
|
|
|
|
def imageUrl(self, id, type, index, width, height):
|
|
|
|
|
2015-04-03 21:13:01 +11:00
|
|
|
server = self.getServer()
|
2015-03-14 08:24:59 +11:00
|
|
|
|
2015-04-03 21:13:01 +11:00
|
|
|
return "%s/mediabrowser/Items/%s/Images/%s/%s//e3ab56fe27d389446754d0fb04910a34/original/%s/%s/0" % (server, id, type, index, width, height)
|
2015-03-14 08:24:59 +11:00
|
|
|
|
|
|
|
def getAuthHeader(self, authenticate=True):
|
|
|
|
clientInfo = ClientInformation()
|
|
|
|
txt_mac = clientInfo.getMachineId()
|
|
|
|
version = clientInfo.getVersion()
|
|
|
|
|
2015-03-14 13:37:03 +11:00
|
|
|
deviceName = self.addonSettings.getSetting('deviceName')
|
2015-03-14 08:24:59 +11:00
|
|
|
deviceName = deviceName.replace("\"", "_")
|
2015-04-03 21:13:01 +11:00
|
|
|
username = self.WINDOW.getProperty("currUser")
|
2015-03-14 08:24:59 +11:00
|
|
|
|
|
|
|
if(authenticate == False):
|
|
|
|
authString = "MediaBrowser Client=\"Kodi\",Device=\"" + deviceName + "\",DeviceId=\"" + txt_mac + "\",Version=\"" + version + "\""
|
|
|
|
headers = {"Accept-encoding": "gzip", "Accept-Charset" : "UTF-8,*", "Authorization" : authString}
|
|
|
|
return headers
|
|
|
|
else:
|
|
|
|
userid = self.getUserId()
|
|
|
|
authString = "MediaBrowser UserId=\"" + userid + "\",Client=\"Kodi\",Device=\"" + deviceName + "\",DeviceId=\"" + txt_mac + "\",Version=\"" + version + "\""
|
|
|
|
headers = {"Accept-encoding": "gzip", "Accept-Charset" : "UTF-8,*", "Authorization" : authString}
|
|
|
|
|
2015-04-03 21:13:01 +11:00
|
|
|
authToken = self.WINDOW.getProperty("accessToken%s" % username)
|
2015-03-14 08:24:59 +11:00
|
|
|
if(authToken != ""):
|
|
|
|
headers["X-MediaBrowser-Token"] = authToken
|
|
|
|
|
2015-03-20 08:50:33 +11:00
|
|
|
self.logMsg("Authentication Header : " + str(headers),2)
|
2015-03-14 08:24:59 +11:00
|
|
|
return headers
|
|
|
|
|
|
|
|
def downloadUrl(self, url, suppress=False, postBody=None, type="GET", popup=0, authenticate=True ):
|
2015-03-20 08:50:33 +11:00
|
|
|
self.logMsg("== ENTER: getURL ==",2)
|
2015-03-14 13:37:03 +11:00
|
|
|
|
|
|
|
if(authenticate == True and suppress == True):
|
|
|
|
token = self.authenticate(retreive=False)
|
|
|
|
if(token == ""):
|
|
|
|
self.logMsg("No auth info set and suppress is true so returning no data!")
|
|
|
|
return ""
|
|
|
|
|
2015-03-14 08:24:59 +11:00
|
|
|
self.TotalUrlCalls = self.TotalUrlCalls + 1
|
|
|
|
if(self.LogCalls):
|
|
|
|
stackString = ""
|
|
|
|
for f in inspect.stack():
|
|
|
|
stackString = stackString + "\r - " + str(f)
|
|
|
|
self.TrackLog = self.TrackLog + "HTTP_API_CALL : " + url + stackString + "\r"
|
|
|
|
|
|
|
|
link = ""
|
2015-04-03 21:13:01 +11:00
|
|
|
https = None
|
2015-03-14 08:24:59 +11:00
|
|
|
try:
|
2015-04-03 21:13:01 +11:00
|
|
|
if url[0:5] == "https":
|
|
|
|
serversplit = 2
|
|
|
|
urlsplit = 3
|
|
|
|
elif url[0:4] == "http":
|
2015-03-14 08:24:59 +11:00
|
|
|
serversplit = 2
|
|
|
|
urlsplit = 3
|
|
|
|
else:
|
|
|
|
serversplit = 0
|
|
|
|
urlsplit = 1
|
|
|
|
|
2015-04-03 21:13:01 +11:00
|
|
|
https = self.addonSettings.getSetting('https')
|
|
|
|
|
2015-03-14 08:24:59 +11:00
|
|
|
server = url.split('/')[serversplit]
|
|
|
|
urlPath = "/"+"/".join(url.split('/')[urlsplit:])
|
|
|
|
|
2015-03-20 08:50:33 +11:00
|
|
|
self.logMsg("DOWNLOAD_URL = " + url,2)
|
|
|
|
self.logMsg("server = " + str(server),2)
|
|
|
|
self.logMsg("urlPath = " + str(urlPath),2)
|
2015-03-14 08:24:59 +11:00
|
|
|
|
2015-03-14 13:37:03 +11:00
|
|
|
if(server[0:1] == ":" or server[-1:] == ":"):
|
|
|
|
self.logMsg("No server host or port set in url")
|
|
|
|
return ""
|
2015-03-14 08:24:59 +11:00
|
|
|
|
|
|
|
head = self.getAuthHeader(authenticate)
|
2015-03-20 08:50:33 +11:00
|
|
|
self.logMsg("HEADERS : " + str(head), level=2)
|
2015-03-14 13:37:03 +11:00
|
|
|
|
2015-04-03 21:13:01 +11:00
|
|
|
if (https == 'false'):
|
|
|
|
#xbmc.log("Https disabled.")
|
2015-04-05 18:21:47 +10:00
|
|
|
conn = httplib.HTTPConnection(server, timeout=30)
|
2015-04-03 21:13:01 +11:00
|
|
|
elif (https == 'true'):
|
|
|
|
#xbmc.log("Https enabled.")
|
2015-04-05 18:21:47 +10:00
|
|
|
conn = httplib.HTTPSConnection(server, timeout=30)
|
2015-03-14 08:24:59 +11:00
|
|
|
|
|
|
|
# make the connection and send the request
|
|
|
|
if(postBody != None):
|
|
|
|
head["Content-Type"] = "application/x-www-form-urlencoded"
|
|
|
|
head["Content-Length"] = str(len(postBody))
|
2015-03-20 08:50:33 +11:00
|
|
|
self.logMsg("POST DATA : " + postBody,2)
|
2015-03-14 08:24:59 +11:00
|
|
|
conn.request(method=type, url=urlPath, body=postBody, headers=head)
|
|
|
|
else:
|
|
|
|
conn.request(method=type, url=urlPath, headers=head)
|
|
|
|
|
|
|
|
# get the response
|
|
|
|
tries = 0
|
|
|
|
while tries <= 4:
|
|
|
|
try:
|
|
|
|
data = conn.getresponse()
|
|
|
|
break
|
|
|
|
except:
|
|
|
|
# TODO: we need to work out which errors we can just quit trying immediately
|
|
|
|
if(xbmc.abortRequested == True):
|
|
|
|
return ""
|
|
|
|
xbmc.sleep(100)
|
|
|
|
if(xbmc.abortRequested == True):
|
|
|
|
return ""
|
|
|
|
tries += 1
|
|
|
|
if tries == 5:
|
|
|
|
data = conn.getresponse()
|
|
|
|
|
2015-03-14 13:37:03 +11:00
|
|
|
self.logMsg("GET URL HEADERS : " + str(data.getheaders()), level=2)
|
2015-03-14 08:24:59 +11:00
|
|
|
|
|
|
|
# process the response
|
|
|
|
contentType = "none"
|
|
|
|
if int(data.status) == 200:
|
|
|
|
retData = data.read()
|
|
|
|
contentType = data.getheader('content-encoding')
|
2015-03-14 13:37:03 +11:00
|
|
|
self.logMsg("Data Len Before : " + str(len(retData)), level=2)
|
2015-03-14 08:24:59 +11:00
|
|
|
if(contentType == "gzip"):
|
|
|
|
retData = StringIO.StringIO(retData)
|
|
|
|
gzipper = gzip.GzipFile(fileobj=retData)
|
|
|
|
link = gzipper.read()
|
|
|
|
else:
|
|
|
|
link = retData
|
2015-03-14 13:37:03 +11:00
|
|
|
self.logMsg("Data Len After : " + str(len(link)), level=2)
|
|
|
|
self.logMsg("====== 200 returned =======", level=2)
|
|
|
|
self.logMsg("Content-Type : " + str(contentType), level=2)
|
|
|
|
self.logMsg(link, level=2)
|
|
|
|
self.logMsg("====== 200 finished ======", level=2)
|
2015-03-14 08:24:59 +11:00
|
|
|
|
|
|
|
elif ( int(data.status) == 301 ) or ( int(data.status) == 302 ):
|
|
|
|
try:
|
|
|
|
conn.close()
|
|
|
|
except:
|
|
|
|
pass
|
|
|
|
return data.getheader('Location')
|
|
|
|
|
|
|
|
elif int(data.status) == 401:
|
|
|
|
WINDOW = xbmcgui.Window(10000)
|
2015-04-03 21:13:01 +11:00
|
|
|
status = WINDOW.getProperty("Server_status")
|
|
|
|
# Prevent multiple re-auth
|
|
|
|
if (status == "401") or (status == "Auth"):
|
2015-03-14 08:24:59 +11:00
|
|
|
pass
|
2015-04-03 21:13:01 +11:00
|
|
|
else:
|
|
|
|
# Tell UserClient token has been revoked.
|
|
|
|
WINDOW.setProperty("Server_status", "401")
|
|
|
|
error = "HTTP response error: " + str(data.status) + " " + str(data.reason)
|
|
|
|
xbmc.log(error)
|
|
|
|
#xbmcgui.Dialog().ok(self.getString(30135),"Reason: %s" % data.reason) #self.getString(30044),
|
|
|
|
|
|
|
|
try:
|
|
|
|
conn.close()
|
|
|
|
except:
|
|
|
|
pass
|
|
|
|
return ""
|
2015-03-14 08:24:59 +11:00
|
|
|
|
|
|
|
elif int(data.status) >= 400:
|
|
|
|
error = "HTTP response error: " + str(data.status) + " " + str(data.reason)
|
|
|
|
xbmc.log(error)
|
2015-03-14 13:37:03 +11:00
|
|
|
stack = self.FormatException()
|
|
|
|
self.logMsg(stack)
|
2015-03-14 08:24:59 +11:00
|
|
|
if suppress is False:
|
|
|
|
if popup == 0:
|
|
|
|
xbmc.executebuiltin("XBMC.Notification(URL error: "+ str(data.reason) +",)")
|
|
|
|
else:
|
2015-03-14 13:37:03 +11:00
|
|
|
xbmcgui.Dialog().ok(self.getString(30135),server)
|
2015-03-14 08:24:59 +11:00
|
|
|
try:
|
|
|
|
conn.close()
|
|
|
|
except:
|
|
|
|
pass
|
|
|
|
return ""
|
|
|
|
else:
|
|
|
|
link = ""
|
|
|
|
except Exception, msg:
|
|
|
|
error = "Unable to connect to " + str(server) + " : " + str(msg)
|
|
|
|
xbmc.log(error)
|
|
|
|
stack = self.FormatException()
|
2015-03-14 13:37:03 +11:00
|
|
|
self.logMsg(stack)
|
2015-03-14 08:24:59 +11:00
|
|
|
if suppress is False:
|
|
|
|
if popup == 0:
|
|
|
|
xbmc.executebuiltin("XBMC.Notification(: Connection Error: Error connecting to server,)")
|
|
|
|
else:
|
2015-03-14 13:37:03 +11:00
|
|
|
xbmcgui.Dialog().ok(self.getString(30204), str(msg))
|
2015-03-14 08:24:59 +11:00
|
|
|
pass
|
|
|
|
else:
|
|
|
|
try:
|
|
|
|
conn.close()
|
|
|
|
except:
|
|
|
|
pass
|
|
|
|
|
|
|
|
return link
|
|
|
|
|
|
|
|
def FormatException(self):
|
|
|
|
exception_list = traceback.format_stack()
|
|
|
|
exception_list = exception_list[:-2]
|
|
|
|
exception_list.extend(traceback.format_tb(sys.exc_info()[2]))
|
|
|
|
exception_list.extend(traceback.format_exception_only(sys.exc_info()[0], sys.exc_info()[1]))
|
|
|
|
|
|
|
|
exception_str = "Traceback (most recent call last):\n"
|
|
|
|
exception_str += "".join(exception_list)
|
|
|
|
# Removing the last \n
|
|
|
|
exception_str = exception_str[:-1]
|
|
|
|
|
|
|
|
return exception_str
|
|
|
|
|
|
|
|
def __del__(self):
|
|
|
|
return
|
|
|
|
# xbmc.log("\rURL_REQUEST_REPORT : Total Calls : " + str(self.TotalUrlCalls) + "\r" + self.TrackLog)
|