expliciting type checks and predicates (server only)
[oweals/peertube.git] / server / helpers / express-utils.ts
1 import * as express from 'express'
2 import * as multer from 'multer'
3 import { CONFIG, REMOTE_SCHEME } from '../initializers'
4 import { logger } from './logger'
5 import { User } from '../../shared/models/users'
6 import { generateRandomString } from './utils'
7
8 function buildNSFWFilter (res: express.Response, paramNSFW?: string) {
9   if (paramNSFW === 'true') return true
10   if (paramNSFW === 'false') return false
11   if (paramNSFW === 'both') return undefined
12
13   if (res.locals.oauth) {
14     const user: User = res.locals.oauth.token.User
15     // User does not want NSFW videos
16     if (user && user.nsfwPolicy === 'do_not_list') return false
17   }
18
19   if (CONFIG.INSTANCE.DEFAULT_NSFW_POLICY === 'do_not_list') return false
20
21   // Display all
22   return null
23 }
24
25 function getHostWithPort (host: string) {
26   const splitted = host.split(':')
27
28   // The port was not specified
29   if (splitted.length === 1) {
30     if (REMOTE_SCHEME.HTTP === 'https') return host + ':443'
31
32     return host + ':80'
33   }
34
35   return host
36 }
37
38 function badRequest (req: express.Request, res: express.Response, next: express.NextFunction) {
39   return res.type('json').status(400).end()
40 }
41
42 function createReqFiles (
43   fieldNames: string[],
44   mimeTypes: { [ id: string ]: string },
45   destinations: { [ fieldName: string ]: string }
46 ) {
47   const storage = multer.diskStorage({
48     destination: (req, file, cb) => {
49       cb(null, destinations[ file.fieldname ])
50     },
51
52     filename: async (req, file, cb) => {
53       const extension = mimeTypes[ file.mimetype ]
54       let randomString = ''
55
56       try {
57         randomString = await generateRandomString(16)
58       } catch (err) {
59         logger.error('Cannot generate random string for file name.', { err })
60         randomString = 'fake-random-string'
61       }
62
63       cb(null, randomString + extension)
64     }
65   })
66
67   let fields: { name: string, maxCount: number }[] = []
68   for (const fieldName of fieldNames) {
69     fields.push({
70       name: fieldName,
71       maxCount: 1
72     })
73   }
74
75   return multer({ storage }).fields(fields)
76 }
77
78 // ---------------------------------------------------------------------------
79
80 export {
81   buildNSFWFilter,
82   getHostWithPort,
83   badRequest,
84   createReqFiles
85 }