pelican_comment_system.py 6.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225
  1. # -*- coding: utf-8 -*-
  2. """
  3. Pelican Comment System
  4. ======================
  5. A Pelican plugin, which allows you to add comments to your articles.
  6. Author: Bernhard Scheirle
  7. """
  8. from __future__ import unicode_literals
  9. import logging
  10. import os
  11. import copy
  12. logger = logging.getLogger(__name__)
  13. from itertools import chain
  14. from pelican import signals
  15. from pelican.readers import Readers
  16. from pelican.writers import Writer
  17. from . comment import Comment
  18. from . import avatars
  19. _all_comments = []
  20. pelican_writer = None
  21. def setdefault(pelican, settings):
  22. from pelican.settings import DEFAULT_CONFIG
  23. for key, value in settings:
  24. DEFAULT_CONFIG.setdefault(key, value)
  25. if not pelican:
  26. return
  27. for key, value in settings:
  28. pelican.settings.setdefault(key, value)
  29. def pelican_initialized(pelican):
  30. from pelican.settings import DEFAULT_CONFIG
  31. settings = [
  32. ('PELICAN_COMMENT_SYSTEM', False),
  33. ('PELICAN_COMMENT_SYSTEM_DIR', 'comments'),
  34. ('PELICAN_COMMENT_SYSTEM_IDENTICON_OUTPUT_PATH', 'images/identicon'),
  35. ('PELICAN_COMMENT_SYSTEM_IDENTICON_DATA', ()),
  36. ('PELICAN_COMMENT_SYSTEM_IDENTICON_SIZE', 72),
  37. ('PELICAN_COMMENT_SYSTEM_AUTHORS', {}),
  38. ('PELICAN_COMMENT_SYSTEM_FEED', os.path.join('feeds', 'comment.%s.atom.xml')),
  39. ('PELICAN_COMMENT_SYSTEM_FEED_ALL', os.path.join('feeds', 'comments.all.atom.xml')),
  40. ('COMMENT_URL', '#comment-{slug}')
  41. ]
  42. setdefault(pelican, settings)
  43. DEFAULT_CONFIG['PAGE_EXCLUDES'].append(
  44. DEFAULT_CONFIG['PELICAN_COMMENT_SYSTEM_DIR'])
  45. DEFAULT_CONFIG['ARTICLE_EXCLUDES'].append(
  46. DEFAULT_CONFIG['PELICAN_COMMENT_SYSTEM_DIR'])
  47. pelican.settings['PAGE_EXCLUDES'].append(
  48. pelican.settings['PELICAN_COMMENT_SYSTEM_DIR'])
  49. pelican.settings['ARTICLE_EXCLUDES'].append(
  50. pelican.settings['PELICAN_COMMENT_SYSTEM_DIR'])
  51. global pelican_writer
  52. pelican_writer = pelican.get_writer()
  53. def initialize(article_generator):
  54. avatars.init(
  55. article_generator.settings['OUTPUT_PATH'],
  56. article_generator.settings[
  57. 'PELICAN_COMMENT_SYSTEM_IDENTICON_OUTPUT_PATH'],
  58. article_generator.settings['PELICAN_COMMENT_SYSTEM_IDENTICON_DATA'],
  59. article_generator.settings[
  60. 'PELICAN_COMMENT_SYSTEM_IDENTICON_SIZE'] / 3,
  61. article_generator.settings['PELICAN_COMMENT_SYSTEM_AUTHORS'],
  62. )
  63. def warn_on_slug_collision(items):
  64. slugs = {}
  65. for comment in items:
  66. if not comment.slug in slugs:
  67. slugs[comment.slug] = [comment]
  68. else:
  69. slugs[comment.slug].append(comment)
  70. for slug, itemList in slugs.items():
  71. len_ = len(itemList)
  72. if len_ > 1:
  73. logger.warning('There are %s comments with the same slug: %s', len_, slug)
  74. for x in itemList:
  75. logger.warning(' %s', x.source_path)
  76. def write_feed_all(gen, writer):
  77. if gen.settings['PELICAN_COMMENT_SYSTEM'] is not True:
  78. return
  79. if gen.settings['PELICAN_COMMENT_SYSTEM_FEED_ALL'] is None:
  80. return
  81. context = copy.copy(gen.context)
  82. context['SITENAME'] += " - All Comments"
  83. context['SITESUBTITLE'] = ""
  84. path = gen.settings['PELICAN_COMMENT_SYSTEM_FEED_ALL']
  85. global _all_comments
  86. _all_comments = sorted(_all_comments)
  87. _all_comments.reverse()
  88. for com in _all_comments:
  89. com.title = com.article.title + " - " + com.title
  90. com.override_url = com.article.url + com.url
  91. writer.write_feed(_all_comments, context, path)
  92. def write_feed(gen, items, context, slug):
  93. if gen.settings['PELICAN_COMMENT_SYSTEM_FEED'] is None:
  94. return
  95. path = gen.settings['PELICAN_COMMENT_SYSTEM_FEED'] % slug
  96. pelican_writer.write_feed(items, context, path)
  97. def process_comments(article_generator):
  98. for article in article_generator.articles:
  99. add_static_comments(article_generator, article)
  100. def mirror_to_translations(article):
  101. for translation in article.translations:
  102. translation.comments_count = article.comments_count
  103. translation.comments = article.comments
  104. def add_static_comments(gen, content):
  105. if gen.settings['PELICAN_COMMENT_SYSTEM'] is not True:
  106. return
  107. global _all_comments
  108. content.comments_count = 0
  109. content.comments = []
  110. mirror_to_translations(content)
  111. # Modify the local context, so we get proper values for the feed
  112. context = copy.copy(gen.context)
  113. context['SITEURL'] += "/" + content.url
  114. context['SITENAME'] += " - Comments: " + content.title
  115. context['SITESUBTITLE'] = ""
  116. folder = os.path.join(
  117. gen.settings['PATH'],
  118. gen.settings['PELICAN_COMMENT_SYSTEM_DIR'],
  119. content.slug
  120. )
  121. if not os.path.isdir(folder):
  122. logger.debug("No comments found for: %s", content.slug)
  123. write_feed(gen, [], context, content.slug)
  124. return
  125. reader = Readers(gen.settings)
  126. comments = []
  127. replies = []
  128. for file in os.listdir(folder):
  129. name, extension = os.path.splitext(file)
  130. if extension[1:].lower() in reader.extensions:
  131. com = reader.read_file(
  132. base_path=folder, path=file,
  133. content_class=Comment, context=context)
  134. com.article = content
  135. _all_comments.append(com)
  136. if hasattr(com, 'replyto'):
  137. replies.append(com)
  138. else:
  139. comments.append(com)
  140. feed_items = sorted(comments + replies)
  141. feed_items.reverse()
  142. warn_on_slug_collision(feed_items)
  143. write_feed(gen, feed_items, context, content.slug)
  144. # TODO: Fix this O(n²) loop
  145. for reply in replies:
  146. for comment in chain(comments, replies):
  147. if comment.slug == reply.replyto:
  148. comment.addReply(reply)
  149. count = 0
  150. for comment in comments:
  151. comment.sortReplies()
  152. count += comment.countReplies()
  153. comments = sorted(comments)
  154. content.comments_count = len(comments) + count
  155. content.comments = comments
  156. mirror_to_translations(content)
  157. def writeIdenticonsToDisk(gen, writer):
  158. avatars.generateAndSaveMissingAvatars()
  159. def pelican_finalized(pelican):
  160. if pelican.settings['PELICAN_COMMENT_SYSTEM'] is not True:
  161. return
  162. global _all_comments
  163. print('Processed %s comment(s)' % len(_all_comments))
  164. _all_comments = []
  165. def register():
  166. signals.initialized.connect(pelican_initialized)
  167. signals.article_generator_init.connect(initialize)
  168. signals.article_generator_finalized.connect(process_comments)
  169. signals.article_writer_finalized.connect(writeIdenticonsToDisk)
  170. signals.article_writer_finalized.connect(write_feed_all)
  171. signals.finalized.connect(pelican_finalized)