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