.oO SearXNG Developer Documentation Oo.
Loading...
Searching...
No Matches
torznab.py
Go to the documentation of this file.
1# SPDX-License-Identifier: AGPL-3.0-or-later
2"""Torznab_ is an API specification that provides a standardized way to query
3torrent site for content. It is used by a number of torrent applications,
4including Prowlarr_ and Jackett_.
5
6Using this engine together with Prowlarr_ or Jackett_ allows you to search
7a huge number of torrent sites which are not directly supported.
8
9Configuration
10=============
11
12The engine has the following settings:
13
14``base_url``:
15 Torznab endpoint URL.
16
17``api_key``:
18 The API key to use for authentication.
19
20``torznab_categories``:
21 The categories to use for searching. This is a list of category IDs. See
22 Prowlarr-categories_ or Jackett-categories_ for more information.
23
24``show_torrent_files``:
25 Whether to show the torrent file in the search results. Be careful as using
26 this with Prowlarr_ or Jackett_ leaks the API key. This should be used only
27 if you are querying a Torznab endpoint without authentication or if the
28 instance is private. Be aware that private trackers may ban you if you share
29 the torrent file. Defaults to ``false``.
30
31``show_magnet_links``:
32 Whether to show the magnet link in the search results. Be aware that private
33 trackers may ban you if you share the magnet link. Defaults to ``true``.
34
35.. _Torznab:
36 https://torznab.github.io/spec-1.3-draft/index.html
37.. _Prowlarr:
38 https://github.com/Prowlarr/Prowlarr
39.. _Jackett:
40 https://github.com/Jackett/Jackett
41.. _Prowlarr-categories:
42 https://wiki.servarr.com/en/prowlarr/cardigann-yml-definition#categories
43.. _Jackett-categories:
44 https://github.com/Jackett/Jackett/wiki/Jackett-Categories
45
46Implementations
47===============
48
49"""
50from __future__ import annotations
51from typing import TYPE_CHECKING
52
53from typing import List, Dict, Any
54from datetime import datetime
55from urllib.parse import quote
56from lxml import etree # type: ignore
57
58from searx.exceptions import SearxEngineAPIException
59
60if TYPE_CHECKING:
61 import httpx
62 import logging
63
64 logger: logging.Logger
65
66# engine settings
67about: Dict[str, Any] = {
68 "website": None,
69 "wikidata_id": None,
70 "official_api_documentation": "https://torznab.github.io/spec-1.3-draft",
71 "use_official_api": True,
72 "require_api_key": False,
73 "results": 'XML',
74}
75categories: List[str] = ['files']
76paging: bool = False
77time_range_support: bool = False
78
79# defined in settings.yml
80# example (Jackett): "http://localhost:9117/api/v2.0/indexers/all/results/torznab"
81base_url: str = ''
82api_key: str = ''
83# https://newznab.readthedocs.io/en/latest/misc/api/#predefined-categories
84torznab_categories: List[str] = []
85show_torrent_files: bool = False
86show_magnet_links: bool = True
87
88
89def init(engine_settings=None): # pylint: disable=unused-argument
90 """Initialize the engine."""
91 if len(base_url) < 1:
92 raise ValueError('missing torznab base_url')
93
94
95def request(query: str, params: Dict[str, Any]) -> Dict[str, Any]:
96 """Build the request params."""
97 search_url: str = base_url + '?t=search&q={search_query}'
98
99 if len(api_key) > 0:
100 search_url += '&apikey={api_key}'
101 if len(torznab_categories) > 0:
102 search_url += '&cat={torznab_categories}'
103
104 params['url'] = search_url.format(
105 search_query=quote(query), api_key=api_key, torznab_categories=",".join([str(x) for x in torznab_categories])
106 )
107
108 return params
109
110
111def response(resp: httpx.Response) -> List[Dict[str, Any]]:
112 """Parse the XML response and return a list of results."""
113 results = []
114 search_results = etree.XML(resp.content)
115
116 # handle errors: https://newznab.readthedocs.io/en/latest/misc/api/#newznab-error-codes
117 if search_results.tag == "error":
118 raise SearxEngineAPIException(search_results.get("description"))
119
120 channel: etree.Element = search_results[0]
121
122 item: etree.Element
123 for item in channel.iterfind('item'):
124 result: Dict[str, Any] = build_result(item)
125 results.append(result)
126
127 return results
128
129
130def build_result(item: etree.Element) -> Dict[str, Any]:
131 """Build a result from a XML item."""
132
133 # extract attributes from XML
134 # see https://torznab.github.io/spec-1.3-draft/torznab/Specification-v1.3.html#predefined-attributes
135 enclosure: etree.Element | None = item.find('enclosure')
136 enclosure_url: str | None = None
137 if enclosure is not None:
138 enclosure_url = enclosure.get('url')
139
140 size = get_attribute(item, 'size')
141 if not size and enclosure:
142 size = enclosure.get('length')
143 if size:
144 size = int(size)
145
146 guid = get_attribute(item, 'guid')
147 comments = get_attribute(item, 'comments')
148 pubDate = get_attribute(item, 'pubDate')
149 seeders = get_torznab_attribute(item, 'seeders')
150 leechers = get_torznab_attribute(item, 'leechers')
151 peers = get_torznab_attribute(item, 'peers')
152
153 # map attributes to searx result
154 result: Dict[str, Any] = {
155 'template': 'torrent.html',
156 'title': get_attribute(item, 'title'),
157 'filesize': size,
158 'files': get_attribute(item, 'files'),
159 'seed': seeders,
160 'leech': _map_leechers(leechers, seeders, peers),
161 'url': _map_result_url(guid, comments),
162 'publishedDate': _map_published_date(pubDate),
163 'torrentfile': None,
164 'magnetlink': None,
165 }
166
167 link = get_attribute(item, 'link')
168 if show_torrent_files:
169 result['torrentfile'] = _map_torrent_file(link, enclosure_url)
170 if show_magnet_links:
171 magneturl = get_torznab_attribute(item, 'magneturl')
172 result['magnetlink'] = _map_magnet_link(magneturl, guid, enclosure_url, link)
173 return result
174
175
176def _map_result_url(guid: str | None, comments: str | None) -> str | None:
177 if guid and guid.startswith('http'):
178 return guid
179 if comments and comments.startswith('http'):
180 return comments
181 return None
182
183
184def _map_leechers(leechers: str | None, seeders: str | None, peers: str | None) -> str | None:
185 if leechers:
186 return leechers
187 if seeders and peers:
188 return str(int(peers) - int(seeders))
189 return None
190
191
192def _map_published_date(pubDate: str | None) -> datetime | None:
193 if pubDate is not None:
194 try:
195 return datetime.strptime(pubDate, '%a, %d %b %Y %H:%M:%S %z')
196 except (ValueError, TypeError) as e:
197 logger.debug("ignore exception (publishedDate): %s", e)
198 return None
199
200
201def _map_torrent_file(link: str | None, enclosure_url: str | None) -> str | None:
202 if link and link.startswith('http'):
203 return link
204 if enclosure_url and enclosure_url.startswith('http'):
205 return enclosure_url
206 return None
207
208
210 magneturl: str | None,
211 guid: str | None,
212 enclosure_url: str | None,
213 link: str | None,
214) -> str | None:
215 if magneturl and magneturl.startswith('magnet'):
216 return magneturl
217 if guid and guid.startswith('magnet'):
218 return guid
219 if enclosure_url and enclosure_url.startswith('magnet'):
220 return enclosure_url
221 if link and link.startswith('magnet'):
222 return link
223 return None
224
225
226def get_attribute(item: etree.Element, property_name: str) -> str | None:
227 """Get attribute from item."""
228 property_element: etree.Element | None = item.find(property_name)
229 if property_element is not None:
230 return property_element.text
231 return None
232
233
234def get_torznab_attribute(item: etree.Element, attribute_name: str) -> str | None:
235 """Get torznab special attribute from item."""
236 element: etree.Element | None = item.find(
237 './/torznab:attr[@name="{attribute_name}"]'.format(attribute_name=attribute_name),
238 {'torznab': 'http://torznab.com/schemas/2015/feed'},
239 )
240 if element is not None:
241 return element.get("value")
242 return None
datetime|None _map_published_date(str|None pubDate)
Definition torznab.py:192
str|None _map_result_url(str|None guid, str|None comments)
Definition torznab.py:176
List[Dict[str, Any]] response(httpx.Response resp)
Definition torznab.py:111
str|None _map_torrent_file(str|None link, str|None enclosure_url)
Definition torznab.py:201
str|None get_torznab_attribute(etree.Element item, str attribute_name)
Definition torznab.py:234
str|None _map_leechers(str|None leechers, str|None seeders, str|None peers)
Definition torznab.py:184
init(engine_settings=None)
Definition torznab.py:89
str|None _map_magnet_link(str|None magneturl, str|None guid, str|None enclosure_url, str|None link)
Definition torznab.py:214
Dict[str, Any] request(str query, Dict[str, Any] params)
Definition torznab.py:95
str|None get_attribute(etree.Element item, str property_name)
Definition torznab.py:226
Dict[str, Any] build_result(etree.Element item)
Definition torznab.py:130