Alexis Métaireau лет назад: 9
Родитель
Сommit
98a83bc3e3

+ 60 - 54
pelican_comment_system/avatars.py

@@ -14,11 +14,11 @@ import hashlib
 logger = logging.getLogger(__name__)
 _log = "pelican_comment_system: avatars: "
 try:
-	from . identicon import identicon
-	_identiconImported = True
+    from . identicon import identicon
+    identiconImported = True
 except ImportError as e:
-	logger.warning(_log + "identicon deactivated: " + str(e))
-	_identiconImported = False
+    logger.warning(_log + "identicon deactivated: " + str(e))
+    _identiconImported = False
 
 # Global Variables
 _identicon_save_path = None
@@ -29,68 +29,74 @@ _initialized = False
 _authors = None
 _missingAvatars = []
 
+
 def _ready():
-	if not _initialized:
-		logger.warning(_log + "Module not initialized. use init")
-	if not _identicon_data:
-		logger.debug(_log + "No identicon data set")
-	return _identiconImported and _initialized and _identicon_data
-
-
-def init(pelican_output_path, identicon_output_path, identicon_data, identicon_size, authors):
-	global _identicon_save_path
-	global _identicon_output_path
-	global _identicon_data
-	global _identicon_size
-	global _initialized
-	global _authors
-	if _initialized:
-		return
-	_identicon_save_path = os.path.join(pelican_output_path, identicon_output_path)
-	_identicon_output_path = identicon_output_path
-	_identicon_data = identicon_data
-	_identicon_size = identicon_size
-	_authors = authors
-	_initialized = True
+    if not _initialized:
+        logger.warning(_log + "Module not initialized. use init")
+    if not _identicon_data:
+        logger.debug(_log + "No identicon data set")
+    return _identiconImported and _initialized and _identicon_data
+
+
+def init(pelican_output_path, identicon_output_path, identicon_data,
+         identicon_size, authors):
+    global _identicon_save_path
+    global _identicon_output_path
+    global _identicon_data
+    global _identicon_size
+    global _initialized
+    global _authors
+    if _initialized:
+        return
+    _identicon_save_path = os.path.join(pelican_output_path,
+                                        identicon_output_path)
+    _identicon_output_path = identicon_output_path
+    _identicon_data = identicon_data
+    _identicon_size = identicon_size
+    _authors = authors
+    _initialized = True
+
 
 def _createIdenticonOutputFolder():
-	if not _ready():
-		return
+    if not _ready():
+        return
 
-	if not os.path.exists(_identicon_save_path):
-		os.makedirs(_identicon_save_path)
+    if not os.path.exists(_identicon_save_path):
+        os.makedirs(_identicon_save_path)
 
 
 def getAvatarPath(comment_id, metadata):
-	if not _ready():
-		return ''
+    if not _ready():
+        return ''
+
+    md5 = hashlib.md5()
+    author = tuple()
+    for data in _identicon_data:
+        if data in metadata:
+            string = "{}".format(metadata[data])
+            md5.update(string.encode('utf-8'))
+            author += tuple([string])
+        else:
+            logger.warning(_log + data +
+                           " is missing in comment: " + comment_id)
 
-	md5 = hashlib.md5()
-	author = tuple()
-	for data in _identicon_data:
-		if data in metadata:
-			string = "{}".format(metadata[data])
-			md5.update(string.encode('utf-8'))
-			author += tuple([string])
-		else:
-			logger.warning(_log + data + " is missing in comment: " + comment_id)
+    if author in _authors:
+        return _authors[author]
 
-	if author in _authors:
-		return _authors[author]
+    global _missingAvatars
 
-	global _missingAvatars
+    code = md5.hexdigest()
 
-	code = md5.hexdigest()
+    if not code in _missingAvatars:
+        _missingAvatars.append(code)
 
-	if not code in _missingAvatars:
-		_missingAvatars.append(code)
+    return os.path.join(_identicon_output_path, '%s.png' % code)
 
-	return os.path.join(_identicon_output_path, '%s.png' % code)
 
 def generateAndSaveMissingAvatars():
-	_createIdenticonOutputFolder()
-	for code in _missingAvatars:
-		avatar_path = '%s.png' % code
-		avatar = identicon.render_identicon(int(code, 16), _identicon_size)
-		avatar_save_path = os.path.join(_identicon_save_path, avatar_path)
-		avatar.save(avatar_save_path, 'PNG')
+    _createIdenticonOutputFolder()
+    for code in _missingAvatars:
+        avatar_path = '%s.png' % code
+        avatar = identicon.render_identicon(int(code, 16), _identicon_size)
+        avatar_save_path = os.path.join(_identicon_save_path, avatar_path)
+        avatar.save(avatar_save_path, 'PNG')

+ 51 - 48
pelican_comment_system/comment.py

@@ -5,57 +5,60 @@ Author: Bernhard Scheirle
 from __future__ import unicode_literals
 import os
 
-from pelican import contents
 from pelican.contents import Content
 from pelican.utils import slugify
 
 from . import avatars
 
+
 class Comment(Content):
-	mandatory_properties = ('author', 'date')
-	default_template = 'None'
-
-	def __init__(self, content, metadata, settings, source_path, context):
-		# Strip the path off the full filename.
-		name = os.path.split(source_path)[1]
-
-		if not hasattr(self, 'slug'):
-			#compute the slug before initializing the base Content object, so it doesn't get set there
-			#This is required because we need a slug containing the file extension.
-			self.slug = slugify( name, settings.get('SLUG_SUBSTITUTIONS', ()))
-
-		super(Comment,self).__init__( content, metadata, settings, source_path, context )
-
-		self.replies = []
-
-		# Strip the extension from the filename.
-		name = os.path.splitext(name)[0]
-		self.avatar = avatars.getAvatarPath(name, metadata)
-		self.title = "Posted by:  {}".format(metadata['author'])
-
-	def addReply(self, comment):
-		self.replies.append(comment)
-
-	def getReply(self, slug):
-		for reply in self.replies:
-			if reply.slug == slug:
-				return reply
-			else:
-				deepReply = reply.getReply( slug )
-				if deepReply != None:
-					return deepReply
-		return None
-
-	def __lt__(self, other):
-		return self.metadata['date'] < other.metadata['date']
-
-	def sortReplies(self):
-		for r in self.replies:
-			r.sortReplies()
-		self.replies = sorted(self.replies)
-
-	def countReplies(self):
-		amount = 0
-		for r in self.replies:
-			amount += r.countReplies()
-		return amount + len(self.replies)
+    mandatory_properties = ('author', 'date')
+    default_template = 'None'
+
+    def __init__(self, content, metadata, settings, source_path, context):
+        # Strip the path off the full filename.
+        name = os.path.split(source_path)[1]
+
+        if not hasattr(self, 'slug'):
+            #compute the slug before initializing the base Content object, so
+            # it doesn't get set there
+            # This is required because we need a slug containing the file
+            # extension.
+            self.slug = slugify(name, settings.get('SLUG_SUBSTITUTIONS', ()))
+
+        super(Comment, self).__init__(content, metadata, settings, source_path,
+                                      context)
+
+        self.replies = []
+
+        # Strip the extension from the filename.
+        name = os.path.splitext(name)[0]
+        self.avatar = avatars.getAvatarPath(name, metadata)
+        self.title = "Posted by:  {}".format(metadata['author'])
+
+    def addReply(self, comment):
+        self.replies.append(comment)
+
+    def getReply(self, slug):
+        for reply in self.replies:
+            if reply.slug == slug:
+                return reply
+            else:
+                deepReply = reply.getReply(slug)
+                if deepReply is not None:
+                    return deepReply
+        return None
+
+    def __lt__(self, other):
+        return self.metadata['date'] < other.metadata['date']
+
+    def sortReplies(self):
+        for r in self.replies:
+            r.sortReplies()
+        self.replies = sorted(self.replies)
+
+    def countReplies(self):
+        amount = 0
+        for r in self.replies:
+            amount += r.countReplies()
+        return amount + len(self.replies)

+ 105 - 96
pelican_comment_system/pelican_comment_system.py

@@ -24,125 +24,134 @@ from . import avatars
 
 
 def pelican_initialized(pelican):
-	from pelican.settings import DEFAULT_CONFIG
-	DEFAULT_CONFIG.setdefault('PELICAN_COMMENT_SYSTEM', False)
-	DEFAULT_CONFIG.setdefault('PELICAN_COMMENT_SYSTEM_DIR', 'comments')
-	DEFAULT_CONFIG.setdefault('PELICAN_COMMENT_SYSTEM_IDENTICON_OUTPUT_PATH' 'images/identicon')
-	DEFAULT_CONFIG.setdefault('PELICAN_COMMENT_SYSTEM_IDENTICON_DATA', ())
-	DEFAULT_CONFIG.setdefault('PELICAN_COMMENT_SYSTEM_IDENTICON_SIZE', 72)
-	DEFAULT_CONFIG.setdefault('PELICAN_COMMENT_SYSTEM_AUTHORS', {})
-	DEFAULT_CONFIG.setdefault('PELICAN_COMMENT_SYSTEM_FEED', os.path.join('feeds', 'comment.%s.atom.xml'))
-	DEFAULT_CONFIG.setdefault('COMMENT_URL', '#comment-{slug}')
-	DEFAULT_CONFIG['PAGE_EXCLUDES'].append(DEFAULT_CONFIG['PELICAN_COMMENT_SYSTEM_DIR'])
-	DEFAULT_CONFIG['ARTICLE_EXCLUDES'].append(DEFAULT_CONFIG['PELICAN_COMMENT_SYSTEM_DIR'])
-	if pelican:
-		pelican.settings.setdefault('PELICAN_COMMENT_SYSTEM', False)
-		pelican.settings.setdefault('PELICAN_COMMENT_SYSTEM_DIR', 'comments')
-		pelican.settings.setdefault('PELICAN_COMMENT_SYSTEM_IDENTICON_OUTPUT_PATH', 'images/identicon')
-		pelican.settings.setdefault('PELICAN_COMMENT_SYSTEM_IDENTICON_DATA', ())
-		pelican.settings.setdefault('PELICAN_COMMENT_SYSTEM_IDENTICON_SIZE', 72)
-		pelican.settings.setdefault('PELICAN_COMMENT_SYSTEM_AUTHORS', {})
-		pelican.settings.setdefault('PELICAN_COMMENT_SYSTEM_FEED', os.path.join('feeds', 'comment.%s.atom.xml'))
-		pelican.settings.setdefault('COMMENT_URL', '#comment-{slug}')
-
-		pelican.settings['PAGE_EXCLUDES'].append(pelican.settings['PELICAN_COMMENT_SYSTEM_DIR'])
-		pelican.settings['ARTICLE_EXCLUDES'].append(pelican.settings['PELICAN_COMMENT_SYSTEM_DIR'])
+    from pelican.settings import DEFAULT_CONFIG
+    DEFAULT_CONFIG.setdefault('PELICAN_COMMENT_SYSTEM', False)
+    DEFAULT_CONFIG.setdefault('PELICAN_COMMENT_SYSTEM_DIR', 'comments')
+    DEFAULT_CONFIG.setdefault('PELICAN_COMMENT_SYSTEM_IDENTICON_OUTPUT_PATH' 'images/identicon')
+    DEFAULT_CONFIG.setdefault('PELICAN_COMMENT_SYSTEM_IDENTICON_DATA', ())
+    DEFAULT_CONFIG.setdefault('PELICAN_COMMENT_SYSTEM_IDENTICON_SIZE', 72)
+    DEFAULT_CONFIG.setdefault('PELICAN_COMMENT_SYSTEM_AUTHORS', {})
+    DEFAULT_CONFIG.setdefault('PELICAN_COMMENT_SYSTEM_FEED', os.path.join('feeds', 'comment.%s.atom.xml'))
+    DEFAULT_CONFIG.setdefault('COMMENT_URL', '#comment-{slug}')
+    DEFAULT_CONFIG['PAGE_EXCLUDES'].append(DEFAULT_CONFIG['PELICAN_COMMENT_SYSTEM_DIR'])
+    DEFAULT_CONFIG['ARTICLE_EXCLUDES'].append(DEFAULT_CONFIG['PELICAN_COMMENT_SYSTEM_DIR'])
+    if pelican:
+        pelican.settings.setdefault('PELICAN_COMMENT_SYSTEM', False)
+        pelican.settings.setdefault('PELICAN_COMMENT_SYSTEM_DIR', 'comments')
+        pelican.settings.setdefault('PELICAN_COMMENT_SYSTEM_IDENTICON_OUTPUT_PATH', 'images/identicon')
+        pelican.settings.setdefault('PELICAN_COMMENT_SYSTEM_IDENTICON_DATA', ())
+        pelican.settings.setdefault('PELICAN_COMMENT_SYSTEM_IDENTICON_SIZE', 72)
+        pelican.settings.setdefault('PELICAN_COMMENT_SYSTEM_AUTHORS', {})
+        pelican.settings.setdefault('PELICAN_COMMENT_SYSTEM_FEED', os.path.join('feeds', 'comment.%s.atom.xml'))
+        pelican.settings.setdefault('COMMENT_URL', '#comment-{slug}')
+
+        pelican.settings['PAGE_EXCLUDES'].append(pelican.settings['PELICAN_COMMENT_SYSTEM_DIR'])
+        pelican.settings['ARTICLE_EXCLUDES'].append(pelican.settings['PELICAN_COMMENT_SYSTEM_DIR'])
 
 def initialize(article_generator):
-	avatars.init(
-		article_generator.settings['OUTPUT_PATH'],
-		article_generator.settings['PELICAN_COMMENT_SYSTEM_IDENTICON_OUTPUT_PATH'],
-		article_generator.settings['PELICAN_COMMENT_SYSTEM_IDENTICON_DATA'],
-		article_generator.settings['PELICAN_COMMENT_SYSTEM_IDENTICON_SIZE']/3,
-		article_generator.settings['PELICAN_COMMENT_SYSTEM_AUTHORS'],
-		)
-
-def warn_on_slug_collision( items ):
-	slugs = {}
-	for comment in items:
-		if not comment.slug in slugs:
-			slugs[ comment.slug ] = [ comment ]
-		else:
-			slugs[ comment.slug ].append( comment )
-
-	for slug, itemList in slugs.items():
-		len_ = len( itemList )
-		if len_ > 1:
-			logger.warning('There are %s comments with the same slug: %s'% (len_, slug))
-			for x in itemList:
-				logger.warning('    %s' % x.source_path)
+    avatars.init(
+        article_generator.settings['OUTPUT_PATH'],
+        article_generator.settings['PELICAN_COMMENT_SYSTEM_IDENTICON_OUTPUT_PATH'],
+        article_generator.settings['PELICAN_COMMENT_SYSTEM_IDENTICON_DATA'],
+        article_generator.settings['PELICAN_COMMENT_SYSTEM_IDENTICON_SIZE']/3,
+        article_generator.settings['PELICAN_COMMENT_SYSTEM_AUTHORS'],
+        )
+
+
+def warn_on_slug_collision(items):
+    slugs = {}
+    for comment in items:
+        if not comment.slug in slugs:
+            slugs[comment.slug] = [comment]
+        else:
+            slugs[comment.slug].append(comment)
+
+    for slug, itemList in slugs.items():
+        len_ = len(itemList)
+        if len_ > 1:
+            logger.warning('There are %s comments with the same slug: %s' %
+                           (len_, slug))
+            for x in itemList:
+                logger.warning('    %s' % x.source_path)
 
 
 def write_feed(gen, items, context, slug):
-	if gen.settings['PELICAN_COMMENT_SYSTEM_FEED'] == None:
-		return
+    if gen.settings['PELICAN_COMMENT_SYSTEM_FEED'] is None:
+        return
 
-	path = gen.settings['PELICAN_COMMENT_SYSTEM_FEED'] % slug
+    path = gen.settings['PELICAN_COMMENT_SYSTEM_FEED'] % slug
+
+    writer = Writer(gen.output_path, settings=gen.settings)
+    writer.write_feed(items, context, path)
 
-	writer = Writer(gen.output_path, settings=gen.settings)
-	writer.write_feed(items, context, path)
 
 def add_static_comments(gen, content):
-	if gen.settings['PELICAN_COMMENT_SYSTEM'] != True:
-		return
+    if gen.settings['PELICAN_COMMENT_SYSTEM'] is not True:
+        return
+
+    content.comments_count = 0
+    content.comments = []
 
-	content.comments_count = 0
-	content.comments = []
+    #Modify the local context, so we get proper values for the feed
+    context = copy.copy(gen.context)
+    context['SITEURL'] += "/" + content.url
+    context['SITENAME'] += " - Comments: " + content.title
+    context['SITESUBTITLE'] = ""
 
-	#Modify the local context, so we get proper values for the feed
-	context = copy.copy(gen.context)
-	context['SITEURL'] += "/" + content.url
-	context['SITENAME'] += " - Comments: " + content.title
-	context['SITESUBTITLE'] = ""
+    folder = os.path.join(
+        gen.settings['PATH'],
+        gen.settings['PELICAN_COMMENT_SYSTEM_DIR'],
+        content.slug
+    )
 
-	folder = os.path.join(gen.settings['PATH'], gen.settings['PELICAN_COMMENT_SYSTEM_DIR'], content.slug)
+    if not os.path.isdir(folder):
+        logger.debug("No comments found for: " + content.slug)
+        write_feed(gen, [], context, content.slug)
+        return
 
-	if not os.path.isdir(folder):
-		logger.debug("No comments found for: " + content.slug)
-		write_feed(gen, [], context, content.slug)
-		return
+    reader = Readers(gen.settings)
+    comments = []
+    replies = []
 
-	reader = Readers(gen.settings)
-	comments = []
-	replies = []
+    for file in os.listdir(folder):
+        name, extension = os.path.splitext(file)
+        if extension[1:].lower() in reader.extensions:
+            com = reader.read_file(
+                base_path=folder, path=file,
+                content_class=Comment, context=context)
 
-	for file in os.listdir(folder):
-		name, extension = os.path.splitext(file)
-		if extension[1:].lower() in reader.extensions:
-			com = reader.read_file(
-				base_path=folder, path=file,
-				content_class=Comment, context=context)
+            if hasattr(com, 'replyto'):
+                replies.append(com)
+            else:
+                comments.append(com)
 
-			if hasattr(com, 'replyto'):
-				replies.append( com )
-			else:
-				comments.append( com )
+    warn_on_slug_collision(comments + replies)
 
-	warn_on_slug_collision( comments + replies )
+    write_feed(gen, comments + replies, context, content.slug)
 
-	write_feed(gen, comments + replies, context, content.slug)
+    #TODO: Fix this O(n²) loop
+    for reply in replies:
+        for comment in chain(comments, replies):
+            if comment.slug == reply.replyto:
+                comment.addReply(reply)
 
-	#TODO: Fix this O(n²) loop
-	for reply in replies:
-		for comment in chain(comments, replies):
-			if comment.slug == reply.replyto:
-				comment.addReply(reply)
+    count = 0
+    for comment in comments:
+        comment.sortReplies()
+        count += comment.countReplies()
 
-	count = 0
-	for comment in comments:
-		comment.sortReplies()
-		count += comment.countReplies()
+    comments = sorted(comments)
 
-	comments = sorted(comments)
+    content.comments_count = len(comments) + count
+    content.comments = comments
 
-	content.comments_count = len(comments) + count
-	content.comments = comments
 
 def writeIdenticonsToDisk(gen, writer):
-	avatars.generateAndSaveMissingAvatars()
+    avatars.generateAndSaveMissingAvatars()
+
 
 def register():
-	signals.initialized.connect(pelican_initialized)
-	signals.article_generator_init.connect(initialize)
-	signals.article_generator_write_article.connect(add_static_comments)
-	signals.article_writer_finalized.connect(writeIdenticonsToDisk)
+    signals.initialized.connect(pelican_initialized)
+    signals.article_generator_init.connect(initialize)
+    signals.article_generator_write_article.connect(add_static_comments)
+    signals.article_writer_finalized.connect(writeIdenticonsToDisk)