discourse.py 4.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182
  1. # SPDX-License-Identifier: AGPL-3.0-or-later
  2. """.. sidebar:: info
  3. - `builtwith.com Discourse <https://trends.builtwith.com/websitelist/Discourse>`_
  4. Discourse is an open source Internet forum system. To search in a forum this
  5. engine offers some additional settings:
  6. - :py:obj:`base_url`
  7. - :py:obj:`api_order`
  8. - :py:obj:`search_endpoint`
  9. - :py:obj:`show_avatar`
  10. - :py:obj:`api_key`
  11. - :py:obj:`api_username`
  12. Example
  13. =======
  14. To search in your favorite Discourse forum, add a configuration like shown here
  15. for the ``paddling.com`` forum:
  16. .. code:: yaml
  17. - name: paddling
  18. engine: discourse
  19. shortcut: paddle
  20. base_url: 'https://forums.paddling.com/'
  21. api_order: views
  22. categories: ['social media', 'sports']
  23. show_avatar: true
  24. If the forum is private, you need to add an API key and username for the search:
  25. .. code:: yaml
  26. - name: paddling
  27. engine: discourse
  28. shortcut: paddle
  29. base_url: 'https://forums.paddling.com/'
  30. api_order: views
  31. categories: ['social media', 'sports']
  32. show_avatar: true
  33. api_key: '<KEY>'
  34. api_username: 'system'
  35. Implementations
  36. ===============
  37. """
  38. from urllib.parse import urlencode
  39. from datetime import datetime, timedelta
  40. import html
  41. from dateutil import parser
  42. from flask_babel import gettext
  43. about = {
  44. "website": "https://discourse.org/",
  45. "wikidata_id": "Q15054354",
  46. "official_api_documentation": "https://docs.discourse.org/",
  47. "use_official_api": True,
  48. "require_api_key": False,
  49. "results": "JSON",
  50. }
  51. base_url: str = None # type: ignore
  52. """URL of the Discourse forum."""
  53. search_endpoint = '/search.json'
  54. """URL path of the `search endpoint`_.
  55. .. _search endpoint: https://docs.discourse.org/#tag/Search
  56. """
  57. api_order = 'likes'
  58. """Order method, valid values are: ``latest``, ``likes``, ``views``, ``latest_topic``"""
  59. show_avatar = False
  60. """Show avatar of the user who send the post."""
  61. api_key = ''
  62. """API key of the Discourse forum."""
  63. api_username = ''
  64. """API username of the Discourse forum."""
  65. paging = True
  66. time_range_support = True
  67. AGO_TIMEDELTA = {
  68. 'day': timedelta(days=1),
  69. 'week': timedelta(days=7),
  70. 'month': timedelta(days=31),
  71. 'year': timedelta(days=365),
  72. }
  73. def request(query, params):
  74. if len(query) <= 2:
  75. return None
  76. q = [query, f'order:{api_order}']
  77. time_range = params.get('time_range')
  78. if time_range:
  79. after_date = datetime.now() - AGO_TIMEDELTA[time_range]
  80. q.append('after:' + after_date.strftime('%Y-%m-%d'))
  81. args = {
  82. 'q': ' '.join(q),
  83. 'page': params['pageno'],
  84. }
  85. params['url'] = f'{base_url}{search_endpoint}?{urlencode(args)}'
  86. params['headers'] = {
  87. 'Accept': 'application/json, text/javascript, */*; q=0.01',
  88. 'X-Requested-With': 'XMLHttpRequest',
  89. }
  90. if api_key != '':
  91. params['headers']['Api-Key'] = api_key
  92. if api_username != '':
  93. params['headers']['Api-Username'] = api_username
  94. return params
  95. def response(resp):
  96. results = []
  97. json_data = resp.json()
  98. if ('topics' or 'posts') not in json_data.keys():
  99. return []
  100. topics = {}
  101. for item in json_data['topics']:
  102. topics[item['id']] = item
  103. for post in json_data['posts']:
  104. result = topics.get(post['topic_id'], {})
  105. url = f"{base_url}/p/{post['id']}"
  106. status = gettext("closed") if result.get('closed', '') else gettext("open")
  107. comments = result.get('posts_count', 0)
  108. publishedDate = parser.parse(result['created_at'])
  109. metadata = []
  110. metadata.append('@' + post.get('username', ''))
  111. if int(comments) > 1:
  112. metadata.append(f'{gettext("comments")}: {comments}')
  113. if result.get('has_accepted_answer'):
  114. metadata.append(gettext("answered"))
  115. elif int(comments) > 1:
  116. metadata.append(status)
  117. result = {
  118. 'url': url,
  119. 'title': html.unescape(result['title']),
  120. 'content': html.unescape(post.get('blurb', '')),
  121. 'metadata': ' | '.join(metadata),
  122. 'publishedDate': publishedDate,
  123. 'upstream': {'topics': result},
  124. }
  125. avatar = post.get('avatar_template', '').replace('{size}', '96')
  126. if show_avatar and avatar:
  127. result['thumbnail'] = base_url + avatar
  128. results.append(result)
  129. results.append({'number_of_results': len(json_data['topics'])})
  130. return results