mirror of https://gitlab.com/tildes/tildes.git
You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
79 lines
2.8 KiB
79 lines
2.8 KiB
# Copyright (c) 2018 Tildes contributors <code@tildes.net>
|
|
# SPDX-License-Identifier: AGPL-3.0-or-later
|
|
|
|
"""JSON API helper functions related to comments."""
|
|
|
|
from pyramid.request import Request
|
|
from tildes.models.comment import Comment
|
|
from tildes.models.comment.comment_tree import CommentInTree
|
|
|
|
|
|
def comment_to_dict(request: Request, comment: Comment) -> dict:
|
|
"""Convert a Comment object to a dictionary for JSON serialization."""
|
|
|
|
# Check permissions for viewing comment details (and set safe defaults)
|
|
author = None
|
|
rendered_html = None
|
|
exemplary = None
|
|
by_op = None
|
|
by_me = None
|
|
is_new_comment = None
|
|
if request.has_permission("view", comment):
|
|
author = comment.user.username
|
|
rendered_html = comment.rendered_html
|
|
exemplary = comment.is_label_active("exemplary")
|
|
by_me = request.user == comment.user if request.user else False
|
|
if request.has_permission("view_author", comment.topic):
|
|
by_op = comment.user == comment.topic.user
|
|
is_new_comment = (
|
|
(comment.created_time > comment.topic.last_visit_time)
|
|
if (
|
|
hasattr(comment.topic, "last_visit_time")
|
|
and comment.topic.last_visit_time
|
|
and not by_me
|
|
)
|
|
else False
|
|
)
|
|
|
|
return {
|
|
"id": comment.comment_id36,
|
|
"topic_id": comment.topic.topic_id36,
|
|
"author": author,
|
|
"rendered_html": rendered_html,
|
|
"created_at": comment.created_time.isoformat(),
|
|
"edited_at": (
|
|
comment.last_edited_time.isoformat() if comment.last_edited_time else None
|
|
),
|
|
"votes": comment.num_votes,
|
|
"removed": comment.is_removed,
|
|
"deleted": comment.is_deleted,
|
|
"exemplary": exemplary,
|
|
"collapsed": (
|
|
(comment.collapsed_state == "full")
|
|
if hasattr(comment, "collapsed_state")
|
|
else None
|
|
),
|
|
"collapsed_individual": (
|
|
(comment.collapsed_state == "individual")
|
|
if hasattr(comment, "collapsed_state")
|
|
else None
|
|
),
|
|
"by_op": by_op,
|
|
"by_me": by_me,
|
|
"new_comment": is_new_comment,
|
|
"voted": comment.user_voted,
|
|
"bookmarked": comment.user_bookmarked,
|
|
}
|
|
|
|
|
|
def comment_subtree_to_dict(request: Request, comments: list[CommentInTree]) -> list:
|
|
"""Convert a comment subtree to a list of dictionaries for JSON serialization."""
|
|
comments_list = []
|
|
for comment in comments:
|
|
comment_dict = comment_to_dict(request, comment)
|
|
comment_dict["depth"] = comment.depth
|
|
comment_dict["children"] = (
|
|
comment_subtree_to_dict(request, comment.replies) if comment.replies else []
|
|
)
|
|
comments_list.append(comment_dict)
|
|
return comments_list
|