pelican_comment_system.py 6.3 KB

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