brave.py 14 KB

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