Centralize logging

This commit is contained in:
angelblue05 2016-06-19 13:30:54 -05:00
parent 354877d31c
commit aa3a6fa17f
2 changed files with 75 additions and 68 deletions

View file

@ -10,13 +10,16 @@ import xbmc
import xbmcaddon import xbmcaddon
import xbmcgui import xbmcgui
addon_ = xbmcaddon.Addon(id='plugin.video.emby') #################################################################################################
addon_path = addon_.getAddonInfo('path').decode('utf-8')
base_resource = xbmc.translatePath(os.path.join(addon_path, 'resources', 'lib')).decode('utf-8') _addon = xbmcaddon.Addon(id='plugin.video.emby')
sys.path.append(base_resource) _addon_path = _addon.getAddonInfo('path').decode('utf-8')
_base_resource = xbmc.translatePath(os.path.join(_addon_path, 'resources', 'lib')).decode('utf-8')
sys.path.append(_base_resource)
#################################################################################################
import artwork import artwork
import utils
import clientinfo import clientinfo
import downloadutils import downloadutils
import librarysync import librarysync
@ -25,9 +28,11 @@ import embydb_functions as embydb
import kodidb_functions as kodidb import kodidb_functions as kodidb
import musicutils as musicutils import musicutils as musicutils
import api import api
from utils import Logging, settings language as lang, kodiSQL
def logMsg(msg, lvl=1): #################################################################################################
utils.logMsg("%s %s" % ("EMBY", "Contextmenu"), msg, lvl)
log = Logging('ContextMenu').log
#Kodi contextmenu item to configure the emby settings #Kodi contextmenu item to configure the emby settings
@ -47,14 +52,14 @@ if __name__ == '__main__':
if (not itemid or itemid == "-1") and xbmc.getInfoLabel("ListItem.Property(embyid)"): if (not itemid or itemid == "-1") and xbmc.getInfoLabel("ListItem.Property(embyid)"):
embyid = xbmc.getInfoLabel("ListItem.Property(embyid)") embyid = xbmc.getInfoLabel("ListItem.Property(embyid)")
else: else:
embyconn = utils.kodiSQL('emby') embyconn = kodiSQL('emby')
embycursor = embyconn.cursor() embycursor = embyconn.cursor()
emby_db = embydb.Embydb_Functions(embycursor) emby_db = embydb.Embydb_Functions(embycursor)
item = emby_db.getItem_byKodiId(itemid, itemtype) item = emby_db.getItem_byKodiId(itemid, itemtype)
embycursor.close() embycursor.close()
if item: embyid = item[0] if item: embyid = item[0]
logMsg("Contextmenu opened for embyid: %s - itemtype: %s" %(embyid,itemtype)) log("Contextmenu opened for embyid: %s - itemtype: %s" %(embyid,itemtype))
if embyid: if embyid:
item = emby.getItem(embyid) item = emby.getItem(embyid)
@ -66,45 +71,45 @@ if __name__ == '__main__':
options=[] options=[]
if likes == True: if likes == True:
#clear like for the item #clear like for the item
options.append(utils.language(30402)) options.append(lang(30402))
if likes == False or likes == None: if likes == False or likes == None:
#Like the item #Like the item
options.append(utils.language(30403)) options.append(lang(30403))
if likes == True or likes == None: if likes == True or likes == None:
#Dislike the item #Dislike the item
options.append(utils.language(30404)) options.append(lang(30404))
if favourite == False: if favourite == False:
#Add to emby favourites #Add to emby favourites
options.append(utils.language(30405)) options.append(lang(30405))
if favourite == True: if favourite == True:
#Remove from emby favourites #Remove from emby favourites
options.append(utils.language(30406)) options.append(lang(30406))
if itemtype == "song": if itemtype == "song":
#Set custom song rating #Set custom song rating
options.append(utils.language(30407)) options.append(lang(30407))
#delete item #delete item
options.append(utils.language(30409)) options.append(lang(30409))
#addon settings #addon settings
options.append(utils.language(30408)) options.append(lang(30408))
#display select dialog and process results #display select dialog and process results
header = utils.language(30401) header = lang(30401)
ret = xbmcgui.Dialog().select(header, options) ret = xbmcgui.Dialog().select(header, options)
if ret != -1: if ret != -1:
if options[ret] == utils.language(30402): if options[ret] == lang(30402):
emby.updateUserRating(embyid, deletelike=True) emby.updateUserRating(embyid, deletelike=True)
if options[ret] == utils.language(30403): if options[ret] == lang(30403):
emby.updateUserRating(embyid, like=True) emby.updateUserRating(embyid, like=True)
if options[ret] == utils.language(30404): if options[ret] == lang(30404):
emby.updateUserRating(embyid, like=False) emby.updateUserRating(embyid, like=False)
if options[ret] == utils.language(30405): if options[ret] == lang(30405):
emby.updateUserRating(embyid, favourite=True) emby.updateUserRating(embyid, favourite=True)
if options[ret] == utils.language(30406): if options[ret] == lang(30406):
emby.updateUserRating(embyid, favourite=False) emby.updateUserRating(embyid, favourite=False)
if options[ret] == utils.language(30407): if options[ret] == lang(30407):
kodiconn = utils.kodiSQL('music') kodiconn = kodiSQL('music')
kodicursor = kodiconn.cursor() kodicursor = kodiconn.cursor()
query = ' '.join(("SELECT rating", "FROM song", "WHERE idSong = ?" )) query = ' '.join(("SELECT rating", "FROM song", "WHERE idSong = ?" ))
kodicursor.execute(query, (itemid,)) kodicursor.execute(query, (itemid,))
@ -113,39 +118,39 @@ if __name__ == '__main__':
if newvalue: if newvalue:
newvalue = int(newvalue) newvalue = int(newvalue)
if newvalue > 5: newvalue = "5" if newvalue > 5: newvalue = "5"
if utils.settings('enableUpdateSongRating') == "true": if settings('enableUpdateSongRating') == "true":
musicutils.updateRatingToFile(newvalue, API.getFilePath()) musicutils.updateRatingToFile(newvalue, API.getFilePath())
if utils.settings('enableExportSongRating') == "true": if settings('enableExportSongRating') == "true":
like, favourite, deletelike = musicutils.getEmbyRatingFromKodiRating(newvalue) like, favourite, deletelike = musicutils.getEmbyRatingFromKodiRating(newvalue)
emby.updateUserRating(embyid, like, favourite, deletelike) emby.updateUserRating(embyid, like, favourite, deletelike)
query = ' '.join(( "UPDATE song","SET rating = ?", "WHERE idSong = ?" )) query = ' '.join(( "UPDATE song","SET rating = ?", "WHERE idSong = ?" ))
kodicursor.execute(query, (newvalue,itemid,)) kodicursor.execute(query, (newvalue,itemid,))
kodiconn.commit() kodiconn.commit()
if options[ret] == utils.language(30408): if options[ret] == lang(30408):
#Open addon settings #Open addon settings
xbmc.executebuiltin("Addon.OpenSettings(plugin.video.emby)") xbmc.executebuiltin("Addon.OpenSettings(plugin.video.emby)")
if options[ret] == utils.language(30409): if options[ret] == lang(30409):
#delete item from the server #delete item from the server
delete = True delete = True
if utils.settings('skipContextMenu') != "true": if settings('skipContextMenu') != "true":
resp = xbmcgui.Dialog().yesno( resp = xbmcgui.Dialog().yesno(
heading="Confirm delete", heading="Confirm delete",
line1=("Delete file from Emby Server? This will " line1=("Delete file from Emby Server? This will "
"also delete the file(s) from disk!")) "also delete the file(s) from disk!"))
if not resp: if not resp:
logMsg("User skipped deletion for: %s." % embyid, 1) log("User skipped deletion for: %s." % embyid, 1)
delete = False delete = False
if delete: if delete:
import downloadutils import downloadutils
doUtils = downloadutils.DownloadUtils() doUtils = downloadutils.DownloadUtils()
url = "{server}/emby/Items/%s?format=json" % embyid url = "{server}/emby/Items/%s?format=json" % embyid
logMsg("Deleting request: %s" % embyid, 0) log("Deleting request: %s" % embyid, 0)
doUtils.downloadUrl(url, action_type="DELETE") doUtils.downloadUrl(url, action_type="DELETE")
'''if utils.settings('skipContextMenu') != "true": '''if settings('skipContextMenu') != "true":
if xbmcgui.Dialog().yesno( if xbmcgui.Dialog().yesno(
heading="Confirm delete", heading="Confirm delete",
line1=("Delete file on Emby Server? This will " line1=("Delete file on Emby Server? This will "

View file

@ -24,10 +24,12 @@ import playlist
import playbackutils as pbutils import playbackutils as pbutils
import playutils import playutils
import api import api
from utils import Logging, window, settings
################################################################################################# #################################################################################################
log = Logging('Entrypoint').log
def doPlayback(itemid, dbid): def doPlayback(itemid, dbid):
@ -44,8 +46,8 @@ def resetAuth():
"Emby might lock your account if you fail to log in too many times. " "Emby might lock your account if you fail to log in too many times. "
"Proceed anyway?")) "Proceed anyway?"))
if resp == 1: if resp == 1:
utils.logMsg("EMBY", "Reset login attempts.", 1) log("EMBY", "Reset login attempts.", 1)
utils.window('emby_serverStatus', value="Auth") window('emby_serverStatus', value="Auth")
else: else:
xbmc.executebuiltin('Addon.OpenSettings(plugin.video.emby)') xbmc.executebuiltin('Addon.OpenSettings(plugin.video.emby)')
@ -59,15 +61,15 @@ def addDirectoryItem(label, path, folder=True):
def doMainListing(): def doMainListing():
xbmcplugin.setContent(int(sys.argv[1]), 'files') xbmcplugin.setContent(int(sys.argv[1]), 'files')
# Get emby nodes from the window props # Get emby nodes from the window props
embyprops = utils.window('Emby.nodes.total') embyprops = window('Emby.nodes.total')
if embyprops: if embyprops:
totalnodes = int(embyprops) totalnodes = int(embyprops)
for i in range(totalnodes): for i in range(totalnodes):
path = utils.window('Emby.nodes.%s.index' % i) path = window('Emby.nodes.%s.index' % i)
if not path: if not path:
path = utils.window('Emby.nodes.%s.content' % i) path = window('Emby.nodes.%s.content' % i)
label = utils.window('Emby.nodes.%s.title' % i) label = window('Emby.nodes.%s.title' % i)
node_type = utils.window('Emby.nodes.%s.type' % i) node_type = window('Emby.nodes.%s.type' % i)
#because we do not use seperate entrypoints for each content type, we need to figure out which items to show in each listing. #because we do not use seperate entrypoints for each content type, we need to figure out which items to show in each listing.
#for now we just only show picture nodes in the picture library video nodes in the video library and all nodes in any other window #for now we just only show picture nodes in the picture library video nodes in the video library and all nodes in any other window
if path and xbmc.getCondVisibility("Window.IsActive(Pictures)") and node_type == "photos": if path and xbmc.getCondVisibility("Window.IsActive(Pictures)") and node_type == "photos":
@ -101,17 +103,17 @@ def resetDeviceId():
dialog = xbmcgui.Dialog() dialog = xbmcgui.Dialog()
language = utils.language language = utils.language
deviceId_old = utils.window('emby_deviceId') deviceId_old = window('emby_deviceId')
try: try:
utils.window('emby_deviceId', clear=True) window('emby_deviceId', clear=True)
deviceId = clientinfo.ClientInfo().getDeviceId(reset=True) deviceId = clientinfo.ClientInfo().getDeviceId(reset=True)
except Exception as e: except Exception as e:
utils.logMsg("EMBY", "Failed to generate a new device Id: %s" % e, 1) log("EMBY", "Failed to generate a new device Id: %s" % e, 1)
dialog.ok( dialog.ok(
heading="Emby for Kodi", heading="Emby for Kodi",
line1=language(33032)) line1=language(33032))
else: else:
utils.logMsg("EMBY", "Successfully removed old deviceId: %s New deviceId: %s" log("EMBY", "Successfully removed old deviceId: %s New deviceId: %s"
% (deviceId_old, deviceId), 1) % (deviceId_old, deviceId), 1)
dialog.ok( dialog.ok(
heading="Emby for Kodi", heading="Emby for Kodi",
@ -139,7 +141,7 @@ def deleteItem():
elif xbmc.getCondVisibility('Container.Content(pictures)'): elif xbmc.getCondVisibility('Container.Content(pictures)'):
itemtype = "picture" itemtype = "picture"
else: else:
utils.logMsg("EMBY delete", "Unknown type, unable to proceed.", 1) log("EMBY delete", "Unknown type, unable to proceed.", 1)
return return
embyconn = utils.kodiSQL('emby') embyconn = utils.kodiSQL('emby')
@ -151,21 +153,21 @@ def deleteItem():
try: try:
embyid = item[0] embyid = item[0]
except TypeError: except TypeError:
utils.logMsg("EMBY delete", "Unknown embyId, unable to proceed.", 1) log("EMBY delete", "Unknown embyId, unable to proceed.", 1)
return return
if utils.settings('skipContextMenu') != "true": if settings('skipContextMenu') != "true":
resp = xbmcgui.Dialog().yesno( resp = xbmcgui.Dialog().yesno(
heading="Confirm delete", heading="Confirm delete",
line1=("Delete file from Emby Server? This will " line1=("Delete file from Emby Server? This will "
"also delete the file(s) from disk!")) "also delete the file(s) from disk!"))
if not resp: if not resp:
utils.logMsg("EMBY delete", "User skipped deletion for: %s." % embyid, 1) log("EMBY delete", "User skipped deletion for: %s." % embyid, 1)
return return
doUtils = downloadutils.DownloadUtils() doUtils = downloadutils.DownloadUtils()
url = "{server}/emby/Items/%s?format=json" % embyid url = "{server}/emby/Items/%s?format=json" % embyid
utils.logMsg("EMBY delete", "Deleting request: %s" % embyid, 0) log("EMBY delete", "Deleting request: %s" % embyid, 0)
doUtils.downloadUrl(url, action_type="DELETE") doUtils.downloadUrl(url, action_type="DELETE")
##### ADD ADDITIONAL USERS ##### ##### ADD ADDITIONAL USERS #####
@ -176,7 +178,7 @@ def addUser():
clientInfo = clientinfo.ClientInfo() clientInfo = clientinfo.ClientInfo()
deviceId = clientInfo.getDeviceId() deviceId = clientInfo.getDeviceId()
deviceName = clientInfo.getDeviceName() deviceName = clientInfo.getDeviceName()
userid = utils.window('emby_currUser') userid = window('emby_currUser')
dialog = xbmcgui.Dialog() dialog = xbmcgui.Dialog()
# Get session # Get session
@ -229,8 +231,8 @@ def addUser():
time=1000) time=1000)
# clear picture # clear picture
position = utils.window('EmbyAdditionalUserPosition.%s' % selected_userId) position = window('EmbyAdditionalUserPosition.%s' % selected_userId)
utils.window('EmbyAdditionalUserImage.%s' % position, clear=True) window('EmbyAdditionalUserImage.%s' % position, clear=True)
return return
else: else:
return return
@ -247,7 +249,7 @@ def addUser():
return return
# Subtract any additional users # Subtract any additional users
utils.logMsg("EMBY", "Displaying list of users: %s" % users) log("EMBY", "Displaying list of users: %s" % users)
resp = dialog.select("Add user to the session", users) resp = dialog.select("Add user to the session", users)
# post additional user # post additional user
if resp > -1: if resp > -1:
@ -262,7 +264,7 @@ def addUser():
time=1000) time=1000)
except: except:
utils.logMsg("EMBY", "Failed to add user to session.") log("EMBY", "Failed to add user to session.")
dialog.notification( dialog.notification(
heading="Error", heading="Error",
message="Unable to add/remove user from the session.", message="Unable to add/remove user from the session.",
@ -272,9 +274,9 @@ def addUser():
# always clear the individual items first # always clear the individual items first
totalNodes = 10 totalNodes = 10
for i in range(totalNodes): for i in range(totalNodes):
if not utils.window('EmbyAdditionalUserImage.%s' % i): if not window('EmbyAdditionalUserImage.%s' % i):
break break
utils.window('EmbyAdditionalUserImage.%s' % i, clear=True) window('EmbyAdditionalUserImage.%s' % i, clear=True)
url = "{server}/emby/Sessions?DeviceId=%s" % deviceId url = "{server}/emby/Sessions?DeviceId=%s" % deviceId
result = doUtils.downloadUrl(url) result = doUtils.downloadUrl(url)
@ -284,9 +286,9 @@ def addUser():
userid = additionaluser['UserId'] userid = additionaluser['UserId']
url = "{server}/emby/Users/%s?format=json" % userid url = "{server}/emby/Users/%s?format=json" % userid
result = doUtils.downloadUrl(url) result = doUtils.downloadUrl(url)
utils.window('EmbyAdditionalUserImage.%s' % count, window('EmbyAdditionalUserImage.%s' % count,
value=art.getUserArtwork(result['Id'], 'Primary')) value=art.getUserArtwork(result['Id'], 'Primary'))
utils.window('EmbyAdditionalUserPosition.%s' % userid, value=str(count)) window('EmbyAdditionalUserPosition.%s' % userid, value=str(count))
count +=1 count +=1
##### THEME MUSIC/VIDEOS ##### ##### THEME MUSIC/VIDEOS #####
@ -318,7 +320,7 @@ def getThemeMedia():
tvtunes = xbmcaddon.Addon(id="script.tvtunes") tvtunes = xbmcaddon.Addon(id="script.tvtunes")
tvtunes.setSetting('custom_path_enable', "true") tvtunes.setSetting('custom_path_enable', "true")
tvtunes.setSetting('custom_path', library) tvtunes.setSetting('custom_path', library)
utils.logMsg("EMBY", "TV Tunes custom path is enabled and set.", 1) log("EMBY", "TV Tunes custom path is enabled and set.", 1)
else: else:
# if it does not exist this will not work so warn user # if it does not exist this will not work so warn user
# often they need to edit the settings first for it to be created. # often they need to edit the settings first for it to be created.
@ -468,7 +470,7 @@ def refreshPlaylist():
sound=False) sound=False)
except Exception as e: except Exception as e:
utils.logMsg("EMBY", "Refresh playlists/nodes failed: %s" % e, 1) log("EMBY", "Refresh playlists/nodes failed: %s" % e, 1)
dialog.notification( dialog.notification(
heading="Emby for Kodi", heading="Emby for Kodi",
message="Emby playlists/nodes refresh failed", message="Emby playlists/nodes refresh failed",
@ -480,9 +482,9 @@ def refreshPlaylist():
def GetSubFolders(nodeindex): def GetSubFolders(nodeindex):
nodetypes = ["",".recent",".recentepisodes",".inprogress",".inprogressepisodes",".unwatched",".nextepisodes",".sets",".genres",".random",".recommended"] nodetypes = ["",".recent",".recentepisodes",".inprogress",".inprogressepisodes",".unwatched",".nextepisodes",".sets",".genres",".random",".recommended"]
for node in nodetypes: for node in nodetypes:
title = utils.window('Emby.nodes.%s%s.title' %(nodeindex,node)) title = window('Emby.nodes.%s%s.title' %(nodeindex,node))
if title: if title:
path = utils.window('Emby.nodes.%s%s.content' %(nodeindex,node)) path = window('Emby.nodes.%s%s.content' %(nodeindex,node))
addDirectoryItem(title, path) addDirectoryItem(title, path)
xbmcplugin.endOfDirectory(int(sys.argv[1])) xbmcplugin.endOfDirectory(int(sys.argv[1]))
@ -510,7 +512,7 @@ def BrowseContent(viewname, browse_type="", folderid=""):
break break
if viewname is not None: if viewname is not None:
utils.logMsg("BrowseContent","viewname: %s - type: %s - folderid: %s - filter: %s" %(viewname.decode('utf-8'), browse_type.decode('utf-8'), folderid.decode('utf-8'), filter_type.decode('utf-8'))) log("BrowseContent","viewname: %s - type: %s - folderid: %s - filter: %s" %(viewname.decode('utf-8'), browse_type.decode('utf-8'), folderid.decode('utf-8'), filter_type.decode('utf-8')))
#set the correct params for the content type #set the correct params for the content type
#only proceed if we have a folderid #only proceed if we have a folderid
if folderid: if folderid:
@ -795,7 +797,7 @@ def getNextUpEpisodes(tagname, limit):
pass pass
else: else:
for item in items: for item in items:
if utils.settings('ignoreSpecialsNextEpisodes') == "true": if settings('ignoreSpecialsNextEpisodes') == "true":
query = { query = {
'jsonrpc': "2.0", 'jsonrpc': "2.0",
@ -1043,7 +1045,7 @@ def getExtraFanArt(embyId,embyPath):
if embyId: if embyId:
#only proceed if we actually have a emby id #only proceed if we actually have a emby id
utils.logMsg("EMBY", "Requesting extrafanart for Id: %s" % embyId, 0) log("EMBY", "Requesting extrafanart for Id: %s" % embyId, 0)
# We need to store the images locally for this to work # We need to store the images locally for this to work
# because of the caching system in xbmc # because of the caching system in xbmc
@ -1072,7 +1074,7 @@ def getExtraFanArt(embyId,embyPath):
xbmcvfs.copy(backdrop, fanartFile) xbmcvfs.copy(backdrop, fanartFile)
count += 1 count += 1
else: else:
utils.logMsg("EMBY", "Found cached backdrop.", 2) log("EMBY", "Found cached backdrop.", 2)
# Use existing cached images # Use existing cached images
dirs, files = xbmcvfs.listdir(fanartDir) dirs, files = xbmcvfs.listdir(fanartDir)
for file in files: for file in files:
@ -1083,7 +1085,7 @@ def getExtraFanArt(embyId,embyPath):
url=fanartFile, url=fanartFile,
listitem=li) listitem=li)
except Exception as e: except Exception as e:
utils.logMsg("EMBY", "Error getting extrafanart: %s" % e, 0) log("EMBY", "Error getting extrafanart: %s" % e, 0)
# Always do endofdirectory to prevent errors in the logs # Always do endofdirectory to prevent errors in the logs
xbmcplugin.endOfDirectory(int(sys.argv[1])) xbmcplugin.endOfDirectory(int(sys.argv[1]))