video.py 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. import html
  2. from hashlib import sha1
  3. from peewee import fn
  4. from aiofiles.tempfile import NamedTemporaryFile
  5. from db import db
  6. from db import Video, User, Like, Tag, VideoTag
  7. from tools import parse_tags, parse_offset
  8. from tools import probe_video, create_preview
  9. from tools import save_content
  10. class VideoError(Exception): pass
  11. async def find_video_by_id(video_id):
  12. try:
  13. video_id = int(video_id)
  14. video_id = abs(video_id)
  15. except ValueError:
  16. raise VideoError('illegal video_id')
  17. try:
  18. return await db.get(Video
  19. .select(Video, User)
  20. .join(User)
  21. .switch(Video)
  22. .where(
  23. (Video.id == video_id) &
  24. (~Video.is_hidden)
  25. ))
  26. except Video.DoesNotExist:
  27. raise VideoError('video is unavailable or doesn\'t exist')
  28. async def get_tags(video_id):
  29. video = await find_video_by_id(video_id)
  30. tags = await db.execute(Tag
  31. .select()
  32. .join(VideoTag)
  33. .join(Video)
  34. .where(Video.id == video.id))
  35. return [tag.tag for tag in tags]
  36. async def get_likes(video_id):
  37. video = await find_video_by_id(video_id)
  38. return await db.count(Like
  39. .select(Like, Video)
  40. .join(Video)
  41. .switch(Like)
  42. .where(Like.video.id == video.id))
  43. async def get_random_video():
  44. return await db.get(Video
  45. .select(Video, User)
  46. .join(User)
  47. .switch(Video)
  48. .order_by(fn.Random())
  49. .limit(1))
  50. async def serialize_video(video):
  51. return {
  52. 'id': video.id,
  53. 'upload_ts': int(video.upload_date.timestamp()),
  54. 'thumbnail': video.thumbnail,
  55. 'uploader_id': video.uploader.id,
  56. 'likes_count': await get_likes(video.id),
  57. 'tags_list': await get_tags(video.id)
  58. }