spotify.py 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  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. # do search-request
  27. def request(query, params):
  28. offset = (params['pageno'] - 1) * 20
  29. params['url'] = search_url.format(query=urlencode({'q': query}), offset=offset)
  30. r = http_post(
  31. 'https://accounts.spotify.com/api/token',
  32. data={'grant_type': 'client_credentials'},
  33. headers={
  34. 'Authorization': 'Basic '
  35. + base64.b64encode("{}:{}".format(api_client_id, api_client_secret).encode()).decode()
  36. },
  37. )
  38. j = loads(r.text)
  39. params['headers'] = {'Authorization': 'Bearer {}'.format(j.get('access_token'))}
  40. return params
  41. # get response from search-request
  42. def response(resp):
  43. results = []
  44. search_res = loads(resp.text)
  45. # parse results
  46. for result in search_res.get('tracks', {}).get('items', {}):
  47. if result['type'] == 'track':
  48. title = result['name']
  49. url = result['external_urls']['spotify']
  50. content = '{} - {} - {}'.format(result['artists'][0]['name'], result['album']['name'], result['name'])
  51. # append result
  52. results.append(
  53. {
  54. 'url': url,
  55. 'title': title,
  56. 'iframe_src': "https://embed.spotify.com/?uri=spotify:track:" + result['id'],
  57. 'content': content,
  58. }
  59. )
  60. # return results
  61. return results