plone.app.discussion/plone/app/discussion/conversation.py

438 lines
14 KiB
Python
Raw Permalink Normal View History

"""The conversation and replies adapters
The conversation is responsible for storing all comments. It provides a
dict-like API for accessing comments, where keys are integers and values
are IComment objects. It also provides features for finding comments quickly.
The two IReplies adapters - one for the IConversation and one for IComment -
manipulate the same data structures, but provide an API for finding and
manipulating the comments directly in reply to a particular comment or at the
top level of the conversation.
"""
from .comment import Comment
from .interfaces import DISCUSSION_ANNOTATION_KEY as ANNOTATION_KEY
from .interfaces import IConversation
from .interfaces import IReplies
2015-02-16 10:22:09 +01:00
from AccessControl.SpecialUsers import nobody as user_nobody
from Acquisition import aq_base
from Acquisition import aq_inner
from Acquisition import aq_parent
from Acquisition import Explicit
2015-02-16 10:22:09 +01:00
from BTrees.LLBTree import LLSet
from BTrees.LOBTree import LOBTree
from BTrees.OIBTree import OIBTree
from OFS.event import ObjectWillBeAddedEvent
from OFS.event import ObjectWillBeRemovedEvent
2015-02-16 10:22:09 +01:00
from OFS.Traversable import Traversable
from persistent import Persistent
from plone.base.interfaces import IHideFromBreadcrumbs
2015-02-16 10:22:09 +01:00
from zope.annotation.interfaces import IAnnotatable
from zope.annotation.interfaces import IAnnotations
from zope.component import adapter
from zope.container.contained import ContainerModifiedEvent
2015-02-16 10:22:09 +01:00
from zope.event import notify
from zope.interface import implementer
from zope.lifecycleevent import ObjectAddedEvent
2015-02-16 10:22:09 +01:00
from zope.lifecycleevent import ObjectCreatedEvent
from zope.lifecycleevent import ObjectRemovedEvent
2018-06-15 10:22:11 +02:00
import time
2018-01-25 13:04:11 +01:00
@implementer(IConversation, IHideFromBreadcrumbs)
class Conversation(Traversable, Persistent, Explicit):
"""A conversation is a container for all comments on a content object.
It manages internal data structures for comment threading and efficient
comment lookup.
"""
__allow_access_to_unprotected_subobjects__ = True
2022-05-01 23:14:09 +02:00
def __init__(self, id="++conversation++default"):
self.id = id
# username -> count of comments; key is removed when count reaches 0
self._commentators = OIBTree()
# id -> comment - find comment by id
self._comments = LOBTree()
# id -> LLSet (children) - find all children for a given comment.
# 0 signifies root.
self._children = LOBTree()
def getId(self):
"""Get the id of the conversation. This is used to construct a
URL.
"""
return self.id
def enabled(self):
parent = aq_inner(self.__parent__)
2022-05-01 23:14:09 +02:00
return parent.restrictedTraverse("@@conversation_view").enabled()
def total_comments(self):
2013-04-18 16:12:00 +02:00
public_comments = [
2022-05-01 23:14:09 +02:00
x for x in self.values() if user_nobody.has_permission("View", x)
2013-04-18 16:12:00 +02:00
]
return len(public_comments)
@property
def last_comment_date(self):
# self._comments is an Instance of a btree. The keys
# are always ordered
comment_keys = self._comments.keys()
for comment_key in reversed(comment_keys):
comment = self._comments[comment_key]
2022-05-01 23:14:09 +02:00
if user_nobody.has_permission("View", comment):
return comment.creation_date
return None
@property
def commentators(self):
return self._commentators
@property
def public_commentators(self):
retval = set()
for comment in self._comments.values():
2022-05-01 23:14:09 +02:00
if not user_nobody.has_permission("View", comment):
continue
retval.add(comment.author_username)
return tuple(retval)
def objectIds(self):
return self._comments.keys()
def getComments(self, start=0, size=None):
2022-05-01 23:14:09 +02:00
"""Get unthreaded comments"""
2018-01-25 13:04:11 +01:00
count = 0
for comment in self._comments.values(min=start):
# Yield the acquisition wrapped comment
yield self[comment.id]
count += 1
if size and count > size:
return
def getThreads(self, start=0, size=None, root=0, depth=None):
2022-05-01 23:14:09 +02:00
"""Get threaded comments"""
def recurse(comment_id, d=0):
# Yield the current comment before we look for its children
2022-05-01 23:14:09 +02:00
yield {"id": comment_id, "comment": self[comment_id], "depth": d}
# Recurse if there are children and we are not out of our depth
if depth is None or d + 1 < depth:
children = self._children.get(comment_id, None)
if children is not None:
for child_id in children:
yield from recurse(child_id, d + 1)
# Find top level threads
comments = self._children.get(root, None)
if comments is not None:
2018-01-25 13:04:11 +01:00
count = 0
for comment_id in comments.keys(min=start):
# Abort if we have found all the threads we want
count += 1
if size and count > size:
return
# Let the closure recurse
yield from recurse(comment_id)
def addComment(self, comment):
"""Add a new comment. The parent id should have been set already. The
comment id may be modified to find a free key. The id used will be
returned.
"""
# Make sure we don't have a wrapped object
comment = aq_base(comment)
2018-05-05 20:25:07 +02:00
id = int(time.time() * 1e6)
while id in self._comments:
id += 1
comment.comment_id = id
notify(ObjectWillBeAddedEvent(comment, self, id))
self._comments[id] = comment
comment.__parent__ = aq_base(self)
# Record unique users who've commented (for logged in users only)
commentator = comment.author_username
if commentator:
2015-05-03 08:25:08 +02:00
if commentator not in self._commentators:
self._commentators[commentator] = 0
self._commentators[commentator] += 1
reply_to = comment.in_reply_to
if not reply_to:
# top level comments are in reply to the faux id 0
comment.in_reply_to = reply_to = 0
2015-05-03 08:25:08 +02:00
if reply_to not in self._children:
self._children[reply_to] = LLSet()
self._children[reply_to].insert(id)
# Add the annotation if not already done
annotions = IAnnotations(self.__parent__)
2015-05-03 08:25:08 +02:00
if ANNOTATION_KEY not in annotions:
annotions[ANNOTATION_KEY] = aq_base(self)
# Notify that the object is added. The object must here be
# acquisition wrapped or the indexing will fail.
notify(ObjectCreatedEvent(comment))
notify(ObjectAddedEvent(comment.__of__(self), self, id))
notify(ContainerModifiedEvent(self))
return id
# Dict API
def __len__(self):
return len(self._comments)
def __contains__(self, key):
2018-05-05 20:25:07 +02:00
return int(key) in self._comments
def __getitem__(self, key):
2022-05-01 23:14:09 +02:00
"""Get an item by its int key"""
try:
2018-05-05 20:25:07 +02:00
comment_id = int(key)
except ValueError:
return
return self._comments[comment_id].__of__(self)
def __delitem__(self, key, suppress_container_modified=False):
2022-05-01 23:14:09 +02:00
"""Delete an item by its int key"""
2018-05-05 20:25:07 +02:00
key = int(key)
comment = self[key].__of__(self)
commentator = comment.author_username
notify(ObjectWillBeRemovedEvent(comment, self, key))
# Remove all children
for child_id in self._children.get(key, []):
# avoid sending ContainerModifiedEvent multiple times
self.__delitem__(child_id, suppress_container_modified=True)
# Remove the comment from _comments
self._comments.pop(key)
# Remove this comment as a child of its parent
if not suppress_container_modified:
parent = comment.in_reply_to
if parent is not None:
parent_children = self._children.get(parent, None)
if parent_children is not None and key in parent_children:
parent_children.remove(key)
# Remove commentators
if commentator and commentator in self._commentators:
if self._commentators[commentator] <= 1:
del self._commentators[commentator]
else:
self._commentators[commentator] -= 1
notify(ObjectRemovedEvent(comment, self, key))
if not suppress_container_modified:
notify(ContainerModifiedEvent(self))
def __iter__(self):
return iter(self._comments)
def get(self, key, default=None):
2018-05-05 20:25:07 +02:00
comment = self._comments.get(int(key), default)
if comment is default:
return default
return comment.__of__(self)
def keys(self):
return self._comments.keys()
def items(self):
2022-05-01 23:14:09 +02:00
return [
(
i[0],
i[1].__of__(self),
)
for i in self._comments.items()
]
def values(self):
return [v.__of__(self) for v in self._comments.values()]
def iterkeys(self):
return self._comments.keys()
def itervalues(self):
for v in self._comments.values():
yield v.__of__(self)
def iteritems(self):
for k, v in self._comments.items():
2022-05-01 23:14:09 +02:00
yield (
k,
v.__of__(self),
)
2015-09-13 18:31:38 +02:00
def allowedContentTypes(self):
return []
@implementer(IConversation)
@adapter(IAnnotatable)
def conversationAdapterFactory(content):
"""
Adapter factory to fetch the default conversation from annotations.
"""
annotations = IAnnotations(content)
2015-05-03 08:25:08 +02:00
if ANNOTATION_KEY not in annotations:
conversation = Conversation()
conversation.__parent__ = aq_base(content)
else:
conversation = annotations[ANNOTATION_KEY]
return conversation.__of__(content)
try:
from Products.LinguaPlone.interfaces import ITranslatable
except ImportError:
pass
else:
2022-05-01 23:14:09 +02:00
2012-01-14 07:13:39 +01:00
@implementer(IConversation) # pragma: no cover
@adapter(IAnnotatable) # pragma: no cover
def conversationCanonicalAdapterFactory(content): # pragma: no cover
"""Adapter factory to fetch the default conversation from annotations.
Will create the conversation if it does not exist.
This adapter will fetch and store all comments on the canonical object,
so that comments will be shared across all translations.
"""
if ITranslatable.providedBy(content):
canonical = content.getCanonical()
if canonical is not None:
return conversationAdapterFactory(canonical)
return conversationAdapterFactory(content)
@implementer(IReplies)
@adapter(Conversation) # relies on implementation details
class ConversationReplies:
"""An IReplies adapter for conversations.
This makes it easy to work with top-level comments.
"""
def __init__(self, context):
self.conversation = context
2018-01-25 13:04:11 +01:00
self.comment_id = 0
def addComment(self, comment):
comment.in_reply_to = None
return self.conversation.addComment(comment)
# Dict API
def __len__(self):
return len(self.children)
def __contains__(self, key):
2018-06-12 14:25:01 +02:00
return int(key) in self.children
def __getitem__(self, key):
2022-05-01 23:14:09 +02:00
"""Get an item by its int key"""
2018-06-12 14:25:01 +02:00
key = int(key)
if key not in self.children:
raise KeyError(key)
return self.conversation[key]
def __delitem__(self, key):
2022-05-01 23:14:09 +02:00
"""Delete an item by its int key"""
2018-06-12 14:25:01 +02:00
key = int(key)
if key not in self.children:
raise KeyError(key)
del self.conversation[key]
def __iter__(self):
return iter(self.children)
def get(self, key, default=None):
2018-06-12 14:25:01 +02:00
key = int(key)
if key not in self.children:
return default
return self.conversation.get(key)
def keys(self):
return self.children
def items(self):
return [(k, self.conversation[k]) for k in self.children]
def values(self):
return [self.conversation[k] for k in self.children]
def iterkeys(self):
return iter(self.children)
def itervalues(self):
for key in self.children:
yield self.conversation[key]
def iteritems(self):
for key in self.children:
2022-05-01 23:14:09 +02:00
yield (
key,
self.conversation[key],
)
@property
def children(self):
# we need to look this up every time, because we may not have a
# dict yet when the adapter is first created
return self.conversation._children.get(self.comment_id, LLSet())
2012-01-14 07:13:39 +01:00
@implementer(IReplies)
@adapter(Comment)
class CommentReplies(ConversationReplies):
"""An IReplies adapter for comments.
This makes it easy to work with replies to specific comments.
"""
# depends on implementation details of conversation
# most likely, anyone writing a different type of Conversation will also
# have a different type of Comment
def __init__(self, context):
self.comment = context
self.conversation = aq_parent(self.comment)
2013-04-18 16:12:00 +02:00
conversation_has_no_children = not hasattr(
self.conversation,
2022-05-01 23:14:09 +02:00
"_children",
2013-04-18 16:12:00 +02:00
)
if self.conversation is None or conversation_has_no_children:
2022-05-01 23:14:09 +02:00
raise TypeError(
"This adapter doesn't know what to do with the " "parent conversation"
)
self.comment_id = self.comment.comment_id
def addComment(self, comment):
comment.in_reply_to = self.comment_id
return self.conversation.addComment(comment)
# Dict API is inherited, written in terms of self.conversation and
# self.children