brave.py 14 KB

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