aboutsummaryrefslogtreecommitdiffhomepage
path: root/server/controllers/api/videos/stats.ts
blob: 71452d9f00156f74d123056e68e8ce3285bc885e (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
import express from 'express'
import { LocalVideoViewerModel } from '@server/models/view/local-video-viewer'
import { VideoStatsTimeserieMetric, VideoStatsTimeserieQuery } from '@shared/models'
import {
  asyncMiddleware,
  authenticate,
  videoOverallStatsValidator,
  videoRetentionStatsValidator,
  videoTimeserieStatsValidator
} from '../../../middlewares'

const statsRouter = express.Router()

statsRouter.get('/:videoId/stats/overall',
  authenticate,
  asyncMiddleware(videoOverallStatsValidator),
  asyncMiddleware(getOverallStats)
)

statsRouter.get('/:videoId/stats/timeseries/:metric',
  authenticate,
  asyncMiddleware(videoTimeserieStatsValidator),
  asyncMiddleware(getTimeserieStats)
)

statsRouter.get('/:videoId/stats/retention',
  authenticate,
  asyncMiddleware(videoRetentionStatsValidator),
  asyncMiddleware(getRetentionStats)
)

// ---------------------------------------------------------------------------

export {
  statsRouter
}

// ---------------------------------------------------------------------------

async function getOverallStats (req: express.Request, res: express.Response) {
  const video = res.locals.videoAll

  const stats = await LocalVideoViewerModel.getOverallStats(video)

  return res.json(stats)
}

async function getRetentionStats (req: express.Request, res: express.Response) {
  const video = res.locals.videoAll

  const stats = await LocalVideoViewerModel.getRetentionStats(video)

  return res.json(stats)
}

async function getTimeserieStats (req: express.Request, res: express.Response) {
  const video = res.locals.videoAll
  const metric = req.params.metric as VideoStatsTimeserieMetric

  const query = req.query as VideoStatsTimeserieQuery

  const stats = await LocalVideoViewerModel.getTimeserieStats({
    video,
    metric,
    startDate: query.startDate ?? buildOneMonthAgo().toISOString(),
    endDate: query.endDate ?? new Date().toISOString()
  })

  return res.json(stats)
}

function buildOneMonthAgo () {
  const monthAgo = new Date()
  monthAgo.setHours(0, 0, 0, 0)

  monthAgo.setDate(monthAgo.getDate() - 29)

  return monthAgo
}