spotify.py 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. # SPDX-License-Identifier: AGPL-3.0-or-later
  2. """
  3. Spotify (Music)
  4. """
  5. from json import loads
  6. from urllib.parse import urlencode
  7. import base64
  8. from searx.network import post as http_post
  9. # about
  10. about = {
  11. "website": 'https://www.spotify.com',
  12. "wikidata_id": 'Q689141',
  13. "official_api_documentation": 'https://developer.spotify.com/web-api/search-item/',
  14. "use_official_api": True,
  15. "require_api_key": False,
  16. "results": 'JSON',
  17. }
  18. # engine dependent config
  19. categories = ['music']
  20. paging = True
  21. api_client_id = None
  22. api_client_secret = None
  23. # search-url
  24. url = 'https://api.spotify.com/'
  25. search_url = url + 'v1/search?{query}&type=track&offset={offset}'
  26. embedded_url = '<iframe data-src="https://embed.spotify.com/?uri=spotify:track:{audioid}"\
  27. width="300" height="80" frameborder="0" allowtransparency="true"></iframe>'
  28. # do search-request
  29. def request(query, params):
  30. offset = (params['pageno'] - 1) * 20
  31. params['url'] = search_url.format(query=urlencode({'q': query}), offset=offset)
  32. r = http_post(
  33. 'https://accounts.spotify.com/api/token',
  34. data={'grant_type': 'client_credentials'},
  35. headers={'Authorization': 'Basic ' + base64.b64encode(
  36. "{}:{}".format(api_client_id, api_client_secret).encode()
  37. ).decode()}
  38. )
  39. j = loads(r.text)
  40. params['headers'] = {'Authorization': 'Bearer {}'.format(j.get('access_token'))}
  41. return params
  42. # get response from search-request
  43. def response(resp):
  44. results = []
  45. search_res = loads(resp.text)
  46. # parse results
  47. for result in search_res.get('tracks', {}).get('items', {}):
  48. if result['type'] == 'track':
  49. title = result['name']
  50. url = result['external_urls']['spotify']
  51. content = '{} - {} - {}'.format(
  52. result['artists'][0]['name'],
  53. result['album']['name'],
  54. result['name'])
  55. embedded = embedded_url.format(audioid=result['id'])
  56. # append result
  57. results.append({'url': url,
  58. 'title': title,
  59. 'embedded': embedded,
  60. 'content': content})
  61. # return results
  62. return results