PlexKodiConnect/resources/lib/LibrarySync.py

432 lines
17 KiB
Python
Raw Normal View History

2015-03-14 08:24:59 +11:00
#################################################################################################
# LibrarySync
#################################################################################################
import xbmc
import xbmcgui
import xbmcaddon
import xbmcvfs
import json
import sqlite3
2015-03-17 04:51:49 +11:00
import inspect
2015-03-14 08:24:59 +11:00
import threading
import urllib
from datetime import datetime, timedelta, time
from itertools import chain
2015-03-14 08:24:59 +11:00
import urllib2
import os
2015-03-14 08:24:59 +11:00
from API import API
import Utils as utils
from DownloadUtils import DownloadUtils
2015-03-18 04:51:45 +11:00
from ReadEmbyDB import ReadEmbyDB
2015-03-18 05:41:26 +11:00
from ReadKodiDB import ReadKodiDB
from WriteKodiVideoDB import WriteKodiVideoDB
from VideoNodes import VideoNodes
2015-03-14 08:24:59 +11:00
2015-03-26 04:37:21 +11:00
addondir = xbmc.translatePath(xbmcaddon.Addon(id='plugin.video.emby').getAddonInfo('profile'))
2015-03-14 08:24:59 +11:00
dataPath = os.path.join(addondir,"library")
movieLibrary = os.path.join(dataPath,'movies')
tvLibrary = os.path.join(dataPath,'tvshows')
2015-03-14 08:24:59 +11:00
WINDOW = xbmcgui.Window( 10000 )
2015-03-14 08:24:59 +11:00
class LibrarySync():
2015-05-07 19:36:34 +10:00
def FullLibrarySync(self,manualRun=False):
#set some variable to check if this is the first run
2015-03-26 04:37:21 +11:00
addon = xbmcaddon.Addon(id='plugin.video.emby')
startupDone = WINDOW.getProperty("startup") == "done"
syncInstallRunDone = addon.getSetting("SyncInstallRunDone") == "true"
dbSyncIndication = addon.getSetting("dbSyncIndication") == "true"
WINDOW.setProperty("SyncDatabaseRunning", "true")
#show the progress dialog
pDialog = None
2015-05-07 19:36:34 +10:00
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
2015-04-05 03:20:48 +10:00
connection = utils.KodiSQL()
cursor = connection.cursor()
2015-05-02 11:47:05 +10:00
#Add the special emby table
if not startupDone:
2015-05-02 10:26:06 +10:00
cursor.execute("CREATE TABLE IF NOT EXISTS emby(emby_id TEXT, kodi_id INTEGER, media_type TEXT, checksum TEXT, parent_id INTEGER)")
connection.commit()
### BUILD VIDEO NODES LISTING ###
VideoNodes().buildVideoNodesListing()
# sync movies
self.MoviesFullSync(connection,cursor,pDialog)
if (self.ShouldStop()):
2015-05-03 06:02:06 +10:00
return False
#sync Tvshows and episodes
self.TvShowsFullSync(connection,cursor,pDialog)
2015-05-03 06:02:06 +10:00
if (self.ShouldStop()):
return False
# sync musicvideos
self.MusicVideosFullSync(connection,cursor,pDialog)
# 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")
finally:
WINDOW.setProperty("SyncDatabaseRunning", "false")
utils.logMsg("Sync DB", "syncDatabase Exiting", 0)
2015-04-05 03:20:48 +10:00
cursor.close()
if(pDialog != None):
pDialog.close()
return True
def MoviesFullSync(self,connection,cursor, pDialog):
views = ReadEmbyDB().getCollections("movies")
allKodiMovieIds = list()
allEmbyMovieIds = list()
for view in views:
allEmbyMovies = ReadEmbyDB().getMovies(view.get('id'))
allKodiMovies = ReadKodiDB().getKodiMovies(connection, cursor)
2015-05-02 11:47:05 +10:00
for kodimovie in allKodiMovies:
allKodiMovieIds.append(kodimovie[1])
total = len(allEmbyMovies) + 1
count = 1
#### PROCESS ADDS AND UPDATES ###
for item in allEmbyMovies:
if (self.ShouldStop()):
return False
if not item.get('IsFolder'):
allEmbyMovieIds.append(item["Id"])
if(pDialog != None):
progressTitle = "Processing " + view.get('title') + " (" + str(count) + " of " + str(total) + ")"
pDialog.update(0, "Emby for Kodi - Running Sync", progressTitle)
2015-05-02 20:51:46 +10:00
count += 1
kodiMovie = None
for kodimovie in allKodiMovies:
if kodimovie[1] == item["Id"]:
kodiMovie = kodimovie
if kodiMovie == None:
WriteKodiVideoDB().addOrUpdateMovieToKodiLibrary(item["Id"],connection, cursor, view.get('title'))
else:
if kodiMovie[2] != API().getChecksum(item):
WriteKodiVideoDB().addOrUpdateMovieToKodiLibrary(item["Id"],connection, cursor, view.get('title'))
2015-05-03 22:44:23 +10:00
#### PROCESS BOX SETS #####
if(pDialog != None):
utils.logMsg("Sync Movies", "BoxSet Sync Started", 1)
boxsets = ReadEmbyDB().getBoxSets()
total = len(boxsets) + 1
count = 1
for boxset in boxsets:
progressTitle = "Processing BoxSets"+ " (" + str(count) + " of " + str(total) + ")"
pDialog.update(0, "Emby for Kodi - Running Sync", progressTitle)
count += 1
if(self.ShouldStop()):
return False
boxsetMovies = ReadEmbyDB().getMoviesInBoxSet(boxset["Id"])
WriteKodiVideoDB().addBoxsetToKodiLibrary(boxset,connection, cursor)
2015-05-03 22:44:23 +10:00
for boxsetMovie in boxsetMovies:
if(self.ShouldStop()):
return False
WriteKodiVideoDB().updateBoxsetToKodiLibrary(boxsetMovie,boxset, connection, cursor)
2015-05-03 22:44:23 +10:00
utils.logMsg("Sync Movies", "BoxSet Sync Finished", 1)
2015-05-02 20:51:46 +10:00
#### PROCESS DELETES #####
allEmbyMovieIds = set(allEmbyMovieIds)
for kodiId in allKodiMovieIds:
if not kodiId in allEmbyMovieIds:
WINDOW.setProperty(kodiId,"deleted")
WriteKodiVideoDB().deleteItemFromKodiLibrary(kodiId, connection, cursor)
### commit all changes to database ###
connection.commit()
2015-05-03 06:02:06 +10:00
def MusicVideosFullSync(self,connection,cursor, pDialog):
allKodiMusicvideoIds = list()
allEmbyMusicvideoIds = list()
allEmbyMusicvideos = ReadEmbyDB().getMusicVideos()
allKodiMusicvideos = ReadKodiDB().getKodiMusicVideos(connection, cursor)
for kodivideo in allKodiMusicvideos:
allKodiMusicvideoIds.append(kodivideo[1])
total = len(allEmbyMusicvideos) + 1
count = 1
#### PROCESS ADDS AND UPDATES ###
for item in allEmbyMusicvideos:
if (self.ShouldStop()):
return False
if not item.get('IsFolder'):
allEmbyMusicvideoIds.append(item["Id"])
if(pDialog != None):
progressTitle = "Processing MusicVideos (" + str(count) + " of " + str(total) + ")"
pDialog.update(0, "Emby for Kodi - Running Sync", progressTitle)
count += 1
kodiVideo = None
for kodivideo in allKodiMusicvideos:
if kodivideo[1] == item["Id"]:
kodiVideo = kodivideo
if kodiVideo == None:
WriteKodiVideoDB().addOrUpdateMusicVideoToKodiLibrary(item["Id"],connection, cursor)
2015-05-03 06:02:06 +10:00
else:
if kodiVideo[2] != API().getChecksum(item):
WriteKodiVideoDB().addOrUpdateMusicVideoToKodiLibrary(item["Id"],connection, cursor)
2015-05-03 06:02:06 +10:00
#### PROCESS DELETES #####
allEmbyMusicvideoIds = set(allEmbyMusicvideoIds)
for kodiId in allKodiMusicvideoIds:
if not kodiId in allEmbyMusicvideoIds:
WINDOW.setProperty(kodiId,"deleted")
WriteKodiVideoDB().deleteItemFromKodiLibrary(kodiId, connection, cursor)
### commit all changes to database ###
connection.commit()
2015-05-03 06:02:06 +10:00
def TvShowsFullSync(self,connection,cursor,pDialog):
views = ReadEmbyDB().getCollections("tvshows")
allKodiTvShowIds = list()
allEmbyTvShowIds = list()
2015-05-02 11:47:05 +10:00
for view in views:
allEmbyTvShows = ReadEmbyDB().getTvShows(view.get('id'))
allKodiTvShows = ReadKodiDB().getKodiTvShows(connection, cursor)
2015-05-02 11:47:05 +10:00
total = len(allEmbyTvShows) + 1
count = 1
2015-05-02 11:47:05 +10:00
for kodishow in allKodiTvShows:
allKodiTvShowIds.append(kodishow[1])
#### TVSHOW: PROCESS ADDS AND UPDATES ###
for item in allEmbyTvShows:
if (self.ShouldStop()):
return False
if(pDialog != None):
progressTitle = "Processing " + view.get('title') + " (" + str(count) + " of " + str(total) + ")"
pDialog.update(0, "Emby for Kodi - Running Sync", progressTitle)
count += 1
if item.get('IsFolder') and item.get('RecursiveItemCount') != 0:
allEmbyTvShowIds.append(item["Id"])
2015-03-19 08:38:02 +11:00
#build a list with all Id's and get the existing entry (if exists) in Kodi DB
kodiShow = None
for kodishow in allKodiTvShows:
if kodishow[1] == item["Id"]:
kodiShow = kodishow
if kodiShow == None:
# Tv show doesn't exist in Kodi yet so proceed and add it
WriteKodiVideoDB().addOrUpdateTvShowToKodiLibrary(item["Id"],connection, cursor, view.get('title'))
else:
# If there are changes to the item, perform a full sync of the item
if kodiShow[2] != API().getChecksum(item):
WriteKodiVideoDB().addOrUpdateTvShowToKodiLibrary(item["Id"],connection, cursor, view.get('title'))
2015-04-05 07:48:02 +10:00
#### PROCESS EPISODES ######
2015-05-02 22:57:43 +10:00
self.EpisodesFullSync(connection,cursor,item["Id"])
2015-05-02 20:51:46 +10:00
#### TVSHOW: PROCESS DELETES #####
allEmbyTvShowIds = set(allEmbyTvShowIds)
for kodiId in allKodiTvShowIds:
if not kodiId in allEmbyTvShowIds:
WINDOW.setProperty(kodiId,"deleted")
WriteKodiVideoDB().deleteItemFromKodiLibrary(kodiId, connection, cursor)
### commit all changes to database ###
connection.commit()
2015-05-02 22:57:43 +10:00
def EpisodesFullSync(self,connection,cursor,showId):
WINDOW = xbmcgui.Window( 10000 )
allKodiEpisodeIds = list()
allEmbyEpisodeIds = list()
2015-05-02 22:57:43 +10:00
#get the kodi parent id
cursor.execute("SELECT kodi_id FROM emby WHERE emby_id=?",(showId,))
kodiShowId = cursor.fetchone()[0]
allEmbyEpisodes = ReadEmbyDB().getEpisodes(showId)
allKodiEpisodes = ReadKodiDB().getKodiEpisodes(connection, cursor, kodiShowId)
2015-05-02 11:47:05 +10:00
for kodiepisode in allKodiEpisodes:
allKodiEpisodeIds.append(kodiepisode[1])
#### EPISODES: PROCESS ADDS AND UPDATES ###
for item in allEmbyEpisodes:
if (self.ShouldStop()):
return False
allEmbyEpisodeIds.append(item["Id"])
2015-05-02 11:47:05 +10:00
#get the existing entry (if exists) in Kodi DB
kodiEpisode = None
for kodiepisode in allKodiEpisodes:
if kodiepisode[1] == item["Id"]:
kodiEpisode = kodiepisode
if kodiEpisode == None:
# Episode doesn't exist in Kodi yet so proceed and add it
WriteKodiVideoDB().addOrUpdateEpisodeToKodiLibrary(item["Id"], kodiShowId, connection, cursor)
else:
# If there are changes to the item, perform a full sync of the item
if kodiEpisode[2] != API().getChecksum(item):
WriteKodiVideoDB().addOrUpdateEpisodeToKodiLibrary(item["Id"], kodiShowId, connection, cursor)
#### EPISODES: PROCESS DELETES #####
allEmbyEpisodeIds = set(allEmbyEpisodeIds)
for kodiId in allKodiEpisodeIds:
2015-05-02 11:47:05 +10:00
if (not kodiId in allEmbyEpisodeIds):
WINDOW.setProperty(kodiId,"deleted")
WriteKodiVideoDB().deleteItemFromKodiLibrary(kodiId, connection, cursor)
def IncrementalSync(self, itemList):
#this will only perform sync for items received by the websocket
addon = xbmcaddon.Addon(id='plugin.video.emby')
dbSyncIndication = addon.getSetting("dbSyncIndication") == "true"
WINDOW.setProperty("SyncDatabaseRunning", "true")
2015-03-22 00:31:30 +11:00
#show the progress dialog
pDialog = None
if (dbSyncIndication):
pDialog = xbmcgui.DialogProgressBG()
pDialog.create('Emby for Kodi', 'Performing incremental sync...')
2015-03-22 00:31:30 +11:00
connection = utils.KodiSQL()
cursor = connection.cursor()
2015-03-22 00:31:30 +11:00
2015-05-02 20:51:46 +10:00
try:
#### PROCESS MOVIES ####
views = ReadEmbyDB().getCollections("movies")
for view in views:
allEmbyMovies = ReadEmbyDB().getMovies(view.get('id'), itemList)
for item in allEmbyMovies:
if not item.get('IsFolder'):
WriteKodiVideoDB().addOrUpdateMovieToKodiLibrary(item["Id"],connection, cursor, view.get('title'))
2015-05-03 22:44:23 +10:00
#### PROCESS BOX SETS #####
boxsets = ReadEmbyDB().getBoxSets()
for boxset in boxsets:
boxsetMovies = ReadEmbyDB().getMoviesInBoxSet(boxset["Id"])
WriteKodiVideoDB().addBoxsetToKodiLibrary(boxset,connection, cursor)
2015-05-03 22:44:23 +10:00
for boxsetMovie in boxsetMovies:
WriteKodiVideoDB().updateBoxsetToKodiLibrary(boxsetMovie,boxset, connection, cursor)
2015-05-02 20:51:46 +10:00
2015-05-03 22:44:23 +10:00
2015-05-02 20:51:46 +10:00
#### PROCESS TV SHOWS ####
views = ReadEmbyDB().getCollections("tvshows")
for view in views:
allEmbyTvShows = ReadEmbyDB().getTvShows(view.get('id'),itemList)
for item in allEmbyTvShows:
if item.get('IsFolder') and item.get('RecursiveItemCount') != 0:
kodiId = WriteKodiVideoDB().addOrUpdateTvShowToKodiLibrary(item["Id"],connection, cursor, view.get('title'))
2015-05-02 20:51:46 +10:00
#### PROCESS EPISODES ######
for item in itemList:
2015-03-22 00:31:30 +11:00
2015-05-02 20:51:46 +10:00
MBitem = ReadEmbyDB().getItem(item)
if MBitem["Type"] == "Episode":
2015-05-02 21:47:04 +10:00
2015-05-02 20:51:46 +10:00
#get the tv show
cursor.execute("SELECT kodi_id FROM emby WHERE media_type='tvshow' AND emby_id=?", (MBitem["SeriesId"],))
2015-05-02 21:47:04 +10:00
result = cursor.fetchone()
2015-05-02 20:51:46 +10:00
if result:
kodi_show_id = result[0]
else:
kodi_show_id = None
2015-05-02 21:47:04 +10:00
2015-05-02 20:51:46 +10:00
if kodi_show_id:
WriteKodiVideoDB().addOrUpdateEpisodeToKodiLibrary(MBitem["Id"], kodi_show_id, connection, cursor)
2015-05-03 06:02:06 +10:00
#### PROCESS MUSICVIDEOS ####
allEmbyMusicvideos = ReadEmbyDB().getMusicVideos(itemList)
for item in allEmbyMusicvideos:
if not item.get('IsFolder'):
WriteKodiVideoDB().addOrUpdateMusicVideoToKodiLibrary(item["Id"],connection, cursor)
### commit all changes to database ###
connection.commit()
2015-05-03 06:02:06 +10:00
2015-05-02 20:51:46 +10:00
finally:
cursor.close()
2015-05-02 21:47:04 +10:00
xbmc.executebuiltin("UpdateLibrary(video)")
WINDOW.setProperty("SyncDatabaseRunning", "false")
2015-05-02 20:51:46 +10:00
#close the progress dialog
if(pDialog != None):
pDialog.close()
def ShouldStop(self):
if(xbmc.abortRequested):
return True
if(WINDOW.getProperty("SyncDatabaseShouldStop") == "true"):
return True
return False
2015-03-17 04:51:49 +11:00
2015-03-16 04:14:23 +11:00