archlinux.py 4.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154
  1. # SPDX-License-Identifier: AGPL-3.0-or-later
  2. """
  3. Arch Linux Wiki
  4. ~~~~~~~~~~~~~~~
  5. This implementation does not use a official API: Mediawiki provides API, but
  6. Arch Wiki blocks access to it.
  7. """
  8. from typing import TYPE_CHECKING
  9. from urllib.parse import urlencode, urljoin, urlparse
  10. import lxml
  11. import babel
  12. from searx.utils import extract_text, eval_xpath_list, eval_xpath_getindex
  13. from searx.enginelib.traits import EngineTraits
  14. from searx.locales import language_tag
  15. if TYPE_CHECKING:
  16. import logging
  17. logger: logging.Logger
  18. traits: EngineTraits
  19. about = {
  20. "website": 'https://wiki.archlinux.org/',
  21. "wikidata_id": 'Q101445877',
  22. "official_api_documentation": None,
  23. "use_official_api": False,
  24. "require_api_key": False,
  25. "results": 'HTML',
  26. }
  27. # engine dependent config
  28. categories = ['it', 'software wikis']
  29. paging = True
  30. main_wiki = 'wiki.archlinux.org'
  31. def request(query, params):
  32. sxng_lang = params['searxng_locale'].split('-')[0]
  33. netloc: str = traits.custom['wiki_netloc'].get(sxng_lang, main_wiki) # type: ignore
  34. title: str = traits.custom['title'].get(sxng_lang, 'Special:Search') # type: ignore
  35. base_url = 'https://' + netloc + '/index.php?'
  36. offset = (params['pageno'] - 1) * 20
  37. if netloc == main_wiki:
  38. eng_lang: str = traits.get_language(sxng_lang, 'English') # type: ignore
  39. query += ' (' + eng_lang + ')'
  40. # wiki.archlinux.org is protected by anubis
  41. # - https://github.com/searxng/searxng/issues/4646#issuecomment-2817848019
  42. params['headers']['User-Agent'] = "SearXNG"
  43. elif netloc == 'wiki.archlinuxcn.org':
  44. base_url = 'https://' + netloc + '/wzh/index.php?'
  45. args = {
  46. 'search': query,
  47. 'title': title,
  48. 'limit': 20,
  49. 'offset': offset,
  50. 'profile': 'default',
  51. }
  52. params['url'] = base_url + urlencode(args)
  53. return params
  54. def response(resp):
  55. results = []
  56. dom = lxml.html.fromstring(resp.text) # type: ignore
  57. # get the base URL for the language in which request was made
  58. sxng_lang = resp.search_params['searxng_locale'].split('-')[0]
  59. netloc: str = traits.custom['wiki_netloc'].get(sxng_lang, main_wiki) # type: ignore
  60. base_url = 'https://' + netloc + '/index.php?'
  61. for result in eval_xpath_list(dom, '//ul[@class="mw-search-results"]/li'):
  62. link = eval_xpath_getindex(result, './/div[@class="mw-search-result-heading"]/a', 0)
  63. content = extract_text(result.xpath('.//div[@class="searchresult"]'))
  64. results.append(
  65. {
  66. 'url': urljoin(base_url, link.get('href')), # type: ignore
  67. 'title': extract_text(link),
  68. 'content': content,
  69. }
  70. )
  71. return results
  72. def fetch_traits(engine_traits: EngineTraits):
  73. """Fetch languages from Archlinux-Wiki. The location of the Wiki address of a
  74. language is mapped in a :py:obj:`custom field
  75. <searx.enginelib.traits.EngineTraits.custom>` (``wiki_netloc``). Depending
  76. on the location, the ``title`` argument in the request is translated.
  77. .. code:: python
  78. "custom": {
  79. "wiki_netloc": {
  80. "de": "wiki.archlinux.de",
  81. # ...
  82. "zh": "wiki.archlinuxcn.org"
  83. }
  84. "title": {
  85. "de": "Spezial:Suche",
  86. # ...
  87. "zh": "Special:\u641c\u7d22"
  88. },
  89. },
  90. """
  91. # pylint: disable=import-outside-toplevel
  92. from searx.network import get # see https://github.com/searxng/searxng/issues/762
  93. engine_traits.custom['wiki_netloc'] = {}
  94. engine_traits.custom['title'] = {}
  95. title_map = {
  96. 'de': 'Spezial:Suche',
  97. 'fa': 'ویژه:جستجو',
  98. 'ja': '特別:検索',
  99. 'zh': 'Special:搜索',
  100. }
  101. resp = get('https://wiki.archlinux.org/')
  102. if not resp.ok: # type: ignore
  103. print("ERROR: response from wiki.archlinux.org is not OK.")
  104. dom = lxml.html.fromstring(resp.text) # type: ignore
  105. for a in eval_xpath_list(dom, "//a[@class='interlanguage-link-target']"):
  106. sxng_tag = language_tag(babel.Locale.parse(a.get('lang'), sep='-'))
  107. # zh_Hans --> zh
  108. sxng_tag = sxng_tag.split('_')[0]
  109. netloc = urlparse(a.get('href')).netloc
  110. if netloc != 'wiki.archlinux.org':
  111. title = title_map.get(sxng_tag)
  112. if not title:
  113. print("ERROR: title tag from %s (%s) is unknown" % (netloc, sxng_tag))
  114. continue
  115. engine_traits.custom['wiki_netloc'][sxng_tag] = netloc
  116. engine_traits.custom['title'][sxng_tag] = title # type: ignore
  117. eng_tag = extract_text(eval_xpath_list(a, ".//span"))
  118. engine_traits.languages[sxng_tag] = eng_tag # type: ignore
  119. engine_traits.languages['en'] = 'English'