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-view'
  5. import { isTestInstance } from '../../../helpers/core-utils'
  6. import { federateVideoIfNeeded } from '../../activitypub/videos'
  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. await Redis.Instance.deleteVideoViews(videoId, hour)
  21. if (views) {
  22. logger.debug('Adding %d views to video %d in hour %d.', views, videoId, hour)
  23. try {
  24. const video = await VideoModel.loadAndPopulateAccountAndServerAndTags(videoId)
  25. if (!video) {
  26. logger.debug('Video %d does not exist anymore, skipping videos view addition.', videoId)
  27. continue
  28. }
  29. await VideoViewModel.create({
  30. startDate,
  31. endDate,
  32. views,
  33. videoId
  34. })
  35. if (video.isOwned()) {
  36. // If this is a remote video, the origin instance will send us an update
  37. await VideoModel.incrementViews(videoId, views)
  38. // Send video update
  39. video.views += views
  40. await federateVideoIfNeeded(video, false)
  41. }
  42. } catch (err) {
  43. logger.error('Cannot create video views for video %d in hour %d.', videoId, hour, { err })
  44. }
  45. }
  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. }