]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blame - server/lib/job-queue/handlers/video-views-stats.ts
Fix import timeout inconsistency
[github/Chocobozzz/PeerTube.git] / server / lib / job-queue / handlers / video-views-stats.ts
CommitLineData
51353d9a 1import { isTestInstance } from '../../../helpers/core-utils'
6b616860
C
2import { logger } from '../../../helpers/logger'
3import { VideoModel } from '../../../models/video/video'
fd261a8d 4import { VideoViewModel } from '../../../models/video/video-view'
51353d9a 5import { Redis } from '../../redis'
6b616860 6
51353d9a 7async function processVideosViewsStats () {
6f0c46be
C
8 const lastHour = new Date()
9
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 (!isTestInstance()) lastHour.setHours(lastHour.getHours() - 1)
12
13 const hour = lastHour.getHours()
14 const startDate = lastHour.setMinutes(0, 0, 0)
15 const endDate = lastHour.setMinutes(59, 59, 999)
6b616860 16
51353d9a 17 const videoIds = await Redis.Instance.listVideosViewedForStats(hour)
6b616860
C
18 if (videoIds.length === 0) return
19
51353d9a 20 logger.info('Processing videos views stats in job for hour %d.', hour)
6b616860
C
21
22 for (const videoId of videoIds) {
9431cabf 23 try {
51353d9a
C
24 const views = await Redis.Instance.getVideoViewsStats(videoId, hour)
25 await Redis.Instance.deleteVideoViewsStats(videoId, hour)
ca6d3622 26
6040f87d 27 if (views) {
51353d9a 28 logger.debug('Adding %d views to video %d stats in hour %d.', views, videoId, hour)
9431cabf 29
9431cabf 30 try {
51353d9a 31 const video = await VideoModel.load(videoId)
63dc5898 32 if (!video) {
51353d9a 33 logger.debug('Video %d does not exist anymore, skipping videos view stats.', videoId)
63dc5898
C
34 continue
35 }
36
9431cabf 37 await VideoViewModel.create({
16c016e8
C
38 startDate: new Date(startDate),
39 endDate: new Date(endDate),
9431cabf
C
40 views,
41 videoId
42 })
43 } catch (err) {
51353d9a 44 logger.error('Cannot create video views stats for video %d in hour %d.', videoId, hour, { err })
9431cabf
C
45 }
46 }
9431cabf 47 } catch (err) {
51353d9a 48 logger.error('Cannot update video views stats of video %d in hour %d.', videoId, hour, { err })
6b616860 49 }
6b616860
C
50 }
51}
52
53// ---------------------------------------------------------------------------
54
55export {
51353d9a 56 processVideosViewsStats
6b616860 57}