video-views.ts 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. import { Redis } from '../../redis'
  2. import { logger } from '../../../helpers/logger'
  3. import { VideoModel } from '../../../models/video/video'
  4. import { VideoViewModel } from '../../../models/video/video-views'
  5. import { isTestInstance } from '../../../helpers/core-utils'
  6. import { federateVideoIfNeeded } from '../../activitypub'
  7. async function processVideosViews () {
  8. const lastHour = new Date()
  9. // In test mode, we run this function multiple times per hour, so we don't want the values of the previous hour
  10. if (!isTestInstance()) lastHour.setHours(lastHour.getHours() - 1)
  11. const hour = lastHour.getHours()
  12. const startDate = lastHour.setMinutes(0, 0, 0)
  13. const endDate = lastHour.setMinutes(59, 59, 999)
  14. const videoIds = await Redis.Instance.getVideosIdViewed(hour)
  15. if (videoIds.length === 0) return
  16. logger.info('Processing videos views in job for hour %d.', hour)
  17. for (const videoId of videoIds) {
  18. try {
  19. const views = await Redis.Instance.getVideoViews(videoId, hour)
  20. if (views) {
  21. logger.debug('Adding %d views to video %d in hour %d.', views, videoId, hour)
  22. try {
  23. const video = await VideoModel.loadAndPopulateAccountAndServerAndTags(videoId)
  24. if (!video) {
  25. logger.debug('Video %d does not exist anymore, skipping videos view addition.', videoId)
  26. continue
  27. }
  28. await VideoViewModel.create({
  29. startDate,
  30. endDate,
  31. views,
  32. videoId
  33. })
  34. if (video.isOwned()) {
  35. // If this is a remote video, the origin instance will send us an update
  36. await VideoModel.incrementViews(videoId, views)
  37. // Send video update
  38. video.views += views
  39. await federateVideoIfNeeded(video, false)
  40. }
  41. } catch (err) {
  42. logger.error('Cannot create video views for video %d in hour %d.', videoId, hour, { err })
  43. }
  44. }
  45. await Redis.Instance.deleteVideoViews(videoId, hour)
  46. } catch (err) {
  47. logger.error('Cannot update video views of video %d in hour %d.', videoId, hour, { err })
  48. }
  49. }
  50. }
  51. // ---------------------------------------------------------------------------
  52. export {
  53. processVideosViews
  54. }