annas_archive.py 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203
  1. # SPDX-License-Identifier: AGPL-3.0-or-later
  2. """`Anna's Archive`_ is a free non-profit online shadow library metasearch
  3. engine providing access to a variety of book resources (also via IPFS), created
  4. by a team of anonymous archivists (AnnaArchivist_).
  5. .. _Anna's Archive: https://annas-archive.org/
  6. .. _AnnaArchivist: https://annas-software.org/AnnaArchivist/annas-archive
  7. Configuration
  8. =============
  9. The engine has the following additional settings:
  10. - :py:obj:`aa_content`
  11. - :py:obj:`aa_ext`
  12. - :py:obj:`aa_sort`
  13. With this options a SearXNG maintainer is able to configure **additional**
  14. engines for specific searches in Anna's Archive. For example a engine to search
  15. for *newest* articles and journals (PDF) / by shortcut ``!aaa <search-term>``.
  16. .. code:: yaml
  17. - name: annas articles
  18. engine: annas_archive
  19. shortcut: aaa
  20. aa_content: 'magazine'
  21. aa_ext: 'pdf'
  22. aa_sort: 'newest'
  23. Implementations
  24. ===============
  25. """
  26. from typing import List, Dict, Any, Optional
  27. from urllib.parse import urlencode
  28. from lxml import html
  29. from searx.utils import extract_text, eval_xpath, eval_xpath_getindex, eval_xpath_list
  30. from searx.enginelib.traits import EngineTraits
  31. from searx.data import ENGINE_TRAITS
  32. # about
  33. about: Dict[str, Any] = {
  34. "website": "https://annas-archive.org/",
  35. "wikidata_id": "Q115288326",
  36. "official_api_documentation": None,
  37. "use_official_api": False,
  38. "require_api_key": False,
  39. "results": "HTML",
  40. }
  41. # engine dependent config
  42. categories: List[str] = ["files"]
  43. paging: bool = True
  44. # search-url
  45. base_url: str = "https://annas-archive.org"
  46. aa_content: str = ""
  47. """Anan's search form field **Content** / possible values::
  48. book_fiction, book_unknown, book_nonfiction,
  49. book_comic, magazine, standards_document
  50. To not filter use an empty string (default).
  51. """
  52. aa_sort: str = ''
  53. """Sort Anna's results, possible values::
  54. newest, oldest, largest, smallest
  55. To sort by *most relevant* use an empty string (default)."""
  56. aa_ext: str = ''
  57. """Filter Anna's results by a file ending. Common filters for example are
  58. ``pdf`` and ``epub``.
  59. .. note::
  60. Anna's Archive is a beta release: Filter results by file extension does not
  61. really work on Anna's Archive.
  62. """
  63. def init(engine_settings=None): # pylint: disable=unused-argument
  64. """Check of engine's settings."""
  65. traits = EngineTraits(**ENGINE_TRAITS['annas archive'])
  66. if aa_content and aa_content not in traits.custom['content']:
  67. raise ValueError(f'invalid setting content: {aa_content}')
  68. if aa_sort and aa_sort not in traits.custom['sort']:
  69. raise ValueError(f'invalid setting sort: {aa_sort}')
  70. if aa_ext and aa_ext not in traits.custom['ext']:
  71. raise ValueError(f'invalid setting ext: {aa_ext}')
  72. def request(query, params: Dict[str, Any]) -> Dict[str, Any]:
  73. lang = traits.get_language(params["language"], traits.all_locale) # type: ignore
  74. args = {
  75. 'lang': lang,
  76. 'content': aa_content,
  77. 'ext': aa_ext,
  78. 'sort': aa_sort,
  79. 'q': query,
  80. 'page': params['pageno'],
  81. }
  82. # filter out None and empty values
  83. filtered_args = dict((k, v) for k, v in args.items() if v)
  84. params["url"] = f"{base_url}/search?{urlencode(filtered_args)}"
  85. return params
  86. def response(resp) -> List[Dict[str, Optional[str]]]:
  87. results: List[Dict[str, Optional[str]]] = []
  88. dom = html.fromstring(resp.text)
  89. for item in eval_xpath_list(dom, '//main//div[contains(@class, "h-[125]")]/a'):
  90. results.append(_get_result(item))
  91. # The rendering of the WEB page is very strange; except the first position
  92. # all other positions of Anna's result page are enclosed in SGML comments.
  93. # These comments are *uncommented* by some JS code, see query of class
  94. # '.js-scroll-hidden' in Anna's HTML template:
  95. # https://annas-software.org/AnnaArchivist/annas-archive/-/blob/main/allthethings/templates/macros/md5_list.html
  96. for item in eval_xpath_list(dom, '//main//div[contains(@class, "js-scroll-hidden")]'):
  97. item = html.fromstring(item.xpath('./comment()')[0].text)
  98. results.append(_get_result(item))
  99. return results
  100. def _get_result(item):
  101. return {
  102. 'template': 'paper.html',
  103. 'url': base_url + extract_text(eval_xpath_getindex(item, './@href', 0)),
  104. 'title': extract_text(eval_xpath(item, './/h3/text()[1]')),
  105. 'publisher': extract_text(eval_xpath(item, './/div[contains(@class, "text-sm")]')),
  106. 'authors': [extract_text(eval_xpath(item, './/div[contains(@class, "italic")]'))],
  107. 'content': extract_text(eval_xpath(item, './/div[contains(@class, "text-xs")]')),
  108. 'thumbnail': extract_text(eval_xpath_getindex(item, './/img/@src', 0, default=None), allow_none=True),
  109. }
  110. def fetch_traits(engine_traits: EngineTraits):
  111. """Fetch languages and other search arguments from Anna's search form."""
  112. # pylint: disable=import-outside-toplevel
  113. import babel
  114. from searx.network import get # see https://github.com/searxng/searxng/issues/762
  115. from searx.locales import language_tag
  116. engine_traits.all_locale = ''
  117. engine_traits.custom['content'] = []
  118. engine_traits.custom['ext'] = []
  119. engine_traits.custom['sort'] = []
  120. resp = get(base_url + '/search')
  121. if not resp.ok: # type: ignore
  122. raise RuntimeError("Response from Anna's search page is not OK.")
  123. dom = html.fromstring(resp.text) # type: ignore
  124. # supported language codes
  125. lang_map = {}
  126. for x in eval_xpath_list(dom, "//form//input[@name='lang']"):
  127. eng_lang = x.get("value")
  128. if eng_lang in ('', '_empty', 'nl-BE', 'und') or eng_lang.startswith('anti__'):
  129. continue
  130. try:
  131. locale = babel.Locale.parse(lang_map.get(eng_lang, eng_lang), sep='-')
  132. except babel.UnknownLocaleError:
  133. # silently ignore unknown languages
  134. # print("ERROR: %s -> %s is unknown by babel" % (x.get("data-name"), eng_lang))
  135. continue
  136. sxng_lang = language_tag(locale)
  137. conflict = engine_traits.languages.get(sxng_lang)
  138. if conflict:
  139. if conflict != eng_lang:
  140. print("CONFLICT: babel %s --> %s, %s" % (sxng_lang, conflict, eng_lang))
  141. continue
  142. engine_traits.languages[sxng_lang] = eng_lang
  143. for x in eval_xpath_list(dom, "//form//input[@name='content']"):
  144. if not x.get("value").startswith("anti__"):
  145. engine_traits.custom['content'].append(x.get("value"))
  146. for x in eval_xpath_list(dom, "//form//input[@name='ext']"):
  147. if not x.get("value").startswith("anti__"):
  148. engine_traits.custom['ext'].append(x.get("value"))
  149. for x in eval_xpath_list(dom, "//form//select[@name='sort']//option"):
  150. engine_traits.custom['sort'].append(x.get("value"))
  151. # for better diff; sort the persistence of these traits
  152. engine_traits.custom['content'].sort()
  153. engine_traits.custom['ext'].sort()
  154. engine_traits.custom['sort'].sort()