2016-04-24 07:50:11 +00:00
|
|
|
import datetime
|
|
|
|
from szurubooru import db, errors
|
2016-04-24 14:34:06 +00:00
|
|
|
from szurubooru.func import users, posts, scores
|
2016-04-24 07:50:11 +00:00
|
|
|
|
|
|
|
class CommentNotFoundError(errors.NotFoundError): pass
|
|
|
|
class EmptyCommentTextError(errors.ValidationError): pass
|
|
|
|
|
|
|
|
def serialize_comment(comment, authenticated_user):
|
2016-04-24 14:34:06 +00:00
|
|
|
ret = {
|
2016-04-24 07:50:11 +00:00
|
|
|
'id': comment.comment_id,
|
|
|
|
'user': users.serialize_user(comment.user, authenticated_user),
|
|
|
|
'post': posts.serialize_post(comment.post, authenticated_user),
|
|
|
|
'text': comment.text,
|
|
|
|
'creationTime': comment.creation_time,
|
|
|
|
'lastEditTime': comment.last_edit_time,
|
|
|
|
}
|
2016-04-24 14:34:06 +00:00
|
|
|
if authenticated_user:
|
|
|
|
ret['ownScore'] = scores.get_score(comment, authenticated_user)
|
|
|
|
return ret
|
2016-04-24 07:50:11 +00:00
|
|
|
|
2016-04-28 16:20:50 +00:00
|
|
|
def serialize_comment_with_details(comment, authenticated_user):
|
|
|
|
return {'comment': serialize_comment(comment, authenticated_user)}
|
|
|
|
|
2016-04-24 12:24:41 +00:00
|
|
|
def try_get_comment_by_id(comment_id):
|
2016-04-24 08:13:22 +00:00
|
|
|
return db.session \
|
|
|
|
.query(db.Comment) \
|
|
|
|
.filter(db.Comment.comment_id == comment_id) \
|
|
|
|
.one_or_none()
|
|
|
|
|
2016-04-24 12:24:41 +00:00
|
|
|
def get_comment_by_id(comment_id):
|
|
|
|
comment = try_get_comment_by_id(comment_id)
|
|
|
|
if comment:
|
|
|
|
return comment
|
|
|
|
raise CommentNotFoundError('Comment %r not found.' % comment_id)
|
|
|
|
|
2016-04-24 07:50:11 +00:00
|
|
|
def create_comment(user, post, text):
|
|
|
|
comment = db.Comment()
|
|
|
|
comment.user = user
|
|
|
|
comment.post = post
|
|
|
|
update_comment_text(comment, text)
|
|
|
|
comment.creation_time = datetime.datetime.now()
|
|
|
|
return comment
|
|
|
|
|
|
|
|
def update_comment_text(comment, text):
|
|
|
|
if not text:
|
|
|
|
raise EmptyCommentTextError('Comment text cannot be empty.')
|
|
|
|
comment.text = text
|