comment.py 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. import html
  2. from db import db
  3. from db import Comment, User, Video
  4. from user import get_authorized_user
  5. from video import find_video_by_id
  6. from tools import parse_offset, validate_text
  7. async def get_comments(video_id, offset=0):
  8. video = await find_video_by_id(video_id)
  9. comments = await db.execute(Comment
  10. .select(Comment, User)
  11. .join(User)
  12. .switch(Comment)
  13. .join(Video)
  14. .where(
  15. (Video.id == video.id) &
  16. (~Comment.is_hidden)
  17. )
  18. .order_by(Comment.publish_date.desc())
  19. .offset(parse_offset(offset))
  20. .limit(5))
  21. return [
  22. {
  23. 'id': comment.id,
  24. 'author_id': comment.user.id,
  25. 'publish_ts': int(comment.publish_date.timestamp()),
  26. 'text': html.escape(comment.text)
  27. } for comment in comments
  28. ]
  29. async def get_comments_count(video_id):
  30. video = await find_video_by_id(video_id)
  31. return await db.count(Comment
  32. .select()
  33. .join(Video)
  34. .where(
  35. (Video.id == video.id) &
  36. (~Comment.is_hidden)
  37. ))
  38. async def post_comment(session, video_id, text):
  39. user = await get_authorized_user(session)
  40. video = await find_video_by_id(video_id)
  41. text = validate_text(text)
  42. return await db.create(Comment,
  43. text=text,
  44. user=user,
  45. video=video)