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