From b6a66ff2edcc3645ec9d02507e8e8357f3be2ca7 Mon Sep 17 00:00:00 2001 From: Krateng Date: Sat, 25 Jul 2020 18:38:56 +0200 Subject: [PATCH] Added Spotify metadata service --- maloja/thirdparty/__init__.py | 12 ++++++++++-- maloja/thirdparty/spotify.py | 36 +++++++++++++++++++++++++++++++++++ 2 files changed, 46 insertions(+), 2 deletions(-) create mode 100644 maloja/thirdparty/spotify.py diff --git a/maloja/thirdparty/__init__.py b/maloja/thirdparty/__init__.py index 78b08f0..097a7a2 100644 --- a/maloja/thirdparty/__init__.py +++ b/maloja/thirdparty/__init__.py @@ -9,6 +9,7 @@ import xml.etree.ElementTree as ElementTree import json import urllib.parse, urllib.request +import base64 from doreah.settings import get_settings from doreah.logging import log @@ -52,6 +53,7 @@ class GenericInterface: # avoid constant disk access, restart on adding services is acceptable for key in self.settings: self.settings[key] = get_settings(self.settings[key]) + self.authorize() def __init_subclass__(cls,abstract=False): if not abstract: @@ -66,6 +68,10 @@ class GenericInterface: services["metadata"].append(s) log(cls.name + " registered as metadata provider") + def authorize(self): + return True + # per default. no authorization is necessary + # proxy scrobbler class ProxyScrobbleInterface(GenericInterface,abstract=True): @@ -150,13 +156,15 @@ class MetadataInterface(GenericInterface,abstract=True): def utf(st): return st.encode(encoding="UTF-8") - +def b64(inp): + return base64.b64encode(inp) ### actually create everything __all__ = [ - "lastfm" + "lastfm", + "spotify" ] from . import * diff --git a/maloja/thirdparty/spotify.py b/maloja/thirdparty/spotify.py new file mode 100644 index 0000000..1c14e85 --- /dev/null +++ b/maloja/thirdparty/spotify.py @@ -0,0 +1,36 @@ +from . import MetadataInterface, utf, b64 +import hashlib +import urllib.parse, urllib.request +import json + +class Spotify(MetadataInterface): + name = "Spotify" + + settings = { + "apiid":"SPOTIFY_API_ID", + "secret":"SPOTIFY_API_SECRET" + } + + metadata = { + "trackurl": "https://api.spotify.com/v1/search?q={artist}%20{title}&type=track&access_token={token}", + "response_type":"json", + "response_parse_tree": ["tracks","items",0,"album","images",0,"url"], + "required_settings": ["apiid","secret"], + "activated_setting": "METADATA_SPOTIFY" + } + + def authorize(self): + + keys = { + "url":"https://accounts.spotify.com/api/token", + "method":"POST", + "headers":{ + "Authorization":"Basic " + b64(utf(self.settings["apiid"] + ":" + self.settings["secret"])).decode("utf-8") + }, + "data":bytes(urllib.parse.urlencode({"grant_type":"client_credentials"}),encoding="utf-8") + } + req = urllib.request.Request(**keys) + response = urllib.request.urlopen(req) + self.settings["token"] = json.loads(response.read())["access_token"] + print(self.settings) + return True