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'
8 async function processVideosViews () {
9 const lastHour = new Date()
11 // In test mode, we run this function multiple times per hour, so we don't want the values of the previous hour
12 if (!isTestInstance()) lastHour.setHours(lastHour.getHours() - 1)
14 const hour = lastHour.getHours()
15 const startDate = lastHour.setMinutes(0, 0, 0)
16 const endDate = lastHour.setMinutes(59, 59, 999)
18 const videoIds = await Redis.Instance.getVideosIdViewed(hour)
19 if (videoIds.length === 0) return
21 logger.info('Processing videos views in job for hour %d.', hour)
23 for (const videoId of videoIds) {
25 const views = await Redis.Instance.getVideoViews(videoId, hour)
27 logger.debug('Adding %d views to video %d in hour %d.', views, videoId, hour)
30 await VideoViewModel.create({
37 const video = await VideoModel.loadAndPopulateAccountAndServerAndTags(videoId)
38 if (video.isOwned()) {
39 // If this is a remote video, the origin instance will send us an update
40 await VideoModel.incrementViews(videoId, views)
44 await federateVideoIfNeeded(video, false)
47 logger.debug('Cannot create video views for video %d in hour %d. Maybe the video does not exist anymore?', videoId, hour)
51 await Redis.Instance.deleteVideoViews(videoId, hour)
53 logger.error('Cannot update video views of video %d in hour %d.', videoId, hour)
58 // ---------------------------------------------------------------------------