]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - server/controllers/static.ts
2064857eb12d30099bc1d00d7f0f4be04be8e847
[github/Chocobozzz/PeerTube.git] / server / controllers / static.ts
1 import * as cors from 'cors'
2 import * as express from 'express'
3 import { join } from 'path'
4 import { getRegisteredPlugins, getRegisteredThemes } from '@server/controllers/api/config'
5 import { serveIndexHTML } from '@server/lib/client-html'
6 import { getTorrentFilePath, getVideoFilePath } from '@server/lib/video-paths'
7 import { MVideoFile, MVideoFullLight } from '@server/types/models'
8 import { HttpStatusCode } from '@shared/core-utils/miscs/http-error-codes'
9 import { VideoStreamingPlaylistType } from '@shared/models/videos/video-streaming-playlist.type'
10 import { HttpNodeinfoDiasporaSoftwareNsSchema20 } from '../../shared/models/nodeinfo'
11 import { root } from '../helpers/core-utils'
12 import { CONFIG, isEmailEnabled } from '../initializers/config'
13 import {
14 CONSTRAINTS_FIELDS,
15 DEFAULT_THEME_NAME,
16 HLS_STREAMING_PLAYLIST_DIRECTORY,
17 PEERTUBE_VERSION,
18 ROUTE_CACHE_LIFETIME,
19 STATIC_DOWNLOAD_PATHS,
20 STATIC_MAX_AGE,
21 STATIC_PATHS,
22 WEBSERVER
23 } from '../initializers/constants'
24 import { getThemeOrDefault } from '../lib/plugins/theme-utils'
25 import { getEnabledResolutions } from '../lib/video-transcoding'
26 import { asyncMiddleware, videosDownloadValidator } from '../middlewares'
27 import { cacheRoute } from '../middlewares/cache'
28 import { UserModel } from '../models/account/user'
29 import { VideoModel } from '../models/video/video'
30 import { VideoCommentModel } from '../models/video/video-comment'
31
32 const staticRouter = express.Router()
33
34 staticRouter.use(cors())
35
36 /*
37 Cors is very important to let other servers access torrent and video files
38 */
39
40 const torrentsPhysicalPath = CONFIG.STORAGE.TORRENTS_DIR
41 staticRouter.use(
42 STATIC_PATHS.TORRENTS,
43 cors(),
44 express.static(torrentsPhysicalPath, { maxAge: 0 }) // Don't cache because we could regenerate the torrent file
45 )
46 staticRouter.use(
47 STATIC_DOWNLOAD_PATHS.TORRENTS + ':id-:resolution([0-9]+).torrent',
48 asyncMiddleware(videosDownloadValidator),
49 downloadTorrent
50 )
51 staticRouter.use(
52 STATIC_DOWNLOAD_PATHS.TORRENTS + ':id-:resolution([0-9]+)-hls.torrent',
53 asyncMiddleware(videosDownloadValidator),
54 downloadHLSVideoFileTorrent
55 )
56
57 // Videos path for webseeding
58 staticRouter.use(
59 STATIC_PATHS.WEBSEED,
60 cors(),
61 express.static(CONFIG.STORAGE.VIDEOS_DIR, { fallthrough: false }) // 404 because we don't have this video
62 )
63 staticRouter.use(
64 STATIC_PATHS.REDUNDANCY,
65 cors(),
66 express.static(CONFIG.STORAGE.REDUNDANCY_DIR, { fallthrough: false }) // 404 because we don't have this video
67 )
68
69 staticRouter.use(
70 STATIC_DOWNLOAD_PATHS.VIDEOS + ':id-:resolution([0-9]+).:extension',
71 asyncMiddleware(videosDownloadValidator),
72 downloadVideoFile
73 )
74
75 staticRouter.use(
76 STATIC_DOWNLOAD_PATHS.HLS_VIDEOS + ':id-:resolution([0-9]+)-fragmented.:extension',
77 asyncMiddleware(videosDownloadValidator),
78 downloadHLSVideoFile
79 )
80
81 // HLS
82 staticRouter.use(
83 STATIC_PATHS.STREAMING_PLAYLISTS.HLS,
84 cors(),
85 express.static(HLS_STREAMING_PLAYLIST_DIRECTORY, { fallthrough: false }) // 404 if the file does not exist
86 )
87
88 // Thumbnails path for express
89 const thumbnailsPhysicalPath = CONFIG.STORAGE.THUMBNAILS_DIR
90 staticRouter.use(
91 STATIC_PATHS.THUMBNAILS,
92 express.static(thumbnailsPhysicalPath, { maxAge: STATIC_MAX_AGE.SERVER, fallthrough: false }) // 404 if the file does not exist
93 )
94
95 // robots.txt service
96 staticRouter.get('/robots.txt',
97 asyncMiddleware(cacheRoute()(ROUTE_CACHE_LIFETIME.ROBOTS)),
98 (_, res: express.Response) => {
99 res.type('text/plain')
100 return res.send(CONFIG.INSTANCE.ROBOTS)
101 }
102 )
103
104 staticRouter.all('/teapot',
105 getCup,
106 asyncMiddleware(serveIndexHTML)
107 )
108
109 // security.txt service
110 staticRouter.get('/security.txt',
111 (_, res: express.Response) => {
112 return res.redirect(HttpStatusCode.MOVED_PERMANENTLY_301, '/.well-known/security.txt')
113 }
114 )
115
116 staticRouter.get('/.well-known/security.txt',
117 asyncMiddleware(cacheRoute()(ROUTE_CACHE_LIFETIME.SECURITYTXT)),
118 (_, res: express.Response) => {
119 res.type('text/plain')
120 return res.send(CONFIG.INSTANCE.SECURITYTXT + CONFIG.INSTANCE.SECURITYTXT_CONTACT)
121 }
122 )
123
124 // nodeinfo service
125 staticRouter.use('/.well-known/nodeinfo',
126 asyncMiddleware(cacheRoute()(ROUTE_CACHE_LIFETIME.NODEINFO)),
127 (_, res: express.Response) => {
128 return res.json({
129 links: [
130 {
131 rel: 'http://nodeinfo.diaspora.software/ns/schema/2.0',
132 href: WEBSERVER.URL + '/nodeinfo/2.0.json'
133 }
134 ]
135 })
136 }
137 )
138 staticRouter.use('/nodeinfo/:version.json',
139 asyncMiddleware(cacheRoute()(ROUTE_CACHE_LIFETIME.NODEINFO)),
140 asyncMiddleware(generateNodeinfo)
141 )
142
143 // dnt-policy.txt service (see https://www.eff.org/dnt-policy)
144 staticRouter.use('/.well-known/dnt-policy.txt',
145 asyncMiddleware(cacheRoute()(ROUTE_CACHE_LIFETIME.DNT_POLICY)),
146 (_, res: express.Response) => {
147 res.type('text/plain')
148
149 return res.sendFile(join(root(), 'dist/server/static/dnt-policy/dnt-policy-1.0.txt'))
150 }
151 )
152
153 // dnt service (see https://www.w3.org/TR/tracking-dnt/#status-resource)
154 staticRouter.use('/.well-known/dnt/',
155 (_, res: express.Response) => {
156 res.json({ tracking: 'N' })
157 }
158 )
159
160 staticRouter.use('/.well-known/change-password',
161 (_, res: express.Response) => {
162 res.redirect('/my-account/settings')
163 }
164 )
165
166 staticRouter.use('/.well-known/host-meta',
167 (_, res: express.Response) => {
168 res.type('application/xml')
169
170 const xml = '<?xml version="1.0" encoding="UTF-8"?>\n' +
171 '<XRD xmlns="http://docs.oasis-open.org/ns/xri/xrd-1.0">\n' +
172 ` <Link rel="lrdd" type="application/xrd+xml" template="${WEBSERVER.URL}/.well-known/webfinger?resource={uri}"/>\n` +
173 '</XRD>'
174
175 res.send(xml).end()
176 }
177 )
178
179 // ---------------------------------------------------------------------------
180
181 export {
182 staticRouter
183 }
184
185 // ---------------------------------------------------------------------------
186
187 async function generateNodeinfo (req: express.Request, res: express.Response) {
188 const { totalVideos } = await VideoModel.getStats()
189 const { totalLocalVideoComments } = await VideoCommentModel.getStats()
190 const { totalUsers, totalMonthlyActiveUsers, totalHalfYearActiveUsers } = await UserModel.getStats()
191 let json = {}
192
193 if (req.params.version && (req.params.version === '2.0')) {
194 json = {
195 version: '2.0',
196 software: {
197 name: 'peertube',
198 version: PEERTUBE_VERSION
199 },
200 protocols: [
201 'activitypub'
202 ],
203 services: {
204 inbound: [],
205 outbound: [
206 'atom1.0',
207 'rss2.0'
208 ]
209 },
210 openRegistrations: CONFIG.SIGNUP.ENABLED,
211 usage: {
212 users: {
213 total: totalUsers,
214 activeMonth: totalMonthlyActiveUsers,
215 activeHalfyear: totalHalfYearActiveUsers
216 },
217 localPosts: totalVideos,
218 localComments: totalLocalVideoComments
219 },
220 metadata: {
221 taxonomy: {
222 postsName: 'Videos'
223 },
224 nodeName: CONFIG.INSTANCE.NAME,
225 nodeDescription: CONFIG.INSTANCE.SHORT_DESCRIPTION,
226 nodeConfig: {
227 search: {
228 remoteUri: {
229 users: CONFIG.SEARCH.REMOTE_URI.USERS,
230 anonymous: CONFIG.SEARCH.REMOTE_URI.ANONYMOUS
231 }
232 },
233 plugin: {
234 registered: getRegisteredPlugins()
235 },
236 theme: {
237 registered: getRegisteredThemes(),
238 default: getThemeOrDefault(CONFIG.THEME.DEFAULT, DEFAULT_THEME_NAME)
239 },
240 email: {
241 enabled: isEmailEnabled()
242 },
243 contactForm: {
244 enabled: CONFIG.CONTACT_FORM.ENABLED
245 },
246 transcoding: {
247 hls: {
248 enabled: CONFIG.TRANSCODING.HLS.ENABLED
249 },
250 webtorrent: {
251 enabled: CONFIG.TRANSCODING.WEBTORRENT.ENABLED
252 },
253 enabledResolutions: getEnabledResolutions('vod')
254 },
255 live: {
256 enabled: CONFIG.LIVE.ENABLED,
257 transcoding: {
258 enabled: CONFIG.LIVE.TRANSCODING.ENABLED,
259 enabledResolutions: getEnabledResolutions('live')
260 }
261 },
262 import: {
263 videos: {
264 http: {
265 enabled: CONFIG.IMPORT.VIDEOS.HTTP.ENABLED
266 },
267 torrent: {
268 enabled: CONFIG.IMPORT.VIDEOS.TORRENT.ENABLED
269 }
270 }
271 },
272 autoBlacklist: {
273 videos: {
274 ofUsers: {
275 enabled: CONFIG.AUTO_BLACKLIST.VIDEOS.OF_USERS.ENABLED
276 }
277 }
278 },
279 avatar: {
280 file: {
281 size: {
282 max: CONSTRAINTS_FIELDS.ACTORS.AVATAR.FILE_SIZE.max
283 },
284 extensions: CONSTRAINTS_FIELDS.ACTORS.AVATAR.EXTNAME
285 }
286 },
287 video: {
288 image: {
289 extensions: CONSTRAINTS_FIELDS.VIDEOS.IMAGE.EXTNAME,
290 size: {
291 max: CONSTRAINTS_FIELDS.VIDEOS.IMAGE.FILE_SIZE.max
292 }
293 },
294 file: {
295 extensions: CONSTRAINTS_FIELDS.VIDEOS.EXTNAME
296 }
297 },
298 videoCaption: {
299 file: {
300 size: {
301 max: CONSTRAINTS_FIELDS.VIDEO_CAPTIONS.CAPTION_FILE.FILE_SIZE.max
302 },
303 extensions: CONSTRAINTS_FIELDS.VIDEO_CAPTIONS.CAPTION_FILE.EXTNAME
304 }
305 },
306 user: {
307 videoQuota: CONFIG.USER.VIDEO_QUOTA,
308 videoQuotaDaily: CONFIG.USER.VIDEO_QUOTA_DAILY
309 },
310 trending: {
311 videos: {
312 intervalDays: CONFIG.TRENDING.VIDEOS.INTERVAL_DAYS
313 }
314 },
315 tracker: {
316 enabled: CONFIG.TRACKER.ENABLED
317 }
318 }
319 }
320 } as HttpNodeinfoDiasporaSoftwareNsSchema20
321 res.contentType('application/json; profile="http://nodeinfo.diaspora.software/ns/schema/2.0#"')
322 } else {
323 json = { error: 'Nodeinfo schema version not handled' }
324 res.status(HttpStatusCode.NOT_FOUND_404)
325 }
326
327 return res.send(json).end()
328 }
329
330 function downloadTorrent (req: express.Request, res: express.Response) {
331 const video = res.locals.videoAll
332
333 const videoFile = getVideoFile(req, video.VideoFiles)
334 if (!videoFile) return res.status(HttpStatusCode.NOT_FOUND_404).end()
335
336 return res.download(getTorrentFilePath(video, videoFile), `${video.name}-${videoFile.resolution}p.torrent`)
337 }
338
339 function downloadHLSVideoFileTorrent (req: express.Request, res: express.Response) {
340 const video = res.locals.videoAll
341
342 const playlist = getHLSPlaylist(video)
343 if (!playlist) return res.status(HttpStatusCode.NOT_FOUND_404).end
344
345 const videoFile = getVideoFile(req, playlist.VideoFiles)
346 if (!videoFile) return res.status(HttpStatusCode.NOT_FOUND_404).end()
347
348 return res.download(getTorrentFilePath(playlist, videoFile), `${video.name}-${videoFile.resolution}p-hls.torrent`)
349 }
350
351 function downloadVideoFile (req: express.Request, res: express.Response) {
352 const video = res.locals.videoAll
353
354 const videoFile = getVideoFile(req, video.VideoFiles)
355 if (!videoFile) return res.status(HttpStatusCode.NOT_FOUND_404).end()
356
357 return res.download(getVideoFilePath(video, videoFile), `${video.name}-${videoFile.resolution}p${videoFile.extname}`)
358 }
359
360 function downloadHLSVideoFile (req: express.Request, res: express.Response) {
361 const video = res.locals.videoAll
362 const playlist = getHLSPlaylist(video)
363 if (!playlist) return res.status(HttpStatusCode.NOT_FOUND_404).end
364
365 const videoFile = getVideoFile(req, playlist.VideoFiles)
366 if (!videoFile) return res.status(HttpStatusCode.NOT_FOUND_404).end()
367
368 const filename = `${video.name}-${videoFile.resolution}p-${playlist.getStringType()}${videoFile.extname}`
369 return res.download(getVideoFilePath(playlist, videoFile), filename)
370 }
371
372 function getVideoFile (req: express.Request, files: MVideoFile[]) {
373 const resolution = parseInt(req.params.resolution, 10)
374 return files.find(f => f.resolution === resolution)
375 }
376
377 function getHLSPlaylist (video: MVideoFullLight) {
378 const playlist = video.VideoStreamingPlaylists.find(p => p.type === VideoStreamingPlaylistType.HLS)
379 if (!playlist) return undefined
380
381 return Object.assign(playlist, { Video: video })
382 }
383
384 function getCup (req: express.Request, res: express.Response, next: express.NextFunction) {
385 res.status(HttpStatusCode.I_AM_A_TEAPOT_418)
386 res.setHeader('Accept-Additions', 'Non-Dairy;1,Sugar;1')
387 res.setHeader('Safe', 'if-sepia-awake')
388
389 return next()
390 }