brave.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523
  1. # SPDX-License-Identifier: AGPL-3.0-or-later
  2. """Brave supports the categories listed in :py:obj:`brave_category` (General,
  3. news, videos, images). The support of :py:obj:`paging` and :py:obj:`time range
  4. <time_range_support>` is limited (see remarks).
  5. Configured ``brave`` engines:
  6. .. code:: yaml
  7. - name: brave
  8. engine: brave
  9. ...
  10. brave_category: search
  11. time_range_support: true
  12. paging: true
  13. - name: brave.images
  14. engine: brave
  15. ...
  16. brave_category: images
  17. - name: brave.videos
  18. engine: brave
  19. ...
  20. brave_category: videos
  21. - name: brave.news
  22. engine: brave
  23. ...
  24. brave_category: news
  25. - name: brave.goggles
  26. time_range_support: true
  27. paging: true
  28. ...
  29. brave_category: goggles
  30. .. _brave regions:
  31. Brave regions
  32. =============
  33. Brave uses two-digit tags for the regions like ``ca`` while SearXNG deals with
  34. locales. To get a mapping, all *officiat de-facto* languages of the Brave
  35. region are mapped to regions in SearXNG (see :py:obj:`babel
  36. <babel.languages.get_official_languages>`):
  37. .. code:: python
  38. "regions": {
  39. ..
  40. "en-CA": "ca",
  41. "fr-CA": "ca",
  42. ..
  43. }
  44. .. note::
  45. The language (aka region) support of Brave's index is limited to very basic
  46. languages. The search results for languages like Chinese or Arabic are of
  47. low quality.
  48. .. _brave googles:
  49. Brave Goggles
  50. =============
  51. .. _list of Goggles: https://search.brave.com/goggles/discover
  52. .. _Goggles Whitepaper: https://brave.com/static-assets/files/goggles.pdf
  53. .. _Goggles Quickstart: https://github.com/brave/goggles-quickstart
  54. Goggles allow you to choose, alter, or extend the ranking of Brave Search
  55. results (`Goggles Whitepaper`_). Goggles are openly developed by the community
  56. of Brave Search users.
  57. Select from the `list of Goggles`_ people have published, or create your own
  58. (`Goggles Quickstart`_).
  59. .. _brave languages:
  60. Brave languages
  61. ===============
  62. Brave's language support is limited to the UI (menus, area local notations,
  63. etc). Brave's index only seems to support a locale, but it does not seem to
  64. support any languages in its index. The choice of available languages is very
  65. small (and its not clear to me where the difference in UI is when switching
  66. from en-us to en-ca or en-gb).
  67. In the :py:obj:`EngineTraits object <searx.enginelib.traits.EngineTraits>` the
  68. UI languages are stored in a custom field named ``ui_lang``:
  69. .. code:: python
  70. "custom": {
  71. "ui_lang": {
  72. "ca": "ca",
  73. "de-DE": "de-de",
  74. "en-CA": "en-ca",
  75. "en-GB": "en-gb",
  76. "en-US": "en-us",
  77. "es": "es",
  78. "fr-CA": "fr-ca",
  79. "fr-FR": "fr-fr",
  80. "ja-JP": "ja-jp",
  81. "pt-BR": "pt-br",
  82. "sq-AL": "sq-al"
  83. }
  84. },
  85. Implementations
  86. ===============
  87. """
  88. from typing import Any, TYPE_CHECKING
  89. from urllib.parse import (
  90. urlencode,
  91. urlparse,
  92. )
  93. from dateutil import parser
  94. from lxml import html
  95. from searx import locales
  96. from searx.utils import (
  97. extract_text,
  98. eval_xpath,
  99. eval_xpath_list,
  100. eval_xpath_getindex,
  101. js_variable_to_python,
  102. get_embeded_stream_url,
  103. )
  104. from searx.enginelib.traits import EngineTraits
  105. from searx.result_types import EngineResults
  106. if TYPE_CHECKING:
  107. import logging
  108. logger: logging.Logger
  109. traits: EngineTraits
  110. about = {
  111. "website": 'https://search.brave.com/',
  112. "wikidata_id": 'Q22906900',
  113. "official_api_documentation": None,
  114. "use_official_api": False,
  115. "require_api_key": False,
  116. "results": 'HTML',
  117. }
  118. base_url = "https://search.brave.com/"
  119. categories = []
  120. brave_category = 'search'
  121. Goggles = Any
  122. """Brave supports common web-search, videos, images, news, and goggles search.
  123. - ``search``: Common WEB search
  124. - ``videos``: search for videos
  125. - ``images``: search for images
  126. - ``news``: search for news
  127. - ``goggles``: Common WEB search with custom rules
  128. """
  129. brave_spellcheck = False
  130. """Brave supports some kind of spell checking. When activated, Brave tries to
  131. fix typos, e.g. it searches for ``food`` when the user queries for ``fooh``. In
  132. the UI of Brave the user gets warned about this, since we can not warn the user
  133. in SearXNG, the spellchecking is disabled by default.
  134. """
  135. send_accept_language_header = True
  136. paging = False
  137. """Brave only supports paging in :py:obj:`brave_category` ``search`` (UI
  138. category All) and in the goggles category."""
  139. max_page = 10
  140. """Tested 9 pages maximum (``&offset=8``), to be save max is set to 10. Trying
  141. to do more won't return any result and you will most likely be flagged as a bot.
  142. """
  143. safesearch = True
  144. safesearch_map = {2: 'strict', 1: 'moderate', 0: 'off'} # cookie: safesearch=off
  145. time_range_support = False
  146. """Brave only supports time-range in :py:obj:`brave_category` ``search`` (UI
  147. category All) and in the goggles category."""
  148. time_range_map = {
  149. 'day': 'pd',
  150. 'week': 'pw',
  151. 'month': 'pm',
  152. 'year': 'py',
  153. }
  154. def request(query, params):
  155. # Don't accept br encoding / see https://github.com/searxng/searxng/pull/1787
  156. params['headers']['Accept-Encoding'] = 'gzip, deflate'
  157. args = {
  158. 'q': query,
  159. 'source': 'web',
  160. }
  161. if brave_spellcheck:
  162. args['spellcheck'] = '1'
  163. if brave_category in ('search', 'goggles'):
  164. if params.get('pageno', 1) - 1:
  165. args['offset'] = params.get('pageno', 1) - 1
  166. if time_range_map.get(params['time_range']):
  167. args['tf'] = time_range_map.get(params['time_range'])
  168. if brave_category == 'goggles':
  169. args['goggles_id'] = Goggles
  170. params["url"] = f"{base_url}{brave_category}?{urlencode(args)}"
  171. # set properties in the cookies
  172. params['cookies']['safesearch'] = safesearch_map.get(params['safesearch'], 'off')
  173. # the useLocation is IP based, we use cookie 'country' for the region
  174. params['cookies']['useLocation'] = '0'
  175. params['cookies']['summarizer'] = '0'
  176. engine_region = traits.get_region(params['searxng_locale'], 'all')
  177. params['cookies']['country'] = engine_region.split('-')[-1].lower() # type: ignore
  178. ui_lang = locales.get_engine_locale(params['searxng_locale'], traits.custom["ui_lang"], 'en-us')
  179. params['cookies']['ui_lang'] = ui_lang
  180. logger.debug("cookies %s", params['cookies'])
  181. params['headers']['Sec-Fetch-Dest'] = "document"
  182. params['headers']['Sec-Fetch-Mode'] = "navigate"
  183. params['headers']['Sec-Fetch-Site'] = "same-origin"
  184. params['headers']['Sec-Fetch-User'] = "?1"
  185. def _extract_published_date(published_date_raw):
  186. if published_date_raw is None:
  187. return None
  188. try:
  189. return parser.parse(published_date_raw)
  190. except parser.ParserError:
  191. return None
  192. def parse_data_string(resp):
  193. # kit.start(app, element, {
  194. # node_ids: [0, 19],
  195. # data: [{"type":"data","data" .... ["q","goggles_id"],"route":1,"url":1}}]
  196. # ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  197. kit_start = resp.text.index("kit.start(app,")
  198. start = resp.text[kit_start:].index('data: [{"type":"data"')
  199. start = kit_start + start + len('data: ')
  200. lev = 0
  201. end = start
  202. inner = False
  203. for c in resp.text[start:]:
  204. if inner and lev == 0:
  205. break
  206. end += 1
  207. if c == "[":
  208. lev += 1
  209. inner = True
  210. continue
  211. if c == "]":
  212. lev -= 1
  213. json_data = js_variable_to_python(resp.text[start:end])
  214. return json_data
  215. def response(resp) -> EngineResults:
  216. if brave_category in ('search', 'goggles'):
  217. return _parse_search(resp)
  218. if brave_category in ('news'):
  219. return _parse_news(resp)
  220. json_data = parse_data_string(resp)
  221. # json_data is a list and at the second position (0,1) in this list we find the "response" data we need ..
  222. json_resp = json_data[1]['data']['body']['response']
  223. if brave_category == 'images':
  224. return _parse_images(json_resp)
  225. if brave_category == 'videos':
  226. return _parse_videos(json_resp)
  227. raise ValueError(f"Unsupported brave category: {brave_category}")
  228. def _parse_search(resp) -> EngineResults:
  229. result_list = EngineResults()
  230. dom = html.fromstring(resp.text)
  231. # I doubt that Brave is still providing the "answer" class / I haven't seen
  232. # answers in brave for a long time.
  233. answer_tag = eval_xpath_getindex(dom, '//div[@class="answer"]', 0, default=None)
  234. if answer_tag:
  235. url = eval_xpath_getindex(dom, '//div[@id="featured_snippet"]/a[@class="result-header"]/@href', 0, default=None)
  236. answer = extract_text(answer_tag)
  237. if answer is not None:
  238. result_list.add(result_list.types.Answer(answer=answer, url=url))
  239. # xpath_results = '//div[contains(@class, "snippet fdb") and @data-type="web"]'
  240. xpath_results = '//div[contains(@class, "snippet ")]'
  241. for result in eval_xpath_list(dom, xpath_results):
  242. url = eval_xpath_getindex(result, './/a[contains(@class, "h")]/@href', 0, default=None)
  243. title_tag = eval_xpath_getindex(
  244. result, './/a[contains(@class, "h")]//div[contains(@class, "title")]', 0, default=None
  245. )
  246. if url is None or title_tag is None or not urlparse(url).netloc: # partial url likely means it's an ad
  247. continue
  248. content: str = extract_text(
  249. eval_xpath_getindex(result, './/div[contains(@class, "snippet-description")]', 0, default='')
  250. ) # type: ignore
  251. pub_date_raw = eval_xpath(result, 'substring-before(.//div[contains(@class, "snippet-description")], "-")')
  252. pub_date = _extract_published_date(pub_date_raw)
  253. if pub_date and content.startswith(pub_date_raw):
  254. content = content.lstrip(pub_date_raw).strip("- \n\t")
  255. thumbnail = eval_xpath_getindex(result, './/img[contains(@class, "thumb")]/@src', 0, default='')
  256. item = {
  257. 'url': url,
  258. 'title': extract_text(title_tag),
  259. 'content': content,
  260. 'publishedDate': pub_date,
  261. 'thumbnail': thumbnail,
  262. }
  263. video_tag = eval_xpath_getindex(
  264. result, './/div[contains(@class, "video-snippet") and @data-macro="video"]', 0, default=None
  265. )
  266. if video_tag is not None:
  267. # In my tests a video tag in the WEB search was most often not a
  268. # video, except the ones from youtube ..
  269. iframe_src = get_embeded_stream_url(url)
  270. if iframe_src:
  271. item['iframe_src'] = iframe_src
  272. item['template'] = 'videos.html'
  273. item['thumbnail'] = eval_xpath_getindex(video_tag, './/img/@src', 0, default='')
  274. pub_date_raw = extract_text(
  275. eval_xpath(video_tag, './/div[contains(@class, "snippet-attributes")]/div/text()')
  276. )
  277. item['publishedDate'] = _extract_published_date(pub_date_raw)
  278. else:
  279. item['thumbnail'] = eval_xpath_getindex(video_tag, './/img/@src', 0, default='')
  280. result_list.append(item)
  281. return result_list
  282. def _parse_news(resp) -> EngineResults:
  283. result_list = EngineResults()
  284. dom = html.fromstring(resp.text)
  285. for result in eval_xpath_list(dom, '//div[contains(@class, "results")]//div[@data-type="news"]'):
  286. # import pdb
  287. # pdb.set_trace()
  288. url = eval_xpath_getindex(result, './/a[contains(@class, "result-header")]/@href', 0, default=None)
  289. if url is None:
  290. continue
  291. title = extract_text(eval_xpath_list(result, './/span[contains(@class, "snippet-title")]'))
  292. content = extract_text(eval_xpath_list(result, './/p[contains(@class, "desc")]'))
  293. thumbnail = eval_xpath_getindex(result, './/div[contains(@class, "image-wrapper")]//img/@src', 0, default='')
  294. item = {
  295. "url": url,
  296. "title": title,
  297. "content": content,
  298. "thumbnail": thumbnail,
  299. }
  300. result_list.append(item)
  301. return result_list
  302. def _parse_images(json_resp) -> EngineResults:
  303. result_list = EngineResults()
  304. for result in json_resp["results"]:
  305. item = {
  306. 'url': result['url'],
  307. 'title': result['title'],
  308. 'content': result['description'],
  309. 'template': 'images.html',
  310. 'resolution': result['properties']['format'],
  311. 'source': result['source'],
  312. 'img_src': result['properties']['url'],
  313. 'thumbnail_src': result['thumbnail']['src'],
  314. }
  315. result_list.append(item)
  316. return result_list
  317. def _parse_videos(json_resp) -> EngineResults:
  318. result_list = EngineResults()
  319. for result in json_resp["results"]:
  320. url = result['url']
  321. item = {
  322. 'url': url,
  323. 'title': result['title'],
  324. 'content': result['description'],
  325. 'template': 'videos.html',
  326. 'length': result['video']['duration'],
  327. 'duration': result['video']['duration'],
  328. 'publishedDate': _extract_published_date(result['age']),
  329. }
  330. if result['thumbnail'] is not None:
  331. item['thumbnail'] = result['thumbnail']['src']
  332. iframe_src = get_embeded_stream_url(url)
  333. if iframe_src:
  334. item['iframe_src'] = iframe_src
  335. result_list.append(item)
  336. return result_list
  337. def fetch_traits(engine_traits: EngineTraits):
  338. """Fetch :ref:`languages <brave languages>` and :ref:`regions <brave
  339. regions>` from Brave."""
  340. # pylint: disable=import-outside-toplevel, too-many-branches
  341. import babel.languages
  342. from searx.locales import region_tag, language_tag
  343. from searx.network import get # see https://github.com/searxng/searxng/issues/762
  344. engine_traits.custom["ui_lang"] = {}
  345. headers = {
  346. 'Accept-Encoding': 'gzip, deflate',
  347. }
  348. lang_map = {'no': 'nb'} # norway
  349. # languages (UI)
  350. resp = get('https://search.brave.com/settings', headers=headers)
  351. if not resp.ok: # type: ignore
  352. print("ERROR: response from Brave is not OK.")
  353. dom = html.fromstring(resp.text) # type: ignore
  354. for option in dom.xpath('//section//option[@value="en-us"]/../option'):
  355. ui_lang = option.get('value')
  356. try:
  357. l = babel.Locale.parse(ui_lang, sep='-')
  358. if l.territory:
  359. sxng_tag = region_tag(babel.Locale.parse(ui_lang, sep='-'))
  360. else:
  361. sxng_tag = language_tag(babel.Locale.parse(ui_lang, sep='-'))
  362. except babel.UnknownLocaleError:
  363. print("ERROR: can't determine babel locale of Brave's (UI) language %s" % ui_lang)
  364. continue
  365. conflict = engine_traits.custom["ui_lang"].get(sxng_tag)
  366. if conflict:
  367. if conflict != ui_lang:
  368. print("CONFLICT: babel %s --> %s, %s" % (sxng_tag, conflict, ui_lang))
  369. continue
  370. engine_traits.custom["ui_lang"][sxng_tag] = ui_lang
  371. # search regions of brave
  372. resp = get('https://cdn.search.brave.com/serp/v2/_app/immutable/chunks/parameters.734c106a.js', headers=headers)
  373. if not resp.ok: # type: ignore
  374. print("ERROR: response from Brave is not OK.")
  375. country_js = resp.text[resp.text.index("options:{all") + len('options:') :] # type: ignore
  376. country_js = country_js[: country_js.index("},k={default")]
  377. country_tags = js_variable_to_python(country_js)
  378. for k, v in country_tags.items():
  379. if k == 'all':
  380. engine_traits.all_locale = 'all'
  381. continue
  382. country_tag = v['value']
  383. # add official languages of the country ..
  384. for lang_tag in babel.languages.get_official_languages(country_tag, de_facto=True):
  385. lang_tag = lang_map.get(lang_tag, lang_tag)
  386. sxng_tag = region_tag(babel.Locale.parse('%s_%s' % (lang_tag, country_tag.upper())))
  387. # print("%-20s: %s <-- %s" % (v['label'], country_tag, sxng_tag))
  388. conflict = engine_traits.regions.get(sxng_tag)
  389. if conflict:
  390. if conflict != country_tag:
  391. print("CONFLICT: babel %s --> %s, %s" % (sxng_tag, conflict, country_tag))
  392. continue
  393. engine_traits.regions[sxng_tag] = country_tag