PlexKodiConnect/resources/lib/librarysync.py

1653 lines
67 KiB
Python
Raw Normal View History

2015-12-25 07:07:00 +11:00
# -*- coding: utf-8 -*-
2016-02-12 00:03:04 +11:00
###############################################################################
2017-08-18 18:38:03 +10:00
from logging import getLogger
2017-04-03 01:02:41 +10:00
from threading import Thread
import Queue
from random import shuffle
2015-12-25 07:07:00 +11:00
import xbmc
from xbmcvfs import exists
2015-12-25 07:07:00 +11:00
from utils import window, settings, getUnixTimestamp, sourcesXML,\
2017-05-17 21:55:24 +10:00
thread_methods, create_actor_db_index, dialog, LogTime, getScreensaver,\
2016-09-02 03:07:28 +10:00
setScreensaver, playlistXSP, language as lang, DateToKodi, reset,\
2017-05-30 01:05:22 +10:00
tryDecode, deletePlaylists, deleteNodes, tryEncode, compare_version
2015-12-25 07:07:00 +11:00
import downloadutils
import itemtypes
import plexdb_functions as plexdb
2015-12-25 07:07:00 +11:00
import kodidb_functions as kodidb
import userclient
import videonodes
import variables as v
2015-12-25 07:07:00 +11:00
from PlexFunctions import GetPlexMetadata, GetAllPlexLeaves, scrobble, \
GetPlexSectionResults, GetAllPlexChildren, GetPMSStatus, get_plex_sections
2016-03-28 01:57:35 +11:00
import PlexAPI
2017-04-03 01:02:41 +10:00
from library_sync.get_metadata import Threaded_Get_Metadata
from library_sync.process_metadata import Threaded_Process_Metadata
import library_sync.sync_info as sync_info
from library_sync.fanart import Process_Fanart_Thread
import music
import state
2015-12-29 04:47:16 +11:00
2016-02-12 00:03:04 +11:00
###############################################################################
2015-12-25 07:07:00 +11:00
2017-08-18 18:38:03 +10:00
log = getLogger("PLEX."+__name__)
2015-12-25 07:07:00 +11:00
2016-09-02 03:07:28 +10:00
###############################################################################
@thread_methods(add_suspends=['SUSPEND_LIBRARY_THREAD', 'STOP_SYNC'])
2016-02-12 00:03:04 +11:00
class LibrarySync(Thread):
2016-03-25 04:52:02 +11:00
"""
"""
2016-12-28 03:33:52 +11:00
def __init__(self, callback=None):
self.mgr = callback
2015-12-25 07:07:00 +11:00
# Dict of items we just processed in order to prevent a reprocessing
# caused by websocket
self.just_processed = {}
# How long do we wait until we start re-processing? (in seconds)
self.ignore_just_processed = 10*60
2016-03-25 04:52:02 +11:00
self.itemsToProcess = []
2016-03-28 01:57:35 +11:00
self.sessionKeys = []
2016-09-11 18:20:29 +10:00
self.fanartqueue = Queue.Queue()
if settings('FanartTV') == 'true':
2017-04-03 01:02:41 +10:00
self.fanartthread = Process_Fanart_Thread(self.fanartqueue)
2016-03-28 01:57:35 +11:00
# How long should we wait at least to process new/changed PMS items?
self.saftyMargin = int(settings('backgroundsync_saftyMargin'))
2016-03-25 04:52:02 +11:00
2016-09-02 03:07:28 +10:00
self.fullSyncInterval = int(settings('fullSyncInterval')) * 60
2016-03-28 04:06:36 +11:00
2015-12-25 07:07:00 +11:00
self.user = userclient.UserClient()
self.vnodes = videonodes.VideoNodes()
self.xbmcplayer = xbmc.Player()
2015-12-25 07:07:00 +11:00
2016-09-26 03:18:27 +10:00
self.syncThreadNumber = int(settings('syncThreadNumber'))
2016-09-02 03:07:28 +10:00
self.installSyncDone = settings('SyncInstallRunDone') == 'true'
state.SYNC_DIALOG = settings('dbSyncIndicator') == 'true'
2016-09-02 03:07:28 +10:00
self.enableMusic = settings('enableMusic') == "true"
self.enableBackgroundSync = settings(
'enableBackgroundSync') == "true"
2015-12-25 07:07:00 +11:00
# Show sync dialog even if user deactivated?
self.force_dialog = True
2016-12-04 01:43:23 +11:00
# Init for replacing paths
window('remapSMB', value=settings('remapSMB'))
window('replaceSMB', value=settings('replaceSMB'))
for typus in v.REMAP_TYPE_FROM_PLEXTYPE.values():
2016-12-04 01:43:23 +11:00
for arg in ('Org', 'New'):
key = 'remapSMB%s%s' % (typus, arg)
window(key, value=settings(key))
# Just in case a time sync goes wrong
2016-09-02 03:07:28 +10:00
self.timeoffset = int(settings('kodiplextimeoffset'))
window('kodiplextimeoffset', value=str(self.timeoffset))
2016-02-12 00:03:04 +11:00
Thread.__init__(self)
2015-12-25 07:07:00 +11:00
def showKodiNote(self, message, icon="plex"):
2016-02-12 00:44:11 +11:00
"""
2016-03-08 22:13:47 +11:00
Shows a Kodi popup, if user selected to do so. Pass message in unicode
or string
icon: "plex": shows Plex icon
"error": shows Kodi error icon
2016-02-12 00:44:11 +11:00
"""
if self.xbmcplayer.isPlaying():
# Don't show any dialog if media is playing
return
if state.SYNC_DIALOG is not True and self.force_dialog is not True:
return
if icon == "plex":
2017-08-18 17:53:10 +10:00
dialog('notification',
heading='{plex}',
message=message,
icon='{plex}',
sound=False)
elif icon == "error":
2017-08-18 17:53:10 +10:00
dialog('notification',
heading='{plex}',
message=message,
type='{error}')
2016-02-12 00:44:11 +11:00
2016-03-12 00:42:14 +11:00
def syncPMStime(self):
"""
PMS does not provide a means to get a server timestamp. This is a work-
around.
2016-03-28 01:57:35 +11:00
In general, everything saved to Kodi shall be in Kodi time.
Any info with a PMS timestamp is in Plex time, naturally
2016-03-12 00:42:14 +11:00
"""
2016-09-02 03:07:28 +10:00
log.info('Synching time with PMS server')
2016-03-12 00:42:14 +11:00
# Find a PMS item where we can toggle the view state to enforce a
# change in lastViewedAt
# Get all Plex libraries
sections = get_plex_sections()
try:
sections.attrib
except AttributeError:
2016-09-02 03:07:28 +10:00
log.error("Error download PMS views, abort syncPMStime")
return False
plexId = None
for mediatype in (v.PLEX_TYPE_MOVIE,
v.PLEX_TYPE_SHOW,
v.PLEX_TYPE_ARTIST):
if plexId is not None:
break
for view in sections:
if plexId is not None:
2016-03-12 00:42:14 +11:00
break
if not view.attrib['type'] == mediatype:
continue
libraryId = view.attrib['key']
2017-04-02 02:28:02 +10:00
items = GetAllPlexLeaves(libraryId)
if items in (None, 401):
2016-09-02 03:07:28 +10:00
log.error("Could not download section %s"
% view.attrib['key'])
continue
for item in items:
if item.attrib.get('viewCount') is not None:
# Don't want to mess with items that have playcount>0
continue
if item.attrib.get('viewOffset') is not None:
# Don't mess with items with a resume point
continue
plexId = item.attrib.get('ratingKey')
2016-09-02 03:07:28 +10:00
log.info('Found an item to sync with: %s' % plexId)
break
if plexId is None:
2016-09-02 03:07:28 +10:00
log.error("Could not find an item to sync time with")
log.error("Aborting PMS-Kodi time sync")
return False
2016-03-12 00:42:14 +11:00
# Get the Plex item's metadata
xml = GetPlexMetadata(plexId)
if xml in (None, 401):
2016-09-02 03:07:28 +10:00
log.error("Could not download metadata, aborting time sync")
return False
2016-03-12 00:42:14 +11:00
timestamp = xml[0].attrib.get('lastViewedAt')
if timestamp is None:
2016-03-12 00:42:14 +11:00
timestamp = xml[0].attrib.get('updatedAt')
2016-09-02 03:07:28 +10:00
log.debug('Using items updatedAt=%s' % timestamp)
if timestamp is None:
2016-03-12 00:42:14 +11:00
timestamp = xml[0].attrib.get('addedAt')
2016-09-02 03:07:28 +10:00
log.debug('Using items addedAt=%s' % timestamp)
if timestamp is None:
timestamp = 0
2016-09-02 03:07:28 +10:00
log.debug('No timestamp; using 0')
2016-03-12 00:42:14 +11:00
# Set the timer
2016-09-02 03:07:28 +10:00
koditime = getUnixTimestamp()
2016-03-12 00:42:14 +11:00
# Toggle watched state
scrobble(plexId, 'watched')
2016-03-12 00:42:14 +11:00
# Let the PMS process this first!
xbmc.sleep(1000)
# Get PMS items to find the item we just changed
2017-04-02 02:28:02 +10:00
items = GetAllPlexLeaves(libraryId, lastViewedAt=timestamp)
2016-03-12 00:42:14 +11:00
# Toggle watched state back
scrobble(plexId, 'unwatched')
if items in (None, 401):
2016-09-02 03:07:28 +10:00
log.error("Could not download metadata, aborting time sync")
return False
2016-03-12 00:42:14 +11:00
plextime = None
for item in items:
if item.attrib['ratingKey'] == plexId:
plextime = item.attrib.get('lastViewedAt')
break
if plextime is None:
2016-09-02 03:07:28 +10:00
log.error('Could not get lastViewedAt - aborting')
return False
2016-03-12 00:42:14 +11:00
# Calculate time offset Kodi-PMS
self.timeoffset = int(koditime) - int(plextime)
2016-09-02 03:07:28 +10:00
window('kodiplextimeoffset', value=str(self.timeoffset))
settings('kodiplextimeoffset', value=str(self.timeoffset))
log.info("Time offset Koditime - Plextime in seconds: %s"
% str(self.timeoffset))
return True
2016-03-12 00:42:14 +11:00
def initializeDBs(self):
"""
Run once during startup to verify that plex db exists.
"""
with plexdb.Get_Plex_DB() as plex_db:
# Create the tables for the plex database
plex_db.plexcursor.execute('''
CREATE TABLE IF NOT EXISTS plex(
plex_id TEXT UNIQUE,
view_id TEXT,
plex_type TEXT,
kodi_type TEXT,
kodi_id INTEGER,
kodi_fileid INTEGER,
kodi_pathid INTEGER,
parent_id INTEGER,
2017-02-02 05:56:06 +11:00
checksum INTEGER,
fanart_synced INTEGER)
''')
plex_db.plexcursor.execute('''
CREATE TABLE IF NOT EXISTS view(
view_id TEXT UNIQUE,
view_name TEXT,
kodi_type TEXT,
kodi_tagid INTEGER,
sync_to_kodi INTEGER)
''')
plex_db.plexcursor.execute('''
CREATE TABLE IF NOT EXISTS version(idVersion TEXT)
''')
2016-12-21 02:13:19 +11:00
# Create an index for actors to speed up sync
create_actor_db_index()
2016-09-02 03:07:28 +10:00
@LogTime
2016-04-07 19:57:34 +10:00
def fullSync(self, repair=False):
"""
repair=True: force sync EVERY item
"""
2016-03-03 03:27:21 +11:00
# self.compare == False: we're syncing EVERY item
# True: we're syncing only the delta, e.g. different checksum
2016-04-07 19:57:34 +10:00
self.compare = not repair
# Empty our list of item's we've just processed in the past
self.just_processed = {}
2016-12-03 23:07:41 +11:00
self.new_items_only = True
# This will also update playstates and userratings!
2017-02-03 02:21:37 +11:00
log.info('Running fullsync for NEW PMS items with repair=%s' % repair)
2016-12-03 23:07:41 +11:00
if self._fullSync() is False:
return False
self.new_items_only = False
# This will NOT update playstates and userratings!
2016-12-03 23:07:41 +11:00
log.info('Running fullsync for CHANGED PMS items with repair=%s'
% repair)
if self._fullSync() is False:
return False
return True
def _fullSync(self):
2016-03-02 02:52:09 +11:00
xbmc.executebuiltin('InhibitIdleShutdown(true)')
2016-09-02 03:07:28 +10:00
screensaver = getScreensaver()
setScreensaver(value="")
2016-03-02 02:52:09 +11:00
2016-12-03 23:07:41 +11:00
if self.new_items_only is True:
# Only do the following once for new items
# Add sources
sourcesXML()
2015-12-25 07:07:00 +11:00
2016-12-03 23:07:41 +11:00
# Set views. Abort if unsuccessful
if not self.maintainViews():
xbmc.executebuiltin('InhibitIdleShutdown(false)')
setScreensaver(value=screensaver)
return False
2016-01-11 19:57:45 +11:00
2015-12-28 23:10:05 +11:00
process = {
2016-01-10 02:14:02 +11:00
'movies': self.PlexMovies,
'tvshows': self.PlexTVShows,
2015-12-28 23:10:05 +11:00
}
if self.enableMusic:
process['music'] = self.PlexMusic
# Do the processing
2015-12-25 07:07:00 +11:00
for itemtype in process:
if (self.thread_stopped() or
self.thread_suspended() or
not process[itemtype]()):
2016-03-02 02:52:09 +11:00
xbmc.executebuiltin('InhibitIdleShutdown(false)')
2016-09-02 03:07:28 +10:00
setScreensaver(value=screensaver)
2015-12-25 07:07:00 +11:00
return False
2016-03-03 03:27:21 +11:00
# Let kodi update the views in any case, since we're doing a full sync
2015-12-25 07:07:00 +11:00
xbmc.executebuiltin('UpdateLibrary(video)')
if self.enableMusic:
xbmc.executebuiltin('UpdateLibrary(music)')
2016-02-12 00:44:11 +11:00
2016-09-02 03:07:28 +10:00
window('plex_initialScan', clear=True)
2016-03-02 02:52:09 +11:00
xbmc.executebuiltin('InhibitIdleShutdown(false)')
2016-09-02 03:07:28 +10:00
setScreensaver(value=screensaver)
if window('plex_scancrashed') == 'true':
# Show warning if itemtypes.py crashed at some point
2017-08-18 17:53:10 +10:00
dialog('ok', heading='{plex}', line1=lang(39408))
2016-09-02 03:07:28 +10:00
window('plex_scancrashed', clear=True)
elif window('plex_scancrashed') == '401':
window('plex_scancrashed', clear=True)
if state.PMS_STATUS not in ('401', 'Auth'):
# Plex server had too much and returned ERROR
2017-08-18 17:53:10 +10:00
dialog('ok', heading='{plex}', line1=lang(39409))
# Path hack, so Kodis Information screen works
with kodidb.GetKodiDB('video') as kodi_db:
try:
kodi_db.pathHack()
2016-09-02 03:07:28 +10:00
log.info('Path hack successful')
except Exception as e:
# Empty movies, tv shows?
2016-09-02 03:07:28 +10:00
log.error('Path hack failed with error message: %s' % str(e))
setScreensaver(value=screensaver)
2015-12-25 07:07:00 +11:00
return True
def processView(self, folderItem, kodi_db, plex_db, totalnodes):
2016-02-12 00:03:04 +11:00
vnodes = self.vnodes
folder = folderItem.attrib
mediatype = folder['type']
# Only process supported formats
if mediatype not in (v.PLEX_TYPE_MOVIE, v.PLEX_TYPE_SHOW,
v.PLEX_TYPE_ARTIST, v.PLEX_TYPE_PHOTO):
2016-03-03 03:27:21 +11:00
return totalnodes
# Prevent duplicate for nodes of the same type
nodes = self.nodes[mediatype]
# Prevent duplicate for playlists of the same type
playlists = self.playlists[mediatype]
2016-03-03 19:04:15 +11:00
sorted_views = self.sorted_views
2016-02-12 00:03:04 +11:00
folderid = folder['key']
foldername = folder['title']
viewtype = folder['type']
# Get current media folders from plex database
view = plex_db.getView_byId(folderid)
2016-02-12 00:03:04 +11:00
try:
current_viewname = view[0]
current_viewtype = view[1]
current_tagid = view[2]
except TypeError:
2016-09-02 03:07:28 +10:00
log.info("Creating viewid: %s in Plex database." % folderid)
2016-02-12 00:03:04 +11:00
tagid = kodi_db.createTag(foldername)
# Create playlist for the video library
2016-03-03 03:27:21 +11:00
if (foldername not in playlists and
mediatype in (v.PLEX_TYPE_MOVIE, v.PLEX_TYPE_SHOW)):
2016-09-02 03:07:28 +10:00
playlistXSP(mediatype, foldername, folderid, viewtype)
2016-03-03 03:27:21 +11:00
playlists.append(foldername)
2016-02-12 00:03:04 +11:00
# Create the video node
2016-03-03 03:27:21 +11:00
if (foldername not in nodes and
mediatype != v.PLEX_TYPE_ARTIST):
2016-03-03 03:27:21 +11:00
vnodes.viewNode(sorted_views.index(foldername),
2016-02-12 00:03:04 +11:00
foldername,
mediatype,
2016-03-01 22:10:09 +11:00
viewtype,
folderid)
2016-03-03 03:27:21 +11:00
nodes.append(foldername)
2016-02-12 00:03:04 +11:00
totalnodes += 1
# Add view to plex database
plex_db.addView(folderid, foldername, viewtype, tagid)
2016-02-12 00:03:04 +11:00
else:
2016-09-02 03:07:28 +10:00
log.info(' '.join((
2016-02-12 00:03:04 +11:00
"Found viewid: %s" % folderid,
"viewname: %s" % current_viewname,
"viewtype: %s" % current_viewtype,
2016-09-02 03:07:28 +10:00
"tagid: %s" % current_tagid)))
2016-03-01 21:26:46 +11:00
# Remove views that are still valid to delete rest later
try:
self.old_views.remove(folderid)
except ValueError:
# View was just created, nothing to remove
pass
2016-02-12 00:03:04 +11:00
# View was modified, update with latest info
if current_viewname != foldername:
2016-09-02 03:07:28 +10:00
log.info("viewid: %s new viewname: %s"
% (folderid, foldername))
2016-02-12 00:03:04 +11:00
tagid = kodi_db.createTag(foldername)
# Update view with new info
plex_db.updateView(foldername, tagid, folderid)
2016-02-12 00:03:04 +11:00
2016-03-03 03:27:21 +11:00
if mediatype != "artist":
if plex_db.getView_byName(current_viewname) is None:
2016-02-12 00:03:04 +11:00
# The tag could be a combined view. Ensure there's
# no other tags with the same name before deleting
# playlist.
2016-09-02 03:07:28 +10:00
playlistXSP(mediatype,
current_viewname,
folderid,
current_viewtype,
True)
2016-02-12 00:03:04 +11:00
# Delete video node
if mediatype != "musicvideos":
2016-03-03 03:27:21 +11:00
vnodes.viewNode(
indexnumber=sorted_views.index(foldername),
tagname=current_viewname,
mediatype=mediatype,
viewtype=current_viewtype,
viewid=folderid,
delete=True)
2016-02-12 00:03:04 +11:00
# Added new playlist
2017-04-03 01:02:41 +10:00
if (foldername not in playlists and mediatype in
(v.PLEX_TYPE_MOVIE, v.PLEX_TYPE_SHOW)):
2016-09-02 03:07:28 +10:00
playlistXSP(mediatype,
foldername,
folderid,
viewtype)
2016-03-03 03:27:21 +11:00
playlists.append(foldername)
2016-02-12 00:03:04 +11:00
# Add new video node
2016-03-03 03:27:21 +11:00
if foldername not in nodes and mediatype != "musicvideos":
vnodes.viewNode(sorted_views.index(foldername),
2016-02-12 00:03:04 +11:00
foldername,
mediatype,
2016-03-01 22:10:09 +11:00
viewtype,
folderid)
2016-03-03 03:27:21 +11:00
nodes.append(foldername)
2016-02-12 00:03:04 +11:00
totalnodes += 1
# Update items with new tag
items = plex_db.getItem_byView(folderid)
2016-02-12 00:03:04 +11:00
for item in items:
# Remove the "s" from viewtype for tags
2016-03-03 03:27:21 +11:00
kodi_db.updateTag(
current_tagid, tagid, item[0], current_viewtype[:-1])
2016-02-12 00:03:04 +11:00
else:
2016-03-03 03:27:21 +11:00
# Validate the playlist exists or recreate it
if mediatype != v.PLEX_TYPE_ARTIST:
2017-04-03 01:02:41 +10:00
if (foldername not in playlists and mediatype in
(v.PLEX_TYPE_MOVIE, v.PLEX_TYPE_SHOW)):
2016-09-02 03:07:28 +10:00
playlistXSP(mediatype,
foldername,
folderid,
viewtype)
2016-03-03 03:27:21 +11:00
playlists.append(foldername)
2016-02-12 00:03:04 +11:00
# Create the video node if not already exists
2016-03-03 03:27:21 +11:00
if foldername not in nodes and mediatype != "musicvideos":
vnodes.viewNode(sorted_views.index(foldername),
2016-02-12 00:03:04 +11:00
foldername,
mediatype,
2016-03-01 22:10:09 +11:00
viewtype,
folderid)
2016-03-03 03:27:21 +11:00
nodes.append(foldername)
2016-02-12 00:03:04 +11:00
totalnodes += 1
2016-03-03 03:27:21 +11:00
return totalnodes
2016-02-12 00:03:04 +11:00
2016-01-11 19:57:45 +11:00
def maintainViews(self):
2015-12-28 23:10:05 +11:00
"""
2016-01-11 19:57:45 +11:00
Compare the views to Plex
2015-12-28 23:10:05 +11:00
"""
2017-05-17 23:42:12 +10:00
if state.DIRECT_PATHS is True and self.enableMusic is True:
if music.set_excludefromscan_music_folders() is True:
log.info('Detected new Music library - restarting now')
# 'New Plex music library detected. Sorry, but we need to
# restart Kodi now due to the changes made.'
2017-08-18 17:53:10 +10:00
dialog('ok', heading='{plex}', line1=lang(39711))
from xbmc import executebuiltin
executebuiltin('RestartApp')
return False
self.views = []
2015-12-25 07:07:00 +11:00
vnodes = self.vnodes
2016-01-11 19:57:45 +11:00
2015-12-25 07:07:00 +11:00
# Get views
sections = get_plex_sections()
2016-03-01 22:10:09 +11:00
try:
sections.attrib
except AttributeError:
2016-09-02 03:07:28 +10:00
log.error("Error download PMS views, abort maintainViews")
return False
2015-12-25 07:07:00 +11:00
# For whatever freaking reason, .copy() or dict() does NOT work?!?!?!
2016-03-03 03:27:21 +11:00
self.nodes = {
v.PLEX_TYPE_MOVIE: [],
v.PLEX_TYPE_SHOW: [],
v.PLEX_TYPE_ARTIST: [],
v.PLEX_TYPE_PHOTO: []
2016-03-03 03:27:21 +11:00
}
self.playlists = {
v.PLEX_TYPE_MOVIE: [],
v.PLEX_TYPE_SHOW: [],
v.PLEX_TYPE_ARTIST: [],
v.PLEX_TYPE_PHOTO: []
}
2016-03-03 19:04:15 +11:00
self.sorted_views = []
2016-03-03 03:27:21 +11:00
for view in sections:
itemType = view.attrib['type']
2017-04-03 01:02:41 +10:00
if (itemType in
(v.PLEX_TYPE_MOVIE, v.PLEX_TYPE_SHOW, v.PLEX_TYPE_PHOTO)):
2016-03-03 19:04:15 +11:00
self.sorted_views.append(view.attrib['title'])
2016-09-02 03:07:28 +10:00
log.debug('Sorted views: %s' % self.sorted_views)
2016-03-03 19:04:15 +11:00
# total nodes for window properties
vnodes.clearProperties()
totalnodes = len(self.sorted_views)
2015-12-25 07:07:00 +11:00
with plexdb.Get_Plex_DB() as plex_db:
2016-03-01 21:26:46 +11:00
# 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 = plex_db.getViews()
2016-03-01 20:40:30 +11:00
with kodidb.GetKodiDB('video') as kodi_db:
2016-03-01 21:26:46 +11:00
for folderItem in sections:
2016-03-03 03:27:21 +11:00
totalnodes = self.processView(folderItem,
kodi_db,
plex_db,
2016-03-03 03:27:21 +11:00
totalnodes)
2016-03-03 19:04:15 +11:00
# Add video nodes listings
# Plex: there seem to be no favorites/favorites tag
# vnodes.singleNode(totalnodes,
# "Favorite movies",
# "movies",
# "favourites")
# totalnodes += 1
# vnodes.singleNode(totalnodes,
# "Favorite tvshows",
# "tvshows",
# "favourites")
# totalnodes += 1
# vnodes.singleNode(totalnodes,
# "channels",
# "movies",
# "channels")
# totalnodes += 1
# Save total
2016-09-02 03:07:28 +10:00
window('Plex.nodes.total', str(totalnodes))
2016-02-12 00:03:04 +11:00
2017-02-01 22:16:35 +11:00
# Get rid of old items (view has been deleted on Plex side)
if self.old_views:
self.delete_views()
# update views for all:
with plexdb.Get_Plex_DB() as plex_db:
self.views = plex_db.getAllViewInfo()
2016-09-02 03:07:28 +10:00
log.info("Finished processing views. Views saved: %s" % self.views)
2016-03-03 03:27:21 +11:00
return True
2015-12-25 07:07:00 +11:00
2017-02-01 22:16:35 +11:00
def delete_views(self):
log.info("Removing views: %s" % self.old_views)
delete_items = []
with plexdb.Get_Plex_DB() as plex_db:
for view in self.old_views:
plex_db.removeView(view)
delete_items.extend(plex_db.get_items_by_viewid(view))
delete_movies = []
delete_tv = []
delete_music = []
for item in delete_items:
if item['kodi_type'] == v.KODI_TYPE_MOVIE:
delete_movies.append(item)
elif item['kodi_type'] in v.KODI_VIDEOTYPES:
delete_tv.append(item)
elif item['kodi_type'] in v.KODI_AUDIOTYPES:
delete_music.append(item)
dialog('notification',
heading='{plex}',
message=lang(30052),
icon='{plex}',
sound=False)
for item in delete_movies:
with itemtypes.Movies() as movie:
2017-02-01 22:16:35 +11:00
movie.remove(item['plex_id'])
for item in delete_tv:
with itemtypes.TVShows() as tv:
2017-02-01 22:16:35 +11:00
tv.remove(item['plex_id'])
# And for the music DB:
for item in delete_music:
with itemtypes.Music() as music:
2017-02-01 22:16:35 +11:00
music.remove(item['plex_id'])
2017-04-03 01:02:41 +10:00
def GetUpdatelist(self, xml, itemType, method, viewName, viewId,
get_children=False):
"""
THIS METHOD NEEDS TO BE FAST! => e.g. no API calls
Adds items to self.updatelist as well as self.allPlexElementsId dict
2015-12-25 07:07:00 +11:00
Input:
xml: PMS answer for section items
itemType: 'Movies', 'TVShows', ...
method: Method name to be called with this itemtype
see itemtypes.py
viewName: Name of the Plex view (e.g. 'My TV shows')
viewId: Id/Key of Plex library (e.g. '1')
2017-04-03 01:02:41 +10:00
get_children: will get Plex children of the item if True,
e.g. for music albums
Output: self.updatelist, self.allPlexElementsId
self.updatelist APPENDED(!!) list itemids (Plex Keys as
2016-01-30 06:07:21 +11:00
as received from API.getRatingKey())
One item in this list is of the form:
'itemId': xxx,
'itemType': 'Movies','TVShows', ...
'method': 'add_update', 'add_updateSeason', ...
'viewName': xxx,
2016-01-28 06:41:28 +11:00
'viewId': xxx,
'title': xxx
'mediaType': xxx, e.g. 'movie', 'episode'
self.allPlexElementsId APPENDED(!!) dict
= {itemid: checksum}
"""
now = getUnixTimestamp()
2016-12-03 23:07:41 +11:00
if self.new_items_only is True:
# Only process Plex items that Kodi does not already have in lib
for item in xml:
itemId = item.attrib.get('ratingKey')
if not itemId:
# Skipping items 'title=All episodes' without a 'ratingKey'
continue
self.allPlexElementsId[itemId] = ("K%s%s" %
(itemId, item.attrib.get('updatedAt', '')))
if itemId not in self.allKodiElementsId:
self.updatelist.append({
'itemId': itemId,
'itemType': itemType,
'method': method,
'viewName': viewName,
'viewId': viewId,
'title': item.attrib.get('title', 'Missing Title'),
2017-04-03 01:02:41 +10:00
'mediaType': item.attrib.get('type'),
'get_children': get_children
2016-12-03 23:07:41 +11:00
})
self.just_processed[itemId] = now
2016-12-03 23:07:41 +11:00
return
2016-04-07 19:57:34 +10:00
if self.compare:
2016-03-01 22:10:09 +11:00
# Only process the delta - new or changed items
for item in xml:
itemId = item.attrib.get('ratingKey')
if not itemId:
2016-12-03 23:07:41 +11:00
# Skipping items 'title=All episodes' without a 'ratingKey'
2016-01-12 20:30:28 +11:00
continue
plex_checksum = ("K%s%s"
% (itemId, item.attrib.get('updatedAt', '')))
2016-01-12 20:30:28 +11:00
self.allPlexElementsId[itemId] = plex_checksum
kodi_checksum = self.allKodiElementsId.get(itemId)
2016-03-01 22:10:09 +11:00
# Only update if movie is not in Kodi or checksum is
# different
2016-01-12 20:30:28 +11:00
if kodi_checksum != plex_checksum:
self.updatelist.append({
'itemId': itemId,
'itemType': itemType,
'method': method,
'viewName': viewName,
'viewId': viewId,
2016-12-03 23:07:41 +11:00
'title': item.attrib.get('title', 'Missing Title'),
2017-04-03 01:02:41 +10:00
'mediaType': item.attrib.get('type'),
'get_children': get_children
})
self.just_processed[itemId] = now
else:
# Initial or repair sync: get all Plex movies
for item in xml:
itemId = item.attrib.get('ratingKey')
if not itemId:
2016-12-03 23:07:41 +11:00
# Skipping items 'title=All episodes' without a 'ratingKey'
2016-01-12 20:30:28 +11:00
continue
2016-12-03 23:07:41 +11:00
self.allPlexElementsId[itemId] = ("K%s%s"
% (itemId, item.attrib.get('updatedAt', '')))
self.updatelist.append({
'itemId': itemId,
'itemType': itemType,
'method': method,
'viewName': viewName,
'viewId': viewId,
2016-12-03 23:07:41 +11:00
'title': item.attrib.get('title', 'Missing Title'),
2017-04-03 01:02:41 +10:00
'mediaType': item.attrib.get('type'),
'get_children': get_children
})
self.just_processed[itemId] = now
2016-12-03 23:07:41 +11:00
def GetAndProcessXMLs(self, itemType):
"""
Downloads all XMLs for itemType (e.g. Movies, TV-Shows). Processes them
by then calling itemtypes.<itemType>()
2015-12-29 04:47:16 +11:00
Input:
itemType: 'Movies', 'TVShows', ...
2016-01-11 17:55:22 +11:00
self.updatelist
showProgress If False, NEVER shows sync progress
"""
# Some logging, just in case.
2016-09-02 03:07:28 +10:00
log.debug("self.updatelist: %s" % self.updatelist)
2016-01-28 06:41:28 +11:00
itemNumber = len(self.updatelist)
if itemNumber == 0:
2016-03-03 03:27:21 +11:00
return
# Run through self.updatelist, get XML metadata per item
# Initiate threads
2016-09-02 03:07:28 +10:00
log.info("Starting sync threads")
getMetadataQueue = Queue.Queue()
processMetadataQueue = Queue.Queue(maxsize=100)
# To keep track
2017-04-03 01:02:41 +10:00
sync_info.GET_METADATA_COUNT = 0
sync_info.PROCESS_METADATA_COUNT = 0
sync_info.PROCESSING_VIEW_NAME = ''
2016-01-10 02:14:02 +11:00
# Populate queue: GetMetadata
2016-01-11 17:55:22 +11:00
for updateItem in self.updatelist:
getMetadataQueue.put(updateItem)
2016-09-26 03:18:27 +10:00
# Spawn GetMetadata threads for downloading
threads = []
2016-09-26 03:18:27 +10:00
for i in range(min(self.syncThreadNumber, itemNumber)):
2017-04-03 01:02:41 +10:00
thread = Threaded_Get_Metadata(getMetadataQueue,
processMetadataQueue)
2016-09-26 03:18:27 +10:00
thread.setDaemon(True)
thread.start()
threads.append(thread)
2016-09-02 03:07:28 +10:00
log.info("%s download threads spawned" % len(threads))
2016-01-30 18:43:28 +11:00
# Spawn one more thread to process Metadata, once downloaded
2017-04-03 01:02:41 +10:00
thread = Threaded_Process_Metadata(processMetadataQueue,
itemType)
2016-01-30 18:43:28 +11:00
thread.setDaemon(True)
thread.start()
threads.append(thread)
2016-12-03 23:07:41 +11:00
# Start one thread to show sync progress ONLY for new PMS items
if self.new_items_only is True and (state.SYNC_DIALOG is True or
self.force_dialog is True):
2017-08-18 18:37:30 +10:00
thread = sync_info.Threaded_Show_Sync_Info(itemNumber, itemType)
2016-12-03 23:07:41 +11:00
thread.setDaemon(True)
thread.start()
threads.append(thread)
2016-01-30 06:07:21 +11:00
# Wait until finished
2016-01-30 18:43:28 +11:00
getMetadataQueue.join()
processMetadataQueue.join()
# Kill threads
2016-09-02 03:07:28 +10:00
log.info("Waiting to kill threads")
for thread in threads:
# Threads might already have quit by themselves (e.g. Kodi exit)
try:
thread.stop_thread()
except AttributeError:
pass
2016-09-02 03:07:28 +10:00
log.debug("Stop sent to all threads")
# Wait till threads are indeed dead
for thread in threads:
try:
thread.join(1.0)
except:
pass
2016-09-02 03:07:28 +10:00
log.info("Sync threads finished")
if (settings('FanartTV') == 'true' and
itemType in ('Movies', 'TVShows')):
for item in self.updatelist:
2017-02-02 22:27:21 +11:00
if item['mediaType'] in (v.PLEX_TYPE_MOVIE, v.PLEX_TYPE_SHOW):
self.fanartqueue.put({
2017-02-02 22:27:21 +11:00
'plex_id': item['itemId'],
'plex_type': item['mediaType'],
'refresh': False
})
2016-01-28 06:41:28 +11:00
self.updatelist = []
2015-12-29 04:47:16 +11:00
2016-09-02 03:07:28 +10:00
@LogTime
def PlexMovies(self):
# Initialize
self.allPlexElementsId = {}
2016-01-12 00:38:01 +11:00
2016-01-11 17:55:22 +11:00
itemType = 'Movies'
views = [x for x in self.views if x['itemtype'] == v.KODI_TYPE_MOVIE]
2016-09-02 03:07:28 +10:00
log.info("Processing Plex %s. Libraries: %s" % (itemType, views))
self.allKodiElementsId = {}
if self.compare:
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(
plex_db.getChecksum(v.PLEX_TYPE_MOVIE))
except ValueError:
self.allKodiElementsId = {}
2016-02-20 06:03:06 +11:00
# PROCESS MOVIES #####
2016-01-11 17:55:22 +11:00
self.updatelist = []
for view in views:
if self.installSyncDone is not True:
state.PATH_VERIFIED = False
if self.thread_stopped() or self.thread_suspended():
return False
# Get items per view
viewId = view['id']
viewName = view['name']
2017-04-02 02:28:02 +10:00
all_plexmovies = GetPlexSectionResults(viewId, args=None)
if all_plexmovies is None:
2016-09-02 03:07:28 +10:00
log.info("Couldnt get section items, aborting for view.")
continue
elif all_plexmovies == 401:
return False
# Populate self.updatelist and self.allPlexElementsId
2016-01-11 17:55:22 +11:00
self.GetUpdatelist(all_plexmovies,
itemType,
'add_update',
viewName,
viewId)
self.GetAndProcessXMLs(itemType)
# Update viewstate for EVERY item
for view in views:
if self.thread_stopped() or self.thread_suspended():
return False
self.PlexUpdateWatched(view['id'], itemType)
2016-02-20 06:03:06 +11:00
# PROCESS DELETES #####
2016-01-11 01:16:59 +11:00
if self.compare:
# Manual sync, process deletes
with itemtypes.Movies() as Movie:
for kodimovie in self.allKodiElementsId:
if kodimovie not in self.allPlexElementsId:
Movie.remove(kodimovie)
2016-09-02 03:07:28 +10:00
log.info("%s sync is finished." % itemType)
2016-01-11 01:16:59 +11:00
return True
2016-01-30 06:07:21 +11:00
def PlexUpdateWatched(self, viewId, itemType,
lastViewedAt=None, updatedAt=None):
"""
2016-01-30 06:07:21 +11:00
Updates plex elements' view status ('watched' or 'unwatched') and
also updates resume times.
This is done by downloading one XML for ALL elements with viewId
"""
if self.new_items_only is False:
# Only do this once for fullsync: the first run where new items are
# added to Kodi
return
xml = GetAllPlexLeaves(viewId,
lastViewedAt=lastViewedAt,
2017-04-02 02:28:02 +10:00
updatedAt=updatedAt)
2016-02-11 22:44:12 +11:00
# Return if there are no items in PMS reply - it's faster
try:
xml[0].attrib
except (TypeError, AttributeError, IndexError):
2016-09-02 03:07:28 +10:00
log.error('Error updating watch status. Could not get viewId: '
'%s of itemType %s with lastViewedAt: %s, updatedAt: '
'%s' % (viewId, itemType, lastViewedAt, updatedAt))
2016-02-11 22:44:12 +11:00
return
2016-03-01 23:31:35 +11:00
if itemType in ('Movies', 'TVShows'):
2016-02-11 22:44:12 +11:00
self.updateKodiVideoLib = True
2016-03-01 23:31:35 +11:00
elif itemType in ('Music'):
self.updateKodiMusicLib = True
2016-02-11 22:44:12 +11:00
itemMth = getattr(itemtypes, itemType)
with itemMth() as method:
method.updateUserdata(xml)
2016-09-02 03:07:28 +10:00
@LogTime
2016-01-10 02:14:02 +11:00
def PlexTVShows(self):
# Initialize
self.allPlexElementsId = {}
2016-01-11 17:55:22 +11:00
itemType = 'TVShows'
2016-01-28 06:41:28 +11:00
views = [x for x in self.views if x['itemtype'] == 'show']
2016-09-02 03:07:28 +10:00
log.info("Media folders for %s: %s" % (itemType, views))
self.allKodiElementsId = {}
2016-01-10 02:14:02 +11:00
if self.compare:
with plexdb.Get_Plex_DB() as plex:
# Pull the list of TV shows already in Kodi
for kind in (v.PLEX_TYPE_SHOW,
v.PLEX_TYPE_SEASON,
v.PLEX_TYPE_EPISODE):
try:
elements = dict(plex.getChecksum(kind))
self.allKodiElementsId.update(elements)
# Yet empty/not yet synched
except ValueError:
pass
2016-02-20 06:03:06 +11:00
# PROCESS TV Shows #####
2016-01-11 17:55:22 +11:00
self.updatelist = []
for view in views:
if self.installSyncDone is not True:
state.PATH_VERIFIED = False
if self.thread_stopped() or self.thread_suspended():
return False
# Get items per view
viewId = view['id']
viewName = view['name']
2017-04-02 02:28:02 +10:00
allPlexTvShows = GetPlexSectionResults(viewId)
if allPlexTvShows is None:
2016-09-02 03:07:28 +10:00
log.error("Error downloading show xml for view %s" % viewId)
continue
elif allPlexTvShows == 401:
return False
2016-01-10 02:14:02 +11:00
# Populate self.updatelist and self.allPlexElementsId
2016-01-11 17:55:22 +11:00
self.GetUpdatelist(allPlexTvShows,
itemType,
'add_update',
viewName,
viewId)
2016-09-02 03:07:28 +10:00
log.debug("Analyzed view %s with ID %s" % (viewName, viewId))
2016-01-11 01:16:59 +11:00
# COPY for later use
allPlexTvShowsId = self.allPlexElementsId.copy()
2016-03-14 02:06:54 +11:00
# Process self.updatelist
self.GetAndProcessXMLs(itemType)
2016-09-02 03:07:28 +10:00
log.debug("GetAndProcessXMLs completed for tv shows")
2016-03-14 02:06:54 +11:00
2016-02-20 06:03:06 +11:00
# PROCESS TV Seasons #####
2016-01-10 02:14:02 +11:00
# Cycle through tv shows
for tvShowId in allPlexTvShowsId:
if self.thread_stopped() or self.thread_suspended():
2016-01-11 17:55:22 +11:00
return False
2016-01-10 02:14:02 +11:00
# Grab all seasons to tvshow from PMS
2017-04-02 02:28:02 +10:00
seasons = GetAllPlexChildren(tvShowId)
if seasons is None:
2016-09-02 03:07:28 +10:00
log.error("Error download season xml for show %s" % tvShowId)
continue
elif seasons == 401:
return False
2016-01-10 02:14:02 +11:00
# Populate self.updatelist and self.allPlexElementsId
2016-01-11 17:55:22 +11:00
self.GetUpdatelist(seasons,
itemType,
'add_updateSeason',
viewName,
viewId)
2016-09-02 03:07:28 +10:00
log.debug("Analyzed all seasons of TV show with Plex Id %s"
% tvShowId)
2016-01-10 02:14:02 +11:00
2016-03-14 02:06:54 +11:00
# Process self.updatelist
self.GetAndProcessXMLs(itemType)
2016-09-02 03:07:28 +10:00
log.debug("GetAndProcessXMLs completed for seasons")
2016-03-14 02:06:54 +11:00
2016-02-20 06:03:06 +11:00
# PROCESS TV Episodes #####
2016-01-10 02:14:02 +11:00
# Cycle through tv shows
for view in views:
if self.thread_stopped() or self.thread_suspended():
2016-01-11 17:55:22 +11:00
return False
2016-01-10 02:14:02 +11:00
# Grab all episodes to tvshow from PMS
2017-04-02 02:28:02 +10:00
episodes = GetAllPlexLeaves(view['id'])
if episodes is None:
2016-09-02 03:07:28 +10:00
log.error("Error downloading episod xml for view %s"
% view.get('name'))
continue
elif episodes == 401:
return False
2016-01-10 02:14:02 +11:00
# Populate self.updatelist and self.allPlexElementsId
2016-01-11 17:55:22 +11:00
self.GetUpdatelist(episodes,
itemType,
'add_updateEpisode',
viewName,
viewId)
2016-09-02 03:07:28 +10:00
log.debug("Analyzed all episodes of TV show with Plex Id %s"
% view['id'])
2016-01-11 17:55:22 +11:00
# Process self.updatelist
self.GetAndProcessXMLs(itemType)
2016-09-02 03:07:28 +10:00
log.debug("GetAndProcessXMLs completed for episodes")
2016-01-11 17:55:22 +11:00
# Refresh season info
# Cycle through tv shows
with itemtypes.TVShows() as TVshow:
for tvShowId in allPlexTvShowsId:
XMLtvshow = GetPlexMetadata(tvShowId)
if XMLtvshow is None or XMLtvshow == 401:
2016-09-02 03:07:28 +10:00
log.error('Could not download XMLtvshow')
continue
2016-01-11 17:55:22 +11:00
TVshow.refreshSeasonEntry(XMLtvshow, tvShowId)
2016-09-02 03:07:28 +10:00
log.debug("Season info refreshed")
2016-01-11 17:55:22 +11:00
# Update viewstate:
for view in views:
if self.thread_stopped() or self.thread_suspended():
return False
self.PlexUpdateWatched(view['id'], itemType)
2016-01-11 01:16:59 +11:00
if self.compare:
# Manual sync, process deletes
with itemtypes.TVShows() as TVShow:
for kodiTvElement in self.allKodiElementsId:
if kodiTvElement not in self.allPlexElementsId:
TVShow.remove(kodiTvElement)
2016-09-02 03:07:28 +10:00
log.info("%s sync is finished." % itemType)
return True
2016-09-02 03:07:28 +10:00
@LogTime
def PlexMusic(self):
itemType = 'Music'
2015-12-25 07:07:00 +11:00
views = [x for x in self.views if x['itemtype'] == v.PLEX_TYPE_ARTIST]
2016-09-02 03:07:28 +10:00
log.info("Media folders for %s: %s" % (itemType, views))
2015-12-25 07:07:00 +11:00
methods = {
v.PLEX_TYPE_ARTIST: 'add_updateArtist',
v.PLEX_TYPE_ALBUM: 'add_updateAlbum',
v.PLEX_TYPE_SONG: 'add_updateSong'
}
urlArgs = {
v.PLEX_TYPE_ARTIST: {'type': 8},
v.PLEX_TYPE_ALBUM: {'type': 9},
v.PLEX_TYPE_SONG: {'type': 10}
2015-12-25 07:07:00 +11:00
}
2016-01-23 22:05:56 +11:00
2016-03-01 22:10:09 +11:00
# Process artist, then album and tracks last to minimize overhead
2017-04-02 02:28:02 +10:00
# Each album needs to be processed directly with its songs
# Remaining songs without album will be processed last
for kind in (v.PLEX_TYPE_ARTIST,
v.PLEX_TYPE_ALBUM,
v.PLEX_TYPE_SONG):
if self.thread_stopped() or self.thread_suspended():
return False
2016-09-02 03:07:28 +10:00
log.debug("Start processing music %s" % kind)
2017-04-02 02:28:02 +10:00
self.allKodiElementsId = {}
self.allPlexElementsId = {}
self.updatelist = []
if self.ProcessMusic(views,
kind,
urlArgs[kind],
methods[kind]) is False:
return False
2016-09-02 03:07:28 +10:00
log.debug("Processing of music %s done" % kind)
self.GetAndProcessXMLs(itemType)
2016-09-02 03:07:28 +10:00
log.debug("GetAndProcessXMLs for music %s completed" % kind)
2016-04-14 00:51:53 +10:00
# Update viewstate for EVERY item
for view in views:
if self.thread_stopped() or self.thread_suspended():
2016-04-14 00:51:53 +10:00
return False
self.PlexUpdateWatched(view['id'], itemType)
# reset stuff
self.allKodiElementsId = {}
self.allPlexElementsId = {}
self.updatelist = []
2016-09-02 03:07:28 +10:00
log.info("%s sync is finished." % itemType)
return True
2015-12-25 07:07:00 +11:00
def ProcessMusic(self, views, kind, urlArgs, method):
2017-04-03 01:02:41 +10:00
# For albums, we need to look at the album's songs simultaneously
get_children = True if kind == v.PLEX_TYPE_ALBUM else False
# Get a list of items already existing in Kodi db
if self.compare:
with plexdb.Get_Plex_DB() as plex_db:
# Pull the list of items already in Kodi
try:
elements = dict(plex_db.getChecksum(kind))
self.allKodiElementsId.update(elements)
# Yet empty/nothing yet synched
except ValueError:
pass
for view in views:
if self.installSyncDone is not True:
state.PATH_VERIFIED = False
if self.thread_stopped() or self.thread_suspended():
return False
# Get items per view
2017-04-02 02:28:02 +10:00
itemsXML = GetPlexSectionResults(view['id'], args=urlArgs)
if itemsXML is None:
2017-04-02 02:28:02 +10:00
log.error("Error downloading xml for view %s" % view['id'])
continue
elif itemsXML == 401:
return False
# Populate self.updatelist and self.allPlexElementsId
self.GetUpdatelist(itemsXML,
'Music',
method,
2017-04-02 02:28:02 +10:00
view['name'],
2017-04-03 01:02:41 +10:00
view['id'],
get_children=get_children)
if self.compare:
# Manual sync, process deletes
with itemtypes.Music() as Music:
for itemid in self.allKodiElementsId:
if itemid not in self.allPlexElementsId:
Music.remove(itemid)
2016-03-25 04:52:02 +11:00
def processMessage(self, message):
"""
processes json.loads() messages from websocket. Triage what we need to
do with "process_" methods
"""
typus = message.get('type')
if typus == 'playing':
self.process_playing(message['PlaySessionStateNotification'])
2016-03-25 04:52:02 +11:00
elif typus == 'timeline':
self.process_timeline(message['TimelineEntry'])
2016-03-25 04:52:02 +11:00
def multi_delete(self, liste, deleteListe):
"""
Deletes the list items of liste at the positions in deleteListe
(which can be in any arbitrary order)
2016-03-25 04:52:02 +11:00
"""
indexes = sorted(deleteListe, reverse=True)
for index in indexes:
del liste[index]
return liste
2016-03-28 04:06:36 +11:00
def processItems(self):
2016-03-25 04:52:02 +11:00
"""
Periodically called to process new/updated PMS items
PMS needs a while to download info from internet AFTER it
showed up under 'timeline' websocket messages
2016-03-28 04:06:36 +11:00
data['type']:
1: movie
2: tv show??
3: season??
4: episode
8: artist (band)
9: album
10: track (song)
12: trailer, extras?
data['state']:
0: 'created',
2: 'matching',
3: 'downloading',
4: 'loading',
5: 'finished',
6: 'analyzing',
9: 'deleted'
2016-03-25 04:52:02 +11:00
"""
2016-03-28 04:06:36 +11:00
self.videoLibUpdate = False
self.musicLibUpdate = False
2016-09-02 03:07:28 +10:00
now = getUnixTimestamp()
2016-03-25 04:52:02 +11:00
deleteListe = []
for i, item in enumerate(self.itemsToProcess):
if self.thread_stopped() or self.thread_suspended():
2017-02-03 00:49:14 +11:00
# Chances are that Kodi gets shut down
break
if item['state'] == 9:
successful = self.process_deleteditems(item)
elif now - item['timestamp'] < self.saftyMargin:
2016-03-25 04:52:02 +11:00
# We haven't waited long enough for the PMS to finish
2016-10-24 01:55:28 +11:00
# processing the item. Do it later (excepting deletions)
2016-03-25 04:52:02 +11:00
continue
else:
2017-02-02 22:27:21 +11:00
successful = self.process_newitems(item)
if successful:
self.just_processed[str(item['ratingKey'])] = now
2016-09-18 03:12:32 +10:00
if successful and settings('FanartTV') == 'true':
2017-02-02 22:27:21 +11:00
plex_type = v.PLEX_TYPE_FROM_WEBSOCKET[item['type']]
if plex_type in (v.PLEX_TYPE_MOVIE, v.PLEX_TYPE_SHOW):
2016-09-18 03:12:32 +10:00
self.fanartqueue.put({
2017-02-02 22:27:21 +11:00
'plex_id': item['ratingKey'],
'plex_type': plex_type,
2016-09-18 03:12:32 +10:00
'refresh': False
})
if successful is True:
deleteListe.append(i)
else:
# Safety net if we can't process an item
item['attempt'] += 1
if item['attempt'] > 3:
log.error('Repeatedly could not process item %s, abort'
% item)
deleteListe.append(i)
2016-03-25 04:52:02 +11:00
# Get rid of the items we just processed
if len(deleteListe) > 0:
self.itemsToProcess = self.multi_delete(
self.itemsToProcess, deleteListe)
# Let Kodi know of the change
2016-03-28 04:06:36 +11:00
if self.videoLibUpdate is True:
2016-09-02 03:07:28 +10:00
log.info("Doing Kodi Video Lib update")
2016-03-25 04:52:02 +11:00
xbmc.executebuiltin('UpdateLibrary(video)')
2016-03-28 04:06:36 +11:00
if self.musicLibUpdate is True:
2016-09-02 03:07:28 +10:00
log.info("Doing Kodi Music Lib update")
2016-03-28 04:06:36 +11:00
xbmc.executebuiltin('UpdateLibrary(music)')
def process_newitems(self, item):
2017-02-02 22:27:21 +11:00
xml = GetPlexMetadata(item['ratingKey'])
2016-10-12 03:35:11 +11:00
try:
mediatype = xml[0].attrib['type']
2016-10-12 03:37:47 +11:00
except (IndexError, KeyError, TypeError):
2017-02-02 22:27:21 +11:00
log.error('Could not download metadata for %s' % item['ratingKey'])
return False
log.debug("Processing new/updated PMS item: %s" % item['ratingKey'])
2016-03-28 04:06:36 +11:00
viewtag = xml.attrib.get('librarySectionTitle')
viewid = xml.attrib.get('librarySectionID')
2017-02-02 22:27:21 +11:00
if mediatype == v.PLEX_TYPE_MOVIE:
2016-03-28 04:06:36 +11:00
self.videoLibUpdate = True
with itemtypes.Movies() as movie:
movie.add_update(xml[0],
viewtag=viewtag,
viewid=viewid)
2017-02-02 22:27:21 +11:00
elif mediatype == v.PLEX_TYPE_EPISODE:
2016-03-28 04:06:36 +11:00
self.videoLibUpdate = True
with itemtypes.TVShows() as show:
show.add_updateEpisode(xml[0],
viewtag=viewtag,
viewid=viewid)
2017-02-02 22:27:21 +11:00
elif mediatype == v.PLEX_TYPE_SONG:
2016-03-28 04:06:36 +11:00
self.musicLibUpdate = True
with itemtypes.Music() as music:
music.add_updateSong(xml[0],
viewtag=viewtag,
viewid=viewid)
2017-02-02 22:27:21 +11:00
return True
2016-03-28 04:06:36 +11:00
def process_deleteditems(self, item):
if item.get('type') == 1:
2016-09-02 03:07:28 +10:00
log.debug("Removing movie %s" % item.get('ratingKey'))
2016-03-28 04:06:36 +11:00
self.videoLibUpdate = True
with itemtypes.Movies() as movie:
movie.remove(item.get('ratingKey'))
elif item.get('type') in (2, 3, 4):
2016-09-02 03:07:28 +10:00
log.debug("Removing episode/season/tv show %s"
% item.get('ratingKey'))
2016-03-28 04:06:36 +11:00
self.videoLibUpdate = True
with itemtypes.TVShows() as show:
show.remove(item.get('ratingKey'))
elif item.get('type') in (8, 9, 10):
2016-09-02 03:07:28 +10:00
log.debug("Removing song/album/artist %s" % item.get('ratingKey'))
2016-03-28 04:06:36 +11:00
self.musicLibUpdate = True
with itemtypes.Music() as music:
music.remove(item.get('ratingKey'))
return True
2016-03-25 04:52:02 +11:00
def process_timeline(self, data):
"""
2016-03-28 04:06:36 +11:00
PMS is messing with the library items, e.g. new or changed. Put in our
"processing queue" for later
2016-03-25 04:52:02 +11:00
"""
now = getUnixTimestamp()
2016-03-25 04:52:02 +11:00
for item in data:
if 'tv.plex' in item.get('identifier', ''):
# Ommit Plex DVR messages - the Plex IDs are not corresponding
# (DVR ratingKeys are not unique and might correspond to a
# movie or episode)
continue
2016-10-12 03:28:07 +11:00
typus = int(item.get('type', 0))
status = int(item.get('state', 0))
if status == 9 or (typus in (1, 4, 10) and status == 5):
# Only process deleted items OR movies, episodes, tracks/songs
plex_id = str(item.get('itemID', '0'))
if plex_id == '0':
log.error('Received malformed PMS message: %s' % item)
2016-10-12 03:28:07 +11:00
continue
try:
if (now - self.just_processed[plex_id] <
self.ignore_just_processed and status != 9):
log.debug('We just processed %s: ignoring' % plex_id)
continue
except KeyError:
# Item has NOT just been processed
pass
# Have we already added this element?
for existingItem in self.itemsToProcess:
if existingItem['ratingKey'] == plex_id:
break
else:
# Haven't added this element to the queue yet
self.itemsToProcess.append({
'state': status,
'type': typus,
'ratingKey': plex_id,
2016-09-02 03:07:28 +10:00
'timestamp': getUnixTimestamp(),
'attempt': 0
})
2016-03-25 04:52:02 +11:00
def process_playing(self, data):
2016-03-28 01:57:35 +11:00
"""
Someone (not necessarily the user signed in) is playing something some-
where
"""
2016-03-25 04:52:02 +11:00
items = []
with plexdb.Get_Plex_DB() as plex_db:
2016-03-25 04:52:02 +11:00
for item in data:
2016-03-28 01:57:35 +11:00
# Drop buffering messages immediately
status = item.get('state')
if status == 'buffering':
2016-03-25 04:52:02 +11:00
continue
ratingKey = item.get('ratingKey')
kodiInfo = plex_db.getItem_byId(ratingKey)
if kodiInfo is None:
# Item not (yet) in Kodi library
continue
2016-03-28 01:57:35 +11:00
sessionKey = item.get('sessionKey')
# Do we already have a sessionKey stored?
if sessionKey not in self.sessionKeys:
if settings('plex_serverowned') == 'false':
# Not our PMS, we are not authorized to get the
# sessions
# On the bright side, it must be us playing :-)
self.sessionKeys = {
sessionKey: {}
}
else:
# PMS is ours - get all current sessions
self.sessionKeys = GetPMSStatus(state.PLEX_TOKEN)
2016-09-02 03:07:28 +10:00
log.debug('Updated current sessions. They are: %s'
% self.sessionKeys)
if sessionKey not in self.sessionKeys:
2016-09-02 03:07:28 +10:00
log.warn('Session key %s still unknown! Skip '
'item' % sessionKey)
continue
2016-03-28 01:57:35 +11:00
currSess = self.sessionKeys[sessionKey]
if settings('plex_serverowned') != 'false':
# Identify the user - same one as signed on with PKC? Skip
# update if neither session's username nor userid match
# (Owner sometime's returns id '1', not always)
if (not state.PLEX_TOKEN and currSess['userId'] == '1'):
# PKC not signed in to plex.tv. Plus owner of PMS is
# playing (the '1').
# Hence must be us (since several users require plex.tv
# token for PKC)
pass
2017-05-18 00:15:16 +10:00
elif not (currSess['userId'] == state.PLEX_USER_ID
or
2017-05-18 00:14:17 +10:00
currSess['username'] == state.PLEX_USERNAME):
2016-10-24 01:15:57 +11:00
log.debug('Our username %s, userid %s did not match '
'the session username %s with userid %s'
2017-05-18 00:14:17 +10:00
% (state.PLEX_USERNAME,
2017-05-18 00:15:16 +10:00
state.PLEX_USER_ID,
2016-10-24 01:15:57 +11:00
currSess['username'],
currSess['userId']))
continue
2016-03-28 01:57:35 +11:00
# Get an up-to-date XML from the PMS
# because PMS will NOT directly tell us:
# duration of item
# viewCount
if currSess.get('duration') is None:
xml = GetPlexMetadata(ratingKey)
if xml in (None, 401):
2016-09-02 03:07:28 +10:00
log.error('Could not get up-to-date xml for item %s'
% ratingKey)
2016-03-28 01:57:35 +11:00
continue
API = PlexAPI.API(xml[0])
userdata = API.getUserData()
currSess['duration'] = userdata['Runtime']
currSess['viewCount'] = userdata['PlayCount']
# Sometimes, Plex tells us resume points in milliseconds and
# not in seconds - thank you very much!
if item.get('viewOffset') > currSess['duration']:
resume = item.get('viewOffset') / 1000
else:
resume = item.get('viewOffset')
2016-03-28 01:57:35 +11:00
# Append to list that we need to process
2016-03-25 04:52:02 +11:00
items.append({
'ratingKey': ratingKey,
'kodi_id': kodiInfo[0],
'file_id': kodiInfo[1],
'kodi_type': kodiInfo[4],
'viewOffset': resume,
'state': status,
2016-03-28 01:57:35 +11:00
'duration': currSess['duration'],
'viewCount': currSess['viewCount'],
2016-09-02 03:07:28 +10:00
'lastViewedAt': DateToKodi(getUnixTimestamp())
2016-03-25 04:52:02 +11:00
})
2016-09-02 03:07:28 +10:00
log.debug('Update playstate for user %s with id %s: %s'
2017-05-18 00:14:17 +10:00
% (state.PLEX_USERNAME,
2017-05-18 00:15:16 +10:00
state.PLEX_USER_ID,
2016-09-02 03:07:28 +10:00
items[-1]))
# Now tell Kodi where we are
2016-03-25 04:52:02 +11:00
for item in items:
itemFkt = getattr(itemtypes,
v.ITEMTYPE_FROM_KODITYPE[item['kodi_type']])
2016-03-25 04:52:02 +11:00
with itemFkt() as Fkt:
Fkt.updatePlaystate(item)
def fanartSync(self, refresh=False):
"""
Checks all Plex movies and TV shows whether they still need fanart
refresh=True Force refresh all external fanart
"""
items = []
with plexdb.Get_Plex_DB() as plex_db:
2017-02-02 22:27:21 +11:00
for plex_type in (v.PLEX_TYPE_MOVIE, v.PLEX_TYPE_SHOW):
items.extend(plex_db.itemsByType(plex_type))
# Shuffle the list to not always start out identically
2016-09-11 19:29:51 +10:00
shuffle(items)
for item in items:
self.fanartqueue.put({
2017-02-02 22:27:21 +11:00
'plex_id': item['plex_id'],
'plex_type': item['plex_type'],
'refresh': refresh
})
2017-08-22 02:53:38 +10:00
def triage_lib_scans(self):
"""
"""
if state.RUN_LIB_SCAN in ("full", "repair"):
log.info('Full library scan requested, starting')
window('plex_dbScan', value="true")
state.DB_SCAN = True
if state.RUN_LIB_SCAN == "full":
self.fullSync()
elif state.RUN_LIB_SCAN == "repair":
self.fullSync(repair=True)
state.RUN_LIB_SCAN = None
window('plex_dbScan', clear=True)
state.DB_SCAN = False
# Full library sync finished
self.showKodiNote(lang(39407))
# Reset views was requested from somewhere else
elif state.RUN_LIB_SCAN == "views":
log.info('Refresh playlist and nodes requested, starting')
window('plex_dbScan', value="true")
state.DB_SCAN = True
state.RUN_LIB_SCAN = None
# First remove playlists
deletePlaylists()
# Remove video nodes
deleteNodes()
# Kick off refresh
if self.maintainViews() is True:
# Ran successfully
log.info("Refresh playlists/nodes completed")
# "Plex playlists/nodes refreshed"
self.showKodiNote(lang(39405))
else:
# Failed
log.error("Refresh playlists/nodes failed")
# "Plex playlists/nodes refresh failed"
self.showKodiNote(lang(39406),
icon="error")
window('plex_dbScan', clear=True)
state.DB_SCAN = False
elif state.RUN_LIB_SCAN == 'fanart':
state.RUN_LIB_SCAN = None
# Only look for missing fanart (No)
# or refresh all fanart (Yes)
self.fanartSync(refresh=dialog(
'yesno',
heading='{plex}',
line1=lang(39223),
nolabel=lang(39224),
yeslabel=lang(39225)))
elif state.RUN_LIB_SCAN == 'textures':
state.RUN_LIB_SCAN = None
state.DB_SCAN = True
window('plex_dbScan', value="true")
import artwork
artwork.Artwork().fullTextureCacheSync()
window('plex_dbScan', clear=True)
state.DB_SCAN = False
else:
raise NotImplementedError('Library scan not defined: %s'
% state.RUN_LIB_SCAN)
2016-08-07 23:33:36 +10:00
def run(self):
2015-12-25 07:07:00 +11:00
try:
2016-08-07 23:33:36 +10:00
self.run_internal()
2015-12-25 07:07:00 +11:00
except Exception as e:
state.DB_SCAN = False
2016-09-02 03:07:28 +10:00
window('plex_dbScan', clear=True)
2016-09-05 00:57:06 +10:00
log.error('LibrarySync thread crashed. Error message: %s' % e)
import traceback
2016-09-02 03:07:28 +10:00
log.error("Traceback:\n%s" % traceback.format_exc())
2016-03-08 21:47:46 +11:00
# Library sync thread has crashed
2017-08-18 17:53:10 +10:00
dialog('ok', heading='{plex}', line1=lang(39400))
2015-12-25 07:07:00 +11:00
raise
2016-08-07 23:33:36 +10:00
def run_internal(self):
2016-03-08 21:20:11 +11:00
# Re-assign handles to have faster calls
thread_stopped = self.thread_stopped
thread_suspended = self.thread_suspended
2016-03-08 21:20:11 +11:00
installSyncDone = self.installSyncDone
enableBackgroundSync = self.enableBackgroundSync
fullSync = self.fullSync
2016-03-25 04:52:02 +11:00
processMessage = self.processMessage
processItems = self.processItems
2016-03-28 04:06:36 +11:00
fullSyncInterval = self.fullSyncInterval
lastSync = 0
lastTimeSync = 0
2016-03-28 04:06:36 +11:00
lastProcessing = 0
oneDay = 60*60*24
2016-03-08 21:20:11 +11:00
2016-12-28 03:33:52 +11:00
# Link to Websocket queue
queue = self.mgr.ws.queue
2016-03-25 04:52:02 +11:00
2015-12-25 07:07:00 +11:00
startupComplete = False
2016-01-28 06:41:28 +11:00
self.views = []
2015-12-25 07:07:00 +11:00
2016-09-02 03:07:28 +10:00
log.info("---===### Starting LibrarySync ###===---")
2016-05-30 00:52:38 +10:00
# Ensure that DBs exist if called for very first time
self.initializeDBs()
if settings('FanartTV') == 'true':
self.fanartthread.start()
while not thread_stopped():
2015-12-25 07:07:00 +11:00
# In the event the server goes offline
while thread_suspended():
2015-12-25 07:07:00 +11:00
# Set in service.py
if thread_stopped():
2015-12-25 07:07:00 +11:00
# Abort was requested while waiting. We should exit
2016-09-02 03:07:28 +10:00
log.info("###===--- LibrarySync Stopped ---===###")
2016-01-28 06:41:28 +11:00
return
2016-02-11 20:56:01 +11:00
xbmc.sleep(1000)
2015-12-25 07:07:00 +11:00
2016-05-31 16:06:42 +10:00
if (window('plex_dbCheck') != "true" and installSyncDone):
# Install sync was already done, don't force-show dialogs
self.force_dialog = False
2015-12-25 07:07:00 +11:00
# Verify the validity of the database
2016-02-20 06:03:06 +11:00
currentVersion = settings('dbCreatedWithVersion')
2016-05-31 16:06:42 +10:00
minVersion = window('plex_minDBVersion')
2015-12-25 07:07:00 +11:00
2017-05-30 01:05:22 +10:00
if not compare_version(currentVersion, minVersion):
2016-09-02 03:07:28 +10:00
log.warn("Db version out of date: %s minimum version "
"required: %s" % (currentVersion, minVersion))
2016-03-08 21:47:46 +11:00
# DB out of date. Proceed to recreate?
2017-08-18 17:53:10 +10:00
resp = dialog('yesno',
heading=lang(29999),
line1=lang(39401))
2015-12-25 07:07:00 +11:00
if not resp:
2016-09-02 03:07:28 +10:00
log.warn("Db version out of date! USER IGNORED!")
2016-03-08 21:47:46 +11:00
# PKC may not work correctly until reset
2017-08-18 17:53:10 +10:00
dialog('ok',
heading='{plex}',
line1=lang(29999) + lang(39402))
2015-12-25 07:07:00 +11:00
else:
2016-09-02 03:07:28 +10:00
reset()
break
2016-05-31 16:06:42 +10:00
window('plex_dbCheck', value="true")
2015-12-25 07:07:00 +11:00
if not startupComplete:
2016-03-02 02:52:09 +11:00
# Also runs when first installed
2015-12-25 07:07:00 +11:00
# Verify the video database can be found
2017-01-29 23:40:34 +11:00
videoDb = v.DB_VIDEO_PATH
if not exists(tryEncode(videoDb)):
2015-12-25 07:07:00 +11:00
# Database does not exists
2016-09-02 03:07:28 +10:00
log.error("The current Kodi version is incompatible "
"to know which Kodi versions are supported.")
log.error('Current Kodi version: %s' % tryDecode(
xbmc.getInfoLabel('System.BuildVersion')))
2016-03-08 21:47:46 +11:00
# "Current Kodi version is unsupported, cancel lib sync"
2017-08-18 17:53:10 +10:00
dialog('ok', heading='{plex}', line1=lang(39403))
2015-12-25 07:07:00 +11:00
break
# Run start up sync
state.DB_SCAN = True
2016-05-31 16:06:42 +10:00
window('plex_dbScan', value="true")
2016-09-02 03:07:28 +10:00
log.info("Db version: %s" % settings('dbCreatedWithVersion'))
lastTimeSync = getUnixTimestamp()
2017-01-21 00:53:20 +11:00
# Initialize time offset Kodi - PMS
2016-03-28 01:57:35 +11:00
self.syncPMStime()
2016-09-02 03:07:28 +10:00
lastSync = getUnixTimestamp()
2017-02-02 05:56:06 +11:00
if settings('FanartTV') == 'true':
# Start getting additional missing artwork
with plexdb.Get_Plex_DB() as plex_db:
missing_fanart = plex_db.get_missing_fanart()
2017-02-02 22:28:57 +11:00
log.info('Trying to get %s additional fanart'
% len(missing_fanart))
2017-02-02 05:56:06 +11:00
for item in missing_fanart:
self.fanartqueue.put({
2017-02-02 22:27:21 +11:00
'plex_id': item['plex_id'],
'plex_type': item['plex_type'],
2017-02-02 05:56:06 +11:00
'refresh': True
})
2017-01-21 00:53:20 +11:00
log.info('Refreshing video nodes and playlists now')
deletePlaylists()
deleteNodes()
log.info("Initial start-up full sync starting")
2016-04-07 19:57:34 +10:00
librarySync = fullSync()
2016-05-31 16:06:42 +10:00
window('plex_dbScan', clear=True)
state.DB_SCAN = False
2016-03-03 03:27:21 +11:00
if librarySync:
2016-09-02 03:07:28 +10:00
log.info("Initial start-up full sync successful")
2016-03-03 03:27:21 +11:00
startupComplete = True
settings('SyncInstallRunDone', value="true")
2017-01-25 02:53:50 +11:00
settings("dbCreatedWithVersion", v.ADDON_VERSION)
2016-03-08 21:20:11 +11:00
installSyncDone = True
self.force_dialog = False
2016-03-03 03:27:21 +11:00
else:
2016-09-02 03:07:28 +10:00
log.error("Initial start-up full sync unsuccessful")
2016-01-28 06:41:28 +11:00
# Currently no db scan, so we can start a new scan
elif state.DB_SCAN is False:
2016-01-28 06:41:28 +11:00
# Full scan was requested from somewhere else, e.g. userclient
2017-08-22 02:53:38 +10:00
if state.RUN_LIB_SCAN is not None:
# Force-show dialogs since they are user-initiated
self.force_dialog = True
self.triage_lib_scans()
self.force_dialog = False
continue
now = getUnixTimestamp()
# Standard syncs - don't force-show dialogs
self.force_dialog = False
if (now - lastSync > fullSyncInterval and
not self.xbmcplayer.isPlaying()):
lastSync = now
log.info('Doing scheduled full library scan')
state.DB_SCAN = True
2017-08-22 02:53:38 +10:00
window('plex_dbScan', value="true")
if fullSync() is False and not thread_stopped():
log.error('Could not finish scheduled full sync')
self.force_dialog = True
self.showKodiNote(lang(39410),
icon='error')
self.force_dialog = False
2016-05-31 16:06:42 +10:00
window('plex_dbScan', clear=True)
state.DB_SCAN = False
# Full library sync finished
self.showKodiNote(lang(39407))
2017-08-22 02:53:38 +10:00
elif now - lastTimeSync > oneDay:
lastTimeSync = now
log.info('Starting daily time sync')
state.DB_SCAN = True
window('plex_dbScan', value="true")
2017-08-22 02:53:38 +10:00
self.syncPMStime()
window('plex_dbScan', clear=True)
state.DB_SCAN = False
2017-08-22 02:53:38 +10:00
elif enableBackgroundSync:
# Check back whether we should process something
# Only do this once every while (otherwise, potentially
# many screen refreshes lead to flickering)
if now - lastProcessing > 5:
lastProcessing = now
processItems()
# See if there is a PMS message we need to handle
try:
message = queue.get(block=False)
except Queue.Empty:
xbmc.sleep(100)
2017-08-22 02:53:38 +10:00
continue
# Got a message from PMS; process it
else:
processMessage(message)
queue.task_done()
# NO sleep!
continue
else:
# Still sleep if backgroundsync disabled
xbmc.sleep(100)
2016-03-25 04:52:02 +11:00
xbmc.sleep(100)
2015-12-25 07:07:00 +11:00
2016-04-10 00:57:45 +10:00
# doUtils could still have a session open due to interrupted sync
try:
downloadutils.DownloadUtils().stopSession()
except:
pass
2016-09-02 03:07:28 +10:00
log.info("###===--- LibrarySync Stopped ---===###")