util.py 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. import datetime
  2. import humanize
  3. import re
  4. # given amount of seconds makes it into this 54 MINUTES AND 53 SECONDS (from humanize) then
  5. # perform a bunch of replace operations to make it look like 54mins. 53secs.
  6. from django.db.models import Q
  7. def getHumanizedTimeString(seconds):
  8. return humanize.precisedelta(
  9. datetime.timedelta(seconds=seconds)).upper(). \
  10. replace(" month".upper(), "m.").replace(" months".upper(), "m.").replace(" days".upper(), "d.").replace(
  11. " day".upper(), "d.").replace(" hours".upper(), "hrs.").replace(" hour".upper(), "hr.").replace(
  12. " minutes".upper(), "mins.").replace(" minute".upper(), "min.").replace(
  13. "and".upper(), "").replace(" seconds".upper(), "secs.").replace(" second".upper(), "sec.").replace(",", "")
  14. # input => ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10", ..., "100"] <- array of 100 video ids
  15. # output => ["1,2,3,4,...,50", "51,52,53,...,100"] <- array of 2 video id strings, each with upto 50 comma sperated video ids
  16. def getVideoIdsStrings(video_ids):
  17. output = []
  18. i = 0
  19. while i < len(video_ids):
  20. output.append(",".join(video_ids[i:i + 50]))
  21. i += 50
  22. return output
  23. # input: array of youtube video duration strings => ["24M23S", "2H2M2S", ...]
  24. # output:integer => seconds
  25. def calculateDuration(vid_durations):
  26. hours_pattern = re.compile(r'(\d+)H')
  27. minutes_pattern = re.compile(r'(\d+)M')
  28. seconds_pattern = re.compile(r'(\d+)S')
  29. total_seconds = 0
  30. for duration in vid_durations:
  31. hours = hours_pattern.search(duration) # returns matches in the form "24H"
  32. mins = minutes_pattern.search(duration) # "24M"
  33. secs = seconds_pattern.search(duration) # "24S"
  34. hours = int(hours.group(1)) if hours else 0 # returns 24
  35. mins = int(mins.group(1)) if mins else 0
  36. secs = int(secs.group(1)) if secs else 0
  37. video_seconds = datetime.timedelta(
  38. hours=hours,
  39. minutes=mins,
  40. seconds=secs
  41. ).total_seconds()
  42. total_seconds += video_seconds
  43. return total_seconds
  44. def getThumbnailURL(thumbnails):
  45. priority = ("maxres", "standard", "high", "medium", "default")
  46. for quality in priority:
  47. if quality in thumbnails:
  48. return thumbnails[quality]["url"]
  49. return ''
  50. # generates a message in the form of "1 / 19 watched! 31mins. 15secs. left to go!"
  51. def generateWatchingMessage(playlist):
  52. """
  53. This is the message that will be seen when a playlist is set to watching.
  54. Takes in the playlist object and calculates the watch time left by looping over unwatched video
  55. and using their durations
  56. """
  57. pass