Move websocket library to library sync

This allows the websocket to properly communicate, since it's not busy
doing incremental syncs anymore.
This commit is contained in:
angelblue05 2015-06-28 07:08:06 -05:00
parent 8fbe680b5e
commit e3412912ac
3 changed files with 123 additions and 58 deletions

View File

@ -36,13 +36,20 @@ WINDOW = xbmcgui.Window( 10000 )
class LibrarySync(threading.Thread): class LibrarySync(threading.Thread):
_shared_state = {}
KodiMonitor = KodiMonitor.Kodi_Monitor() KodiMonitor = KodiMonitor.Kodi_Monitor()
clientInfo = ClientInformation() clientInfo = ClientInformation()
addonName = clientInfo.getAddonName() addonName = clientInfo.getAddonName()
doIncrementalSync = False
updateItems = []
removeItems = []
def __init__(self, *args): def __init__(self, *args):
self.__dict__ = self._shared_state
threading.Thread.__init__(self, *args) threading.Thread.__init__(self, *args)
def logMsg(self, msg, lvl=1): def logMsg(self, msg, lvl=1):
@ -648,6 +655,103 @@ class LibrarySync(threading.Thread):
# tell any widgets to refresh because the content has changed # tell any widgets to refresh because the content has changed
WINDOW.setProperty("widgetreload", datetime.now().strftime('%Y-%m-%d %H:%M:%S')) WINDOW.setProperty("widgetreload", datetime.now().strftime('%Y-%m-%d %H:%M:%S'))
def removefromDB(self, itemList, deleteEmbyItem = False):
# Delete from Kodi before Emby
# To be able to get mediaType
doUtils = DownloadUtils()
video = []
music = []
itemIds = ','.join(itemList)
url = "{server}/mediabrowser/Users/{UserId}/Items?Ids=%s&format=json" % itemIds
result = doUtils.downloadUrl(url)
if result is "":
# Websocket feedback
self.logMsg("Item %s is removed." % itemIds)
return
for item in result[u'Items']:
# Sort by type for database deletion
itemId = item["Id"]
mediaType = item["MediaType"]
if "Video" in mediaType:
video.append(itemId)
elif "Audio" in mediaType:
music.append(itemId)
if len(video) > 0:
#Process video library
connection = utils.KodiSQL("video")
cursor = connection.cursor()
for item in video:
type = ReadKodiDB().getTypeByEmbyId(item, connection, cursor)
self.logMsg("Type: %s" % type)
self.logMsg("Message: Doing LibraryChanged: Items Removed: Calling deleteItemFromKodiLibrary: %s" % item, 0)
if "episode" in type:
# Get the TV Show Id for reference later
showId = ReadKodiDB().getShowIdByEmbyId(item, connection, cursor)
self.logMsg("ShowId: %s" % showId, 0)
WriteKodiVideoDB().deleteItemFromKodiLibrary(item, connection, cursor)
# Verification
if "episode" in type:
showTotalCount = ReadKodiDB().getShowTotalCount(showId, connection, cursor)
self.logMsg("ShowTotalCount: %s" % showTotalCount, 0)
# If there are no episodes left
if not showTotalCount:
# Delete show
embyId = ReadKodiDB().getEmbyIdByKodiId(showId, "tvshow", connection, cursor)
self.logMsg("Message: Doing LibraryChanged: Deleting show: %s" % embyId, 0)
WriteKodiVideoDB().deleteItemFromKodiLibrary(embyId, connection, cursor)
connection.commit()
cursor.close()
if len(music) > 0:
#Process music library
addon = xbmcaddon.Addon(id='plugin.video.emby')
if addon.getSetting("enableMusicSync") is "true":
connection = utils.KodiSQL("music")
cursor = connection.cursor()
for item in music:
self.logMsg("Message : Doing LibraryChanged : Items Removed : Calling deleteItemFromKodiLibrary (musiclibrary): " + item, 0)
WriteKodiMusicDB().deleteItemFromKodiLibrary(item, connection, cursor)
connection.commit()
cursor.close()
if deleteEmbyItem:
for item in itemList:
url = "{server}/mediabrowser/Items/%s" % item
self.logMsg('Deleting via URL: %s' % url)
doUtils.downloadUrl(url, type="DELETE")
xbmc.executebuiltin("Container.Refresh")
def remove_items(self, itemsRemoved):
self.removeItems.extend(itemsRemoved)
def update_items(self, itemsToUpdate):
# doing adds and updates
if(len(itemsToUpdate) > 0):
self.logMsg("Message : Doing LibraryChanged : Processing Added and Updated : " + str(itemsToUpdate), 0)
self.updateItems.extend(itemsToUpdate)
self.doIncrementalSync = True
def user_data_update(self, userDataList):
self.updateItems = []
for userData in userDataList:
itemId = userData.get("ItemId")
if(itemId != None):
self.updateItems.append(itemId)
if(len(self.updateItems) > 0):
self.logMsg("Message : Doing UserDataChanged : Processing Updated : " + str(self.updateItems), 0)
self.doIncrementalSync = True
def ShouldStop(self): def ShouldStop(self):
if(xbmc.abortRequested): if(xbmc.abortRequested):
@ -683,6 +787,19 @@ class LibrarySync(threading.Thread):
libSync = self.FullLibrarySync() libSync = self.FullLibrarySync()
utils.logMsg("Doing_Db_Sync Post Resume: syncDatabase (Finished) " + str(libSync),0) utils.logMsg("Doing_Db_Sync Post Resume: syncDatabase (Finished) " + str(libSync),0)
if self.doIncrementalSync:
# Add or update item to Kodi library
listItems = self.updateItems
self.updateItems = []
self.doIncrementalSync = False
self.IncrementalSync(listItems)
if len(self.removeItems) > 0:
# Remove item from Kodi library
listItems = self.removeItems
self.removeItems = []
self.removefromDB(listItems)
if self.KodiMonitor.waitForAbort(1): if self.KodiMonitor.waitForAbort(1):
# Abort was requested while waiting. We should exit # Abort was requested while waiting. We should exit
break break

View File

@ -106,11 +106,9 @@ class Player( xbmc.Player ):
if percentComplete > .80 and data.get("Type") == "Episode" and addonSettings.getSetting("offerDelete")=="true": if percentComplete > .80 and data.get("Type") == "Episode" and addonSettings.getSetting("offerDelete")=="true":
return_value = xbmcgui.Dialog().yesno("Offer Delete", "Delete\n" + data.get("currentfile").split("/")[-1] + "\non Emby Server? ") return_value = xbmcgui.Dialog().yesno("Offer Delete", "Delete\n" + data.get("currentfile").split("/")[-1] + "\non Emby Server? ")
if return_value: if return_value:
url='{server}/mediabrowser/Items/' + item_id # Delete Kodi entry before Emby
xbmc.log('Deleting via URL: ' + url) listItem = [item_id]
self.doUtils.downloadUrl(url, type="DELETE") LibrarySync().removefromDB(listItem, True)
xbmc.sleep (15000)
xbmc.executebuiltin( "Container.Refresh" )
#if(refresh_id != None): #if(refresh_id != None):
#report updates playcount and resume status to Kodi and MB3 #report updates playcount and resume status to Kodi and MB3
#librarySync.updatePlayCount(item_id) #librarySync.updatePlayCount(item_id)

View File

@ -156,7 +156,7 @@ class WebSocketThread(threading.Thread):
userDataList = data.get("UserDataList") userDataList = data.get("UserDataList")
self.logMsg("Message : Doing UserDataChanged : UserDataList : " + str(userDataList), 0) self.logMsg("Message : Doing UserDataChanged : UserDataList : " + str(userDataList), 0)
if(userDataList != None): if(userDataList != None):
self.user_data_update(userDataList) LibrarySync().user_data_update(userDataList)
elif(messageType != None and messageType == "LibraryChanged"): elif(messageType != None and messageType == "LibraryChanged"):
foldersAddedTo = data.get("FoldersAddedTo") foldersAddedTo = data.get("FoldersAddedTo")
@ -171,8 +171,8 @@ class WebSocketThread(threading.Thread):
self.logMsg("Message : WebSocket LibraryChanged : Items Updated : " + str(itemsUpdated), 0) self.logMsg("Message : WebSocket LibraryChanged : Items Updated : " + str(itemsUpdated), 0)
self.logMsg("Message : WebSocket LibraryChanged : Items Removed : " + str(itemsRemoved), 0) self.logMsg("Message : WebSocket LibraryChanged : Items Removed : " + str(itemsRemoved), 0)
self.remove_items(itemsRemoved) LibrarySync().remove_items(itemsRemoved)
self.update_items(itemsToUpdate) LibrarySync().update_items(itemsToUpdate)
elif messageType == "GeneralCommand": elif messageType == "GeneralCommand":
@ -249,56 +249,6 @@ class WebSocketThread(threading.Thread):
else: else:
self.logMsg("Unknown command.", 1) self.logMsg("Unknown command.", 1)
def remove_items(self, itemsRemoved):
#Process video library
connection = utils.KodiSQL("video")
cursor = connection.cursor()
for item in itemsRemoved:
type=ReadKodiDB().getTypeByEmbyId(item, connection, cursor)
self.logMsg("Type: " + str(type))
self.logMsg("Message : Doing LibraryChanged : Items Removed : Calling deleteItemFromKodiLibrary: " + item, 0)
if type == "episode":
showId=ReadKodiDB().getShowIdByEmbyId(item, connection, cursor) # Get the TV Show ID
self.logMsg("ShowID: " + str(showId),0)
WriteKodiVideoDB().deleteItemFromKodiLibrary(item, connection, cursor)
if type == "episode":
showTotalCount = ReadKodiDB().getShowTotalCount(showId, connection, cursor) # Check if there are no episodes left
self.logMsg("ShowTotalCount: " + str(showTotalCount),0)
if showTotalCount == 0 or showTotalCount == None: # Delete show if no episodes are left
embyId=ReadKodiDB().getEmbyIdByKodiId(showId, "tvshow", connection, cursor)
self.logMsg("Message : Doing LibraryChanged : Deleting show:" + embyId, 0)
WriteKodiVideoDB().deleteItemFromKodiLibrary(embyId, connection, cursor)
connection.commit()
cursor.close()
#Process music library
addon = xbmcaddon.Addon(id='plugin.video.emby')
if addon.getSetting("enableMusicSync") == "true":
connection = utils.KodiSQL("music")
cursor = connection.cursor()
for item in itemsRemoved:
self.logMsg("Message : Doing LibraryChanged : Items Removed : Calling deleteItemFromKodiLibrary (musiclibrary): " + item, 0)
WriteKodiMusicDB().deleteItemFromKodiLibrary(item, connection, cursor)
connection.commit()
cursor.close()
def update_items(self, itemsToUpdate):
# doing adds and updates
if(len(itemsToUpdate) > 0):
self.logMsg("Message : Doing LibraryChanged : Processing Added and Updated : " + str(itemsToUpdate), 0)
LibrarySync().IncrementalSync(itemsToUpdate)
def user_data_update(self, userDataList):
itemsToUpdate = list()
for userData in userDataList:
itemId = userData.get("ItemId")
if(itemId != None):
itemsToUpdate.append(itemId)
if(len(itemsToUpdate) > 0):
self.logMsg("Message : Doing UserDataChanged : Processing Updated : " + str(itemsToUpdate), 0)
LibrarySync().IncrementalSync(itemsToUpdate)
def on_error(self, ws, error): def on_error(self, ws, error):
if "10061" in str(error): if "10061" in str(error):
# Server is offline # Server is offline