Fix well known and json parser with mastodon
[oweals/peertube.git] / server / controllers / services.ts
1 import * as express from 'express'
2
3 import { CONFIG, EMBED_SIZE, PREVIEWS_SIZE } from '../initializers'
4 import { oembedValidator } from '../middlewares'
5 import { asyncMiddleware } from '../middlewares/async'
6 import { VideoInstance } from '../models'
7
8 const servicesRouter = express.Router()
9
10 servicesRouter.use('/oembed',
11   asyncMiddleware(oembedValidator),
12   generateOEmbed
13 )
14
15 // ---------------------------------------------------------------------------
16
17 export {
18   servicesRouter
19 }
20
21 // ---------------------------------------------------------------------------
22
23 function generateOEmbed (req: express.Request, res: express.Response, next: express.NextFunction) {
24   const video = res.locals.video as VideoInstance
25   const webserverUrl = CONFIG.WEBSERVER.URL
26   const maxHeight = parseInt(req.query.maxheight, 10)
27   const maxWidth = parseInt(req.query.maxwidth, 10)
28
29   const embedUrl = webserverUrl + video.getEmbedPath()
30   let thumbnailUrl = webserverUrl + video.getPreviewPath()
31   let embedWidth = EMBED_SIZE.width
32   let embedHeight = EMBED_SIZE.height
33
34   if (maxHeight < embedHeight) embedHeight = maxHeight
35   if (maxWidth < embedWidth) embedWidth = maxWidth
36
37   // Our thumbnail is too big for the consumer
38   if (
39     (maxHeight !== undefined && maxHeight < PREVIEWS_SIZE.height) ||
40     (maxWidth !== undefined && maxWidth < PREVIEWS_SIZE.width)
41   ) {
42     thumbnailUrl = undefined
43   }
44
45   const html = `<iframe width="${embedWidth}" height="${embedHeight}" src="${embedUrl}" frameborder="0" allowfullscreen></iframe>`
46
47   const json: any = {
48     type: 'video',
49     version: '1.0',
50     html,
51     width: embedWidth,
52     height: embedHeight,
53     title: video.name,
54     author_name: video.VideoChannel.Account.name,
55     provider_name: 'PeerTube',
56     provider_url: webserverUrl
57   }
58
59   if (thumbnailUrl !== undefined) {
60     json.thumbnail_url = thumbnailUrl
61     json.thumbnail_width = PREVIEWS_SIZE.width
62     json.thumbnail_height = PREVIEWS_SIZE.height
63   }
64
65   return res.json(json)
66 }