piped.py 4.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169
  1. # SPDX-License-Identifier: AGPL-3.0-or-later
  2. """An alternative privacy-friendly YouTube frontend which is efficient by
  3. design. `Piped’s architecture`_ consists of 3 components:
  4. - :py:obj:`backend <backend_url>`
  5. - :py:obj:`frontend <frontend_url>`
  6. - proxy
  7. .. _Piped’s architecture: https://docs.piped.video/docs/architecture/
  8. Configuration
  9. =============
  10. The :py:obj:`backend_url` and :py:obj:`frontend_url` has to be set in the engine
  11. named `piped` and are used by all piped engines
  12. .. code:: yaml
  13. - name: piped
  14. engine: piped
  15. piped_filter: videos
  16. ...
  17. frontend_url: https://..
  18. backend_url:
  19. - https://..
  20. - https://..
  21. - name: piped.music
  22. engine: piped
  23. network: piped
  24. shortcut: ppdm
  25. piped_filter: music_songs
  26. ...
  27. Known Quirks
  28. ============
  29. The implementation to support :py:obj:`paging <searx.enginelib.Engine.paging>`
  30. is based on the *nextpage* method of Piped's REST API / the :py:obj:`frontend
  31. API <frontend_url>`. This feature is *next page driven* and plays well with the
  32. :ref:`infinite_scroll <settings ui>` setting in SearXNG but it does not really
  33. fit into SearXNG's UI to select a page by number.
  34. Implementations
  35. ===============
  36. """
  37. from __future__ import annotations
  38. import time
  39. import random
  40. from urllib.parse import urlencode
  41. import datetime
  42. from dateutil import parser
  43. from searx.utils import humanize_number
  44. # about
  45. about = {
  46. "website": 'https://github.com/TeamPiped/Piped/',
  47. "wikidata_id": 'Q107565255',
  48. "official_api_documentation": 'https://docs.piped.video/docs/api-documentation/',
  49. "use_official_api": True,
  50. "require_api_key": False,
  51. "results": 'JSON',
  52. }
  53. # engine dependent config
  54. categories = []
  55. paging = True
  56. # search-url
  57. backend_url: list | str = "https://pipedapi.kavin.rocks"
  58. """Piped-Backend_: The core component behind Piped. The value is an URL or a
  59. list of URLs. In the latter case instance will be selected randomly. For a
  60. complete list of official instances see Piped-Instances (`JSON
  61. <https://piped-instances.kavin.rocks/>`__)
  62. .. _Piped-Instances: https://github.com/TeamPiped/Piped/wiki/Instances
  63. .. _Piped-Backend: https://github.com/TeamPiped/Piped-Backend
  64. """
  65. frontend_url: str = "https://piped.video"
  66. """Piped-Frontend_: URL to use as link and for embeds.
  67. .. _Piped-Frontend: https://github.com/TeamPiped/Piped
  68. """
  69. piped_filter = 'all'
  70. """Content filter ``music_songs`` or ``videos``"""
  71. def _backend_url() -> str:
  72. from searx.engines import engines # pylint: disable=import-outside-toplevel
  73. url = engines['piped'].backend_url # type: ignore
  74. if isinstance(url, list):
  75. url = random.choice(url)
  76. return url
  77. def _frontend_url() -> str:
  78. from searx.engines import engines # pylint: disable=import-outside-toplevel
  79. return engines['piped'].frontend_url # type: ignore
  80. def request(query, params):
  81. args = {
  82. 'q': query,
  83. 'filter': piped_filter,
  84. }
  85. path = "/search"
  86. if params['pageno'] > 1:
  87. # don't use nextpage when user selected to jump back to page 1
  88. nextpage = params['engine_data'].get('nextpage')
  89. if nextpage:
  90. path = "/nextpage/search"
  91. args['nextpage'] = nextpage
  92. params["url"] = _backend_url() + f"{path}?" + urlencode(args)
  93. return params
  94. def response(resp):
  95. results = []
  96. json = resp.json()
  97. for result in json["items"]:
  98. # note: piped returns -1 for all upload times when filtering for music
  99. uploaded = result.get("uploaded", -1)
  100. item = {
  101. # the api url differs from the frontend, hence use piped.video as default
  102. "url": _frontend_url() + result.get("url", ""),
  103. "title": result.get("title", ""),
  104. "publishedDate": parser.parse(time.ctime(uploaded / 1000)) if uploaded != -1 else None,
  105. "iframe_src": _frontend_url() + '/embed' + result.get("url", ""),
  106. "views": humanize_number(result["views"]),
  107. }
  108. length = result.get("duration")
  109. if length:
  110. item["length"] = datetime.timedelta(seconds=length)
  111. if piped_filter == 'videos':
  112. item["template"] = "videos.html"
  113. # if the value of shortDescription set, but is None, return empty string
  114. item["content"] = result.get("shortDescription", "") or ""
  115. item["thumbnail"] = result.get("thumbnail", "")
  116. elif piped_filter == 'music_songs':
  117. item["template"] = "default.html"
  118. item["thumbnail"] = result.get("thumbnail", "")
  119. item["content"] = result.get("uploaderName", "") or ""
  120. results.append(item)
  121. results.append(
  122. {
  123. "engine_data": json["nextpage"],
  124. "key": "nextpage",
  125. }
  126. )
  127. return results