]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - server/middlewares/validators/oembed.ts
fb7b726e5c7913857a6242e2d41d4b52169c70d8
[github/Chocobozzz/PeerTube.git] / server / middlewares / validators / oembed.ts
1 import * as express from 'express'
2 import { query } from 'express-validator/check'
3 import { join } from 'path'
4 import { isTestInstance, logger } from '../../helpers'
5 import { isIdOrUUIDValid } from '../../helpers/custom-validators/misc'
6 import { isVideoExist } from '../../helpers/custom-validators/videos'
7 import { CONFIG } from '../../initializers'
8 import { areValidationErrors } from './utils'
9
10 const urlShouldStartWith = CONFIG.WEBSERVER.SCHEME + '://' + join(CONFIG.WEBSERVER.HOST, 'videos', 'watch') + '/'
11 const videoWatchRegex = new RegExp('([^/]+)$')
12 const isURLOptions = {
13 require_host: true,
14 require_tld: true
15 }
16
17 // We validate 'localhost', so we don't have the top level domain
18 if (isTestInstance()) {
19 isURLOptions.require_tld = false
20 }
21
22 const oembedValidator = [
23 query('url').isURL(isURLOptions).withMessage('Should have a valid url'),
24 query('maxwidth').optional().isInt().withMessage('Should have a valid max width'),
25 query('maxheight').optional().isInt().withMessage('Should have a valid max height'),
26 query('format').optional().isIn([ 'xml', 'json' ]).withMessage('Should have a valid format'),
27
28 async (req: express.Request, res: express.Response, next: express.NextFunction) => {
29 logger.debug('Checking oembed parameters', { parameters: req.query })
30
31 if (areValidationErrors(req, res)) return
32
33 if (req.query.format !== undefined && req.query.format !== 'json') {
34 return res.status(501)
35 .json({ error: 'Requested format is not implemented on server.' })
36 .end()
37 }
38
39 const startIsOk = req.query.url.startsWith(urlShouldStartWith)
40 const matches = videoWatchRegex.exec(req.query.url)
41 if (startIsOk === false || matches === null) {
42 return res.status(400)
43 .json({ error: 'Invalid url.' })
44 .end()
45 }
46
47 const videoId = matches[1]
48 if (isIdOrUUIDValid(videoId) === false) {
49 return res.status(400)
50 .json({ error: 'Invalid video id.' })
51 .end()
52 }
53
54 if (!await isVideoExist(videoId, res)) return
55
56 return next()
57 }
58 ]
59
60 // ---------------------------------------------------------------------------
61
62 export {
63 oembedValidator
64 }