piped.py 4.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165
  1. # SPDX-License-Identifier: AGPL-3.0-or-later
  2. # lint: pylint
  3. """An alternative privacy-friendly YouTube frontend which is efficient by
  4. design. `Piped’s architecture`_ consists of 3 components:
  5. - :py:obj:`backend <backend_url>`
  6. - :py:obj:`frontend <frontend_url>`
  7. - proxy
  8. .. _Piped’s architecture: https://docs.piped.video/docs/architecture/
  9. Configuration
  10. =============
  11. The :py:obj:`backend_url` and :py:obj:`frontend_url` has to be set in the engine
  12. named `piped` and are used by all piped engines
  13. .. code:: yaml
  14. - name: piped
  15. engine: piped
  16. piped_filter: videos
  17. ...
  18. frontend_url: https://..
  19. backend_url:
  20. - https://..
  21. - https://..
  22. - name: piped.music
  23. engine: piped
  24. network: piped
  25. shortcut: ppdm
  26. piped_filter: music_songs
  27. ...
  28. Known Quirks
  29. ============
  30. The implementation to support :py:obj:`paging <searx.enginelib.Engine.paging>`
  31. is based on the *nextpage* method of Piped's REST API / the :py:obj:`frontend
  32. API <frontend_url>`. This feature is *next page driven* and plays well with the
  33. :ref:`infinite_scroll <settings ui>` setting in SearXNG but it does not really
  34. fit into SearXNG's UI to select a page by number.
  35. Implementations
  36. ===============
  37. """
  38. from __future__ import annotations
  39. import time
  40. import random
  41. from urllib.parse import urlencode
  42. import datetime
  43. from dateutil import parser
  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 offical 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. publishedDate = parser.parse(time.ctime(result.get("uploaded", 0) / 1000))
  99. item = {
  100. # the api url differs from the frontend, hence use piped.video as default
  101. "url": _frontend_url() + result.get("url", ""),
  102. "title": result.get("title", ""),
  103. "publishedDate": publishedDate,
  104. "iframe_src": _frontend_url() + '/embed' + result.get("url", ""),
  105. }
  106. if piped_filter == 'videos':
  107. item["template"] = "videos.html"
  108. # if the value of shortDescription set, but is None, return empty string
  109. item["content"] = result.get("shortDescription", "") or ""
  110. item["thumbnail"] = result.get("thumbnail", "")
  111. elif piped_filter == 'music_songs':
  112. item["template"] = "default.html"
  113. item["img_src"] = result.get("thumbnail", "")
  114. item["content"] = result.get("uploaderName", "") or ""
  115. length = result.get("duration")
  116. if length:
  117. item["length"] = datetime.timedelta(seconds=length)
  118. results.append(item)
  119. results.append(
  120. {
  121. "engine_data": json["nextpage"],
  122. "key": "nextpage",
  123. }
  124. )
  125. return results