Improve + make artwork thread-save

This commit is contained in:
tomkat83 2016-09-11 13:51:53 +02:00
parent bfc0249720
commit 59882a7be8

View file

@ -8,6 +8,7 @@ import requests
import os import os
import urllib import urllib
from sqlite3 import OperationalError from sqlite3 import OperationalError
from threading import Lock
import xbmc import xbmc
import xbmcgui import xbmcgui
@ -27,152 +28,133 @@ log = logging.getLogger("PLEX."+__name__)
############################################################################### ###############################################################################
def setKodiWebServerDetails():
"""
Get the Kodi webserver details - used to set the texture cache
"""
xbmc_port = None
xbmc_username = None
xbmc_password = None
web_query = {
"jsonrpc": "2.0",
"id": 1,
"method": "Settings.GetSettingValue",
"params": {
"setting": "services.webserver"
}
}
result = xbmc.executeJSONRPC(json.dumps(web_query))
result = json.loads(result)
try:
xbmc_webserver_enabled = result['result']['value']
except (KeyError, TypeError):
xbmc_webserver_enabled = False
if not xbmc_webserver_enabled:
# Enable the webserver, it is disabled
web_port = {
"jsonrpc": "2.0",
"id": 1,
"method": "Settings.SetSettingValue",
"params": {
"setting": "services.webserverport",
"value": 8080
}
}
result = xbmc.executeJSONRPC(json.dumps(web_port))
xbmc_port = 8080
web_user = {
"jsonrpc": "2.0",
"id": 1,
"method": "Settings.SetSettingValue",
"params": {
"setting": "services.webserver",
"value": True
}
}
result = xbmc.executeJSONRPC(json.dumps(web_user))
xbmc_username = "kodi"
# Webserver already enabled
web_port = {
"jsonrpc": "2.0",
"id": 1,
"method": "Settings.GetSettingValue",
"params": {
"setting": "services.webserverport"
}
}
result = xbmc.executeJSONRPC(json.dumps(web_port))
result = json.loads(result)
try:
xbmc_port = result['result']['value']
except (TypeError, KeyError):
pass
web_user = {
"jsonrpc": "2.0",
"id": 1,
"method": "Settings.GetSettingValue",
"params": {
"setting": "services.webserverusername"
}
}
result = xbmc.executeJSONRPC(json.dumps(web_user))
result = json.loads(result)
try:
xbmc_username = result['result']['value']
except TypeError:
pass
web_pass = {
"jsonrpc": "2.0",
"id": 1,
"method": "Settings.GetSettingValue",
"params": {
"setting": "services.webserverpassword"
}
}
result = xbmc.executeJSONRPC(json.dumps(web_pass))
result = json.loads(result)
try:
xbmc_password = result['result']['value']
except TypeError:
pass
return (xbmc_port, xbmc_username, xbmc_password)
class Artwork(): class Artwork():
lock = Lock()
enableTextureCache = settings('enableTextureCache') == "true"
imageCacheLimitThreads = int(settings('imageCacheLimit'))
imageCacheLimitThreads = imageCacheLimitThreads * 5
log.info("Using Image Cache Thread Count: %s" % imageCacheLimitThreads)
xbmc_host = 'localhost' xbmc_host = 'localhost'
xbmc_port = None xbmc_port = None
xbmc_username = None xbmc_username = None
xbmc_password = None xbmc_password = None
if enableTextureCache:
xbmc_port, xbmc_username, xbmc_password = setKodiWebServerDetails()
imageCacheThreads = [] imageCacheThreads = []
imageCacheLimitThreads = 0
def __init__(self):
self.enableTextureCache = settings('enableTextureCache') == "true"
self.imageCacheLimitThreads = int(settings('imageCacheLimit'))
self.imageCacheLimitThreads = int(self.imageCacheLimitThreads * 5)
log.info("Using Image Cache Thread Count: %s" % self.imageCacheLimitThreads)
if not self.xbmc_port and self.enableTextureCache:
self.setKodiWebServerDetails()
self.userId = window('currUserId')
self.server = window('pms_server')
def double_urlencode(self, text): def double_urlencode(self, text):
text = self.single_urlencode(text) text = self.single_urlencode(text)
text = self.single_urlencode(text) text = self.single_urlencode(text)
return text return text
def single_urlencode(self, text): def single_urlencode(self, text):
# urlencode needs a utf- string
text = urllib.urlencode({'blahblahblah': tryEncode(text)}) #urlencode needs a utf- string text = urllib.urlencode({'blahblahblah': tryEncode(text)})
text = text[13:] text = text[13:]
# return the result again as unicode
return tryDecode(text) #return the result again as unicode return tryDecode(text)
def setKodiWebServerDetails(self):
# Get the Kodi webserver details - used to set the texture cache
web_query = {
"jsonrpc": "2.0",
"id": 1,
"method": "Settings.GetSettingValue",
"params": {
"setting": "services.webserver"
}
}
result = xbmc.executeJSONRPC(json.dumps(web_query))
result = json.loads(result)
try:
xbmc_webserver_enabled = result['result']['value']
except (KeyError, TypeError):
xbmc_webserver_enabled = False
if not xbmc_webserver_enabled:
# Enable the webserver, it is disabled
web_port = {
"jsonrpc": "2.0",
"id": 1,
"method": "Settings.SetSettingValue",
"params": {
"setting": "services.webserverport",
"value": 8080
}
}
result = xbmc.executeJSONRPC(json.dumps(web_port))
self.xbmc_port = 8080
web_user = {
"jsonrpc": "2.0",
"id": 1,
"method": "Settings.SetSettingValue",
"params": {
"setting": "services.webserver",
"value": True
}
}
result = xbmc.executeJSONRPC(json.dumps(web_user))
self.xbmc_username = "kodi"
# Webserver already enabled
web_port = {
"jsonrpc": "2.0",
"id": 1,
"method": "Settings.GetSettingValue",
"params": {
"setting": "services.webserverport"
}
}
result = xbmc.executeJSONRPC(json.dumps(web_port))
result = json.loads(result)
try:
self.xbmc_port = result['result']['value']
except (TypeError, KeyError):
pass
web_user = {
"jsonrpc": "2.0",
"id": 1,
"method": "Settings.GetSettingValue",
"params": {
"setting": "services.webserverusername"
}
}
result = xbmc.executeJSONRPC(json.dumps(web_user))
result = json.loads(result)
try:
self.xbmc_username = result['result']['value']
except TypeError:
pass
web_pass = {
"jsonrpc": "2.0",
"id": 1,
"method": "Settings.GetSettingValue",
"params": {
"setting": "services.webserverpassword"
}
}
result = xbmc.executeJSONRPC(json.dumps(web_pass))
result = json.loads(result)
try:
self.xbmc_password = result['result']['value']
except TypeError:
pass
def fullTextureCacheSync(self): def fullTextureCacheSync(self):
# This method will sync all Kodi artwork to textures13.db """
# and cache them locally. This takes diskspace! This method will sync all Kodi artwork to textures13.db
import xbmcaddon and cache them locally. This takes diskspace!
string = xbmcaddon.Addon().getLocalizedString """
if not xbmcgui.Dialog().yesno( if not xbmcgui.Dialog().yesno(
"Image Texture Cache", string(39250)): "Image Texture Cache", lang(39250)):
return return
log.info("Doing Image Cache Sync") log.info("Doing Image Cache Sync")
@ -182,7 +164,7 @@ class Artwork():
# ask to rest all existing or not # ask to rest all existing or not
if xbmcgui.Dialog().yesno( if xbmcgui.Dialog().yesno(
"Image Texture Cache", string(39251), ""): "Image Texture Cache", lang(39251), ""):
log.info("Resetting all cache data first") log.info("Resetting all cache data first")
# Remove all existing textures first # Remove all existing textures first
path = tryDecode(xbmc.translatePath("special://thumbnails/")) path = tryDecode(xbmc.translatePath("special://thumbnails/"))
@ -210,20 +192,20 @@ class Artwork():
if tableName != "version": if tableName != "version":
cursor.execute("DELETE FROM " + tableName) cursor.execute("DELETE FROM " + tableName)
connection.commit() connection.commit()
cursor.close() connection.close()
# Cache all entries in video DB # Cache all entries in video DB
connection = kodiSQL('video') connection = kodiSQL('video')
cursor = connection.cursor() cursor = connection.cursor()
cursor.execute("SELECT url FROM art WHERE media_type != 'actor'") # dont include actors # dont include actors
cursor.execute("SELECT url FROM art WHERE media_type != 'actor'")
result = cursor.fetchall() result = cursor.fetchall()
total = len(result) total = len(result)
log.info("Image cache sync about to process %s images" % total) log.info("Image cache sync about to process %s images" % total)
cursor.close() connection.close()
count = 0 count = 0
for url in result: for url in result:
if pdialog.iscanceled(): if pdialog.iscanceled():
break break
@ -232,7 +214,6 @@ class Artwork():
pdialog.update(percentage, "%s %s" % (lang(33045), message)) pdialog.update(percentage, "%s %s" % (lang(33045), message))
self.cacheTexture(url[0]) self.cacheTexture(url[0])
count += 1 count += 1
# Cache all entries in music DB # Cache all entries in music DB
connection = kodiSQL('music') connection = kodiSQL('music')
cursor = connection.cursor() cursor = connection.cursor()
@ -240,11 +221,10 @@ class Artwork():
result = cursor.fetchall() result = cursor.fetchall()
total = len(result) total = len(result)
log.info("Image cache sync about to process %s images" % total) log.info("Image cache sync about to process %s images" % total)
cursor.close() connection.close()
count = 0 count = 0
for url in result: for url in result:
if pdialog.iscanceled(): if pdialog.iscanceled():
break break
@ -253,63 +233,64 @@ class Artwork():
pdialog.update(percentage, "%s %s" % (lang(33045), message)) pdialog.update(percentage, "%s %s" % (lang(33045), message))
self.cacheTexture(url[0]) self.cacheTexture(url[0])
count += 1 count += 1
pdialog.update(100, "%s %s"
pdialog.update(100, "%s %s" % (lang(33046), len(self.imageCacheThreads))) % (lang(33046), len(self.imageCacheThreads)))
log.info("Waiting for all threads to exit") log.info("Waiting for all threads to exit")
while len(self.imageCacheThreads): while len(self.imageCacheThreads):
for thread in self.imageCacheThreads: with self.lock:
if thread.is_finished: for thread in self.imageCacheThreads:
self.imageCacheThreads.remove(thread) if thread.is_finished:
pdialog.update(100, "%s %s" % (lang(33046), len(self.imageCacheThreads))) self.imageCacheThreads.remove(thread)
log.info("Waiting for all threads to exit: %s" % len(self.imageCacheThreads)) pdialog.update(100, "%s %s"
% (lang(33046), len(self.imageCacheThreads)))
log.info("Waiting for all threads to exit: %s"
% len(self.imageCacheThreads))
xbmc.sleep(500) xbmc.sleep(500)
pdialog.close() pdialog.close()
def addWorkerImageCacheThread(self, url): def addWorkerImageCacheThread(self, url):
while True: while True:
# removed finished # removed finished
for thread in self.imageCacheThreads: with self.lock:
if thread.is_finished: for thread in self.imageCacheThreads:
self.imageCacheThreads.remove(thread) if thread.is_finished:
self.imageCacheThreads.remove(thread)
# add a new thread or wait and retry if we hit our limit # add a new thread or wait and retry if we hit our limit
if len(self.imageCacheThreads) < self.imageCacheLimitThreads: with self.lock:
newThread = image_cache_thread.ImageCacheThread() if len(self.imageCacheThreads) < self.imageCacheLimitThreads:
newThread.set_url(self.double_urlencode(url)) newThread = image_cache_thread.ImageCacheThread()
newThread.set_host(self.xbmc_host, self.xbmc_port) newThread.set_url(self.double_urlencode(url))
newThread.set_auth(self.xbmc_username, self.xbmc_password) newThread.set_host(self.xbmc_host, self.xbmc_port)
newThread.start() newThread.set_auth(self.xbmc_username, self.xbmc_password)
self.imageCacheThreads.append(newThread) newThread.start()
return self.imageCacheThreads.append(newThread)
else: return
log.info("Waiting for empty queue spot: %s" % len(self.imageCacheThreads)) log.debug("Waiting for empty queue spot: %s"
xbmc.sleep(50) % len(self.imageCacheThreads))
xbmc.sleep(50)
def cacheTexture(self, url): def cacheTexture(self, url):
# Cache a single image url to the texture cache # Cache a single image url to the texture cache
if url and self.enableTextureCache: if url and self.enableTextureCache:
log.debug("Processing: %s" % url) log.debug("Processing: %s" % url)
if not self.imageCacheLimitThreads: if not self.imageCacheLimitThreads:
# Add image to texture cache by simply calling it at the http endpoint # Add image to texture cache by simply calling it at the http
# endpoint
url = self.double_urlencode(url) url = self.double_urlencode(url)
try: # Extreme short timeouts so we will have a exception. try:
response = requests.head( # Extreme short timeouts so we will have a exception.
url=("http://%s:%s/image/image://%s" requests.head(
% (self.xbmc_host, self.xbmc_port, url)), url=("http://%s:%s/image/image://%s"
auth=(self.xbmc_username, self.xbmc_password), % (self.xbmc_host, self.xbmc_port, url)),
timeout=(0.01, 0.01)) auth=(self.xbmc_username, self.xbmc_password),
timeout=(0.01, 0.01))
# We don't need the result # We don't need the result
except: pass except:
pass
else: else:
self.addWorkerImageCacheThread(url) self.addWorkerImageCacheThread(url)
def addArtwork(self, artwork, kodiId, mediaType, cursor): def addArtwork(self, artwork, kodiId, mediaType, cursor):
# Kodi conversion table # Kodi conversion table
kodiart = { kodiart = {
@ -328,7 +309,8 @@ class Artwork():
for art in artwork: for art in artwork:
if art == "Backdrop": if art == "Backdrop":
# Backdrop entry is a list # Backdrop entry is a list
# Process extra fanart for artwork downloader (fanart, fanart1, fanart2...) # Process extra fanart for artwork downloader (fanart, fanart1,
# fanart2...)
backdrops = artwork[art] backdrops = artwork[art]
backdropsNumber = len(backdrops) backdropsNumber = len(backdrops)
@ -390,67 +372,58 @@ class Artwork():
cursor=cursor) cursor=cursor)
def addOrUpdateArt(self, imageUrl, kodiId, mediaType, imageType, cursor): def addOrUpdateArt(self, imageUrl, kodiId, mediaType, imageType, cursor):
# Possible that the imageurl is an empty string if not imageUrl:
if imageUrl: # Possible that the imageurl is an empty string
cacheimage = False return
query = ' '.join((
"SELECT url",
"FROM art",
"WHERE media_id = ?",
"AND media_type = ?",
"AND type = ?"
))
cursor.execute(query, (kodiId, mediaType, imageType,))
try:
# Update the artwork
url = cursor.fetchone()[0]
except TypeError:
# Add the artwork
log.debug("Adding Art Link for kodiId: %s (%s)"
% (kodiId, imageUrl))
query = (
'''
INSERT INTO art(media_id, media_type, type, url)
VALUES (?, ?, ?, ?)
'''
)
cursor.execute(query, (kodiId, mediaType, imageType, imageUrl))
else:
if url == imageUrl:
# Only cache artwork if it changed
return
# Only for the main backdrop, poster
if (window('plex_initialScan') != "true" and
imageType in ("fanart", "poster")):
# Delete current entry before updating with the new one
self.deleteCachedArtwork(url)
log.debug("Updating Art url for %s kodiId %s %s -> (%s)"
% (imageType, kodiId, url, imageUrl))
query = ' '.join(( query = ' '.join((
"UPDATE art",
"SELECT url", "SET url = ?",
"FROM art",
"WHERE media_id = ?", "WHERE media_id = ?",
"AND media_type = ?", "AND media_type = ?",
"AND type = ?" "AND type = ?"
)) ))
cursor.execute(query, (kodiId, mediaType, imageType,)) cursor.execute(query, (imageUrl, kodiId, mediaType, imageType))
try: # Update the artwork
url = cursor.fetchone()[0]
except TypeError: # Add the artwork # Cache fanart and poster in Kodi texture cache
cacheimage = True self.cacheTexture(imageUrl)
log.debug("Adding Art Link for kodiId: %s (%s)" % (kodiId, imageUrl))
query = (
'''
INSERT INTO art(media_id, media_type, type, url)
VALUES (?, ?, ?, ?)
'''
)
cursor.execute(query, (kodiId, mediaType, imageType, imageUrl))
else: # Only cache artwork if it changed
if url != imageUrl:
cacheimage = True
# Only for the main backdrop, poster
if (window('plex_initialScan') != "true" and
imageType in ("fanart", "poster")):
# Delete current entry before updating with the new one
self.deleteCachedArtwork(url)
log.info("Updating Art url for %s kodiId: %s (%s) -> (%s)"
% (imageType, kodiId, url, imageUrl))
query = ' '.join((
"UPDATE art",
"SET url = ?",
"WHERE media_id = ?",
"AND media_type = ?",
"AND type = ?"
))
cursor.execute(query, (imageUrl, kodiId, mediaType, imageType))
# Cache fanart and poster in Kodi texture cache
if cacheimage:
self.cacheTexture(imageUrl)
def deleteArtwork(self, kodiId, mediaType, cursor): def deleteArtwork(self, kodiId, mediaType, cursor):
query = ' '.join(( query = ' '.join((
"SELECT url",
"SELECT url, type",
"FROM art", "FROM art",
"WHERE media_id = ?", "WHERE media_id = ?",
"AND media_type = ?" "AND media_type = ?"
@ -458,159 +431,34 @@ class Artwork():
cursor.execute(query, (kodiId, mediaType,)) cursor.execute(query, (kodiId, mediaType,))
rows = cursor.fetchall() rows = cursor.fetchall()
for row in rows: for row in rows:
self.deleteCachedArtwork(row[0])
url = row[0]
imageType = row[1]
if imageType in ("poster", "fanart"):
self.deleteCachedArtwork(url)
def deleteCachedArtwork(self, url): def deleteCachedArtwork(self, url):
# Only necessary to remove and apply a new backdrop or poster # Only necessary to remove and apply a new backdrop or poster
connection = kodiSQL('texture') connection = kodiSQL('texture')
cursor = connection.cursor() cursor = connection.cursor()
try: try:
cursor.execute("SELECT cachedurl FROM texture WHERE url = ?", (url,)) cursor.execute("SELECT cachedurl FROM texture WHERE url = ?",
(url,))
cachedurl = cursor.fetchone()[0] cachedurl = cursor.fetchone()[0]
except TypeError: except TypeError:
log.info("Could not find cached url.") log.info("Could not find cached url.")
except OperationalError: except OperationalError:
log.info("Database is locked. Skip deletion process.") log.warn("Database is locked. Skip deletion process.")
else:
else: # Delete thumbnail as well as the entry # Delete thumbnail as well as the entry
thumbnails = tryDecode( thumbnails = tryDecode(
xbmc.translatePath("special://thumbnails/%s" % cachedurl)) xbmc.translatePath("special://thumbnails/%s" % cachedurl))
log.info("Deleting cached thumbnail: %s" % thumbnails) log.debug("Deleting cached thumbnail: %s" % thumbnails)
xbmcvfs.delete(thumbnails) try:
xbmcvfs.delete(thumbnails)
except Exception as e:
log.error('Could not delete cached artwork %s. Error: %s'
% (thumbnails, e))
try: try:
cursor.execute("DELETE FROM texture WHERE url = ?", (url,)) cursor.execute("DELETE FROM texture WHERE url = ?", (url,))
connection.commit() connection.commit()
except OperationalError: except OperationalError:
log.debug("Issue deleting url from cache. Skipping.") log.error("OperationalError deleting url from cache.")
finally: finally:
cursor.close() connection.close()
def getPeopleArtwork(self, people):
# append imageurl if existing
for person in people:
personId = person['Id']
tag = person.get('PrimaryImageTag')
image = ""
if tag:
image = (
"%s/emby/Items/%s/Images/Primary?"
"MaxWidth=400&MaxHeight=400&Index=0&Tag=%s"
% (self.server, personId, tag))
person['imageurl'] = image
return people
def getUserArtwork(self, itemId, itemType):
# Load user information set by UserClient
image = ("%s/emby/Users/%s/Images/%s?Format=original"
% (self.server, itemId, itemType))
return image
def getAllArtwork(self, item, parentInfo=False):
itemid = item['Id']
artworks = item['ImageTags']
backdrops = item.get('BackdropImageTags', [])
maxHeight = 10000
maxWidth = 10000
customquery = ""
# if utils.settings('compressArt') == "true":
# customquery = "&Quality=90"
# if utils.settings('enableCoverArt') == "false":
# customquery += "&EnableImageEnhancers=false"
allartworks = {
'Primary': "",
'Art': "",
'Banner': "",
'Logo': "",
'Thumb': "",
'Disc': "",
'Backdrop': []
}
# Process backdrops
for index, tag in enumerate(backdrops):
artwork = (
"%s/emby/Items/%s/Images/Backdrop/%s?"
"MaxWidth=%s&MaxHeight=%s&Format=original&Tag=%s%s"
% (self.server, itemid, index, maxWidth, maxHeight, tag, customquery))
allartworks['Backdrop'].append(artwork)
# Process the rest of the artwork
for art in artworks:
# Filter backcover
if art != "BoxRear":
tag = artworks[art]
artwork = (
"%s/emby/Items/%s/Images/%s/0?"
"MaxWidth=%s&MaxHeight=%s&Format=original&Tag=%s%s"
% (self.server, itemid, art, maxWidth, maxHeight, tag, customquery))
allartworks[art] = artwork
# Process parent items if the main item is missing artwork
if parentInfo:
# Process parent backdrops
if not allartworks['Backdrop']:
parentId = item.get('ParentBackdropItemId')
if parentId:
# If there is a parentId, go through the parent backdrop list
parentbackdrops = item['ParentBackdropImageTags']
for index, tag in enumerate(parentbackdrops):
artwork = (
"%s/emby/Items/%s/Images/Backdrop/%s?"
"MaxWidth=%s&MaxHeight=%s&Format=original&Tag=%s%s"
% (self.server, parentId, index, maxWidth, maxHeight, tag, customquery))
allartworks['Backdrop'].append(artwork)
# Process the rest of the artwork
parentartwork = ['Logo', 'Art', 'Thumb']
for parentart in parentartwork:
if not allartworks[parentart]:
parentId = item.get('Parent%sItemId' % parentart)
if parentId:
parentTag = item['Parent%sImageTag' % parentart]
artwork = (
"%s/emby/Items/%s/Images/%s/0?"
"MaxWidth=%s&MaxHeight=%s&Format=original&Tag=%s%s"
% (self.server, parentId, parentart,
maxWidth, maxHeight, parentTag, customquery))
allartworks[parentart] = artwork
# Parent album works a bit differently
if not allartworks['Primary']:
parentId = item.get('AlbumId')
if parentId and item.get('AlbumPrimaryImageTag'):
parentTag = item['AlbumPrimaryImageTag']
artwork = (
"%s/emby/Items/%s/Images/Primary/0?"
"MaxWidth=%s&MaxHeight=%s&Format=original&Tag=%s%s"
% (self.server, parentId, maxWidth, maxHeight, parentTag, customquery))
allartworks['Primary'] = artwork
return allartworks