]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - server/helpers/express-utils.ts
correct error codes and backward compat
[github/Chocobozzz/PeerTube.git] / server / helpers / express-utils.ts
1 import * as express from 'express'
2 import * as multer from 'multer'
3 import { extname } from 'path'
4 import { HttpStatusCode } from '../../shared/core-utils/miscs/http-error-codes'
5 import { CONFIG } from '../initializers/config'
6 import { REMOTE_SCHEME } from '../initializers/constants'
7 import { isArray } from './custom-validators/misc'
8 import { logger } from './logger'
9 import { deleteFileAndCatch, generateRandomString } from './utils'
10 import { getExtFromMimetype } from './video'
11 import { ProblemDocument, ProblemDocumentExtension } from 'http-problem-details'
12
13 function buildNSFWFilter (res?: express.Response, paramNSFW?: string) {
14 if (paramNSFW === 'true') return true
15 if (paramNSFW === 'false') return false
16 if (paramNSFW === 'both') return undefined
17
18 if (res?.locals.oauth) {
19 const user = res.locals.oauth.token.User
20
21 // User does not want NSFW videos
22 if (user.nsfwPolicy === 'do_not_list') return false
23
24 // Both
25 return undefined
26 }
27
28 if (CONFIG.INSTANCE.DEFAULT_NSFW_POLICY === 'do_not_list') return false
29
30 // Display all
31 return null
32 }
33
34 function cleanUpReqFiles (
35 req: { files: { [fieldname: string]: Express.Multer.File[] } | Express.Multer.File[] }
36 ) {
37 const filesObject = req.files
38 if (!filesObject) return
39
40 if (isArray(filesObject)) {
41 filesObject.forEach(f => deleteFileAndCatch(f.path))
42 return
43 }
44
45 for (const key of Object.keys(filesObject)) {
46 const files = filesObject[key]
47
48 files.forEach(f => deleteFileAndCatch(f.path))
49 }
50 }
51
52 function getHostWithPort (host: string) {
53 const splitted = host.split(':')
54
55 // The port was not specified
56 if (splitted.length === 1) {
57 if (REMOTE_SCHEME.HTTP === 'https') return host + ':443'
58
59 return host + ':80'
60 }
61
62 return host
63 }
64
65 function badRequest (req: express.Request, res: express.Response) {
66 return res.type('json')
67 .status(HttpStatusCode.BAD_REQUEST_400)
68 .end()
69 }
70
71 function createReqFiles (
72 fieldNames: string[],
73 mimeTypes: { [id: string]: string | string[] },
74 destinations: { [fieldName: string]: string }
75 ) {
76 const storage = multer.diskStorage({
77 destination: (req, file, cb) => {
78 cb(null, destinations[file.fieldname])
79 },
80
81 filename: async (req, file, cb) => {
82 let extension: string
83 const fileExtension = extname(file.originalname)
84 const extensionFromMimetype = getExtFromMimetype(mimeTypes, file.mimetype)
85
86 // Take the file extension if we don't understand the mime type
87 if (!extensionFromMimetype) {
88 extension = fileExtension
89 } else {
90 // Take the first available extension for this mimetype
91 extension = extensionFromMimetype
92 }
93
94 let randomString = ''
95
96 try {
97 randomString = await generateRandomString(16)
98 } catch (err) {
99 logger.error('Cannot generate random string for file name.', { err })
100 randomString = 'fake-random-string'
101 }
102
103 cb(null, randomString + extension)
104 }
105 })
106
107 const fields: { name: string, maxCount: number }[] = []
108 for (const fieldName of fieldNames) {
109 fields.push({
110 name: fieldName,
111 maxCount: 1
112 })
113 }
114
115 return multer({ storage }).fields(fields)
116 }
117
118 function isUserAbleToSearchRemoteURI (res: express.Response) {
119 const user = res.locals.oauth ? res.locals.oauth.token.User : undefined
120
121 return CONFIG.SEARCH.REMOTE_URI.ANONYMOUS === true ||
122 (CONFIG.SEARCH.REMOTE_URI.USERS === true && user !== undefined)
123 }
124
125 function getCountVideos (req: express.Request) {
126 return req.query.skipCount !== true
127 }
128
129 // helpers added in server.ts and used in subsequent controllers used
130 const apiResponseHelpers = (req, res: express.Response, next = null) => {
131 res.fail = (options) => {
132 const { data, status = HttpStatusCode.BAD_REQUEST_400, message, title, type, docs = res.docs, instance } = options
133
134 const extension = new ProblemDocumentExtension({
135 ...data,
136 docs,
137 // fields for <= 3.2 compatibility, deprecated
138 error: message,
139 code: type
140 })
141
142 res.status(status)
143 res.setHeader('Content-Type', 'application/problem+json')
144 res.json(new ProblemDocument({
145 status,
146 title,
147 instance,
148 // fields intended to replace 'error' and 'code' respectively
149 detail: message,
150 type: type && 'https://docs.joinpeertube.org/api-rest-reference.html#section/Errors/' + type
151 }, extension))
152 }
153
154 if (next) next()
155 }
156
157 // ---------------------------------------------------------------------------
158
159 export {
160 buildNSFWFilter,
161 getHostWithPort,
162 isUserAbleToSearchRemoteURI,
163 badRequest,
164 createReqFiles,
165 cleanUpReqFiles,
166 getCountVideos,
167 apiResponseHelpers
168 }