soundcloud.py 3.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108
  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 = url + 'search?{query}'\
  27. '&variant_ids='\
  28. '&facet=model'\
  29. '&limit=20'\
  30. '&offset={offset}'\
  31. '&linked_partitioning=1'\
  32. '&client_id={client_id}' # noqa
  33. embedded_url = '<iframe width="100%" height="166" ' +\
  34. 'scrolling="no" frameborder="no" ' +\
  35. 'data-src="https://w.soundcloud.com/player/?url={uri}"></iframe>'
  36. cid_re = re.compile(r'client_id:"([^"]*)"', re.I | re.U)
  37. guest_client_id = ''
  38. def get_client_id():
  39. response = http_get("https://soundcloud.com")
  40. if response.ok:
  41. tree = html.fromstring(response.content)
  42. # script_tags has been moved from /assets/app/ to /assets/ path. I
  43. # found client_id in https://a-v2.sndcdn.com/assets/49-a0c01933-3.js
  44. script_tags = tree.xpath("//script[contains(@src, '/assets/')]")
  45. app_js_urls = [script_tag.get('src') for script_tag in script_tags if script_tag is not None]
  46. # extracts valid app_js urls from soundcloud.com content
  47. for app_js_url in app_js_urls[::-1]:
  48. # gets app_js and searches for the clientid
  49. response = http_get(app_js_url)
  50. if response.ok:
  51. cids = cid_re.search(response.content.decode())
  52. if cids is not None and len(cids.groups()):
  53. return cids.groups()[0]
  54. logger.warning("Unable to fetch guest client_id from SoundCloud, check parser!")
  55. return ""
  56. def init(engine_settings=None):
  57. global guest_client_id
  58. # api-key
  59. guest_client_id = get_client_id()
  60. # do search-request
  61. def request(query, params):
  62. offset = (params['pageno'] - 1) * 20
  63. params['url'] = search_url.format(query=urlencode({'q': query}),
  64. offset=offset,
  65. client_id=guest_client_id)
  66. return params
  67. # get response from search-request
  68. def response(resp):
  69. results = []
  70. search_res = loads(resp.text)
  71. # parse results
  72. for result in search_res.get('collection', []):
  73. if result['kind'] in ('track', 'playlist'):
  74. title = result['title']
  75. content = result['description'] or ''
  76. publishedDate = parser.parse(result['last_modified'])
  77. uri = quote_plus(result['uri'])
  78. embedded = embedded_url.format(uri=uri)
  79. # append result
  80. results.append({'url': result['permalink_url'],
  81. 'title': title,
  82. 'publishedDate': publishedDate,
  83. 'embedded': embedded,
  84. 'content': content})
  85. # return results
  86. return results