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