Support roles with rights and add moderator role
[oweals/peertube.git] / server / helpers / utils.ts
1 import * as express from 'express'
2 import * as Sequelize from 'sequelize'
3
4 import { pseudoRandomBytesPromise } from './core-utils'
5 import { CONFIG, database as db } from '../initializers'
6 import { ResultList } from '../../shared'
7 import { VideoResolution } from '../../shared/models/videos/video-resolution.enum'
8
9 function badRequest (req: express.Request, res: express.Response, next: express.NextFunction) {
10   return res.type('json').status(400).end()
11 }
12
13 async function generateRandomString (size: number) {
14   const raw = await pseudoRandomBytesPromise(size)
15
16   return raw.toString('hex')
17 }
18
19 interface FormattableToJSON {
20   toFormattedJSON ()
21 }
22
23 function getFormattedObjects<U, T extends FormattableToJSON> (objects: T[], objectsTotal: number) {
24   const formattedObjects: U[] = []
25
26   objects.forEach(object => {
27     formattedObjects.push(object.toFormattedJSON())
28   })
29
30   const res: ResultList<U> = {
31     total: objectsTotal,
32     data: formattedObjects
33   }
34
35   return res
36 }
37
38 async function isSignupAllowed () {
39   if (CONFIG.SIGNUP.ENABLED === false) {
40     return false
41   }
42
43   // No limit and signup is enabled
44   if (CONFIG.SIGNUP.LIMIT === -1) {
45     return true
46   }
47
48   const totalUsers = await db.User.countTotal()
49
50   return totalUsers < CONFIG.SIGNUP.LIMIT
51 }
52
53 function computeResolutionsToTranscode (videoFileHeight: number) {
54   const resolutionsEnabled: number[] = []
55   const configResolutions = CONFIG.TRANSCODING.RESOLUTIONS
56
57   const resolutions = [
58     VideoResolution.H_240P,
59     VideoResolution.H_360P,
60     VideoResolution.H_480P,
61     VideoResolution.H_720P,
62     VideoResolution.H_1080P
63   ]
64
65   for (const resolution of resolutions) {
66     if (configResolutions[resolution.toString()] === true && videoFileHeight > resolution) {
67       resolutionsEnabled.push(resolution)
68     }
69   }
70
71   return resolutionsEnabled
72 }
73
74 function resetSequelizeInstance (instance: Sequelize.Instance<any>, savedFields: object) {
75   Object.keys(savedFields).forEach(key => {
76     const value = savedFields[key]
77     instance.set(key, value)
78   })
79 }
80
81 type SortType = { sortModel: any, sortValue: string }
82
83 // ---------------------------------------------------------------------------
84
85 export {
86   badRequest,
87   generateRandomString,
88   getFormattedObjects,
89   isSignupAllowed,
90   computeResolutionsToTranscode,
91   resetSequelizeInstance,
92   SortType
93 }