first work on the transition to use kodi db for all actions

This commit is contained in:
Marcel van der Veldt 2015-05-01 13:30:21 +02:00
parent fdff2cefb7
commit 8a990ba217
6 changed files with 464 additions and 1310 deletions

View file

@ -12,6 +12,7 @@ import inspect
import threading
import urllib
from datetime import datetime, timedelta, time
from itertools import chain
import urllib2
import os
@ -47,22 +48,20 @@ class LibrarySync():
completed = True
connection = utils.KodiSQL()
cursor = connection.cursor()
#TEMP --> add new columns
try:
cursor.execute("alter table movie ADD COLUMN 'embyId' TEXT")
cursor.execute("alter table tvshow ADD COLUMN 'embyId' TEXT")
cursor.execute("alter table episode ADD COLUMN 'embyId' TEXT")
cursor.execute("alter table musicvideo ADD COLUMN 'embyId' TEXT")
connection.commit()
except: pass
# sync movies
if(syncInstallRunDone == False): # on first install run do a full sync with model progress dialog
completed = completed and self.TvShowsSync(connection, cursor,True, True)
completed = completed and self.MoviesSync(connection, cursor,True, True)
completed = completed and self.MusicVideosSync(True, True,connection , cursor)
elif(startupDone == False): # on first run after startup do a inc then a full sync
self.TvShowsSync(connection, cursor,False, False)
self.MoviesSync(connection, cursor,False, False)
self.MusicVideosSync(False, False, connection,cursor)
self.TvShowsSync(connection, cursor,True, False)
self.MoviesSync(connection, cursor,True, False)
self.MusicVideosSync(True, False,connection,cursor)
else: # on scheduled sync do a full sync
self.TvShowsSync(connection, cursor,True, False)
self.MoviesSync(connection, cursor,True, False)
self.MusicVideosSync(True, False,connection,cursor)
self.MoviesSync(connection,cursor,True)
#sync Tvshows and episodes
self.TvShowsSync(connection,cursor,True)
# set the install done setting
if(syncInstallRunDone == False and completed):
@ -79,539 +78,144 @@ class LibrarySync():
return True
def MoviesSync(self,connection, cursor, fullsync, installFirstRun,itemList = []):
def MoviesSync(self,connection,cursor,installFirstRun,itemList = []):
pDialog = xbmcgui.DialogProgressBG()
pDialog.create('Sync DB', 'Sync Movies')
views = ReadEmbyDB().getCollections("movies")
allKodiMovieIds = list()
allEmbyMovieIds = list()
for view in views:
allMB3Movies = ReadEmbyDB().getMovies(view.get('id'))
allKodiMovies = ReadKodiDB().getKodiMovies(connection, cursor)
#### PROCESS ADDS AND UPDATES ###
for item in allMB3Movies:
if not item.get('IsFolder'):
allEmbyMovieIds.append(item["Id"])
kodiMovie = None
for kodimovie in allKodiMovies:
allKodiMovieIds.append(kodimovie[1])
if kodimovie[1] == item["Id"]:
kodiMovie = kodimovie
if kodiMovie == None:
allKodiMovieIds.append(item["Id"])
WriteKodiDB().addOrUpdateMovieToKodiLibrary(item["Id"],connection, cursor, view.get('title'))
else:
# TODO --> compare with eTag
if kodiMovie[2] != item["Name"] or item["Id"] in itemList:
WriteKodiDB().addOrUpdateMovieToKodiLibrary(item["Id"],connection, cursor, view.get('title'))
#### PROCESS DELETES #####
allEmbyMovieIds = set(allEmbyMovieIds)
for kodiId in allKodiMovieIds:
if not kodiId in allEmbyMovieIds:
WINDOW.setProperty(kodiId,"deleted")
WriteKodiDB().deleteMovieFromKodiLibrary(kodiId, connection, cursor)
if(pDialog != None):
pDialog.close()
def TvShowsSync(self,connection,cursor,installFirstRun,itemList = []):
pDialog = xbmcgui.DialogProgressBG()
pDialog.create('Sync DB', 'Sync TV Shows')
views = ReadEmbyDB().getCollections("tvshows")
allKodiTvShowIds = list()
allEmbyTvShowIds = list()
for view in views:
allEmbyTvShows = ReadEmbyDB().getTvShows(view.get('id'))
allKodiTvShows = ReadKodiDB().getKodiTvShows(connection, cursor)
#### TVSHOW: PROCESS ADDS AND UPDATES ###
for item in allEmbyTvShows:
if item.get('IsFolder') and item.get('RecursiveItemCount') != 0:
allEmbyTvShowIds.append(item["Id"])
#build a list with all Id's and get the existing entry (if exists) in Kodi DB
kodiShow = None
for kodishow in allKodiTvShows:
allKodiTvShowIds.append(kodishow[1])
if kodishow[1] == item["Id"]:
kodiShow = kodishow
if kodiShow == None:
# Tv show doesn't exist in Kodi yet so proceed and add it
allKodiTvShowIds.append(item["Id"])
kodiId = WriteKodiDB().addOrUpdateTvShowToKodiLibrary(item["Id"],connection, cursor, view.get('title'))
else:
kodiId = kodishow[0]
# If there are changes to the item, perform a full sync of the item
if kodiShow[2] != item["Name"] or item["Id"] in itemList:
WriteKodiDB().addOrUpdateTvShowToKodiLibrary(item["Id"],connection, cursor, view.get('title'))
#### PROCESS EPISODES ######
self.EpisodesSync(connection,cursor,installFirstRun, item["Id"], kodiId, itemList)
#### TVSHOW: PROCESS DELETES #####
allEmbyTvShowIds = set(allEmbyTvShowIds)
for kodiId in allKodiTvShowIds:
if not kodiId in allEmbyTvShowIds:
WINDOW.setProperty(kodiId,"deleted")
WriteKodiDB().deleteTvShowFromKodiLibrary(kodiId, connection, cursor)
if(pDialog != None):
pDialog.close()
def EpisodesSync(self,connection,cursor,installFirstRun, embyShowId, kodiShowId, itemList = []):
WINDOW = xbmcgui.Window( 10000 )
pDialog = None
startedSync = datetime.today()
try:
addon = xbmcaddon.Addon(id='plugin.video.emby')
dbSyncIndication = addon.getSetting("dbSyncIndication")
allKodiEpisodeIds = list()
allEmbyEpisodeIds = list()
if(installFirstRun or dbSyncIndication == "Dialog Progress"):
pDialog = xbmcgui.DialogProgress()
elif(dbSyncIndication == "BG Progress"):
pDialog = xbmcgui.DialogProgressBG()
allEmbyEpisodes = ReadEmbyDB().getEpisodes(embyShowId)
allKodiEpisodes = ReadKodiDB().getKodiEpisodes(connection, cursor, kodiShowId)
if(pDialog != None):
pDialog.create('Sync DB', 'Sync DB')
#### EPISODES: PROCESS ADDS AND UPDATES ###
for item in allEmbyEpisodes:
totalItemsAdded = 0
totalItemsUpdated = 0
totalItemsDeleted = 0
allEmbyEpisodeIds.append(item["Id"])
allEmbyMovieIds = list()
#build a list with all Id's and get the existing entry (if exists) in Kodi DB
kodiEpisode = None
for kodiepisode in allKodiEpisodes:
allKodiEpisodeIds.append(kodiepisode[1])
if kodiepisode[1] == item["Id"]:
kodiEpisode = kodiepisode
views = ReadEmbyDB().getCollections("movies")
viewCount = len(views)
viewCurrent = 1
progressTitle = ""
if kodiEpisode == None:
# Episode doesn't exist in Kodi yet so proceed and add it
allKodiEpisodeIds.append(item["Id"])
WriteKodiDB().addOrUpdateEpisodeToKodiLibrary(item["Id"], kodiShowId, connection, cursor)
else:
# If there are changes to the item, perform a full sync of the item
if kodiEpisode[2] != item["Name"] or item["Id"] in itemList:
WriteKodiDB().addOrUpdateTvShowToKodiLibrary(item["Id"], kodiShowId, connection, cursor)
for view in views:
#### EPISODES: PROCESS DELETES #####
allEmbyEpisodeIds = set(allEmbyEpisodeIds)
print allEmbyEpisodeIds
for kodiId in allKodiEpisodeIds:
if not kodiId in allEmbyEpisodeIds:
WINDOW.setProperty(kodiId,"deleted")
print "deleting ???-->" + kodiId
#WriteKodiDB().deleteEpisodeFromKodiLibrary(kodiId, connection, cursor)
#process new movies
allMB3Movies = ReadEmbyDB().getMovies(id = view.get('id'), fullinfo=True, fullSync = fullsync, itemList = itemList)
allKodiIds = set(ReadKodiDB().getKodiMoviesIds(True))
if(self.ShouldStop(pDialog)):
return False
if(allMB3Movies == None):
return False
if(pDialog != None):
progressTitle = "Sync DB : Processing " + view.get('title') + " " + str(viewCurrent) + " of " + str(viewCount)
pDialog.update(0, progressTitle)
total = len(allMB3Movies) + 1
count = 1
for item in allMB3Movies:
if not item.get('IsFolder'):
allEmbyMovieIds.append(item["Id"])
item['Tag'] = []
item['Tag'].append(view.get('title'))
if item["Id"] not in allKodiIds:
WriteKodiDB().addMovieToKodiLibrary(item,connection, cursor)
totalItemsAdded += 1
if(self.ShouldStop(pDialog)):
return False
# update progress bar
if(pDialog != None):
percentage = int(((float(count) / float(total)) * 100))
pDialog.update(percentage, progressTitle, "Adding Movie: " + str(count))
count += 1
if(self.ShouldStop(pDialog)):
return False
if(pDialog != None):
progressTitle = "Sync DB : Processing " + view.get('title') + " " + str(viewCurrent) + " of " + str(viewCount)
pDialog.update(0, progressTitle, "")
total = len(allMB3Movies) + 1
count = 1
#process updates
allKodiMovies = ReadKodiDB().getKodiMovies(True)
for item in allMB3Movies:
if not item.get('IsFolder'):
item['Tag'] = []
item['Tag'].append(view.get('title'))
if allKodiMovies != None:
kodimovie = allKodiMovies.get(item["Id"], None)
else:
kodimovie = None
userData = API().getUserData(item)
if(kodimovie != None):
updated = WriteKodiDB().updateMovieToKodiLibrary_Batched(item, kodimovie, connection, cursor)
if(updated):
totalItemsUpdated += 1
if(self.ShouldStop(pDialog)):
return False
# update progress bar
if(pDialog != None):
percentage = int(((float(count) / float(total)) * 100))
pDialog.update(percentage, progressTitle, "Updating Movie: " + str(count))
count += 1
viewCurrent += 1
# process box sets - TODO cope with movies removed from a set
if fullsync:
if(pDialog != None):
progressTitle = "Sync DB : BoxSets"
pDialog.update(0, progressTitle, "Retrieving Boxset List")
utils.logMsg("Sync Movies", "BoxSet Sync Started", 1)
boxsets = ReadEmbyDB().getBoxSets()
if(pDialog != None):
total = len(boxsets) + 1
count = 1
for boxset in boxsets:
if(pDialog != None):
percentage = int(((float(count) / float(total)) * 100))
pDialog.update(percentage, progressTitle, "Updating BoxSet: " + str(count) + " of " + str(total))
count += 1
if(self.ShouldStop(pDialog)):
return False
boxsetMovies = ReadEmbyDB().getMoviesInBoxSet(boxset["Id"])
WriteKodiDB().addBoxsetToKodiLibrary(boxset,connection, cursor)
for boxsetMovie in boxsetMovies:
if(self.ShouldStop(pDialog)):
return False
WriteKodiDB().updateBoxsetToKodiLibrary(boxsetMovie,boxset)
utils.logMsg("Sync Movies", "BoxSet Sync Finished", 1)
if(pDialog != None):
progressTitle = "Removing Deleted Items"
pDialog.update(0, progressTitle, "")
if(self.ShouldStop(pDialog)):
return False
# process any deletes only at fullsync
if fullsync:
allKodiIds = ReadKodiDB().getKodiMoviesIds(True)
allEmbyMovieIds = set(allEmbyMovieIds)
for kodiId in allKodiIds:
if not kodiId in allEmbyMovieIds:
WINDOW.setProperty(kodiId,"deleted")
WriteKodiDB().deleteMovieFromKodiLibrary(kodiId)
totalItemsDeleted += 1
if(self.ShouldStop(pDialog)):
return False
# display notification if set up
notificationString = ""
if(totalItemsAdded > 0):
notificationString += "Added:" + str(totalItemsAdded) + " "
if(totalItemsUpdated > 0):
notificationString += "Updated:" + str(totalItemsUpdated) + " "
if(totalItemsDeleted > 0):
notificationString += "Deleted:" + str(totalItemsDeleted) + " "
timeTaken = datetime.today() - startedSync
timeTakenString = str(int(timeTaken.seconds / 60)) + ":" + str(timeTaken.seconds % 60)
utils.logMsg("Sync Movies", "Finished " + timeTakenString + " " + notificationString, 0)
if(dbSyncIndication == "Notify OnChange" and notificationString != ""):
notificationString = "(" + timeTakenString + ") " + notificationString
xbmc.executebuiltin("XBMC.Notification(Movie Sync: " + notificationString + ",)")
elif(dbSyncIndication == "Notify OnFinish"):
if(notificationString == ""):
notificationString = "Done"
notificationString = "(" + timeTakenString + ") " + notificationString
xbmc.executebuiltin("XBMC.Notification(Movie Sync: " + notificationString + ",)")
finally:
if(pDialog != None):
pDialog.close()
return True
def TvShowsSync(self, connection, cursor ,fullsync, installFirstRun, itemList = []):
addon = xbmcaddon.Addon(id='plugin.video.emby')
WINDOW = xbmcgui.Window( 10000 )
pDialog = None
startedSync = datetime.today()
try:
dbSyncIndication = addon.getSetting("dbSyncIndication")
if(installFirstRun or dbSyncIndication == "Dialog Progress"):
pDialog = xbmcgui.DialogProgress()
elif(dbSyncIndication == "BG Progress"):
pDialog = xbmcgui.DialogProgressBG()
if(pDialog != None):
pDialog.create('Sync DB', 'Sync DB')
totalItemsAdded = 0
totalItemsUpdated = 0
totalItemsDeleted = 0
allTVShows = list()
allMB3EpisodeIds = list() #for use with deletions
allKodiEpisodeIds = [] # for use with deletions
views = ReadEmbyDB().getCollections("tvshows")
viewCount = len(views)
viewCurrent = 1
progressTitle = ""
for view in views:
progressTitle = "Sync DB : Processing " + view.get('title') + " " + str(viewCurrent) + " of " + str(viewCount)
# incremental sync --> new episodes only
if fullsync == False:
latestMBEpisodes = ReadEmbyDB().getLatestEpisodes(fullinfo = True, itemList = itemList)
utils.logMsg("Sync TV", "Inc Sync Started on : " + str(len(latestMBEpisodes)) + " : " + str(itemList), 1)
if latestMBEpisodes != None:
allKodiTvShowsIds = set(ReadKodiDB().getKodiTvShowsIds(True))
# get included TV Shows
showList = []
for episode in latestMBEpisodes:
if(episode["SeriesId"] not in showList):
showList.append(episode["SeriesId"])
utils.logMsg("Incremental TV Sync", "Included TV Show List : " + str(showList), 0)
if(pDialog != None):
pDialog.update(0, progressTitle)
total = len(showList) + 1
count = 1
# process included TV Shows
for showID in showList:
embyTvShow = ReadEmbyDB().getFullItem(showID)
if(showID not in allKodiTvShowsIds):
utils.logMsg("Incremental TV Sync", "Adding TV Show : " + embyTvShow.get("Name"), 1)
WriteKodiDB().addTVShowToKodiLibrary(embyTvShow, connection, cursor)
kodiTvShow = ReadKodiDB().getKodiTVShow(showID)
utils.logMsg("Incremental TV Sync", "Updating TV Show : " + embyTvShow.get("Name"), 1)
WriteKodiDB().updateTVShowToKodiLibrary(embyTvShow, kodiTvShow, connection, cursor)
# update progress bar
if(pDialog != None):
percentage = int(((float(count) / float(total)) * 100))
pDialog.update(percentage, progressTitle, "Processing TV Shows : " + str(count))
count += 1
if(pDialog != None):
pDialog.update(0, progressTitle)
total = len(latestMBEpisodes) + 1
count = 1
# process new episodes
for episode in latestMBEpisodes:
if(self.ShouldStop(pDialog)):
return False
WriteKodiDB().addEpisodeToKodiLibrary(episode, connection, cursor)
progressAction = "Adding"
totalItemsAdded += 1
# update progress bar
if(pDialog != None):
percentage = int(((float(count) / float(total)) * 100))
pDialog.update(percentage, progressTitle, progressAction + " Episode: " + str(count))
count += 1
#process updates
if(pDialog != None):
progressTitle = "Sync DB : Processing Episodes"
pDialog.update(0, progressTitle)
total = len(latestMBEpisodes) + 1
count = 1
for episode in latestMBEpisodes:
if(self.ShouldStop(pDialog)):
return False
allKodiTVShows = ReadKodiDB().getKodiTvShows(False)
kodishow = allKodiTVShows.get(episode["SeriesId"],None)
kodiEpisodes = ReadKodiDB().getKodiEpisodes(kodishow["tvshowid"],True,True)
if(self.ShouldStop(pDialog)):
return False
userData = API().getUserData(episode)
if kodiEpisodes != None:
KodiItem = kodiEpisodes.get(episode.get("Id"), None)
if(KodiItem != None):
WriteKodiDB().updateEpisodeToKodiLibrary(episode, KodiItem, connection, cursor)
if(self.ShouldStop(pDialog)):
return False
# update progress bar
if(pDialog != None):
percentage = int(((float(count) / float(total)) * 100))
pDialog.update(percentage, progressTitle, "Updating Episode: " + str(count))
count += 1
# full sync --> Tv shows and Episodes
if fullsync:
viewTVShows = list()
tvShowData = ReadEmbyDB().getTVShows(id = view.get('id') , fullinfo = True, fullSync = True)
allKodiIds = set(ReadKodiDB().getKodiTvShowsIds(True))
if(self.ShouldStop(pDialog)):
return False
if (tvShowData == None):
return False
if(pDialog != None):
progressTitle = "Sync DB : Processing TV Shows"
pDialog.update(0, progressTitle)
total = len(tvShowData) + 1
count = 1
# add TV Shows
for item in tvShowData:
if item.get('IsFolder') and item.get('RecursiveItemCount') != 0:
allTVShows.append(item["Id"])
viewTVShows.append(item["Id"])
item['Tag'] = []
item['Tag'].append(view.get('title'))
progMessage = "Processing"
if item["Id"] not in allKodiIds:
WriteKodiDB().addTVShowToKodiLibrary(item,connection, cursor)
totalItemsAdded += 1
if(self.ShouldStop(pDialog)):
return False
# update progress bar
if(pDialog != None):
percentage = int(((float(count) / float(total)) * 100))
pDialog.update(percentage, progressTitle, "Adding Tv Show: " + str(count))
count += 1
if(pDialog != None):
progressTitle = "Sync DB : Processing TV Shows"
pDialog.update(0, progressTitle, "")
total = len(viewTVShows) + 1
count = 1
# update TV Shows
allKodiTVShows = ReadKodiDB().getKodiTvShows(True)
for item in tvShowData:
if item.get('IsFolder'):
item['Tag'] = []
item['Tag'].append(view.get('title'))
if allKodiTVShows != None:
kodishow = allKodiTVShows.get(item["Id"],None)
else:
kodishow = None
if(kodishow != None):
updated = WriteKodiDB().updateTVShowToKodiLibrary(item,kodishow,connection, cursor)
if(updated):
totalItemsUpdated += 1
if(self.ShouldStop(pDialog)):
return False
# update progress bar
if(pDialog != None):
percentage = int(((float(count) / float(total)) * 100))
pDialog.update(percentage, progressTitle, "Updating Tv Show: " + str(count))
count += 1
# do episode adds
allEpisodes = list()
showTotal = len(viewTVShows)
showCurrent = 1
for tvshow in viewTVShows:
episodeData = ReadEmbyDB().getEpisodes(tvshow,True)
if episodeData != None:
if(self.ShouldStop(pDialog)):
return False
if(pDialog != None):
progressTitle = "Sync DB : Processing Tv Show " + str(showCurrent) + " of " + str(showTotal)
pDialog.update(0, progressTitle)
total = len(episodeData) + 1
count = 0
for item in episodeData:
if(self.ShouldStop(pDialog)):
return False
progressAction = "Adding"
WriteKodiDB().addEpisodeToKodiLibrary(item, connection, cursor)
# update progress bar
if(pDialog != None):
percentage = int(((float(count) / float(total)) * 100))
pDialog.update(percentage, progressTitle, progressAction + " Episode: " + str(count))
count += 1
showCurrent += 1
# do episode updates
showCurrent = 1
for tvshow in viewTVShows:
episodeData = ReadEmbyDB().getEpisodes(tvshow,True)
kodiEpisodes = None
allKodiTVShows = ReadKodiDB().getKodiTvShows(False)
if allKodiTVShows != None:
kodishow = allKodiTVShows.get(tvshow,None)
if kodishow != None:
kodiEpisodes = ReadKodiDB().getKodiEpisodes(kodishow["tvshowid"],True,True)
if(self.ShouldStop(pDialog)):
return False
if(pDialog != None):
progressTitle = "Sync DB : Processing Tv Show " + str(showCurrent) + " of " + str(showTotal)
pDialog.update(0, progressTitle)
total = len(episodeData) + 1
count = 0
#we have to compare the lists somehow
for item in episodeData:
#add episodeId to the list of all episodes for use later on the deletes
allMB3EpisodeIds.append(item["Id"])
matchFound = False
userData = API().getUserData(item)
if kodiEpisodes != None:
KodiItem = kodiEpisodes.get(item.get("Id"), None)
if(KodiItem != None):
updated = WriteKodiDB().updateEpisodeToKodiLibrary(item, KodiItem, connection, cursor)
if(updated):
totalItemsUpdated += 1
if(self.ShouldStop(pDialog)):
return False
# update progress bar
if(pDialog != None):
percentage = int(((float(count) / float(total)) * 100))
pDialog.update(percentage, progressTitle, "Updating Episode: " + str(count))
count += 1
#add all kodi episodes to a list with episodes for use later on to delete episodes
#the mediabrowser ID is set as uniqueID in the NFO... for some reason this has key 'unknown' in the json response
if kodishow != None:
show = ReadKodiDB().getKodiEpisodes(kodishow["tvshowid"],False,False)
if show != None:
for episode in show:
dict = {'episodeid': str(episode["uniqueid"]["unknown"]),'tvshowid': tvshow}
allKodiEpisodeIds.append(dict)
showCurrent += 1
if(pDialog != None):
progressTitle = "Removing Deleted Items"
pDialog.update(0, progressTitle)
if(self.ShouldStop(pDialog)):
return False
# DELETES -- EPISODES
# process any deletes only at fullsync
allMB3EpisodeIdsSet = set(allMB3EpisodeIds)
for episode in allKodiEpisodeIds:
if episode.get('episodeid') not in allMB3EpisodeIdsSet:
WINDOW.setProperty("embyid" + str(episode.get('episodeid')),"deleted")
WriteKodiDB().deleteEpisodeFromKodiLibrary(episode.get('episodeid'),episode.get('tvshowid'))
totalItemsDeleted += 1
# DELETES -- TV SHOWS
if fullsync:
allKodiShows = ReadKodiDB().getKodiTvShowsIds(True)
allMB3TVShows = set(allTVShows)
for show in allKodiShows:
if not show in allMB3TVShows:
WriteKodiDB().deleteTVShowFromKodiLibrary(show)
totalItemsDeleted += 1
if(self.ShouldStop(pDialog)):
return False
# display notification if set up
notificationString = ""
if(totalItemsAdded > 0):
notificationString += "Added:" + str(totalItemsAdded) + " "
if(totalItemsUpdated > 0):
notificationString += "Updated:" + str(totalItemsUpdated) + " "
if(totalItemsDeleted > 0):
notificationString += "Deleted:" + str(totalItemsDeleted) + " "
timeTaken = datetime.today() - startedSync
timeTakenString = str(int(timeTaken.seconds / 60)) + ":" + str(timeTaken.seconds % 60)
utils.logMsg("Sync Episodes", "Finished " + timeTakenString + " " + notificationString, 0)
if(dbSyncIndication == "Notify OnChange" and notificationString != ""):
notificationString = "(" + timeTakenString + ") " + notificationString
xbmc.executebuiltin("XBMC.Notification(Episode Sync: " + notificationString + ",)")
elif(dbSyncIndication == "Notify OnFinish"):
if(notificationString == ""):
notificationString = "Done"
notificationString = "(" + timeTakenString + ") " + notificationString
xbmc.executebuiltin("XBMC.Notification(Episode Sync: " + notificationString + ",)")
finally:
if(pDialog != None):
pDialog.close()
return True
def MusicVideosSync(self, fullsync, installFirstRun,connection, cursor):

View file

@ -6,30 +6,22 @@ import xbmc
import xbmcgui
import xbmcaddon
from DownloadUtils import DownloadUtils
addon = xbmcaddon.Addon(id='plugin.video.emby')
class ReadEmbyDB():
def getMovies(self, id, fullinfo = False, fullSync = True, itemList = []):
def getMovies(self, id):
result = None
doUtils = DownloadUtils()
if fullSync:
sortstring = "&SortBy=SortName"
else:
if(len(itemList) > 0): # if we want a certain list specify it
#sortstring = "&Ids=" + ",".join(itemList)
sortstring = "" # work around for now until ParetnId and Id work together
else: # just get the last 20 created items
sortstring = "&Limit=20&SortBy=DateCreated"
if fullinfo:
url = "{server}/mediabrowser/Users/{UserId}/items?ParentId=%s%s&Fields=Path,Genres,SortName,Studios,Writer,ProductionYear,Taglines,CommunityRating,OfficialRating,CumulativeRunTimeTicks,Metascore,AirTime,DateCreated,MediaStreams,People,Overview&Recursive=true&SortOrder=Descending&IncludeItemTypes=Movie&CollapseBoxSetItems=false&format=json&ImageTypeLimit=1" % (id, sortstring)
else:
url = "{server}/mediabrowser/Users/{UserId}/items?ParentId=%s%s&Fields=CumulativeRunTimeTicks&Recursive=true&SortOrder=Descending&IncludeItemTypes=Movie&CollapseBoxSetItems=false&format=json&ImageTypeLimit=1" % (id, sortstring)
#only get basic info for our sync-compares
sortstring = "&SortBy=SortName"
url = "{server}/mediabrowser/Users/{UserId}/items?ParentId=%s%s&Fields=CumulativeRunTimeTicks&Recursive=true&SortOrder=Descending&IncludeItemTypes=Movie&CollapseBoxSetItems=false&format=json&ImageTypeLimit=1" % (id, sortstring)
jsonData = doUtils.downloadUrl(url)
if (jsonData == ""):
@ -38,14 +30,6 @@ class ReadEmbyDB():
if (jsonData[u'Items'] != ""):
result = jsonData[u'Items']
# work around for now until ParetnId and Id work together
if (result != None and len(result) > 0 and len(itemList) > 0):
newResult = []
for item in result:
if (item[u'Id'] in itemList):
newResult.append(item)
result = newResult
return result
def getMusicVideos(self, fullinfo = False, fullSync = True):
@ -98,20 +82,14 @@ class ReadEmbyDB():
return result
def getTVShows(self, id, fullinfo = False, fullSync = False):
def getTvShows(self, id):
result = None
doUtils = DownloadUtils()
if not fullSync:
sortstring = "&Limit=20&SortBy=DateCreated"
else:
sortstring = "&SortBy=SortName"
if fullinfo:
url = "{server}/mediabrowser/Users/{UserId}/Items?ParentId=%s%s&Fields=Path,Genres,SortName,Studios,Writer,ProductionYear,Taglines,CommunityRating,OfficialRating,CumulativeRunTimeTicks,Metascore,AirTime,DateCreated,MediaStreams,People,Overview&Recursive=true&SortOrder=Descending&IncludeItemTypes=Series&format=json&ImageTypeLimit=1" % (id, sortstring)
else:
url = "{server}/mediabrowser/Users/{UserId}/Items?ParentId=%s%s&Fields=CumulativeRunTimeTicks&Recursive=true&SortOrder=Descending&IncludeItemTypes=Series&format=json&ImageTypeLimit=1" % (id, sortstring)
#only get basic info for our sync-compares
sortstring = "&SortBy=SortName"
url = "{server}/mediabrowser/Users/{UserId}/Items?ParentId=%s%s&Fields=CumulativeRunTimeTicks&Recursive=true&SortOrder=Descending&IncludeItemTypes=Series&format=json&ImageTypeLimit=1" % (id, sortstring)
jsonData = doUtils.downloadUrl(url)
if (jsonData == ""):
@ -138,15 +116,12 @@ class ReadEmbyDB():
return result
def getEpisodes(self, showId, fullinfo = False):
def getEpisodes(self, showId):
result = None
doUtils = DownloadUtils()
if fullinfo:
url = "{server}/mediabrowser/Users/{UserId}/Items?ParentId=%s&IsVirtualUnaired=false&IsMissing=False&SortBy=SortName&Fields=Path,Genres,SortName,Studios,Writer,ProductionYear,Taglines,CommunityRating,OfficialRating,CumulativeRunTimeTicks,Metascore,AirTime,DateCreated,MediaStreams,People,Overview&Recursive=true&SortOrder=Ascending&IncludeItemTypes=Episode&format=json&ImageTypeLimit=1" % showId
else:
url = "{server}/mediabrowser/Users/{UserId}/Items?ParentId=%s&IsVirtualUnaired=false&IsMissing=False&SortBy=SortName&Fields=Name,SortName,CumulativeRunTimeTicks&Recursive=true&SortOrder=Ascending&IncludeItemTypes=Episode&format=json&ImageTypeLimit=1" % showId
url = "{server}/mediabrowser/Users/{UserId}/Items?ParentId=%s&IsVirtualUnaired=false&IsMissing=False&SortBy=SortName&Fields=Name,SortName,CumulativeRunTimeTicks&Recursive=true&SortOrder=Ascending&IncludeItemTypes=Episode&format=json&ImageTypeLimit=1" % showId
jsonData = doUtils.downloadUrl(url)
if (jsonData == ""):

View file

@ -30,71 +30,38 @@ class ReadKodiDB():
movies = result['movies']
movie = movies[0]
for item in movies:
if item["imdbnumber"] == id:
if id in item["file"]:
movie = item
break
return movie
def getEmbyIdByKodiId(self, kodiid, type):
#returns the emby id by search on kodi id
xbmc.sleep(sleepVal)
embyId = None
json_response = None
connection = utils.KodiSQL()
cursor = connection.cursor()
if type == "movie":
json_response = xbmc.executeJSONRPC('{"jsonrpc": "2.0", "method": "VideoLibrary.GetMovieDetails", "params": { "movieid": %d, "properties" : ["imdbnumber","file"] }, "id": "libMovies"}' %kodiid)
cursor.execute("SELECT embyId as embyId FROM movie WHERE idMovie = ?",(kodiid,))
if type == "episode":
json_response = xbmc.executeJSONRPC('{"jsonrpc": "2.0", "method": "VideoLibrary.GetEpisodeDetails", "params": {"episodeid": %d, "properties": ["file","uniqueid"]}, "id": 1}' %kodiid)
cursor.execute("SELECT embyId as embyId FROM episode WHERE idEpisode = ?",(kodiid,))
if type == "musicvideo":
connection = utils.KodiSQL()
cursor = connection.cursor()
cursor.execute("SELECT c23 as MBid FROM musicvideo WHERE idMVideo = ?",(kodiid,))
result = cursor.fetchone()
cursor.close()
if result != None:
embyId = result[0]
cursor.execute("SELECT embyId as embyId FROM musicvideo WHERE idMVideo = ?",(kodiid,))
if type == "tvshow":
cursor.execute("SELECT embyId as embyId FROM tvshow WHERE idShow = ?",(kodiid,))
if json_response != None:
jsonobject = json.loads(json_response.decode('utf-8','replace'))
if(jsonobject.has_key('result')):
result = jsonobject['result']
resulttype = type + "details"
if(result.has_key(resulttype)):
item = result[resulttype]
if type == "movie":
if item.has_key('imdbnumber'):
embyId = item['imdbnumber']
if type == "episode":
if item.has_key('uniqueid'):
if item['uniqueid'].has_key('unknown'):
embyId = item["uniqueid"]["unknown"]
result = cursor.fetchone()
cursor.close()
if result != None:
embyId = result[0]
return embyId
def getKodiMovies(self,fullInfo = False):
def getKodiMovies(self, connection, cursor):
#returns all movies in Kodi db
xbmc.sleep(sleepVal)
if fullInfo:
json_response = xbmc.executeJSONRPC('{"jsonrpc": "2.0", "method": "VideoLibrary.GetMovies", "params": { "properties" : ["art", "rating", "thumbnail", "fanart", "resume", "runtime", "year", "genre", "cast", "trailer", "country", "lastplayed", "studio", "set", "imdbnumber", "mpaa", "tagline", "plotoutline","plot", "sorttitle", "director", "writer", "playcount", "tag", "file"] }, "id": "libMovies"}')
else:
json_response = xbmc.executeJSONRPC('{"jsonrpc": "2.0", "method": "VideoLibrary.GetMovies", "params": { "properties" : ["resume", "playcount", "imdbnumber", "lastplayed", "file"] }, "id": "libMovies"}')
jsonobject = json.loads(json_response.decode('utf-8','replace'))
movies = None
if(jsonobject.has_key('result')):
result = jsonobject['result']
if(result.has_key('movies')):
movies = result['movies']
kodiMovieMap = None
if(movies != None and len(movies) > 0):
kodiMovieMap = {}
for kodimovie in movies:
key = kodimovie["imdbnumber"] #extract the id from the imdbnumber
kodiMovieMap[key] = kodimovie
return kodiMovieMap
cursor.execute("SELECT idMovie, embyId, c00 FROM movie")
allmovies = cursor.fetchall()
#this will return a list with tuples of all items returned from the database
return allmovies
def getKodiMoviesIds(self,returnMB3Ids = False):
# returns a list of movieIds or MB3 Id's from all movies currently in the Kodi library
@ -132,29 +99,11 @@ class ReadKodiDB():
return allKodiTvShowsIds
def getKodiTvShows(self,fullInfo = False):
#returns all tvshows in Kodi db inserted by MB
xbmc.sleep(sleepVal)
if fullInfo:
json_response = xbmc.executeJSONRPC('{"jsonrpc": "2.0", "method": "VideoLibrary.GetTVShows", "params": { "properties": ["art", "genre", "plot", "mpaa", "cast", "studio", "sorttitle", "title", "originaltitle", "imdbnumber", "year", "premiered", "rating", "thumbnail", "playcount", "lastplayed", "file", "fanart", "tag"], "sort": { "order": "ascending", "method": "label", "ignorearticle": true } }, "id": "libTvShows"}')
else:
json_response = xbmc.executeJSONRPC('{"jsonrpc": "2.0", "method": "VideoLibrary.GetTVShows", "params": { "properties": ["sorttitle", "title", "playcount", "lastplayed", "imdbnumber", "file"], "sort": { "order": "ascending", "method": "label", "ignorearticle": true } }, "id": "libTvShows"}')
jsonobject = json.loads(json_response.decode('utf-8','replace'))
tvshows = None
if(jsonobject.has_key('result')):
result = jsonobject['result']
if(result.has_key('tvshows')):
tvshows = result['tvshows']
kodiShowMap = None
if(tvshows != None and len(tvshows) > 0):
kodiShowMap = {}
for kodishow in tvshows:
key = kodishow["imdbnumber"] #extract the id from the imdb number
kodiShowMap[key] = kodishow
return kodiShowMap
def getKodiTvShows(self, connection, cursor):
cursor.execute("SELECT idShow, embyId, c00 FROM tvshow")
allshows = cursor.fetchall()
#this will return a list with tuples of all items returned from the database
return allshows
def getKodiTVShow(self, id):
xbmc.sleep(sleepVal)
@ -171,28 +120,11 @@ class ReadKodiDB():
break
return tvshow
def getKodiEpisodes(self, KodiTvShowId, fullInfo = True, returnmap = True):
xbmc.sleep(sleepVal)
episodes = None
if fullInfo:
json_response = xbmc.executeJSONRPC('{"jsonrpc": "2.0", "method": "VideoLibrary.GetEpisodes", "params": {"tvshowid": %d, "properties": ["title", "playcount", "plot", "season", "episode", "showtitle", "file", "lastplayed", "rating", "resume", "art", "streamdetails", "firstaired", "runtime", "writer", "cast", "director", "dateadded", "uniqueid", "thumbnail", "fanart"], "sort": {"method": "episode"}}, "id": 1}' %KodiTvShowId)
else:
json_response = xbmc.executeJSONRPC('{"jsonrpc": "2.0", "method": "VideoLibrary.GetEpisodes", "params": {"tvshowid": %d, "properties": ["title", "playcount", "season", "episode", "lastplayed", "resume","file","uniqueid"], "sort": {"method": "episode"}}, "id": 1}' %KodiTvShowId)
jsonobject = json.loads(json_response.decode('utf-8','replace'))
episodes = None
if(jsonobject.has_key('result')):
result = jsonobject['result']
if(result.has_key('episodes')):
episodes = result['episodes']
if returnmap:
episodeMap = None
if(episodes != None):
episodeMap = {}
for KodiItem in episodes:
episodeMap[KodiItem["uniqueid"]["unknown"]] = KodiItem
return episodeMap
else:
return episodes
def getKodiEpisodes(self, connection, cursor, showid):
cursor.execute("SELECT idEpisode, embyId, c00 FROM episode WHERE idShow = ?", (showid,))
allepisodes = cursor.fetchall()
#this will return a list with tuples of all items returned from the database
return allepisodes
def getKodiEpisodeByMbItem(self, episodeid, tvshowid):
episode = None

File diff suppressed because it is too large Load diff

View file

@ -115,12 +115,10 @@ class Service():
self.logMsg("Doing_Db_Sync: syncDatabase (Started)")
libSync = librarySync.syncDatabase()
self.logMsg("Doing_Db_Sync: syncDatabase (Finished) " + str(libSync))
countSync = librarySync.updatePlayCounts()
self.logMsg("Doing_Db_Sync: updatePlayCounts (Finished) " + str(countSync))
# Force refresh newly set thumbnails
xbmc.executebuiltin("UpdateLibrary(video)")
if(libSync and countSync):
if(libSync):
startupComplete = True
else:
if self.KodiMonitor.waitForAbort(10):