From f8632a97d82e78f9ce4f2d6f7ad6a737e2ab8a63 Mon Sep 17 00:00:00 2001 From: angelblue05 Date: Tue, 21 Apr 2015 21:20:02 -0500 Subject: [PATCH] Revert "Adjusted the rest to use the new method" This reverts commit 0c91c0b28b5423e0677d1260814c13db63503778. --- resources/lib/ClientInformation.py | 161 ++++++++++++++++++++++++----- resources/lib/ConnectionManager.py | 78 ++++++++------ resources/lib/ReadEmbyDB.py | 18 ++-- resources/lib/UserClient.py | 59 +++++------ resources/lib/WebSocketClient.py | 6 +- resources/lib/WriteKodiDB.py | 114 +++++++++++--------- 6 files changed, 282 insertions(+), 154 deletions(-) diff --git a/resources/lib/ClientInformation.py b/resources/lib/ClientInformation.py index 2625c12e..c17576aa 100644 --- a/resources/lib/ClientInformation.py +++ b/resources/lib/ClientInformation.py @@ -1,54 +1,70 @@ +####################################################################### +# CLIENTINFORMATION: centralized client data +# ------------------------------- +# addonId, addonName, addon version, clientId, platform +####################################################################### +# USER: centralized Userdata +# ------------------------------- +# username, userId, token, server, http prefix, LogLevel +####################################################################### + import xbmc import xbmcaddon import xbmcgui - import os from uuid import uuid4 as uuid4 from Lock import Lock -import Utils as utils - - class ClientInformation(): - def __init__(self): addonId = self.getAddonId() self.addon = xbmcaddon.Addon(id=addonId) + self.WINDOW = xbmcgui.Window( 10000 ) - self.className = self.__class__.__name__ - self.addonName = self.getAddonName() + level = User().getLogLevel() + self.logLevel = 0 + + if (level != None and level != ""): + self.logLevel = int(level) + + if (self.logLevel == 2): + self.LogCalls = True - def logMsg(self, msg, lvl=1): + def logMsg(self, msg, level = 1): - utils.logMsg("%s %s" % (self.addonName, self.className), str(msg), int(lvl)) + addonName = self.getAddonName() + className = self.__class__.__name__ + + if (self.logLevel >= level): + try: + xbmc.log("%s %s -> %s" % (addonName, className, str(msg))) + except UnicodeEncodeError: + try: + xbmc.log("%s %s -> %s" % (addonName, className, str(msg))) + except: pass def getAddonId(self): # To use when declaring xbmcaddon.Addon(id=addonId) - return "plugin.video.emby" + addonId = "plugin.video.emby" + return addonId def getAddonName(self): # Useful for logging - return self.addon.getAddonInfo('name').upper() + addonName = self.addon.getAddonInfo('name').upper() + return addonName def getVersion(self): - - return self.addon.getAddonInfo('version') - - def getDeviceName(self): - - deviceName = self.addon.getSetting('deviceName') - deviceName = deviceName.replace("\"", "_") - deviceName = deviceName.replace("/", "_") - - return deviceName + + version = self.addon.getAddonInfo('version') + return version def getMachineId(self): - WINDOW = xbmcgui.Window(10000) + WINDOW = self.WINDOW clientId = WINDOW.getProperty("client_id") - if (clientId != None and clientId != ""): + if(clientId != None and clientId != ""): return clientId # we need to load and or generate a client machine id @@ -62,21 +78,21 @@ class ClientInformation(): lock = Lock(machine_guid_lock_path) locked = lock.acquire() - if (locked == True): + if(locked == True): fd = os.open(machine_guid_path, os.O_CREAT|os.O_RDWR) clientId = os.read(fd, 256) - if (len(clientId) == 0): + if(len(clientId) == 0): uuid = uuid4() clientId = str("%012X" % uuid) - self.logMsg("ClientId saved to FILE: %s" % clientId, 2) + self.logMsg("ClientId saved to FILE : %s" % clientId,1) os.write(fd, clientId) os.fsync(fd) os.close(fd) - self.logMsg("ClientId saved to WINDOW: %s" % clientId, 1) + self.logMsg("ClientId saved to WINDOW : %s" % clientId,1) WINDOW.setProperty("client_id", clientId) finally: @@ -100,3 +116,94 @@ class ClientInformation(): return "Linux/Android" return "Unknown" + + +class User(ClientInformation): + + def __init__(self): + addonId = self.getAddonId() + self.addon = xbmcaddon.Addon(id=addonId) + self.WINDOW = xbmcgui.Window( 10000 ) + + level = self.getLogLevel() + 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): + + addonName = self.getAddonName() + className = self.__class__.__name__ + + if (self.logLevel >= level): + try: + xbmc.log("%s %s -> %s" % (addonName, className, str(msg))) + except UnicodeEncodeError: + try: + xbmc.log("%s %s -> %s" % (addonName, className, str(msg))) + except: pass + + def getUsername(self): + + username = self.addon.getSetting('username') + return username + + def getUserId(self): + + username = self.getUsername() + w_userId = self.WINDOW.getProperty('userId%s' % username) + s_userId = self.addon.getSetting('userId%s' % username) + + # Verify if userId is saved to Window + if (w_userId != ""): + self.logMsg("Returning saved (WINDOW) UserId for user: %s UserId: %s" % (username, w_userId),2) + return w_userId + # Verify if userId is saved in settings + elif (s_userId != ""): + self.logMsg("Returning saved (SETTINGS) UserId for user: %s UserId: %s" % (username, s_userId),2) + self.WINDOW.setProperty('userId%s' % username, s_userId) + return s_userId + else: + return "" + + def getToken(self): + + username = self.getUsername() + w_token = self.WINDOW.getProperty('AccessToken%s' % username) + s_token = self.addon.getSetting('AccessToken%s' % username) + + # Verify if token is saved to Window + if (w_token != ""): + self.logMsg("Returning saved (WINDOW) AccessToken for user: %s Token: %s" % (username, w_token),2) + return w_token + # Verify if token is saved in settings + elif (s_token != ""): + self.logMsg("Returning saved (SETTINGS) AccessToken for user: %s Token: %s" % (username, s_token),2) + self.WINDOW.setProperty('AccessToken%s' % username, s_token) + return s_token + else: + self.logMsg("User is not authenticated.") + return "" + + def getServer(self): + + host = self.addon.getSetting('ipaddress') + port = self.addon.getSetting('port') + return host + ":" + port + + def getHTTPprefix(self): + # For https support + prefix = self.addon.getSetting('prefix') + if prefix: + return "https://" + else: + return "http://" + + def getLogLevel(self): + + level = self.addon.getSetting('logLevel') + return level diff --git a/resources/lib/ConnectionManager.py b/resources/lib/ConnectionManager.py index f91722d2..e06aa315 100644 --- a/resources/lib/ConnectionManager.py +++ b/resources/lib/ConnectionManager.py @@ -13,7 +13,6 @@ import socket import threading from datetime import datetime -import Utils as utils from DownloadUtils import DownloadUtils from UserClient import UserClient from ClientInformation import ClientInformation @@ -22,32 +21,48 @@ from ClientInformation import ClientInformation class ConnectionManager(): clientInfo = ClientInformation() - uc = UserClient() + userClient = UserClient() doUtils = DownloadUtils() - addonName = clientInfo.getAddonName() - addonId = clientInfo.getAddonId() - addon = xbmcaddon.Addon(id=addonId) - WINDOW = xbmcgui.Window(10000) - logLevel = 0 + addon = None + WINDOW = xbmcgui.Window(10000) def __init__(self): - self.className = self.__class__.__name__ - self.__language__ = self.addon.getLocalizedString - - def logMsg(self, msg, lvl=1): + clientInfo = self.clientInfo - utils.logMsg("%s %s" % (self.addonName, self.className), msg, int(lvl)) + self.addonId = clientInfo.getAddonId() + self.addonName = clientInfo.getAddonName() + self.addon = xbmcaddon.Addon(id=self.addonId) + self.__language__ = self.addon.getLocalizedString + + def logMsg(self, msg, level=1): + + addonName = self.addonName + className = self.__class__.__name__ + s_logLevel = self.userClient.getLogLevel() + + # Attempt to change logLevel live + if (self.logLevel != s_logLevel): + self.logLevel = s_logLevel + + if (self.logLevel >= level): + try: + xbmc.log("%s %s -> %s" % (addonName, className, str(msg))) + except UnicodeEncodeError: + try: + xbmc.log("%s %s -> %s" % (addonName, className, str(msg.encode('utf-8')))) + except: + pass def checkServer(self): self.WINDOW.setProperty("Server_Checked", "True") - self.logMsg("Connection Manager Called", 2) + self.logMsg("Connection Manager Called") addon = self.addon - server = self.uc.getServer() + server = self.userClient.getServer() if (server != ""): self.logMsg("Server already set", 2) @@ -63,7 +78,7 @@ class ConnectionManager(): prefix,ip,port = serverInfo.split(":") setServer = xbmcgui.Dialog().yesno(self.__language__(30167), "Proceed with the following server?", self.__language__(30169) + serverInfo) - if (setServer == 1): + if setServer == 1: self.logMsg("Server selected. Saving information.", 1) addon.setSetting("ipaddress", ip.replace("/", "")) addon.setSetting("port", port) @@ -78,40 +93,39 @@ class ConnectionManager(): # Get List of public users self.logMsg("Getting user list", 1) server = ip.replace("/", "") + ":" + port - url = "%s/mediabrowser/Users/Public?format=json" % serverInfo try: - result = self.doUtils.downloadUrl(url, authenticate=False) + jsonData = self.doUtils.downloadUrl(serverInfo + "/mediabrowser/Users/Public?format=json", authenticate=False) except Exception, msg: - error = "Unable to connect to %s: %s" % (server, msg) - self.logMsg(error, 1) + error = "Get User unable to connect to " + server + " : " + str(msg) + xbmc.log (error) return "" - if (result == ""): + if (jsonData == False): return - self.logMsg("jsonData: %s" % result, 2) - + self.logMsg("jsonData : " + str(jsonData), level=2) + result = json.loads(jsonData) + names = [] userList = [] for user in result: - name = user[u'Name'] + name = user.get("Name") userList.append(name) - - if(user[u'HasPassword'] == True): + if(user.get("HasPassword") == True): name = name + " (Secure)" names.append(name) - self.logMsg("User List: %s" % names, 1) - self.logMsg("User List: %s" % userList, 2) + self.logMsg("User List: " + str(names)) + self.logMsg("User List: " + str(userList)) return_value = xbmcgui.Dialog().select(self.__language__(30200), names) - if (return_value > -1): + if(return_value > -1): selected_user = userList[return_value] - self.logMsg("Selected User: %s" % selected_user, 1) + self.logMsg("elected User: %s" % selected_user) self.addon.setSetting("username", selected_user) else: - self.logMsg("No user selected.", 1) + xbmc.log("No user selected.") xbmc.executebuiltin('Addon.OpenSettings(%s)' % self.addonId) return @@ -139,8 +153,8 @@ class ConnectionManager(): sock.setsockopt(socket.SOL_IP, socket.IP_MULTICAST_LOOP, 1) sock.setsockopt(socket.IPPROTO_IP, socket.SO_REUSEADDR, 1) - self.logMsg("MutliGroup : %s" % str(MULTI_GROUP), 2); - self.logMsg("Sending UDP Data: %s" % MESSAGE, 2); + self.logMsg("MutliGroup : %s" % str(MULTI_GROUP)); + self.logMsg("Sending UDP Data: %s" % MESSAGE); sock.sendto(MESSAGE, MULTI_GROUP) try: diff --git a/resources/lib/ReadEmbyDB.py b/resources/lib/ReadEmbyDB.py index 4d80455c..584a0bd5 100644 --- a/resources/lib/ReadEmbyDB.py +++ b/resources/lib/ReadEmbyDB.py @@ -182,11 +182,11 @@ class ReadEmbyDB(): def getCollections(self, type): #Build a list of the user views - doUtils = DownloadUtils() + downloadUtils = DownloadUtils() try: url = "{server}/mediabrowser/Users/{UserId}/Items/Root?format=json" - result = doUtils.downloadUrl(url) + result = downloadUtils.downloadUrl(url) except Exception, msg: error = "Can't connect: %s" % msg xbmc.log(error) @@ -198,7 +198,7 @@ class ReadEmbyDB(): parentid = result[u'Id'] url = "{server}/mediabrowser/Users/{UserId}/items?ParentId=%s&Sortby=SortName&format=json" % parentid - result = doUtils.downloadUrl(url) + result = downloadUtils.downloadUrl(url) collections=[] if (result == ""): @@ -209,11 +209,9 @@ class ReadEmbyDB(): for item in result: if (item[u'RecursiveItemCount'] != 0): Name = item[u'Name'] - if u'CollectionType' not in item: + itemtype = item[u'CollectionType'] + if itemtype == None or itemtype == "": itemtype = "movies" # User may not have declared the type - else: - itemtype = item[u'CollectionType'] - if itemtype == type and Name != "Collections": collections.append({'title': Name, 'type' : itemtype, @@ -249,9 +247,9 @@ class ReadEmbyDB(): if type == None: type = "None" # User may not have declared the type if type == type: - collections.append( {'title' : Name, - 'type' : type, - 'id' : view[u'Id']}) + collections.append({'title': Name, + 'type' : type, + 'id' : view[u'Id']}) return collections def getBoxSets(self): diff --git a/resources/lib/UserClient.py b/resources/lib/UserClient.py index 575f5929..b3df3a58 100644 --- a/resources/lib/UserClient.py +++ b/resources/lib/UserClient.py @@ -19,22 +19,18 @@ from DownloadUtils import DownloadUtils class UserClient(threading.Thread): - # Borg - multiple instances, shared state - _shared_state = {} clientInfo = ClientInformation() doUtils = DownloadUtils() - KodiMonitor = KodiMonitor.Kodi_Monitor() - addonName = clientInfo.getAddonName() - addonId = clientInfo.getAddonId() - addon = xbmcaddon.Addon(id=addonId) - WINDOW = xbmcgui.Window(10000) + className = None stopClient = False logLevel = 0 + addon = None auth = True retry = 0 + WINDOW = xbmcgui.Window(10000) currUser = None currUserId = None @@ -44,7 +40,10 @@ class UserClient(threading.Thread): def __init__(self, *args): - self.__dict__ = self._shared_state + self.KodiMonitor = KodiMonitor.Kodi_Monitor() + + self.addonId = self.clientInfo.getAddonId() + self.addon = xbmcaddon.Addon(id=self.addonId) self.className = self.__class__.__name__ threading.Thread.__init__(self, *args) @@ -56,7 +55,7 @@ class UserClient(threading.Thread): def getUsername(self): username = self.addon.getSetting('username') - + if (username == ""): self.logMsg("No username saved.", 2) return "" @@ -137,19 +136,18 @@ class UserClient(threading.Thread): # Get public Users url = "%s/mediabrowser/Users/Public?format=json" % server - result = self.doUtils.downloadUrl(url, authenticate=False) + jsonData = self.doUtils.downloadUrl(url, authenticate=False) users = [] - if (result != ""): - users = result + if (jsonData != ""): + users = json.loads(jsonData) return users def loadCurrUser(self): WINDOW = self.WINDOW - doUtils = self.doUtils username = self.getUsername() # Only to be used if token exists @@ -164,14 +162,6 @@ class UserClient(threading.Thread): WINDOW.setProperty("server_%s" % username, self.getServer(prefix=False)) WINDOW.setProperty("userId%s" % username, self.currUserId) - # Set DownloadUtils values - doUtils.setUsername(username) - doUtils.setUserId(self.currUserId) - doUtils.setServer(self.currServer) - doUtils.setToken(self.currToken) - # Start DownloadUtils session - doUtils.startSession() - self.currUser = username def authenticate(self): @@ -205,15 +195,11 @@ class UserClient(threading.Thread): users = self.getPublicUsers() password = "" - '''if users == "": - self.WINDOW.setProperty("Server_status", "Stop") - return''' # Find user in list for user in users: - name = user[u'Name'] + name = user.get("Name") userHasPassword = False - - if (unicode(username, 'utf-8') in name): + if (username == name): # Verify if user has a password if (user.get("HasPassword") == True): userHasPassword = True @@ -221,7 +207,7 @@ class UserClient(threading.Thread): if (userHasPassword): password = xbmcgui.Dialog().input("Enter password for user: %s" % username, option=xbmcgui.ALPHANUM_HIDE_INPUT) # If password dialog is cancelled - if (password == ""): + if password == "": self.logMsg("No password entered.", 0) self.WINDOW.setProperty("Server_status", "Stop") self.auth = False @@ -236,21 +222,22 @@ class UserClient(threading.Thread): # Authenticate username and password url = "%s/mediabrowser/Users/AuthenticateByName?format=json" % server - data = {'username': username, 'password': sha1} - self.logMsg(data, 2) + messageData = "username=%s&password=%s" % (username, sha1) - result = self.doUtils.downloadUrl(url, postBody=data, type="POST", authenticate=False) + resp = self.doUtils.downloadUrl(url, postBody=messageData, type="POST", authenticate=False) + result = None accessToken = None try: - self.logMsg("Auth_Reponse: %s" % result, 1) - accessToken = result[u'AccessToken'] + self.logMsg("Auth_Reponse: %s" % resp, 1) + result = json.loads(resp) + accessToken = result.get("AccessToken") except: pass if (result != None and accessToken != None): self.currUser = username - userId = result[u'User'][u'Id'] + userId = result.get("User").get("Id") addon.setSetting("accessToken%s" % username, accessToken) addon.setSetting("userId%s" % username, userId) self.logMsg("User Authenticated: %s" % accessToken) @@ -262,7 +249,7 @@ class UserClient(threading.Thread): self.logMsg("User authentication failed.") addon.setSetting("accessToken%s" % username, "") addon.setSetting("userId%s" % username, "") - xbmcgui.Dialog().ok("Error connecting", "Invalid username or password.") + xbmcgui.Dialog().ok("Error Connecting", "Wrong password.") # Give two attempts at entering password self.retry += 1 @@ -275,7 +262,7 @@ class UserClient(threading.Thread): def resetClient(self): - if (self.currToken != None): + if self.currToken != None: # In case of 401, removed saved token self.addon.setSetting("accessToken%s" % self.currUser, "") self.WINDOW.setProperty("accessToken%s" % self.currUser, "") diff --git a/resources/lib/WebSocketClient.py b/resources/lib/WebSocketClient.py index ec61c45a..574b1cb0 100644 --- a/resources/lib/WebSocketClient.py +++ b/resources/lib/WebSocketClient.py @@ -236,7 +236,7 @@ class WebSocketThread(threading.Thread): LibrarySync().TvShowsSync(connection, cursor, fullsync = False, installFirstRun = False, itemList = itemsToUpdate) cursor.close() - def user_data_update(self, userData): + def user_data_update(self, userDataList): for userData in userDataList: self.logMsg("Message : Doing UserDataChanged : UserData : " + str(userData), 0) @@ -268,11 +268,11 @@ class WebSocketThread(threading.Thread): messageString = json.dumps(messageData) self.logMsg("Opened : " + str(messageString)) ws.send(messageString) - ''' + # Set Capabilities xbmc.log("postcapabilities_called") downloadUtils = DownloadUtils() - downloadUtils.startSession()''' + downloadUtils.postcapabilities() def getWebSocketPort(self, host, port): diff --git a/resources/lib/WriteKodiDB.py b/resources/lib/WriteKodiDB.py index b46ccb44..dbcd306d 100644 --- a/resources/lib/WriteKodiDB.py +++ b/resources/lib/WriteKodiDB.py @@ -32,11 +32,15 @@ class WriteKodiDB(): mb3Id = ReadKodiDB().getEmbyIdByKodiId(id, type) if(mb3Id != None): - addon = xbmcaddon.Addon(id='plugin.video.emby') + addon = xbmcaddon.Addon(id='plugin.video.emby') + WINDOW = xbmcgui.Window(10000) + username = WINDOW.getProperty('currUser') + userid = WINDOW.getProperty('userId%s' % username) + server = WINDOW.getProperty('server%s' % username) downloadUtils = DownloadUtils() - watchedurl = "{server}/mediabrowser/Users/{UserId}/PlayedItems/%s" % mb3Id + watchedurl = "%s/mediabrowser/Users/%s/PlayedItems/%s" % (server, userid, mb3Id) utils.logMsg("Emby","watchedurl -->" + watchedurl) if playcount != 0: downloadUtils.downloadUrl(watchedurl, postBody="", type="POST") @@ -47,7 +51,8 @@ class WriteKodiDB(): addon = xbmcaddon.Addon(id='plugin.video.emby') WINDOW = xbmcgui.Window(10000) username = WINDOW.getProperty('currUser') - server = WINDOW.getProperty('server%s' % username) + userid = WINDOW.getProperty('userId%s' % username) + server = WINDOW.getProperty('server%s' % username) downloadUtils = DownloadUtils() @@ -108,12 +113,12 @@ class WriteKodiDB(): #trailer link trailerUrl = None if MBitem.get("LocalTrailerCount") != None and MBitem.get("LocalTrailerCount") > 0: - itemTrailerUrl = "{server}/mediabrowser/Users/{UserId}/Items/%s/LocalTrailers?format=json" % MBitem.get("Id") - jsonData = downloadUtils.downloadUrl(itemTrailerUrl) - if (jsonData != ""): - trailerItem = jsonData - if trailerItem[0][u'LocationType'] == "FileSystem": - trailerUrl = PlayUtils().getPlayUrl(server, trailerItem[0][u'Id'], trailerItem[0]) + itemTrailerUrl = "%s/mediabrowser/Users/%s/Items/%s/LocalTrailers?format=json" % (server, userid, MBitem.get("Id")) + jsonData = downloadUtils.downloadUrl(itemTrailerUrl, suppress=False, popup=0 ) + if(jsonData != ""): + trailerItem = json.loads(jsonData) + if trailerItem[0].get("LocationType") == "FileSystem": + trailerUrl = PlayUtils().getPlayUrl(server, trailerItem[0].get("Id"), trailerItem[0]) trailerUrl = utils.convertEncoding(trailerUrl) self.getPropertyParam_Batched(KodiItem, "trailer", trailerUrl, params) @@ -412,7 +417,6 @@ class WriteKodiDB(): #update artwork changes = False - artwork = {} artwork["thumb"] = API().getArtwork(MBitem, "Primary") @@ -672,11 +676,11 @@ class WriteKodiDB(): trailerUrl = None if MBitem.get("LocalTrailerCount") != None and MBitem.get("LocalTrailerCount") > 0: itemTrailerUrl = "%s/mediabrowser/Users/%s/Items/%s/LocalTrailers?format=json" % (server, userid, MBitem.get("Id")) - jsonData = downloadUtils.downloadUrl(itemTrailerUrl) + jsonData = downloadUtils.downloadUrl(itemTrailerUrl, suppress=False, popup=0 ) if(jsonData != ""): - trailerItem = jsonData - if trailerItem[0][u'LocationType'] == "FileSystem": - trailerUrl = PlayUtils().getPlayUrl(server, trailerItem[0][u'Id'], trailerItem[0]) + trailerItem = json.loads(jsonData) + if trailerItem[0].get("LocationType") == "FileSystem": + trailerUrl = PlayUtils().getPlayUrl(server, trailerItem[0].get("Id"), trailerItem[0]) trailerUrl = utils.convertEncoding(trailerUrl) #create the movie @@ -687,13 +691,18 @@ class WriteKodiDB(): cursor.execute(pathsql, (movieid, fileid, title, plot, shortplot, rating, year, MBitem["Id"], sorttitle, runtime, title, trailerUrl)) + actionPerformed = False + try: connection.commit() utils.logMsg("Emby","Added movie to Kodi Library",MBitem["Id"] + " - " + MBitem["Name"]) + actionPerformed = True except: utils.logMsg("Emby","Error adding movie to Kodi Library",MBitem["Id"] + " - " + MBitem["Name"]) actionPerformed = False + return actionPerformed + def addMusicVideoToKodiLibrary( self, MBitem, connection, cursor ): #adds a musicvideo to Kodi by directly inserting it to connectionthe DB while there is no addMusicVideo available on the json API @@ -763,25 +772,55 @@ class WriteKodiDB(): pathsql="insert into musicvideo(idMVideo, idFile, c00, c04, c08, c23) values(?, ?, ?, ?, ?, ?)" cursor.execute(pathsql, (musicvideoid, fileid, title, runtime, plot, MBitem["Id"])) + actionPerformed = False + try: connection.commit() utils.logMsg("Emby","Added musicvideo to Kodi Library",MBitem["Id"] + " - " + MBitem["Name"]) + actionPerformed = True except: utils.logMsg("Emby","Error adding musicvideo to Kodi Library",MBitem["Id"] + " - " + MBitem["Name"]) - actionPerformed = False + return actionPerformed + def addEpisodeToKodiLibrary(self, MBitem, connection, cursor): #adds a Episode to Kodi by directly inserting it to the DB while there is no addEpisode available on the json API #TODO: PR at Kodi team for a addEpisode endpoint on their API + # check season + season = 0 + if MBitem.get("ParentIndexNumber") != None: + season = int(MBitem.get("ParentIndexNumber")) + else: + utils.logMsg("Emby","Error adding episode to Kodi Library, no ParentIndexNumber - ID: " + MBitem["Id"] + " - " + MBitem["Name"]) + return False + # first check the episode is not already in the DB using the Emby ID which is stored in c20 cursor.execute("SELECT idEpisode FROM episode WHERE c20 = ?",(MBitem["Id"],)) result = cursor.fetchone() if result != None: utils.logMsg("Emby", "Episode already exists in DB : " + MBitem["Id"] + " - " + MBitem["Name"], 2) - return + return False + # get the showid + cursor.execute("SELECT idShow as showid FROM tvshow WHERE c12 = ?",(MBitem["SeriesId"],)) + result = cursor.fetchone() + showid = -1 + if(result == None): + utils.logMsg("Emby","Error adding episode to Kodi Library, couldn't find show - ID: " + MBitem["Id"] + " - " + MBitem["Name"]) + return False + else: + showid = result[0] + + # check season + cursor.execute("SELECT idSeason FROM seasons WHERE idShow = ? and season = ?",(showid, season)) + result = cursor.fetchone() + if(result == None): + utils.logMsg("Emby","Error adding episode to Kodi Library, season does not exist - ShowId: " + str(showid) + " SeasonNo: " + str(season) + " EmbyId: " + MBitem["Id"] + " Name: " + MBitem["Name"]) + return False + + # do add addon = xbmcaddon.Addon(id='plugin.video.emby') port = addon.getSetting('port') host = addon.getSetting('ipaddress') @@ -839,33 +878,7 @@ class WriteKodiDB(): fileid = fileid + 1 sql="INSERT OR REPLACE into files(idFile, idPath, strFilename, playCount, lastPlayed, dateAdded) values(?, ?, ?, ?, ?, ?)" cursor.execute(sql, (fileid,pathid,filename,playcount,lastplayed,dateadded)) - - #get the showid - cursor.execute("SELECT idShow as showid FROM tvshow WHERE c12 = ?",(MBitem["SeriesId"],)) - result = cursor.fetchone() - showid = -1 - if(result == None): - utils.logMsg("Emby","Error adding episode to Kodi Library, couldn't find show - ID: " + MBitem["Id"] + " - " + MBitem["Name"]) - actionPerformed = False - return False - else: - showid = result[0] - - # check season - season = 0 - if MBitem.get("ParentIndexNumber") != None: - season = int(MBitem.get("ParentIndexNumber")) - else: - utils.logMsg("Emby","Error adding episode to Kodi Library, no ParentIndexNumber - ID: " + MBitem["Id"] + " - " + MBitem["Name"]) - return False - - cursor.execute("SELECT idSeason FROM seasons WHERE idShow = ? and season = ?",(showid, season)) - result = cursor.fetchone() - if(result == None): - utils.logMsg("Emby","Error adding episode to Kodi Library, season does not exist - ShowId: " + str(showid) + " SeasonNo: " + str(season) + " EmbyId: " + MBitem["Id"] + " Name: " + MBitem["Name"]) - actionPerformed = False - return False - + # build info episode = 0 if MBitem.get("IndexNumber") != None: @@ -888,13 +901,17 @@ class WriteKodiDB(): pathsql = "INSERT into episode(idEpisode, idFile, c00, c01, c03, c05, c09, c20, c12, c13, c14, idShow, c15, c16) values(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)" cursor.execute(pathsql, (episodeid, fileid, title, plot, rating, premieredate, runtime, MBitem["Id"], season, episode, title, showid, "-1", "-1")) + actionPerformed = False + try: connection.commit() utils.logMsg("Emby","Added episode to Kodi Library - ID: " + MBitem["Id"] + " - " + MBitem["Name"]) + actionPerformed = True except: utils.logMsg("Emby","Error adding episode to Kodi Library - ID: " + MBitem["Id"] + " - " + MBitem["Name"]) - actionPerformed = False - + + return actionPerformed + def deleteMovieFromKodiLibrary(self, id ): kodiItem = ReadKodiDB().getKodiMovie(id) utils.logMsg("deleting movie from Kodi library",id) @@ -965,6 +982,7 @@ class WriteKodiDB(): elif "/" in path: toplevelpathstr = path.rsplit("/",2)[1] toplevelpath = path.replace(toplevelpathstr + "/","") + cursor.execute("SELECT idPath as tlpathid FROM path WHERE strPath = ?",(toplevelpath,)) result = cursor.fetchone() if result == None: @@ -992,12 +1010,16 @@ class WriteKodiDB(): pathsql="insert into tvshowlinkpath(idShow,idPath) values(?, ?)" cursor.execute(pathsql, (showid,pathid)) + actionPerformed = False + try: connection.commit() utils.logMsg("Emby","Added TV Show to Kodi Library: " + MBitem["Id"] + " - " + MBitem["Name"]) + actionPerformed = True except: utils.logMsg("Emby","Error adding tvshow to Kodi Library: " + MBitem["Id"] + " - " + MBitem["Name"]) - actionPerformed = False + + return actionPerformed def deleteTVShowFromKodiLibrary(self, id): xbmc.sleep(sleepVal)