1 import { VideoViewModel } from '@server/models/view/video-view'
2 import { isTestOrDevInstance } from '../../../helpers/core-utils'
3 import { logger } from '../../../helpers/logger'
4 import { VideoModel } from '../../../models/video/video'
5 import { Redis } from '../../redis'
7 async function processVideosViewsStats () {
8 const lastHour = new Date()
10 // In test mode, we run this function multiple times per hour, so we don't want the values of the previous hour
11 if (!isTestOrDevInstance()) lastHour.setHours(lastHour.getHours() - 1)
13 const hour = lastHour.getHours()
14 const startDate = lastHour.setMinutes(0, 0, 0)
15 const endDate = lastHour.setMinutes(59, 59, 999)
17 const videoIds = await Redis.Instance.listVideosViewedForStats(hour)
18 if (videoIds.length === 0) return
20 logger.info('Processing videos views stats in job for hour %d.', hour)
22 for (const videoId of videoIds) {
24 const views = await Redis.Instance.getVideoViewsStats(videoId, hour)
25 await Redis.Instance.deleteVideoViewsStats(videoId, hour)
28 logger.debug('Adding %d views to video %d stats in hour %d.', views, videoId, hour)
31 const video = await VideoModel.load(videoId)
33 logger.debug('Video %d does not exist anymore, skipping videos view stats.', videoId)
37 await VideoViewModel.create({
38 startDate: new Date(startDate),
39 endDate: new Date(endDate),
44 logger.error('Cannot create video views stats for video %d in hour %d.', videoId, hour, { err })
48 logger.error('Cannot update video views stats of video %d in hour %d.', videoId, hour, { err })
53 // ---------------------------------------------------------------------------
56 processVideosViewsStats