torznab.py 7.6 KB

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