soundcloud.py 3.4 KB

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