From ad80fdfe1d0979e0ec0f47855f26d7b6f1556ef7 Mon Sep 17 00:00:00 2001 From: tomkat83 Date: Wed, 4 Jan 2017 20:57:16 +0100 Subject: [PATCH] Rename embydb_functions to plexdb_functions --- resources/lib/PlexAPI.py | 10 +- resources/lib/context_entry.py | 10 +- resources/lib/entrypoint.py | 10 +- resources/lib/itemtypes.py | 500 ++++++------------ resources/lib/kodimonitor.py | 49 +- resources/lib/librarysync.py | 87 ++- resources/lib/player.py | 28 +- resources/lib/playlist_func.py | 82 +-- resources/lib/plexbmchelper/functions.py | 10 +- ...mbydb_functions.py => plexdb_functions.py} | 112 ++-- 10 files changed, 309 insertions(+), 589 deletions(-) rename resources/lib/{embydb_functions.py => plexdb_functions.py} (74%) diff --git a/resources/lib/PlexAPI.py b/resources/lib/PlexAPI.py index fa8ca2d1..a437512c 100644 --- a/resources/lib/PlexAPI.py +++ b/resources/lib/PlexAPI.py @@ -51,7 +51,7 @@ from utils import window, settings, language as lang, tryDecode, tryEncode, \ DateToKodi, KODILANGUAGE from PlexFunctions import PLEX_TO_KODI_TIMEFACTOR, PMSHttpsEnabled, \ REMAP_TYPE_FROM_PLEXTYPE -import embydb_functions as embydb +import plexdb_functions as plexdb ############################################################################### @@ -2305,10 +2305,10 @@ class API(): kodiindex = 0 for stream in mediastreams: index = stream.attrib['id'] - # Since Emby returns all possible tracks together, have to pull + # Since plex returns all possible tracks together, have to pull # only external subtitles. key = stream.attrib.get('key') - # IsTextSubtitleStream if true, is available to download from emby. + # IsTextSubtitleStream if true, is available to download from plex. if stream.attrib.get('streamType') == "3" and key: # Direct stream url = ("%s%s" % (self.server, key)) @@ -2467,10 +2467,10 @@ class API(): plexId = self.getRatingKey() listItem.setProperty('plexid', plexId) - with embydb.GetEmbyDB() as emby_db: + with plexdb.Get_Plex_DB() as plex_db: try: listItem.setProperty('dbid', - str(emby_db.getItem_byId(plexId)[0])) + str(plex_db.getItem_byId(plexId)[0])) except TypeError: pass # Expensive operation diff --git a/resources/lib/context_entry.py b/resources/lib/context_entry.py index f9772bfc..382d21ab 100644 --- a/resources/lib/context_entry.py +++ b/resources/lib/context_entry.py @@ -8,7 +8,7 @@ import xbmc import xbmcaddon import PlexFunctions as PF -import embydb_functions as embydb +import plexdb_functions as plexdb from utils import window, settings, dialog, language as lang, kodiSQL from dialogs import context @@ -75,8 +75,8 @@ class ContextMenu(object): def _get_item_id(cls, kodi_id, item_type): item_id = xbmc.getInfoLabel('ListItem.Property(plexid)') if not item_id and kodi_id and item_type: - with embydb.GetEmbyDB() as emby_db: - item = emby_db.getItem_byKodiId(kodi_id, item_type) + with plexdb.Get_Plex_DB() as plexcursor: + item = plexcursor.getItem_byKodiId(kodi_id, item_type) try: item_id = item[0] except TypeError: @@ -140,8 +140,8 @@ class ContextMenu(object): elif selected == OPTIONS['PMS_Play']: self._PMS_play() - elif selected == OPTIONS['Refresh']: - self.emby.refreshItem(self.item_id) + # elif selected == OPTIONS['Refresh']: + # self.emby.refreshItem(self.item_id) # elif selected == OPTIONS['AddFav']: # self.emby.updateUserRating(self.item_id, favourite=True) diff --git a/resources/lib/entrypoint.py b/resources/lib/entrypoint.py index 84fe180d..251ae0b5 100644 --- a/resources/lib/entrypoint.py +++ b/resources/lib/entrypoint.py @@ -17,7 +17,7 @@ from utils import window, settings, language as lang from utils import tryDecode, tryEncode, CatchExceptions import clientinfo import downloadutils -import embydb_functions as embydb +import plexdb_functions as plexdb import playbackutils as pbutils import PlexFunctions @@ -263,12 +263,8 @@ def deleteItem(): log.error("Unknown type, unable to proceed.") return - from utils import kodiSQL - embyconn = kodiSQL('plex') - embycursor = embyconn.cursor() - emby_db = embydb.Embydb_Functions(embycursor) - item = emby_db.getItem_byKodiId(dbid, itemtype) - embycursor.close() + with plexdb.Get_Plex_DB() as plexcursor: + item = plexcursor.getItem_byKodiId(dbid, itemtype) try: plexid = item[0] diff --git a/resources/lib/itemtypes.py b/resources/lib/itemtypes.py index e91ea674..f31f1941 100644 --- a/resources/lib/itemtypes.py +++ b/resources/lib/itemtypes.py @@ -12,7 +12,7 @@ import xbmcgui import artwork from utils import tryEncode, tryDecode, settings, window, kodiSQL, \ CatchExceptions, KODIVERSION -import embydb_functions as embydb +import plexdb_functions as plexdb import kodidb_functions as kodidb import PlexAPI @@ -45,11 +45,11 @@ class Items(object): """ Open DB connections and cursors """ - self.embyconn = kodiSQL('plex') - self.embycursor = self.embyconn.cursor() + self.plexconn = kodiSQL('plex') + self.plexcursor = self.plexconn.cursor() self.kodiconn = kodiSQL('video') self.kodicursor = self.kodiconn.cursor() - self.emby_db = embydb.Embydb_Functions(self.embycursor) + self.plex_db = plexdb.Plex_DB_Functions(self.plexcursor) self.kodi_db = kodidb.Kodidb_Functions(self.kodicursor) return self @@ -57,9 +57,9 @@ class Items(object): """ Make sure DB changes are committed and connection to DB is closed. """ - self.embyconn.commit() + self.plexconn.commit() self.kodiconn.commit() - self.embyconn.close() + self.plexconn.close() self.kodiconn.close() return self @@ -85,170 +85,6 @@ class Items(object): self.kodicursor) self.kodi_db.assignBoxset(setid, kodiId) - def itemsbyId(self, items, process, pdialog=None): - # Process items by itemid. Process can be added, update, userdata, remove - embycursor = self.embycursor - kodicursor = self.kodicursor - music_enabled = self.music_enabled - - itemtypes = { - - 'Movie': Movies, - 'BoxSet': Movies, - 'Series': TVShows, - 'Season': TVShows, - 'Episode': TVShows, - 'MusicAlbum': Music, - 'MusicArtist': Music, - 'AlbumArtist': Music, - 'Audio': Music - } - - update_videolibrary = False - total = 0 - for item in items: - total += len(items[item]) - - if total == 0: - return False - - log.info("Processing %s: %s" % (process, items)) - if pdialog: - pdialog.update(heading="Processing %s: %s items" % (process, total)) - - count = 0 - for itemtype in items: - - # Safety check - if not itemtypes.get(itemtype): - # We don't process this type of item - continue - - itemlist = items[itemtype] - if not itemlist: - # The list to process is empty - continue - - musicconn = None - - if itemtype in ('MusicAlbum', 'MusicArtist', 'AlbumArtist', 'Audio'): - if music_enabled: - musicconn = kodiSQL('music') - musiccursor = musicconn.cursor() - items_process = itemtypes[itemtype](embycursor, musiccursor) - else: - # Music is not enabled, do not proceed with itemtype - continue - else: - update_videolibrary = True - items_process = itemtypes[itemtype](embycursor, kodicursor) - - if itemtype == "Movie": - actions = { - 'added': items_process.added, - 'update': items_process.add_update, - 'userdata': items_process.updateUserdata, - 'remove': items_process.remove - } - elif itemtype == "BoxSet": - actions = { - 'added': items_process.added_boxset, - 'update': items_process.add_updateBoxset, - 'remove': items_process.remove - } - elif itemtype == "MusicVideo": - actions = { - 'added': items_process.added, - 'update': items_process.add_update, - 'userdata': items_process.updateUserdata, - 'remove': items_process.remove - } - elif itemtype == "Series": - actions = { - 'added': items_process.added, - 'update': items_process.add_update, - 'userdata': items_process.updateUserdata, - 'remove': items_process.remove - } - elif itemtype == "Season": - actions = { - 'added': items_process.added_season, - 'update': items_process.add_updateSeason, - 'remove': items_process.remove - } - elif itemtype == "Episode": - actions = { - 'added': items_process.added_episode, - 'update': items_process.add_updateEpisode, - 'userdata': items_process.updateUserdata, - 'remove': items_process.remove - } - elif itemtype == "MusicAlbum": - actions = { - 'added': items_process.added_album, - 'update': items_process.add_updateAlbum, - 'userdata': items_process.updateUserdata, - 'remove': items_process.remove - } - elif itemtype in ("MusicArtist", "AlbumArtist"): - actions = { - 'added': items_process.added, - 'update': items_process.add_updateArtist, - 'remove': items_process.remove - } - elif itemtype == "Audio": - actions = { - 'added': items_process.added_song, - 'update': items_process.add_updateSong, - 'userdata': items_process.updateUserdata, - 'remove': items_process.remove - } - else: - log.info("Unsupported itemtype: %s." % itemtype) - actions = {} - - if actions.get(process): - - if process == "remove": - for item in itemlist: - actions[process](item) - - elif process == "added": - actions[process](itemlist, pdialog) - - else: - processItems = emby.getFullItems(itemlist) - for item in processItems: - - title = item['Name'] - - if itemtype == "Episode": - title = "%s - %s" % (item['SeriesName'], title) - - if pdialog: - percentage = int((float(count) / float(total))*100) - pdialog.update(percentage, message=title) - count += 1 - - actions[process](item) - - - if musicconn is not None: - # close connection for special types - log.info("Updating music database.") - musicconn.commit() - musiccursor.close() - - return (True, update_videolibrary) - - def contentPop(self, name, time=5000): - xbmcgui.Dialog().notification( - heading="Emby for Kodi", - message="Added: %s" % name, - icon="special://home/addons/plugin.video.plexkodiconnect/icon.png", - time=time, - sound=False) - def updateUserdata(self, xml, viewtag=None, viewid=None): """ Updates the Kodi watched state of the item from PMS. Also retrieves @@ -260,7 +96,7 @@ class Items(object): API = PlexAPI.API(mediaitem) # Get key and db entry on the Kodi db side try: - fileid = self.emby_db.getItem_byId(API.getRatingKey())[1] + fileid = self.plex_db.getItem_byId(API.getRatingKey())[1] except: continue # Grab the user's viewcount, resume points etc. from PMS' answer @@ -305,7 +141,7 @@ class Movies(Items): def add_update(self, item, viewtag=None, viewid=None): # Process single movie kodicursor = self.kodicursor - emby_db = self.emby_db + plex_db = self.plex_db artwork = self.artwork API = PlexAPI.API(item) @@ -318,11 +154,11 @@ class Movies(Items): if not itemid: log.error("Cannot parse XML data for movie") return - emby_dbitem = emby_db.getItem_byId(itemid) + plex_dbitem = plex_db.getItem_byId(itemid) try: - movieid = emby_dbitem[0] - fileid = emby_dbitem[1] - pathid = emby_dbitem[2] + movieid = plex_dbitem[0] + fileid = plex_dbitem[1] + pathid = plex_dbitem[2] except TypeError: # movieid @@ -495,10 +331,10 @@ class Movies(Items): sorttitle, runtime, mpaa, genre, director, title, studio, trailer, country, playurl, pathid)) - # Create or update the reference in emby table Add reference is + # Create or update the reference in plex table Add reference is # idempotent; the call here updates also fileid and pathid when item is # moved or renamed - emby_db.addReference(itemid, movieid, "Movie", "movie", fileid, pathid, + plex_db.addReference(itemid, movieid, "Movie", "movie", fileid, pathid, None, checksum, viewid) # Update the path @@ -543,23 +379,23 @@ class Movies(Items): self.kodi_db.addPlaystate(fileid, resume, runtime, playcount, dateplayed) def remove(self, itemid): - # Remove movieid, fileid, emby reference - emby_db = self.emby_db + # Remove movieid, fileid, plex reference + plex_db = self.plex_db kodicursor = self.kodicursor artwork = self.artwork - emby_dbitem = emby_db.getItem_byId(itemid) + plex_dbitem = plex_db.getItem_byId(itemid) try: - kodiid = emby_dbitem[0] - fileid = emby_dbitem[1] - mediatype = emby_dbitem[4] + kodiid = plex_dbitem[0] + fileid = plex_dbitem[1] + mediatype = plex_dbitem[4] log.info("Removing %sid: %s fileid: %s" % (mediatype, kodiid, fileid)) except TypeError: return - # Remove the emby reference - emby_db.removeItem(itemid) + # Remove the plex reference + plex_db.removeItem(itemid) # Remove artwork artwork.deleteArtwork(kodiid, mediatype, kodicursor) @@ -570,13 +406,13 @@ class Movies(Items): elif mediatype == "set": # Delete kodi boxset - boxset_movies = emby_db.getItem_byParentId(kodiid, "movie") + boxset_movies = plex_db.getItem_byParentId(kodiid, "movie") for movie in boxset_movies: plexid = movie[0] movieid = movie[1] self.kodi_db.removefromBoxset(movieid) - # Update emby reference - emby_db.updateParentId(plexid, None) + # Update plex reference + plex_db.updateParentId(plexid, None) kodicursor.execute("DELETE FROM sets WHERE idSet = ?", (kodiid,)) @@ -590,7 +426,7 @@ class TVShows(Items): def add_update(self, item, viewtag=None, viewid=None): # Process single tvshow kodicursor = self.kodicursor - emby_db = self.emby_db + plex_db = self.plex_db artwork = self.artwork API = PlexAPI.API(item) @@ -604,10 +440,10 @@ class TVShows(Items): # If the item doesn't exist, we'll add it to the database update_item = True force_episodes = False - emby_dbitem = emby_db.getItem_byId(itemid) + plex_dbitem = plex_db.getItem_byId(itemid) try: - showid = emby_dbitem[0] - pathid = emby_dbitem[2] + showid = plex_dbitem[0] + pathid = plex_dbitem[2] except TypeError: update_item = False kodicursor.execute("select coalesce(max(idShow),0) from tvshow") @@ -627,11 +463,6 @@ class TVShows(Items): # Force re-add episodes after the show is re-created. force_episodes = True - if viewtag is None or viewid is None: - # Get view tag from emby - viewtag, viewid, mediatype = embyserver.getView_plexid(itemid) - log.debug("View tag found: %s" % viewtag) - # fileId information checksum = API.getChecksum() @@ -701,7 +532,7 @@ class TVShows(Items): # Add reference is idempotent; the call here updates also fileid # and pathid when item is moved or renamed - emby_db.addReference(itemid, + plex_db.addReference(itemid, showid, "Series", "tvshow", @@ -737,8 +568,8 @@ class TVShows(Items): query = "INSERT INTO tvshowlinkpath(idShow, idPath) values(?, ?)" kodicursor.execute(query, (showid, pathid)) - # Create the reference in emby table - emby_db.addReference(itemid, showid, "Series", "tvshow", pathid=pathid, + # Create the reference in plex table + plex_db.addReference(itemid, showid, "Series", "tvshow", pathid=pathid, checksum=checksum, mediafolderid=viewid) # Update the path query = ' '.join(( @@ -765,11 +596,11 @@ class TVShows(Items): tags.extend(collections) self.kodi_db.addTags(showid, tags, "tvshow") - if force_episodes: - # We needed to recreate the show entry. Re-add episodes now. - log.info("Repairing episodes for showid: %s %s" % (showid, title)) - all_episodes = embyserver.getEpisodesbyShow(itemid) - self.added_episode(all_episodes['Items'], None) + # if force_episodes: + # # We needed to recreate the show entry. Re-add episodes now. + # log.info("Repairing episodes for showid: %s %s" % (showid, title)) + # all_episodes = embyserver.getEpisodesbyShow(itemid) + # self.added_episode(all_episodes['Items'], None) @CatchExceptions(warnuser=True) def add_updateSeason(self, item, viewtag=None, viewid=None): @@ -779,15 +610,15 @@ class TVShows(Items): log.error('Error getting itemid for season, skipping') return kodicursor = self.kodicursor - emby_db = self.emby_db + plex_db = self.plex_db artwork = self.artwork seasonnum = API.getIndex() # Get parent tv show Plex id plexshowid = item.attrib.get('parentRatingKey') # Get Kodi showid - emby_dbitem = emby_db.getItem_byId(plexshowid) + plex_dbitem = plex_db.getItem_byId(plexshowid) try: - showid = emby_dbitem[0] + showid = plex_dbitem[0] except: log.error('Could not find parent tv show for season %s. ' 'Skipping season for now.' % (itemid)) @@ -797,9 +628,9 @@ class TVShows(Items): checksum = API.getChecksum() # Check whether Season already exists update_item = True - emby_dbitem = emby_db.getItem_byId(itemid) + plex_dbitem = plex_db.getItem_byId(itemid) try: - embyDbItemId = emby_dbitem[0] + plexdbItemId = plex_dbitem[0] except TypeError: update_item = False @@ -808,11 +639,11 @@ class TVShows(Items): artwork.addArtwork(allartworks, seasonid, "season", kodicursor) if update_item: - # Update a reference: checksum in emby table - emby_db.updateReference(itemid, checksum) + # Update a reference: checksum in plex table + plex_db.updateReference(itemid, checksum) else: - # Create the reference in emby table - emby_db.addReference(itemid, + # Create the reference in plex table + plex_db.addReference(itemid, seasonid, "Season", "season", @@ -826,7 +657,7 @@ class TVShows(Items): """ # Process single episode kodicursor = self.kodicursor - emby_db = self.emby_db + plex_db = self.plex_db artwork = self.artwork API = PlexAPI.API(item) @@ -838,11 +669,11 @@ class TVShows(Items): if not itemid: log.error('Error getting itemid for episode, skipping') return - emby_dbitem = emby_db.getItem_byId(itemid) + plex_dbitem = plex_db.getItem_byId(itemid) try: - episodeid = emby_dbitem[0] - fileid = emby_dbitem[1] - pathid = emby_dbitem[2] + episodeid = plex_dbitem[0] + fileid = plex_dbitem[1] + pathid = plex_dbitem[2] except TypeError: update_item = False # episodeid @@ -910,19 +741,10 @@ class TVShows(Items): # title = "| %02d | %s" % (item['IndexNumberEnd'], title) # Get season id - show = emby_db.getItem_byId(seriesId) + show = plex_db.getItem_byId(seriesId) try: showid = show[0] except TypeError: - # self.logMsg("Show is missing from database, trying to add", 2) - # show = self.emby.getItem(seriesId) - # self.logMsg("Show now: %s. Trying to add new show" % show, 2) - # self.add_update(show) - # show = emby_db.getItem_byId(seriesId) - # try: - # showid = show[0] - # except TypeError: - # log.error("Skipping: %s. Unable to add series: %s." % (itemid, seriesId)) log.error("Parent tvshow now found, skip item") return False seasonid = self.kodi_db.addSeason(showid, season) @@ -1010,7 +832,7 @@ class TVShows(Items): airsBeforeSeason, airsBeforeEpisode, playurl, pathid, fileid, episodeid)) # Update parentid reference - emby_db.updateParentId(itemid, seasonid) + plex_db.updateParentId(itemid, seasonid) ##### OR ADD THE EPISODE ##### else: @@ -1044,10 +866,10 @@ class TVShows(Items): premieredate, runtime, director, season, episode, title, showid, airsBeforeSeason, airsBeforeEpisode, playurl, pathid)) - # Create or update the reference in emby table Add reference is + # Create or update the reference in plex table Add reference is # idempotent; the call here updates also fileid and pathid when item is # moved or renamed - emby_db.addReference(itemid, episodeid, "Episode", "episode", fileid, + plex_db.addReference(itemid, episodeid, "Episode", "episode", fileid, pathid, seasonid, checksum) # Update the path @@ -1110,17 +932,17 @@ class TVShows(Items): dateplayed) def remove(self, itemid): - # Remove showid, fileid, pathid, emby reference - emby_db = self.emby_db + # Remove showid, fileid, pathid, plex reference + plex_db = self.plex_db kodicursor = self.kodicursor - emby_dbitem = emby_db.getItem_byId(itemid) + plex_dbitem = plex_db.getItem_byId(itemid) try: - kodiid = emby_dbitem[0] - fileid = emby_dbitem[1] - pathid = emby_dbitem[2] - parentid = emby_dbitem[3] - mediatype = emby_dbitem[4] + kodiid = plex_dbitem[0] + fileid = plex_dbitem[1] + pathid = plex_dbitem[2] + parentid = plex_dbitem[3] + mediatype = plex_dbitem[4] log.info("Removing %s kodiid: %s fileid: %s" % (mediatype, kodiid, fileid)) except TypeError: @@ -1128,8 +950,8 @@ class TVShows(Items): ##### PROCESS ITEM ##### - # Remove the emby reference - emby_db.removeItem(itemid) + # Remove the plex reference + plex_db.removeItem(itemid) ##### IF EPISODE ##### @@ -1139,19 +961,19 @@ class TVShows(Items): self.removeEpisode(kodiid, fileid) # Season verification - season = emby_db.getItem_byKodiId(parentid, "season") + season = plex_db.getItem_byKodiId(parentid, "season") try: showid = season[1] except TypeError: return - season_episodes = emby_db.getItem_byParentId(parentid, "episode") + season_episodes = plex_db.getItem_byParentId(parentid, "episode") if not season_episodes: self.removeSeason(parentid) - emby_db.removeItem(season[0]) + plex_db.removeItem(season[0]) # Show verification - show = emby_db.getItem_byKodiId(showid, "tvshow") + show = plex_db.getItem_byKodiId(showid, "tvshow") query = ' '.join(( "SELECT totalCount", @@ -1162,31 +984,31 @@ class TVShows(Items): result = kodicursor.fetchone() if result and result[0] is None: # There's no episodes left, delete show and any possible remaining seasons - seasons = emby_db.getItem_byParentId(showid, "season") + seasons = plex_db.getItem_byParentId(showid, "season") for season in seasons: self.removeSeason(season[1]) else: - # Delete emby season entries - emby_db.removeItems_byParentId(showid, "season") + # Delete plex season entries + plex_db.removeItems_byParentId(showid, "season") self.removeShow(showid) - emby_db.removeItem(show[0]) + plex_db.removeItem(show[0]) ##### IF TVSHOW ##### elif mediatype == "tvshow": # Remove episodes, seasons, tvshow - seasons = emby_db.getItem_byParentId(kodiid, "season") + seasons = plex_db.getItem_byParentId(kodiid, "season") for season in seasons: seasonid = season[1] - season_episodes = emby_db.getItem_byParentId(seasonid, "episode") + season_episodes = plex_db.getItem_byParentId(seasonid, "episode") for episode in season_episodes: self.removeEpisode(episode[1], episode[2]) else: - # Remove emby episodes - emby_db.removeItems_byParentId(seasonid, "episode") + # Remove plex episodes + plex_db.removeItems_byParentId(seasonid, "episode") else: - # Remove emby seasons - emby_db.removeItems_byParentId(kodiid, "season") + # Remove plex seasons + plex_db.removeItems_byParentId(kodiid, "season") # Remove tvshow self.removeShow(kodiid) @@ -1195,22 +1017,22 @@ class TVShows(Items): elif mediatype == "season": # Remove episodes, season, verify tvshow - season_episodes = emby_db.getItem_byParentId(kodiid, "episode") + season_episodes = plex_db.getItem_byParentId(kodiid, "episode") for episode in season_episodes: self.removeEpisode(episode[1], episode[2]) else: - # Remove emby episodes - emby_db.removeItems_byParentId(kodiid, "episode") + # Remove plex episodes + plex_db.removeItems_byParentId(kodiid, "episode") # Remove season self.removeSeason(kodiid) # Show verification - seasons = emby_db.getItem_byParentId(parentid, "season") + seasons = plex_db.getItem_byParentId(parentid, "season") if not seasons: # There's no seasons, delete the show self.removeShow(parentid) - emby_db.removeItem_byKodiId(parentid, "tvshow") + plex_db.removeItem_byKodiId(parentid, "tvshow") log.debug("Deleted %s: %s from kodi database" % (mediatype, itemid)) @@ -1249,12 +1071,12 @@ class Music(Items): OVERWRITE this method, because we need to open another DB. Open DB connections and cursors """ - self.embyconn = kodiSQL('plex') - self.embycursor = self.embyconn.cursor() + self.plexconn = kodiSQL('plex') + self.plexcursor = self.plexconn.cursor() # Here it is, not 'video' but 'music' self.kodiconn = kodiSQL('music') self.kodicursor = self.kodiconn.cursor() - self.emby_db = embydb.Embydb_Functions(self.embycursor) + self.plex_db = plexdb.Plex_DB_Functions(self.plexcursor) self.kodi_db = kodidb.Kodidb_Functions(self.kodicursor) return self @@ -1262,15 +1084,15 @@ class Music(Items): def add_updateArtist(self, item, viewtag=None, viewid=None, artisttype="MusicArtist"): kodicursor = self.kodicursor - emby_db = self.emby_db + plex_db = self.plex_db artwork = self.artwork API = PlexAPI.API(item) update_item = True itemid = API.getRatingKey() - emby_dbitem = emby_db.getItem_byId(itemid) + plex_dbitem = plex_db.getItem_byId(itemid) try: - artistid = emby_dbitem[0] + artistid = plex_dbitem[0] except TypeError: update_item = False @@ -1300,19 +1122,19 @@ class Music(Items): # UPDATE THE ARTIST ##### if update_item: log.info("UPDATE artist itemid: %s - Name: %s" % (itemid, name)) - # Update the checksum in emby table - emby_db.updateReference(itemid, checksum) + # Update the checksum in plex table + plex_db.updateReference(itemid, checksum) # OR ADD THE ARTIST ##### else: log.info("ADD artist itemid: %s - Name: %s" % (itemid, name)) - # safety checks: It looks like Emby supports the same artist + # safety checks: It looks like plex supports the same artist # multiple times. # Kodi doesn't allow that. In case that happens we just merge the # artist entries. artistid = self.kodi_db.addArtist(name, musicBrainzId) - # Create the reference in emby table - emby_db.addReference( + # Create the reference in plex table + plex_db.addReference( itemid, artistid, artisttype, "artist", checksum=checksum) # Process the artist @@ -1343,7 +1165,7 @@ class Music(Items): @CatchExceptions(warnuser=True) def add_updateAlbum(self, item, viewtag=None, viewid=None): kodicursor = self.kodicursor - emby_db = self.emby_db + plex_db = self.plex_db artwork = self.artwork API = PlexAPI.API(item) @@ -1352,9 +1174,9 @@ class Music(Items): if not itemid: log.error('Error processing Album, skipping') return - emby_dbitem = emby_db.getItem_byId(itemid) + plex_dbitem = plex_db.getItem_byId(itemid) try: - albumid = emby_dbitem[0] + albumid = plex_dbitem[0] except TypeError: # Albumid not found update_item = False @@ -1393,19 +1215,19 @@ class Music(Items): # UPDATE THE ALBUM ##### if update_item: log.info("UPDATE album itemid: %s - Name: %s" % (itemid, name)) - # Update the checksum in emby table - emby_db.updateReference(itemid, checksum) + # Update the checksum in plex table + plex_db.updateReference(itemid, checksum) # OR ADD THE ALBUM ##### else: log.info("ADD album itemid: %s - Name: %s" % (itemid, name)) - # safety checks: It looks like Emby supports the same artist + # safety checks: It looks like plex supports the same artist # multiple times. # Kodi doesn't allow that. In case that happens we just merge the # artist entries. albumid = self.kodi_db.addAlbum(name, musicBrainzId) - # Create the reference in emby table - emby_db.addReference( + # Create the reference in plex table + plex_db.addReference( itemid, albumid, "MusicAlbum", "album", checksum=checksum) # Process the album info @@ -1462,41 +1284,41 @@ class Music(Items): rating, lastScraped, dateadded, studio, albumid)) - # Associate the parentid for emby reference + # Associate the parentid for plex reference parentId = item.attrib.get('parentRatingKey') if parentId is not None: - emby_dbartist = emby_db.getItem_byId(parentId) + plex_dbartist = plex_db.getItem_byId(parentId) try: - artistid = emby_dbartist[0] + artistid = plex_dbartist[0] except TypeError: - log.info('Artist %s does not exist in emby database' + log.info('Artist %s does not exist in plex database' % parentId) artist = GetPlexMetadata(parentId) # Item may not be an artist, verification necessary. if artist is not None and artist != 401: if artist[0].attrib.get('type') == "artist": # Update with the parentId, for remove reference - emby_db.addReference( + plex_db.addReference( parentId, parentId, "MusicArtist", "artist") - emby_db.updateParentId(itemid, parentId) + plex_db.updateParentId(itemid, parentId) else: - # Update emby reference with the artistid - emby_db.updateParentId(itemid, artistid) + # Update plex reference with the artistid + plex_db.updateParentId(itemid, artistid) # Assign main artists to album # Plex unfortunately only supports 1 artist :-( artistId = parentId - emby_dbartist = emby_db.getItem_byId(artistId) + plex_dbartist = plex_db.getItem_byId(artistId) try: - artistid = emby_dbartist[0] + artistid = plex_dbartist[0] except TypeError: - # Artist does not exist in emby database, create the reference + # Artist does not exist in plex database, create the reference log.info('Artist %s does not exist in Plex database' % artistId) artist = GetPlexMetadata(artistId) if artist is not None and artist != 401: self.add_updateArtist(artist[0], artisttype="AlbumArtist") - emby_dbartist = emby_db.getItem_byId(artistId) - artistid = emby_dbartist[0] + plex_dbartist = plex_db.getItem_byId(artistId) + artistid = plex_dbartist[0] else: # Best take this name over anything else. query = "UPDATE artist SET strArtist = ? WHERE idArtist = ?" @@ -1522,8 +1344,8 @@ class Music(Items): ''' ) kodicursor.execute(query, (artistid, name, year)) - # Update emby reference with parentid - emby_db.updateParentId(artistId, albumid) + # Update plex reference with parentid + plex_db.updateParentId(artistId, albumid) # Add genres self.kodi_db.addMusicGenres(albumid, genres, "album") # Update artwork @@ -1533,7 +1355,7 @@ class Music(Items): def add_updateSong(self, item, viewtag=None, viewid=None): # Process single song kodicursor = self.kodicursor - emby_db = self.emby_db + plex_db = self.plex_db artwork = self.artwork API = PlexAPI.API(item) @@ -1542,11 +1364,11 @@ class Music(Items): if not itemid: log.error('Error processing Song; skipping') return - emby_dbitem = emby_db.getItem_byId(itemid) + plex_dbitem = plex_db.getItem_byId(itemid) try: - songid = emby_dbitem[0] - pathid = emby_dbitem[2] - albumid = emby_dbitem[3] + songid = plex_dbitem[0] + pathid = plex_dbitem[2] + albumid = plex_dbitem[3] except TypeError: # Songid not found update_item = False @@ -1630,8 +1452,8 @@ class Music(Items): duration, year, filename, playcount, dateplayed, rating, comment, songid)) - # Update the checksum in emby table - emby_db.updateReference(itemid, checksum) + # Update the checksum in plex table + plex_db.updateReference(itemid, checksum) # OR ADD THE SONG ##### else: @@ -1642,9 +1464,9 @@ class Music(Items): try: # Get the album - emby_dbalbum = emby_db.getItem_byId( + plex_dbalbum = plex_db.getItem_byId( item.attrib.get('parentRatingKey')) - albumid = emby_dbalbum[0] + albumid = plex_dbalbum[0] except KeyError: # Verify if there's an album associated. album_name = item.get('parentTitle') @@ -1652,7 +1474,7 @@ class Music(Items): log.info("Creating virtual music album for song: %s." % itemid) albumid = self.kodi_db.addAlbum(album_name, API.getProvider('MusicBrainzAlbum')) - emby_db.addReference("%salbum%s" % (itemid, albumid), albumid, "MusicAlbum_", "album") + plex_db.addReference("%salbum%s" % (itemid, albumid), albumid, "MusicAlbum_", "album") else: # No album Id associated to the song. log.error("Song itemid: %s has no albumId associated." @@ -1662,15 +1484,15 @@ class Music(Items): except TypeError: # No album found. Let's create it log.info("Album database entry missing.") - emby_albumId = item.attrib.get('parentRatingKey') - album = GetPlexMetadata(emby_albumId) + plex_albumId = item.attrib.get('parentRatingKey') + album = GetPlexMetadata(plex_albumId) if album is None or album == 401: log.error('Could not download album, abort') return self.add_updateAlbum(album[0]) - emby_dbalbum = emby_db.getItem_byId(emby_albumId) + plex_dbalbum = plex_db.getItem_byId(plex_albumId) try: - albumid = emby_dbalbum[0] + albumid = plex_dbalbum[0] log.debug("Found albumid: %s" % albumid) except TypeError: # No album found, create a single's album @@ -1724,8 +1546,8 @@ class Music(Items): duration, year, filename, musicBrainzId, playcount, dateplayed, rating, 0, 0)) - # Create the reference in emby table - emby_db.addReference( + # Create the reference in plex table + plex_db.addReference( itemid, songid, "Audio", "song", pathid=pathid, parentid=albumid, @@ -1752,17 +1574,17 @@ class Music(Items): artist_name = artist['Name'] artist_eid = artist['Id'] - artist_edb = emby_db.getItem_byId(artist_eid) + artist_edb = plex_db.getItem_byId(artist_eid) try: artistid = artist_edb[0] except TypeError: - # Artist is missing from emby database, add it. + # Artist is missing from plex database, add it. artistXml = GetPlexMetadata(artist_eid) if artistXml is None or artistXml == 401: log.error('Error getting artist, abort') return self.add_updateArtist(artistXml[0]) - artist_edb = emby_db.getItem_byId(artist_eid) + artist_edb = plex_db.getItem_byId(artist_eid) artistid = artist_edb[0] finally: if KODIVERSION >= 17: @@ -1798,17 +1620,17 @@ class Music(Items): artist_name = artist['Name'] album_artists.append(artist_name) artist_eid = artist['Id'] - artist_edb = emby_db.getItem_byId(artist_eid) + artist_edb = plex_db.getItem_byId(artist_eid) try: artistid = artist_edb[0] except TypeError: - # Artist is missing from emby database, add it. + # Artist is missing from plex database, add it. artistXml = GetPlexMetadata(artist_eid) if artistXml is None or artistXml == 401: log.error('Error getting artist, abort') return self.add_updateArtist(artistXml) - artist_edb = emby_db.getItem_byId(artist_eid) + artist_edb = plex_db.getItem_byId(artist_eid) artistid = artist_edb[0] finally: query = ( @@ -1868,21 +1690,21 @@ class Music(Items): artwork.addArtwork(allart, albumid, "album", kodicursor) def remove(self, itemid): - # Remove kodiid, fileid, pathid, emby reference - emby_db = self.emby_db + # Remove kodiid, fileid, pathid, plex reference + plex_db = self.plex_db - emby_dbitem = emby_db.getItem_byId(itemid) + plex_dbitem = plex_db.getItem_byId(itemid) try: - kodiid = emby_dbitem[0] - mediatype = emby_dbitem[4] + kodiid = plex_dbitem[0] + mediatype = plex_dbitem[4] log.info("Removing %s kodiid: %s" % (mediatype, kodiid)) except TypeError: return ##### PROCESS ITEM ##### - # Remove the emby reference - emby_db.removeItem(itemid) + # Remove the plex reference + plex_db.removeItem(itemid) ##### IF SONG ##### @@ -1891,15 +1713,15 @@ class Music(Items): self.removeSong(kodiid) # This should only address single song scenario, where server doesn't actually # create an album for the song. - emby_db.removeWildItem(itemid) + plex_db.removeWildItem(itemid) - for item in emby_db.getItem_byWildId(itemid): + for item in plex_db.getItem_byWildId(itemid): item_kid = item[0] item_mediatype = item[1] if item_mediatype == "album": - childs = emby_db.getItem_byParentId(item_kid, "song") + childs = plex_db.getItem_byParentId(item_kid, "song") if not childs: # Delete album self.removeAlbum(item_kid) @@ -1908,12 +1730,12 @@ class Music(Items): elif mediatype == "album": # Delete songs, album - album_songs = emby_db.getItem_byParentId(kodiid, "song") + album_songs = plex_db.getItem_byParentId(kodiid, "song") for song in album_songs: self.removeSong(song[1]) else: - # Remove emby songs - emby_db.removeItems_byParentId(kodiid, "song") + # Remove plex songs + plex_db.removeItems_byParentId(kodiid, "song") # Remove the album self.removeAlbum(kodiid) @@ -1922,22 +1744,22 @@ class Music(Items): elif mediatype == "artist": # Delete songs, album, artist - albums = emby_db.getItem_byParentId(kodiid, "album") + albums = plex_db.getItem_byParentId(kodiid, "album") for album in albums: albumid = album[1] - album_songs = emby_db.getItem_byParentId(albumid, "song") + album_songs = plex_db.getItem_byParentId(albumid, "song") for song in album_songs: self.removeSong(song[1]) else: - # Remove emby song - emby_db.removeItems_byParentId(albumid, "song") - # Remove emby artist - emby_db.removeItems_byParentId(albumid, "artist") + # Remove plex song + plex_db.removeItems_byParentId(albumid, "song") + # Remove plex artist + plex_db.removeItems_byParentId(albumid, "artist") # Remove kodi album self.removeAlbum(albumid) else: - # Remove emby albums - emby_db.removeItems_byParentId(kodiid, "album") + # Remove plex albums + plex_db.removeItems_byParentId(kodiid, "album") # Remove artist self.removeArtist(kodiid) diff --git a/resources/lib/kodimonitor.py b/resources/lib/kodimonitor.py index 066613da..4aeafa13 100644 --- a/resources/lib/kodimonitor.py +++ b/resources/lib/kodimonitor.py @@ -9,7 +9,7 @@ import xbmc import xbmcgui import downloadutils -import embydb_functions as embydb +import plexdb_functions as plexdb import playbackutils as pbutils from utils import window, settings, CatchExceptions, tryDecode, tryEncode from PlexFunctions import scrobble, REMAP_TYPE_FROM_PLEXTYPE @@ -93,12 +93,12 @@ class KodiMonitor(xbmc.Monitor): log.info("Item is invalid for playstate update.") else: # Send notification to the server. - with embydb.GetEmbyDB() as emby_db: - emby_dbitem = emby_db.getItem_byKodiId(kodiid, item_type) + with plexdb.Get_Plex_DB() as plexcur: + plex_dbitem = plexcur.getItem_byKodiId(kodiid, item_type) try: - itemid = emby_dbitem[0] + itemid = plex_dbitem[0] except TypeError: - log.error("Could not find itemid in emby database for a " + log.error("Could not find itemid in plex database for a " "video library update") else: # Stop from manually marking as watched unwatched, with actual playback. @@ -113,40 +113,7 @@ class KodiMonitor(xbmc.Monitor): scrobble(itemid, 'unwatched') elif method == "VideoLibrary.OnRemove": - # Removed function, because with plugin paths + clean library, it will wipe - # entire library if user has permissions. Instead, use the emby context menu available - # in Isengard and higher version pass - '''try: - kodiid = data['id'] - type = data['type'] - except (KeyError, TypeError): - log.info("Item is invalid for emby deletion.") - else: - # Send the delete action to the server. - embyconn = utils.kodiSQL('plex') - embycursor = embyconn.cursor() - emby_db = embydb.Embydb_Functions(embycursor) - emby_dbitem = emby_db.getItem_byKodiId(kodiid, type) - try: - itemid = emby_dbitem[0] - except TypeError: - log.info("Could not find itemid in emby database.") - else: - if settings('skipContextMenu') != "true": - resp = xbmcgui.Dialog().yesno( - heading="Confirm delete", - line1="Delete file on Emby Server?") - if not resp: - log.info("User skipped deletion.") - embycursor.close() - return - - url = "{server}/emby/Items/%s?format=json" % itemid - log.info("Deleting request: %s" % itemid) - doUtils.downloadUrl(url, action_type="DELETE") - finally: - embycursor.close()''' elif method == "System.OnSleep": # Connection is going to sleep @@ -219,10 +186,10 @@ class KodiMonitor(xbmc.Monitor): if plexid is None: # Get Plex' item id - with embydb.GetEmbyDB() as emby_db: - emby_dbitem = emby_db.getItem_byKodiId(kodiid, typus) + with plexdb.Get_Plex_DB() as plexcursor: + plex_dbitem = plexcursor.getItem_byKodiId(kodiid, typus) try: - plexid = emby_dbitem[0] + plexid = plex_dbitem[0] except TypeError: log.info("No Plex id returned for kodiid %s. Aborting playback" " report" % kodiid) diff --git a/resources/lib/librarysync.py b/resources/lib/librarysync.py index 749990cd..fdf96ade 100644 --- a/resources/lib/librarysync.py +++ b/resources/lib/librarysync.py @@ -11,7 +11,7 @@ import xbmc import xbmcgui import xbmcvfs -from utils import window, settings, getUnixTimestamp, kodiSQL, sourcesXML,\ +from utils import window, settings, getUnixTimestamp, sourcesXML,\ ThreadMethods, ThreadMethodsAdditionalStop, LogTime, getScreensaver,\ setScreensaver, playlistXSP, language as lang, DateToKodi, reset,\ advancedSettingsXML, getKodiVideoDBPath, tryDecode, deletePlaylists,\ @@ -19,7 +19,7 @@ from utils import window, settings, getUnixTimestamp, kodiSQL, sourcesXML,\ import clientinfo import downloadutils import itemtypes -import embydb_functions as embydb +import plexdb_functions as plexdb import kodidb_functions as kodidb import userclient import videonodes @@ -302,9 +302,9 @@ class ProcessFanartThread(Thread): # Leave the Plex art untouched allartworks = None else: - with embydb.GetEmbyDB() as emby_db: + with plexdb.Get_Plex_DB() as plex_db: try: - kodiId = emby_db.getItem_byId(item['itemId'])[0] + kodiId = plex_db.getItem_byId(item['itemId'])[0] except TypeError: log.error('Could not get Kodi id for plex id %s' % item['itemId']) @@ -530,25 +530,18 @@ class LibrarySync(Thread): def initializeDBs(self): """ - Run once during startup to verify that emby db exists. + Run once during startup to verify that plex db exists. """ - embyconn = kodiSQL('plex') - embycursor = embyconn.cursor() - # Create the tables for the emby database - # emby, view, version - embycursor.execute( - """CREATE TABLE IF NOT EXISTS emby( - emby_id TEXT UNIQUE, media_folder TEXT, emby_type TEXT, media_type TEXT, kodi_id INTEGER, - kodi_fileid INTEGER, kodi_pathid INTEGER, parent_id INTEGER, checksum INTEGER)""") - embycursor.execute( - """CREATE TABLE IF NOT EXISTS view( - view_id TEXT UNIQUE, view_name TEXT, media_type TEXT, kodi_tagid INTEGER)""") - embycursor.execute("CREATE TABLE IF NOT EXISTS version(idVersion TEXT)") - embyconn.commit() - - # content sync: movies, tvshows, musicvideos, music - embyconn.close() - + with plexdb.Get_Plex_DB() as plex_db: + # Create the tables for the plex database + plex_db.plexcursor.execute( + """CREATE TABLE IF NOT EXISTS emby( + emby_id TEXT UNIQUE, media_folder TEXT, emby_type TEXT, media_type TEXT, kodi_id INTEGER, + kodi_fileid INTEGER, kodi_pathid INTEGER, parent_id INTEGER, checksum INTEGER)""") + plex_db.plexcursor.execute( + """CREATE TABLE IF NOT EXISTS view( + view_id TEXT UNIQUE, view_name TEXT, media_type TEXT, kodi_tagid INTEGER)""") + plex_db.plexcursor.execute("CREATE TABLE IF NOT EXISTS version(idVersion TEXT)") # Create an index for actors to speed up sync create_actor_db_index() @@ -634,7 +627,7 @@ class LibrarySync(Thread): log.error('Path hack failed with error message: %s' % str(e)) return True - def processView(self, folderItem, kodi_db, emby_db, totalnodes): + def processView(self, folderItem, kodi_db, plex_db, totalnodes): vnodes = self.vnodes folder = folderItem.attrib mediatype = folder['type'] @@ -652,8 +645,8 @@ class LibrarySync(Thread): foldername = folder['title'] viewtype = folder['type'] - # Get current media folders from emby database - view = emby_db.getView_byId(folderid) + # Get current media folders from plex database + view = plex_db.getView_byId(folderid) try: current_viewname = view[0] current_viewtype = view[1] @@ -676,8 +669,8 @@ class LibrarySync(Thread): folderid) nodes.append(foldername) totalnodes += 1 - # Add view to emby database - emby_db.addView(folderid, foldername, viewtype, tagid) + # Add view to plex database + plex_db.addView(folderid, foldername, viewtype, tagid) else: log.info(' '.join(( "Found viewid: %s" % folderid, @@ -699,10 +692,10 @@ class LibrarySync(Thread): tagid = kodi_db.createTag(foldername) # Update view with new info - emby_db.updateView(foldername, tagid, folderid) + plex_db.updateView(foldername, tagid, folderid) if mediatype != "artist": - if emby_db.getView_byName(current_viewname) is None: + if plex_db.getView_byName(current_viewname) is None: # The tag could be a combined view. Ensure there's # no other tags with the same name before deleting # playlist. @@ -739,7 +732,7 @@ class LibrarySync(Thread): totalnodes += 1 # Update items with new tag - items = emby_db.getItem_byView(folderid) + items = plex_db.getItem_byView(folderid) for item in items: # Remove the "s" from viewtype for tags kodi_db.updateTag( @@ -806,15 +799,15 @@ class LibrarySync(Thread): vnodes.clearProperties() totalnodes = len(self.sorted_views) - with embydb.GetEmbyDB() as emby_db: + with plexdb.Get_Plex_DB() as plex_db: # Backup old views to delete them later, if needed (at the end # of this method, only unused views will be left in oldviews) - self.old_views = emby_db.getViews() + self.old_views = plex_db.getViews() with kodidb.GetKodiDB('video') as kodi_db: for folderItem in sections: totalnodes = self.processView(folderItem, kodi_db, - emby_db, + plex_db, totalnodes) # Add video nodes listings # Plex: there seem to be no favorites/favorites tag @@ -833,19 +826,17 @@ class LibrarySync(Thread): # "movies", # "channels") # totalnodes += 1 - with kodidb.GetKodiDB('music') as kodi_db: - pass # Save total window('Plex.nodes.total', str(totalnodes)) # Reopen DB connection to ensure that changes were commited before - with embydb.GetEmbyDB() as emby_db: + with plexdb.Get_Plex_DB() as plex_db: log.info("Removing views: %s" % self.old_views) for view in self.old_views: - emby_db.removeView(view) + plex_db.removeView(view) # update views for all: - self.views = emby_db.getAllViewInfo() + self.views = plex_db.getAllViewInfo() log.info("Finished processing views. Views saved: %s" % self.views) return True @@ -1052,11 +1043,11 @@ class LibrarySync(Thread): self.allKodiElementsId = {} if self.compare: - with embydb.GetEmbyDB() as emby_db: + with plexdb.Get_Plex_DB() as plex_db: # Get movies from Plex server # Pull the list of movies and boxsets in Kodi try: - self.allKodiElementsId = dict(emby_db.getChecksum('Movie')) + self.allKodiElementsId = dict(plex_db.getChecksum('Movie')) except ValueError: self.allKodiElementsId = {} @@ -1139,11 +1130,11 @@ class LibrarySync(Thread): self.allKodiElementsId = {} if self.compare: - with embydb.GetEmbyDB() as emby_db: + with plexdb.Get_Plex_DB() as plex: # Pull the list of TV shows already in Kodi for kind in ('Series', 'Season', 'Episode'): try: - elements = dict(emby_db.getChecksum(kind)) + elements = dict(plex.getChecksum(kind)) self.allKodiElementsId.update(elements) # Yet empty/not yet synched except ValueError: @@ -1309,10 +1300,10 @@ class LibrarySync(Thread): # Get a list of items already existing in Kodi db if self.compare: - with embydb.GetEmbyDB() as emby_db: + with plexdb.Get_Plex_DB() as plex_db: # Pull the list of items already in Kodi try: - elements = dict(emby_db.getChecksum(kind)) + elements = dict(plex_db.getChecksum(kind)) self.allKodiElementsId.update(elements) # Yet empty/nothing yet synched except ValueError: @@ -1560,14 +1551,14 @@ class LibrarySync(Thread): where """ items = [] - with embydb.GetEmbyDB() as emby_db: + with plexdb.Get_Plex_DB() as plex_db: for item in data: # Drop buffering messages immediately state = item.get('state') if state == 'buffering': continue ratingKey = item.get('ratingKey') - kodiInfo = emby_db.getItem_byId(ratingKey) + kodiInfo = plex_db.getItem_byId(ratingKey) if kodiInfo is None: # Item not (yet) in Kodi library continue @@ -1669,9 +1660,9 @@ class LibrarySync(Thread): 'Movie': 'Movies', 'Series': 'TVShows' } - with embydb.GetEmbyDB() as emby_db: + with plexdb.Get_Plex_DB() as plex_db: for plextype in typus: - items.extend(emby_db.itemsByType(plextype)) + items.extend(plex_db.itemsByType(plextype)) # Shuffle the list to not always start out identically shuffle(items) for item in items: diff --git a/resources/lib/player.py b/resources/lib/player.py index 06b6b0f8..3c983315 100644 --- a/resources/lib/player.py +++ b/resources/lib/player.py @@ -11,7 +11,7 @@ from utils import window, settings, language as lang, DateToKodi, \ getUnixTimestamp import clientinfo import downloadutils -import embydb_functions as embydb +import plexdb_functions as plexdb import kodidb_functions as kodidb ############################################################################### @@ -88,13 +88,13 @@ class Player(xbmc.Player): log.info("ONPLAYBACK_STARTED: %s itemid: %s" % (currentFile, itemId)) - embyitem = "emby_%s" % currentFile - runtime = window("%s.runtime" % embyitem) - refresh_id = window("%s.refreshid" % embyitem) - playMethod = window("%s.playmethod" % embyitem) - itemType = window("%s.type" % embyitem) + plexitem = "emby_%s" % currentFile + runtime = window("%s.runtime" % plexitem) + refresh_id = window("%s.refreshid" % plexitem) + playMethod = window("%s.playmethod" % plexitem) + itemType = window("%s.type" % plexitem) try: - playcount = int(window("%s.playcount" % embyitem)) + playcount = int(window("%s.playcount" % plexitem)) except ValueError: playcount = 0 window('emby_skipWatched%s' % itemId, value="true") @@ -134,7 +134,7 @@ class Player(xbmc.Player): volume = result.get('volume') muted = result.get('muted') - # Postdata structure to send to Emby server + # Postdata structure to send to plex server url = "{server}/:/timeline?" postdata = { @@ -154,7 +154,7 @@ class Player(xbmc.Player): postdata['AudioStreamIndex'] = window("%sAudioStreamIndex" % currentFile) postdata['SubtitleStreamIndex'] = window("%sSubtitleStreamIndex" % currentFile) else: - # Get the current kodi audio and subtitles and convert to Emby equivalent + # Get the current kodi audio and subtitles and convert to plex equivalent tracks_query = { "jsonrpc": "2.0", "id": 1, @@ -190,9 +190,9 @@ class Player(xbmc.Player): # Postdata for the subtitles if subsEnabled and len(xbmc.Player().getAvailableSubtitleStreams()) > 0: - # Number of audiotracks to help get Emby Index + # Number of audiotracks to help get plex Index audioTracks = len(xbmc.Player().getAvailableAudioStreams()) - mapping = window("%s.indexMapping" % embyitem) + mapping = window("%s.indexMapping" % plexitem) if mapping: # Set in playbackutils.py @@ -229,10 +229,10 @@ class Player(xbmc.Player): log.error('Could not get kodi runtime, setting to zero') runtime = 0 - with embydb.GetEmbyDB() as emby_db: - emby_dbitem = emby_db.getItem_byId(itemId) + with plexdb.Get_Plex_DB() as plex_db: + plex_dbitem = plex_db.getItem_byId(itemId) try: - fileid = emby_dbitem[1] + fileid = plex_dbitem[1] except TypeError: log.info("Could not find fileid in plex db.") fileid = None diff --git a/resources/lib/playlist_func.py b/resources/lib/playlist_func.py index 8e355eda..cd94e01f 100644 --- a/resources/lib/playlist_func.py +++ b/resources/lib/playlist_func.py @@ -1,9 +1,9 @@ import logging from urllib import quote -import embydb_functions as embydb +import plexdb_functions as plexdb from downloadutils import DownloadUtils as DU -from utils import JSONRPC, tryEncode, tryDecode +from utils import JSONRPC, tryEncode from PlexAPI import API ############################################################################### @@ -12,7 +12,7 @@ log = logging.getLogger("PLEX."+__name__) ############################################################################### -# kodi_item: +# kodi_item dict: # {u'type': u'movie', u'id': 3, 'file': path-to-file} @@ -94,12 +94,12 @@ def playlist_item_from_kodi(kodi_item): item = Playlist_Item() item.kodi_id = kodi_item.get('id') if item.kodi_id: - with embydb.GetEmbyDB() as emby_db: - emby_dbitem = emby_db.getItem_byKodiId(kodi_item['id'], + with plexdb.Get_Plex_DB() as plex_db: + plex_dbitem = plex_db.getItem_byKodiId(kodi_item['id'], kodi_item['type']) try: - item.plex_id = emby_dbitem[0] - item.plex_UUID = emby_dbitem[0] # we dont need the uuid yet :-) + item.plex_id = plex_dbitem[0] + item.plex_UUID = plex_dbitem[0] # we dont need the uuid yet :-) except TypeError: pass item.file = kodi_item.get('file') @@ -121,11 +121,11 @@ def playlist_item_from_plex(plex_id): """ item = Playlist_Item() item.plex_id = plex_id - with embydb.GetEmbyDB() as emby_db: - emby_dbitem = emby_db.getItem_byId(plex_id) + with plexdb.Get_Plex_DB() as plex_db: + plex_dbitem = plex_db.getItem_byId(plex_id) try: - item.kodi_id = emby_dbitem[0] - item.kodi_type = emby_dbitem[4] + item.kodi_id = plex_dbitem[0] + item.kodi_type = plex_dbitem[4] except: raise KeyError('Could not find plex_id %s in database' % plex_id) return item @@ -141,8 +141,8 @@ def playlist_item_from_xml(playlist, xml_video_element): item.ID = xml_video_element.attrib['%sItemID' % playlist.kind] item.guid = xml_video_element.attrib.get('guid') if item.plex_id: - with embydb.GetEmbyDB() as emby_db: - db_element = emby_db.getItem_byId(item.plex_id) + with plexdb.Get_Plex_DB() as plex_db: + db_element = plex_db.getItem_byId(item.plex_id) try: item.kodi_id, item.kodi_type = int(db_element[0]), db_element[4] except TypeError: @@ -517,59 +517,3 @@ def remove_from_Kodi_playlist(playlist, pos): 'position': pos })) del playlist.items[pos] - - -# NOT YET UPDATED!! - -def _processItems(self, startitem, startPlayer=False): - startpos = None - with embydb.GetEmbyDB() as emby_db: - for pos, item in enumerate(self.items): - kodiId = None - plexId = item['plexId'] - embydb_item = emby_db.getItem_byId(plexId) - try: - kodiId = embydb_item[0] - mediatype = embydb_item[4] - except TypeError: - log.info('Couldnt find item %s in Kodi db' % plexId) - xml = PF.GetPlexMetadata(plexId) - if xml in (None, 401): - log.error('Could not download plexId %s' % plexId) - else: - log.debug('Downloaded xml metadata, adding now') - self._addtoPlaylist_xbmc(xml[0]) - else: - # Add to playlist - log.debug("Adding %s PlexId %s, KodiId %s to playlist." - % (mediatype, plexId, kodiId)) - self._addtoPlaylist(kodiId, mediatype) - # Add the kodiId - if kodiId is not None: - item['kodiId'] = str(kodiId) - if (startpos is None and startitem[1] == item[startitem[0]]): - startpos = pos - - if startPlayer is True and len(self.playlist) > 0: - if startpos is not None: - self.player.play(self.playlist, startpos=startpos) - else: - log.info('Never received a starting item for playlist, ' - 'starting with the first entry') - self.player.play(self.playlist) - -def _addtoPlaylist_xbmc(self, item): - API = PlexAPI.API(item) - params = { - 'mode': "play", - 'dbid': 'plextrailer', - 'id': API.getRatingKey(), - 'filename': API.getKey() - } - playurl = "plugin://plugin.video.plexkodiconnect/movies/?%s" \ - % urlencode(params) - - listitem = API.CreateListItemFromPlexItem() - playbackutils.PlaybackUtils(item).setArtwork(listitem) - - self.playlist.add(playurl, listitem) diff --git a/resources/lib/plexbmchelper/functions.py b/resources/lib/plexbmchelper/functions.py index 443b1c8f..d9d19f85 100644 --- a/resources/lib/plexbmchelper/functions.py +++ b/resources/lib/plexbmchelper/functions.py @@ -5,7 +5,7 @@ import string import xbmc -import embydb_functions as embydb +import plexdb_functions as plexdb ############################################################################### @@ -146,11 +146,11 @@ class jsonClass(): def skipTo(self, plexId, typus): # playlistId = self.getPlaylistId(tryDecode(xbmc_type(typus))) # playerId = self. - with embydb.GetEmbyDB() as emby_db: - embydb_item = emby_db.getItem_byId(plexId) + with plexdb.Get_Plex_DB() as plex_db: + plexdb_item = plex_db.getItem_byId(plexId) try: - dbid = embydb_item[0] - mediatype = embydb_item[4] + dbid = plexdb_item[0] + mediatype = plexdb_item[4] except TypeError: log.info('Couldnt find item %s in Kodi db' % plexId) return diff --git a/resources/lib/embydb_functions.py b/resources/lib/plexdb_functions.py similarity index 74% rename from resources/lib/embydb_functions.py rename to resources/lib/plexdb_functions.py index d502a4b7..fa8d0eca 100644 --- a/resources/lib/embydb_functions.py +++ b/resources/lib/plexdb_functions.py @@ -12,29 +12,29 @@ log = logging.getLogger("PLEX."+__name__) ############################################################################### -class GetEmbyDB(): +class Get_Plex_DB(): """ - Usage: with GetEmbyDB() as emby_db: - do stuff with emby_db + Usage: with Get_Plex_DB() as plexcursor: + plexcursor.do_something() On exiting "with" (no matter what), commits get automatically committed and the db gets closed """ def __enter__(self): - self.embyconn = kodiSQL('plex') - self.emby_db = Embydb_Functions(self.embyconn.cursor()) - return self.emby_db + self.plexconn = kodiSQL('plex') + self.plexcursor = Plex_DB_Functions(self.plexconn.cursor()) + return self.plexcursor def __exit__(self, type, value, traceback): - self.embyconn.commit() - self.embyconn.close() + self.plexconn.commit() + self.plexconn.close() -class Embydb_Functions(): +class Plex_DB_Functions(): - def __init__(self, embycursor): + def __init__(self, plexcursor): - self.embycursor = embycursor + self.plexcursor = plexcursor def getViews(self): @@ -45,15 +45,15 @@ class Embydb_Functions(): "SELECT view_id", "FROM view" )) - self.embycursor.execute(query) - rows = self.embycursor.fetchall() + self.plexcursor.execute(query) + rows = self.plexcursor.fetchall() for row in rows: views.append(row[0]) return views def getAllViewInfo(self): - embycursor = self.embycursor + plexcursor = self.plexcursor views = [] query = ' '.join(( @@ -61,8 +61,8 @@ class Embydb_Functions(): "SELECT view_id, view_name, media_type", "FROM view" )) - embycursor.execute(query) - rows = embycursor.fetchall() + plexcursor.execute(query) + rows = plexcursor.fetchall() for row in rows: views.append({'id': row[0], 'name': row[1], @@ -78,8 +78,8 @@ class Embydb_Functions(): "FROM view", "WHERE view_id = ?" )) - self.embycursor.execute(query, (viewid,)) - view = self.embycursor.fetchone() + self.plexcursor.execute(query, (viewid,)) + view = self.plexcursor.fetchone() return view @@ -93,8 +93,8 @@ class Embydb_Functions(): "FROM view", "WHERE media_type = ?" )) - self.embycursor.execute(query, (mediatype,)) - rows = self.embycursor.fetchall() + self.plexcursor.execute(query, (mediatype,)) + rows = self.plexcursor.fetchall() for row in rows: views.append({ @@ -113,9 +113,9 @@ class Embydb_Functions(): "FROM view", "WHERE view_name = ?" )) - self.embycursor.execute(query, (tagname,)) + self.plexcursor.execute(query, (tagname,)) try: - view = self.embycursor.fetchone()[0] + view = self.plexcursor.fetchone()[0] except TypeError: view = None @@ -132,7 +132,7 @@ class Embydb_Functions(): VALUES (?, ?, ?, ?) ''' ) - self.embycursor.execute(query, (plexid, name, mediatype, tagid)) + self.plexcursor.execute(query, (plexid, name, mediatype, tagid)) def updateView(self, name, tagid, mediafolderid): @@ -142,7 +142,7 @@ class Embydb_Functions(): "SET view_name = ?, kodi_tagid = ?", "WHERE view_id = ?" )) - self.embycursor.execute(query, (name, tagid, mediafolderid)) + self.plexcursor.execute(query, (name, tagid, mediafolderid)) def removeView(self, viewid): @@ -151,7 +151,7 @@ class Embydb_Functions(): "DELETE FROM view", "WHERE view_id = ?" )) - self.embycursor.execute(query, (viewid,)) + self.plexcursor.execute(query, (viewid,)) def getItem_byFileId(self, fileId, kodiType): """ @@ -165,8 +165,8 @@ class Embydb_Functions(): "WHERE kodi_fileid = ? AND media_type = ?" )) try: - self.embycursor.execute(query, (fileId, kodiType)) - item = self.embycursor.fetchone()[0] + self.plexcursor.execute(query, (fileId, kodiType)) + item = self.plexcursor.fetchone()[0] return item except: return None @@ -183,8 +183,8 @@ class Embydb_Functions(): "WHERE kodi_id = ? AND media_type = ?" )) try: - self.embycursor.execute(query, (fileId, kodiType)) - item = self.embycursor.fetchone()[0] + self.plexcursor.execute(query, (fileId, kodiType)) + item = self.plexcursor.fetchone()[0] return item except: return None @@ -198,8 +198,8 @@ class Embydb_Functions(): "WHERE emby_id = ?" )) try: - self.embycursor.execute(query, (plexid,)) - item = self.embycursor.fetchone() + self.plexcursor.execute(query, (plexid,)) + item = self.plexcursor.fetchone() return item except: return None @@ -211,8 +211,8 @@ class Embydb_Functions(): "FROM emby", "WHERE emby_id LIKE ?" )) - self.embycursor.execute(query, (plexid+"%",)) - return self.embycursor.fetchall() + self.plexcursor.execute(query, (plexid+"%",)) + return self.plexcursor.fetchall() def getItem_byView(self, mediafolderid): @@ -222,8 +222,8 @@ class Embydb_Functions(): "FROM emby", "WHERE media_folder = ?" )) - self.embycursor.execute(query, (mediafolderid,)) - return self.embycursor.fetchall() + self.plexcursor.execute(query, (mediafolderid,)) + return self.plexcursor.fetchall() def getPlexId(self, kodiid, mediatype): """ @@ -236,8 +236,8 @@ class Embydb_Functions(): "WHERE kodi_id = ? AND media_type = ?" )) try: - self.embycursor.execute(query, (kodiid, mediatype)) - item = self.embycursor.fetchone() + self.plexcursor.execute(query, (kodiid, mediatype)) + item = self.plexcursor.fetchone() return item except: return None @@ -251,8 +251,8 @@ class Embydb_Functions(): "WHERE kodi_id = ?", "AND media_type = ?" )) - self.embycursor.execute(query, (kodiid, mediatype,)) - return self.embycursor.fetchone() + self.plexcursor.execute(query, (kodiid, mediatype,)) + return self.plexcursor.fetchone() def getItem_byParentId(self, parentid, mediatype): @@ -263,8 +263,8 @@ class Embydb_Functions(): "WHERE parent_id = ?", "AND media_type = ?" )) - self.embycursor.execute(query, (parentid, mediatype,)) - return self.embycursor.fetchall() + self.plexcursor.execute(query, (parentid, mediatype,)) + return self.plexcursor.fetchall() def getItemId_byParentId(self, parentid, mediatype): @@ -275,8 +275,8 @@ class Embydb_Functions(): "WHERE parent_id = ?", "AND media_type = ?" )) - self.embycursor.execute(query, (parentid, mediatype,)) - return self.embycursor.fetchall() + self.plexcursor.execute(query, (parentid, mediatype,)) + return self.plexcursor.fetchall() def getChecksum(self, mediatype): @@ -286,8 +286,8 @@ class Embydb_Functions(): "FROM emby", "WHERE emby_type = ?" )) - self.embycursor.execute(query, (mediatype,)) - return self.embycursor.fetchall() + self.plexcursor.execute(query, (mediatype,)) + return self.plexcursor.fetchall() def getMediaType_byId(self, plexid): @@ -297,9 +297,9 @@ class Embydb_Functions(): "FROM emby", "WHERE emby_id = ?" )) - self.embycursor.execute(query, (plexid,)) + self.plexcursor.execute(query, (plexid,)) try: - itemtype = self.embycursor.fetchone()[0] + itemtype = self.plexcursor.fetchone()[0] except TypeError: itemtype = None @@ -330,18 +330,18 @@ class Embydb_Functions(): VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?) ''' ) - self.embycursor.execute(query, (plexid, kodiid, fileid, pathid, embytype, mediatype, + self.plexcursor.execute(query, (plexid, kodiid, fileid, pathid, embytype, mediatype, parentid, checksum, mediafolderid)) def updateReference(self, plexid, checksum): query = "UPDATE emby SET checksum = ? WHERE emby_id = ?" - self.embycursor.execute(query, (checksum, plexid)) + self.plexcursor.execute(query, (checksum, plexid)) def updateParentId(self, plexid, parent_kodiid): query = "UPDATE emby SET parent_id = ? WHERE emby_id = ?" - self.embycursor.execute(query, (parent_kodiid, plexid)) + self.plexcursor.execute(query, (parent_kodiid, plexid)) def removeItems_byParentId(self, parent_kodiid, mediatype): @@ -351,7 +351,7 @@ class Embydb_Functions(): "WHERE parent_id = ?", "AND media_type = ?" )) - self.embycursor.execute(query, (parent_kodiid, mediatype,)) + self.plexcursor.execute(query, (parent_kodiid, mediatype,)) def removeItem_byKodiId(self, kodiid, mediatype): @@ -361,17 +361,17 @@ class Embydb_Functions(): "WHERE kodi_id = ?", "AND media_type = ?" )) - self.embycursor.execute(query, (kodiid, mediatype,)) + self.plexcursor.execute(query, (kodiid, mediatype,)) def removeItem(self, plexid): query = "DELETE FROM emby WHERE emby_id = ?" - self.embycursor.execute(query, (plexid,)) + self.plexcursor.execute(query, (plexid,)) def removeWildItem(self, plexid): query = "DELETE FROM emby WHERE emby_id LIKE ?" - self.embycursor.execute(query, (plexid+"%",)) + self.plexcursor.execute(query, (plexid+"%",)) def itemsByType(self, plextype): """ @@ -390,9 +390,9 @@ class Embydb_Functions(): "FROM emby", "WHERE emby_type = ?", )) - self.embycursor.execute(query, (plextype, )) + self.plexcursor.execute(query, (plextype, )) result = [] - for row in self.embycursor.fetchall(): + for row in self.plexcursor.fetchall(): result.append({ 'plexId': row[0], 'kodiId': row[1],