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