1 import express from 'express'
2 import { param, query } from 'express-validator'
3 import { isDateValid } from '@server/helpers/custom-validators/misc'
4 import { isValidStatTimeserieMetric } from '@server/helpers/custom-validators/video-stats'
5 import { STATS_TIMESERIE } from '@server/initializers/constants'
6 import { HttpStatusCode, UserRight, VideoStatsTimeserieQuery } from '@shared/models'
7 import { areValidationErrors, checkUserCanManageVideo, doesVideoExist, isValidVideoIdParam } from '../shared'
9 const videoOverallStatsValidator = [
10 isValidVideoIdParam('videoId'),
20 async (req: express.Request, res: express.Response, next: express.NextFunction) => {
21 if (areValidationErrors(req, res)) return
22 if (!await commonStatsCheck(req, res)) return
28 const videoRetentionStatsValidator = [
29 isValidVideoIdParam('videoId'),
31 async (req: express.Request, res: express.Response, next: express.NextFunction) => {
32 if (areValidationErrors(req, res)) return
33 if (!await commonStatsCheck(req, res)) return
35 if (res.locals.videoAll.isLive) {
37 status: HttpStatusCode.BAD_REQUEST_400,
38 message: 'Cannot get retention stats of live video'
46 const videoTimeserieStatsValidator = [
47 isValidVideoIdParam('videoId'),
50 .custom(isValidStatTimeserieMetric),
60 async (req: express.Request, res: express.Response, next: express.NextFunction) => {
61 if (areValidationErrors(req, res)) return
62 if (!await commonStatsCheck(req, res)) return
64 const query: VideoStatsTimeserieQuery = req.query
66 (query.startDate && !query.endDate) ||
67 (!query.startDate && query.endDate)
70 status: HttpStatusCode.BAD_REQUEST_400,
71 message: 'Both start date and end date should be defined if one of them is specified'
75 if (query.startDate && getIntervalByDays(query.startDate, query.endDate) > STATS_TIMESERIE.MAX_DAYS) {
77 status: HttpStatusCode.BAD_REQUEST_400,
78 message: 'Star date and end date interval is too big'
86 // ---------------------------------------------------------------------------
89 videoOverallStatsValidator,
90 videoTimeserieStatsValidator,
91 videoRetentionStatsValidator
94 // ---------------------------------------------------------------------------
96 async function commonStatsCheck (req: express.Request, res: express.Response) {
97 if (!await doesVideoExist(req.params.videoId, res, 'all')) return false
98 if (!checkUserCanManageVideo(res.locals.oauth.token.User, res.locals.videoAll, UserRight.SEE_ALL_VIDEOS, res)) return false
103 function getIntervalByDays (startDateString: string, endDateString: string) {
104 const startDate = new Date(startDateString)
105 const endDate = new Date(endDateString)
107 return (endDate.getTime() - startDate.getTime()) / 1000 / 86400