torznab.py 7.6 KB

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