Fix get version
[oweals/peertube.git] / server / controllers / static.ts
1 import * as cors from 'cors'
2 import * as express from 'express'
3 import { CONFIG, ROUTE_CACHE_LIFETIME, STATIC_DOWNLOAD_PATHS, STATIC_MAX_AGE, STATIC_PATHS } from '../initializers'
4 import { VideosPreviewCache } from '../lib/cache'
5 import { cacheRoute } from '../middlewares/cache'
6 import { asyncMiddleware, videosGetValidator } from '../middlewares'
7 import { VideoModel } from '../models/video/video'
8 import { VideosCaptionCache } from '../lib/cache/videos-caption-cache'
9 import { UserModel } from '../models/account/user'
10 import { VideoCommentModel } from '../models/video/video-comment'
11 import { HttpNodeinfoDiasporaSoftwareNsSchema20 } from '../../shared/models/nodeinfo'
12 import { join } from 'path'
13 import { root } from '../helpers/core-utils'
14
15 const packageJSON = require('../../../package.json')
16 const staticRouter = express.Router()
17
18 staticRouter.use(cors())
19
20 /*
21   Cors is very important to let other servers access torrent and video files
22 */
23
24 const torrentsPhysicalPath = CONFIG.STORAGE.TORRENTS_DIR
25 staticRouter.use(
26   STATIC_PATHS.TORRENTS,
27   cors(),
28   express.static(torrentsPhysicalPath, { maxAge: 0 }) // Don't cache because we could regenerate the torrent file
29 )
30 staticRouter.use(
31   STATIC_DOWNLOAD_PATHS.TORRENTS + ':id-:resolution([0-9]+).torrent',
32   asyncMiddleware(videosGetValidator),
33   asyncMiddleware(downloadTorrent)
34 )
35
36 // Videos path for webseeding
37 const videosPhysicalPath = CONFIG.STORAGE.VIDEOS_DIR
38 staticRouter.use(
39   STATIC_PATHS.WEBSEED,
40   cors(),
41   express.static(videosPhysicalPath)
42 )
43 staticRouter.use(
44   STATIC_DOWNLOAD_PATHS.VIDEOS + ':id-:resolution([0-9]+).:extension',
45   asyncMiddleware(videosGetValidator),
46   asyncMiddleware(downloadVideoFile)
47 )
48
49 // Thumbnails path for express
50 const thumbnailsPhysicalPath = CONFIG.STORAGE.THUMBNAILS_DIR
51 staticRouter.use(
52   STATIC_PATHS.THUMBNAILS,
53   express.static(thumbnailsPhysicalPath, { maxAge: STATIC_MAX_AGE, fallthrough: false }) // 404 if the file does not exist
54 )
55
56 const avatarsPhysicalPath = CONFIG.STORAGE.AVATARS_DIR
57 staticRouter.use(
58   STATIC_PATHS.AVATARS,
59   express.static(avatarsPhysicalPath, { maxAge: STATIC_MAX_AGE, fallthrough: false }) // 404 if the file does not exist
60 )
61
62 // We don't have video previews, fetch them from the origin instance
63 staticRouter.use(
64   STATIC_PATHS.PREVIEWS + ':uuid.jpg',
65   asyncMiddleware(getPreview)
66 )
67
68 // We don't have video captions, fetch them from the origin instance
69 staticRouter.use(
70   STATIC_PATHS.VIDEO_CAPTIONS + ':videoId-:captionLanguage([a-z]+).vtt',
71   asyncMiddleware(getVideoCaption)
72 )
73
74 // robots.txt service
75 staticRouter.get('/robots.txt',
76   asyncMiddleware(cacheRoute(ROUTE_CACHE_LIFETIME.ROBOTS)),
77   (_, res: express.Response) => {
78     res.type('text/plain')
79     return res.send(CONFIG.INSTANCE.ROBOTS)
80   }
81 )
82
83 // security.txt service
84 staticRouter.get('/security.txt',
85   (_, res: express.Response) => {
86     return res.redirect(301, '/.well-known/security.txt')
87   }
88 )
89
90 staticRouter.get('/.well-known/security.txt',
91   asyncMiddleware(cacheRoute(ROUTE_CACHE_LIFETIME.SECURITYTXT)),
92   (_, res: express.Response) => {
93     res.type('text/plain')
94     return res.send(CONFIG.INSTANCE.SECURITYTXT + CONFIG.INSTANCE.SECURITYTXT_CONTACT)
95   }
96 )
97
98 // nodeinfo service
99 staticRouter.use('/.well-known/nodeinfo',
100   asyncMiddleware(cacheRoute(ROUTE_CACHE_LIFETIME.NODEINFO)),
101   (_, res: express.Response) => {
102     return res.json({
103       links: [
104         {
105           rel: 'http://nodeinfo.diaspora.software/ns/schema/2.0',
106           href: CONFIG.WEBSERVER.URL + '/nodeinfo/2.0.json'
107         }
108       ]
109     })
110   }
111 )
112 staticRouter.use('/nodeinfo/:version.json',
113   asyncMiddleware(cacheRoute(ROUTE_CACHE_LIFETIME.NODEINFO)),
114   asyncMiddleware(generateNodeinfo)
115 )
116
117 // dnt-policy.txt service (see https://www.eff.org/dnt-policy)
118 staticRouter.use('/.well-known/dnt-policy.txt',
119   asyncMiddleware(cacheRoute(ROUTE_CACHE_LIFETIME.DNT_POLICY)),
120   (_, res: express.Response) => {
121     res.type('text/plain')
122
123     return res.sendFile(join(root(), 'dist/server/static/dnt-policy/dnt-policy-1.0.txt'))
124   }
125 )
126
127 // dnt service (see https://www.w3.org/TR/tracking-dnt/#status-resource)
128 staticRouter.use('/.well-known/dnt/',
129   (_, res: express.Response) => {
130     res.json({ tracking: 'N' })
131   }
132 )
133
134 // ---------------------------------------------------------------------------
135
136 export {
137   staticRouter
138 }
139
140 // ---------------------------------------------------------------------------
141
142 async function getPreview (req: express.Request, res: express.Response, next: express.NextFunction) {
143   const path = await VideosPreviewCache.Instance.getFilePath(req.params.uuid)
144   if (!path) return res.sendStatus(404)
145
146   return res.sendFile(path, { maxAge: STATIC_MAX_AGE })
147 }
148
149 async function getVideoCaption (req: express.Request, res: express.Response) {
150   const path = await VideosCaptionCache.Instance.getFilePath({
151     videoId: req.params.videoId,
152     language: req.params.captionLanguage
153   })
154   if (!path) return res.sendStatus(404)
155
156   return res.sendFile(path, { maxAge: STATIC_MAX_AGE })
157 }
158
159 async function generateNodeinfo (req: express.Request, res: express.Response, next: express.NextFunction) {
160   const { totalVideos } = await VideoModel.getStats()
161   const { totalLocalVideoComments } = await VideoCommentModel.getStats()
162   const { totalUsers } = await UserModel.getStats()
163   let json = {}
164
165   if (req.params.version && (req.params.version === '2.0')) {
166     json = {
167       version: '2.0',
168       software: {
169         name: 'peertube',
170         version: packageJSON.version
171       },
172       protocols: [
173         'activitypub'
174       ],
175       services: {
176         inbound: [],
177         outbound: [
178           'atom1.0',
179           'rss2.0'
180         ]
181       },
182       openRegistrations: CONFIG.SIGNUP.ENABLED,
183       usage: {
184         users: {
185           total: totalUsers
186         },
187         localPosts: totalVideos,
188         localComments: totalLocalVideoComments
189       },
190       metadata: {
191         taxonomy: {
192           postsName: 'Videos'
193         },
194         nodeName: CONFIG.INSTANCE.NAME,
195         nodeDescription: CONFIG.INSTANCE.SHORT_DESCRIPTION
196       }
197     } as HttpNodeinfoDiasporaSoftwareNsSchema20
198     res.contentType('application/json; profile="http://nodeinfo.diaspora.software/ns/schema/2.0#"')
199   } else {
200     json = { error: 'Nodeinfo schema version not handled' }
201     res.status(404)
202   }
203
204   return res.send(json).end()
205 }
206
207 async function downloadTorrent (req: express.Request, res: express.Response, next: express.NextFunction) {
208   const { video, videoFile } = getVideoAndFile(req, res)
209   if (!videoFile) return res.status(404).end()
210
211   return res.download(video.getTorrentFilePath(videoFile), `${video.name}-${videoFile.resolution}p.torrent`)
212 }
213
214 async function downloadVideoFile (req: express.Request, res: express.Response, next: express.NextFunction) {
215   const { video, videoFile } = getVideoAndFile(req, res)
216   if (!videoFile) return res.status(404).end()
217
218   return res.download(video.getVideoFilePath(videoFile), `${video.name}-${videoFile.resolution}p${videoFile.extname}`)
219 }
220
221 function getVideoAndFile (req: express.Request, res: express.Response) {
222   const resolution = parseInt(req.params.resolution, 10)
223   const video: VideoModel = res.locals.video
224
225   const videoFile = video.VideoFiles.find(f => f.resolution === resolution)
226
227   return { video, videoFile }
228 }