Revert "Revert "Adjusted the rest to use the new method""

This reverts commit f8632a97d8.
This commit is contained in:
angelblue05 2015-04-21 21:31:16 -05:00
parent f8632a97d8
commit 78acae377f
6 changed files with 153 additions and 281 deletions

View file

@ -1,70 +1,54 @@
#######################################################################
# 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 )
level = User().getLogLevel()
self.logLevel = 0
if (level != None and level != ""):
self.logLevel = int(level)
if (self.logLevel == 2):
self.LogCalls = True
self.className = self.__class__.__name__
self.addonName = self.getAddonName()
def logMsg(self, msg, level = 1):
def logMsg(self, msg, lvl=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
utils.logMsg("%s %s" % (self.addonName, self.className), str(msg), int(lvl))
def getAddonId(self):
# To use when declaring xbmcaddon.Addon(id=addonId)
addonId = "plugin.video.emby"
return addonId
return "plugin.video.emby"
def getAddonName(self):
# Useful for logging
addonName = self.addon.getAddonInfo('name').upper()
return addonName
return self.addon.getAddonInfo('name').upper()
def getVersion(self):
version = self.addon.getAddonInfo('version')
return version
return self.addon.getAddonInfo('version')
def getDeviceName(self):
deviceName = self.addon.getSetting('deviceName')
deviceName = deviceName.replace("\"", "_")
deviceName = deviceName.replace("/", "_")
return deviceName
def getMachineId(self):
WINDOW = self.WINDOW
WINDOW = xbmcgui.Window(10000)
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
@ -78,21 +62,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,1)
self.logMsg("ClientId saved to FILE: %s" % clientId, 2)
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:
@ -116,94 +100,3 @@ 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

View file

@ -13,6 +13,7 @@ import socket
import threading
from datetime import datetime
import Utils as utils
from DownloadUtils import DownloadUtils
from UserClient import UserClient
from ClientInformation import ClientInformation
@ -21,48 +22,32 @@ from ClientInformation import ClientInformation
class ConnectionManager():
clientInfo = ClientInformation()
userClient = UserClient()
uc = UserClient()
doUtils = DownloadUtils()
logLevel = 0
addon = None
addonName = clientInfo.getAddonName()
addonId = clientInfo.getAddonId()
addon = xbmcaddon.Addon(id=addonId)
WINDOW = xbmcgui.Window(10000)
logLevel = 0
def __init__(self):
clientInfo = self.clientInfo
self.addonId = clientInfo.getAddonId()
self.addonName = clientInfo.getAddonName()
self.addon = xbmcaddon.Addon(id=self.addonId)
self.__language__ = self.addon.getLocalizedString
self.className = self.__class__.__name__
self.__language__ = self.addon.getLocalizedString
def logMsg(self, msg, level=1):
addonName = self.addonName
className = self.__class__.__name__
s_logLevel = self.userClient.getLogLevel()
def logMsg(self, msg, lvl=1):
# 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
utils.logMsg("%s %s" % (self.addonName, self.className), msg, int(lvl))
def checkServer(self):
self.WINDOW.setProperty("Server_Checked", "True")
self.logMsg("Connection Manager Called")
self.logMsg("Connection Manager Called", 2)
addon = self.addon
server = self.userClient.getServer()
server = self.uc.getServer()
if (server != ""):
self.logMsg("Server already set", 2)
@ -78,7 +63,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)
@ -93,39 +78,40 @@ 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:
jsonData = self.doUtils.downloadUrl(serverInfo + "/mediabrowser/Users/Public?format=json", authenticate=False)
result = self.doUtils.downloadUrl(url, authenticate=False)
except Exception, msg:
error = "Get User unable to connect to " + server + " : " + str(msg)
xbmc.log (error)
error = "Unable to connect to %s: %s" % (server, msg)
self.logMsg(error, 1)
return ""
if (jsonData == False):
if (result == ""):
return
self.logMsg("jsonData : " + str(jsonData), level=2)
result = json.loads(jsonData)
self.logMsg("jsonData: %s" % result, 2)
names = []
userList = []
for user in result:
name = user.get("Name")
name = user[u'Name']
userList.append(name)
if(user.get("HasPassword") == True):
if(user[u'HasPassword'] == True):
name = name + " (Secure)"
names.append(name)
self.logMsg("User List: " + str(names))
self.logMsg("User List: " + str(userList))
self.logMsg("User List: %s" % names, 1)
self.logMsg("User List: %s" % userList, 2)
return_value = xbmcgui.Dialog().select(self.__language__(30200), names)
if(return_value > -1):
if (return_value > -1):
selected_user = userList[return_value]
self.logMsg("elected User: %s" % selected_user)
self.logMsg("Selected User: %s" % selected_user, 1)
self.addon.setSetting("username", selected_user)
else:
xbmc.log("No user selected.")
self.logMsg("No user selected.", 1)
xbmc.executebuiltin('Addon.OpenSettings(%s)' % self.addonId)
return
@ -153,8 +139,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));
self.logMsg("Sending UDP Data: %s" % MESSAGE);
self.logMsg("MutliGroup : %s" % str(MULTI_GROUP), 2);
self.logMsg("Sending UDP Data: %s" % MESSAGE, 2);
sock.sendto(MESSAGE, MULTI_GROUP)
try:

View file

@ -182,11 +182,11 @@ class ReadEmbyDB():
def getCollections(self, type):
#Build a list of the user views
downloadUtils = DownloadUtils()
doUtils = DownloadUtils()
try:
url = "{server}/mediabrowser/Users/{UserId}/Items/Root?format=json"
result = downloadUtils.downloadUrl(url)
result = doUtils.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 = downloadUtils.downloadUrl(url)
result = doUtils.downloadUrl(url)
collections=[]
if (result == ""):
@ -209,9 +209,11 @@ class ReadEmbyDB():
for item in result:
if (item[u'RecursiveItemCount'] != 0):
Name = item[u'Name']
itemtype = item[u'CollectionType']
if itemtype == None or itemtype == "":
if u'CollectionType' not in item:
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,
@ -247,9 +249,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):

View file

@ -19,18 +19,22 @@ 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()
className = None
addonId = clientInfo.getAddonId()
addon = xbmcaddon.Addon(id=addonId)
WINDOW = xbmcgui.Window(10000)
stopClient = False
logLevel = 0
addon = None
auth = True
retry = 0
WINDOW = xbmcgui.Window(10000)
currUser = None
currUserId = None
@ -40,10 +44,7 @@ class UserClient(threading.Thread):
def __init__(self, *args):
self.KodiMonitor = KodiMonitor.Kodi_Monitor()
self.addonId = self.clientInfo.getAddonId()
self.addon = xbmcaddon.Addon(id=self.addonId)
self.__dict__ = self._shared_state
self.className = self.__class__.__name__
threading.Thread.__init__(self, *args)
@ -55,7 +56,7 @@ class UserClient(threading.Thread):
def getUsername(self):
username = self.addon.getSetting('username')
if (username == ""):
self.logMsg("No username saved.", 2)
return ""
@ -136,18 +137,19 @@ class UserClient(threading.Thread):
# Get public Users
url = "%s/mediabrowser/Users/Public?format=json" % server
jsonData = self.doUtils.downloadUrl(url, authenticate=False)
result = self.doUtils.downloadUrl(url, authenticate=False)
users = []
if (jsonData != ""):
users = json.loads(jsonData)
if (result != ""):
users = result
return users
def loadCurrUser(self):
WINDOW = self.WINDOW
doUtils = self.doUtils
username = self.getUsername()
# Only to be used if token exists
@ -162,6 +164,14 @@ 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):
@ -195,11 +205,15 @@ 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.get("Name")
name = user[u'Name']
userHasPassword = False
if (username == name):
if (unicode(username, 'utf-8') in name):
# Verify if user has a password
if (user.get("HasPassword") == True):
userHasPassword = True
@ -207,7 +221,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
@ -222,22 +236,21 @@ class UserClient(threading.Thread):
# Authenticate username and password
url = "%s/mediabrowser/Users/AuthenticateByName?format=json" % server
messageData = "username=%s&password=%s" % (username, sha1)
data = {'username': username, 'password': sha1}
self.logMsg(data, 2)
resp = self.doUtils.downloadUrl(url, postBody=messageData, type="POST", authenticate=False)
result = self.doUtils.downloadUrl(url, postBody=data, type="POST", authenticate=False)
result = None
accessToken = None
try:
self.logMsg("Auth_Reponse: %s" % resp, 1)
result = json.loads(resp)
accessToken = result.get("AccessToken")
self.logMsg("Auth_Reponse: %s" % result, 1)
accessToken = result[u'AccessToken']
except:
pass
if (result != None and accessToken != None):
self.currUser = username
userId = result.get("User").get("Id")
userId = result[u'User'][u'Id']
addon.setSetting("accessToken%s" % username, accessToken)
addon.setSetting("userId%s" % username, userId)
self.logMsg("User Authenticated: %s" % accessToken)
@ -249,7 +262,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", "Wrong password.")
xbmcgui.Dialog().ok("Error connecting", "Invalid username or password.")
# Give two attempts at entering password
self.retry += 1
@ -262,7 +275,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, "")

View file

@ -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, userDataList):
def user_data_update(self, userData):
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.postcapabilities()
downloadUtils.startSession()'''
def getWebSocketPort(self, host, port):

View file

@ -32,15 +32,11 @@ class WriteKodiDB():
mb3Id = ReadKodiDB().getEmbyIdByKodiId(id, type)
if(mb3Id != None):
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)
addon = xbmcaddon.Addon(id='plugin.video.emby')
downloadUtils = DownloadUtils()
watchedurl = "%s/mediabrowser/Users/%s/PlayedItems/%s" % (server, userid, mb3Id)
watchedurl = "{server}/mediabrowser/Users/{UserId}/PlayedItems/%s" % mb3Id
utils.logMsg("Emby","watchedurl -->" + watchedurl)
if playcount != 0:
downloadUtils.downloadUrl(watchedurl, postBody="", type="POST")
@ -51,8 +47,7 @@ class WriteKodiDB():
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)
server = WINDOW.getProperty('server%s' % username)
downloadUtils = DownloadUtils()
@ -113,12 +108,12 @@ class WriteKodiDB():
#trailer link
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, 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])
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])
trailerUrl = utils.convertEncoding(trailerUrl)
self.getPropertyParam_Batched(KodiItem, "trailer", trailerUrl, params)
@ -417,6 +412,7 @@ class WriteKodiDB():
#update artwork
changes = False
artwork = {}
artwork["thumb"] = API().getArtwork(MBitem, "Primary")
@ -676,11 +672,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, suppress=False, popup=0 )
jsonData = downloadUtils.downloadUrl(itemTrailerUrl)
if(jsonData != ""):
trailerItem = json.loads(jsonData)
if trailerItem[0].get("LocationType") == "FileSystem":
trailerUrl = PlayUtils().getPlayUrl(server, trailerItem[0].get("Id"), trailerItem[0])
trailerItem = jsonData
if trailerItem[0][u'LocationType'] == "FileSystem":
trailerUrl = PlayUtils().getPlayUrl(server, trailerItem[0][u'Id'], trailerItem[0])
trailerUrl = utils.convertEncoding(trailerUrl)
#create the movie
@ -691,18 +687,13 @@ 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
@ -772,55 +763,25 @@ 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 False
return
# 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')
@ -878,7 +839,33 @@ 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:
@ -901,17 +888,13 @@ 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"])
return actionPerformed
actionPerformed = False
def deleteMovieFromKodiLibrary(self, id ):
kodiItem = ReadKodiDB().getKodiMovie(id)
utils.logMsg("deleting movie from Kodi library",id)
@ -982,7 +965,6 @@ 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:
@ -1010,16 +992,12 @@ 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"])
return actionPerformed
actionPerformed = False
def deleteTVShowFromKodiLibrary(self, id):
xbmc.sleep(sleepVal)