1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
|
# SPDX-License-Identifier: AGPL-3.0-or-later
"""`Anna's Archive`_ is a free non-profit online shadow library metasearch
engine providing access to a variety of book resources (also via IPFS), created
by a team of anonymous archivists (AnnaArchivist_).
.. _Anna's Archive: https://annas-archive.gl/
.. _AnnaArchivist: https://software.annas-archive.gl/AnnaArchivist/annas-archive
Configuration
=============
The engine has the following additional settings:
- :py:obj:`aa_content`
- :py:obj:`aa_ext`
- :py:obj:`aa_sort`
With this options a SearXNG maintainer is able to configure **additional**
engines for specific searches in Anna's Archive. For example a engine to search
for *newest* articles and journals (PDF) / by shortcut ``!aaa <search-term>``.
.. code:: yaml
- name: annas articles
engine: annas_archive
categories = ["general", "articles"]
shortcut: aaa
aa_content: "magazine"
aa_ext: "pdf"
aa_sort: "newest"
Implementations
===============
"""
import random
import typing as t
from urllib.parse import urlencode
from lxml import html
from lxml.etree import ElementBase
from searx.data import ENGINE_TRAITS
from searx.enginelib.traits import EngineTraits
from searx.result_types import EngineResults
from searx.utils import eval_xpath, eval_xpath_getindex, eval_xpath_list, extract_text
if t.TYPE_CHECKING:
from searx.extended_types import SXNG_Response
from searx.search.processors import OnlineParams
# about
about: dict[str, t.Any] = {
"website": "https://annas-archive.gl/",
"wikidata_id": "Q115288326",
"official_api_documentation": None,
"use_official_api": False,
"require_api_key": False,
"results": "HTML",
}
# engine dependent config
categories = ["files", "books"]
paging: bool = True
language_support = True
# search-url
base_url: list[str] | str = []
"""List of Anna's archive domains or a single domain (as string)."""
aa_content: str = ""
"""Anan's search form field **Content** / possible values::
book_fiction, book_unknown, book_nonfiction,
book_comic, magazine, standards_document
To not filter use an empty string (default).
"""
aa_sort: str = ""
"""Sort Anna's results, possible values::
newest, oldest, largest, smallest, newest_added, oldest_added, random
To sort by *most relevant* use an empty string (default)."""
aa_ext: str = ""
"""Filter Anna's results by a file ending. Common filters for example are
``pdf`` and ``epub``.
.. note::
Anna's Archive is a beta release: Filter results by file extension does not
really work on Anna's Archive.
"""
def setup(_engine_settings: dict[str, t.Any]) -> bool:
"""Check of engine's settings."""
traits: EngineTraits = EngineTraits(**ENGINE_TRAITS["annas archive"])
if not base_url:
raise ValueError("missing required config `base_url`")
if aa_content and aa_content not in traits.custom["content"]:
raise ValueError(f"invalid setting content: {aa_content}")
if aa_sort and aa_sort not in traits.custom["sort"]:
raise ValueError(f"invalid setting sort: {aa_sort}")
if aa_ext and aa_ext not in traits.custom["ext"]:
raise ValueError(f"invalid setting ext: {aa_ext}")
return True
def _get_base_url_choice() -> str:
if isinstance(base_url, list):
return random.choice(base_url)
return base_url
def request(query: str, params: "OnlineParams") -> None:
lang = traits.get_language(params["searxng_locale"], traits.all_locale)
args = {
"lang": lang,
"content": aa_content,
"ext": aa_ext,
"sort": aa_sort,
"q": query,
"page": params["pageno"],
}
# filter out empty values
filtered_args = dict((k, v) for k, v in args.items() if v)
params["base_url"] = _get_base_url_choice()
params["url"] = f"{params['base_url']}/search?{urlencode(filtered_args)}"
def response(resp: "SXNG_Response") -> EngineResults:
res = EngineResults()
dom = html.fromstring(resp.text)
# Each result is a div with class "flex" inside "js-aarecord-list-outer"
# container. The "flex" filter excludes non-result div such as section
# separators.
for item in eval_xpath_list(
dom,
"//main//div[contains(@class, 'js-aarecord-list-outer')]/div[contains(@class, 'flex')]",
):
result = _get_result(item, resp.search_params["base_url"])
if result is not None:
res.add(res.types.Paper(**result))
return res
def _get_result(item: ElementBase, base_url_choice: str) -> dict[str, t.Any] | None:
# the first direct child "a" contains the link to the result page
href_els = item.xpath("./a/@href")
if not href_els:
return None
# the link with class "js-vim-focus" is always the title link
title_text = extract_text(
xpath_results=eval_xpath(item, ".//a[contains(@class, 'js-vim-focus')]"),
allow_none=True,
)
if not title_text:
return None
result: dict[str, t.Any] = {
"url": base_url_choice + href_els[0],
"title": title_text,
}
result["content"] = extract_text(
xpath_results=eval_xpath_getindex(
element=item,
# the content is in a div with class "relative" and "line-clamp"
xpath_spec=".//div[@class='relative']/div[contains(@class, 'line-clamp')]",
index=0,
default=None,
),
allow_none=True,
)
result["thumbnail"] = eval_xpath_getindex(
element=item,
# the thumbnail is the src of the first img in the result item
xpath_spec=".//img/@src",
index=0,
default=None,
)
result["authors"] = [
extract_text(
xpath_results=eval_xpath_getindex(
element=item,
# identified by the "user-edit" icon
xpath_spec=".//a[.//span[contains(@class, 'icon-[mdi--user-edit]')]]",
index=0,
default=None,
),
allow_none=True,
)
]
result["publisher"] = extract_text(
xpath_results=eval_xpath_getindex(
element=item,
# identified by the "company" icon
xpath_spec=".//a[.//span[contains(@class, 'icon-[mdi--company]')]]",
index=0,
default=None,
),
allow_none=True,
)
tags_text = extract_text(
xpath_results=eval_xpath_getindex(
element=item,
# the only one with "font-semibold" class
xpath_spec=".//div[contains(@class, 'font-semibold')]",
index=0,
default=None,
),
allow_none=True,
)
if tags_text:
result["tags"] = [tag.strip() for tag in tags_text.split("Save")[0].split("·") if tag.strip()]
return result
def fetch_traits(engine_traits: EngineTraits) -> None:
"""Fetch languages and other search arguments from Anna's search form."""
# pylint: disable=import-outside-toplevel
import babel
from searx.locales import language_tag
from searx.network import get # see https://github.com/searxng/searxng/issues/762
engine_traits.all_locale = ""
engine_traits.custom["content"] = []
engine_traits.custom["ext"] = []
engine_traits.custom["sort"] = []
resp = get(_get_base_url_choice() + "/search", timeout=5)
if not resp.ok:
raise RuntimeError("Response from Anna's Archive is not OK.")
dom = html.fromstring(resp.text)
# supported language codes
lang_map: dict[str, str] = {}
for x in eval_xpath_list(dom, "//form//input[@name='lang']"):
eng_lang = x.get("value")
if eng_lang in ("", "_empty", "nl-BE", "und") or eng_lang.startswith("anti__"):
continue
try:
locale = babel.Locale.parse(lang_map.get(eng_lang, eng_lang), sep="-")
except babel.UnknownLocaleError:
# silently ignore unknown languages
# print("ERROR: %s -> %s is unknown by babel" % (x.get("data-name"), eng_lang))
continue
sxng_lang = language_tag(locale)
conflict = engine_traits.languages.get(sxng_lang)
if conflict:
if conflict != eng_lang:
print("CONFLICT: babel %s --> %s, %s" % (sxng_lang, conflict, eng_lang))
continue
engine_traits.languages[sxng_lang] = eng_lang
for x in eval_xpath_list(dom, "//form//input[@name='content']"):
if not x.get("value").startswith("anti__"):
engine_traits.custom["content"].append(x.get("value"))
for x in eval_xpath_list(dom, "//form//input[@name='ext']"):
if not x.get("value").startswith("anti__"):
engine_traits.custom["ext"].append(x.get("value"))
for x in eval_xpath_list(dom, "//form//select[@name='sort']//option"):
engine_traits.custom["sort"].append(x.get("value"))
# for better diff; sort the persistence of these traits
engine_traits.custom["content"].sort()
engine_traits.custom["ext"].sort()
engine_traits.custom["sort"].sort()
|