2016-04-24 07:50:11 +00:00
|
|
|
import datetime
|
|
|
|
from szurubooru import db, errors
|
2016-05-30 20:07:44 +00:00
|
|
|
from szurubooru.func import users, scores, util
|
2016-04-24 07:50:11 +00:00
|
|
|
|
2016-08-14 09:43:19 +00:00
|
|
|
class InvalidCommentIdError(errors.ValidationError): pass
|
2016-04-24 07:50:11 +00:00
|
|
|
class CommentNotFoundError(errors.NotFoundError): pass
|
|
|
|
class EmptyCommentTextError(errors.ValidationError): pass
|
|
|
|
|
2016-08-14 08:53:19 +00:00
|
|
|
def serialize_comment(comment, auth_user, options=None):
|
2016-05-30 20:07:44 +00:00
|
|
|
return util.serialize_entity(
|
|
|
|
comment,
|
|
|
|
{
|
|
|
|
'id': lambda: comment.comment_id,
|
2016-08-14 08:53:19 +00:00
|
|
|
'user': lambda: users.serialize_micro_user(comment.user, auth_user),
|
2016-05-30 20:07:44 +00:00
|
|
|
'postId': lambda: comment.post.post_id,
|
2016-08-06 19:16:39 +00:00
|
|
|
'version': lambda: comment.version,
|
2016-05-30 20:07:44 +00:00
|
|
|
'text': lambda: comment.text,
|
|
|
|
'creationTime': lambda: comment.creation_time,
|
|
|
|
'lastEditTime': lambda: comment.last_edit_time,
|
2016-06-11 07:29:23 +00:00
|
|
|
'score': lambda: comment.score,
|
2016-08-14 08:53:19 +00:00
|
|
|
'ownScore': lambda: scores.get_score(comment, auth_user),
|
2016-05-30 21:08:22 +00:00
|
|
|
},
|
|
|
|
options)
|
2016-04-28 16:20:50 +00:00
|
|
|
|
2016-04-24 12:24:41 +00:00
|
|
|
def try_get_comment_by_id(comment_id):
|
2016-08-14 09:43:19 +00:00
|
|
|
try:
|
|
|
|
comment_id = int(comment_id)
|
|
|
|
except ValueError:
|
|
|
|
raise InvalidCommentIdError('Invalid comment ID: %r.' % 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)
|
2016-07-03 12:46:15 +00:00
|
|
|
comment.creation_time = datetime.datetime.utcnow()
|
2016-04-24 07:50:11 +00:00
|
|
|
return comment
|
|
|
|
|
|
|
|
def update_comment_text(comment, text):
|
2016-08-14 08:45:00 +00:00
|
|
|
assert comment
|
2016-04-24 07:50:11 +00:00
|
|
|
if not text:
|
|
|
|
raise EmptyCommentTextError('Comment text cannot be empty.')
|
|
|
|
comment.text = text
|