2
1

oembed.ts 2.2 KB

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