3616c074d35c378a7b434aef4e0a7eeb0389a421
[oweals/peertube.git] / server / controllers / api / server / stats.ts
1 import * as express from 'express'
2 import { ServerStats } from '../../../../shared/models/server/server-stats.model'
3 import { asyncMiddleware } from '../../../middlewares'
4 import { UserModel } from '../../../models/account/user'
5 import { ActorFollowModel } from '../../../models/activitypub/actor-follow'
6 import { VideoModel } from '../../../models/video/video'
7 import { VideoCommentModel } from '../../../models/video/video-comment'
8 import { VideoRedundancyModel } from '../../../models/redundancy/video-redundancy'
9 import { ROUTE_CACHE_LIFETIME } from '../../../initializers/constants'
10 import { cacheRoute } from '../../../middlewares/cache'
11 import { VideoFileModel } from '../../../models/video/video-file'
12 import { CONFIG } from '../../../initializers/config'
13
14 const statsRouter = express.Router()
15
16 statsRouter.get('/stats',
17   asyncMiddleware(cacheRoute()(ROUTE_CACHE_LIFETIME.STATS)),
18   asyncMiddleware(getStats)
19 )
20
21 async function getStats (req: express.Request, res: express.Response) {
22   const { totalLocalVideos, totalLocalVideoViews, totalVideos } = await VideoModel.getStats()
23   const { totalLocalVideoComments, totalVideoComments } = await VideoCommentModel.getStats()
24   const { totalUsers } = await UserModel.getStats()
25   const { totalInstanceFollowers, totalInstanceFollowing } = await ActorFollowModel.getStats()
26   const { totalLocalVideoFilesSize } = await VideoFileModel.getStats()
27
28   const videosRedundancyStats = await Promise.all(
29     CONFIG.REDUNDANCY.VIDEOS.STRATEGIES.map(r => {
30       return VideoRedundancyModel.getStats(r.strategy)
31         .then(stats => Object.assign(stats, { strategy: r.strategy, totalSize: r.size }))
32     })
33   )
34
35   const data: ServerStats = {
36     totalLocalVideos,
37     totalLocalVideoViews,
38     totalLocalVideoFilesSize,
39     totalLocalVideoComments,
40     totalVideos,
41     totalVideoComments,
42     totalUsers,
43     totalInstanceFollowers,
44     totalInstanceFollowing,
45     videosRedundancy: videosRedundancyStats
46   }
47
48   return res.json(data).end()
49 }
50
51 // ---------------------------------------------------------------------------
52
53 export {
54   statsRouter
55 }