brave.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449
  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 dateutil import parser
  80. from lxml import html
  81. from searx import locales
  82. from searx.utils import (
  83. extract_text,
  84. eval_xpath,
  85. eval_xpath_list,
  86. eval_xpath_getindex,
  87. js_variable_to_python,
  88. )
  89. from searx.enginelib.traits import EngineTraits
  90. if TYPE_CHECKING:
  91. import logging
  92. logger: logging.Logger
  93. traits: EngineTraits
  94. about = {
  95. "website": 'https://search.brave.com/',
  96. "wikidata_id": 'Q22906900',
  97. "official_api_documentation": None,
  98. "use_official_api": False,
  99. "require_api_key": False,
  100. "results": 'HTML',
  101. }
  102. base_url = "https://search.brave.com/"
  103. categories = []
  104. brave_category = 'search'
  105. """Brave supports common web-search, video search, image and video search.
  106. - ``search``: Common WEB search
  107. - ``videos``: search for videos
  108. - ``images``: search for images
  109. - ``news``: search for news
  110. """
  111. brave_spellcheck = False
  112. """Brave supports some kind of spell checking. When activated, Brave tries to
  113. fix typos, e.g. it searches for ``food`` when the user queries for ``fooh``. In
  114. the UI of Brave the user gets warned about this, since we can not warn the user
  115. in SearXNG, the spellchecking is disabled by default.
  116. """
  117. send_accept_language_header = True
  118. paging = False
  119. """Brave only supports paging in :py:obj:`brave_category` ``search`` (UI
  120. category All)."""
  121. max_page = 10
  122. """Tested 9 pages maximum (``&offset=8``), to be save max is set to 10. Trying
  123. to do more won't return any result and you will most likely be flagged as a bot.
  124. """
  125. safesearch = True
  126. safesearch_map = {2: 'strict', 1: 'moderate', 0: 'off'} # cookie: safesearch=off
  127. time_range_support = False
  128. """Brave only supports time-range in :py:obj:`brave_category` ``search`` (UI
  129. category All)."""
  130. time_range_map = {
  131. 'day': 'pd',
  132. 'week': 'pw',
  133. 'month': 'pm',
  134. 'year': 'py',
  135. }
  136. def request(query, params):
  137. # Don't accept br encoding / see https://github.com/searxng/searxng/pull/1787
  138. params['headers']['Accept-Encoding'] = 'gzip, deflate'
  139. args = {
  140. 'q': query,
  141. }
  142. if brave_spellcheck:
  143. args['spellcheck'] = '1'
  144. if brave_category == 'search':
  145. if params.get('pageno', 1) - 1:
  146. args['offset'] = params.get('pageno', 1) - 1
  147. if time_range_map.get(params['time_range']):
  148. args['tf'] = time_range_map.get(params['time_range'])
  149. params["url"] = f"{base_url}{brave_category}?{urlencode(args)}"
  150. # set properties in the cookies
  151. params['cookies']['safesearch'] = safesearch_map.get(params['safesearch'], 'off')
  152. # the useLocation is IP based, we use cookie 'country' for the region
  153. params['cookies']['useLocation'] = '0'
  154. params['cookies']['summarizer'] = '0'
  155. engine_region = traits.get_region(params['searxng_locale'], 'all')
  156. params['cookies']['country'] = engine_region.split('-')[-1].lower() # type: ignore
  157. ui_lang = locales.get_engine_locale(params['searxng_locale'], traits.custom["ui_lang"], 'en-us')
  158. params['cookies']['ui_lang'] = ui_lang
  159. logger.debug("cookies %s", params['cookies'])
  160. def _extract_published_date(published_date_raw):
  161. if published_date_raw is None:
  162. return None
  163. try:
  164. return parser.parse(published_date_raw)
  165. except parser.ParserError:
  166. return None
  167. def response(resp):
  168. if brave_category == 'search':
  169. return _parse_search(resp)
  170. datastr = ""
  171. for line in resp.text.split("\n"):
  172. if "const data = " in line:
  173. datastr = line.replace("const data = ", "").strip()[:-1]
  174. break
  175. json_data = js_variable_to_python(datastr)
  176. json_resp = json_data[1]['data']['body']['response']
  177. if brave_category == 'news':
  178. return _parse_news(json_resp['news'])
  179. if brave_category == 'images':
  180. return _parse_images(json_resp)
  181. if brave_category == 'videos':
  182. return _parse_videos(json_resp)
  183. raise ValueError(f"Unsupported brave category: {brave_category}")
  184. def _parse_search(resp):
  185. result_list = []
  186. dom = html.fromstring(resp.text)
  187. answer_tag = eval_xpath_getindex(dom, '//div[@class="answer"]', 0, default=None)
  188. if answer_tag:
  189. url = eval_xpath_getindex(dom, '//div[@id="featured_snippet"]/a[@class="result-header"]/@href', 0, default=None)
  190. result_list.append({'answer': extract_text(answer_tag), 'url': url})
  191. # xpath_results = '//div[contains(@class, "snippet fdb") and @data-type="web"]'
  192. xpath_results = '//div[contains(@class, "snippet ")]'
  193. for result in eval_xpath_list(dom, xpath_results):
  194. url = eval_xpath_getindex(result, './/a[contains(@class, "h")]/@href', 0, default=None)
  195. title_tag = eval_xpath_getindex(result, './/div[contains(@class, "url")]', 0, default=None)
  196. if url is None or title_tag is None or not urlparse(url).netloc: # partial url likely means it's an ad
  197. continue
  198. content_tag = eval_xpath_getindex(result, './/div[contains(@class, "snippet-description")]', 0, default='')
  199. pub_date_raw = eval_xpath(result, 'substring-before(.//div[contains(@class, "snippet-description")], "-")')
  200. img_src = eval_xpath_getindex(result, './/img[contains(@class, "thumb")]/@src', 0, default='')
  201. item = {
  202. 'url': url,
  203. 'title': extract_text(title_tag),
  204. 'content': extract_text(content_tag),
  205. 'publishedDate': _extract_published_date(pub_date_raw),
  206. 'img_src': img_src,
  207. }
  208. video_tag = eval_xpath_getindex(
  209. result, './/div[contains(@class, "video-snippet") and @data-macro="video"]', 0, default=None
  210. )
  211. if video_tag is not None:
  212. # In my tests a video tag in the WEB search was most often not a
  213. # video, except the ones from youtube ..
  214. iframe_src = _get_iframe_src(url)
  215. if iframe_src:
  216. item['iframe_src'] = iframe_src
  217. item['template'] = 'videos.html'
  218. item['thumbnail'] = eval_xpath_getindex(video_tag, './/img/@src', 0, default='')
  219. pub_date_raw = extract_text(
  220. eval_xpath(video_tag, './/div[contains(@class, "snippet-attributes")]/div/text()')
  221. )
  222. item['publishedDate'] = _extract_published_date(pub_date_raw)
  223. else:
  224. item['img_src'] = eval_xpath_getindex(video_tag, './/img/@src', 0, default='')
  225. result_list.append(item)
  226. return result_list
  227. def _get_iframe_src(url):
  228. parsed_url = urlparse(url)
  229. if parsed_url.path == '/watch' and parsed_url.query:
  230. video_id = parse_qs(parsed_url.query).get('v', []) # type: ignore
  231. if video_id:
  232. return 'https://www.youtube-nocookie.com/embed/' + video_id[0] # type: ignore
  233. return None
  234. def _parse_news(json_resp):
  235. result_list = []
  236. for result in json_resp["results"]:
  237. item = {
  238. 'url': result['url'],
  239. 'title': result['title'],
  240. 'content': result['description'],
  241. 'publishedDate': _extract_published_date(result['age']),
  242. }
  243. if result['thumbnail'] is not None:
  244. item['img_src'] = result['thumbnail']['src']
  245. result_list.append(item)
  246. return result_list
  247. def _parse_images(json_resp):
  248. result_list = []
  249. for result in json_resp["results"]:
  250. item = {
  251. 'url': result['url'],
  252. 'title': result['title'],
  253. 'content': result['description'],
  254. 'template': 'images.html',
  255. 'img_format': result['properties']['format'],
  256. 'source': result['source'],
  257. 'img_src': result['properties']['url'],
  258. }
  259. result_list.append(item)
  260. return result_list
  261. def _parse_videos(json_resp):
  262. result_list = []
  263. for result in json_resp["results"]:
  264. url = result['url']
  265. item = {
  266. 'url': url,
  267. 'title': result['title'],
  268. 'content': result['description'],
  269. 'template': 'videos.html',
  270. 'length': result['video']['duration'],
  271. 'duration': result['video']['duration'],
  272. 'publishedDate': _extract_published_date(result['age']),
  273. }
  274. if result['thumbnail'] is not None:
  275. item['thumbnail'] = result['thumbnail']['src']
  276. iframe_src = _get_iframe_src(url)
  277. if iframe_src:
  278. item['iframe_src'] = iframe_src
  279. result_list.append(item)
  280. return result_list
  281. def fetch_traits(engine_traits: EngineTraits):
  282. """Fetch :ref:`languages <brave languages>` and :ref:`regions <brave
  283. regions>` from Brave."""
  284. # pylint: disable=import-outside-toplevel, too-many-branches
  285. import babel.languages
  286. from searx.locales import region_tag, language_tag
  287. from searx.network import get # see https://github.com/searxng/searxng/issues/762
  288. engine_traits.custom["ui_lang"] = {}
  289. headers = {
  290. 'Accept-Encoding': 'gzip, deflate',
  291. }
  292. lang_map = {'no': 'nb'} # norway
  293. # languages (UI)
  294. resp = get('https://search.brave.com/settings', headers=headers)
  295. if not resp.ok: # type: ignore
  296. print("ERROR: response from Brave is not OK.")
  297. dom = html.fromstring(resp.text) # type: ignore
  298. for option in dom.xpath('//div[@id="language-select"]//option'):
  299. ui_lang = option.get('value')
  300. try:
  301. if '-' in ui_lang:
  302. sxng_tag = region_tag(babel.Locale.parse(ui_lang, sep='-'))
  303. else:
  304. sxng_tag = language_tag(babel.Locale.parse(ui_lang))
  305. except babel.UnknownLocaleError:
  306. print("ERROR: can't determine babel locale of Brave's (UI) language %s" % ui_lang)
  307. continue
  308. conflict = engine_traits.custom["ui_lang"].get(sxng_tag)
  309. if conflict:
  310. if conflict != ui_lang:
  311. print("CONFLICT: babel %s --> %s, %s" % (sxng_tag, conflict, ui_lang))
  312. continue
  313. engine_traits.custom["ui_lang"][sxng_tag] = ui_lang
  314. # search regions of brave
  315. resp = get('https://cdn.search.brave.com/serp/v2/_app/immutable/chunks/parameters.734c106a.js', headers=headers)
  316. if not resp.ok: # type: ignore
  317. print("ERROR: response from Brave is not OK.")
  318. country_js = resp.text[resp.text.index("options:{all") + len('options:') :]
  319. country_js = country_js[: country_js.index("},k={default")]
  320. country_tags = js_variable_to_python(country_js)
  321. for k, v in country_tags.items():
  322. if k == 'all':
  323. engine_traits.all_locale = 'all'
  324. continue
  325. country_tag = v['value']
  326. # add official languages of the country ..
  327. for lang_tag in babel.languages.get_official_languages(country_tag, de_facto=True):
  328. lang_tag = lang_map.get(lang_tag, lang_tag)
  329. sxng_tag = region_tag(babel.Locale.parse('%s_%s' % (lang_tag, country_tag.upper())))
  330. # print("%-20s: %s <-- %s" % (v['label'], country_tag, sxng_tag))
  331. conflict = engine_traits.regions.get(sxng_tag)
  332. if conflict:
  333. if conflict != country_tag:
  334. print("CONFLICT: babel %s --> %s, %s" % (sxng_tag, conflict, country_tag))
  335. continue
  336. engine_traits.regions[sxng_tag] = country_tag