brave.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425
  1. # SPDX-License-Identifier: AGPL-3.0-or-later
  2. # lint: pylint
  3. """Brave supports the categories listed in :py:obj:`brave_category` (General,
  4. news, videos, images). The support of :py:obj:`paging` and :py:obj:`time range
  5. <time_range_support>` is limited (see remarks).
  6. Configured ``brave`` engines:
  7. .. code:: yaml
  8. - name: brave
  9. engine: brave
  10. ...
  11. brave_category: search
  12. time_range_support: true
  13. paging: true
  14. - name: brave.images
  15. engine: brave
  16. ...
  17. brave_category: images
  18. - name: brave.videos
  19. engine: brave
  20. ...
  21. brave_category: videos
  22. - name: brave.news
  23. engine: brave
  24. ...
  25. brave_category: news
  26. .. _brave regions:
  27. Brave regions
  28. =============
  29. Brave uses two-digit tags for the regions like ``ca`` while SearXNG deals with
  30. locales. To get a mapping, all *officiat de-facto* languages of the Brave
  31. region are mapped to regions in SearXNG (see :py:obj:`babel
  32. <babel.languages.get_official_languages>`):
  33. .. code:: python
  34. "regions": {
  35. ..
  36. "en-CA": "ca",
  37. "fr-CA": "ca",
  38. ..
  39. }
  40. .. note::
  41. The language (aka region) support of Brave's index is limited to very basic
  42. languages. The search results for languages like Chinese or Arabic are of
  43. low quality.
  44. .. _brave languages:
  45. Brave languages
  46. ===============
  47. Brave's language support is limited to the UI (menus, area local notations,
  48. etc). Brave's index only seems to support a locale, but it does not seem to
  49. support any languages in its index. The choice of available languages is very
  50. small (and its not clear to me where the difference in UI is when switching
  51. from en-us to en-ca or en-gb).
  52. In the :py:obj:`EngineTraits object <searx.enginelib.traits.EngineTraits>` the
  53. UI languages are stored in a custom field named ``ui_lang``:
  54. .. code:: python
  55. "custom": {
  56. "ui_lang": {
  57. "ca": "ca",
  58. "de-DE": "de-de",
  59. "en-CA": "en-ca",
  60. "en-GB": "en-gb",
  61. "en-US": "en-us",
  62. "es": "es",
  63. "fr-CA": "fr-ca",
  64. "fr-FR": "fr-fr",
  65. "ja-JP": "ja-jp",
  66. "pt-BR": "pt-br",
  67. "sq-AL": "sq-al"
  68. }
  69. },
  70. Implementations
  71. ===============
  72. """
  73. from typing import TYPE_CHECKING
  74. from urllib.parse import (
  75. urlencode,
  76. urlparse,
  77. parse_qs,
  78. )
  79. from lxml import html
  80. from searx import locales
  81. from searx.utils import (
  82. extract_text,
  83. eval_xpath_list,
  84. eval_xpath_getindex,
  85. js_variable_to_python,
  86. )
  87. from searx.enginelib.traits import EngineTraits
  88. if TYPE_CHECKING:
  89. import logging
  90. logger: logging.Logger
  91. traits: EngineTraits
  92. about = {
  93. "website": 'https://search.brave.com/',
  94. "wikidata_id": 'Q22906900',
  95. "official_api_documentation": None,
  96. "use_official_api": False,
  97. "require_api_key": False,
  98. "results": 'HTML',
  99. }
  100. base_url = "https://search.brave.com/"
  101. categories = []
  102. brave_category = 'search'
  103. """Brave supports common web-search, video search, image and video search.
  104. - ``search``: Common WEB search
  105. - ``videos``: search for videos
  106. - ``images``: search for images
  107. - ``news``: search for news
  108. """
  109. brave_spellcheck = False
  110. """Brave supports some kind of spell checking. When activated, Brave tries to
  111. fix typos, e.g. it searches for ``food`` when the user queries for ``fooh``. In
  112. the UI of Brave the user gets warned about this, since we can not warn the user
  113. in SearXNG, the spellchecking is disabled by default.
  114. """
  115. send_accept_language_header = True
  116. paging = False
  117. """Brave only supports paging in :py:obj:`brave_category` ``search`` (UI
  118. category All)."""
  119. safesearch = True
  120. safesearch_map = {2: 'strict', 1: 'moderate', 0: 'off'} # cookie: safesearch=off
  121. time_range_support = False
  122. """Brave only supports time-range in :py:obj:`brave_category` ``search`` (UI
  123. category All)."""
  124. time_range_map = {
  125. 'day': 'pd',
  126. 'week': 'pw',
  127. 'month': 'pm',
  128. 'year': 'py',
  129. }
  130. def request(query, params):
  131. # Don't accept br encoding / see https://github.com/searxng/searxng/pull/1787
  132. params['headers']['Accept-Encoding'] = 'gzip, deflate'
  133. args = {
  134. 'q': query,
  135. }
  136. if brave_spellcheck:
  137. args['spellcheck'] = '1'
  138. if brave_category == 'search':
  139. if params.get('pageno', 1) - 1:
  140. args['offset'] = params.get('pageno', 1) - 1
  141. if time_range_map.get(params['time_range']):
  142. args['tf'] = time_range_map.get(params['time_range'])
  143. params["url"] = f"{base_url}{brave_category}?{urlencode(args)}"
  144. # set properties in the cookies
  145. params['cookies']['safesearch'] = safesearch_map.get(params['safesearch'], 'off')
  146. # the useLocation is IP based, we use cookie 'country' for the region
  147. params['cookies']['useLocation'] = '0'
  148. params['cookies']['summarizer'] = '0'
  149. engine_region = traits.get_region(params['searxng_locale'], 'all')
  150. params['cookies']['country'] = engine_region.split('-')[-1].lower() # type: ignore
  151. ui_lang = locales.get_engine_locale(params['searxng_locale'], traits.custom["ui_lang"], 'en-us')
  152. params['cookies']['ui_lang'] = ui_lang
  153. logger.debug("cookies %s", params['cookies'])
  154. def response(resp):
  155. if brave_category == 'search':
  156. return _parse_search(resp)
  157. datastr = ""
  158. for line in resp.text.split("\n"):
  159. if "const data = " in line:
  160. datastr = line.replace("const data = ", "").strip()[:-1]
  161. break
  162. json_data = js_variable_to_python(datastr)
  163. json_resp = json_data[1]['data']['body']['response']
  164. if brave_category == 'news':
  165. return _parse_news(json_resp['news'])
  166. if brave_category == 'images':
  167. return _parse_images(json_resp)
  168. if brave_category == 'videos':
  169. return _parse_videos(json_resp)
  170. raise ValueError(f"Unsupported brave category: {brave_category}")
  171. def _parse_search(resp):
  172. result_list = []
  173. dom = html.fromstring(resp.text)
  174. answer_tag = eval_xpath_getindex(dom, '//div[@class="answer"]', 0, default=None)
  175. if answer_tag:
  176. url = eval_xpath_getindex(dom, '//div[@id="featured_snippet"]/a[@class="result-header"]/@href', 0, default=None)
  177. result_list.append({'answer': extract_text(answer_tag), 'url': url})
  178. # xpath_results = '//div[contains(@class, "snippet fdb") and @data-type="web"]'
  179. xpath_results = '//div[contains(@class, "snippet ")]'
  180. for result in eval_xpath_list(dom, xpath_results):
  181. url = eval_xpath_getindex(result, './/a[contains(@class, "h")]/@href', 0, default=None)
  182. title_tag = eval_xpath_getindex(result, './/div[contains(@class, "title")]', 0, default=None)
  183. if url is None or title_tag is None or not urlparse(url).netloc: # partial url likely means it's an ad
  184. continue
  185. content_tag = eval_xpath_getindex(result, './/div[@class="snippet-description"]', 0, default='')
  186. img_src = eval_xpath_getindex(result, './/img[contains(@class, "thumb")]/@src', 0, default='')
  187. item = {
  188. 'url': url,
  189. 'title': extract_text(title_tag),
  190. 'content': extract_text(content_tag),
  191. 'img_src': img_src,
  192. }
  193. video_tag = eval_xpath_getindex(
  194. result, './/div[contains(@class, "video-snippet") and @data-macro="video"]', 0, default=None
  195. )
  196. if video_tag is not None:
  197. # In my tests a video tag in the WEB search was most often not a
  198. # video, except the ones from youtube ..
  199. iframe_src = _get_iframe_src(url)
  200. if iframe_src:
  201. item['iframe_src'] = iframe_src
  202. item['template'] = 'videos.html'
  203. item['thumbnail'] = eval_xpath_getindex(video_tag, './/img/@src', 0, default='')
  204. else:
  205. item['img_src'] = eval_xpath_getindex(video_tag, './/img/@src', 0, default='')
  206. result_list.append(item)
  207. return result_list
  208. def _get_iframe_src(url):
  209. parsed_url = urlparse(url)
  210. if parsed_url.path == '/watch' and parsed_url.query:
  211. video_id = parse_qs(parsed_url.query).get('v', []) # type: ignore
  212. if video_id:
  213. return 'https://www.youtube-nocookie.com/embed/' + video_id[0] # type: ignore
  214. return None
  215. def _parse_news(json_resp):
  216. result_list = []
  217. for result in json_resp["results"]:
  218. item = {
  219. 'url': result['url'],
  220. 'title': result['title'],
  221. 'content': result['description'],
  222. }
  223. if result['thumbnail'] is not None:
  224. item['img_src'] = result['thumbnail']['src']
  225. result_list.append(item)
  226. return result_list
  227. def _parse_images(json_resp):
  228. result_list = []
  229. for result in json_resp["results"]:
  230. item = {
  231. 'url': result['url'],
  232. 'title': result['title'],
  233. 'content': result['description'],
  234. 'template': 'images.html',
  235. 'img_format': result['properties']['format'],
  236. 'source': result['source'],
  237. 'img_src': result['properties']['url'],
  238. }
  239. result_list.append(item)
  240. return result_list
  241. def _parse_videos(json_resp):
  242. result_list = []
  243. for result in json_resp["results"]:
  244. url = result['url']
  245. item = {
  246. 'url': url,
  247. 'title': result['title'],
  248. 'content': result['description'],
  249. 'template': 'videos.html',
  250. 'length': result['video']['duration'],
  251. 'duration': result['video']['duration'],
  252. }
  253. if result['thumbnail'] is not None:
  254. item['thumbnail'] = result['thumbnail']['src']
  255. iframe_src = _get_iframe_src(url)
  256. if iframe_src:
  257. item['iframe_src'] = iframe_src
  258. result_list.append(item)
  259. return result_list
  260. def fetch_traits(engine_traits: EngineTraits):
  261. """Fetch :ref:`languages <brave languages>` and :ref:`regions <brave
  262. regions>` from Brave."""
  263. # pylint: disable=import-outside-toplevel, too-many-branches
  264. import babel.languages
  265. from searx.locales import region_tag, language_tag
  266. from searx.network import get # see https://github.com/searxng/searxng/issues/762
  267. engine_traits.custom["ui_lang"] = {}
  268. headers = {
  269. 'Accept-Encoding': 'gzip, deflate',
  270. }
  271. lang_map = {'no': 'nb'} # norway
  272. # languages (UI)
  273. resp = get('https://search.brave.com/settings', headers=headers)
  274. if not resp.ok: # type: ignore
  275. print("ERROR: response from Brave is not OK.")
  276. dom = html.fromstring(resp.text) # type: ignore
  277. for option in dom.xpath('//div[@id="language-select"]//option'):
  278. ui_lang = option.get('value')
  279. try:
  280. if '-' in ui_lang:
  281. sxng_tag = region_tag(babel.Locale.parse(ui_lang, sep='-'))
  282. else:
  283. sxng_tag = language_tag(babel.Locale.parse(ui_lang))
  284. except babel.UnknownLocaleError:
  285. print("ERROR: can't determine babel locale of Brave's (UI) language %s" % ui_lang)
  286. continue
  287. conflict = engine_traits.custom["ui_lang"].get(sxng_tag)
  288. if conflict:
  289. if conflict != ui_lang:
  290. print("CONFLICT: babel %s --> %s, %s" % (sxng_tag, conflict, ui_lang))
  291. continue
  292. engine_traits.custom["ui_lang"][sxng_tag] = ui_lang
  293. # search regions of brave
  294. resp = get('https://cdn.search.brave.com/serp/v2/_app/immutable/chunks/parameters.734c106a.js', headers=headers)
  295. if not resp.ok: # type: ignore
  296. print("ERROR: response from Brave is not OK.")
  297. country_js = resp.text[resp.text.index("options:{all") + len('options:') :]
  298. country_js = country_js[: country_js.index("},k={default")]
  299. country_tags = js_variable_to_python(country_js)
  300. for k, v in country_tags.items():
  301. if k == 'all':
  302. engine_traits.all_locale = 'all'
  303. continue
  304. country_tag = v['value']
  305. # add official languages of the country ..
  306. for lang_tag in babel.languages.get_official_languages(country_tag, de_facto=True):
  307. lang_tag = lang_map.get(lang_tag, lang_tag)
  308. sxng_tag = region_tag(babel.Locale.parse('%s_%s' % (lang_tag, country_tag.upper())))
  309. # print("%-20s: %s <-- %s" % (v['label'], country_tag, sxng_tag))
  310. conflict = engine_traits.regions.get(sxng_tag)
  311. if conflict:
  312. if conflict != country_tag:
  313. print("CONFLICT: babel %s --> %s, %s" % (sxng_tag, conflict, country_tag))
  314. continue
  315. engine_traits.regions[sxng_tag] = country_tag