Ejemplo n.º 1
0
    def FullLibrarySync(self,manualRun=False):
        
        
        addon = xbmcaddon.Addon(id='plugin.video.emby')
        startupDone = WINDOW.getProperty("startup") == "done"
        syncInstallRunDone = addon.getSetting("SyncInstallRunDone") == "true"
        performMusicSync = addon.getSetting("enableMusicSync") == "true"
        dbSyncIndication = addon.getSetting("dbSyncIndication") == "true"        
        
        # just do a incremental sync if that is what is required
        if(addon.getSetting("useIncSync") == "true"):
            utils.logMsg("Sync Database", "Using incremental sync instead of full sync useIncSync=True)", 0)
            
            du = DownloadUtils()
            
            lastSync = addon.getSetting("LastIncrenetalSync")
            if(lastSync == None or len(lastSync) == 0):
                lastSync = "2010-01-01T00:00:00Z"
            utils.logMsg("Sync Database", "Incremental Sync Setting Last Run Time Loaded : " + lastSync, 0)

            url = "{server}/Emby.Kodi.SyncQueue/{UserId}/" + lastSync + "/GetItems?format=json"
            utils.logMsg("Sync Database", "Incremental Sync Get Items URL : " + url, 0)
            
            results = du.downloadUrl(url)
            utils.logMsg("Sync Database", "Incfemental Sync Changes : " + str(results), 0)
            
            changedItems = results["ItemsUpdated"] + results["ItemsAdded"]
            removedItems = results["ItemsRemoved"]
            userChanges = results["UserDataChanged"]
            
            WINDOW.setProperty("startup", "done")
            
            LibrarySync().remove_items(removedItems)
            LibrarySync().update_items(changedItems)
            LibrarySync().user_data_update(userChanges)
            
            # save last sync time
            lastSync = (datetime.utcnow() - timedelta(minutes=5)).strftime('%Y-%m-%dT%H:%M:%SZ')
            utils.logMsg("Sync Database", "Incremental Sync Setting Last Run Time Saved : " + lastSync, 0)
            addon.setSetting("LastIncrenetalSync", lastSync)     
            
            return True
		
        #set some variable to check if this is the first run
        WINDOW.setProperty("SyncDatabaseRunning", "true")     
        
        #show the progress dialog
        pDialog = None
        if (syncInstallRunDone == False or dbSyncIndication or manualRun):
            pDialog = xbmcgui.DialogProgressBG()
            pDialog.create('Emby for Kodi', 'Performing full sync')
        
        if(WINDOW.getProperty("SyncDatabaseShouldStop") ==  "true"):
            utils.logMsg("Sync Database", "Can not start SyncDatabaseShouldStop=True", 0)
            return True

        try:
            completed = True
            

            ### BUILD VIDEO NODES LISTING ###
            VideoNodes().buildVideoNodesListing()
            ### CREATE SOURCES ###
            if addon.getSetting("Sources") != "true":
                # Only create sources once
                self.logMsg("Sources.xml created.", 0)
                utils.createSources()
                addon.setSetting("Sources", "true")
            
            ### PROCESS VIDEO LIBRARY ###
            
            #create the sql connection to video db
            connection = utils.KodiSQL("video")
            cursor = connection.cursor()
            
            #Add the special emby table
            cursor.execute("CREATE TABLE IF NOT EXISTS emby(emby_id TEXT, kodi_id INTEGER, media_type TEXT, checksum TEXT, parent_id INTEGER)")
            connection.commit()
            
            # sync movies
            self.MoviesFullSync(connection,cursor,pDialog)
            
            if (self.ShouldStop()):
                return False
            
            #sync Tvshows and episodes
            self.TvShowsFullSync(connection,cursor,pDialog)
            
            if (self.ShouldStop()):
                return False
                    
            # sync musicvideos
            self.MusicVideosFullSync(connection,cursor,pDialog)
            
            #close sql connection
            cursor.close()
            
            ### PROCESS MUSIC LIBRARY ###
            if performMusicSync:
                #create the sql connection to music db
                connection = utils.KodiSQL("music")
                cursor = connection.cursor()
                
                #Add the special emby table
                cursor.execute("CREATE TABLE IF NOT EXISTS emby(emby_id TEXT, kodi_id INTEGER, media_type TEXT, checksum TEXT, parent_id INTEGER)")
                connection.commit()
                
                self.MusicFullSync(connection,cursor,pDialog)
                cursor.close()
            
            # set the install done setting
            if(syncInstallRunDone == False and completed):
                addon = xbmcaddon.Addon(id='plugin.video.emby') #force a new instance of the addon
                addon.setSetting("SyncInstallRunDone", "true")        
            
            # Commit all DB changes at once and Force refresh the library
            xbmc.executebuiltin("UpdateLibrary(video)")
            
            # set prop to show we have run for the first time
            WINDOW.setProperty("startup", "done")
            
            # tell any widgets to refresh because the content has changed
            WINDOW.setProperty("widgetreload", datetime.now().strftime('%Y-%m-%d %H:%M:%S'))
            
        finally:
            WINDOW.setProperty("SyncDatabaseRunning", "false")
            utils.logMsg("Sync DB", "syncDatabase Exiting", 0)
            

        if(pDialog != None):
            pDialog.close()
        
        return True      
Ejemplo n.º 2
0
    def FullLibrarySync(self,manualRun=False):
        
        startupDone = WINDOW.getProperty("startup") == "done"
        syncInstallRunDone = utils.settings("SyncInstallRunDone") == "true"
        performMusicSync = utils.settings("enableMusicSync") == "true"
        dbSyncIndication = utils.settings("dbSyncIndication") == "true"

        ### BUILD VIDEO NODES LISTING ###
        VideoNodes().buildVideoNodesListing()
        ### CREATE SOURCES ###
        if utils.settings("Sources") != "true":
            # Only create sources once
            self.logMsg("Sources.xml created.", 0)
            utils.createSources()
            utils.settings("Sources", "true")  
        
        # just do a incremental sync if that is what is required
        if(utils.settings("useIncSync") == "true" and utils.settings("SyncInstallRunDone") == "true") and manualRun == False:
            utils.logMsg("Sync Database", "Using incremental sync instead of full sync useIncSync=True)", 0)
            
            du = DownloadUtils()
            
            lastSync = utils.settings("LastIncrenetalSync")
            if(lastSync == None or len(lastSync) == 0):
                lastSync = "2010-01-01T00:00:00Z"
            utils.logMsg("Sync Database", "Incremental Sync Setting Last Run Time Loaded : " + lastSync, 0)

            lastSync = urllib2.quote(lastSync)
            
            url = "{server}/Emby.Kodi.SyncQueue/{UserId}/GetItems?LastUpdateDT=" + lastSync + "&format=json"
            utils.logMsg("Sync Database", "Incremental Sync Get Items URL : " + url, 0)
            
            try:
                results = du.downloadUrl(url)
                changedItems = results["ItemsUpdated"] + results["ItemsAdded"]
                removedItems = results["ItemsRemoved"]
                userChanges = results["UserDataChanged"]                
            except:
                utils.logMsg("Sync Database", "Incremental Sync Get Changes Failed", 0)
                pass
            else:
                maxItems = int(utils.settings("incSyncMaxItems"))
                utils.logMsg("Sync Database", "Incremental Sync Changes : " + str(results), 0)
                if(len(changedItems) < maxItems and len(removedItems) < maxItems and len(userChanges) < maxItems):
                
                    WINDOW.setProperty("startup", "done")
                    
                    LibrarySync().remove_items(removedItems)
                    LibrarySync().update_items(changedItems)
                    LibrarySync().user_data_update(userChanges)
                    
                    self.SaveLastSync()
                    
                    return True
                else:
                    utils.logMsg("Sync Database", "Too Many For Incremental Sync (" + str(maxItems) + "), changedItems" + str(len(changedItems)) + " removedItems:" + str(len(removedItems)) + " userChanges:" + str(len(userChanges)), 0)
        
        #set some variable to check if this is the first run
        WINDOW.setProperty("SyncDatabaseRunning", "true")     
        
        #show the progress dialog
        pDialog = None
        if (syncInstallRunDone == False or dbSyncIndication or manualRun):
            pDialog = xbmcgui.DialogProgressBG()
            pDialog.create('Emby for Kodi', 'Performing full sync')
        
        if(WINDOW.getProperty("SyncDatabaseShouldStop") ==  "true"):
            utils.logMsg("Sync Database", "Can not start SyncDatabaseShouldStop=True", 0)
            return True

        try:
            completed = True
                        
            ### PROCESS VIDEO LIBRARY ###
            
            #create the sql connection to video db
            connection = utils.KodiSQL("video")
            cursor = connection.cursor()
            
            #Add the special emby table
            cursor.execute("CREATE TABLE IF NOT EXISTS emby(emby_id TEXT, kodi_id INTEGER, media_type TEXT, checksum TEXT, parent_id INTEGER, kodi_file_id INTEGER)")
            try:
                cursor.execute("ALTER TABLE emby ADD COLUMN kodi_file_id INTEGER")
            except: pass
            connection.commit()
            
            # sync movies
            self.MoviesFullSync(connection,cursor,pDialog)
            
            if (self.ShouldStop()):
                return False
            
            #sync Tvshows and episodes
            self.TvShowsFullSync(connection,cursor,pDialog)
            
            if (self.ShouldStop()):
                return False
                    
            # sync musicvideos
            self.MusicVideosFullSync(connection,cursor,pDialog)
            
            #close sql connection
            cursor.close()
            
            ### PROCESS MUSIC LIBRARY ###
            if performMusicSync:
                #create the sql connection to music db
                connection = utils.KodiSQL("music")
                cursor = connection.cursor()
                
                #Add the special emby table
                cursor.execute("CREATE TABLE IF NOT EXISTS emby(emby_id TEXT, kodi_id INTEGER, media_type TEXT, checksum TEXT, parent_id INTEGER, kodi_file_id INTEGER)")
                try:
                    cursor.execute("ALTER TABLE emby ADD COLUMN kodi_file_id INTEGER")
                except: pass
                connection.commit()
                
                self.MusicFullSync(connection,cursor,pDialog)
                cursor.close()
            
            # set the install done setting
            if(syncInstallRunDone == False and completed):
                utils.settings("SyncInstallRunDone", "true")
                utils.settings("dbCreatedWithVersion", self.clientInfo.getVersion())    
            
            # Commit all DB changes at once and Force refresh the library
            xbmc.executebuiltin("UpdateLibrary(video)")
            #xbmc.executebuiltin("UpdateLibrary(music)")
            
            # set prop to show we have run for the first time
            WINDOW.setProperty("startup", "done")
            
            # tell any widgets to refresh because the content has changed
            WINDOW.setProperty("widgetreload", datetime.now().strftime('%Y-%m-%d %H:%M:%S'))
            
            self.SaveLastSync()
            
        finally:
            WINDOW.setProperty("SyncDatabaseRunning", "false")
            utils.logMsg("Sync DB", "syncDatabase Exiting", 0)

        if(pDialog != None):
            pDialog.close()
        
        return True