brave.py 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. # SPDX-License-Identifier: AGPL-3.0-or-later
  2. """
  3. Brave (General, news, videos, images)
  4. """
  5. from urllib.parse import urlencode
  6. import chompjs
  7. import json
  8. about = {
  9. "website": 'https://search.brave.com/',
  10. "wikidata_id": 'Q22906900',
  11. "official_api_documentation": None,
  12. "use_official_api": False,
  13. "require_api_key": False,
  14. "results": 'HTML',
  15. }
  16. base_url = "https://search.brave.com/"
  17. paging = False
  18. categories = ['images', 'videos', 'news'] # images, videos, news
  19. def request(query, params):
  20. args = {
  21. 'q': query,
  22. 'spellcheck': 1,
  23. }
  24. params["url"] = f"{base_url}{categories[0]}?{urlencode(args)}"
  25. def get_video_results(json_data):
  26. results = []
  27. for result in json_data:
  28. results.append(
  29. {
  30. 'template': 'videos.html',
  31. 'url': result['url'],
  32. 'thumbnail_src': result['thumbnail']['src'],
  33. 'img_src': result['properties']['url'],
  34. 'content': result['description'],
  35. 'title': result['title'],
  36. 'source': result['source'],
  37. 'duration': result['video']['duration'],
  38. }
  39. )
  40. return results
  41. def response(resp):
  42. results = []
  43. datastr = ""
  44. for line in resp.text.split("\n"):
  45. if "const data = " in line:
  46. datastr = line.replace("const data = ", "").strip()[:-1]
  47. break
  48. json_data = chompjs.parse_js_object(datastr)
  49. json_results = json_data[1]["data"]["body"]["response"]["results"]
  50. with open("outfile.json", "w") as f:
  51. json.dump(json_data, f)
  52. for result in json_results:
  53. item = {
  54. 'url': result['url'],
  55. 'title': result['title'],
  56. 'content': result['description'],
  57. }
  58. if result['thumbnail'] != "null":
  59. item['thumbnail'] = result['thumbnail']['src']
  60. match categories[0]:
  61. case 'images':
  62. item['template'] = 'images.html'
  63. item['img_format'] = result['properties']['format']
  64. item['source'] = result['source']
  65. item['img_src'] = result['properties']['url']
  66. case 'videos':
  67. item['template'] = 'videos.html'
  68. item['length'] = result['video']['duration']
  69. results.append(item)
  70. return results