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