]>
Commit | Line | Data |
---|---|---|
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' | |
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 (!isTestOrDevInstance()) 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 | } |