PlexKodiConnect/resources/lib/artwork.py

200 lines
6.6 KiB
Python
Raw Normal View History

#!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import absolute_import, division, unicode_literals
2017-12-09 05:43:06 +11:00
from logging import getLogger
from urllib import quote_plus, unquote
2017-12-10 00:35:08 +11:00
import requests
import xbmc
2018-11-06 01:23:51 +11:00
from . import backgroundthread, path_ops, utils
2018-06-22 03:24:37 +10:00
from . import state
2016-08-30 03:39:59 +10:00
###############################################################################
2018-06-22 03:24:37 +10:00
LOG = getLogger('PLEX.artwork')
2018-03-02 17:36:45 +11:00
# Disable annoying requests warnings
requests.packages.urllib3.disable_warnings()
2018-11-06 04:00:01 +11:00
# Potentially issues with limited number of threads Hence let Kodi wait till
# download is successful
TIMEOUT = (35.1, 35.1)
2018-11-06 01:23:51 +11:00
IMAGE_CACHING_SUSPENDS = [
state.SUSPEND_LIBRARY_THREAD,
state.DB_SCAN
]
2018-06-22 03:24:37 +10:00
if not utils.settings('imageSyncDuringPlayback') == 'true':
2018-11-06 01:23:51 +11:00
IMAGE_CACHING_SUSPENDS.append(state.SUSPEND_SYNC)
2018-03-04 23:39:18 +11:00
###############################################################################
def double_urlencode(text):
return quote_plus(quote_plus(text))
def double_urldecode(text):
return unquote(unquote(text))
2018-11-06 01:23:51 +11:00
class ImageCachingThread(backgroundthread.KillableThread):
def __init__(self):
2018-11-06 04:00:01 +11:00
self._canceled = False
super(ImageCachingThread, self).__init__()
2018-11-06 01:23:51 +11:00
def isCanceled(self):
2018-11-06 04:00:01 +11:00
return self._canceled or state.STOP_PKC
2018-11-06 01:23:51 +11:00
def isSuspended(self):
return any(IMAGE_CACHING_SUSPENDS)
2018-11-06 04:00:01 +11:00
def cancel(self):
self._canceled = True
2018-11-06 01:23:51 +11:00
@staticmethod
def _art_url_generator():
from . import kodidb_functions as kodidb
for kind in ('video', 'music'):
with kodidb.GetKodiDB(kind) as kodi_db:
for kodi_type in ('poster', 'fanart'):
for url in kodi_db.artwork_generator(kodi_type):
yield url
def missing_art_cache_generator(self):
from . import kodidb_functions as kodidb
with kodidb.GetKodiDB('texture') as kodi_db:
for url in self._art_url_generator():
if kodi_db.url_not_yet_cached(url):
yield url
def run(self):
2018-11-06 00:18:52 +11:00
LOG.info("---===### Starting ImageCachingThread ###===---")
2018-11-06 01:23:51 +11:00
# Cache already synced artwork first
for url in self.missing_art_cache_generator():
if self.isCanceled():
return
while self.isSuspended():
# Set in service.py
2018-11-06 01:23:51 +11:00
if self.isCanceled():
# Abort was requested while waiting. We should exit
2018-11-06 00:18:52 +11:00
LOG.info("---===### Stopped ImageCachingThread ###===---")
return
xbmc.sleep(1000)
2018-11-06 04:00:01 +11:00
cache_url(url)
2018-11-06 00:18:52 +11:00
LOG.info("---===### Stopped ImageCachingThread ###===---")
2018-11-06 04:00:01 +11:00
def cache_url(url):
url = double_urlencode(utils.try_encode(url))
sleeptime = 0
while True:
try:
requests.head(
url="http://%s:%s/image/image://%s"
% (state.WEBSERVER_HOST,
state.WEBSERVER_PORT,
url),
auth=(state.WEBSERVER_USERNAME,
state.WEBSERVER_PASSWORD),
timeout=TIMEOUT)
except requests.Timeout:
# We don't need the result, only trigger Kodi to start the
# download. All is well
break
except requests.ConnectionError:
if state.STOP_PKC:
# Kodi terminated
break
# Server thinks its a DOS attack, ('error 10053')
# Wait before trying again
if sleeptime > 5:
LOG.error('Repeatedly got ConnectionError for url %s',
double_urldecode(url))
break
LOG.debug('Were trying too hard to download art, server '
'over-loaded. Sleep %s seconds before trying '
'again to download %s',
2**sleeptime, double_urldecode(url))
xbmc.sleep((2**sleeptime) * 1000)
sleeptime += 1
continue
except Exception as err:
LOG.error('Unknown exception for url %s: %s'.
double_urldecode(url), err)
import traceback
LOG.error("Traceback:\n%s", traceback.format_exc())
break
# We did not even get a timeout
break
2018-11-06 04:00:01 +11:00
def modify_artwork(artworks, kodi_id, kodi_type, cursor):
"""
Pass in an artworks dict (see PlexAPI) to set an items artwork.
"""
for kodi_art, url in artworks.iteritems():
modify_art(url, kodi_id, kodi_type, kodi_art, cursor)
2018-11-06 04:00:01 +11:00
def modify_art(url, kodi_id, kodi_type, kodi_art, cursor):
"""
Adds or modifies the artwork of kind kodi_art (e.g. 'poster') in the
Kodi art table for item kodi_id/kodi_type. Will also cache everything
except actor portraits.
"""
query = '''
SELECT url FROM art
WHERE media_id = ? AND media_type = ? AND type = ?
LIMIT 1
'''
cursor.execute(query, (kodi_id, kodi_type, kodi_art,))
try:
# Update the artwork
old_url = cursor.fetchone()[0]
except TypeError:
# Add the artwork
query = '''
INSERT INTO art(media_id, media_type, type, url)
VALUES (?, ?, ?, ?)
2018-03-04 23:39:18 +11:00
'''
2018-11-06 04:00:01 +11:00
cursor.execute(query, (kodi_id, kodi_type, kodi_art, url))
else:
if url == old_url:
# Only cache artwork if it changed
return
delete_cached_artwork(old_url)
2018-03-04 23:39:18 +11:00
query = '''
2018-11-06 04:00:01 +11:00
UPDATE art SET url = ?
2018-03-04 23:39:18 +11:00
WHERE media_id = ? AND media_type = ? AND type = ?
'''
2018-11-06 04:00:01 +11:00
cursor.execute(query, (url, kodi_id, kodi_type, kodi_art))
2018-11-06 04:00:01 +11:00
def delete_artwork(kodiId, mediaType, cursor):
cursor.execute('SELECT url FROM art WHERE media_id = ? AND media_type = ?',
(kodiId, mediaType, ))
for row in cursor.fetchall():
delete_cached_artwork(row[0])
def delete_cached_artwork(url):
"""
Deleted the cached artwork with path url (if it exists)
"""
from . import kodidb_functions as kodidb
with kodidb.GetKodiDB('texture') as kodi_db:
try:
2018-11-06 04:00:01 +11:00
kodi_db.cursor.execute("SELECT cachedurl FROM texture WHERE url=? LIMIT 1",
(url, ))
cachedurl = kodi_db.cursor.fetchone()[0]
except TypeError:
2018-03-01 03:42:21 +11:00
# Could not find cached url
pass
2016-09-11 21:51:53 +10:00
else:
# Delete thumbnail as well as the entry
path = path_ops.translate_path("special://thumbnails/%s"
% cachedurl)
if path_ops.exists(path):
path_ops.rmtree(path, ignore_errors=True)
2018-11-06 04:00:01 +11:00
kodi_db.cursor.execute("DELETE FROM texture WHERE url = ?", (url,))