use the latest source for download utils

This commit is contained in:
faush01 2015-03-14 13:37:03 +11:00
parent 5e580e6e2c
commit 0eacb876c7
2 changed files with 177 additions and 113 deletions

View file

@ -13,78 +13,98 @@ import json as json
from random import randrange from random import randrange
from uuid import uuid4 as uuid4 from uuid import uuid4 as uuid4
from ClientInformation import ClientInformation from ClientInformation import ClientInformation
import Utils as utils
import encodings import encodings
import time import time
import traceback import traceback
addonSettings = xbmcaddon.Addon(id='plugin.video.mb3sync')
getString = addonSettings.getLocalizedString
class DownloadUtils(): class DownloadUtils():
logLevel = 0 logLevel = 0
addonSettings = None
getString = None getString = None
LogCalls = False LogCalls = False
TrackLog = "" TrackLog = ""
TotalUrlCalls = 0 TotalUrlCalls = 0
def __init__(self, *args): def __init__(self, *args):
pass self.addonSettings = xbmcaddon.Addon(id='plugin.video.mb3sync')
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:
xbmc.log("mb3sync DownloadUtils -> " + str(msg))
except UnicodeEncodeError:
try:
xbmc.log("mb3sync DownloadUtils -> " + str(msg.encode('utf-8')))
except: pass
def getServer(self): def getServer(self):
port = addonSettings.getSetting('port') port = self.addonSettings.getSetting('port')
host = addonSettings.getSetting('ipaddress') host = self.addonSettings.getSetting('ipaddress')
return host + ":" + port return host + ":" + port
def getUserId(self, suppress=True): def getUserId(self, suppress=True):
WINDOW = xbmcgui.Window( 10000 ) WINDOW = xbmcgui.Window( 10000 )
port = addonSettings.getSetting('port') self.addonSettings = xbmcaddon.Addon(id='plugin.video.mb3sync')
host = addonSettings.getSetting('ipaddress') port = self.addonSettings.getSetting('port')
userName = addonSettings.getSetting('username') host = self.addonSettings.getSetting('ipaddress')
userName = self.addonSettings.getSetting('username')
userid = WINDOW.getProperty("userid" + userName) userid = WINDOW.getProperty("userid" + userName)
if(userid != None and userid != ""): if(userid != None and userid != ""):
utils.logMsg("MB3 Sync","DownloadUtils -> Returning saved UserID : " + userid + "UserName: " + userName) self.logMsg("DownloadUtils -> Returning saved (WINDOW) UserID : " + userid + "UserName: " + userName)
return userid
userid = self.addonSettings.getSetting("userid" + userName)
if(userid != None and userid != ""):
WINDOW.setProperty("userid" + userName, userid)
self.logMsg("DownloadUtils -> Returning saved (SETTING) UserID : " + userid + "UserName: " + userName)
return userid return userid
utils.logMsg("MB3 Sync","Looking for user name: " + userName) self.logMsg("Looking for user name: " + userName)
authOk = self.authenticate() authOk = self.authenticate()
if(authOk == ""): if(authOk == ""):
if(suppress == False): if(suppress == False):
xbmcgui.Dialog().ok(getString(30044), getString(30044)) xbmcgui.Dialog().ok(self.getString(30044), self.getString(30044))
return "" return ""
userid = WINDOW.getProperty("userid"+ userName) userid = WINDOW.getProperty("userid" + userName)
if(userid == "" and suppress == False): if(userid == "" and suppress == False):
xbmcgui.Dialog().ok(getString(30045),getString(30045)) xbmcgui.Dialog().ok(self.getString(30045),self.getString(30045))
utils.logMsg("MB3 Sync","userid : " + userid) self.logMsg("userid : " + userid)
self.postcapabilities() self.postcapabilities()
return userid return userid
def postcapabilities(self): def postcapabilities(self):
utils.logMsg("MB3 Sync","postcapabilities called") self.logMsg("postcapabilities called")
# Set Capabilities # Set Capabilities
mb3Port = addonSettings.getSetting('port') mb3Port = self.addonSettings.getSetting('port')
mb3Host = addonSettings.getSetting('ipaddress') mb3Host = self.addonSettings.getSetting('ipaddress')
clientInfo = ClientInformation() clientInfo = ClientInformation()
machineId = clientInfo.getMachineId() machineId = clientInfo.getMachineId()
# get session id # get session id
url = "http://" + mb3Host + ":" + mb3Port + "/mediabrowser/Sessions?DeviceId=" + machineId + "&format=json" url = "http://" + mb3Host + ":" + mb3Port + "/mediabrowser/Sessions?DeviceId=" + machineId + "&format=json"
utils.logMsg("MB3 Sync","Session URL : " + url); self.logMsg("Session URL : " + url);
jsonData = self.downloadUrl(url) jsonData = self.downloadUrl(url)
utils.logMsg("MB3 Sync","Session JsonData : " + jsonData) self.logMsg("Session JsonData : " + jsonData)
result = json.loads(jsonData) result = json.loads(jsonData)
utils.logMsg("MB3 Sync","Session JsonData : " + str(result)) self.logMsg("Session JsonData : " + str(result))
sessionId = result[0].get("Id") sessionId = result[0].get("Id")
utils.logMsg("MB3 Sync","Session Id : " + str(sessionId)) self.logMsg("Session Id : " + str(sessionId))
# post capability data # post capability data
playableMediaTypes = "Audio,Video,Photo" playableMediaTypes = "Audio,Video,Photo"
@ -97,63 +117,92 @@ class DownloadUtils():
#postData["PlayableMediaTypes"] = "Video"; #postData["PlayableMediaTypes"] = "Video";
#postData["SupportedCommands"] = "MoveUp"; #postData["SupportedCommands"] = "MoveUp";
stringdata = json.dumps(postData) stringdata = json.dumps(postData)
utils.logMsg("MB3 Sync","Capabilities URL : " + url); self.logMsg("Capabilities URL : " + url);
utils.logMsg("MB3 Sync","Capabilities Data : " + stringdata) self.logMsg("Capabilities Data : " + stringdata)
self.downloadUrl(url, postBody=stringdata, type="POST") self.downloadUrl(url, postBody=stringdata, type="POST")
def authenticate(self): def authenticate(self, retreive=True):
WINDOW = xbmcgui.Window( 10000 )
token = WINDOW.getProperty("AccessToken"+addonSettings.getSetting('username')) WINDOW = xbmcgui.Window(10000)
self.addonSettings = xbmcaddon.Addon(id='plugin.video.mb3sync')
username = self.addonSettings.getSetting('username')
token = WINDOW.getProperty("AccessToken" + username)
if(token != None and token != ""): if(token != None and token != ""):
utils.logMsg("MB3 Sync","DownloadUtils -> Returning saved AccessToken for user : " + addonSettings.getSetting('username') + " token: "+ token) self.logMsg("DownloadUtils -> Returning saved (WINDOW) AccessToken for user:" + username + " token:" + token)
return token return token
port = addonSettings.getSetting("port") token = self.addonSettings.getSetting("AccessToken" + username)
host = addonSettings.getSetting("ipaddress") if(token != None and token != ""):
if(host == None or host == "" or port == None or port == ""): WINDOW.setProperty("AccessToken" + username, token)
self.logMsg("DownloadUtils -> Returning saved (SETTINGS) AccessToken for user:" + username + " token:" + token)
return token
port = self.addonSettings.getSetting("port")
host = self.addonSettings.getSetting("ipaddress")
if(host == None or host == "" or host == "<none>" or port == None or port == ""):
return "" return ""
url = "http://" + addonSettings.getSetting("ipaddress") + ":" + addonSettings.getSetting("port") + "/mediabrowser/Users/AuthenticateByName?format=json" if(retreive == False):
return ""
url = "http://" + host + ":" + port + "/mediabrowser/Users/AuthenticateByName?format=json"
clientInfo = ClientInformation() clientInfo = ClientInformation()
txt_mac = clientInfo.getMachineId() txt_mac = clientInfo.getMachineId()
version = clientInfo.getVersion() version = clientInfo.getVersion()
deviceName = addonSettings.getSetting('deviceName')
deviceName = deviceName.replace("\"", "_")
authString = "Mediabrowser Client=\"Kodi\",Device=\"" + deviceName + "\",DeviceId=\"" + txt_mac + "\",Version=\"" + version + "\""
headers = {'Accept-encoding': 'gzip', 'Authorization' : authString}
if addonSettings.getSetting('password') !=None and addonSettings.getSetting('password') !='': # get user info
sha1 = hashlib.sha1(addonSettings.getSetting('password')) jsonData = self.downloadUrl("http://" + host + ":" + port + "/mediabrowser/Users/Public?format=json", authenticate=False)
users = []
if(jsonData != ""):
users = json.loads(jsonData)
userHasPassword = False
for user in users:
name = user.get("Name")
if(username == name):
if(user.get("HasPassword") == True):
userHasPassword = True
break
password = ""
if(userHasPassword):
password = xbmcgui.Dialog().input("Enter Password for user : " + username)
if (password != ""):
sha1 = hashlib.sha1(password)
sha1 = sha1.hexdigest() sha1 = sha1.hexdigest()
else: else:
sha1 = 'da39a3ee5e6b4b0d3255bfef95601890afd80709' sha1 = 'da39a3ee5e6b4b0d3255bfef95601890afd80709'
messageData = "username=" + addonSettings.getSetting('username') + "&password=" + sha1 messageData = "username=" + username + "&password=" + sha1
resp = self.downloadUrl(url, postBody=messageData, type="POST", authenticate=False, suppress=True) resp = self.downloadUrl(url, postBody=messageData, type="POST", authenticate=False)
result = None result = None
accessToken = None accessToken = None
try: try:
xbmc.log("Auth_Reponce: " + str(resp))
result = json.loads(resp) result = json.loads(resp)
accessToken = result.get("AccessToken") accessToken = result.get("AccessToken")
except: except:
pass pass
if(result != None and accessToken != None): if(result != None and accessToken != None):
utils.logMsg("MB3 Sync","User Authenticated : " + accessToken) userID = result.get("User").get("Id")
WINDOW.setProperty("AccessToken"+addonSettings.getSetting('username'), accessToken) self.logMsg("User Authenticated : " + accessToken)
WINDOW.setProperty("userid"+addonSettings.getSetting('username'), result.get("User").get("Id")) WINDOW.setProperty("AccessToken" + username, accessToken)
WINDOW.setProperty("mb3_authenticated", "true") WINDOW.setProperty("userid" + username, userID)
self.addonSettings.setSetting("AccessToken" + username, accessToken)
self.addonSettings.setSetting("userid" + username, userID)
return accessToken return accessToken
else: else:
utils.logMsg("MB3 Sync","User NOT Authenticated") self.logMsg("User NOT Authenticated")
WINDOW.setProperty("AccessToken"+addonSettings.getSetting('username'), "") WINDOW.setProperty("AccessToken" + username, "")
WINDOW.setProperty("mb3_authenticated", "false") WINDOW.setProperty("userid" + username, "")
self.addonSettings.setSetting("AccessToken" + username, "")
self.addonSettings.setSetting("userid" + username, "")
return "" return ""
def getArtwork(self, data, type, index = "0", userParentInfo = False): def getArtwork(self, data, type, index = "0", userParentInfo = False):
@ -166,7 +215,7 @@ class DownloadUtils():
if data.get("Type") == "Season" or data.get("Type")== "Episode": if data.get("Type") == "Season" or data.get("Type")== "Episode":
id = data.get("SeriesId") id = data.get("SeriesId")
getSeriesData = True getSeriesData = True
elif type == "poster" and data.get("Type") == "Episode" and addonSettings.getSetting('useSeasonPoster')=='true': # Change the Id to the Season to get the season poster elif type == "poster" and data.get("Type") == "Episode" and self.addonSettings.getSetting('useSeasonPoster')=='true': # Change the Id to the Season to get the season poster
id = data.get("SeasonId") id = data.get("SeasonId")
if type == "poster" or type == "tvshow.poster": # Now that the Ids are right, change type to MB3 name if type == "poster" or type == "tvshow.poster": # Now that the Ids are right, change type to MB3 name
type="Primary" type="Primary"
@ -213,7 +262,7 @@ class DownloadUtils():
played = "0" played = "0"
totalbackdrops = 0 totalbackdrops = 0
if addonSettings.getSetting('showArtIndicators')=='true': # add watched, unplayedcount and percentage played indicators to posters if self.addonSettings.getSetting('showArtIndicators')=='true': # add watched, unplayedcount and percentage played indicators to posters
if (originalType =="Primary" or originalType =="Backdrop" or originalType =="Banner") and data.get("Type") != "Episode": if (originalType =="Primary" or originalType =="Backdrop" or originalType =="Banner") and data.get("Type") != "Episode":
if originalType =="Backdrop" and index == "0" and data.get("BackdropImageTags") != None: if originalType =="Backdrop" and index == "0" and data.get("BackdropImageTags") != None:
totalbackdrops = len(data.get("BackdropImageTags")) totalbackdrops = len(data.get("BackdropImageTags"))
@ -223,17 +272,17 @@ class DownloadUtils():
UnWatched = 0 if userData.get("UnplayedItemCount")==None else userData.get("UnplayedItemCount") UnWatched = 0 if userData.get("UnplayedItemCount")==None else userData.get("UnplayedItemCount")
if UnWatched <> 0 and addonSettings.getSetting('showUnplayedIndicators')=='true': if UnWatched <> 0 and self.addonSettings.getSetting('showUnplayedIndicators')=='true':
query = query + "&UnplayedCount=" + str(UnWatched) query = query + "&UnplayedCount=" + str(UnWatched)
if(userData != None and userData.get("Played") == True and addonSettings.getSetting('showWatchedIndicators')=='true'): if(userData != None and userData.get("Played") == True and self.addonSettings.getSetting('showWatchedIndicators')=='true'):
query = query + "&AddPlayedIndicator=true" query = query + "&AddPlayedIndicator=true"
PlayedPercentage = 0 if userData.get("PlayedPercentage")==None else userData.get("PlayedPercentage") PlayedPercentage = 0 if userData.get("PlayedPercentage")==None else userData.get("PlayedPercentage")
if PlayedPercentage == 0 and userData!=None and userData.get("PlayedPercentage")!=None : if PlayedPercentage == 0 and userData!=None and userData.get("PlayedPercentage")!=None :
PlayedPercentage = userData.get("PlayedPercentage") PlayedPercentage = userData.get("PlayedPercentage")
if (PlayedPercentage != 100 or PlayedPercentage) != 0 and addonSettings.getSetting('showPlayedPrecentageIndicators')=='true': if (PlayedPercentage != 100 or PlayedPercentage) != 0 and self.addonSettings.getSetting('showPlayedPrecentageIndicators')=='true':
played = str(PlayedPercentage) played = str(PlayedPercentage)
elif originalType =="Primary2": elif originalType =="Primary2":
@ -241,16 +290,16 @@ class DownloadUtils():
UnWatched = 0 if userData.get("UnplayedItemCount")==None else userData.get("UnplayedItemCount") UnWatched = 0 if userData.get("UnplayedItemCount")==None else userData.get("UnplayedItemCount")
if UnWatched <> 0 and addonSettings.getSetting('showUnplayedIndicators')=='true': if UnWatched <> 0 and self.addonSettings.getSetting('showUnplayedIndicators')=='true':
query = query + "&UnplayedCount=" + str(UnWatched) query = query + "&UnplayedCount=" + str(UnWatched)
if(userData != None and userData.get("Played") == True and addonSettings.getSetting('showWatchedIndicators')=='true'): if(userData != None and userData.get("Played") == True and self.addonSettings.getSetting('showWatchedIndicators')=='true'):
query = query + "&AddPlayedIndicator=true" query = query + "&AddPlayedIndicator=true"
PlayedPercentage = 0 if userData.get("PlayedPercentage")==None else userData.get("PlayedPercentage") PlayedPercentage = 0 if userData.get("PlayedPercentage")==None else userData.get("PlayedPercentage")
if PlayedPercentage == 0 and userData!=None and userData.get("PlayedPercentage")!=None : if PlayedPercentage == 0 and userData!=None and userData.get("PlayedPercentage")!=None :
PlayedPercentage = userData.get("PlayedPercentage") PlayedPercentage = userData.get("PlayedPercentage")
if (PlayedPercentage != 100 or PlayedPercentage) != 0 and addonSettings.getSetting('showPlayedPrecentageIndicators')=='true': if (PlayedPercentage != 100 or PlayedPercentage) != 0 and self.addonSettings.getSetting('showPlayedPrecentageIndicators')=='true':
played = str(PlayedPercentage) played = str(PlayedPercentage)
height = "338" height = "338"
@ -261,16 +310,16 @@ class DownloadUtils():
UnWatched = 0 if userData.get("UnplayedItemCount")==None else userData.get("UnplayedItemCount") UnWatched = 0 if userData.get("UnplayedItemCount")==None else userData.get("UnplayedItemCount")
if UnWatched <> 0 and addonSettings.getSetting('showUnplayedIndicators')=='true': if UnWatched <> 0 and self.addonSettings.getSetting('showUnplayedIndicators')=='true':
query = query + "&UnplayedCount=" + str(UnWatched) query = query + "&UnplayedCount=" + str(UnWatched)
if(userData != None and userData.get("Played") == True and addonSettings.getSetting('showWatchedIndicators')=='true'): if(userData != None and userData.get("Played") == True and self.addonSettings.getSetting('showWatchedIndicators')=='true'):
query = query + "&AddPlayedIndicator=true" query = query + "&AddPlayedIndicator=true"
PlayedPercentage = 0 if userData.get("PlayedPercentage")==None else userData.get("PlayedPercentage") PlayedPercentage = 0 if userData.get("PlayedPercentage")==None else userData.get("PlayedPercentage")
if PlayedPercentage == 0 and userData!=None and userData.get("PlayedPercentage")!=None : if PlayedPercentage == 0 and userData!=None and userData.get("PlayedPercentage")!=None :
PlayedPercentage = userData.get("PlayedPercentage") PlayedPercentage = userData.get("PlayedPercentage")
if (PlayedPercentage != 100 or PlayedPercentage) != 0 and addonSettings.getSetting('showPlayedPrecentageIndicators')=='true': if (PlayedPercentage != 100 or PlayedPercentage) != 0 and self.addonSettings.getSetting('showPlayedPrecentageIndicators')=='true':
played = str(PlayedPercentage) played = str(PlayedPercentage)
@ -280,16 +329,16 @@ class DownloadUtils():
UnWatched = 0 if userData.get("UnplayedItemCount")==None else userData.get("UnplayedItemCount") UnWatched = 0 if userData.get("UnplayedItemCount")==None else userData.get("UnplayedItemCount")
if UnWatched <> 0 and addonSettings.getSetting('showUnplayedIndicators')=='true': if UnWatched <> 0 and self.addonSettings.getSetting('showUnplayedIndicators')=='true':
query = query + "&UnplayedCount=" + str(UnWatched) query = query + "&UnplayedCount=" + str(UnWatched)
if(userData != None and userData.get("Played") == True and addonSettings.getSetting('showWatchedIndicators')=='true'): if(userData != None and userData.get("Played") == True and self.addonSettings.getSetting('showWatchedIndicators')=='true'):
query = query + "&AddPlayedIndicator=true" query = query + "&AddPlayedIndicator=true"
PlayedPercentage = 0 if userData.get("PlayedPercentage")==None else userData.get("PlayedPercentage") PlayedPercentage = 0 if userData.get("PlayedPercentage")==None else userData.get("PlayedPercentage")
if PlayedPercentage == 0 and userData!=None and userData.get("PlayedPercentage")!=None : if PlayedPercentage == 0 and userData!=None and userData.get("PlayedPercentage")!=None :
PlayedPercentage = userData.get("PlayedPercentage") PlayedPercentage = userData.get("PlayedPercentage")
if (PlayedPercentage != 100 or PlayedPercentage) != 0 and addonSettings.getSetting('showPlayedPrecentageIndicators')=='true': if (PlayedPercentage != 100 or PlayedPercentage) != 0 and self.addonSettings.getSetting('showPlayedPrecentageIndicators')=='true':
played = str(PlayedPercentage) played = str(PlayedPercentage)
height = "270" height = "270"
@ -300,16 +349,16 @@ class DownloadUtils():
UnWatched = 0 if userData.get("UnplayedItemCount")==None else userData.get("UnplayedItemCount") UnWatched = 0 if userData.get("UnplayedItemCount")==None else userData.get("UnplayedItemCount")
if UnWatched <> 0 and addonSettings.getSetting('showUnplayedIndicators')=='true': if UnWatched <> 0 and self.addonSettings.getSetting('showUnplayedIndicators')=='true':
query = query + "&UnplayedCount=" + str(UnWatched) query = query + "&UnplayedCount=" + str(UnWatched)
if(userData != None and userData.get("Played") == True and addonSettings.getSetting('showWatchedIndicators')=='true'): if(userData != None and userData.get("Played") == True and self.addonSettings.getSetting('showWatchedIndicators')=='true'):
query = query + "&AddPlayedIndicator=true" query = query + "&AddPlayedIndicator=true"
PlayedPercentage = 0 if userData.get("PlayedPercentage")==None else userData.get("PlayedPercentage") PlayedPercentage = 0 if userData.get("PlayedPercentage")==None else userData.get("PlayedPercentage")
if PlayedPercentage == 0 and userData!=None and userData.get("PlayedPercentage")!=None : if PlayedPercentage == 0 and userData!=None and userData.get("PlayedPercentage")!=None :
PlayedPercentage = userData.get("PlayedPercentage") PlayedPercentage = userData.get("PlayedPercentage")
if (PlayedPercentage != 100 or PlayedPercentage) != 0 and addonSettings.getSetting('showPlayedPrecentageIndicators')=='true': if (PlayedPercentage != 100 or PlayedPercentage) != 0 and self.addonSettings.getSetting('showPlayedPrecentageIndicators')=='true':
played = str(PlayedPercentage) played = str(PlayedPercentage)
height = "410" height = "410"
@ -325,16 +374,16 @@ class DownloadUtils():
UnWatched = 0 if userData.get("UnplayedItemCount")==None else userData.get("UnplayedItemCount") UnWatched = 0 if userData.get("UnplayedItemCount")==None else userData.get("UnplayedItemCount")
if UnWatched <> 0 and addonSettings.getSetting('showUnplayedIndicators')=='true': if UnWatched <> 0 and self.addonSettings.getSetting('showUnplayedIndicators')=='true':
query = query + "&UnplayedCount=" + str(UnWatched) query = query + "&UnplayedCount=" + str(UnWatched)
if(userData != None and userData.get("Played") == True and addonSettings.getSetting('showWatchedIndicators')=='true'): if(userData != None and userData.get("Played") == True and self.addonSettings.getSetting('showWatchedIndicators')=='true'):
query = query + "&AddPlayedIndicator=true" query = query + "&AddPlayedIndicator=true"
PlayedPercentage = 0 if userData.get("PlayedPercentage")==None else userData.get("PlayedPercentage") PlayedPercentage = 0 if userData.get("PlayedPercentage")==None else userData.get("PlayedPercentage")
if PlayedPercentage == 0 and userData!=None and userData.get("PlayedPercentage")!=None : if PlayedPercentage == 0 and userData!=None and userData.get("PlayedPercentage")!=None :
PlayedPercentage = userData.get("PlayedPercentage") PlayedPercentage = userData.get("PlayedPercentage")
if (PlayedPercentage != 100 or PlayedPercentage) != 0 and addonSettings.getSetting('showPlayedPrecentageIndicators')=='true': if (PlayedPercentage != 100 or PlayedPercentage) != 0 and self.addonSettings.getSetting('showPlayedPrecentageIndicators')=='true':
played = str(PlayedPercentage) played = str(PlayedPercentage)
height = "370" height = "370"
@ -349,16 +398,16 @@ class DownloadUtils():
UnWatched = 0 if userData.get("UnplayedItemCount")==None else userData.get("UnplayedItemCount") UnWatched = 0 if userData.get("UnplayedItemCount")==None else userData.get("UnplayedItemCount")
if UnWatched <> 0 and addonSettings.getSetting('showUnplayedIndicators')=='true': if UnWatched <> 0 and self.addonSettings.getSetting('showUnplayedIndicators')=='true':
query = query + "&UnplayedCount=" + str(UnWatched) query = query + "&UnplayedCount=" + str(UnWatched)
if(userData != None and userData.get("Played") == True and addonSettings.getSetting('showWatchedIndicators')=='true'): if(userData != None and userData.get("Played") == True and self.addonSettings.getSetting('showWatchedIndicators')=='true'):
query = query + "&AddPlayedIndicator=true" query = query + "&AddPlayedIndicator=true"
PlayedPercentage = 0 if userData.get("PlayedPercentage")==None else userData.get("PlayedPercentage") PlayedPercentage = 0 if userData.get("PlayedPercentage")==None else userData.get("PlayedPercentage")
if PlayedPercentage == 0 and userData!=None and userData.get("PlayedPercentage")!=None : if PlayedPercentage == 0 and userData!=None and userData.get("PlayedPercentage")!=None :
PlayedPercentage = userData.get("PlayedPercentage") PlayedPercentage = userData.get("PlayedPercentage")
if (PlayedPercentage != 100 or PlayedPercentage) != 0 and addonSettings.getSetting('showPlayedPrecentageIndicators')=='true': if (PlayedPercentage != 100 or PlayedPercentage) != 0 and self.addonSettings.getSetting('showPlayedPrecentageIndicators')=='true':
played = str(PlayedPercentage) played = str(PlayedPercentage)
height = "910" height = "910"
@ -370,20 +419,20 @@ class DownloadUtils():
index = str(randrange(0,totalbackdrops)) index = str(randrange(0,totalbackdrops))
# use the local image proxy server that is made available by this addons service # use the local image proxy server that is made available by this addons service
port = addonSettings.getSetting('port') port = self.addonSettings.getSetting('port')
host = addonSettings.getSetting('ipaddress') host = self.addonSettings.getSetting('ipaddress')
server = host + ":" + port server = host + ":" + port
if addonSettings.getSetting('compressArt')=='true': if self.addonSettings.getSetting('compressArt')=='true':
query = query + "&Quality=90" query = query + "&Quality=90"
if imageTag == None: if imageTag == None:
imageTag = "e3ab56fe27d389446754d0fb04910a34" imageTag = "e3ab56fe27d389446754d0fb04910a34"
artwork = "http://" + server + "/mediabrowser/Items/" + str(id) + "/Images/" + type + "/" + index + "/" + imageTag + "/original/" + width + "/" + height + "/" + played + "?" + query artwork = "http://" + server + "/mediabrowser/Items/" + str(id) + "/Images/" + type + "/" + index + "/" + imageTag + "/original/" + width + "/" + height + "/" + played + "?" + query
if addonSettings.getSetting('disableCoverArt')=='true': if self.addonSettings.getSetting('disableCoverArt')=='true':
artwork = artwork + "&EnableImageEnhancers=false" artwork = artwork + "&EnableImageEnhancers=false"
utils.logMsg("MB3 Sync","getArtwork : " + artwork, level=2) self.logMsg("getArtwork : " + artwork, level=2)
# do not return non-existing images # do not return non-existing images
if ( (type!="Backdrop" and imageTag=="e3ab56fe27d389446754d0fb04910a34") | #Remember, this is the placeholder tag, meaning we didn't find a valid tag if ( (type!="Backdrop" and imageTag=="e3ab56fe27d389446754d0fb04910a34") | #Remember, this is the placeholder tag, meaning we didn't find a valid tag
@ -399,8 +448,8 @@ class DownloadUtils():
id = data.get("Id") id = data.get("Id")
port = addonSettings.getSetting('port') port = self.addonSettings.getSetting('port')
host = addonSettings.getSetting('ipaddress') host = self.addonSettings.getSetting('ipaddress')
server = host + ":" + port server = host + ":" + port
artwork = "http://" + server + "/mediabrowser/Users/" + str(id) + "/Images/" + type + "?Format=original" artwork = "http://" + server + "/mediabrowser/Users/" + str(id) + "/Images/" + type + "?Format=original"
@ -409,8 +458,8 @@ class DownloadUtils():
def imageUrl(self, id, type, index, width, height): def imageUrl(self, id, type, index, width, height):
port = addonSettings.getSetting('port') port = self.addonSettings.getSetting('port')
host = addonSettings.getSetting('ipaddress') host = self.addonSettings.getSetting('ipaddress')
server = host + ":" + port server = host + ":" + port
return "http://" + server + "/mediabrowser/Items/" + str(id) + "/Images/" + type + "/" + str(index) + "/e3ab56fe27d389446754d0fb04910a34/original/" + str(width) + "/" + str(height) + "/0" return "http://" + server + "/mediabrowser/Items/" + str(id) + "/Images/" + type + "/" + str(index) + "/e3ab56fe27d389446754d0fb04910a34/original/" + str(width) + "/" + str(height) + "/0"
@ -420,7 +469,7 @@ class DownloadUtils():
txt_mac = clientInfo.getMachineId() txt_mac = clientInfo.getMachineId()
version = clientInfo.getVersion() version = clientInfo.getVersion()
deviceName = addonSettings.getSetting('deviceName') deviceName = self.addonSettings.getSetting('deviceName')
deviceName = deviceName.replace("\"", "_") deviceName = deviceName.replace("\"", "_")
if(authenticate == False): if(authenticate == False):
@ -436,11 +485,19 @@ class DownloadUtils():
if(authToken != ""): if(authToken != ""):
headers["X-MediaBrowser-Token"] = authToken headers["X-MediaBrowser-Token"] = authToken
utils.logMsg("MB3 Sync","Authentication Header : " + str(headers)) self.logMsg("Authentication Header : " + str(headers))
return headers return headers
def downloadUrl(self, url, suppress=False, postBody=None, type="GET", popup=0, authenticate=True ): def downloadUrl(self, url, suppress=False, postBody=None, type="GET", popup=0, authenticate=True ):
utils.logMsg("MB3 Sync","== ENTER: getURL ==") self.logMsg("== ENTER: getURL ==")
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 ""
suppress = False
self.TotalUrlCalls = self.TotalUrlCalls + 1 self.TotalUrlCalls = self.TotalUrlCalls + 1
if(self.LogCalls): if(self.LogCalls):
@ -461,20 +518,24 @@ class DownloadUtils():
server = url.split('/')[serversplit] server = url.split('/')[serversplit]
urlPath = "/"+"/".join(url.split('/')[urlsplit:]) urlPath = "/"+"/".join(url.split('/')[urlsplit:])
utils.logMsg("MB3 Sync","DOWNLOAD_URL = " + url) self.logMsg("DOWNLOAD_URL = " + url)
utils.logMsg("MB3 Sync","server = "+str(server), level=2) self.logMsg("server = " + str(server))
utils.logMsg("MB3 Sync","urlPath = "+str(urlPath), level=2) self.logMsg("urlPath = " + str(urlPath))
conn = httplib.HTTPConnection(server, timeout=5) if(server[0:1] == ":" or server[-1:] == ":"):
self.logMsg("No server host or port set in url")
return ""
head = self.getAuthHeader(authenticate) head = self.getAuthHeader(authenticate)
utils.logMsg("MB3 Sync","HEADERS : " + str(head), level=1) self.logMsg("HEADERS : " + str(head), level=1)
conn = httplib.HTTPConnection(server, timeout=5)
# make the connection and send the request # make the connection and send the request
if(postBody != None): if(postBody != None):
head["Content-Type"] = "application/x-www-form-urlencoded" head["Content-Type"] = "application/x-www-form-urlencoded"
head["Content-Length"] = str(len(postBody)) head["Content-Length"] = str(len(postBody))
utils.logMsg("MB3 Sync","POST DATA : " + postBody) self.logMsg("POST DATA : " + postBody)
conn.request(method=type, url=urlPath, body=postBody, headers=head) conn.request(method=type, url=urlPath, body=postBody, headers=head)
else: else:
conn.request(method=type, url=urlPath, headers=head) conn.request(method=type, url=urlPath, headers=head)
@ -496,25 +557,25 @@ class DownloadUtils():
if tries == 5: if tries == 5:
data = conn.getresponse() data = conn.getresponse()
utils.logMsg("MB3 Sync","GET URL HEADERS : " + str(data.getheaders()), level=2) self.logMsg("GET URL HEADERS : " + str(data.getheaders()), level=2)
# process the response # process the response
contentType = "none" contentType = "none"
if int(data.status) == 200: if int(data.status) == 200:
retData = data.read() retData = data.read()
contentType = data.getheader('content-encoding') contentType = data.getheader('content-encoding')
utils.logMsg("MB3 Sync","Data Len Before : " + str(len(retData)), level=2) self.logMsg("Data Len Before : " + str(len(retData)), level=2)
if(contentType == "gzip"): if(contentType == "gzip"):
retData = StringIO.StringIO(retData) retData = StringIO.StringIO(retData)
gzipper = gzip.GzipFile(fileobj=retData) gzipper = gzip.GzipFile(fileobj=retData)
link = gzipper.read() link = gzipper.read()
else: else:
link = retData link = retData
utils.logMsg("MB3 Sync","Data Len After : " + str(len(link)), level=2) self.logMsg("Data Len After : " + str(len(link)), level=2)
utils.logMsg("MB3 Sync","====== 200 returned =======", level=2) self.logMsg("====== 200 returned =======", level=2)
utils.logMsg("MB3 Sync","Content-Type : " + str(contentType), level=2) self.logMsg("Content-Type : " + str(contentType), level=2)
utils.logMsg("MB3 Sync",link, level=2) self.logMsg(link, level=2)
utils.logMsg("MB3 Sync","====== 200 finished ======", level=2) self.logMsg("====== 200 finished ======", level=2)
elif ( int(data.status) == 301 ) or ( int(data.status) == 302 ): elif ( int(data.status) == 301 ) or ( int(data.status) == 302 ):
try: try:
@ -527,15 +588,14 @@ class DownloadUtils():
error = "HTTP response error: " + str(data.status) + " " + str(data.reason) error = "HTTP response error: " + str(data.status) + " " + str(data.reason)
xbmc.log(error) xbmc.log(error)
username = self.addonSettings.getSetting("username")
WINDOW = xbmcgui.Window(10000) WINDOW = xbmcgui.Window(10000)
timeStamp = WINDOW.getProperty("mb3sync_LAST_USER_ERROR") WINDOW.setProperty("AccessToken" + username, "")
if(timeStamp == None or timeStamp == ""): WINDOW.setProperty("userid" + username, "")
timeStamp = "0" self.addonSettings.setSetting("AccessToken" + username, "")
self.addonSettings.setSetting("userid" + username, "")
if((int(timeStamp) + 10) < int(time.time())):
xbmcgui.Dialog().ok(getString(30135), getString(30044))
WINDOW.setProperty("mb3sync_LAST_USER_ERROR", str(int(time.time())))
xbmcgui.Dialog().ok(self.getString(30135), self.getString(30044), "Reason : " + str(data.reason))
try: try:
conn.close() conn.close()
except: except:
@ -545,11 +605,13 @@ class DownloadUtils():
elif int(data.status) >= 400: elif int(data.status) >= 400:
error = "HTTP response error: " + str(data.status) + " " + str(data.reason) error = "HTTP response error: " + str(data.status) + " " + str(data.reason)
xbmc.log(error) xbmc.log(error)
stack = self.FormatException()
self.logMsg(stack)
if suppress is False: if suppress is False:
if popup == 0: if popup == 0:
xbmc.executebuiltin("XBMC.Notification(URL error: "+ str(data.reason) +",)") xbmc.executebuiltin("XBMC.Notification(URL error: "+ str(data.reason) +",)")
else: else:
xbmcgui.Dialog().ok(getString(30135),server) xbmcgui.Dialog().ok(self.getString(30135),server)
try: try:
conn.close() conn.close()
except: except:
@ -561,12 +623,12 @@ class DownloadUtils():
error = "Unable to connect to " + str(server) + " : " + str(msg) error = "Unable to connect to " + str(server) + " : " + str(msg)
xbmc.log(error) xbmc.log(error)
stack = self.FormatException() stack = self.FormatException()
utils.logMsg("MB3 Sync",stack) self.logMsg(stack)
if suppress is False: if suppress is False:
if popup == 0: if popup == 0:
xbmc.executebuiltin("XBMC.Notification(: Connection Error: Error connecting to server,)") xbmc.executebuiltin("XBMC.Notification(: Connection Error: Error connecting to server,)")
else: else:
xbmcgui.Dialog().ok(getString(30204), str(msg)) xbmcgui.Dialog().ok(self.getString(30204), str(msg))
pass pass
else: else:
try: try:

View file

@ -18,6 +18,8 @@ import KodiMonitor
import Utils as utils import Utils as utils
from LibrarySync import LibrarySync from LibrarySync import LibrarySync
from Player import Player from Player import Player
from DownloadUtils import DownloadUtils
from ConnectionManager import ConnectionManager
librarySync = LibrarySync() librarySync = LibrarySync()
class Service(): class Service():
@ -33,6 +35,8 @@ class Service():
def ServiceEntryPoint(self): def ServiceEntryPoint(self):
ConnectionManager().checkServer()
player = Player() player = Player()
lastProgressUpdate = datetime.today() lastProgressUpdate = datetime.today()
@ -76,7 +80,7 @@ class Service():
pass pass
else: else:
# background worker for database sync # background worker for database sync
if WINDOW.getProperty("mb3_authenticated") == "true": if DownloadUtils().authenticate(retreive=False) != "":
#full sync #full sync
if((interval_FullSync >= cur_seconds_fullsync)): if((interval_FullSync >= cur_seconds_fullsync)):
@ -91,8 +95,6 @@ class Service():
cur_seconds_incrsync = interval_IncrementalSync cur_seconds_incrsync = interval_IncrementalSync
else: else:
cur_seconds_incrsync -= 1 cur_seconds_incrsync -= 1
else:
utils.checkAuthentication()
utils.logMsg("MB3 Sync Service" "stopping Service",0) utils.logMsg("MB3 Sync Service" "stopping Service",0)