lemmy.py 5.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197
  1. # SPDX-License-Identifier: AGPL-3.0-or-later
  2. # lint: pylint
  3. """This engine uses the Lemmy API (https://lemmy.ml/api/v3/search), which is
  4. documented at `lemmy-js-client`_ / `Interface Search`_. Since Lemmy is
  5. federated, results are from many different, independent lemmy instances, and not
  6. only the official one.
  7. .. _lemmy-js-client: https://join-lemmy.org/api/modules.html
  8. .. _Interface Search: https://join-lemmy.org/api/interfaces/Search.html
  9. Configuration
  10. =============
  11. The engine has the following additional settings:
  12. - :py:obj:`base_url`
  13. - :py:obj:`lemmy_type`
  14. This implementation is used by different lemmy engines in the :ref:`settings.yml
  15. <settings engine>`:
  16. .. code:: yaml
  17. - name: lemmy communities
  18. lemmy_type: Communities
  19. ...
  20. - name: lemmy users
  21. lemmy_type: Users
  22. ...
  23. - name: lemmy posts
  24. lemmy_type: Posts
  25. ...
  26. - name: lemmy comments
  27. lemmy_type: Comments
  28. ...
  29. Implementations
  30. ===============
  31. """
  32. from datetime import datetime
  33. from urllib.parse import urlencode
  34. from flask_babel import gettext
  35. from searx.utils import markdown_to_text
  36. about = {
  37. "website": 'https://lemmy.ml/',
  38. "wikidata_id": 'Q84777032',
  39. "official_api_documentation": "https://join-lemmy.org/api/",
  40. "use_official_api": True,
  41. "require_api_key": False,
  42. "results": 'JSON',
  43. }
  44. paging = True
  45. categories = ['social media']
  46. base_url = "https://lemmy.ml/"
  47. """By default, https://lemmy.ml is used for providing the results. If you want
  48. to use a different lemmy instance, you can specify ``base_url``.
  49. """
  50. lemmy_type = "Communities"
  51. """Any of ``Communities``, ``Users``, ``Posts``, ``Comments``"""
  52. def request(query, params):
  53. args = {
  54. 'q': query,
  55. 'page': params['pageno'],
  56. 'type_': lemmy_type,
  57. }
  58. params['url'] = f"{base_url}api/v3/search?{urlencode(args)}"
  59. return params
  60. def _get_communities(json):
  61. results = []
  62. for result in json["communities"]:
  63. counts = result['counts']
  64. metadata = (
  65. f"{gettext('subscribers')}: {counts.get('subscribers', 0)}"
  66. f" | {gettext('posts')}: {counts.get('posts', 0)}"
  67. f" | {gettext('active users')}: {counts.get('users_active_half_year', 0)}"
  68. )
  69. results.append(
  70. {
  71. 'url': result['community']['actor_id'],
  72. 'title': result['community']['title'],
  73. 'content': markdown_to_text(result['community'].get('description', '')),
  74. 'img_src': result['community'].get('icon', result['community'].get('banner')),
  75. 'publishedDate': datetime.strptime(counts['published'][:19], '%Y-%m-%dT%H:%M:%S'),
  76. 'metadata': metadata,
  77. }
  78. )
  79. return results
  80. def _get_users(json):
  81. results = []
  82. for result in json["users"]:
  83. results.append(
  84. {
  85. 'url': result['person']['actor_id'],
  86. 'title': result['person']['name'],
  87. 'content': markdown_to_text(result['person'].get('bio', '')),
  88. }
  89. )
  90. return results
  91. def _get_posts(json):
  92. results = []
  93. for result in json["posts"]:
  94. user = result['creator'].get('display_name', result['creator']['name'])
  95. img_src = None
  96. if result['post'].get('thumbnail_url'):
  97. img_src = result['post']['thumbnail_url'] + '?format=webp&thumbnail=208'
  98. metadata = (
  99. f"&#x25B2; {result['counts']['upvotes']} &#x25BC; {result['counts']['downvotes']}"
  100. f" | {gettext('user')}: {user}"
  101. f" | {gettext('comments')}: {result['counts']['comments']}"
  102. f" | {gettext('community')}: {result['community']['title']}"
  103. )
  104. content = result['post'].get('body', '').strip()
  105. if content:
  106. content = markdown_to_text(content)
  107. results.append(
  108. {
  109. 'url': result['post']['ap_id'],
  110. 'title': result['post']['name'],
  111. 'content': content,
  112. 'img_src': img_src,
  113. 'publishedDate': datetime.strptime(result['post']['published'][:19], '%Y-%m-%dT%H:%M:%S'),
  114. 'metadata': metadata,
  115. }
  116. )
  117. return results
  118. def _get_comments(json):
  119. results = []
  120. for result in json["comments"]:
  121. user = result['creator'].get('display_name', result['creator']['name'])
  122. content = result['comment'].get('content', '').strip()
  123. if content:
  124. content = markdown_to_text(content)
  125. metadata = (
  126. f"&#x25B2; {result['counts']['upvotes']} &#x25BC; {result['counts']['downvotes']}"
  127. f" | {gettext('user')}: {user}"
  128. f" | {gettext('community')}: {result['community']['title']}"
  129. )
  130. results.append(
  131. {
  132. 'url': result['comment']['ap_id'],
  133. 'title': result['post']['name'],
  134. 'content': markdown_to_text(result['comment']['content']),
  135. 'publishedDate': datetime.strptime(result['comment']['published'][:19], '%Y-%m-%dT%H:%M:%S'),
  136. 'metadata': metadata,
  137. }
  138. )
  139. return results
  140. def response(resp):
  141. json = resp.json()
  142. if lemmy_type == "Communities":
  143. return _get_communities(json)
  144. if lemmy_type == "Users":
  145. return _get_users(json)
  146. if lemmy_type == "Posts":
  147. return _get_posts(json)
  148. if lemmy_type == "Comments":
  149. return _get_comments(json)
  150. raise ValueError(f"Unsupported lemmy type: {lemmy_type}")