Commit 400574c1 authored by Jean-Francois Dockes's avatar Jean-Francois Dockes
Browse files

deezer embryo: displays a bit of stuff, no playing yet

parent b33c2fa2
#!/usr/bin/python3
#
# A lot of code copied from the Kodi Tidal addon which is:
# Copyright (C) 2014 Thomas Amland
#
# Additional code and modifications:
# Copyright (C) 2020 J.F.Dockes
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
import sys
import os
import json
import re
import base64
import conftree
import cmdtalkplugin
from upmplgutils import *
# Using kodi plugin routing plugin: lets use reuse a lot of code from
# the addon.
from routing import Plugin
# Need bogus base_url value to avoid plugin trying to call xbmc to
# retrieve addon id
plugin = Plugin('')
import deezersession
_rootid = '0$deezer$'
_rootidre = '0\$deezer\$'
def msg(s):
print("%s" % s, file=sys.stderr)
# Func name to method mapper
dispatcher = cmdtalkplugin.Dispatch()
# Pipe message handler
msgproc = cmdtalkplugin.Processor(dispatcher)
sess = deezersession.Session()
def maybelogin():
if sess.isloggedin():
return True
global httphp
if "UPMPD_HTTPHOSTPORT" not in os.environ:
raise Exception("No UPMPD_HTTPHOSTPORT in environment")
httphp = os.environ["UPMPD_HTTPHOSTPORT"]
global pathprefix
if "UPMPD_PATHPREFIX" not in os.environ:
raise Exception("No UPMPD_PATHPREFIX in environment")
pathprefix = os.environ["UPMPD_PATHPREFIX"]
if "UPMPD_CONFIG" not in os.environ:
raise Exception("No UPMPD_CONFIG in environment")
upconfig = conftree.ConfSimple(os.environ["UPMPD_CONFIG"])
username = upconfig.get('deezeruser')
password = upconfig.get('deezerpass')
if not username or not password:
raise Exception("deezeruser and/or deezerpass " +
"not set in configuration")
setMimeAndSamplerate("audio/mpeg", "44100")
cachedir = getcachedir(upconfig, "deezer")
return sess.login(cachedir, username, password)
def add_directory(title, endpoint):
if callable(endpoint):
endpoint = plugin.url_for(endpoint)
xbmcplugin.addDirectoryItem(None, endpoint, title)
def urls_from_id(view_func, items):
#msgproc.log("urls_from_id: items: %s" % str([item.id for item in items]))
return [plugin.url_for(view_func, item.id)
for item in items if str(item.id).find('http') != 0]
def view(data_items, urls, end=True):
for item, url in zip(data_items, urls):
title = item.name
try:
image = item.image if item.image else None
except:
image = None
try:
upnpclass = item.upnpclass if item.upnpclass else None
except:
upnpclass = None
try:
artnm = item.artist if item.artist else None
except:
artnm = None
xbmcplugin.entries.append(
direntry(_rootid + url, xbmcplugin.objid, title, arturi=image,
artist=artnm, upnpclass=upnpclass))
def track_list(tracks):
xbmcplugin.entries += trackentries(httphp, pathprefix,
xbmcplugin.objid, tracks)
@plugin.route('/')
def root():
if not maybelogin():
return []
items = sess.get_alluserplaylists()
view(items, urls_from_id(userplaylist_view, items))
@plugin.route('/userplaylist_view/<id>')
def userplaylist_view(id):
track_list(sess.get_user_playlist(id))
@plugin.route('/artist/<artist_id>')
def artist_view(artist_id):
albums = session.get_artist_albums(artist_id)
view(albums, urls_from_id(album_view, albums))
@plugin.route('/album/<album_id>')
def album_view(album_id):
track_list(session.get_album_tracks(album_id))
@dispatcher.record('browse')
def browse(a):
global xbmcplugin
xbmcplugin = XbmcPlugin(_rootid)
msgproc.log("browse: [%s]" % a)
if 'objid' not in a:
raise Exception("No objid in args")
objid = a['objid']
bflg = a['flag'] if 'flag' in a else 'children'
if re.match(_rootidre, objid) is None:
raise Exception("bad objid [%s]" % objid)
maybelogin()
xbmcplugin.objid = objid
idpath = objid.replace(_rootid, '', 1)
plugin.run([idpath])
#msgproc.log("%s" % xbmcplugin.entries)
encoded = json.dumps(xbmcplugin.entries)
return {"entries" : encoded}
@dispatcher.record('search')
def search(a):
global xbmcplugin
xbmcplugin = XbmcPlugin(_rootid)
msgproc.log("search: %s" % a)
objid = a['objid']
field = a['field'] if 'field' in a else None
value = a['value']
objkind = a['objkind'] if 'objkind' in a and a['objkind'] else None
if re.match(_rootidre, objid) is None:
raise Exception("bad objid [%s]" % objid)
xbmcplugin.objid = objid
maybelogin()
if objkind and objkind not in ['album', 'artist', 'track']:
objkind = 'album'
# Deezer search takes a string and a 'filter' value which defines
# the kind of results: 'album', 'artist', 'track'. We would like
# to be able to search a specific field, but nope
searchresults = sess.search(value, objkind)
if (not objkind or objkind == 'artist') and searchresults.artists:
view(searchresults.artists,
urls_from_id(artist_view, searchresults.artists), end=False)
if (not objkind or objkind == 'album') and searchresults.albums:
view(searchresults.albums,
urls_from_id(album_view, searchresults.albums), end=False)
if (not objkind or objkind == 'track') and searchresults.tracks:
track_list(searchresults.tracks)
#msgproc.log("search results: %s" % xbmcplugin.entries)
encoded = json.dumps(xbmcplugin.entries)
return {"entries" : encoded}
msgproc.log("Deezer running")
msgproc.mainloop()
#
# Copyright (C) 2021 Jean-Francois Dockes
#
# A lot of code strongly inspired or copied from the Kodi Deezer API,
# the copyright of which is not too clear (but it's GPL):
# Copyright (C) 2016 Jakub Gawron
# Copyright (C) 2020 Valentin271 (Github.com)
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the
# Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
# Deezer low level interface and session management. We return barely
# prepared json objects
import sys
import time
import requests
import json
import hashlib
from upmplgutils import *
# For debugging the details of the HTTP transaction. Note that http.client
# logs to stdout by default, so you need to actually edit the module to log
# to stderr if you want these messages (else they mess up the communication
# with our parent).
#import logging
#import http.client as http_client
#http_client.HTTPConnection.debuglevel = 1
#logging.basicConfig(stream=sys.stderr)
#logging.getLogger().setLevel(logging.DEBUG)
#requests_log = logging.getLogger("requests.packages.urllib3")
#requests_log.setLevel(logging.DEBUG)
#requests_log.propagate = True
# Bogus logging class initially to avoid to change the qobuz module code. Could
# get rid of it here...
class MLog(object):
def __init__(self):
self.f = sys.stderr
self.level = 3
def _doprint(self, msg):
print("DeezerAPI: %s" % msg, file=self.f)
def debug(self, msg):
if self.level >= 3:
self._doprint(msg)
def info(self, msg):
if self.level >= 2:
self._doprint(msg)
def warn(self, msg):
if self.level >= 1:
self._doprint(msg)
log = MLog()
class DeezerAPI(object):
def __init__(self):
self.apiUrl = "http://api.deezer.com/2.0/{service}/{id}/{method}"
self.streamUrl = "http://tv.deezer.com/smarttv/streaming.php"
self.authUrl = "http://tv.deezer.com/smarttv/authentication.php"
self.username = None
self.passmd5 = None
self.access_token = None
self.user_id = None
self.error = None
self.status_code = None
self.session = requests.Session()
def _check_ka(self, ka, mandatory, allowed=[]):
for label in mandatory:
if not label in ka:
raise Exception("DeezerAPI: missing parameter %s" % label)
for label in ka:
if label not in mandatory and label not in allowed:
raise Exception("DeezerAPI: invalid parameter %s" % label)
def _api_request(self, service, id='', method='', params={}):
self.error = ''
self.status_code = None
url = self.apiUrl.format(service=service,id=id,method=method)
r = None
iparams = {'output': 'json', 'access_token': self.access_token}
params.update(iparams)
log.info("Request: url [%s] params [%s]" % (url, params))
time1 = time.time()
try:
r = self.session.get(url, params=params)
except:
self.error = 'HTTP request failed'
log.warn(self.error)
return None
time2 = time.time()
log.info('Request took {:.3f} ms'.format((time2-time1)*1000.0))
#log.debug("DeezerAPI: response: %s" % r.text)
self.status_code = int(r.status_code)
if self.status_code != 200:
log.warn("status code !200. data: %s" % r.content)
return None
if not r.content:
self.error = 'Request return no content'
log.warn(self.error)
return None
js = r.json()
if 'error' in js:
code = js['error']['code']
log.warn("Deezer returned error: %s" % r.content)
# Do something if it is "need login again"
return None
return js
def isloggedin(self):
log.debug("isloggedin(): username %s" % self.username)
return self.access_token is not None
def _clear_login(self):
self.access_token = None
self.user_id = None
def user_login(self, cachedir, username, password):
log.info("user_login")
self.username = username
self.passmd5 = hashlib.md5(password.encode('utf-8')).hexdigest()
try:
with open(os.path.join(cachedir, 'token'), "r") as f:
self.access_token = f.read()
except:
data = self.session.get(self.authUrl, params={
'login': self.username, 'password': self.passmd5,
'device': 'panasonic'})
js = data.json()
if 'access_token' not in js:
log.warn("login failed")
if data:
log.warn("deezer response %s" % data.content)
self._clear_login()
return False
self.access_token = js['access_token']
with open(os.path.join(cachedir, 'token'), "w") as f:
f.write(self.access_token)
if not self.getUser():
log.warn("getUser failed")
return True
return False
def getUser(self):
data = self._api_request('user', 'me')
if 'id' in data:
self.user_id = data['id']
return True
return False
def getAllUserPlaylists(self, **ka):
if not self.isloggedin():
return {}
data = self._api_request('user', self.user_id, 'playlists')
return data
def getUserPlaylist(self, **ka):
if not self.isloggedin():
return None
self._check_ka(ka, ['playlist_id'])
data = self._api_request('playlist', ka['playlist_id'], 'tracks')
return None
def search(self, query, filter, offset=0):
if not self.isloggedin():
return None
data = self._api_request('search', method=filter,
params={'q': query, 'index': offset})
return data
# defined to emulate the session object from the tidal module, which is
# defined in the tidalapi part (we want to keep the qobuz api/ dir as
# much alone as possible.
from __future__ import print_function
import sys
import json
from upmplgmodels import Artist, Album, Track, Playlist, SearchResult, \
Category, Genre, Model
from upmplgutils import *
import deezerapi
import urllib
import datetime
import traceback
import base64
class Session(object):
def __init__(self):
self.api = deezerapi.DeezerAPI()
def login(self, cachedir, username, password):
data = self.api.user_login(cachedir, username, password)
if data:
return True
else:
return False
def isloggedin(self):
return self.api.isloggedin()
def get_alluserplaylists(self):
data = self.api.getAllUserPlaylists()
if not data:
return []
return [_parse_playlist(p) for p in data['data']]
def get_user_playlist(self, id):
data = self.api.getUserPlaylist(playlist_id=id)
if not data:
return []
return [_parse_track(t) for t in data]
def _search1(self, query, tp):
uplog("_search1: query [%s] tp [%s]" % (query, tp))
limit = 200
if tp == 'artist':
limit = 20
elif tp == 'album' or tp == 'playlist':
limit = 50
offset = 0
all = []
while offset < limit:
uplog("_search1: call api.search, offset %d" % offset)
data = self.api.search(query, tp, offset=offset)
uplog("_search1: got %d results" % len(data['data']))
ncnt = 0
ndata = []
try:
if tp == 'artist':
ncnt = len(data['data'])
ndata = [_parse_artist(i) for i in data['data']]
elif tp == 'album':
ncnt = len(data['data'])
ndata = [_parse_album(i) for i in data['data']]
elif tp == 'track':
ncnt = len(data['data'])
ndata = [_parse_track(i) for i in data['data']]
except Exception as err:
uplog("_search1: exception while parsing result: %s" % err)
break
all.extend(ndata)
if ncnt == 0:
break
offset += ncnt
if tp == 'artist':
return SearchResult(artists=all)
elif tp == 'album':
return SearchResult(albums=all)
elif tp == 'track':
return SearchResult(tracks=all)
def search(self, query, tp):
if tp:
return self._search1(query, tp)
else:
cplt = SearchResult()
res = self._search1(query, 'artist')
cplt.artists = res.artists
res = self._search1(query, 'album')
cplt.albums = res.albums
res = self._search1(query, 'track')
cplt.tracks = res.tracks
return cplt
def _parse_playlist(data, artist=None, artists=None):
kwargs = {
'id': data['id'],
'name': data['title'],
'num_tracks': data.get('nb_tracks'),
'duration': data.get('duration')
}
return Playlist(**kwargs)
def encode_prefix(p):
return base64.urlsafe_b64encode(p.encode('utf-8')).decode('utf-8')
def decode_prefix(p):
return base64.urlsafe_b64decode(p.encode('utf-8')).decode('utf-8')
def _parse_category(data):
return Category(id=encode_prefix(data['prefix']), name=data['title'], iid = data['id'])
def _parse_genre(data):
return Genre(id=encode_prefix(data['prefix']), name=data['title'], iid = data['id'])
def _parse_artist(data):
return Artist(id=data['id'], name=data['name'])
def _parse_album(data):
#uplog(data)
#uplog("-_"*30)
kwargs = {
'id': data['id'],
'name': data['title']
}
if 'artist' in data:
kwargs['artist'] = data['artist']['name']
k = 'cover'
if 'cover_big' in data:
k = 'cover_big'
if k in data:
kwargs['image'] = data[k]
a = Album(**kwargs)
return a
def _parse_track(data, albumarg = None):
artist = Artist(id=data['artist']['id'], name=data['artist']['name'])
kwargs = {
'id': data['id'],
'name': data['title'],
'duration': data['duration'],
'artist': artist,
'available': True
}
if 'track_position' in data:
kwargs['track_num'] = data['track_position']
else:
kwargs['track_num'] = 0
if albumarg:
kwargs['album'] = albumarg
elif 'album' in data:
alb = data['album']
kwargs['album'] = Album(image=alb['cover_big'], name=alb['title'])
# If track has own cover, use it (e.g. for multialbum playlists)
if 'picture_big' in data:
kwargs['image'] = data['picture_big']
return Track(**kwargs)
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment