]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blame_incremental - server/helpers/utils.ts
Fix lint
[github/Chocobozzz/PeerTube.git] / server / helpers / utils.ts
... / ...
CommitLineData
1import * as express from 'express'
2import * as multer from 'multer'
3import { Model } from 'sequelize-typescript'
4import { ResultList } from '../../shared'
5import { VideoResolution } from '../../shared/models/videos'
6import { CONFIG, REMOTE_SCHEME } from '../initializers'
7import { UserModel } from '../models/account/user'
8import { ActorModel } from '../models/activitypub/actor'
9import { ApplicationModel } from '../models/application/application'
10import { pseudoRandomBytesPromise } from './core-utils'
11import { logger } from './logger'
12
13function getHostWithPort (host: string) {
14 const splitted = host.split(':')
15
16 // The port was not specified
17 if (splitted.length === 1) {
18 if (REMOTE_SCHEME.HTTP === 'https') return host + ':443'
19
20 return host + ':80'
21 }
22
23 return host
24}
25
26function badRequest (req: express.Request, res: express.Response, next: express.NextFunction) {
27 return res.type('json').status(400).end()
28}
29
30function createReqFiles (
31 fieldNames: string[],
32 mimeTypes: { [ id: string ]: string },
33 destinations: { [ fieldName: string ]: string }
34) {
35 const storage = multer.diskStorage({
36 destination: (req, file, cb) => {
37 cb(null, destinations[file.fieldname])
38 },
39
40 filename: async (req, file, cb) => {
41 const extension = mimeTypes[file.mimetype]
42 let randomString = ''
43
44 try {
45 randomString = await generateRandomString(16)
46 } catch (err) {
47 logger.error('Cannot generate random string for file name.', err)
48 randomString = 'fake-random-string'
49 }
50
51 cb(null, randomString + extension)
52 }
53 })
54
55 const fields = []
56 for (const fieldName of fieldNames) {
57 fields.push({
58 name: fieldName,
59 maxCount: 1
60 })
61 }
62
63 return multer({ storage }).fields(fields)
64}
65
66async function generateRandomString (size: number) {
67 const raw = await pseudoRandomBytesPromise(size)
68
69 return raw.toString('hex')
70}
71
72interface FormattableToJSON {
73 toFormattedJSON ()
74}
75
76function getFormattedObjects<U, T extends FormattableToJSON> (objects: T[], objectsTotal: number) {
77 const formattedObjects: U[] = []
78
79 objects.forEach(object => {
80 formattedObjects.push(object.toFormattedJSON())
81 })
82
83 const res: ResultList<U> = {
84 total: objectsTotal,
85 data: formattedObjects
86 }
87
88 return res
89}
90
91async function isSignupAllowed () {
92 if (CONFIG.SIGNUP.ENABLED === false) {
93 return false
94 }
95
96 // No limit and signup is enabled
97 if (CONFIG.SIGNUP.LIMIT === -1) {
98 return true
99 }
100
101 const totalUsers = await UserModel.countTotal()
102
103 return totalUsers < CONFIG.SIGNUP.LIMIT
104}
105
106function computeResolutionsToTranscode (videoFileHeight: number) {
107 const resolutionsEnabled: number[] = []
108 const configResolutions = CONFIG.TRANSCODING.RESOLUTIONS
109
110 const resolutions = [
111 VideoResolution.H_240P,
112 VideoResolution.H_360P,
113 VideoResolution.H_480P,
114 VideoResolution.H_720P,
115 VideoResolution.H_1080P
116 ]
117
118 for (const resolution of resolutions) {
119 if (configResolutions[resolution + 'p'] === true && videoFileHeight > resolution) {
120 resolutionsEnabled.push(resolution)
121 }
122 }
123
124 return resolutionsEnabled
125}
126
127function resetSequelizeInstance (instance: Model<any>, savedFields: object) {
128 Object.keys(savedFields).forEach(key => {
129 const value = savedFields[key]
130 instance.set(key, value)
131 })
132}
133
134let serverActor: ActorModel
135async function getServerActor () {
136 if (serverActor === undefined) {
137 const application = await ApplicationModel.load()
138 serverActor = application.Account.Actor
139 }
140
141 if (!serverActor) {
142 logger.error('Cannot load server actor.')
143 process.exit(0)
144 }
145
146 return Promise.resolve(serverActor)
147}
148
149type SortType = { sortModel: any, sortValue: string }
150
151// ---------------------------------------------------------------------------
152
153export {
154 badRequest,
155 generateRandomString,
156 getFormattedObjects,
157 isSignupAllowed,
158 computeResolutionsToTranscode,
159 resetSequelizeInstance,
160 getServerActor,
161 SortType,
162 getHostWithPort,
163 createReqFiles
164}