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