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 { deleteFileAsync, generateRandomString } from './utils'
6 import { extname } from 'path'
7 import { isArray } from './custom-validators/misc'
8 import { UserModel } from '../models/account/user'
10 function buildNSFWFilter (res?: express.Response, paramNSFW?: string) {
11 if (paramNSFW === 'true') return true
12 if (paramNSFW === 'false') return false
13 if (paramNSFW === 'both') return undefined
15 if (res && res.locals.oauth) {
16 const user: UserModel = res.locals.oauth.token.User
18 // User does not want NSFW videos
19 if (user.nsfwPolicy === 'do_not_list') return false
25 if (CONFIG.INSTANCE.DEFAULT_NSFW_POLICY === 'do_not_list') return false
31 function cleanUpReqFiles (req: { files: { [ fieldname: string ]: Express.Multer.File[] } | Express.Multer.File[] }) {
32 const files = req.files
37 (files as Express.Multer.File[]).forEach(f => deleteFileAsync(f.path))
41 for (const key of Object.keys(files)) {
42 const file = files[ key ]
44 if (isArray(file)) file.forEach(f => deleteFileAsync(f.path))
45 else deleteFileAsync(file.path)
49 function getHostWithPort (host: string) {
50 const splitted = host.split(':')
52 // The port was not specified
53 if (splitted.length === 1) {
54 if (REMOTE_SCHEME.HTTP === 'https') return host + ':443'
62 function badRequest (req: express.Request, res: express.Response, next: express.NextFunction) {
63 return res.type('json').status(400).end()
66 function createReqFiles (
68 mimeTypes: { [ id: string ]: string },
69 destinations: { [ fieldName: string ]: string }
71 const storage = multer.diskStorage({
72 destination: (req, file, cb) => {
73 cb(null, destinations[ file.fieldname ])
76 filename: async (req, file, cb) => {
77 const extension = mimeTypes[ file.mimetype ] || extname(file.originalname)
81 randomString = await generateRandomString(16)
83 logger.error('Cannot generate random string for file name.', { err })
84 randomString = 'fake-random-string'
87 cb(null, randomString + extension)
91 let fields: { name: string, maxCount: number }[] = []
92 for (const fieldName of fieldNames) {
99 return multer({ storage }).fields(fields)
102 function isUserAbleToSearchRemoteURI (res: express.Response) {
103 const user: UserModel = res.locals.oauth ? res.locals.oauth.token.User : undefined
105 return CONFIG.SEARCH.REMOTE_URI.ANONYMOUS === true ||
106 (CONFIG.SEARCH.REMOTE_URI.USERS === true && user !== undefined)
109 // ---------------------------------------------------------------------------
114 isUserAbleToSearchRemoteURI,