1
0
mirror of https://github.com/spl0k/supysonic.git synced 2024-12-23 01:16:18 +00:00

Cache lyrics obtained from ChartLyrics

Lyrics are stored as json in a zlib-compressed file.
This commit is contained in:
Carey Metcalfe 2019-01-17 00:51:42 -05:00
parent 3db489aa7b
commit 7fa1501112

View File

@ -16,6 +16,9 @@ import shlex
import subprocess import subprocess
import uuid import uuid
import io import io
import hashlib
import json
import zlib
from flask import request, Response, send_file from flask import request, Response, send_file
from flask import current_app from flask import current_app
@ -234,21 +237,37 @@ def lyrics():
value = lyrics value = lyrics
)) ))
# Create a stable, unique, filesystem-compatible identifier for the artist+title
unique = hashlib.md5(json.dumps([x.lower() for x in (artist, title)]).encode('utf-8')).hexdigest()
cache_key = "lyrics-{}".format(unique)
lyrics = dict()
try:
lyrics = json.loads(
zlib.decompress(
current_app.cache.get_value(cache_key)
).decode('utf-8')
)
except (CacheMiss, zlib.error, TypeError, ValueError):
try: try:
r = requests.get("http://api.chartlyrics.com/apiv1.asmx/SearchLyricDirect", r = requests.get("http://api.chartlyrics.com/apiv1.asmx/SearchLyricDirect",
params={'artist': artist, 'song': title}, timeout=5) params={'artist': artist, 'song': title}, timeout=5)
root = ElementTree.fromstring(r.content) root = ElementTree.fromstring(r.content)
ns = {'cl': 'http://api.chartlyrics.com/'} ns = {'cl': 'http://api.chartlyrics.com/'}
return request.formatter('lyrics', dict( lyrics = dict(
artist = root.find('cl:LyricArtist', namespaces=ns).text, artist = root.find('cl:LyricArtist', namespaces=ns).text,
title = root.find('cl:LyricSong', namespaces=ns).text, title = root.find('cl:LyricSong', namespaces=ns).text,
value = root.find('cl:Lyric', namespaces=ns).text value = root.find('cl:Lyric', namespaces=ns).text
)) )
current_app.cache.set(
cache_key, zlib.compress(json.dumps(lyrics).encode('utf-8'), 9)
)
except requests.exceptions.RequestException as e: # pragma: nocover except requests.exceptions.RequestException as e: # pragma: nocover
logger.warning('Error while requesting the ChartLyrics API: ' + str(e)) logger.warning('Error while requesting the ChartLyrics API: ' + str(e))
return request.formatter('lyrics', dict()) # pragma: nocover return request.formatter('lyrics', lyrics)
def read_file_as_unicode(path): def read_file_as_unicode(path):
""" Opens a file trying with different encodings and returns the contents as a unicode string """ """ Opens a file trying with different encodings and returns the contents as a unicode string """