diff options
Diffstat (limited to 'server/lib/job-queue/handlers/video-views-stats.ts')
-rw-r--r-- | server/lib/job-queue/handlers/video-views-stats.ts | 57 |
1 files changed, 57 insertions, 0 deletions
diff --git a/server/lib/job-queue/handlers/video-views-stats.ts b/server/lib/job-queue/handlers/video-views-stats.ts new file mode 100644 index 000000000..caf5f6962 --- /dev/null +++ b/server/lib/job-queue/handlers/video-views-stats.ts | |||
@@ -0,0 +1,57 @@ | |||
1 | import { isTestInstance } from '../../../helpers/core-utils' | ||
2 | import { logger } from '../../../helpers/logger' | ||
3 | import { VideoModel } from '../../../models/video/video' | ||
4 | import { VideoViewModel } from '../../../models/video/video-view' | ||
5 | import { Redis } from '../../redis' | ||
6 | |||
7 | async function processVideosViewsStats () { | ||
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) | ||
16 | |||
17 | const videoIds = await Redis.Instance.listVideosViewedForStats(hour) | ||
18 | if (videoIds.length === 0) return | ||
19 | |||
20 | logger.info('Processing videos views stats in job for hour %d.', hour) | ||
21 | |||
22 | for (const videoId of videoIds) { | ||
23 | try { | ||
24 | const views = await Redis.Instance.getVideoViewsStats(videoId, hour) | ||
25 | await Redis.Instance.deleteVideoViewsStats(videoId, hour) | ||
26 | |||
27 | if (views) { | ||
28 | logger.debug('Adding %d views to video %d stats in hour %d.', views, videoId, hour) | ||
29 | |||
30 | try { | ||
31 | const video = await VideoModel.load(videoId) | ||
32 | if (!video) { | ||
33 | logger.debug('Video %d does not exist anymore, skipping videos view stats.', videoId) | ||
34 | continue | ||
35 | } | ||
36 | |||
37 | await VideoViewModel.create({ | ||
38 | startDate: new Date(startDate), | ||
39 | endDate: new Date(endDate), | ||
40 | views, | ||
41 | videoId | ||
42 | }) | ||
43 | } catch (err) { | ||
44 | logger.error('Cannot create video views stats for video %d in hour %d.', videoId, hour, { err }) | ||
45 | } | ||
46 | } | ||
47 | } catch (err) { | ||
48 | logger.error('Cannot update video views stats of video %d in hour %d.', videoId, hour, { err }) | ||
49 | } | ||
50 | } | ||
51 | } | ||
52 | |||
53 | // --------------------------------------------------------------------------- | ||
54 | |||
55 | export { | ||
56 | processVideosViewsStats | ||
57 | } | ||