Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

change artwork provider to fanart.tv #3214

Open
wants to merge 5 commits into
base: develop
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion data/interfaces/default/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@
"aTargets": [0],
"mData":"ArtistID",
"mRender": function ( data, type, full ) {
return '<div id="artistImg"><img class="albumArt" alt="" id="'+ data + '" data-src="artwork/thumbs/artist/' + data + '"/></div>';
return '<div id="artistImg"><img class="albumArt" height="50" width="50" alt="" id="'+ data + '" data-src="artwork/thumbs/artist/' + data + '"/></div>';
}
},
{
Expand Down
7 changes: 3 additions & 4 deletions headphones/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -443,10 +443,9 @@ def dbcheck():
# General speed up
c.execute('CREATE INDEX IF NOT EXISTS artist_artistsortname ON artists(ArtistSortName COLLATE NOCASE ASC)')

exists = c.execute('SELECT * FROM pragma_index_info("have_matched_artist_album")').fetchone()
if not exists:
c.execute('CREATE INDEX have_matched_artist_album ON have(Matched ASC, ArtistName COLLATE NOCASE ASC, AlbumTitle COLLATE NOCASE ASC)')
c.execute('DROP INDEX IF EXISTS have_matched')
c.execute(
"""CREATE INDEX IF NOT EXISTS have_matched_artist_album ON have(Matched ASC, ArtistName COLLATE NOCASE ASC, AlbumTitle COLLATE NOCASE ASC)""")
c.execute('DROP INDEX IF EXISTS have_matched')

try:
c.execute('SELECT IncludeExtras from artists')
Expand Down
3 changes: 3 additions & 0 deletions headphones/albumart.py
Original file line number Diff line number Diff line change
Expand Up @@ -139,6 +139,9 @@ def getartwork(artwork_path):
if headphones.CONFIG.ALBUM_ART_MAX_WIDTH:
maxwidth = int(headphones.CONFIG.ALBUM_ART_MAX_WIDTH)

if artwork_path is None:
return

resp = request.request_response(artwork_path, timeout=20, stream=True, whitelist_status_code=404)

if resp:
Expand Down
268 changes: 158 additions & 110 deletions headphones/cache.py

Large diffs are not rendered by default.

2 changes: 1 addition & 1 deletion headphones/importer.py
Original file line number Diff line number Diff line change
Expand Up @@ -540,7 +540,7 @@ def addArtisttoDB(artistid, extrasonly=False, forcefull=False, type="artist"):
try:
cache.getThumb(ArtistID=artistid)
except Exception as e:
logger.error("Error getting album art: %s", e)
logger.error("Error getting artist art: %s", e)

logger.info(u"Fetching Metacritic reviews for: %s" % artist['artist_name'])
try:
Expand Down
6 changes: 4 additions & 2 deletions headphones/lastfm.py
Original file line number Diff line number Diff line change
Expand Up @@ -52,11 +52,13 @@ def request_lastfm(method, **kwargs):
# Parse response and check for errors.
if not data:
logger.error("Error calling Last.FM method: %s", method)
return
# when there is a last.fm api fail, this return prevents artist artwork from loading
# return

if "error" in data:
logger.debug("Last.FM returned an error: %s", data["message"])
return
# when there is a last.fm api fail, this return prevents artist artwork from loading
# return

return data

Expand Down
118 changes: 118 additions & 0 deletions lib/fanart/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,118 @@
__author__ = 'Andrea De Marco <[email protected]>'
__maintainer__ = 'Pol Canelles <[email protected]>'
__version__ = '2.0.0'
__classifiers__ = [
'Development Status :: 5 - Production/Stable',
'Intended Audience :: Developers',
'License :: OSI Approved :: Apache Software License',
'Operating System :: OS Independent',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
'Programming Language :: Python :: 3.6',
'Programming Language :: Python :: 3.7',
'Topic :: Internet :: WWW/HTTP',
'Topic :: Software Development :: Libraries',
]
__copyright__ = "2012, %s " % __author__
__license__ = """
Copyright %s.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either expressed or implied.
See the License for the specific language governing permissions and
limitations under the License.
""" % __copyright__

__docformat__ = 'restructuredtext en'

__doc__ = """
:abstract: Python interface to fanart.tv API (v3)
:version: %s
:author: %s
:contact: http://z4r.github.com/
:date: 2012-04-04
:copyright: %s
""" % (__version__, __author__, __license__)


def values(obj):
return [v for k, v in obj.__dict__.items() if not k.startswith('_')]


BASEURL = 'http://webservice.fanart.tv/v3'


class FORMAT(object):
JSON = 'JSON'
XML = 'XML'
PHP = 'PHP'


class WS(object):
MUSIC = 'music'
MOVIE = 'movies'
TV = 'tv'


class TYPE(object):
ALL = 'all'

class TV(object):
ART = 'clearart'
LOGO = 'clearlogo'
CHARACTER = 'characterart'
THUMB = 'tvthumb'
SEASONTHUMB = 'seasonthumb'
SEASONBANNER = 'seasonbanner'
SEASONPOSTER = 'seasonposter'
BACKGROUND = 'showbackground'
HDLOGO = 'hdtvlogo'
HDART = 'hdclearart'
POSTER = 'tvposter'
BANNER = 'tvbanner'

class MUSIC(object):
DISC = 'cdart'
LOGO = 'musiclogo'
BACKGROUND = 'artistbackground'
COVER = 'albumcover'
THUMB = 'artistthumb'

class MOVIE(object):
ART = 'movieart'
LOGO = 'movielogo'
DISC = 'moviedisc'
POSTER = 'movieposter'
BACKGROUND = 'moviebackground'
HDLOGO = 'hdmovielogo'
HDART = 'hdmovieclearart'
BANNER = 'moviebanner'
THUMB = 'moviethumb'


class SORT(object):
POPULAR = 1
NEWEST = 2
OLDEST = 3


class LIMIT(object):
ONE = 1
ALL = 2


FORMAT_LIST = values(FORMAT)
WS_LIST = values(WS)
TYPE_LIST = values(TYPE.MUSIC) + values(TYPE.TV) + values(TYPE.MOVIE) + [TYPE.ALL]
MUSIC_TYPE_LIST = values(TYPE.MUSIC) + [TYPE.ALL]
TV_TYPE_LIST = values(TYPE.TV) + [TYPE.ALL]
MOVIE_TYPE_LIST = values(TYPE.MOVIE) + [TYPE.ALL]
SORT_LIST = values(SORT)
LIMIT_LIST = values(LIMIT)
50 changes: 50 additions & 0 deletions lib/fanart/core.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
import requests
import fanart
from fanart.errors import RequestFanartError, ResponseFanartError


class Request(object):
def __init__(self, apikey, id, ws, type=None, sort=None, limit=None):
'''
.. warning:: Since the migration to fanart.tv's api v3, we cannot use
the kwargs `type/sort/limit` as we did before, so for now this
kwargs will be ignored.
'''
self._apikey = apikey
self._id = id
self._ws = ws
self._type = type or fanart.TYPE.ALL
self._sort = sort or fanart.SORT.POPULAR
self._limit = limit or fanart.LIMIT.ALL
self.validate()
self._response = None

def validate(self):
for attribute_name in ('ws', 'type', 'sort', 'limit'):
attribute = getattr(self, '_' + attribute_name)
choices = getattr(fanart, attribute_name.upper() + '_LIST')
if attribute not in choices:
raise RequestFanartError(
'Not allowed {}: {} [{}]'.format(
attribute_name, attribute, ', '.join(choices)))

def __str__(self):
return '{base_url}/{ws}/{id}?api_key={apikey}'.format(
base_url=fanart.BASEURL,
ws=self._ws,
id=self._id,
apikey=self._apikey,
)

def response(self):
try:
response = requests.get(str(self))
rjson = response.json()
if not isinstance(rjson, dict):
raise Exception(response.text)
if 'error message' in rjson:
#raise Exception(rjson['status'], rjson['error message'])
raise Exception(rjson['error message'])
return rjson
except Exception as e:
raise ResponseFanartError(str(e))
15 changes: 15 additions & 0 deletions lib/fanart/errors.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
class FanartError(Exception):
def __str__(self):
return ', '.join(map(str, self.args))

def __repr__(self):
name = self.__class__.__name__
return '%s%r' % (name, self.args)


class ResponseFanartError(FanartError):
pass


class RequestFanartError(FanartError):
pass
46 changes: 46 additions & 0 deletions lib/fanart/immutable.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
class Immutable(object):
_mutable = False

def __setattr__(self, name, value):
if self._mutable or name == '_mutable':
super(Immutable, self).__setattr__(name, value)
else:
raise TypeError("Can't modify immutable instance")

def __delattr__(self, name):
if self._mutable:
super(Immutable, self).__delattr__(name)
else:
raise TypeError("Can't modify immutable instance")

def __eq__(self, other):
return hash(self) == hash(other)

def __hash__(self):
return hash(repr(self))

def __repr__(self):
return '%s(%s)' % (
self.__class__.__name__,
', '.join(['{0}={1}'.format(k, repr(v)) for k, v in self])
)

def __iter__(self):
l = list(self.__dict__.keys())
l.sort()
for k in l:
if not k.startswith('_'):
yield k, getattr(self, k)

@staticmethod
def mutablemethod(f):
def func(self, *args, **kwargs):
if isinstance(self, Immutable):
old_mutable = self._mutable
self._mutable = True
res = f(self, *args, **kwargs)
self._mutable = old_mutable
else:
res = f(self, *args, **kwargs)
return res
return func
70 changes: 70 additions & 0 deletions lib/fanart/items.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
import json
import os
import requests
from fanart.core import Request
from fanart.immutable import Immutable


class LeafItem(Immutable):
KEY = NotImplemented

@Immutable.mutablemethod
def __init__(self, id, url, likes):
self.id = int(id)
self.url = url
self.likes = int(likes)
self._content = None

@classmethod
def from_dict(cls, resource):
return cls(**dict([(str(k), v) for k, v in resource.items()]))

@classmethod
def extract(cls, resource):
return [cls.from_dict(i) for i in resource.get(cls.KEY, {})]

@Immutable.mutablemethod
def content(self):
if not self._content:
self._content = requests.get(self.url).content
return self._content

def __str__(self):
return self.url


class ResourceItem(Immutable):
WS = NotImplemented
request_cls = Request

@classmethod
def from_dict(cls, map):
raise NotImplementedError

@classmethod
def get(cls, id):
map = cls.request_cls(
apikey=os.environ.get('FANART_APIKEY'),
id=id,
ws=cls.WS
).response()
return cls.from_dict(map)

def json(self, **kw):
return json.dumps(
self,
default=lambda o: dict(
[(k, v) for k, v in o.__dict__.items()
if not k.startswith('_')]),
**kw
)


class CollectableItem(Immutable):
@classmethod
def from_dict(cls, key, map):
raise NotImplementedError

@classmethod
def collection_from_dict(cls, map):
return [cls.from_dict(k, v) for k, v in map.items()]
Loading