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