spotify.py 2.0 KB

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