Rename embydb_functions to plexdb_functions

This commit is contained in:
tomkat83 2017-01-04 20:57:16 +01:00
parent 266ad70605
commit ad80fdfe1d
10 changed files with 309 additions and 589 deletions

View file

@ -51,7 +51,7 @@ from utils import window, settings, language as lang, tryDecode, tryEncode, \
DateToKodi, KODILANGUAGE DateToKodi, KODILANGUAGE
from PlexFunctions import PLEX_TO_KODI_TIMEFACTOR, PMSHttpsEnabled, \ from PlexFunctions import PLEX_TO_KODI_TIMEFACTOR, PMSHttpsEnabled, \
REMAP_TYPE_FROM_PLEXTYPE REMAP_TYPE_FROM_PLEXTYPE
import embydb_functions as embydb import plexdb_functions as plexdb
############################################################################### ###############################################################################
@ -2305,10 +2305,10 @@ class API():
kodiindex = 0 kodiindex = 0
for stream in mediastreams: for stream in mediastreams:
index = stream.attrib['id'] 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. # only external subtitles.
key = stream.attrib.get('key') 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: if stream.attrib.get('streamType') == "3" and key:
# Direct stream # Direct stream
url = ("%s%s" % (self.server, key)) url = ("%s%s" % (self.server, key))
@ -2467,10 +2467,10 @@ class API():
plexId = self.getRatingKey() plexId = self.getRatingKey()
listItem.setProperty('plexid', plexId) listItem.setProperty('plexid', plexId)
with embydb.GetEmbyDB() as emby_db: with plexdb.Get_Plex_DB() as plex_db:
try: try:
listItem.setProperty('dbid', listItem.setProperty('dbid',
str(emby_db.getItem_byId(plexId)[0])) str(plex_db.getItem_byId(plexId)[0]))
except TypeError: except TypeError:
pass pass
# Expensive operation # Expensive operation

View file

@ -8,7 +8,7 @@ import xbmc
import xbmcaddon import xbmcaddon
import PlexFunctions as PF 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 utils import window, settings, dialog, language as lang, kodiSQL
from dialogs import context from dialogs import context
@ -75,8 +75,8 @@ class ContextMenu(object):
def _get_item_id(cls, kodi_id, item_type): def _get_item_id(cls, kodi_id, item_type):
item_id = xbmc.getInfoLabel('ListItem.Property(plexid)') item_id = xbmc.getInfoLabel('ListItem.Property(plexid)')
if not item_id and kodi_id and item_type: if not item_id and kodi_id and item_type:
with embydb.GetEmbyDB() as emby_db: with plexdb.Get_Plex_DB() as plexcursor:
item = emby_db.getItem_byKodiId(kodi_id, item_type) item = plexcursor.getItem_byKodiId(kodi_id, item_type)
try: try:
item_id = item[0] item_id = item[0]
except TypeError: except TypeError:
@ -140,8 +140,8 @@ class ContextMenu(object):
elif selected == OPTIONS['PMS_Play']: elif selected == OPTIONS['PMS_Play']:
self._PMS_play() self._PMS_play()
elif selected == OPTIONS['Refresh']: # elif selected == OPTIONS['Refresh']:
self.emby.refreshItem(self.item_id) # self.emby.refreshItem(self.item_id)
# elif selected == OPTIONS['AddFav']: # elif selected == OPTIONS['AddFav']:
# self.emby.updateUserRating(self.item_id, favourite=True) # self.emby.updateUserRating(self.item_id, favourite=True)

View file

@ -17,7 +17,7 @@ from utils import window, settings, language as lang
from utils import tryDecode, tryEncode, CatchExceptions from utils import tryDecode, tryEncode, CatchExceptions
import clientinfo import clientinfo
import downloadutils import downloadutils
import embydb_functions as embydb import plexdb_functions as plexdb
import playbackutils as pbutils import playbackutils as pbutils
import PlexFunctions import PlexFunctions
@ -263,12 +263,8 @@ def deleteItem():
log.error("Unknown type, unable to proceed.") log.error("Unknown type, unable to proceed.")
return return
from utils import kodiSQL with plexdb.Get_Plex_DB() as plexcursor:
embyconn = kodiSQL('plex') item = plexcursor.getItem_byKodiId(dbid, itemtype)
embycursor = embyconn.cursor()
emby_db = embydb.Embydb_Functions(embycursor)
item = emby_db.getItem_byKodiId(dbid, itemtype)
embycursor.close()
try: try:
plexid = item[0] plexid = item[0]

View file

@ -12,7 +12,7 @@ import xbmcgui
import artwork import artwork
from utils import tryEncode, tryDecode, settings, window, kodiSQL, \ from utils import tryEncode, tryDecode, settings, window, kodiSQL, \
CatchExceptions, KODIVERSION CatchExceptions, KODIVERSION
import embydb_functions as embydb import plexdb_functions as plexdb
import kodidb_functions as kodidb import kodidb_functions as kodidb
import PlexAPI import PlexAPI
@ -45,11 +45,11 @@ class Items(object):
""" """
Open DB connections and cursors Open DB connections and cursors
""" """
self.embyconn = kodiSQL('plex') self.plexconn = kodiSQL('plex')
self.embycursor = self.embyconn.cursor() self.plexcursor = self.plexconn.cursor()
self.kodiconn = kodiSQL('video') self.kodiconn = kodiSQL('video')
self.kodicursor = self.kodiconn.cursor() 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) self.kodi_db = kodidb.Kodidb_Functions(self.kodicursor)
return self return self
@ -57,9 +57,9 @@ class Items(object):
""" """
Make sure DB changes are committed and connection to DB is closed. Make sure DB changes are committed and connection to DB is closed.
""" """
self.embyconn.commit() self.plexconn.commit()
self.kodiconn.commit() self.kodiconn.commit()
self.embyconn.close() self.plexconn.close()
self.kodiconn.close() self.kodiconn.close()
return self return self
@ -85,170 +85,6 @@ class Items(object):
self.kodicursor) self.kodicursor)
self.kodi_db.assignBoxset(setid, kodiId) 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): def updateUserdata(self, xml, viewtag=None, viewid=None):
""" """
Updates the Kodi watched state of the item from PMS. Also retrieves Updates the Kodi watched state of the item from PMS. Also retrieves
@ -260,7 +96,7 @@ class Items(object):
API = PlexAPI.API(mediaitem) API = PlexAPI.API(mediaitem)
# Get key and db entry on the Kodi db side # Get key and db entry on the Kodi db side
try: try:
fileid = self.emby_db.getItem_byId(API.getRatingKey())[1] fileid = self.plex_db.getItem_byId(API.getRatingKey())[1]
except: except:
continue continue
# Grab the user's viewcount, resume points etc. from PMS' answer # 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): def add_update(self, item, viewtag=None, viewid=None):
# Process single movie # Process single movie
kodicursor = self.kodicursor kodicursor = self.kodicursor
emby_db = self.emby_db plex_db = self.plex_db
artwork = self.artwork artwork = self.artwork
API = PlexAPI.API(item) API = PlexAPI.API(item)
@ -318,11 +154,11 @@ class Movies(Items):
if not itemid: if not itemid:
log.error("Cannot parse XML data for movie") log.error("Cannot parse XML data for movie")
return return
emby_dbitem = emby_db.getItem_byId(itemid) plex_dbitem = plex_db.getItem_byId(itemid)
try: try:
movieid = emby_dbitem[0] movieid = plex_dbitem[0]
fileid = emby_dbitem[1] fileid = plex_dbitem[1]
pathid = emby_dbitem[2] pathid = plex_dbitem[2]
except TypeError: except TypeError:
# movieid # movieid
@ -495,10 +331,10 @@ class Movies(Items):
sorttitle, runtime, mpaa, genre, director, title, studio, sorttitle, runtime, mpaa, genre, director, title, studio,
trailer, country, playurl, pathid)) 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 # idempotent; the call here updates also fileid and pathid when item is
# moved or renamed # moved or renamed
emby_db.addReference(itemid, movieid, "Movie", "movie", fileid, pathid, plex_db.addReference(itemid, movieid, "Movie", "movie", fileid, pathid,
None, checksum, viewid) None, checksum, viewid)
# Update the path # Update the path
@ -543,23 +379,23 @@ class Movies(Items):
self.kodi_db.addPlaystate(fileid, resume, runtime, playcount, dateplayed) self.kodi_db.addPlaystate(fileid, resume, runtime, playcount, dateplayed)
def remove(self, itemid): def remove(self, itemid):
# Remove movieid, fileid, emby reference # Remove movieid, fileid, plex reference
emby_db = self.emby_db plex_db = self.plex_db
kodicursor = self.kodicursor kodicursor = self.kodicursor
artwork = self.artwork artwork = self.artwork
emby_dbitem = emby_db.getItem_byId(itemid) plex_dbitem = plex_db.getItem_byId(itemid)
try: try:
kodiid = emby_dbitem[0] kodiid = plex_dbitem[0]
fileid = emby_dbitem[1] fileid = plex_dbitem[1]
mediatype = emby_dbitem[4] mediatype = plex_dbitem[4]
log.info("Removing %sid: %s fileid: %s" log.info("Removing %sid: %s fileid: %s"
% (mediatype, kodiid, fileid)) % (mediatype, kodiid, fileid))
except TypeError: except TypeError:
return return
# Remove the emby reference # Remove the plex reference
emby_db.removeItem(itemid) plex_db.removeItem(itemid)
# Remove artwork # Remove artwork
artwork.deleteArtwork(kodiid, mediatype, kodicursor) artwork.deleteArtwork(kodiid, mediatype, kodicursor)
@ -570,13 +406,13 @@ class Movies(Items):
elif mediatype == "set": elif mediatype == "set":
# Delete kodi boxset # Delete kodi boxset
boxset_movies = emby_db.getItem_byParentId(kodiid, "movie") boxset_movies = plex_db.getItem_byParentId(kodiid, "movie")
for movie in boxset_movies: for movie in boxset_movies:
plexid = movie[0] plexid = movie[0]
movieid = movie[1] movieid = movie[1]
self.kodi_db.removefromBoxset(movieid) self.kodi_db.removefromBoxset(movieid)
# Update emby reference # Update plex reference
emby_db.updateParentId(plexid, None) plex_db.updateParentId(plexid, None)
kodicursor.execute("DELETE FROM sets WHERE idSet = ?", (kodiid,)) kodicursor.execute("DELETE FROM sets WHERE idSet = ?", (kodiid,))
@ -590,7 +426,7 @@ class TVShows(Items):
def add_update(self, item, viewtag=None, viewid=None): def add_update(self, item, viewtag=None, viewid=None):
# Process single tvshow # Process single tvshow
kodicursor = self.kodicursor kodicursor = self.kodicursor
emby_db = self.emby_db plex_db = self.plex_db
artwork = self.artwork artwork = self.artwork
API = PlexAPI.API(item) API = PlexAPI.API(item)
@ -604,10 +440,10 @@ class TVShows(Items):
# 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
update_item = True update_item = True
force_episodes = False force_episodes = False
emby_dbitem = emby_db.getItem_byId(itemid) plex_dbitem = plex_db.getItem_byId(itemid)
try: try:
showid = emby_dbitem[0] showid = plex_dbitem[0]
pathid = emby_dbitem[2] pathid = plex_dbitem[2]
except TypeError: except TypeError:
update_item = False update_item = False
kodicursor.execute("select coalesce(max(idShow),0) from tvshow") 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 re-add episodes after the show is re-created.
force_episodes = True 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 # fileId information
checksum = API.getChecksum() checksum = API.getChecksum()
@ -701,7 +532,7 @@ class TVShows(Items):
# Add reference is idempotent; the call here updates also fileid # Add reference is idempotent; the call here updates also fileid
# and pathid when item is moved or renamed # and pathid when item is moved or renamed
emby_db.addReference(itemid, plex_db.addReference(itemid,
showid, showid,
"Series", "Series",
"tvshow", "tvshow",
@ -737,8 +568,8 @@ class TVShows(Items):
query = "INSERT INTO tvshowlinkpath(idShow, idPath) values(?, ?)" query = "INSERT INTO tvshowlinkpath(idShow, idPath) values(?, ?)"
kodicursor.execute(query, (showid, pathid)) kodicursor.execute(query, (showid, pathid))
# Create the reference in emby table # Create the reference in plex table
emby_db.addReference(itemid, showid, "Series", "tvshow", pathid=pathid, plex_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((
@ -765,11 +596,11 @@ class TVShows(Items):
tags.extend(collections) tags.extend(collections)
self.kodi_db.addTags(showid, tags, "tvshow") self.kodi_db.addTags(showid, tags, "tvshow")
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 = embyserver.getEpisodesbyShow(itemid) # all_episodes = embyserver.getEpisodesbyShow(itemid)
self.added_episode(all_episodes['Items'], None) # self.added_episode(all_episodes['Items'], None)
@CatchExceptions(warnuser=True) @CatchExceptions(warnuser=True)
def add_updateSeason(self, item, viewtag=None, viewid=None): def add_updateSeason(self, item, viewtag=None, viewid=None):
@ -779,15 +610,15 @@ class TVShows(Items):
log.error('Error getting itemid for season, skipping') log.error('Error getting itemid for season, skipping')
return return
kodicursor = self.kodicursor kodicursor = self.kodicursor
emby_db = self.emby_db plex_db = self.plex_db
artwork = self.artwork artwork = self.artwork
seasonnum = API.getIndex() seasonnum = API.getIndex()
# Get parent tv show Plex id # Get parent tv show Plex id
plexshowid = item.attrib.get('parentRatingKey') plexshowid = item.attrib.get('parentRatingKey')
# Get Kodi showid # Get Kodi showid
emby_dbitem = emby_db.getItem_byId(plexshowid) plex_dbitem = plex_db.getItem_byId(plexshowid)
try: try:
showid = emby_dbitem[0] showid = plex_dbitem[0]
except: except:
log.error('Could not find parent tv show for season %s. ' log.error('Could not find parent tv show for season %s. '
'Skipping season for now.' % (itemid)) 'Skipping season for now.' % (itemid))
@ -797,9 +628,9 @@ class TVShows(Items):
checksum = API.getChecksum() checksum = API.getChecksum()
# Check whether Season already exists # Check whether Season already exists
update_item = True update_item = True
emby_dbitem = emby_db.getItem_byId(itemid) plex_dbitem = plex_db.getItem_byId(itemid)
try: try:
embyDbItemId = emby_dbitem[0] plexdbItemId = plex_dbitem[0]
except TypeError: except TypeError:
update_item = False update_item = False
@ -808,11 +639,11 @@ class TVShows(Items):
artwork.addArtwork(allartworks, seasonid, "season", kodicursor) artwork.addArtwork(allartworks, seasonid, "season", kodicursor)
if update_item: if update_item:
# Update a reference: checksum in emby table # Update a reference: checksum in plex table
emby_db.updateReference(itemid, checksum) plex_db.updateReference(itemid, checksum)
else: else:
# Create the reference in emby table # Create the reference in plex table
emby_db.addReference(itemid, plex_db.addReference(itemid,
seasonid, seasonid,
"Season", "Season",
"season", "season",
@ -826,7 +657,7 @@ class TVShows(Items):
""" """
# Process single episode # Process single episode
kodicursor = self.kodicursor kodicursor = self.kodicursor
emby_db = self.emby_db plex_db = self.plex_db
artwork = self.artwork artwork = self.artwork
API = PlexAPI.API(item) API = PlexAPI.API(item)
@ -838,11 +669,11 @@ class TVShows(Items):
if not itemid: if not itemid:
log.error('Error getting itemid for episode, skipping') log.error('Error getting itemid for episode, skipping')
return return
emby_dbitem = emby_db.getItem_byId(itemid) plex_dbitem = plex_db.getItem_byId(itemid)
try: try:
episodeid = emby_dbitem[0] episodeid = plex_dbitem[0]
fileid = emby_dbitem[1] fileid = plex_dbitem[1]
pathid = emby_dbitem[2] pathid = plex_dbitem[2]
except TypeError: except TypeError:
update_item = False update_item = False
# episodeid # episodeid
@ -910,19 +741,10 @@ class TVShows(Items):
# title = "| %02d | %s" % (item['IndexNumberEnd'], title) # title = "| %02d | %s" % (item['IndexNumberEnd'], title)
# Get season id # Get season id
show = emby_db.getItem_byId(seriesId) show = plex_db.getItem_byId(seriesId)
try: try:
showid = show[0] showid = show[0]
except TypeError: 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") log.error("Parent tvshow now found, skip item")
return False return False
seasonid = self.kodi_db.addSeason(showid, season) seasonid = self.kodi_db.addSeason(showid, season)
@ -1010,7 +832,7 @@ class TVShows(Items):
airsBeforeSeason, airsBeforeEpisode, playurl, pathid, airsBeforeSeason, airsBeforeEpisode, playurl, pathid,
fileid, episodeid)) fileid, episodeid))
# Update parentid reference # Update parentid reference
emby_db.updateParentId(itemid, seasonid) plex_db.updateParentId(itemid, seasonid)
##### OR ADD THE EPISODE ##### ##### OR ADD THE EPISODE #####
else: else:
@ -1044,10 +866,10 @@ class TVShows(Items):
premieredate, runtime, director, season, episode, title, showid, premieredate, runtime, director, season, episode, title, showid,
airsBeforeSeason, airsBeforeEpisode, playurl, pathid)) 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 # idempotent; the call here updates also fileid and pathid when item is
# moved or renamed # moved or renamed
emby_db.addReference(itemid, episodeid, "Episode", "episode", fileid, plex_db.addReference(itemid, episodeid, "Episode", "episode", fileid,
pathid, seasonid, checksum) pathid, seasonid, checksum)
# Update the path # Update the path
@ -1110,17 +932,17 @@ class TVShows(Items):
dateplayed) dateplayed)
def remove(self, itemid): def remove(self, itemid):
# Remove showid, fileid, pathid, emby reference # Remove showid, fileid, pathid, plex reference
emby_db = self.emby_db plex_db = self.plex_db
kodicursor = self.kodicursor kodicursor = self.kodicursor
emby_dbitem = emby_db.getItem_byId(itemid) plex_dbitem = plex_db.getItem_byId(itemid)
try: try:
kodiid = emby_dbitem[0] kodiid = plex_dbitem[0]
fileid = emby_dbitem[1] fileid = plex_dbitem[1]
pathid = emby_dbitem[2] pathid = plex_dbitem[2]
parentid = emby_dbitem[3] parentid = plex_dbitem[3]
mediatype = emby_dbitem[4] mediatype = plex_dbitem[4]
log.info("Removing %s kodiid: %s fileid: %s" log.info("Removing %s kodiid: %s fileid: %s"
% (mediatype, kodiid, fileid)) % (mediatype, kodiid, fileid))
except TypeError: except TypeError:
@ -1128,8 +950,8 @@ class TVShows(Items):
##### PROCESS ITEM ##### ##### PROCESS ITEM #####
# Remove the emby reference # Remove the plex reference
emby_db.removeItem(itemid) plex_db.removeItem(itemid)
##### IF EPISODE ##### ##### IF EPISODE #####
@ -1139,19 +961,19 @@ class TVShows(Items):
self.removeEpisode(kodiid, fileid) self.removeEpisode(kodiid, fileid)
# Season verification # Season verification
season = emby_db.getItem_byKodiId(parentid, "season") season = plex_db.getItem_byKodiId(parentid, "season")
try: try:
showid = season[1] showid = season[1]
except TypeError: except TypeError:
return return
season_episodes = emby_db.getItem_byParentId(parentid, "episode") season_episodes = plex_db.getItem_byParentId(parentid, "episode")
if not season_episodes: if not season_episodes:
self.removeSeason(parentid) self.removeSeason(parentid)
emby_db.removeItem(season[0]) plex_db.removeItem(season[0])
# Show verification # Show verification
show = emby_db.getItem_byKodiId(showid, "tvshow") show = plex_db.getItem_byKodiId(showid, "tvshow")
query = ' '.join(( query = ' '.join((
"SELECT totalCount", "SELECT totalCount",
@ -1162,31 +984,31 @@ class TVShows(Items):
result = kodicursor.fetchone() result = kodicursor.fetchone()
if result and result[0] is None: if result and result[0] is None:
# There's no episodes left, delete show and any possible remaining seasons # 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: for season in seasons:
self.removeSeason(season[1]) self.removeSeason(season[1])
else: else:
# Delete emby season entries # Delete plex season entries
emby_db.removeItems_byParentId(showid, "season") plex_db.removeItems_byParentId(showid, "season")
self.removeShow(showid) self.removeShow(showid)
emby_db.removeItem(show[0]) plex_db.removeItem(show[0])
##### IF TVSHOW ##### ##### IF TVSHOW #####
elif mediatype == "tvshow": elif mediatype == "tvshow":
# Remove episodes, seasons, tvshow # Remove episodes, seasons, tvshow
seasons = emby_db.getItem_byParentId(kodiid, "season") seasons = plex_db.getItem_byParentId(kodiid, "season")
for season in seasons: for season in seasons:
seasonid = season[1] seasonid = season[1]
season_episodes = emby_db.getItem_byParentId(seasonid, "episode") season_episodes = plex_db.getItem_byParentId(seasonid, "episode")
for episode in season_episodes: for episode in season_episodes:
self.removeEpisode(episode[1], episode[2]) self.removeEpisode(episode[1], episode[2])
else: else:
# Remove emby episodes # Remove plex episodes
emby_db.removeItems_byParentId(seasonid, "episode") plex_db.removeItems_byParentId(seasonid, "episode")
else: else:
# Remove emby seasons # Remove plex seasons
emby_db.removeItems_byParentId(kodiid, "season") plex_db.removeItems_byParentId(kodiid, "season")
# Remove tvshow # Remove tvshow
self.removeShow(kodiid) self.removeShow(kodiid)
@ -1195,22 +1017,22 @@ class TVShows(Items):
elif mediatype == "season": elif mediatype == "season":
# Remove episodes, season, verify tvshow # 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: for episode in season_episodes:
self.removeEpisode(episode[1], episode[2]) self.removeEpisode(episode[1], episode[2])
else: else:
# Remove emby episodes # Remove plex episodes
emby_db.removeItems_byParentId(kodiid, "episode") plex_db.removeItems_byParentId(kodiid, "episode")
# Remove season # Remove season
self.removeSeason(kodiid) self.removeSeason(kodiid)
# Show verification # Show verification
seasons = emby_db.getItem_byParentId(parentid, "season") seasons = plex_db.getItem_byParentId(parentid, "season")
if not seasons: if not seasons:
# There's no seasons, delete the show # There's no seasons, delete the show
self.removeShow(parentid) 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)) 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. OVERWRITE this method, because we need to open another DB.
Open DB connections and cursors Open DB connections and cursors
""" """
self.embyconn = kodiSQL('plex') self.plexconn = kodiSQL('plex')
self.embycursor = self.embyconn.cursor() self.plexcursor = self.plexconn.cursor()
# Here it is, not 'video' but 'music' # Here it is, not 'video' but 'music'
self.kodiconn = kodiSQL('music') self.kodiconn = kodiSQL('music')
self.kodicursor = self.kodiconn.cursor() 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) self.kodi_db = kodidb.Kodidb_Functions(self.kodicursor)
return self return self
@ -1262,15 +1084,15 @@ class Music(Items):
def add_updateArtist(self, item, viewtag=None, viewid=None, def add_updateArtist(self, item, viewtag=None, viewid=None,
artisttype="MusicArtist"): artisttype="MusicArtist"):
kodicursor = self.kodicursor kodicursor = self.kodicursor
emby_db = self.emby_db plex_db = self.plex_db
artwork = self.artwork artwork = self.artwork
API = PlexAPI.API(item) API = PlexAPI.API(item)
update_item = True update_item = True
itemid = API.getRatingKey() itemid = API.getRatingKey()
emby_dbitem = emby_db.getItem_byId(itemid) plex_dbitem = plex_db.getItem_byId(itemid)
try: try:
artistid = emby_dbitem[0] artistid = plex_dbitem[0]
except TypeError: except TypeError:
update_item = False update_item = False
@ -1300,19 +1122,19 @@ class Music(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 plex table
emby_db.updateReference(itemid, checksum) plex_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 # safety checks: It looks like plex supports the same artist
# multiple times. # multiple times.
# Kodi doesn't allow that. In case that happens we just merge the # Kodi doesn't allow that. In case that happens we just merge the
# artist entries. # 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 plex table
emby_db.addReference( plex_db.addReference(
itemid, artistid, artisttype, "artist", checksum=checksum) itemid, artistid, artisttype, "artist", checksum=checksum)
# Process the artist # Process the artist
@ -1343,7 +1165,7 @@ class Music(Items):
@CatchExceptions(warnuser=True) @CatchExceptions(warnuser=True)
def add_updateAlbum(self, item, viewtag=None, viewid=None): def add_updateAlbum(self, item, viewtag=None, viewid=None):
kodicursor = self.kodicursor kodicursor = self.kodicursor
emby_db = self.emby_db plex_db = self.plex_db
artwork = self.artwork artwork = self.artwork
API = PlexAPI.API(item) API = PlexAPI.API(item)
@ -1352,9 +1174,9 @@ class Music(Items):
if not itemid: if not itemid:
log.error('Error processing Album, skipping') log.error('Error processing Album, skipping')
return return
emby_dbitem = emby_db.getItem_byId(itemid) plex_dbitem = plex_db.getItem_byId(itemid)
try: try:
albumid = emby_dbitem[0] albumid = plex_dbitem[0]
except TypeError: except TypeError:
# Albumid not found # Albumid not found
update_item = False update_item = False
@ -1393,19 +1215,19 @@ class Music(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 plex table
emby_db.updateReference(itemid, checksum) plex_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 # safety checks: It looks like plex supports the same artist
# multiple times. # multiple times.
# Kodi doesn't allow that. In case that happens we just merge the # Kodi doesn't allow that. In case that happens we just merge the
# artist entries. # artist entries.
albumid = self.kodi_db.addAlbum(name, musicBrainzId) albumid = self.kodi_db.addAlbum(name, musicBrainzId)
# Create the reference in emby table # Create the reference in plex table
emby_db.addReference( plex_db.addReference(
itemid, albumid, "MusicAlbum", "album", checksum=checksum) itemid, albumid, "MusicAlbum", "album", checksum=checksum)
# Process the album info # Process the album info
@ -1462,41 +1284,41 @@ class Music(Items):
rating, lastScraped, dateadded, studio, rating, lastScraped, dateadded, studio,
albumid)) albumid))
# Associate the parentid for emby reference # Associate the parentid for plex reference
parentId = item.attrib.get('parentRatingKey') parentId = item.attrib.get('parentRatingKey')
if parentId is not None: if parentId is not None:
emby_dbartist = emby_db.getItem_byId(parentId) plex_dbartist = plex_db.getItem_byId(parentId)
try: try:
artistid = emby_dbartist[0] artistid = plex_dbartist[0]
except TypeError: except TypeError:
log.info('Artist %s does not exist in emby database' log.info('Artist %s does not exist in plex database'
% parentId) % parentId)
artist = GetPlexMetadata(parentId) artist = GetPlexMetadata(parentId)
# Item may not be an artist, verification necessary. # Item may not be an artist, verification necessary.
if artist is not None and artist != 401: if artist is not None and artist != 401:
if artist[0].attrib.get('type') == "artist": if artist[0].attrib.get('type') == "artist":
# Update with the parentId, for remove reference # Update with the parentId, for remove reference
emby_db.addReference( plex_db.addReference(
parentId, parentId, "MusicArtist", "artist") parentId, parentId, "MusicArtist", "artist")
emby_db.updateParentId(itemid, parentId) plex_db.updateParentId(itemid, parentId)
else: else:
# Update emby reference with the artistid # Update plex reference with the artistid
emby_db.updateParentId(itemid, artistid) plex_db.updateParentId(itemid, artistid)
# Assign main artists to album # Assign main artists to album
# Plex unfortunately only supports 1 artist :-( # Plex unfortunately only supports 1 artist :-(
artistId = parentId artistId = parentId
emby_dbartist = emby_db.getItem_byId(artistId) plex_dbartist = plex_db.getItem_byId(artistId)
try: try:
artistid = emby_dbartist[0] artistid = plex_dbartist[0]
except TypeError: 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) log.info('Artist %s does not exist in Plex database' % artistId)
artist = GetPlexMetadata(artistId) artist = GetPlexMetadata(artistId)
if artist is not None and artist != 401: if artist is not None and artist != 401:
self.add_updateArtist(artist[0], artisttype="AlbumArtist") self.add_updateArtist(artist[0], artisttype="AlbumArtist")
emby_dbartist = emby_db.getItem_byId(artistId) plex_dbartist = plex_db.getItem_byId(artistId)
artistid = emby_dbartist[0] artistid = plex_dbartist[0]
else: else:
# Best take this name over anything else. # Best take this name over anything else.
query = "UPDATE artist SET strArtist = ? WHERE idArtist = ?" query = "UPDATE artist SET strArtist = ? WHERE idArtist = ?"
@ -1522,8 +1344,8 @@ class Music(Items):
''' '''
) )
kodicursor.execute(query, (artistid, name, year)) kodicursor.execute(query, (artistid, name, year))
# Update emby reference with parentid # Update plex reference with parentid
emby_db.updateParentId(artistId, albumid) plex_db.updateParentId(artistId, albumid)
# Add genres # Add genres
self.kodi_db.addMusicGenres(albumid, genres, "album") self.kodi_db.addMusicGenres(albumid, genres, "album")
# Update artwork # Update artwork
@ -1533,7 +1355,7 @@ class Music(Items):
def add_updateSong(self, item, viewtag=None, viewid=None): def add_updateSong(self, item, viewtag=None, viewid=None):
# Process single song # Process single song
kodicursor = self.kodicursor kodicursor = self.kodicursor
emby_db = self.emby_db plex_db = self.plex_db
artwork = self.artwork artwork = self.artwork
API = PlexAPI.API(item) API = PlexAPI.API(item)
@ -1542,11 +1364,11 @@ class Music(Items):
if not itemid: if not itemid:
log.error('Error processing Song; skipping') log.error('Error processing Song; skipping')
return return
emby_dbitem = emby_db.getItem_byId(itemid) plex_dbitem = plex_db.getItem_byId(itemid)
try: try:
songid = emby_dbitem[0] songid = plex_dbitem[0]
pathid = emby_dbitem[2] pathid = plex_dbitem[2]
albumid = emby_dbitem[3] albumid = plex_dbitem[3]
except TypeError: except TypeError:
# Songid not found # Songid not found
update_item = False update_item = False
@ -1630,8 +1452,8 @@ class Music(Items):
duration, year, filename, playcount, duration, year, filename, playcount,
dateplayed, rating, comment, songid)) dateplayed, rating, comment, songid))
# Update the checksum in emby table # Update the checksum in plex table
emby_db.updateReference(itemid, checksum) plex_db.updateReference(itemid, checksum)
# OR ADD THE SONG ##### # OR ADD THE SONG #####
else: else:
@ -1642,9 +1464,9 @@ class Music(Items):
try: try:
# Get the album # Get the album
emby_dbalbum = emby_db.getItem_byId( plex_dbalbum = plex_db.getItem_byId(
item.attrib.get('parentRatingKey')) item.attrib.get('parentRatingKey'))
albumid = emby_dbalbum[0] albumid = plex_dbalbum[0]
except KeyError: except KeyError:
# Verify if there's an album associated. # Verify if there's an album associated.
album_name = item.get('parentTitle') album_name = item.get('parentTitle')
@ -1652,7 +1474,7 @@ class Music(Items):
log.info("Creating virtual music album for song: %s." log.info("Creating virtual music album for song: %s."
% itemid) % itemid)
albumid = self.kodi_db.addAlbum(album_name, API.getProvider('MusicBrainzAlbum')) 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: else:
# No album Id associated to the song. # No album Id associated to the song.
log.error("Song itemid: %s has no albumId associated." log.error("Song itemid: %s has no albumId associated."
@ -1662,15 +1484,15 @@ class Music(Items):
except TypeError: except TypeError:
# No album found. Let's create it # No album found. Let's create it
log.info("Album database entry missing.") log.info("Album database entry missing.")
emby_albumId = item.attrib.get('parentRatingKey') plex_albumId = item.attrib.get('parentRatingKey')
album = GetPlexMetadata(emby_albumId) album = GetPlexMetadata(plex_albumId)
if album is None or album == 401: if album is None or album == 401:
log.error('Could not download album, abort') log.error('Could not download album, abort')
return return
self.add_updateAlbum(album[0]) self.add_updateAlbum(album[0])
emby_dbalbum = emby_db.getItem_byId(emby_albumId) plex_dbalbum = plex_db.getItem_byId(plex_albumId)
try: try:
albumid = emby_dbalbum[0] albumid = plex_dbalbum[0]
log.debug("Found albumid: %s" % albumid) log.debug("Found albumid: %s" % albumid)
except TypeError: except TypeError:
# No album found, create a single's album # No album found, create a single's album
@ -1724,8 +1546,8 @@ class Music(Items):
duration, year, filename, musicBrainzId, playcount, duration, year, filename, musicBrainzId, playcount,
dateplayed, rating, 0, 0)) dateplayed, rating, 0, 0))
# Create the reference in emby table # Create the reference in plex table
emby_db.addReference( plex_db.addReference(
itemid, songid, "Audio", "song", itemid, songid, "Audio", "song",
pathid=pathid, pathid=pathid,
parentid=albumid, parentid=albumid,
@ -1752,17 +1574,17 @@ class Music(Items):
artist_name = artist['Name'] artist_name = artist['Name']
artist_eid = artist['Id'] artist_eid = artist['Id']
artist_edb = emby_db.getItem_byId(artist_eid) artist_edb = plex_db.getItem_byId(artist_eid)
try: try:
artistid = artist_edb[0] artistid = artist_edb[0]
except TypeError: except TypeError:
# Artist is missing from emby database, add it. # Artist is missing from plex database, add it.
artistXml = GetPlexMetadata(artist_eid) artistXml = GetPlexMetadata(artist_eid)
if artistXml is None or artistXml == 401: if artistXml is None or artistXml == 401:
log.error('Error getting artist, abort') log.error('Error getting artist, abort')
return return
self.add_updateArtist(artistXml[0]) 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] artistid = artist_edb[0]
finally: finally:
if KODIVERSION >= 17: if KODIVERSION >= 17:
@ -1798,17 +1620,17 @@ class Music(Items):
artist_name = artist['Name'] artist_name = artist['Name']
album_artists.append(artist_name) album_artists.append(artist_name)
artist_eid = artist['Id'] artist_eid = artist['Id']
artist_edb = emby_db.getItem_byId(artist_eid) artist_edb = plex_db.getItem_byId(artist_eid)
try: try:
artistid = artist_edb[0] artistid = artist_edb[0]
except TypeError: except TypeError:
# Artist is missing from emby database, add it. # Artist is missing from plex database, add it.
artistXml = GetPlexMetadata(artist_eid) artistXml = GetPlexMetadata(artist_eid)
if artistXml is None or artistXml == 401: if artistXml is None or artistXml == 401:
log.error('Error getting artist, abort') log.error('Error getting artist, abort')
return return
self.add_updateArtist(artistXml) self.add_updateArtist(artistXml)
artist_edb = emby_db.getItem_byId(artist_eid) artist_edb = plex_db.getItem_byId(artist_eid)
artistid = artist_edb[0] artistid = artist_edb[0]
finally: finally:
query = ( query = (
@ -1868,21 +1690,21 @@ class Music(Items):
artwork.addArtwork(allart, albumid, "album", kodicursor) artwork.addArtwork(allart, albumid, "album", kodicursor)
def remove(self, itemid): def remove(self, itemid):
# Remove kodiid, fileid, pathid, emby reference # Remove kodiid, fileid, pathid, plex reference
emby_db = self.emby_db plex_db = self.plex_db
emby_dbitem = emby_db.getItem_byId(itemid) plex_dbitem = plex_db.getItem_byId(itemid)
try: try:
kodiid = emby_dbitem[0] kodiid = plex_dbitem[0]
mediatype = emby_dbitem[4] mediatype = plex_dbitem[4]
log.info("Removing %s kodiid: %s" % (mediatype, kodiid)) log.info("Removing %s kodiid: %s" % (mediatype, kodiid))
except TypeError: except TypeError:
return return
##### PROCESS ITEM ##### ##### PROCESS ITEM #####
# Remove the emby reference # Remove the plex reference
emby_db.removeItem(itemid) plex_db.removeItem(itemid)
##### IF SONG ##### ##### IF SONG #####
@ -1891,15 +1713,15 @@ class Music(Items):
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) 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_kid = item[0]
item_mediatype = item[1] item_mediatype = item[1]
if item_mediatype == "album": if item_mediatype == "album":
childs = emby_db.getItem_byParentId(item_kid, "song") childs = plex_db.getItem_byParentId(item_kid, "song")
if not childs: if not childs:
# Delete album # Delete album
self.removeAlbum(item_kid) self.removeAlbum(item_kid)
@ -1908,12 +1730,12 @@ class Music(Items):
elif mediatype == "album": elif mediatype == "album":
# Delete songs, 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: for song in album_songs:
self.removeSong(song[1]) self.removeSong(song[1])
else: else:
# Remove emby songs # Remove plex songs
emby_db.removeItems_byParentId(kodiid, "song") plex_db.removeItems_byParentId(kodiid, "song")
# Remove the album # Remove the album
self.removeAlbum(kodiid) self.removeAlbum(kodiid)
@ -1922,22 +1744,22 @@ class Music(Items):
elif mediatype == "artist": elif mediatype == "artist":
# Delete songs, album, artist # Delete songs, album, artist
albums = emby_db.getItem_byParentId(kodiid, "album") albums = plex_db.getItem_byParentId(kodiid, "album")
for album in albums: for album in albums:
albumid = album[1] albumid = album[1]
album_songs = emby_db.getItem_byParentId(albumid, "song") album_songs = plex_db.getItem_byParentId(albumid, "song")
for song in album_songs: for song in album_songs:
self.removeSong(song[1]) self.removeSong(song[1])
else: else:
# Remove emby song # Remove plex song
emby_db.removeItems_byParentId(albumid, "song") plex_db.removeItems_byParentId(albumid, "song")
# Remove emby artist # Remove plex artist
emby_db.removeItems_byParentId(albumid, "artist") plex_db.removeItems_byParentId(albumid, "artist")
# Remove kodi album # Remove kodi album
self.removeAlbum(albumid) self.removeAlbum(albumid)
else: else:
# Remove emby albums # Remove plex albums
emby_db.removeItems_byParentId(kodiid, "album") plex_db.removeItems_byParentId(kodiid, "album")
# Remove artist # Remove artist
self.removeArtist(kodiid) self.removeArtist(kodiid)

View file

@ -9,7 +9,7 @@ import xbmc
import xbmcgui import xbmcgui
import downloadutils import downloadutils
import embydb_functions as embydb import plexdb_functions as plexdb
import playbackutils as pbutils import playbackutils as pbutils
from utils import window, settings, CatchExceptions, tryDecode, tryEncode from utils import window, settings, CatchExceptions, tryDecode, tryEncode
from PlexFunctions import scrobble, REMAP_TYPE_FROM_PLEXTYPE from PlexFunctions import scrobble, REMAP_TYPE_FROM_PLEXTYPE
@ -93,12 +93,12 @@ class KodiMonitor(xbmc.Monitor):
log.info("Item is invalid for playstate update.") log.info("Item is invalid for playstate update.")
else: else:
# Send notification to the server. # Send notification to the server.
with embydb.GetEmbyDB() as emby_db: with plexdb.Get_Plex_DB() as plexcur:
emby_dbitem = emby_db.getItem_byKodiId(kodiid, item_type) plex_dbitem = plexcur.getItem_byKodiId(kodiid, item_type)
try: try:
itemid = emby_dbitem[0] itemid = plex_dbitem[0]
except TypeError: 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") "video library update")
else: else:
# Stop from manually marking as watched unwatched, with actual playback. # Stop from manually marking as watched unwatched, with actual playback.
@ -113,40 +113,7 @@ class KodiMonitor(xbmc.Monitor):
scrobble(itemid, 'unwatched') scrobble(itemid, 'unwatched')
elif method == "VideoLibrary.OnRemove": 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 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": elif method == "System.OnSleep":
# Connection is going to sleep # Connection is going to sleep
@ -219,10 +186,10 @@ class KodiMonitor(xbmc.Monitor):
if plexid is None: if plexid is None:
# Get Plex' item id # Get Plex' item id
with embydb.GetEmbyDB() as emby_db: with plexdb.Get_Plex_DB() as plexcursor:
emby_dbitem = emby_db.getItem_byKodiId(kodiid, typus) plex_dbitem = plexcursor.getItem_byKodiId(kodiid, typus)
try: try:
plexid = emby_dbitem[0] plexid = plex_dbitem[0]
except TypeError: except TypeError:
log.info("No Plex id returned for kodiid %s. Aborting playback" log.info("No Plex id returned for kodiid %s. Aborting playback"
" report" % kodiid) " report" % kodiid)

View file

@ -11,7 +11,7 @@ import xbmc
import xbmcgui import xbmcgui
import xbmcvfs import xbmcvfs
from utils import window, settings, getUnixTimestamp, kodiSQL, sourcesXML,\ from utils import window, settings, getUnixTimestamp, sourcesXML,\
ThreadMethods, ThreadMethodsAdditionalStop, LogTime, getScreensaver,\ ThreadMethods, ThreadMethodsAdditionalStop, LogTime, getScreensaver,\
setScreensaver, playlistXSP, language as lang, DateToKodi, reset,\ setScreensaver, playlistXSP, language as lang, DateToKodi, reset,\
advancedSettingsXML, getKodiVideoDBPath, tryDecode, deletePlaylists,\ advancedSettingsXML, getKodiVideoDBPath, tryDecode, deletePlaylists,\
@ -19,7 +19,7 @@ from utils import window, settings, getUnixTimestamp, kodiSQL, sourcesXML,\
import clientinfo import clientinfo
import downloadutils import downloadutils
import itemtypes import itemtypes
import embydb_functions as embydb import plexdb_functions as plexdb
import kodidb_functions as kodidb import kodidb_functions as kodidb
import userclient import userclient
import videonodes import videonodes
@ -302,9 +302,9 @@ class ProcessFanartThread(Thread):
# Leave the Plex art untouched # Leave the Plex art untouched
allartworks = None allartworks = None
else: else:
with embydb.GetEmbyDB() as emby_db: with plexdb.Get_Plex_DB() as plex_db:
try: try:
kodiId = emby_db.getItem_byId(item['itemId'])[0] kodiId = plex_db.getItem_byId(item['itemId'])[0]
except TypeError: except TypeError:
log.error('Could not get Kodi id for plex id %s' log.error('Could not get Kodi id for plex id %s'
% item['itemId']) % item['itemId'])
@ -530,25 +530,18 @@ class LibrarySync(Thread):
def initializeDBs(self): 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') with plexdb.Get_Plex_DB() as plex_db:
embycursor = embyconn.cursor() # Create the tables for the plex database
# Create the tables for the emby database plex_db.plexcursor.execute(
# emby, view, version """CREATE TABLE IF NOT EXISTS emby(
embycursor.execute( emby_id TEXT UNIQUE, media_folder TEXT, emby_type TEXT, media_type TEXT, kodi_id INTEGER,
"""CREATE TABLE IF NOT EXISTS emby( kodi_fileid INTEGER, kodi_pathid INTEGER, parent_id INTEGER, checksum INTEGER)""")
emby_id TEXT UNIQUE, media_folder TEXT, emby_type TEXT, media_type TEXT, kodi_id INTEGER, plex_db.plexcursor.execute(
kodi_fileid INTEGER, kodi_pathid INTEGER, parent_id INTEGER, checksum INTEGER)""") """CREATE TABLE IF NOT EXISTS view(
embycursor.execute( view_id TEXT UNIQUE, view_name TEXT, media_type TEXT, kodi_tagid INTEGER)""")
"""CREATE TABLE IF NOT EXISTS view( plex_db.plexcursor.execute("CREATE TABLE IF NOT EXISTS version(idVersion TEXT)")
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()
# Create an index for actors to speed up sync # Create an index for actors to speed up sync
create_actor_db_index() create_actor_db_index()
@ -634,7 +627,7 @@ class LibrarySync(Thread):
log.error('Path hack failed with error message: %s' % str(e)) log.error('Path hack failed with error message: %s' % str(e))
return True return True
def processView(self, folderItem, kodi_db, emby_db, totalnodes): def processView(self, folderItem, kodi_db, plex_db, totalnodes):
vnodes = self.vnodes vnodes = self.vnodes
folder = folderItem.attrib folder = folderItem.attrib
mediatype = folder['type'] mediatype = folder['type']
@ -652,8 +645,8 @@ class LibrarySync(Thread):
foldername = folder['title'] foldername = folder['title']
viewtype = folder['type'] viewtype = folder['type']
# Get current media folders from emby database # Get current media folders from plex database
view = emby_db.getView_byId(folderid) view = plex_db.getView_byId(folderid)
try: try:
current_viewname = view[0] current_viewname = view[0]
current_viewtype = view[1] current_viewtype = view[1]
@ -676,8 +669,8 @@ class LibrarySync(Thread):
folderid) folderid)
nodes.append(foldername) nodes.append(foldername)
totalnodes += 1 totalnodes += 1
# Add view to emby database # Add view to plex database
emby_db.addView(folderid, foldername, viewtype, tagid) plex_db.addView(folderid, foldername, viewtype, tagid)
else: else:
log.info(' '.join(( log.info(' '.join((
"Found viewid: %s" % folderid, "Found viewid: %s" % folderid,
@ -699,10 +692,10 @@ class LibrarySync(Thread):
tagid = kodi_db.createTag(foldername) tagid = kodi_db.createTag(foldername)
# Update view with new info # Update view with new info
emby_db.updateView(foldername, tagid, folderid) plex_db.updateView(foldername, tagid, folderid)
if mediatype != "artist": 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 # The tag could be a combined view. Ensure there's
# no other tags with the same name before deleting # no other tags with the same name before deleting
# playlist. # playlist.
@ -739,7 +732,7 @@ class LibrarySync(Thread):
totalnodes += 1 totalnodes += 1
# Update items with new tag # Update items with new tag
items = emby_db.getItem_byView(folderid) items = plex_db.getItem_byView(folderid)
for item in items: for item in items:
# Remove the "s" from viewtype for tags # Remove the "s" from viewtype for tags
kodi_db.updateTag( kodi_db.updateTag(
@ -806,15 +799,15 @@ class LibrarySync(Thread):
vnodes.clearProperties() vnodes.clearProperties()
totalnodes = len(self.sorted_views) 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 # Backup old views to delete them later, if needed (at the end
# of this method, only unused views will be left in oldviews) # 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: with kodidb.GetKodiDB('video') as kodi_db:
for folderItem in sections: for folderItem in sections:
totalnodes = self.processView(folderItem, totalnodes = self.processView(folderItem,
kodi_db, kodi_db,
emby_db, plex_db,
totalnodes) totalnodes)
# Add video nodes listings # Add video nodes listings
# Plex: there seem to be no favorites/favorites tag # Plex: there seem to be no favorites/favorites tag
@ -833,19 +826,17 @@ class LibrarySync(Thread):
# "movies", # "movies",
# "channels") # "channels")
# totalnodes += 1 # totalnodes += 1
with kodidb.GetKodiDB('music') as kodi_db:
pass
# Save total # Save total
window('Plex.nodes.total', str(totalnodes)) window('Plex.nodes.total', str(totalnodes))
# Reopen DB connection to ensure that changes were commited before # 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) log.info("Removing views: %s" % self.old_views)
for view in self.old_views: for view in self.old_views:
emby_db.removeView(view) plex_db.removeView(view)
# update views for all: # update views for all:
self.views = emby_db.getAllViewInfo() self.views = plex_db.getAllViewInfo()
log.info("Finished processing views. Views saved: %s" % self.views) log.info("Finished processing views. Views saved: %s" % self.views)
return True return True
@ -1052,11 +1043,11 @@ class LibrarySync(Thread):
self.allKodiElementsId = {} self.allKodiElementsId = {}
if self.compare: if self.compare:
with embydb.GetEmbyDB() as emby_db: with plexdb.Get_Plex_DB() as plex_db:
# Get movies from Plex server # Get movies from Plex server
# Pull the list of movies and boxsets in Kodi # Pull the list of movies and boxsets in Kodi
try: try:
self.allKodiElementsId = dict(emby_db.getChecksum('Movie')) self.allKodiElementsId = dict(plex_db.getChecksum('Movie'))
except ValueError: except ValueError:
self.allKodiElementsId = {} self.allKodiElementsId = {}
@ -1139,11 +1130,11 @@ class LibrarySync(Thread):
self.allKodiElementsId = {} self.allKodiElementsId = {}
if self.compare: 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 # Pull the list of TV shows already in Kodi
for kind in ('Series', 'Season', 'Episode'): for kind in ('Series', 'Season', 'Episode'):
try: try:
elements = dict(emby_db.getChecksum(kind)) elements = dict(plex.getChecksum(kind))
self.allKodiElementsId.update(elements) self.allKodiElementsId.update(elements)
# Yet empty/not yet synched # Yet empty/not yet synched
except ValueError: except ValueError:
@ -1309,10 +1300,10 @@ class LibrarySync(Thread):
# Get a list of items already existing in Kodi db # Get a list of items already existing in Kodi db
if self.compare: 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 # Pull the list of items already in Kodi
try: try:
elements = dict(emby_db.getChecksum(kind)) elements = dict(plex_db.getChecksum(kind))
self.allKodiElementsId.update(elements) self.allKodiElementsId.update(elements)
# Yet empty/nothing yet synched # Yet empty/nothing yet synched
except ValueError: except ValueError:
@ -1560,14 +1551,14 @@ class LibrarySync(Thread):
where where
""" """
items = [] items = []
with embydb.GetEmbyDB() as emby_db: with plexdb.Get_Plex_DB() as plex_db:
for item in data: for item in data:
# Drop buffering messages immediately # Drop buffering messages immediately
state = item.get('state') state = item.get('state')
if state == 'buffering': if state == 'buffering':
continue continue
ratingKey = item.get('ratingKey') ratingKey = item.get('ratingKey')
kodiInfo = emby_db.getItem_byId(ratingKey) kodiInfo = plex_db.getItem_byId(ratingKey)
if kodiInfo is None: if kodiInfo is None:
# Item not (yet) in Kodi library # Item not (yet) in Kodi library
continue continue
@ -1669,9 +1660,9 @@ class LibrarySync(Thread):
'Movie': 'Movies', 'Movie': 'Movies',
'Series': 'TVShows' 'Series': 'TVShows'
} }
with embydb.GetEmbyDB() as emby_db: with plexdb.Get_Plex_DB() as plex_db:
for plextype in typus: 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 the list to not always start out identically
shuffle(items) shuffle(items)
for item in items: for item in items:

View file

@ -11,7 +11,7 @@ from utils import window, settings, language as lang, DateToKodi, \
getUnixTimestamp getUnixTimestamp
import clientinfo import clientinfo
import downloadutils import downloadutils
import embydb_functions as embydb import plexdb_functions as plexdb
import kodidb_functions as kodidb import kodidb_functions as kodidb
############################################################################### ###############################################################################
@ -88,13 +88,13 @@ class Player(xbmc.Player):
log.info("ONPLAYBACK_STARTED: %s itemid: %s" % (currentFile, itemId)) log.info("ONPLAYBACK_STARTED: %s itemid: %s" % (currentFile, itemId))
embyitem = "emby_%s" % currentFile plexitem = "emby_%s" % currentFile
runtime = window("%s.runtime" % embyitem) runtime = window("%s.runtime" % plexitem)
refresh_id = window("%s.refreshid" % embyitem) refresh_id = window("%s.refreshid" % plexitem)
playMethod = window("%s.playmethod" % embyitem) playMethod = window("%s.playmethod" % plexitem)
itemType = window("%s.type" % embyitem) itemType = window("%s.type" % plexitem)
try: try:
playcount = int(window("%s.playcount" % embyitem)) playcount = int(window("%s.playcount" % plexitem))
except ValueError: except ValueError:
playcount = 0 playcount = 0
window('emby_skipWatched%s' % itemId, value="true") window('emby_skipWatched%s' % itemId, value="true")
@ -134,7 +134,7 @@ class Player(xbmc.Player):
volume = result.get('volume') volume = result.get('volume')
muted = result.get('muted') muted = result.get('muted')
# Postdata structure to send to Emby server # Postdata structure to send to plex server
url = "{server}/:/timeline?" url = "{server}/:/timeline?"
postdata = { postdata = {
@ -154,7 +154,7 @@ class Player(xbmc.Player):
postdata['AudioStreamIndex'] = window("%sAudioStreamIndex" % currentFile) postdata['AudioStreamIndex'] = window("%sAudioStreamIndex" % currentFile)
postdata['SubtitleStreamIndex'] = window("%sSubtitleStreamIndex" % currentFile) postdata['SubtitleStreamIndex'] = window("%sSubtitleStreamIndex" % currentFile)
else: 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 = { tracks_query = {
"jsonrpc": "2.0", "jsonrpc": "2.0",
"id": 1, "id": 1,
@ -190,9 +190,9 @@ class Player(xbmc.Player):
# Postdata for the subtitles # Postdata for the subtitles
if subsEnabled and len(xbmc.Player().getAvailableSubtitleStreams()) > 0: 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()) audioTracks = len(xbmc.Player().getAvailableAudioStreams())
mapping = window("%s.indexMapping" % embyitem) mapping = window("%s.indexMapping" % plexitem)
if mapping: # Set in playbackutils.py if mapping: # Set in playbackutils.py
@ -229,10 +229,10 @@ class Player(xbmc.Player):
log.error('Could not get kodi runtime, setting to zero') log.error('Could not get kodi runtime, setting to zero')
runtime = 0 runtime = 0
with embydb.GetEmbyDB() as emby_db: with plexdb.Get_Plex_DB() as plex_db:
emby_dbitem = emby_db.getItem_byId(itemId) plex_dbitem = plex_db.getItem_byId(itemId)
try: try:
fileid = emby_dbitem[1] fileid = plex_dbitem[1]
except TypeError: except TypeError:
log.info("Could not find fileid in plex db.") log.info("Could not find fileid in plex db.")
fileid = None fileid = None

View file

@ -1,9 +1,9 @@
import logging import logging
from urllib import quote from urllib import quote
import embydb_functions as embydb import plexdb_functions as plexdb
from downloadutils import DownloadUtils as DU from downloadutils import DownloadUtils as DU
from utils import JSONRPC, tryEncode, tryDecode from utils import JSONRPC, tryEncode
from PlexAPI import API 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} # {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 = Playlist_Item()
item.kodi_id = kodi_item.get('id') item.kodi_id = kodi_item.get('id')
if item.kodi_id: if item.kodi_id:
with embydb.GetEmbyDB() as emby_db: with plexdb.Get_Plex_DB() as plex_db:
emby_dbitem = emby_db.getItem_byKodiId(kodi_item['id'], plex_dbitem = plex_db.getItem_byKodiId(kodi_item['id'],
kodi_item['type']) kodi_item['type'])
try: try:
item.plex_id = emby_dbitem[0] item.plex_id = plex_dbitem[0]
item.plex_UUID = emby_dbitem[0] # we dont need the uuid yet :-) item.plex_UUID = plex_dbitem[0] # we dont need the uuid yet :-)
except TypeError: except TypeError:
pass pass
item.file = kodi_item.get('file') item.file = kodi_item.get('file')
@ -121,11 +121,11 @@ def playlist_item_from_plex(plex_id):
""" """
item = Playlist_Item() item = Playlist_Item()
item.plex_id = plex_id item.plex_id = plex_id
with embydb.GetEmbyDB() as emby_db: with plexdb.Get_Plex_DB() as plex_db:
emby_dbitem = emby_db.getItem_byId(plex_id) plex_dbitem = plex_db.getItem_byId(plex_id)
try: try:
item.kodi_id = emby_dbitem[0] item.kodi_id = plex_dbitem[0]
item.kodi_type = emby_dbitem[4] item.kodi_type = plex_dbitem[4]
except: except:
raise KeyError('Could not find plex_id %s in database' % plex_id) raise KeyError('Could not find plex_id %s in database' % plex_id)
return item 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.ID = xml_video_element.attrib['%sItemID' % playlist.kind]
item.guid = xml_video_element.attrib.get('guid') item.guid = xml_video_element.attrib.get('guid')
if item.plex_id: if item.plex_id:
with embydb.GetEmbyDB() as emby_db: with plexdb.Get_Plex_DB() as plex_db:
db_element = emby_db.getItem_byId(item.plex_id) db_element = plex_db.getItem_byId(item.plex_id)
try: try:
item.kodi_id, item.kodi_type = int(db_element[0]), db_element[4] item.kodi_id, item.kodi_type = int(db_element[0]), db_element[4]
except TypeError: except TypeError:
@ -517,59 +517,3 @@ def remove_from_Kodi_playlist(playlist, pos):
'position': pos 'position': pos
})) }))
del playlist.items[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)

View file

@ -5,7 +5,7 @@ import string
import xbmc import xbmc
import embydb_functions as embydb import plexdb_functions as plexdb
############################################################################### ###############################################################################
@ -146,11 +146,11 @@ class jsonClass():
def skipTo(self, plexId, typus): def skipTo(self, plexId, typus):
# playlistId = self.getPlaylistId(tryDecode(xbmc_type(typus))) # playlistId = self.getPlaylistId(tryDecode(xbmc_type(typus)))
# playerId = self. # playerId = self.
with embydb.GetEmbyDB() as emby_db: with plexdb.Get_Plex_DB() as plex_db:
embydb_item = emby_db.getItem_byId(plexId) plexdb_item = plex_db.getItem_byId(plexId)
try: try:
dbid = embydb_item[0] dbid = plexdb_item[0]
mediatype = embydb_item[4] mediatype = plexdb_item[4]
except TypeError: except TypeError:
log.info('Couldnt find item %s in Kodi db' % plexId) log.info('Couldnt find item %s in Kodi db' % plexId)
return return

View file

@ -12,29 +12,29 @@ log = logging.getLogger("PLEX."+__name__)
############################################################################### ###############################################################################
class GetEmbyDB(): class Get_Plex_DB():
""" """
Usage: with GetEmbyDB() as emby_db: Usage: with Get_Plex_DB() as plexcursor:
do stuff with emby_db plexcursor.do_something()
On exiting "with" (no matter what), commits get automatically committed On exiting "with" (no matter what), commits get automatically committed
and the db gets closed and the db gets closed
""" """
def __enter__(self): def __enter__(self):
self.embyconn = kodiSQL('plex') self.plexconn = kodiSQL('plex')
self.emby_db = Embydb_Functions(self.embyconn.cursor()) self.plexcursor = Plex_DB_Functions(self.plexconn.cursor())
return self.emby_db return self.plexcursor
def __exit__(self, type, value, traceback): def __exit__(self, type, value, traceback):
self.embyconn.commit() self.plexconn.commit()
self.embyconn.close() 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): def getViews(self):
@ -45,15 +45,15 @@ class Embydb_Functions():
"SELECT view_id", "SELECT view_id",
"FROM view" "FROM view"
)) ))
self.embycursor.execute(query) self.plexcursor.execute(query)
rows = self.embycursor.fetchall() rows = self.plexcursor.fetchall()
for row in rows: for row in rows:
views.append(row[0]) views.append(row[0])
return views return views
def getAllViewInfo(self): def getAllViewInfo(self):
embycursor = self.embycursor plexcursor = self.plexcursor
views = [] views = []
query = ' '.join(( query = ' '.join((
@ -61,8 +61,8 @@ class Embydb_Functions():
"SELECT view_id, view_name, media_type", "SELECT view_id, view_name, media_type",
"FROM view" "FROM view"
)) ))
embycursor.execute(query) plexcursor.execute(query)
rows = embycursor.fetchall() rows = plexcursor.fetchall()
for row in rows: for row in rows:
views.append({'id': row[0], views.append({'id': row[0],
'name': row[1], 'name': row[1],
@ -78,8 +78,8 @@ class Embydb_Functions():
"FROM view", "FROM view",
"WHERE view_id = ?" "WHERE view_id = ?"
)) ))
self.embycursor.execute(query, (viewid,)) self.plexcursor.execute(query, (viewid,))
view = self.embycursor.fetchone() view = self.plexcursor.fetchone()
return view return view
@ -93,8 +93,8 @@ class Embydb_Functions():
"FROM view", "FROM view",
"WHERE media_type = ?" "WHERE media_type = ?"
)) ))
self.embycursor.execute(query, (mediatype,)) self.plexcursor.execute(query, (mediatype,))
rows = self.embycursor.fetchall() rows = self.plexcursor.fetchall()
for row in rows: for row in rows:
views.append({ views.append({
@ -113,9 +113,9 @@ class Embydb_Functions():
"FROM view", "FROM view",
"WHERE view_name = ?" "WHERE view_name = ?"
)) ))
self.embycursor.execute(query, (tagname,)) self.plexcursor.execute(query, (tagname,))
try: try:
view = self.embycursor.fetchone()[0] view = self.plexcursor.fetchone()[0]
except TypeError: except TypeError:
view = None view = None
@ -132,7 +132,7 @@ class Embydb_Functions():
VALUES (?, ?, ?, ?) VALUES (?, ?, ?, ?)
''' '''
) )
self.embycursor.execute(query, (plexid, name, mediatype, tagid)) self.plexcursor.execute(query, (plexid, name, mediatype, tagid))
def updateView(self, name, tagid, mediafolderid): def updateView(self, name, tagid, mediafolderid):
@ -142,7 +142,7 @@ class Embydb_Functions():
"SET view_name = ?, kodi_tagid = ?", "SET view_name = ?, kodi_tagid = ?",
"WHERE view_id = ?" "WHERE view_id = ?"
)) ))
self.embycursor.execute(query, (name, tagid, mediafolderid)) self.plexcursor.execute(query, (name, tagid, mediafolderid))
def removeView(self, viewid): def removeView(self, viewid):
@ -151,7 +151,7 @@ class Embydb_Functions():
"DELETE FROM view", "DELETE FROM view",
"WHERE view_id = ?" "WHERE view_id = ?"
)) ))
self.embycursor.execute(query, (viewid,)) self.plexcursor.execute(query, (viewid,))
def getItem_byFileId(self, fileId, kodiType): def getItem_byFileId(self, fileId, kodiType):
""" """
@ -165,8 +165,8 @@ class Embydb_Functions():
"WHERE kodi_fileid = ? AND media_type = ?" "WHERE kodi_fileid = ? AND media_type = ?"
)) ))
try: try:
self.embycursor.execute(query, (fileId, kodiType)) self.plexcursor.execute(query, (fileId, kodiType))
item = self.embycursor.fetchone()[0] item = self.plexcursor.fetchone()[0]
return item return item
except: except:
return None return None
@ -183,8 +183,8 @@ class Embydb_Functions():
"WHERE kodi_id = ? AND media_type = ?" "WHERE kodi_id = ? AND media_type = ?"
)) ))
try: try:
self.embycursor.execute(query, (fileId, kodiType)) self.plexcursor.execute(query, (fileId, kodiType))
item = self.embycursor.fetchone()[0] item = self.plexcursor.fetchone()[0]
return item return item
except: except:
return None return None
@ -198,8 +198,8 @@ class Embydb_Functions():
"WHERE emby_id = ?" "WHERE emby_id = ?"
)) ))
try: try:
self.embycursor.execute(query, (plexid,)) self.plexcursor.execute(query, (plexid,))
item = self.embycursor.fetchone() item = self.plexcursor.fetchone()
return item return item
except: return None except: return None
@ -211,8 +211,8 @@ class Embydb_Functions():
"FROM emby", "FROM emby",
"WHERE emby_id LIKE ?" "WHERE emby_id LIKE ?"
)) ))
self.embycursor.execute(query, (plexid+"%",)) self.plexcursor.execute(query, (plexid+"%",))
return self.embycursor.fetchall() return self.plexcursor.fetchall()
def getItem_byView(self, mediafolderid): def getItem_byView(self, mediafolderid):
@ -222,8 +222,8 @@ class Embydb_Functions():
"FROM emby", "FROM emby",
"WHERE media_folder = ?" "WHERE media_folder = ?"
)) ))
self.embycursor.execute(query, (mediafolderid,)) self.plexcursor.execute(query, (mediafolderid,))
return self.embycursor.fetchall() return self.plexcursor.fetchall()
def getPlexId(self, kodiid, mediatype): def getPlexId(self, kodiid, mediatype):
""" """
@ -236,8 +236,8 @@ class Embydb_Functions():
"WHERE kodi_id = ? AND media_type = ?" "WHERE kodi_id = ? AND media_type = ?"
)) ))
try: try:
self.embycursor.execute(query, (kodiid, mediatype)) self.plexcursor.execute(query, (kodiid, mediatype))
item = self.embycursor.fetchone() item = self.plexcursor.fetchone()
return item return item
except: except:
return None return None
@ -251,8 +251,8 @@ class Embydb_Functions():
"WHERE kodi_id = ?", "WHERE kodi_id = ?",
"AND media_type = ?" "AND media_type = ?"
)) ))
self.embycursor.execute(query, (kodiid, mediatype,)) self.plexcursor.execute(query, (kodiid, mediatype,))
return self.embycursor.fetchone() return self.plexcursor.fetchone()
def getItem_byParentId(self, parentid, mediatype): def getItem_byParentId(self, parentid, mediatype):
@ -263,8 +263,8 @@ class Embydb_Functions():
"WHERE parent_id = ?", "WHERE parent_id = ?",
"AND media_type = ?" "AND media_type = ?"
)) ))
self.embycursor.execute(query, (parentid, mediatype,)) self.plexcursor.execute(query, (parentid, mediatype,))
return self.embycursor.fetchall() return self.plexcursor.fetchall()
def getItemId_byParentId(self, parentid, mediatype): def getItemId_byParentId(self, parentid, mediatype):
@ -275,8 +275,8 @@ class Embydb_Functions():
"WHERE parent_id = ?", "WHERE parent_id = ?",
"AND media_type = ?" "AND media_type = ?"
)) ))
self.embycursor.execute(query, (parentid, mediatype,)) self.plexcursor.execute(query, (parentid, mediatype,))
return self.embycursor.fetchall() return self.plexcursor.fetchall()
def getChecksum(self, mediatype): def getChecksum(self, mediatype):
@ -286,8 +286,8 @@ class Embydb_Functions():
"FROM emby", "FROM emby",
"WHERE emby_type = ?" "WHERE emby_type = ?"
)) ))
self.embycursor.execute(query, (mediatype,)) self.plexcursor.execute(query, (mediatype,))
return self.embycursor.fetchall() return self.plexcursor.fetchall()
def getMediaType_byId(self, plexid): def getMediaType_byId(self, plexid):
@ -297,9 +297,9 @@ class Embydb_Functions():
"FROM emby", "FROM emby",
"WHERE emby_id = ?" "WHERE emby_id = ?"
)) ))
self.embycursor.execute(query, (plexid,)) self.plexcursor.execute(query, (plexid,))
try: try:
itemtype = self.embycursor.fetchone()[0] itemtype = self.plexcursor.fetchone()[0]
except TypeError: except TypeError:
itemtype = None itemtype = None
@ -330,18 +330,18 @@ class Embydb_Functions():
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
''' '''
) )
self.embycursor.execute(query, (plexid, kodiid, fileid, pathid, embytype, mediatype, self.plexcursor.execute(query, (plexid, kodiid, fileid, pathid, embytype, mediatype,
parentid, checksum, mediafolderid)) parentid, checksum, mediafolderid))
def updateReference(self, plexid, checksum): def updateReference(self, plexid, checksum):
query = "UPDATE emby SET checksum = ? WHERE emby_id = ?" 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): def updateParentId(self, plexid, parent_kodiid):
query = "UPDATE emby SET parent_id = ? WHERE emby_id = ?" 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): def removeItems_byParentId(self, parent_kodiid, mediatype):
@ -351,7 +351,7 @@ class Embydb_Functions():
"WHERE parent_id = ?", "WHERE parent_id = ?",
"AND media_type = ?" "AND media_type = ?"
)) ))
self.embycursor.execute(query, (parent_kodiid, mediatype,)) self.plexcursor.execute(query, (parent_kodiid, mediatype,))
def removeItem_byKodiId(self, kodiid, mediatype): def removeItem_byKodiId(self, kodiid, mediatype):
@ -361,17 +361,17 @@ class Embydb_Functions():
"WHERE kodi_id = ?", "WHERE kodi_id = ?",
"AND media_type = ?" "AND media_type = ?"
)) ))
self.embycursor.execute(query, (kodiid, mediatype,)) self.plexcursor.execute(query, (kodiid, mediatype,))
def removeItem(self, plexid): def removeItem(self, plexid):
query = "DELETE FROM emby WHERE emby_id = ?" query = "DELETE FROM emby WHERE emby_id = ?"
self.embycursor.execute(query, (plexid,)) self.plexcursor.execute(query, (plexid,))
def removeWildItem(self, plexid): def removeWildItem(self, plexid):
query = "DELETE FROM emby WHERE emby_id LIKE ?" query = "DELETE FROM emby WHERE emby_id LIKE ?"
self.embycursor.execute(query, (plexid+"%",)) self.plexcursor.execute(query, (plexid+"%",))
def itemsByType(self, plextype): def itemsByType(self, plextype):
""" """
@ -390,9 +390,9 @@ class Embydb_Functions():
"FROM emby", "FROM emby",
"WHERE emby_type = ?", "WHERE emby_type = ?",
)) ))
self.embycursor.execute(query, (plextype, )) self.plexcursor.execute(query, (plextype, ))
result = [] result = []
for row in self.embycursor.fetchall(): for row in self.plexcursor.fetchall():
result.append({ result.append({
'plexId': row[0], 'plexId': row[0],
'kodiId': row[1], 'kodiId': row[1],