]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - server/helpers/utils.ts
Add patch for angular cli 6
[github/Chocobozzz/PeerTube.git] / server / helpers / utils.ts
1 import { Model } from 'sequelize-typescript'
2 import { ResultList } from '../../shared'
3 import { VideoResolution } from '../../shared/models/videos'
4 import { CONFIG } from '../initializers'
5 import { UserModel } from '../models/account/user'
6 import { ActorModel } from '../models/activitypub/actor'
7 import { ApplicationModel } from '../models/application/application'
8 import { pseudoRandomBytesPromise } from './core-utils'
9 import { logger } from './logger'
10
11 async function generateRandomString (size: number) {
12 const raw = await pseudoRandomBytesPromise(size)
13
14 return raw.toString('hex')
15 }
16
17 interface FormattableToJSON {
18 toFormattedJSON ()
19 }
20
21 function getFormattedObjects<U, T extends FormattableToJSON> (objects: T[], objectsTotal: number) {
22 const formattedObjects: U[] = []
23
24 objects.forEach(object => {
25 formattedObjects.push(object.toFormattedJSON())
26 })
27
28 const res: ResultList<U> = {
29 total: objectsTotal,
30 data: formattedObjects
31 }
32
33 return res
34 }
35
36 async function isSignupAllowed () {
37 if (CONFIG.SIGNUP.ENABLED === false) {
38 return false
39 }
40
41 // No limit and signup is enabled
42 if (CONFIG.SIGNUP.LIMIT === -1) {
43 return true
44 }
45
46 const totalUsers = await UserModel.countTotal()
47
48 return totalUsers < CONFIG.SIGNUP.LIMIT
49 }
50
51 function computeResolutionsToTranscode (videoFileHeight: number) {
52 const resolutionsEnabled: number[] = []
53 const configResolutions = CONFIG.TRANSCODING.RESOLUTIONS
54
55 const resolutions = [
56 VideoResolution.H_240P,
57 VideoResolution.H_360P,
58 VideoResolution.H_480P,
59 VideoResolution.H_720P,
60 VideoResolution.H_1080P
61 ]
62
63 for (const resolution of resolutions) {
64 if (configResolutions[resolution + 'p'] === true && videoFileHeight > resolution) {
65 resolutionsEnabled.push(resolution)
66 }
67 }
68
69 return resolutionsEnabled
70 }
71
72 function resetSequelizeInstance (instance: Model<any>, savedFields: object) {
73 Object.keys(savedFields).forEach(key => {
74 const value = savedFields[key]
75 instance.set(key, value)
76 })
77 }
78
79 let serverActor: ActorModel
80 async function getServerActor () {
81 if (serverActor === undefined) {
82 const application = await ApplicationModel.load()
83 serverActor = application.Account.Actor
84 }
85
86 if (!serverActor) {
87 logger.error('Cannot load server actor.')
88 process.exit(0)
89 }
90
91 return Promise.resolve(serverActor)
92 }
93
94 type SortType = { sortModel: any, sortValue: string }
95
96 // ---------------------------------------------------------------------------
97
98 export {
99 generateRandomString,
100 getFormattedObjects,
101 isSignupAllowed,
102 computeResolutionsToTranscode,
103 resetSequelizeInstance,
104 getServerActor,
105 SortType
106 }