This commit is contained in:
angelblue05 2016-10-10 06:14:10 -05:00 committed by GitHub
parent 6eb8cdfa30
commit 2b0c9d1bbc
11 changed files with 268 additions and 327 deletions

View file

@ -157,7 +157,7 @@ class Main(object):
if __name__ == "__main__": if __name__ == "__main__":
log.info("plugin.video.emby started") log.info("plugin.video.emby started")
try: try:
Main() Main()
except Exception as error: except Exception as error:
@ -165,5 +165,5 @@ if __name__ == "__main__":
errStrings = ga.formatException() errStrings = ga.formatException()
ga.sendEventData("Exception", errStrings[0], errStrings[1]) ga.sendEventData("Exception", errStrings[0], errStrings[1])
log.exception(error) log.exception(error)
log.info("plugin.video.emby stopped") log.info("plugin.video.emby stopped")

View file

@ -110,7 +110,7 @@ class DownloadUtils(object):
} }
self.downloadUrl(url, postBody=data, action_type="POST") self.downloadUrl(url, postBody=data, action_type="POST")
log.debug("Posted capabilities to %s" % self.session['Server']) log.debug("Posted capabilities to %s", self.session['Server'])
# Attempt at getting sessionId # Attempt at getting sessionId
url = "{server}/emby/Sessions?DeviceId=%s&format=json" % device_id url = "{server}/emby/Sessions?DeviceId=%s&format=json" % device_id
@ -301,7 +301,7 @@ class DownloadUtils(object):
raise Warning('restricted') raise Warning('restricted')
elif (response.headers['X-Application-Error-Code'] == elif (response.headers['X-Application-Error-Code'] ==
"UnauthorizedAccessException"): "UnauthorizedAccessException"):
# User tried to do something his emby account doesn't allow # User tried to do something his emby account doesn't allow
pass pass

View file

@ -3,23 +3,10 @@
################################################################################################## ##################################################################################################
import logging import logging
import urllib
from ntpath import dirname
from datetime import datetime
import xbmc
import xbmcgui
import xbmcvfs
import api
import artwork
import downloadutils
import embydb_functions as embydb
import kodidb_functions as kodidb
import read_embyserver as embyserver import read_embyserver as embyserver
import musicutils
from objects import Movies, MusicVideos, TVShows, Music from objects import Movies, MusicVideos, TVShows, Music
from utils import window, settings, language as lang, kodiSQL from utils import settings, kodiSQL
################################################################################################# #################################################################################################
@ -36,28 +23,15 @@ class Items(object):
self.embycursor = embycursor self.embycursor = embycursor
self.kodicursor = kodicursor self.kodicursor = kodicursor
self.doUtils = downloadutils.DownloadUtils()
self.kodiversion = int(xbmc.getInfoLabel('System.BuildVersion')[:2])
self.directpath = settings('useDirectPaths') == "1"
self.music_enabled = settings('enableMusic') == "true"
self.contentmsg = settings('newContent') == "true"
self.newvideo_time = int(settings('newvideotime'))*1000
self.newmusic_time = int(settings('newmusictime'))*1000
self.artwork = artwork.Artwork()
self.emby = embyserver.Read_EmbyServer() self.emby = embyserver.Read_EmbyServer()
self.emby_db = embydb.Embydb_Functions(embycursor) self.music_enabled = settings('enableMusic') == "true"
self.kodi_db = kodidb.Kodidb_Functions(kodicursor)
def itemsbyId(self, items, process, pdialog=None): def itemsbyId(self, items, process, pdialog=None):
# Process items by itemid. Process can be added, update, userdata, remove # Process items by itemid. Process can be added, update, userdata, remove
emby = self.emby
embycursor = self.embycursor embycursor = self.embycursor
kodicursor = self.kodicursor kodicursor = self.kodicursor
music_enabled = self.music_enabled
itemtypes = { itemtypes = {
'Movie': Movies, 'Movie': Movies,
@ -80,11 +54,10 @@ class Items(object):
if total == 0: if total == 0:
return False return False
log.info("Processing %s: %s" % (process, items)) log.info("Processing %s: %s", process, items)
if pdialog: if pdialog:
pdialog.update(heading="Processing %s: %s items" % (process, total)) pdialog.update(heading="Processing %s: %s items" % (process, total))
count = 0
for itemtype in items: for itemtype in items:
# Safety check # Safety check
@ -100,7 +73,7 @@ class Items(object):
musicconn = None musicconn = None
if itemtype in ('MusicAlbum', 'MusicArtist', 'AlbumArtist', 'Audio'): if itemtype in ('MusicAlbum', 'MusicArtist', 'AlbumArtist', 'Audio'):
if music_enabled: if self.music_enabled:
musicconn = kodiSQL('music') musicconn = kodiSQL('music')
musiccursor = musicconn.cursor() musiccursor = musicconn.cursor()
items_process = itemtypes[itemtype](embycursor, musiccursor, pdialog) items_process = itemtypes[itemtype](embycursor, musiccursor, pdialog)
@ -113,19 +86,18 @@ class Items(object):
if process == "added": if process == "added":
processItems = itemlist
items_process.add_all(itemtype, itemlist) items_process.add_all(itemtype, itemlist)
elif process == "remove": elif process == "remove":
items_process.remove_all(itemtype, itemlist) items_process.remove_all(itemtype, itemlist)
else: else:
processItems = emby.getFullItems(itemlist) process_items = self.emby.getFullItems(itemlist)
items_process.process_all(itemtype, process, processItems, total) items_process.process_all(itemtype, process, process_items, total)
if musicconn is not None: if musicconn is not None:
# close connection for special types # close connection for special types
log.info("Updating music database.") log.info("updating music database")
musicconn.commit() musicconn.commit()
musiccursor.close() musiccursor.close()
return (True, update_videolibrary) return (True, update_videolibrary)

View file

@ -999,14 +999,11 @@ class ManualSync(LibrarySync):
def __init__(self): def __init__(self):
LibrarySync.__init__(self) LibrarySync.__init__(self)
def sync(self): def sync(self):
return self.fullSync(manualrun=True) return self.fullSync(manualrun=True)
def movies(self, embycursor, kodicursor, pdialog): def movies(self, embycursor, kodicursor, pdialog):
return Movies(embycursor, kodicursor, pdialog).compare_all() return Movies(embycursor, kodicursor, pdialog).compare_all()

View file

@ -78,11 +78,11 @@ class Items(object):
if self.pdialog and view: if self.pdialog and view:
self.pdialog.update(heading="Processing %s / %s items" % (view['name'], total)) self.pdialog.update(heading="Processing %s / %s items" % (view['name'], total))
action = self._get_func(item_type, "added") process = self._get_func(item_type, "added")
if view: if view:
action(items, total, view) process(items, total, view)
else: else:
action(items, total) process(items, total)
def process_all(self, item_type, action, items, total=None, view=None): def process_all(self, item_type, action, items, total=None, view=None):

View file

@ -4,12 +4,9 @@
import logging import logging
import urllib import urllib
from ntpath import dirname
from datetime import datetime
import api import api
import common import common
import downloadutils
import embydb_functions as embydb import embydb_functions as embydb
import kodidb_functions as kodidb import kodidb_functions as kodidb
from utils import window, settings, language as lang, catch_except from utils import window, settings, language as lang, catch_except
@ -20,12 +17,12 @@ log = logging.getLogger("EMBY."+__name__)
################################################################################################## ##################################################################################################
class Movies(common.Items): class Movies(common.Items):
def __init__(self, embycursor, kodicursor, pdialog=None): def __init__(self, embycursor, kodicursor, pdialog=None):
self.embycursor = embycursor self.embycursor = embycursor
self.emby_db = embydb.Embydb_Functions(self.embycursor) self.emby_db = embydb.Embydb_Functions(self.embycursor)
self.kodicursor = kodicursor self.kodicursor = kodicursor
@ -33,7 +30,7 @@ class Movies(common.Items):
self.pdialog = pdialog self.pdialog = pdialog
self.new_time = int(settings('newvideotime'))*1000 self.new_time = int(settings('newvideotime'))*1000
common.Items.__init__(self) common.Items.__init__(self)
def _get_func(self, item_type, action): def _get_func(self, item_type, action):
@ -62,7 +59,7 @@ class Movies(common.Items):
pdialog = self.pdialog pdialog = self.pdialog
views = self.emby_db.getView_byType('movies') views = self.emby_db.getView_byType('movies')
views += self.emby_db.getView_byType('mixed') views += self.emby_db.getView_byType('mixed')
log.info("Media folders: %s" % views) log.info("Media folders: %s", views)
try: try:
all_kodisets = dict(self.emby_db.get_checksum('BoxSet')) all_kodisets = dict(self.emby_db.get_checksum('BoxSet'))
@ -107,7 +104,7 @@ class Movies(common.Items):
# Only update if movie is not in Kodi or checksum is different # Only update if movie is not in Kodi or checksum is different
updatelist.append(itemid) updatelist.append(itemid)
log.info("Movies to update for %s: %s" % (viewName, updatelist)) log.info("Movies to update for %s: %s", viewName, updatelist)
embymovies = self.emby.getFullItems(updatelist) embymovies = self.emby.getFullItems(updatelist)
total = len(updatelist) total = len(updatelist)
del updatelist[:] del updatelist[:]
@ -137,7 +134,7 @@ class Movies(common.Items):
updatelist.append(itemid) updatelist.append(itemid)
embyboxsets.append(boxset) embyboxsets.append(boxset)
log.info("Boxsets to update: %s" % updatelist) log.info("Boxsets to update: %s", updatelist)
self.total = len(updatelist) self.total = len(updatelist)
if pdialog: if pdialog:
@ -158,14 +155,14 @@ class Movies(common.Items):
for kodimovie in all_kodimovies: for kodimovie in all_kodimovies:
if kodimovie not in all_embymoviesIds: if kodimovie not in all_embymoviesIds:
self.remove(kodimovie) self.remove(kodimovie)
else:
log.info("Movies compare finished.") log.info("Movies compare finished.")
for boxset in all_kodisets: for boxset in all_kodisets:
if boxset not in all_embyboxsetsIds: if boxset not in all_embyboxsetsIds:
self.remove(boxset) self.remove(boxset)
else:
log.info("Boxsets compare finished.") log.info("Boxsets compare finished.")
return True return True
@ -193,11 +190,11 @@ class Movies(common.Items):
movieid = emby_dbitem[0] movieid = emby_dbitem[0]
fileid = emby_dbitem[1] fileid = emby_dbitem[1]
pathid = emby_dbitem[2] pathid = emby_dbitem[2]
log.info("movieid: %s fileid: %s pathid: %s" % (movieid, fileid, pathid)) log.info("movieid: %s fileid: %s pathid: %s", movieid, fileid, pathid)
except TypeError: except TypeError:
update_item = False update_item = False
log.debug("movieid: %s not found." % itemid) log.debug("movieid: %s not found", itemid)
# movieid # movieid
kodicursor.execute("select coalesce(max(idMovie),0) from movie") kodicursor.execute("select coalesce(max(idMovie),0) from movie")
movieid = kodicursor.fetchone()[0] + 1 movieid = kodicursor.fetchone()[0] + 1
@ -211,12 +208,12 @@ class Movies(common.Items):
except TypeError: except TypeError:
# item is not found, let's recreate it. # item is not found, let's recreate it.
update_item = False update_item = False
log.info("movieid: %s missing from Kodi, repairing the entry." % movieid) log.info("movieid: %s missing from Kodi, repairing the entry", movieid)
if not view: if not view:
# Get view tag from emby # Get view tag from emby
viewtag, viewid, mediatype = self.emby.getView_embyId(itemid) viewtag, viewid, mediatype = self.emby.getView_embyId(itemid)
log.debug("View tag found: %s" % viewtag) log.debug("View tag found: %s", viewtag)
else: else:
viewtag = view['name'] viewtag = view['name']
viewid = view['id'] viewid = view['id']
@ -270,16 +267,16 @@ class Movies(common.Items):
trailer = item['RemoteTrailers'][0]['Url'] trailer = item['RemoteTrailers'][0]['Url']
except (KeyError, IndexError): except (KeyError, IndexError):
trailer = None trailer = None
else: else:
try: try:
trailerId = trailer.rsplit('=', 1)[1] trailer_id = trailer.rsplit('=', 1)[1]
except IndexError: except IndexError:
log.info("Failed to process trailer: %s" % trailer) log.info("Failed to process trailer: %s", trailer)
trailer = None trailer = None
else: else:
trailer = "plugin://plugin.video.youtube/play/?video_id=%s" % trailerId trailer = "plugin://plugin.video.youtube/play/?video_id=%s" % trailer_id
##### GET THE FILE AND PATH ##### ##### GET THE FILE AND PATH #####
playurl = API.get_file_path() playurl = API.get_file_path()
@ -293,7 +290,7 @@ class Movies(common.Items):
# Direct paths is set the Kodi way # Direct paths is set the Kodi way
if not self.path_validation(playurl): if not self.path_validation(playurl):
return False return False
path = playurl.replace(filename, "") path = playurl.replace(filename, "")
window('emby_pathverified', value="true") window('emby_pathverified', value="true")
else: else:
@ -311,12 +308,12 @@ class Movies(common.Items):
##### UPDATE THE MOVIE ##### ##### UPDATE THE MOVIE #####
if update_item: if update_item:
log.info("UPDATE movie itemid: %s - Title: %s" % (itemid, title)) log.info("UPDATE movie itemid: %s - Title: %s", itemid, title)
# Update the movie entry # Update the movie entry
if self.kodi_version > 16: if self.kodi_version > 16:
query = ' '.join(( query = ' '.join((
"UPDATE movie", "UPDATE movie",
"SET c00 = ?, c01 = ?, c02 = ?, c03 = ?, c04 = ?, c05 = ?, c06 = ?,", "SET c00 = ?, c01 = ?, c02 = ?, c03 = ?, c04 = ?, c05 = ?, c06 = ?,",
"c07 = ?, c09 = ?, c10 = ?, c11 = ?, c12 = ?, c14 = ?, c15 = ?,", "c07 = ?, c09 = ?, c10 = ?, c11 = ?, c12 = ?, c14 = ?, c15 = ?,",
@ -324,11 +321,12 @@ class Movies(common.Items):
"WHERE idMovie = ?" "WHERE idMovie = ?"
)) ))
kodicursor.execute(query, (title, plot, shortplot, tagline, votecount, rating, kodicursor.execute(query, (title, plot, shortplot, tagline, votecount, rating,
writer, year, imdb, sorttitle, runtime, mpaa, genre, director, title, studio, writer, year, imdb, sorttitle, runtime, mpaa, genre,
trailer, country, year, movieid)) director, title, studio, trailer, country, year,
movieid))
else: else:
query = ' '.join(( query = ' '.join((
"UPDATE movie", "UPDATE movie",
"SET c00 = ?, c01 = ?, c02 = ?, c03 = ?, c04 = ?, c05 = ?, c06 = ?,", "SET c00 = ?, c01 = ?, c02 = ?, c03 = ?, c04 = ?, c05 = ?, c06 = ?,",
"c07 = ?, c09 = ?, c10 = ?, c11 = ?, c12 = ?, c14 = ?, c15 = ?,", "c07 = ?, c09 = ?, c10 = ?, c11 = ?, c12 = ?, c14 = ?, c15 = ?,",
@ -336,51 +334,52 @@ class Movies(common.Items):
"WHERE idMovie = ?" "WHERE idMovie = ?"
)) ))
kodicursor.execute(query, (title, plot, shortplot, tagline, votecount, rating, kodicursor.execute(query, (title, plot, shortplot, tagline, votecount, rating,
writer, year, imdb, sorttitle, runtime, mpaa, genre, director, title, studio, writer, year, imdb, sorttitle, runtime, mpaa, genre,
trailer, country, movieid)) director, title, studio, trailer, country, movieid))
# Update the checksum in emby table # Update the checksum in emby table
emby_db.updateReference(itemid, checksum) emby_db.updateReference(itemid, checksum)
##### OR ADD THE MOVIE ##### ##### OR ADD THE MOVIE #####
else: else:
log.info("ADD movie itemid: %s - Title: %s" % (itemid, title)) log.info("ADD movie itemid: %s - Title: %s", itemid, title)
# Add path # Add path
pathid = self.kodi_db.addPath(path) pathid = self.kodi_db.addPath(path)
# Add the file # Add the file
fileid = self.kodi_db.addFile(filename, pathid) fileid = self.kodi_db.addFile(filename, pathid)
# Create the movie entry # Create the movie entry
if self.kodi_version > 16: if self.kodi_version > 16:
query = ( query = (
''' '''
INSERT INTO movie( INSERT INTO movie(
idMovie, idFile, c00, c01, c02, c03, c04, c05, c06, c07, idMovie, idFile, c00, c01, c02, c03, c04, c05, c06, c07,
c09, c10, c11, c12, c14, c15, c16, c18, c19, c21, premiered) c09, c10, c11, c12, c14, c15, c16, c18, c19, c21, premiered)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
''' '''
) )
kodicursor.execute(query, (movieid, fileid, title, plot, shortplot, tagline, kodicursor.execute(query, (movieid, fileid, title, plot, shortplot, tagline,
votecount, rating, writer, year, imdb, sorttitle, runtime, mpaa, genre, votecount, rating, writer, year, imdb, sorttitle,
director, title, studio, trailer, country, year)) runtime, mpaa, genre, director, title, studio, trailer,
country, year))
else: else:
query = ( query = (
''' '''
INSERT INTO movie( INSERT INTO movie(
idMovie, idFile, c00, c01, c02, c03, c04, c05, c06, c07, idMovie, idFile, c00, c01, c02, c03, c04, c05, c06, c07,
c09, c10, c11, c12, c14, c15, c16, c18, c19, c21) c09, c10, c11, c12, c14, c15, c16, c18, c19, c21)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
''' '''
) )
kodicursor.execute(query, (movieid, fileid, title, plot, shortplot, tagline, kodicursor.execute(query, (movieid, fileid, title, plot, shortplot, tagline,
votecount, rating, writer, year, imdb, sorttitle, runtime, mpaa, genre, votecount, rating, writer, year, imdb, sorttitle,
director, title, studio, trailer, country)) runtime, mpaa, genre, director, title, studio, trailer,
country))
# Create the reference in emby table # Create the reference in emby table
emby_db.addReference(itemid, movieid, "Movie", "movie", fileid, pathid, None, checksum, viewid) emby_db.addReference(itemid, movieid, "Movie", "movie", fileid, pathid, None,
checksum, viewid)
# Update the path # Update the path
query = ' '.join(( query = ' '.join((
@ -399,7 +398,7 @@ class Movies(common.Items):
"WHERE idFile = ?" "WHERE idFile = ?"
)) ))
kodicursor.execute(query, (pathid, filename, dateadded, fileid)) kodicursor.execute(query, (pathid, filename, dateadded, fileid))
# Process countries # Process countries
if 'ProductionLocations' in item: if 'ProductionLocations' in item:
self.kodi_db.addCountries(movieid, item['ProductionLocations'], "movie") self.kodi_db.addCountries(movieid, item['ProductionLocations'], "movie")
@ -447,7 +446,7 @@ class Movies(common.Items):
# Process artwork # Process artwork
artwork.add_artwork(artwork.get_all_artwork(boxset), setid, "set", self.kodicursor) artwork.add_artwork(artwork.get_all_artwork(boxset), setid, "set", self.kodicursor)
# Process movies inside boxset # Process movies inside boxset
current_movies = emby_db.getItemId_byParentId(setid, "movie") current_movies = emby_db.getItemId_byParentId(setid, "movie")
process = [] process = []
@ -472,10 +471,10 @@ class Movies(common.Items):
try: try:
movieid = emby_dbitem[0] movieid = emby_dbitem[0]
except TypeError: except TypeError:
log.info("Failed to add: %s to boxset." % movie['Name']) log.info("Failed to add: %s to boxset", movie['Name'])
continue continue
log.info("New addition to boxset %s: %s" % (title, movie['Name'])) log.info("New addition to boxset %s: %s", title, movie['Name'])
self.kodi_db.assignBoxset(setid, movieid) self.kodi_db.assignBoxset(setid, movieid)
# Update emby reference # Update emby reference
emby_db.updateParentId(itemid, setid) emby_db.updateParentId(itemid, setid)
@ -486,7 +485,7 @@ class Movies(common.Items):
# Process removals from boxset # Process removals from boxset
for movie in process: for movie in process:
movieid = current[movie] movieid = current[movie]
log.info("Remove from boxset %s: %s" % (title, movieid)) log.info("Remove from boxset %s: %s", title, movieid)
self.kodi_db.removefromBoxset(movieid) self.kodi_db.removefromBoxset(movieid)
# Update emby reference # Update emby reference
emby_db.updateParentId(movie, None) emby_db.updateParentId(movie, None)
@ -499,7 +498,7 @@ class Movies(common.Items):
# Poster with progress bar # Poster with progress bar
emby_db = self.emby_db emby_db = self.emby_db
API = api.API(item) API = api.API(item)
# Get emby information # Get emby information
itemid = item['Id'] itemid = item['Id']
checksum = API.get_checksum() checksum = API.get_checksum()
@ -511,7 +510,7 @@ class Movies(common.Items):
try: try:
movieid = emby_dbitem[0] movieid = emby_dbitem[0]
fileid = emby_dbitem[1] fileid = emby_dbitem[1]
log.info("Update playstate for movie: %s fileid: %s" % (item['Name'], fileid)) log.info("Update playstate for movie: %s fileid: %s", item['Name'], fileid)
except TypeError: except TypeError:
return return
@ -527,7 +526,7 @@ class Movies(common.Items):
resume = API.adjust_resume(userdata['Resume']) resume = API.adjust_resume(userdata['Resume'])
total = round(float(runtime), 6) total = round(float(runtime), 6)
log.debug("%s New resume point: %s" % (itemid, resume)) log.debug("%s New resume point: %s", itemid, resume)
self.kodi_db.addPlaystate(fileid, resume, total, playcount, dateplayed) self.kodi_db.addPlaystate(fileid, resume, total, playcount, dateplayed)
emby_db.updateReference(itemid, checksum) emby_db.updateReference(itemid, checksum)
@ -543,7 +542,7 @@ class Movies(common.Items):
kodiid = emby_dbitem[0] kodiid = emby_dbitem[0]
fileid = emby_dbitem[1] fileid = emby_dbitem[1]
mediatype = emby_dbitem[4] mediatype = emby_dbitem[4]
log.info("Removing %sid: %s fileid: %s" % (mediatype, kodiid, fileid)) log.info("Removing %sid: %s fileid: %s", mediatype, kodiid, fileid)
except TypeError: except TypeError:
return return
@ -569,4 +568,4 @@ class Movies(common.Items):
kodicursor.execute("DELETE FROM sets WHERE idSet = ?", (kodiid,)) kodicursor.execute("DELETE FROM sets WHERE idSet = ?", (kodiid,))
log.info("Deleted %s %s from kodi database" % (mediatype, itemid)) log.info("Deleted %s %s from kodi database", mediatype, itemid)

View file

@ -3,13 +3,10 @@
################################################################################################## ##################################################################################################
import logging import logging
import urllib
from ntpath import dirname
from datetime import datetime from datetime import datetime
import api import api
import common import common
import downloadutils
import embydb_functions as embydb import embydb_functions as embydb
import kodidb_functions as kodidb import kodidb_functions as kodidb
import musicutils import musicutils
@ -21,12 +18,12 @@ log = logging.getLogger("EMBY."+__name__)
################################################################################################## ##################################################################################################
class Music(common.Items): class Music(common.Items):
def __init__(self, embycursor, kodicursor, pdialog=None): def __init__(self, embycursor, kodicursor, pdialog=None):
self.embycursor = embycursor self.embycursor = embycursor
self.emby_db = embydb.Embydb_Functions(self.embycursor) self.emby_db = embydb.Embydb_Functions(self.embycursor)
self.kodicursor = kodicursor self.kodicursor = kodicursor
@ -40,7 +37,7 @@ class Music(common.Items):
self.enableupdatesongrating = settings('enableUpdateSongRating') == "true" self.enableupdatesongrating = settings('enableUpdateSongRating') == "true"
self.userid = window('emby_currUser') self.userid = window('emby_currUser')
self.server = window('emby_server%s' % self.userid) self.server = window('emby_server%s' % self.userid)
common.Items.__init__(self) common.Items.__init__(self)
def _get_func(self, item_type, action): def _get_func(self, item_type, action):
@ -133,7 +130,7 @@ class Music(common.Items):
if all_kodisongs.get(itemid) != API.get_checksum(): if all_kodisongs.get(itemid) != API.get_checksum():
# Only update if songs is not in Kodi or checksum is different # Only update if songs is not in Kodi or checksum is different
updatelist.append(itemid) updatelist.append(itemid)
log.info("%s to update: %s" % (data_type, updatelist)) log.info("%s to update: %s", data_type, updatelist)
embyitems = self.emby.getFullItems(updatelist) embyitems = self.emby.getFullItems(updatelist)
self.total = len(updatelist) self.total = len(updatelist)
del updatelist[:] del updatelist[:]
@ -152,18 +149,20 @@ class Music(common.Items):
for kodiartist in all_kodiartists: for kodiartist in all_kodiartists:
if kodiartist not in all_embyartistsIds and all_kodiartists[kodiartist] is not None: if kodiartist not in all_embyartistsIds and all_kodiartists[kodiartist] is not None:
self.remove(kodiartist) self.remove(kodiartist)
else:
log.info("Artist compare finished.") log.info("Artist compare finished.")
for kodialbum in all_kodialbums: for kodialbum in all_kodialbums:
if kodialbum not in all_embyalbumsIds: if kodialbum not in all_embyalbumsIds:
self.remove(kodialbum) self.remove(kodialbum)
else:
log.info("Albums compare finished.") log.info("Albums compare finished.")
for kodisong in all_kodisongs: for kodisong in all_kodisongs:
if kodisong not in all_embysongsIds: if kodisong not in all_embysongsIds:
self.remove(kodisong) self.remove(kodisong)
else:
log.info("Songs compare finished.") log.info("Songs compare finished.")
return True return True
@ -176,7 +175,7 @@ class Music(common.Items):
self.added_album(all_albums['Items']) self.added_album(all_albums['Items'])
def added_album(self, items, total=None): def added_album(self, items, total=None):
update = True if not self.total else False update = True if not self.total else False
for item in super(Music, self).added(items, total, update): for item in super(Music, self).added(items, total, update):
@ -188,7 +187,7 @@ class Music(common.Items):
self.added_song(all_songs['Items']) self.added_song(all_songs['Items'])
def added_song(self, items, total=None): def added_song(self, items, total=None):
update = True if not self.total else False update = True if not self.total else False
for item in super(Music, self).added(items, total, update): for item in super(Music, self).added(items, total, update):
@ -212,7 +211,7 @@ class Music(common.Items):
artistid = emby_dbitem[0] artistid = emby_dbitem[0]
except TypeError: except TypeError:
update_item = False update_item = False
log.debug("artistid: %s not found." % itemid) log.debug("artistid: %s not found", itemid)
##### The artist details ##### ##### The artist details #####
lastScraped = datetime.now().strftime('%Y-%m-%d %H:%M:%S') lastScraped = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
@ -239,19 +238,18 @@ class Music(common.Items):
##### UPDATE THE ARTIST ##### ##### UPDATE THE ARTIST #####
if update_item: if update_item:
log.info("UPDATE artist itemid: %s - Name: %s" % (itemid, name)) log.info("UPDATE artist itemid: %s - Name: %s", itemid, name)
# Update the checksum in emby table # Update the checksum in emby table
emby_db.updateReference(itemid, checksum) emby_db.updateReference(itemid, checksum)
##### OR ADD THE ARTIST ##### ##### OR ADD THE ARTIST #####
else: else:
log.info("ADD artist itemid: %s - Name: %s" % (itemid, name)) log.info("ADD artist itemid: %s - Name: %s", itemid, name)
# safety checks: It looks like Emby supports the same artist multiple times. # safety checks: It looks like Emby supports the same artist multiple times.
# Kodi doesn't allow that. In case that happens we just merge the artist entries. # Kodi doesn't allow that. In case that happens we just merge the artist entries.
artistid = self.kodi_db.addArtist(name, musicBrainzId) artistid = self.kodi_db.addArtist(name, musicBrainzId)
# Create the reference in emby table # Create the reference in emby table
emby_db.addReference(itemid, artistid, artisttype, "artist", checksum=checksum) emby_db.addReference(itemid, artistid, artisttype, "artist", checksum=checksum)
# Process the artist # Process the artist
if self.kodi_version in (16, 17): if self.kodi_version in (16, 17):
@ -272,8 +270,7 @@ class Music(common.Items):
"WHERE idArtist = ?" "WHERE idArtist = ?"
)) ))
kodicursor.execute(query, (genres, bio, thumb, fanart, lastScraped, kodicursor.execute(query, (genres, bio, thumb, fanart, lastScraped,
dateadded, artistid)) dateadded, artistid))
# Update artwork # Update artwork
artwork.add_artwork(artworks, artistid, "artist", kodicursor) artwork.add_artwork(artworks, artistid, "artist", kodicursor)
@ -296,7 +293,7 @@ class Music(common.Items):
albumid = emby_dbitem[0] albumid = emby_dbitem[0]
except TypeError: except TypeError:
update_item = False update_item = False
log.debug("albumid: %s not found." % itemid) log.debug("albumid: %s not found", itemid)
##### The album details ##### ##### The album details #####
lastScraped = datetime.now().strftime('%Y-%m-%d %H:%M:%S') lastScraped = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
@ -325,13 +322,13 @@ class Music(common.Items):
##### UPDATE THE ALBUM ##### ##### UPDATE THE ALBUM #####
if update_item: if update_item:
log.info("UPDATE album itemid: %s - Name: %s" % (itemid, name)) log.info("UPDATE album itemid: %s - Name: %s", itemid, name)
# Update the checksum in emby table # Update the checksum in emby table
emby_db.updateReference(itemid, checksum) emby_db.updateReference(itemid, checksum)
##### OR ADD THE ALBUM ##### ##### OR ADD THE ALBUM #####
else: else:
log.info("ADD album itemid: %s - Name: %s" % (itemid, name)) log.info("ADD album itemid: %s - Name: %s", itemid, name)
# safety checks: It looks like Emby supports the same artist multiple times. # safety checks: It looks like Emby supports the same artist multiple times.
# Kodi doesn't allow that. In case that happens we just merge the artist entries. # Kodi doesn't allow that. In case that happens we just merge the artist entries.
albumid = self.kodi_db.addAlbum(name, musicBrainzId) albumid = self.kodi_db.addAlbum(name, musicBrainzId)
@ -350,7 +347,7 @@ class Music(common.Items):
"WHERE idAlbum = ?" "WHERE idAlbum = ?"
)) ))
kodicursor.execute(query, (artistname, year, genre, bio, thumb, rating, lastScraped, kodicursor.execute(query, (artistname, year, genre, bio, thumb, rating, lastScraped,
"album", albumid)) "album", albumid))
elif self.kodi_version == 16: elif self.kodi_version == 16:
# Kodi Jarvis # Kodi Jarvis
query = ' '.join(( query = ' '.join((
@ -361,7 +358,7 @@ class Music(common.Items):
"WHERE idAlbum = ?" "WHERE idAlbum = ?"
)) ))
kodicursor.execute(query, (artistname, year, genre, bio, thumb, rating, lastScraped, kodicursor.execute(query, (artistname, year, genre, bio, thumb, rating, lastScraped,
"album", albumid)) "album", albumid))
elif self.kodi_version == 15: elif self.kodi_version == 15:
# Kodi Isengard # Kodi Isengard
query = ' '.join(( query = ' '.join((
@ -372,7 +369,7 @@ class Music(common.Items):
"WHERE idAlbum = ?" "WHERE idAlbum = ?"
)) ))
kodicursor.execute(query, (artistname, year, genre, bio, thumb, rating, lastScraped, kodicursor.execute(query, (artistname, year, genre, bio, thumb, rating, lastScraped,
dateadded, "album", albumid)) dateadded, "album", albumid))
else: else:
# Kodi Helix # Kodi Helix
query = ' '.join(( query = ' '.join((
@ -383,7 +380,7 @@ class Music(common.Items):
"WHERE idAlbum = ?" "WHERE idAlbum = ?"
)) ))
kodicursor.execute(query, (artistname, year, genre, bio, thumb, rating, lastScraped, kodicursor.execute(query, (artistname, year, genre, bio, thumb, rating, lastScraped,
dateadded, albumid)) dateadded, albumid))
# Assign main artists to album # Assign main artists to album
for artist in item['AlbumArtists']: for artist in item['AlbumArtists']:
@ -458,8 +455,8 @@ class Music(common.Items):
albumid = emby_dbitem[3] albumid = emby_dbitem[3]
except TypeError: except TypeError:
update_item = False update_item = False
log.debug("songid: %s not found." % itemid) log.debug("songid: %s not found", itemid)
##### The song details ##### ##### The song details #####
checksum = API.get_checksum() checksum = API.get_checksum()
dateadded = API.get_date_created() dateadded = API.get_date_created()
@ -489,8 +486,8 @@ class Music(common.Items):
else: else:
hasEmbeddedCover = False hasEmbeddedCover = False
comment = API.get_overview() comment = API.get_overview()
##### GET THE FILE AND PATH ##### ##### GET THE FILE AND PATH #####
if self.directstream: if self.directstream:
path = "%s/emby/Audio/%s/" % (self.server, itemid) path = "%s/emby/Audio/%s/" % (self.server, itemid)
@ -512,21 +509,21 @@ class Music(common.Items):
# Direct paths is set the Kodi way # Direct paths is set the Kodi way
if not self.path_validation(playurl): if not self.path_validation(playurl):
return False return False
path = playurl.replace(filename, "") path = playurl.replace(filename, "")
window('emby_pathverified', value="true") window('emby_pathverified', value="true")
##### UPDATE THE SONG ##### ##### UPDATE THE SONG #####
if update_item: if update_item:
log.info("UPDATE song itemid: %s - Title: %s" % (itemid, title)) log.info("UPDATE song itemid: %s - Title: %s", itemid, title)
# Update path # Update path
query = "UPDATE path SET strPath = ? WHERE idPath = ?" query = "UPDATE path SET strPath = ? WHERE idPath = ?"
kodicursor.execute(query, (path, pathid)) kodicursor.execute(query, (path, pathid))
# Update the song entry # Update the song entry
query = ' '.join(( query = ' '.join((
"UPDATE song", "UPDATE song",
"SET idAlbum = ?, strArtists = ?, strGenres = ?, strTitle = ?, iTrack = ?,", "SET idAlbum = ?, strArtists = ?, strGenres = ?, strTitle = ?, iTrack = ?,",
"iDuration = ?, iYear = ?, strFilename = ?, iTimesPlayed = ?, lastplayed = ?,", "iDuration = ?, iYear = ?, strFilename = ?, iTimesPlayed = ?, lastplayed = ?,",
@ -534,15 +531,15 @@ class Music(common.Items):
"WHERE idSong = ?" "WHERE idSong = ?"
)) ))
kodicursor.execute(query, (albumid, artists, genre, title, track, duration, year, kodicursor.execute(query, (albumid, artists, genre, title, track, duration, year,
filename, playcount, dateplayed, rating, comment, songid)) filename, playcount, dateplayed, rating, comment, songid))
# Update the checksum in emby table # Update the checksum in emby table
emby_db.updateReference(itemid, checksum) emby_db.updateReference(itemid, checksum)
##### OR ADD THE SONG ##### ##### OR ADD THE SONG #####
else: else:
log.info("ADD song itemid: %s - Title: %s" % (itemid, title)) log.info("ADD song itemid: %s - Title: %s", itemid, title)
# Add path # Add path
pathid = self.kodi_db.addPath(path) pathid = self.kodi_db.addPath(path)
@ -554,12 +551,12 @@ class Music(common.Items):
# Verify if there's an album associated. # Verify if there's an album associated.
album_name = item.get('Album') album_name = item.get('Album')
if album_name: if album_name:
log.info("Creating virtual music album for song: %s." % itemid) log.info("Creating virtual music album for song: %s", itemid)
albumid = self.kodi_db.addAlbum(album_name, API.get_provider('MusicBrainzAlbum')) albumid = self.kodi_db.addAlbum(album_name, API.get_provider('MusicBrainzAlbum'))
emby_db.addReference("%salbum%s" % (itemid, albumid), albumid, "MusicAlbum_", "album") emby_db.addReference("%salbum%s" % (itemid, albumid), albumid, "MusicAlbum_", "album")
else: else:
# No album Id associated to the song. # No album Id associated to the song.
log.error("Song itemid: %s has no albumId associated." % itemid) log.error("Song itemid: %s has no albumId associated", itemid)
return False return False
except TypeError: except TypeError:
@ -571,7 +568,7 @@ class Music(common.Items):
emby_dbalbum = emby_db.getItem_byId(emby_albumId) emby_dbalbum = emby_db.getItem_byId(emby_albumId)
try: try:
albumid = emby_dbalbum[0] albumid = emby_dbalbum[0]
log.info("Found albumid: %s" % albumid) log.info("Found albumid: %s", albumid)
except TypeError: except TypeError:
# No album found, create a single's album # No album found, create a single's album
log.info("Failed to add album. Creating singles.") log.info("Failed to add album. Creating singles.")
@ -607,7 +604,7 @@ class Music(common.Items):
''' '''
) )
kodicursor.execute(query, (albumid, genre, year, dateadded)) kodicursor.execute(query, (albumid, genre, year, dateadded))
# Create the song entry # Create the song entry
kodicursor.execute("select coalesce(max(idSong),0) from song") kodicursor.execute("select coalesce(max(idSong),0) from song")
songid = kodicursor.fetchone()[0] + 1 songid = kodicursor.fetchone()[0] + 1
@ -622,24 +619,24 @@ class Music(common.Items):
''' '''
) )
kodicursor.execute(query, (songid, albumid, pathid, artists, genre, title, track, kodicursor.execute(query, (songid, albumid, pathid, artists, genre, title, track,
duration, year, filename, musicBrainzId, playcount, dateplayed, rating)) duration, year, filename, musicBrainzId, playcount,
dateplayed, rating))
# Create the reference in emby table # Create the reference in emby table
emby_db.addReference(itemid, songid, "Audio", "song", pathid=pathid, parentid=albumid, emby_db.addReference(itemid, songid, "Audio", "song", pathid=pathid, parentid=albumid,
checksum=checksum) checksum=checksum)
# Link song to album # Link song to album
query = ( query = (
''' '''
INSERT OR REPLACE INTO albuminfosong( INSERT OR REPLACE INTO albuminfosong(
idAlbumInfoSong, idAlbumInfo, iTrack, strTitle, iDuration) idAlbumInfoSong, idAlbumInfo, iTrack, strTitle, iDuration)
VALUES (?, ?, ?, ?, ?) VALUES (?, ?, ?, ?, ?)
''' '''
) )
kodicursor.execute(query, (songid, albumid, track, title, duration)) kodicursor.execute(query, (songid, albumid, track, title, duration))
# Link song to artists # Link song to artists
for index, artist in enumerate(item['ArtistItems']): for index, artist in enumerate(item['ArtistItems']):
@ -660,31 +657,31 @@ class Music(common.Items):
query = ( query = (
''' '''
INSERT OR REPLACE INTO song_artist(idArtist, idSong, idRole, iOrder, strArtist) INSERT OR REPLACE INTO song_artist(idArtist, idSong, idRole, iOrder, strArtist)
VALUES (?, ?, ?, ?, ?) VALUES (?, ?, ?, ?, ?)
''' '''
) )
kodicursor.execute(query, (artistid, songid, 1, index, artist_name)) kodicursor.execute(query, (artistid, songid, 1, index, artist_name))
# May want to look into only doing this once? # May want to look into only doing this once?
query = ( query = (
''' '''
INSERT OR REPLACE INTO role(idRole, strRole) INSERT OR REPLACE INTO role(idRole, strRole)
VALUES (?, ?) VALUES (?, ?)
''' '''
) )
kodicursor.execute(query, (1, 'Composer')) kodicursor.execute(query, (1, 'Composer'))
else: else:
query = ( query = (
''' '''
INSERT OR REPLACE INTO song_artist(idArtist, idSong, iOrder, strArtist) INSERT OR REPLACE INTO song_artist(idArtist, idSong, iOrder, strArtist)
VALUES (?, ?, ?, ?) VALUES (?, ?, ?, ?)
''' '''
) )
kodicursor.execute(query, (artistid, songid, index, artist_name)) kodicursor.execute(query, (artistid, songid, index, artist_name))
# Verify if album artist exists # Verify if album artist exists
album_artists = [] album_artists = []
for artist in item['AlbumArtists']: for artist in item['AlbumArtists']:
@ -720,38 +717,38 @@ class Music(common.Items):
''' '''
) )
kodicursor.execute(query, (artistid, item['Album'], 0)) kodicursor.execute(query, (artistid, item['Album'], 0))
else:
album_artists = " / ".join(album_artists)
query = ' '.join((
"SELECT strArtists", album_artists = " / ".join(album_artists)
"FROM album", query = ' '.join((
"WHERE idAlbum = ?"
)) "SELECT strArtists",
kodicursor.execute(query, (albumid,)) "FROM album",
result = kodicursor.fetchone() "WHERE idAlbum = ?"
if result and result[0] != album_artists: ))
# Field is empty kodicursor.execute(query, (albumid,))
if self.kodi_version in (16, 17): result = kodicursor.fetchone()
# Kodi Jarvis, Krypton if result and result[0] != album_artists:
query = "UPDATE album SET strArtists = ? WHERE idAlbum = ?" # Field is empty
kodicursor.execute(query, (album_artists, albumid)) if self.kodi_version in (16, 17):
elif self.kodi_version == 15: # Kodi Jarvis, Krypton
# Kodi Isengard query = "UPDATE album SET strArtists = ? WHERE idAlbum = ?"
query = "UPDATE album SET strArtists = ? WHERE idAlbum = ?" kodicursor.execute(query, (album_artists, albumid))
kodicursor.execute(query, (album_artists, albumid)) elif self.kodi_version == 15:
else: # Kodi Isengard
# Kodi Helix query = "UPDATE album SET strArtists = ? WHERE idAlbum = ?"
query = "UPDATE album SET strArtists = ? WHERE idAlbum = ?" kodicursor.execute(query, (album_artists, albumid))
kodicursor.execute(query, (album_artists, albumid)) else:
# Kodi Helix
query = "UPDATE album SET strArtists = ? WHERE idAlbum = ?"
kodicursor.execute(query, (album_artists, albumid))
# Add genres # Add genres
self.kodi_db.addMusicGenres(songid, genres, "song") self.kodi_db.addMusicGenres(songid, genres, "song")
# Update artwork # Update artwork
allart = artwork.get_all_artwork(item, parent_info=True) allart = artwork.get_all_artwork(item, parent_info=True)
if hasEmbeddedCover: if hasEmbeddedCover:
allart["Primary"] = "image://music@" + artwork.single_urlencode( playurl ) allart["Primary"] = "image://music@" + artwork.single_urlencode(playurl)
artwork.add_artwork(allart, songid, "song", kodicursor) artwork.add_artwork(allart, songid, "song", kodicursor)
if item.get('AlbumId') is None: if item.get('AlbumId') is None:
@ -771,7 +768,6 @@ class Music(common.Items):
itemid = item['Id'] itemid = item['Id']
checksum = API.get_checksum() checksum = API.get_checksum()
userdata = API.get_userdata() userdata = API.get_userdata()
runtime = API.get_runtime()
rating = userdata['UserRating'] rating = userdata['UserRating']
# Get Kodi information # Get Kodi information
@ -779,25 +775,25 @@ class Music(common.Items):
try: try:
kodiid = emby_dbitem[0] kodiid = emby_dbitem[0]
mediatype = emby_dbitem[4] mediatype = emby_dbitem[4]
log.info("Update playstate for %s: %s" % (mediatype, item['Name'])) log.info("Update playstate for %s: %s", mediatype, item['Name'])
except TypeError: except TypeError:
return return
if mediatype == "song": if mediatype == "song":
#should we ignore this item ? #should we ignore this item ?
#happens when userdata updated by ratings method #happens when userdata updated by ratings method
if window("ignore-update-%s" %itemid): if window("ignore-update-%s" %itemid):
window("ignore-update-%s" %itemid,clear=True) window("ignore-update-%s" %itemid,clear=True)
return return
# Process playstates # Process playstates
playcount = userdata['PlayCount'] playcount = userdata['PlayCount']
dateplayed = userdata['LastPlayedDate'] dateplayed = userdata['LastPlayedDate']
#process item ratings #process item ratings
rating, comment, hasEmbeddedCover = musicutils.getAdditionalSongTags(itemid, rating, API, kodicursor, emby_db, self.enableimportsongrating, self.enableexportsongrating, self.enableupdatesongrating) rating, comment, hasEmbeddedCover = musicutils.getAdditionalSongTags(itemid, rating, API, kodicursor, emby_db, self.enableimportsongrating, self.enableexportsongrating, self.enableupdatesongrating)
query = "UPDATE song SET iTimesPlayed = ?, lastplayed = ?, rating = ? WHERE idSong = ?" query = "UPDATE song SET iTimesPlayed = ?, lastplayed = ?, rating = ? WHERE idSong = ?"
kodicursor.execute(query, (playcount, dateplayed, rating, kodiid)) kodicursor.execute(query, (playcount, dateplayed, rating, kodiid))
@ -806,7 +802,7 @@ class Music(common.Items):
if self.kodi_version >= 17: if self.kodi_version >= 17:
query = "UPDATE album SET fRating = ? WHERE idAlbum = ?" query = "UPDATE album SET fRating = ? WHERE idAlbum = ?"
else: else:
query = "UPDATE album SET iRating = ? WHERE idAlbum = ?" query = "UPDATE album SET iRating = ? WHERE idAlbum = ?"
kodicursor.execute(query, (rating, kodiid)) kodicursor.execute(query, (rating, kodiid))
emby_db.updateReference(itemid, checksum) emby_db.updateReference(itemid, checksum)
@ -814,14 +810,12 @@ class Music(common.Items):
def remove(self, itemid): def remove(self, itemid):
# Remove kodiid, fileid, pathid, emby reference # Remove kodiid, fileid, pathid, emby reference
emby_db = self.emby_db emby_db = self.emby_db
kodicursor = self.kodicursor
artwork = self.artwork
emby_dbitem = emby_db.getItem_byId(itemid) emby_dbitem = emby_db.getItem_byId(itemid)
try: try:
kodiid = emby_dbitem[0] kodiid = emby_dbitem[0]
mediatype = emby_dbitem[4] mediatype = emby_dbitem[4]
log.info("Removing %s kodiid: %s" % (mediatype, kodiid)) log.info("Removing %s kodiid: %s", mediatype, kodiid)
except TypeError: except TypeError:
return return
@ -837,7 +831,7 @@ class Music(common.Items):
# Delete song # Delete song
self.removeSong(kodiid) self.removeSong(kodiid)
# This should only address single song scenario, where server doesn't actually # This should only address single song scenario, where server doesn't actually
# create an album for the song. # create an album for the song.
emby_db.removeWildItem(itemid) emby_db.removeWildItem(itemid)
for item in emby_db.getItem_byWildId(itemid): for item in emby_db.getItem_byWildId(itemid):

View file

@ -4,15 +4,12 @@
import logging import logging
import urllib import urllib
from ntpath import dirname
from datetime import datetime
import api import api
import common import common
import downloadutils
import embydb_functions as embydb import embydb_functions as embydb
import kodidb_functions as kodidb import kodidb_functions as kodidb
from utils import window, settings, language as lang, catch_except from utils import window, language as lang, catch_except
################################################################################################## ##################################################################################################
@ -23,15 +20,15 @@ log = logging.getLogger("EMBY."+__name__)
class MusicVideos(common.Items): class MusicVideos(common.Items):
def __init__(self, embycursor, kodicursor, pdialog=None): def __init__(self, embycursor, kodicursor, pdialog=None):
self.embycursor = embycursor self.embycursor = embycursor
self.emby_db = embydb.Embydb_Functions(self.embycursor) self.emby_db = embydb.Embydb_Functions(self.embycursor)
self.kodicursor = kodicursor self.kodicursor = kodicursor
self.kodi_db = kodidb.Kodidb_Functions(self.kodicursor) self.kodi_db = kodidb.Kodidb_Functions(self.kodicursor)
self.pdialog = pdialog self.pdialog = pdialog
common.Items.__init__(self) common.Items.__init__(self)
def _get_func(self, item_type, action): def _get_func(self, item_type, action):
@ -53,7 +50,7 @@ class MusicVideos(common.Items):
pdialog = self.pdialog pdialog = self.pdialog
# Pull the list of musicvideos in Kodi # Pull the list of musicvideos in Kodi
views = self.emby_db.getView_byType('musicvideos') views = self.emby_db.getView_byType('musicvideos')
log.info("Media folders: %s" % views) log.info("Media folders: %s", views)
try: try:
all_kodimvideos = dict(self.emby_db.get_checksum('MusicVideo')) all_kodimvideos = dict(self.emby_db.get_checksum('MusicVideo'))
@ -92,7 +89,7 @@ class MusicVideos(common.Items):
# Only update if musicvideo is not in Kodi or checksum is different # Only update if musicvideo is not in Kodi or checksum is different
updatelist.append(itemid) updatelist.append(itemid)
log.info("MusicVideos to update for %s: %s" % (viewName, updatelist)) log.info("MusicVideos to update for %s: %s", viewName, updatelist)
embymvideos = self.emby.getFullItems(updatelist) embymvideos = self.emby.getFullItems(updatelist)
self.total = len(updatelist) self.total = len(updatelist)
del updatelist[:] del updatelist[:]
@ -116,9 +113,8 @@ class MusicVideos(common.Items):
for kodimvideo in all_kodimvideos: for kodimvideo in all_kodimvideos:
if kodimvideo not in all_embymvideosIds: if kodimvideo not in all_embymvideosIds:
self.remove(kodimvideo) self.remove(kodimvideo)
else:
log.info("MusicVideos compare finished.")
log.info("MusicVideos compare finished.")
return True return True
@ -144,11 +140,11 @@ class MusicVideos(common.Items):
mvideoid = emby_dbitem[0] mvideoid = emby_dbitem[0]
fileid = emby_dbitem[1] fileid = emby_dbitem[1]
pathid = emby_dbitem[2] pathid = emby_dbitem[2]
log.info("mvideoid: %s fileid: %s pathid: %s" % (mvideoid, fileid, pathid)) log.info("mvideoid: %s fileid: %s pathid: %s", mvideoid, fileid, pathid)
except TypeError: except TypeError:
update_item = False update_item = False
log.debug("mvideoid: %s not found." % itemid) log.debug("mvideoid: %s not found", itemid)
# mvideoid # mvideoid
kodicursor.execute("select coalesce(max(idMVideo),0) from musicvideo") kodicursor.execute("select coalesce(max(idMVideo),0) from musicvideo")
mvideoid = kodicursor.fetchone()[0] + 1 mvideoid = kodicursor.fetchone()[0] + 1
@ -162,12 +158,12 @@ class MusicVideos(common.Items):
except TypeError: except TypeError:
# item is not found, let's recreate it. # item is not found, let's recreate it.
update_item = False update_item = False
log.info("mvideoid: %s missing from Kodi, repairing the entry." % mvideoid) log.info("mvideoid: %s missing from Kodi, repairing the entry.", mvideoid)
if not view: if not view:
# Get view tag from emby # Get view tag from emby
viewtag, viewid, mediatype = self.emby.getView_embyId(itemid) viewtag, viewid, mediatype = self.emby.getView_embyId(itemid)
log.debug("View tag found: %s" % viewtag) log.debug("View tag found: %s", viewtag)
else: else:
viewtag = view['name'] viewtag = view['name']
viewid = view['id'] viewid = view['id']
@ -194,7 +190,7 @@ class MusicVideos(common.Items):
people = API.get_people() people = API.get_people()
director = " / ".join(people['Director']) director = " / ".join(people['Director'])
##### GET THE FILE AND PATH ##### ##### GET THE FILE AND PATH #####
playurl = API.get_file_path() playurl = API.get_file_path()
@ -208,7 +204,7 @@ class MusicVideos(common.Items):
# Direct paths is set the Kodi way # Direct paths is set the Kodi way
if not self.path_validation(playurl): if not self.path_validation(playurl):
return False return False
path = playurl.replace(filename, "") path = playurl.replace(filename, "")
window('emby_pathverified', value="true") window('emby_pathverified', value="true")
else: else:
@ -226,8 +222,8 @@ class MusicVideos(common.Items):
##### UPDATE THE MUSIC VIDEO ##### ##### UPDATE THE MUSIC VIDEO #####
if update_item: if update_item:
log.info("UPDATE mvideo itemid: %s - Title: %s" % (itemid, title)) log.info("UPDATE mvideo itemid: %s - Title: %s", itemid, title)
# Update path # Update path
query = "UPDATE path SET strPath = ? WHERE idPath = ?" query = "UPDATE path SET strPath = ? WHERE idPath = ?"
kodicursor.execute(query, (path, pathid)) kodicursor.execute(query, (path, pathid))
@ -238,22 +234,21 @@ class MusicVideos(common.Items):
# Update the music video entry # Update the music video entry
query = ' '.join(( query = ' '.join((
"UPDATE musicvideo", "UPDATE musicvideo",
"SET c00 = ?, c04 = ?, c05 = ?, c06 = ?, c07 = ?, c08 = ?, c09 = ?, c10 = ?,", "SET c00 = ?, c04 = ?, c05 = ?, c06 = ?, c07 = ?, c08 = ?, c09 = ?, c10 = ?,",
"c11 = ?, c12 = ?" "c11 = ?, c12 = ?"
"WHERE idMVideo = ?" "WHERE idMVideo = ?"
)) ))
kodicursor.execute(query, (title, runtime, director, studio, year, plot, album, kodicursor.execute(query, (title, runtime, director, studio, year, plot, album,
artist, genre, track, mvideoid)) artist, genre, track, mvideoid))
# Update the checksum in emby table # Update the checksum in emby table
emby_db.updateReference(itemid, checksum) emby_db.updateReference(itemid, checksum)
##### OR ADD THE MUSIC VIDEO ##### ##### OR ADD THE MUSIC VIDEO #####
else: else:
log.info("ADD mvideo itemid: %s - Title: %s" % (itemid, title)) log.info("ADD mvideo itemid: %s - Title: %s", itemid, title)
# Add path # Add path
query = ' '.join(( query = ' '.join((
@ -289,7 +284,7 @@ class MusicVideos(common.Items):
''' '''
) )
kodicursor.execute(query, (fileid, pathid, filename, dateadded)) kodicursor.execute(query, (fileid, pathid, filename, dateadded))
# Create the musicvideo entry # Create the musicvideo entry
query = ( query = (
''' '''
@ -300,13 +295,12 @@ class MusicVideos(common.Items):
''' '''
) )
kodicursor.execute(query, (mvideoid, fileid, title, runtime, director, studio, kodicursor.execute(query, (mvideoid, fileid, title, runtime, director, studio,
year, plot, album, artist, genre, track)) year, plot, album, artist, genre, track))
# Create the reference in emby table # Create the reference in emby table
emby_db.addReference(itemid, mvideoid, "MusicVideo", "musicvideo", fileid, pathid, emby_db.addReference(itemid, mvideoid, "MusicVideo", "musicvideo", fileid, pathid,
checksum=checksum, mediafolderid=viewid) checksum=checksum, mediafolderid=viewid)
# Process cast # Process cast
people = item['People'] people = item['People']
artists = item['ArtistItems'] artists = item['ArtistItems']
@ -342,7 +336,7 @@ class MusicVideos(common.Items):
# Poster with progress bar # Poster with progress bar
emby_db = self.emby_db emby_db = self.emby_db
API = api.API(item) API = api.API(item)
# Get emby information # Get emby information
itemid = item['Id'] itemid = item['Id']
checksum = API.get_checksum() checksum = API.get_checksum()
@ -354,9 +348,7 @@ class MusicVideos(common.Items):
try: try:
mvideoid = emby_dbitem[0] mvideoid = emby_dbitem[0]
fileid = emby_dbitem[1] fileid = emby_dbitem[1]
log.info( log.info("Update playstate for musicvideo: %s fileid: %s", item['Name'], fileid)
"Update playstate for musicvideo: %s fileid: %s"
% (item['Name'], fileid))
except TypeError: except TypeError:
return return
@ -386,7 +378,7 @@ class MusicVideos(common.Items):
mvideoid = emby_dbitem[0] mvideoid = emby_dbitem[0]
fileid = emby_dbitem[1] fileid = emby_dbitem[1]
pathid = emby_dbitem[2] pathid = emby_dbitem[2]
log.info("Removing mvideoid: %s fileid: %s" % (mvideoid, fileid, pathid)) log.info("Removing mvideoid: %s fileid: %s pathid: %s", mvideoid, fileid, pathid)
except TypeError: except TypeError:
return return
@ -400,7 +392,7 @@ class MusicVideos(common.Items):
)) ))
kodicursor.execute(query, (mvideoid,)) kodicursor.execute(query, (mvideoid,))
for row in kodicursor.fetchall(): for row in kodicursor.fetchall():
url = row[0] url = row[0]
imagetype = row[1] imagetype = row[1]
if imagetype in ("poster", "fanart"): if imagetype in ("poster", "fanart"):
@ -412,4 +404,4 @@ class MusicVideos(common.Items):
kodicursor.execute("DELETE FROM path WHERE idPath = ?", (pathid,)) kodicursor.execute("DELETE FROM path WHERE idPath = ?", (pathid,))
self.embycursor.execute("DELETE FROM emby WHERE emby_id = ?", (itemid,)) self.embycursor.execute("DELETE FROM emby WHERE emby_id = ?", (itemid,))
log.info("Deleted musicvideo %s from kodi database" % itemid) log.info("Deleted musicvideo %s from kodi database", itemid)

View file

@ -5,11 +5,9 @@
import logging import logging
import urllib import urllib
from ntpath import dirname from ntpath import dirname
from datetime import datetime
import api import api
import common import common
import downloadutils
import embydb_functions as embydb import embydb_functions as embydb
import kodidb_functions as kodidb import kodidb_functions as kodidb
from utils import window, settings, language as lang, catch_except from utils import window, settings, language as lang, catch_except
@ -20,12 +18,12 @@ log = logging.getLogger("EMBY."+__name__)
################################################################################################## ##################################################################################################
class TVShows(common.Items): class TVShows(common.Items):
def __init__(self, embycursor, kodicursor, pdialog=None): def __init__(self, embycursor, kodicursor, pdialog=None):
self.embycursor = embycursor self.embycursor = embycursor
self.emby_db = embydb.Embydb_Functions(self.embycursor) self.emby_db = embydb.Embydb_Functions(self.embycursor)
self.kodicursor = kodicursor self.kodicursor = kodicursor
@ -33,7 +31,7 @@ class TVShows(common.Items):
self.pdialog = pdialog self.pdialog = pdialog
self.new_time = int(settings('newvideotime'))*1000 self.new_time = int(settings('newvideotime'))*1000
common.Items.__init__(self) common.Items.__init__(self)
def _get_func(self, item_type, action): def _get_func(self, item_type, action):
@ -69,7 +67,7 @@ class TVShows(common.Items):
pdialog = self.pdialog pdialog = self.pdialog
views = self.emby_db.getView_byType('tvshows') views = self.emby_db.getView_byType('tvshows')
views += self.emby_db.getView_byType('mixed') views += self.emby_db.getView_byType('mixed')
log.info("Media folders: %s" % views) log.info("Media folders: %s", views)
# Pull the list of tvshows and episodes in Kodi # Pull the list of tvshows and episodes in Kodi
try: try:
@ -118,7 +116,7 @@ class TVShows(common.Items):
# Only update if movie is not in Kodi or checksum is different # Only update if movie is not in Kodi or checksum is different
updatelist.append(itemid) updatelist.append(itemid)
log.info("TVShows to update for %s: %s" % (viewName, updatelist)) log.info("TVShows to update for %s: %s", viewName, updatelist)
embytvshows = self.emby.getFullItems(updatelist) embytvshows = self.emby.getFullItems(updatelist)
self.total = len(updatelist) self.total = len(updatelist)
del updatelist[:] del updatelist[:]
@ -137,7 +135,7 @@ class TVShows(common.Items):
title = embytvshow['Name'] title = embytvshow['Name']
all_embytvshowsIds.add(itemid) all_embytvshowsIds.add(itemid)
self.update_pdialog() self.update_pdialog()
self.add_update(embytvshow, view) self.add_update(embytvshow, view)
self.count += 1 self.count += 1
@ -164,7 +162,7 @@ class TVShows(common.Items):
# Only update if movie is not in Kodi or checksum is different # Only update if movie is not in Kodi or checksum is different
updatelist.append(itemid) updatelist.append(itemid)
log.info("Episodes to update for %s: %s" % (viewName, updatelist)) log.info("Episodes to update for %s: %s", viewName, updatelist)
embyepisodes = self.emby.getFullItems(updatelist) embyepisodes = self.emby.getFullItems(updatelist)
self.total = len(updatelist) self.total = len(updatelist)
del updatelist[:] del updatelist[:]
@ -181,19 +179,19 @@ class TVShows(common.Items):
##### PROCESS DELETES ##### ##### PROCESS DELETES #####
log.info("all_embytvshowsIds = %s " % all_embytvshowsIds) log.info("all_embytvshowsIds = %s ", all_embytvshowsIds)
for koditvshow in all_koditvshows: for koditvshow in all_koditvshows:
if koditvshow not in all_embytvshowsIds: if koditvshow not in all_embytvshowsIds:
self.remove(koditvshow) self.remove(koditvshow)
else:
log.info("TVShows compare finished.") log.info("TVShows compare finished.")
for kodiepisode in all_kodiepisodes: for kodiepisode in all_kodiepisodes:
if kodiepisode not in all_embyepisodesIds: if kodiepisode not in all_embyepisodesIds:
self.remove(kodiepisode) self.remove(kodiepisode)
else:
log.info("Episodes compare finished.") log.info("Episodes compare finished.")
return True return True
@ -207,7 +205,7 @@ class TVShows(common.Items):
self.added_episode(all_episodes['Items']) self.added_episode(all_episodes['Items'])
def added_season(self, items, total=None, view=None): def added_season(self, items, total=None, view=None):
update = True if not self.total else False update = True if not self.total else False
for item in super(TVShows, self).added(items, total, update): for item in super(TVShows, self).added(items, total, update):
@ -238,7 +236,7 @@ class TVShows(common.Items):
API = api.API(item) API = api.API(item)
if settings('syncEmptyShows') == "false" and not item.get('RecursiveItemCount'): if settings('syncEmptyShows') == "false" and not item.get('RecursiveItemCount'):
log.info("Skipping empty show: %s" % item['Name']) log.info("Skipping empty show: %s", item['Name'])
return return
# If the item already exist in the local Kodi DB we'll perform a full item update # If the item already exist in the local Kodi DB we'll perform a full item update
# If the item doesn't exist, we'll add it to the database # If the item doesn't exist, we'll add it to the database
@ -249,11 +247,11 @@ class TVShows(common.Items):
try: try:
showid = emby_dbitem[0] showid = emby_dbitem[0]
pathid = emby_dbitem[2] pathid = emby_dbitem[2]
log.info("showid: %s pathid: %s" % (showid, pathid)) log.info("showid: %s pathid: %s", showid, pathid)
except TypeError: except TypeError:
update_item = False update_item = False
log.debug("showid: %s not found." % itemid) log.debug("showid: %s not found", itemid)
kodicursor.execute("select coalesce(max(idShow),0) from tvshow") kodicursor.execute("select coalesce(max(idShow),0) from tvshow")
showid = kodicursor.fetchone()[0] + 1 showid = kodicursor.fetchone()[0] + 1
@ -266,7 +264,7 @@ class TVShows(common.Items):
except TypeError: except TypeError:
# item is not found, let's recreate it. # item is not found, let's recreate it.
update_item = False update_item = False
log.info("showid: %s missing from Kodi, repairing the entry." % showid) log.info("showid: %s missing from Kodi, repairing the entry", showid)
# Force re-add episodes after the show is re-created. # Force re-add episodes after the show is re-created.
force_episodes = True force_episodes = True
@ -274,17 +272,14 @@ class TVShows(common.Items):
if view is None: if view is None:
# Get view tag from emby # Get view tag from emby
viewtag, viewid, mediatype = emby.getView_embyId(itemid) viewtag, viewid, mediatype = emby.getView_embyId(itemid)
log.debug("View tag found: %s" % viewtag) log.debug("View tag found: %s", viewtag)
else: else:
viewtag = view['name'] viewtag = view['name']
viewid = view['id'] viewid = view['id']
# fileId information # fileId information
checksum = API.get_checksum() checksum = API.get_checksum()
dateadded = API.get_date_created()
userdata = API.get_userdata() userdata = API.get_userdata()
playcount = userdata['PlayCount']
dateplayed = userdata['LastPlayedDate']
# item details # item details
genres = item['Genres'] genres = item['Genres']
@ -314,13 +309,13 @@ class TVShows(common.Items):
emby_other_item = emby_db.getItem_byId(emby_other[0]) emby_other_item = emby_db.getItem_byId(emby_other[0])
showid = emby_other_item[0] showid = emby_other_item[0]
pathid = emby_other_item[2] pathid = emby_other_item[2]
log.info("showid: %s pathid: %s" % (showid, pathid)) log.info("showid: %s pathid: %s", showid, pathid)
# Create the reference in emby table # Create the reference in emby table
emby_db.addReference(itemid, showid, "Series", "tvshow", pathid=pathid, emby_db.addReference(itemid, showid, "Series", "tvshow", pathid=pathid,
checksum=checksum, mediafolderid=viewid) checksum=checksum, mediafolderid=viewid)
update_item = True update_item = True
##### GET THE FILE AND PATH ##### ##### GET THE FILE AND PATH #####
playurl = API.get_file_path() playurl = API.get_file_path()
@ -347,26 +342,26 @@ class TVShows(common.Items):
##### UPDATE THE TVSHOW ##### ##### UPDATE THE TVSHOW #####
if update_item: if update_item:
log.info("UPDATE tvshow itemid: %s - Title: %s" % (itemid, title)) log.info("UPDATE tvshow itemid: %s - Title: %s", itemid, title)
# Update the tvshow entry # Update the tvshow entry
query = ' '.join(( query = ' '.join((
"UPDATE tvshow", "UPDATE tvshow",
"SET c00 = ?, c01 = ?, c04 = ?, c05 = ?, c08 = ?, c09 = ?,", "SET c00 = ?, c01 = ?, c04 = ?, c05 = ?, c08 = ?, c09 = ?,",
"c12 = ?, c13 = ?, c14 = ?, c15 = ?", "c12 = ?, c13 = ?, c14 = ?, c15 = ?",
"WHERE idShow = ?" "WHERE idShow = ?"
)) ))
kodicursor.execute(query, (title, plot, rating, premieredate, genre, title, kodicursor.execute(query, (title, plot, rating, premieredate, genre, title,
tvdb, mpaa, studio, sorttitle, showid)) tvdb, mpaa, studio, sorttitle, showid))
# Update the checksum in emby table # Update the checksum in emby table
emby_db.updateReference(itemid, checksum) emby_db.updateReference(itemid, checksum)
##### OR ADD THE TVSHOW ##### ##### OR ADD THE TVSHOW #####
else: else:
log.info("ADD tvshow itemid: %s - Title: %s" % (itemid, title)) log.info("ADD tvshow itemid: %s - Title: %s", itemid, title)
# Add top path # Add top path
toppathid = self.kodi_db.addPath(toplevelpath) toppathid = self.kodi_db.addPath(toplevelpath)
query = ' '.join(( query = ' '.join((
@ -376,21 +371,20 @@ class TVShows(common.Items):
"WHERE idPath = ?" "WHERE idPath = ?"
)) ))
kodicursor.execute(query, (toplevelpath, "tvshows", "metadata.local", 1, toppathid)) kodicursor.execute(query, (toplevelpath, "tvshows", "metadata.local", 1, toppathid))
# Add path # Add path
pathid = self.kodi_db.addPath(path) pathid = self.kodi_db.addPath(path)
# Create the tvshow entry # Create the tvshow entry
query = ( query = (
''' '''
INSERT INTO tvshow( INSERT INTO tvshow(idShow, c00, c01, c04, c05, c08, c09, c12, c13, c14, c15)
idShow, c00, c01, c04, c05, c08, c09, c12, c13, c14, c15)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
''' '''
) )
kodicursor.execute(query, (showid, title, plot, rating, premieredate, genre, kodicursor.execute(query, (showid, title, plot, rating, premieredate, genre,
title, tvdb, mpaa, studio, sorttitle)) title, tvdb, mpaa, studio, sorttitle))
# Link the path # Link the path
query = "INSERT INTO tvshowlinkpath(idShow, idPath) values(?, ?)" query = "INSERT INTO tvshowlinkpath(idShow, idPath) values(?, ?)"
@ -398,7 +392,7 @@ class TVShows(common.Items):
# Create the reference in emby table # Create the reference in emby table
emby_db.addReference(itemid, showid, "Series", "tvshow", pathid=pathid, emby_db.addReference(itemid, showid, "Series", "tvshow", pathid=pathid,
checksum=checksum, mediafolderid=viewid) checksum=checksum, mediafolderid=viewid)
# Update the path # Update the path
query = ' '.join(( query = ' '.join((
@ -408,7 +402,7 @@ class TVShows(common.Items):
"WHERE idPath = ?" "WHERE idPath = ?"
)) ))
kodicursor.execute(query, (path, None, None, 1, pathid)) kodicursor.execute(query, (path, None, None, 1, pathid))
# Process cast # Process cast
people = artwork.get_people_artwork(item['People']) people = artwork.get_people_artwork(item['People'])
self.kodi_db.addPeople(showid, people, "tvshow") self.kodi_db.addPeople(showid, people, "tvshow")
@ -436,7 +430,7 @@ class TVShows(common.Items):
if force_episodes: if force_episodes:
# We needed to recreate the show entry. Re-add episodes now. # We needed to recreate the show entry. Re-add episodes now.
log.info("Repairing episodes for showid: %s %s" % (showid, title)) log.info("Repairing episodes for showid: %s %s", showid, title)
all_episodes = emby.getEpisodesbyShow(itemid) all_episodes = emby.getEpisodesbyShow(itemid)
self.added_episode(all_episodes['Items'], None) self.added_episode(all_episodes['Items'], None)
@ -461,9 +455,9 @@ class TVShows(common.Items):
show = self.emby.getItem(seriesId) show = self.emby.getItem(seriesId)
self.add_update(show) self.add_update(show)
return return
seasonid = self.kodi_db.addSeason(showid, seasonnum, item['Name']) seasonid = self.kodi_db.addSeason(showid, seasonnum, item['Name'])
if item['LocationType'] != "Virtual": if item['LocationType'] != "Virtual":
# Create the reference in emby table # Create the reference in emby table
emby_db.addReference(item['Id'], seasonid, "Season", "season", parentid=showid) emby_db.addReference(item['Id'], seasonid, "Season", "season", parentid=showid)
@ -494,11 +488,11 @@ class TVShows(common.Items):
episodeid = emby_dbitem[0] episodeid = emby_dbitem[0]
fileid = emby_dbitem[1] fileid = emby_dbitem[1]
pathid = emby_dbitem[2] pathid = emby_dbitem[2]
log.info("episodeid: %s fileid: %s pathid: %s" % (episodeid, fileid, pathid)) log.info("episodeid: %s fileid: %s pathid: %s", episodeid, fileid, pathid)
except TypeError: except TypeError:
update_item = False update_item = False
log.debug("episodeid: %s not found." % itemid) log.debug("episodeid: %s not found", itemid)
# episodeid # episodeid
kodicursor.execute("select coalesce(max(idEpisode),0) from episode") kodicursor.execute("select coalesce(max(idEpisode),0) from episode")
episodeid = kodicursor.fetchone()[0] + 1 episodeid = kodicursor.fetchone()[0] + 1
@ -512,7 +506,7 @@ class TVShows(common.Items):
except TypeError: except TypeError:
# item is not found, let's recreate it. # item is not found, let's recreate it.
update_item = False update_item = False
log.info("episodeid: %s missing from Kodi, repairing the entry." % episodeid) log.info("episodeid: %s missing from Kodi, repairing the entry", episodeid)
# fileId information # fileId information
checksum = API.get_checksum() checksum = API.get_checksum()
@ -536,12 +530,12 @@ class TVShows(common.Items):
seriesId = item['SeriesId'] seriesId = item['SeriesId']
except KeyError: except KeyError:
# Missing seriesId, skip # Missing seriesId, skip
log.error("Skipping: %s. SeriesId is missing." % itemid) log.error("Skipping: %s. SeriesId is missing.", itemid)
return False return False
season = item.get('ParentIndexNumber') season = item.get('ParentIndexNumber')
episode = item.get('IndexNumber', -1) episode = item.get('IndexNumber', -1)
if season is None: if season is None:
if item.get('AbsoluteEpisodeNumber'): if item.get('AbsoluteEpisodeNumber'):
# Anime scenario # Anime scenario
@ -559,7 +553,7 @@ class TVShows(common.Items):
airsBeforeEpisode = item.get('AirsBeforeEpisodeNumber') airsBeforeEpisode = item.get('AirsBeforeEpisodeNumber')
# Append multi episodes to title # Append multi episodes to title
if item.get('IndexNumberEnd'): if item.get('IndexNumberEnd'):
title = "| %02d | %s" % (item['IndexNumberEnd'], title) title = "| %02d | %s" % (item['IndexNumberEnd'], title)
# Get season id # Get season id
@ -574,12 +568,12 @@ class TVShows(common.Items):
try: try:
showid = show[0] showid = show[0]
except TypeError: except TypeError:
log.error("Skipping: %s. Unable to add series: %s." % (itemid, seriesId)) log.error("Skipping: %s. Unable to add series: %s", itemid, seriesId)
return False return False
seasonid = self.kodi_db.addSeason(showid, season) seasonid = self.kodi_db.addSeason(showid, season)
##### GET THE FILE AND PATH ##### ##### GET THE FILE AND PATH #####
playurl = API.get_file_path() playurl = API.get_file_path()
@ -593,7 +587,7 @@ class TVShows(common.Items):
# Direct paths is set the Kodi way # Direct paths is set the Kodi way
if not self.path_validation(playurl): if not self.path_validation(playurl):
return False return False
path = playurl.replace(filename, "") path = playurl.replace(filename, "")
window('emby_pathverified', value="true") window('emby_pathverified', value="true")
else: else:
@ -611,47 +605,46 @@ class TVShows(common.Items):
##### UPDATE THE EPISODE ##### ##### UPDATE THE EPISODE #####
if update_item: if update_item:
log.info("UPDATE episode itemid: %s - Title: %s" % (itemid, title)) log.info("UPDATE episode itemid: %s - Title: %s", itemid, title)
# Update the movie entry # Update the movie entry
if self.kodi_version in (16, 17): if self.kodi_version in (16, 17):
# Kodi Jarvis, Krypton # Kodi Jarvis, Krypton
query = ' '.join(( query = ' '.join((
"UPDATE episode", "UPDATE episode",
"SET c00 = ?, c01 = ?, c03 = ?, c04 = ?, c05 = ?, c09 = ?, c10 = ?,", "SET c00 = ?, c01 = ?, c03 = ?, c04 = ?, c05 = ?, c09 = ?, c10 = ?,",
"c12 = ?, c13 = ?, c14 = ?, c15 = ?, c16 = ?, idSeason = ?, idShow = ?", "c12 = ?, c13 = ?, c14 = ?, c15 = ?, c16 = ?, idSeason = ?, idShow = ?",
"WHERE idEpisode = ?" "WHERE idEpisode = ?"
)) ))
kodicursor.execute(query, (title, plot, rating, writer, premieredate, kodicursor.execute(query, (title, plot, rating, writer, premieredate, runtime,
runtime, director, season, episode, title, airsBeforeSeason, director, season, episode, title, airsBeforeSeason,
airsBeforeEpisode, seasonid, showid, episodeid)) airsBeforeEpisode, seasonid, showid, episodeid))
else: else:
query = ' '.join(( query = ' '.join((
"UPDATE episode", "UPDATE episode",
"SET c00 = ?, c01 = ?, c03 = ?, c04 = ?, c05 = ?, c09 = ?, c10 = ?,", "SET c00 = ?, c01 = ?, c03 = ?, c04 = ?, c05 = ?, c09 = ?, c10 = ?,",
"c12 = ?, c13 = ?, c14 = ?, c15 = ?, c16 = ?, idShow = ?", "c12 = ?, c13 = ?, c14 = ?, c15 = ?, c16 = ?, idShow = ?",
"WHERE idEpisode = ?" "WHERE idEpisode = ?"
)) ))
kodicursor.execute(query, (title, plot, rating, writer, premieredate, kodicursor.execute(query, (title, plot, rating, writer, premieredate, runtime,
runtime, director, season, episode, title, airsBeforeSeason, director, season, episode, title, airsBeforeSeason,
airsBeforeEpisode, showid, episodeid)) airsBeforeEpisode, showid, episodeid))
# Update the checksum in emby table # Update the checksum in emby table
emby_db.updateReference(itemid, checksum) emby_db.updateReference(itemid, checksum)
# Update parentid reference # Update parentid reference
emby_db.updateParentId(itemid, seasonid) emby_db.updateParentId(itemid, seasonid)
##### OR ADD THE EPISODE ##### ##### OR ADD THE EPISODE #####
else: else:
log.info("ADD episode itemid: %s - Title: %s" % (itemid, title)) log.info("ADD episode itemid: %s - Title: %s", itemid, title)
# Add path # Add path
pathid = self.kodi_db.addPath(path) pathid = self.kodi_db.addPath(path)
# Add the file # Add the file
fileid = self.kodi_db.addFile(filename, pathid) fileid = self.kodi_db.addFile(filename, pathid)
# Create the episode entry # Create the episode entry
if self.kodi_version in (16, 17): if self.kodi_version in (16, 17):
# Kodi Jarvis, Krypton # Kodi Jarvis, Krypton
@ -665,8 +658,8 @@ class TVShows(common.Items):
''' '''
) )
kodicursor.execute(query, (episodeid, fileid, title, plot, rating, writer, kodicursor.execute(query, (episodeid, fileid, title, plot, rating, writer,
premieredate, runtime, director, season, episode, title, showid, premieredate, runtime, director, season, episode, title,
airsBeforeSeason, airsBeforeEpisode, seasonid)) showid, airsBeforeSeason, airsBeforeEpisode, seasonid))
else: else:
query = ( query = (
''' '''
@ -678,12 +671,12 @@ class TVShows(common.Items):
''' '''
) )
kodicursor.execute(query, (episodeid, fileid, title, plot, rating, writer, kodicursor.execute(query, (episodeid, fileid, title, plot, rating, writer,
premieredate, runtime, director, season, episode, title, showid, premieredate, runtime, director, season, episode, title,
airsBeforeSeason, airsBeforeEpisode)) showid, airsBeforeSeason, airsBeforeEpisode))
# Create the reference in emby table # Create the reference in emby table
emby_db.addReference(itemid, episodeid, "Episode", "episode", fileid, pathid, emby_db.addReference(itemid, episodeid, "Episode", "episode", fileid, pathid,
seasonid, checksum) seasonid, checksum)
# Update the path # Update the path
query = ' '.join(( query = ' '.join((
@ -702,7 +695,7 @@ class TVShows(common.Items):
"WHERE idFile = ?" "WHERE idFile = ?"
)) ))
kodicursor.execute(query, (pathid, filename, dateadded, fileid)) kodicursor.execute(query, (pathid, filename, dateadded, fileid))
# Process cast # Process cast
people = artwork.get_people_artwork(item['People']) people = artwork.get_people_artwork(item['People'])
self.kodi_db.addPeople(episodeid, people, "episode") self.kodi_db.addPeople(episodeid, people, "episode")
@ -736,7 +729,7 @@ class TVShows(common.Items):
# Poster with progress bar # Poster with progress bar
emby_db = self.emby_db emby_db = self.emby_db
API = api.API(item) API = api.API(item)
# Get emby information # Get emby information
itemid = item['Id'] itemid = item['Id']
checksum = API.get_checksum() checksum = API.get_checksum()
@ -750,9 +743,7 @@ class TVShows(common.Items):
kodiid = emby_dbitem[0] kodiid = emby_dbitem[0]
fileid = emby_dbitem[1] fileid = emby_dbitem[1]
mediatype = emby_dbitem[4] mediatype = emby_dbitem[4]
log.info( log.info("Update playstate for %s: %s fileid: %s", mediatype, item['Name'], fileid)
"Update playstate for %s: %s fileid: %s"
% (mediatype, item['Name'], fileid))
except TypeError: except TypeError:
return return
@ -769,7 +760,7 @@ class TVShows(common.Items):
resume = API.adjust_resume(userdata['Resume']) resume = API.adjust_resume(userdata['Resume'])
total = round(float(runtime), 6) total = round(float(runtime), 6)
log.debug("%s New resume point: %s" % (itemid, resume)) log.debug("%s New resume point: %s", itemid, resume)
self.kodi_db.addPlaystate(fileid, resume, total, playcount, dateplayed) self.kodi_db.addPlaystate(fileid, resume, total, playcount, dateplayed)
if not self.direct_path and not resume: if not self.direct_path and not resume:
@ -796,18 +787,15 @@ class TVShows(common.Items):
def remove(self, itemid): def remove(self, itemid):
# Remove showid, fileid, pathid, emby reference # Remove showid, fileid, pathid, emby reference
emby_db = self.emby_db emby_db = self.emby_db
embycursor = self.embycursor
kodicursor = self.kodicursor kodicursor = self.kodicursor
artwork = self.artwork
emby_dbitem = emby_db.getItem_byId(itemid) emby_dbitem = emby_db.getItem_byId(itemid)
try: try:
kodiid = emby_dbitem[0] kodiid = emby_dbitem[0]
fileid = emby_dbitem[1] fileid = emby_dbitem[1]
pathid = emby_dbitem[2]
parentid = emby_dbitem[3] parentid = emby_dbitem[3]
mediatype = emby_dbitem[4] mediatype = emby_dbitem[4]
log.info("Removing %s kodiid: %s fileid: %s" % (mediatype, kodiid, fileid)) log.info("Removing %s kodiid: %s fileid: %s", mediatype, kodiid, fileid)
except TypeError: except TypeError:
return return
@ -816,7 +804,6 @@ class TVShows(common.Items):
# Remove the emby reference # Remove the emby reference
emby_db.removeItem(itemid) emby_db.removeItem(itemid)
##### IF EPISODE ##### ##### IF EPISODE #####
if mediatype == "episode": if mediatype == "episode":
@ -829,7 +816,7 @@ class TVShows(common.Items):
showid = season[1] showid = season[1]
except TypeError: except TypeError:
return return
season_episodes = emby_db.getItem_byParentId(parentid, "episode") season_episodes = emby_db.getItem_byParentId(parentid, "episode")
if not season_episodes: if not season_episodes:
self.removeSeason(parentid) self.removeSeason(parentid)
@ -886,7 +873,7 @@ class TVShows(common.Items):
else: else:
# Remove emby episodes # Remove emby episodes
emby_db.removeItems_byParentId(kodiid, "episode") emby_db.removeItems_byParentId(kodiid, "episode")
# Remove season # Remove season
self.removeSeason(kodiid) self.removeSeason(kodiid)
@ -897,14 +884,14 @@ class TVShows(common.Items):
self.removeShow(parentid) self.removeShow(parentid)
emby_db.removeItem_byKodiId(parentid, "tvshow") emby_db.removeItem_byKodiId(parentid, "tvshow")
log.info("Deleted %s: %s from kodi database" % (mediatype, itemid)) log.info("Deleted %s: %s from kodi database", mediatype, itemid)
def removeShow(self, kodiid): def removeShow(self, kodiid):
kodicursor = self.kodicursor kodicursor = self.kodicursor
self.artwork.delete_artwork(kodiid, "tvshow", kodicursor) self.artwork.delete_artwork(kodiid, "tvshow", kodicursor)
kodicursor.execute("DELETE FROM tvshow WHERE idShow = ?", (kodiid,)) kodicursor.execute("DELETE FROM tvshow WHERE idShow = ?", (kodiid,))
log.debug("Removed tvshow: %s." % kodiid) log.debug("Removed tvshow: %s", kodiid)
def removeSeason(self, kodiid): def removeSeason(self, kodiid):
@ -912,7 +899,7 @@ class TVShows(common.Items):
self.artwork.delete_artwork(kodiid, "season", kodicursor) self.artwork.delete_artwork(kodiid, "season", kodicursor)
kodicursor.execute("DELETE FROM seasons WHERE idSeason = ?", (kodiid,)) kodicursor.execute("DELETE FROM seasons WHERE idSeason = ?", (kodiid,))
log.debug("Removed season: %s." % kodiid) log.debug("Removed season: %s", kodiid)
def removeEpisode(self, kodiid, fileid): def removeEpisode(self, kodiid, fileid):
@ -921,4 +908,4 @@ class TVShows(common.Items):
self.artwork.delete_artwork(kodiid, "episode", kodicursor) self.artwork.delete_artwork(kodiid, "episode", kodicursor)
kodicursor.execute("DELETE FROM episode WHERE idEpisode = ?", (kodiid,)) kodicursor.execute("DELETE FROM episode WHERE idEpisode = ?", (kodiid,))
kodicursor.execute("DELETE FROM files WHERE idFile = ?", (fileid,)) kodicursor.execute("DELETE FROM files WHERE idFile = ?", (fileid,))
log.debug("Removed episode: %s." % kodiid) log.debug("Removed episode: %s", kodiid)

View file

@ -148,10 +148,10 @@ class Service(object):
self.shutdown() self.shutdown()
def _startup(self): def _startup(self):
ga = GoogleAnalytics() ga = GoogleAnalytics()
ga.sendEventData("Application", "Startup") ga.sendEventData("Application", "Startup")
# Start up events # Start up events
self.warn_auth = True self.warn_auth = True
@ -288,7 +288,7 @@ class Service(object):
log.exception(error) log.exception(error)
def shutdown(self): def shutdown(self):
ga = GoogleAnalytics() ga = GoogleAnalytics()
ga.sendEventData("Application", "Shutdown") ga.sendEventData("Application", "Shutdown")

View file

@ -44,7 +44,7 @@ if __name__ == "__main__":
except Exception as error: except Exception as error:
ga = GoogleAnalytics() ga = GoogleAnalytics()
errStrings = ga.formatException() errStrings = ga.formatException()
ga.sendEventData("Exception", errStrings[0], errStrings[1]) ga.sendEventData("Exception", errStrings[0], errStrings[1])
log.exception(error) log.exception(error)
log.info("Forcing shutdown") log.info("Forcing shutdown")
service.shutdown() service.shutdown()