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