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 urllib.parse import quote_plus, urlencode
  8. from lxml import html
  9. from dateutil import parser
  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. resp = http_get("https://soundcloud.com")
  39. if resp.ok:
  40. tree = html.fromstring(resp.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. resp = http_get(app_js_url)
  49. if resp.ok:
  50. cids = cid_re.search(resp.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): # pylint: disable=unused-argument
  56. global guest_client_id # pylint: disable=global-statement
  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. def response(resp):
  65. results = []
  66. search_res = loads(resp.text)
  67. # parse results
  68. for result in search_res.get('collection', []):
  69. if result['kind'] in ('track', 'playlist'):
  70. uri = quote_plus(result['uri'])
  71. res = {
  72. 'url': result['permalink_url'],
  73. 'title': result['title'],
  74. 'content': result['description'] or '',
  75. 'publishedDate': parser.parse(result['last_modified']),
  76. 'iframe_src': "https://w.soundcloud.com/player/?url=" + uri,
  77. }
  78. thumbnail = result['artwork_url'] or result['user']['avatar_url']
  79. if thumbnail:
  80. res['thumbnail'] = thumbnail
  81. results.append(res)
  82. return results