]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blame - server/controllers/static.ts
emit more specific status codes on video upload (#3423)
[github/Chocobozzz/PeerTube.git] / server / controllers / static.ts
CommitLineData
4d4e5cd4 1import * as cors from 'cors'
50d6de9c 2import * as express from 'express'
9c6ca37f 3import {
4c1c1709
C
4 CONSTRAINTS_FIELDS,
5 DEFAULT_THEME_NAME,
34dd7cb4
C
6 HLS_STREAMING_PLAYLIST_DIRECTORY,
7 PEERTUBE_VERSION,
9c6ca37f
C
8 ROUTE_CACHE_LIFETIME,
9 STATIC_DOWNLOAD_PATHS,
10 STATIC_MAX_AGE,
6dd9de95 11 STATIC_PATHS,
4c1c1709 12 WEBSERVER
74dc3bca 13} from '../initializers/constants'
98d3324d 14import { cacheRoute } from '../middlewares/cache'
eccf70f0 15import { asyncMiddleware, videosDownloadValidator } from '../middlewares'
02756fbd 16import { VideoModel } from '../models/video/video'
3f6d68d9
RK
17import { UserModel } from '../models/account/user'
18import { VideoCommentModel } from '../models/video/video-comment'
c75937d0 19import { HttpNodeinfoDiasporaSoftwareNsSchema20 } from '../../shared/models/nodeinfo'
aac0118d
C
20import { join } from 'path'
21import { root } from '../helpers/core-utils'
4c1c1709 22import { CONFIG, isEmailEnabled } from '../initializers/config'
557b13ae 23import { getPreview, getVideoCaption } from './lazy-static'
d7a25329 24import { VideoStreamingPlaylistType } from '@shared/models/videos/video-streaming-playlist.type'
26d6bf65 25import { MVideoFile, MVideoFullLight } from '@server/types/models'
d7a25329 26import { getTorrentFilePath, getVideoFilePath } from '@server/lib/video-paths'
174e0855
RK
27import { getThemeOrDefault } from '../lib/plugins/theme-utils'
28import { getEnabledResolutions, getRegisteredPlugins, getRegisteredThemes } from '@server/controllers/api/config'
2d53be02 29import { HttpStatusCode } from '@shared/core-utils/miscs/http-error-codes'
f2eb23cd 30import { serveIndexHTML } from '@server/lib/client-html'
65fcc311
C
31
32const staticRouter = express.Router()
33
62945f06
C
34staticRouter.use(cors())
35
65fcc311 36/*
60862425 37 Cors is very important to let other servers access torrent and video files
65fcc311
C
38*/
39
40const torrentsPhysicalPath = CONFIG.STORAGE.TORRENTS_DIR
41staticRouter.use(
42 STATIC_PATHS.TORRENTS,
43 cors(),
49379960 44 express.static(torrentsPhysicalPath, { maxAge: 0 }) // Don't cache because we could regenerate the torrent file
65fcc311 45)
02756fbd
C
46staticRouter.use(
47 STATIC_DOWNLOAD_PATHS.TORRENTS + ':id-:resolution([0-9]+).torrent',
eccf70f0 48 asyncMiddleware(videosDownloadValidator),
a1587156 49 downloadTorrent
02756fbd 50)
d7a25329
C
51staticRouter.use(
52 STATIC_DOWNLOAD_PATHS.TORRENTS + ':id-:resolution([0-9]+)-hls.torrent',
eccf70f0 53 asyncMiddleware(videosDownloadValidator),
a1587156 54 downloadHLSVideoFileTorrent
d7a25329 55)
65fcc311
C
56
57// Videos path for webseeding
65fcc311
C
58staticRouter.use(
59 STATIC_PATHS.WEBSEED,
60 cors(),
b9fffa29 61 express.static(CONFIG.STORAGE.VIDEOS_DIR, { fallthrough: false }) // 404 because we don't have this video
65fcc311 62)
6040f87d 63staticRouter.use(
b9fffa29 64 STATIC_PATHS.REDUNDANCY,
6040f87d 65 cors(),
b9fffa29 66 express.static(CONFIG.STORAGE.REDUNDANCY_DIR, { fallthrough: false }) // 404 because we don't have this video
6040f87d
C
67)
68
02756fbd
C
69staticRouter.use(
70 STATIC_DOWNLOAD_PATHS.VIDEOS + ':id-:resolution([0-9]+).:extension',
eccf70f0 71 asyncMiddleware(videosDownloadValidator),
a1587156 72 downloadVideoFile
02756fbd 73)
65fcc311 74
d7a25329 75staticRouter.use(
efcd6f2e 76 STATIC_DOWNLOAD_PATHS.HLS_VIDEOS + ':id-:resolution([0-9]+)-fragmented.:extension',
eccf70f0 77 asyncMiddleware(videosDownloadValidator),
a1587156 78 downloadHLSVideoFile
d7a25329
C
79)
80
09209296
C
81// HLS
82staticRouter.use(
9c6ca37f 83 STATIC_PATHS.STREAMING_PLAYLISTS.HLS,
09209296 84 cors(),
9c6ca37f 85 express.static(HLS_STREAMING_PLAYLIST_DIRECTORY, { fallthrough: false }) // 404 if the file does not exist
09209296
C
86)
87
65fcc311
C
88// Thumbnails path for express
89const thumbnailsPhysicalPath = CONFIG.STORAGE.THUMBNAILS_DIR
90staticRouter.use(
91 STATIC_PATHS.THUMBNAILS,
cd4cb177 92 express.static(thumbnailsPhysicalPath, { maxAge: STATIC_MAX_AGE.SERVER, fallthrough: false }) // 404 if the file does not exist
65fcc311
C
93)
94
557b13ae 95// DEPRECATED: use lazy-static route instead
c5911fd3
C
96const avatarsPhysicalPath = CONFIG.STORAGE.AVATARS_DIR
97staticRouter.use(
98 STATIC_PATHS.AVATARS,
cd4cb177 99 express.static(avatarsPhysicalPath, { maxAge: STATIC_MAX_AGE.SERVER, fallthrough: false }) // 404 if the file does not exist
c5911fd3
C
100)
101
557b13ae 102// DEPRECATED: use lazy-static route instead
65fcc311 103staticRouter.use(
f981dae8 104 STATIC_PATHS.PREVIEWS + ':uuid.jpg',
eb080476 105 asyncMiddleware(getPreview)
65fcc311
C
106)
107
557b13ae 108// DEPRECATED: use lazy-static route instead
40e87e9e
C
109staticRouter.use(
110 STATIC_PATHS.VIDEO_CAPTIONS + ':videoId-:captionLanguage([a-z]+).vtt',
111 asyncMiddleware(getVideoCaption)
112)
113
ac235c37 114// robots.txt service
3f6d68d9 115staticRouter.get('/robots.txt',
f2f0eda5 116 asyncMiddleware(cacheRoute()(ROUTE_CACHE_LIFETIME.ROBOTS)),
3f6d68d9
RK
117 (_, res: express.Response) => {
118 res.type('text/plain')
119 return res.send(CONFIG.INSTANCE.ROBOTS)
120 }
121)
122
f2eb23cd
RK
123staticRouter.all('/teapot',
124 getCup,
125 asyncMiddleware(serveIndexHTML)
126)
127
5447516b
AH
128// security.txt service
129staticRouter.get('/security.txt',
130 (_, res: express.Response) => {
2d53be02 131 return res.redirect(HttpStatusCode.MOVED_PERMANENTLY_301, '/.well-known/security.txt')
5447516b
AH
132 }
133)
134
135staticRouter.get('/.well-known/security.txt',
f2f0eda5 136 asyncMiddleware(cacheRoute()(ROUTE_CACHE_LIFETIME.SECURITYTXT)),
5447516b
AH
137 (_, res: express.Response) => {
138 res.type('text/plain')
139 return res.send(CONFIG.INSTANCE.SECURITYTXT + CONFIG.INSTANCE.SECURITYTXT_CONTACT)
140 }
141)
142
3f6d68d9
RK
143// nodeinfo service
144staticRouter.use('/.well-known/nodeinfo',
f2f0eda5 145 asyncMiddleware(cacheRoute()(ROUTE_CACHE_LIFETIME.NODEINFO)),
3f6d68d9
RK
146 (_, res: express.Response) => {
147 return res.json({
148 links: [
149 {
150 rel: 'http://nodeinfo.diaspora.software/ns/schema/2.0',
6dd9de95 151 href: WEBSERVER.URL + '/nodeinfo/2.0.json'
3f6d68d9
RK
152 }
153 ]
154 })
155 }
156)
157staticRouter.use('/nodeinfo/:version.json',
f2f0eda5 158 asyncMiddleware(cacheRoute()(ROUTE_CACHE_LIFETIME.NODEINFO)),
3f6d68d9
RK
159 asyncMiddleware(generateNodeinfo)
160)
ac235c37 161
aad0ec24
RK
162// dnt-policy.txt service (see https://www.eff.org/dnt-policy)
163staticRouter.use('/.well-known/dnt-policy.txt',
f2f0eda5 164 asyncMiddleware(cacheRoute()(ROUTE_CACHE_LIFETIME.DNT_POLICY)),
aad0ec24
RK
165 (_, res: express.Response) => {
166 res.type('text/plain')
aac0118d 167
d1105b97 168 return res.sendFile(join(root(), 'dist/server/static/dnt-policy/dnt-policy-1.0.txt'))
aad0ec24
RK
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' })
31414127
RK
176 }
177)
178
179staticRouter.use('/.well-known/change-password',
180 (_, res: express.Response) => {
181 res.redirect('/my-account/settings')
aad0ec24
RK
182 }
183)
184
3ddb1ec5
C
185staticRouter.use('/.well-known/host-meta',
186 (_, res: express.Response) => {
03371ad9 187 res.type('application/xml')
3ddb1ec5
C
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
65fcc311
C
198// ---------------------------------------------------------------------------
199
200export {
201 staticRouter
202}
f981dae8
C
203
204// ---------------------------------------------------------------------------
205
536598cf 206async function generateNodeinfo (req: express.Request, res: express.Response) {
3f6d68d9
RK
207 const { totalVideos } = await VideoModel.getStats()
208 const { totalLocalVideoComments } = await VideoCommentModel.getStats()
209 const { totalUsers } = 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',
66170ca8 217 version: PEERTUBE_VERSION
3f6d68d9
RK
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 },
234 localPosts: totalVideos,
235 localComments: totalLocalVideoComments
236 },
237 metadata: {
238 taxonomy: {
239 postsName: 'Videos'
240 },
241 nodeName: CONFIG.INSTANCE.NAME,
174e0855
RK
242 nodeDescription: CONFIG.INSTANCE.SHORT_DESCRIPTION,
243 nodeConfig: {
9677fca7
RK
244 search: {
245 remoteUri: {
246 users: CONFIG.SEARCH.REMOTE_URI.USERS,
247 anonymous: CONFIG.SEARCH.REMOTE_URI.ANONYMOUS
248 }
249 },
174e0855
RK
250 plugin: {
251 registered: getRegisteredPlugins()
252 },
253 theme: {
254 registered: getRegisteredThemes(),
255 default: getThemeOrDefault(CONFIG.THEME.DEFAULT, DEFAULT_THEME_NAME)
256 },
257 email: {
4c1c1709 258 enabled: isEmailEnabled()
174e0855
RK
259 },
260 contactForm: {
261 enabled: CONFIG.CONTACT_FORM.ENABLED
262 },
263 transcoding: {
264 hls: {
265 enabled: CONFIG.TRANSCODING.HLS.ENABLED
266 },
267 webtorrent: {
268 enabled: CONFIG.TRANSCODING.WEBTORRENT.ENABLED
269 },
c6c0fa6c
C
270 enabledResolutions: getEnabledResolutions('vod')
271 },
272 live: {
273 enabled: CONFIG.LIVE.ENABLED,
274 transcoding: {
275 enabled: CONFIG.LIVE.TRANSCODING.ENABLED,
276 enabledResolutions: getEnabledResolutions('live')
277 }
174e0855
RK
278 },
279 import: {
280 videos: {
281 http: {
282 enabled: CONFIG.IMPORT.VIDEOS.HTTP.ENABLED
283 },
284 torrent: {
285 enabled: CONFIG.IMPORT.VIDEOS.TORRENT.ENABLED
286 }
287 }
288 },
289 autoBlacklist: {
290 videos: {
291 ofUsers: {
292 enabled: CONFIG.AUTO_BLACKLIST.VIDEOS.OF_USERS.ENABLED
293 }
294 }
295 },
296 avatar: {
297 file: {
298 size: {
299 max: CONSTRAINTS_FIELDS.ACTORS.AVATAR.FILE_SIZE.max
300 },
301 extensions: CONSTRAINTS_FIELDS.ACTORS.AVATAR.EXTNAME
302 }
303 },
304 video: {
305 image: {
306 extensions: CONSTRAINTS_FIELDS.VIDEOS.IMAGE.EXTNAME,
307 size: {
308 max: CONSTRAINTS_FIELDS.VIDEOS.IMAGE.FILE_SIZE.max
309 }
310 },
311 file: {
312 extensions: CONSTRAINTS_FIELDS.VIDEOS.EXTNAME
313 }
314 },
315 videoCaption: {
316 file: {
317 size: {
318 max: CONSTRAINTS_FIELDS.VIDEO_CAPTIONS.CAPTION_FILE.FILE_SIZE.max
319 },
320 extensions: CONSTRAINTS_FIELDS.VIDEO_CAPTIONS.CAPTION_FILE.EXTNAME
321 }
322 },
323 user: {
324 videoQuota: CONFIG.USER.VIDEO_QUOTA,
325 videoQuotaDaily: CONFIG.USER.VIDEO_QUOTA_DAILY
326 },
327 trending: {
328 videos: {
329 intervalDays: CONFIG.TRENDING.VIDEOS.INTERVAL_DAYS
330 }
331 },
332 tracker: {
333 enabled: CONFIG.TRACKER.ENABLED
334 }
335 }
3f6d68d9
RK
336 }
337 } as HttpNodeinfoDiasporaSoftwareNsSchema20
98d3324d 338 res.contentType('application/json; profile="http://nodeinfo.diaspora.software/ns/schema/2.0#"')
3f6d68d9
RK
339 } else {
340 json = { error: 'Nodeinfo schema version not handled' }
2d53be02 341 res.status(HttpStatusCode.NOT_FOUND_404)
3f6d68d9
RK
342 }
343
98d3324d 344 return res.send(json).end()
3f6d68d9
RK
345}
346
a1587156 347function downloadTorrent (req: express.Request, res: express.Response) {
d7a25329
C
348 const video = res.locals.videoAll
349
350 const videoFile = getVideoFile(req, video.VideoFiles)
2d53be02 351 if (!videoFile) return res.status(HttpStatusCode.NOT_FOUND_404).end()
d7a25329
C
352
353 return res.download(getTorrentFilePath(video, videoFile), `${video.name}-${videoFile.resolution}p.torrent`)
354}
355
a1587156 356function downloadHLSVideoFileTorrent (req: express.Request, res: express.Response) {
d7a25329
C
357 const video = res.locals.videoAll
358
359 const playlist = getHLSPlaylist(video)
2d53be02 360 if (!playlist) return res.status(HttpStatusCode.NOT_FOUND_404).end
d7a25329
C
361
362 const videoFile = getVideoFile(req, playlist.VideoFiles)
2d53be02 363 if (!videoFile) return res.status(HttpStatusCode.NOT_FOUND_404).end()
02756fbd 364
d7a25329 365 return res.download(getTorrentFilePath(playlist, videoFile), `${video.name}-${videoFile.resolution}p-hls.torrent`)
02756fbd
C
366}
367
a1587156 368function downloadVideoFile (req: express.Request, res: express.Response) {
d7a25329
C
369 const video = res.locals.videoAll
370
371 const videoFile = getVideoFile(req, video.VideoFiles)
2d53be02 372 if (!videoFile) return res.status(HttpStatusCode.NOT_FOUND_404).end()
02756fbd 373
d7a25329 374 return res.download(getVideoFilePath(video, videoFile), `${video.name}-${videoFile.resolution}p${videoFile.extname}`)
02756fbd
C
375}
376
a1587156 377function downloadHLSVideoFile (req: express.Request, res: express.Response) {
453e83ea 378 const video = res.locals.videoAll
d7a25329 379 const playlist = getHLSPlaylist(video)
2d53be02 380 if (!playlist) return res.status(HttpStatusCode.NOT_FOUND_404).end
d7a25329
C
381
382 const videoFile = getVideoFile(req, playlist.VideoFiles)
2d53be02 383 if (!videoFile) return res.status(HttpStatusCode.NOT_FOUND_404).end()
d7a25329
C
384
385 const filename = `${video.name}-${videoFile.resolution}p-${playlist.getStringType()}${videoFile.extname}`
386 return res.download(getVideoFilePath(playlist, videoFile), filename)
387}
388
389function getVideoFile (req: express.Request, files: MVideoFile[]) {
390 const resolution = parseInt(req.params.resolution, 10)
391 return files.find(f => f.resolution === resolution)
392}
02756fbd 393
d7a25329
C
394function getHLSPlaylist (video: MVideoFullLight) {
395 const playlist = video.VideoStreamingPlaylists.find(p => p.type === VideoStreamingPlaylistType.HLS)
396 if (!playlist) return undefined
02756fbd 397
d7a25329 398 return Object.assign(playlist, { Video: video })
02756fbd 399}
f2eb23cd
RK
400
401function getCup (req: express.Request, res: express.Response, next: express.NextFunction) {
402 res.status(HttpStatusCode.I_AM_A_TEAPOT_418)
403 res.setHeader('Accept-Additions', 'Non-Dairy;1,Sugar;1')
404 res.setHeader('Safe', 'if-sepia-awake')
405
406 return next()
407}