soundcloud.py 3.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103
  1. # SPDX-License-Identifier: AGPL-3.0-or-later
  2. """
  3. Soundcloud (Music)
  4. """
  5. import re
  6. from json import loads
  7. from lxml import html
  8. from dateutil import parser
  9. from urllib.parse import quote_plus, urlencode
  10. from searx.network import get as http_get
  11. # about
  12. about = {
  13. "website": 'https://soundcloud.com',
  14. "wikidata_id": 'Q568769',
  15. "official_api_documentation": 'https://developers.soundcloud.com/',
  16. "use_official_api": True,
  17. "require_api_key": False,
  18. "results": 'JSON',
  19. }
  20. # engine dependent config
  21. categories = ['music']
  22. paging = True
  23. # search-url
  24. # missing attribute: user_id, app_version, app_locale
  25. url = 'https://api-v2.soundcloud.com/'
  26. search_url = (
  27. url + 'search?{query}'
  28. '&variant_ids='
  29. '&facet=model'
  30. '&limit=20'
  31. '&offset={offset}'
  32. '&linked_partitioning=1'
  33. '&client_id={client_id}'
  34. ) # noqa
  35. cid_re = re.compile(r'client_id:"([^"]*)"', re.I | re.U)
  36. guest_client_id = ''
  37. def get_client_id():
  38. response = http_get("https://soundcloud.com")
  39. if response.ok:
  40. tree = html.fromstring(response.content)
  41. # script_tags has been moved from /assets/app/ to /assets/ path. I
  42. # found client_id in https://a-v2.sndcdn.com/assets/49-a0c01933-3.js
  43. script_tags = tree.xpath("//script[contains(@src, '/assets/')]")
  44. app_js_urls = [script_tag.get('src') for script_tag in script_tags if script_tag is not None]
  45. # extracts valid app_js urls from soundcloud.com content
  46. for app_js_url in app_js_urls[::-1]:
  47. # gets app_js and searches for the clientid
  48. response = http_get(app_js_url)
  49. if response.ok:
  50. cids = cid_re.search(response.content.decode())
  51. if cids is not None and len(cids.groups()):
  52. return cids.groups()[0]
  53. logger.warning("Unable to fetch guest client_id from SoundCloud, check parser!")
  54. return ""
  55. def init(engine_settings=None):
  56. global guest_client_id
  57. # api-key
  58. guest_client_id = get_client_id()
  59. # do search-request
  60. def request(query, params):
  61. offset = (params['pageno'] - 1) * 20
  62. params['url'] = search_url.format(query=urlencode({'q': query}), offset=offset, client_id=guest_client_id)
  63. return params
  64. # get response from search-request
  65. def response(resp):
  66. results = []
  67. search_res = loads(resp.text)
  68. # parse results
  69. for result in search_res.get('collection', []):
  70. if result['kind'] in ('track', 'playlist'):
  71. uri = quote_plus(result['uri'])
  72. res = {
  73. 'url': result['permalink_url'],
  74. 'title': result['title'],
  75. 'content': result['description'] or '',
  76. 'publishedDate': parser.parse(result['last_modified']),
  77. 'iframe_src': "https://w.soundcloud.com/player/?url=" + uri,
  78. }
  79. img_src = result['artwork_url'] or result['user']['avatar_url']
  80. if img_src:
  81. res['img_src'] = img_src
  82. results.append(res)
  83. return results