]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blame - server/helpers/express-utils.ts
Updated travis.yml git depth 1
[github/Chocobozzz/PeerTube.git] / server / helpers / express-utils.ts
CommitLineData
0626e7af
C
1import * as express from 'express'
2import * as multer from 'multer'
3import { CONFIG, REMOTE_SCHEME } from '../initializers'
4import { logger } from './logger'
5import { User } from '../../shared/models/users'
6import { generateRandomString } from './utils'
7
0b18f4aa
C
8function buildNSFWFilter (res: express.Response, paramNSFW?: string) {
9 if (paramNSFW === 'true') return true
10 if (paramNSFW === 'false') return false
11 if (paramNSFW === 'both') return undefined
d525fc39 12
0626e7af
C
13 if (res.locals.oauth) {
14 const user: User = res.locals.oauth.token.User
d525fc39
C
15 // User does not want NSFW videos
16 if (user && user.nsfwPolicy === 'do_not_list') return false
0626e7af
C
17 }
18
d525fc39
C
19 if (CONFIG.INSTANCE.DEFAULT_NSFW_POLICY === 'do_not_list') return false
20
21 // Display all
22 return null
0626e7af
C
23}
24
25function 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
38function badRequest (req: express.Request, res: express.Response, next: express.NextFunction) {
39 return res.type('json').status(400).end()
40}
41
42function 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 const fields = []
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
80export {
d525fc39 81 buildNSFWFilter,
0626e7af
C
82 getHostWithPort,
83 badRequest,
84 createReqFiles
85}