]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - server/controllers/static.ts
0aab12756ad53fd56910bd97975c035f9fc65295
[github/Chocobozzz/PeerTube.git] / server / controllers / static.ts
1 import * as cors from 'cors'
2 import * as express from 'express'
3 import {
4 HLS_STREAMING_PLAYLIST_DIRECTORY,
5 PEERTUBE_VERSION,
6 ROUTE_CACHE_LIFETIME,
7 STATIC_DOWNLOAD_PATHS,
8 STATIC_MAX_AGE,
9 STATIC_PATHS,
10 WEBSERVER
11 } from '../initializers/constants'
12 import { cacheRoute } from '../middlewares/cache'
13 import { asyncMiddleware, videosDownloadValidator } from '../middlewares'
14 import { VideoModel } from '../models/video/video'
15 import { UserModel } from '../models/account/user'
16 import { VideoCommentModel } from '../models/video/video-comment'
17 import { HttpNodeinfoDiasporaSoftwareNsSchema20 } from '../../shared/models/nodeinfo'
18 import { join } from 'path'
19 import { root } from '../helpers/core-utils'
20 import { CONFIG } from '../initializers/config'
21 import { getPreview, getVideoCaption } from './lazy-static'
22 import { VideoStreamingPlaylistType } from '@shared/models/videos/video-streaming-playlist.type'
23 import { MVideoFile, MVideoFullLight } from '@server/typings/models'
24 import { getTorrentFilePath, getVideoFilePath } from '@server/lib/video-paths'
25
26 const staticRouter = express.Router()
27
28 staticRouter.use(cors())
29
30 /*
31 Cors is very important to let other servers access torrent and video files
32 */
33
34 const torrentsPhysicalPath = CONFIG.STORAGE.TORRENTS_DIR
35 staticRouter.use(
36 STATIC_PATHS.TORRENTS,
37 cors(),
38 express.static(torrentsPhysicalPath, { maxAge: 0 }) // Don't cache because we could regenerate the torrent file
39 )
40 staticRouter.use(
41 STATIC_DOWNLOAD_PATHS.TORRENTS + ':id-:resolution([0-9]+).torrent',
42 asyncMiddleware(videosDownloadValidator),
43 asyncMiddleware(downloadTorrent)
44 )
45 staticRouter.use(
46 STATIC_DOWNLOAD_PATHS.TORRENTS + ':id-:resolution([0-9]+)-hls.torrent',
47 asyncMiddleware(videosDownloadValidator),
48 asyncMiddleware(downloadHLSVideoFileTorrent)
49 )
50
51 // Videos path for webseeding
52 staticRouter.use(
53 STATIC_PATHS.WEBSEED,
54 cors(),
55 express.static(CONFIG.STORAGE.VIDEOS_DIR, { fallthrough: false }) // 404 because we don't have this video
56 )
57 staticRouter.use(
58 STATIC_PATHS.REDUNDANCY,
59 cors(),
60 express.static(CONFIG.STORAGE.REDUNDANCY_DIR, { fallthrough: false }) // 404 because we don't have this video
61 )
62
63 staticRouter.use(
64 STATIC_DOWNLOAD_PATHS.VIDEOS + ':id-:resolution([0-9]+).:extension',
65 asyncMiddleware(videosDownloadValidator),
66 asyncMiddleware(downloadVideoFile)
67 )
68
69 staticRouter.use(
70 STATIC_DOWNLOAD_PATHS.HLS_VIDEOS + ':id-:resolution([0-9]+)-fragmented.:extension',
71 asyncMiddleware(videosDownloadValidator),
72 asyncMiddleware(downloadHLSVideoFile)
73 )
74
75 // HLS
76 staticRouter.use(
77 STATIC_PATHS.STREAMING_PLAYLISTS.HLS,
78 cors(),
79 express.static(HLS_STREAMING_PLAYLIST_DIRECTORY, { fallthrough: false }) // 404 if the file does not exist
80 )
81
82 // Thumbnails path for express
83 const thumbnailsPhysicalPath = CONFIG.STORAGE.THUMBNAILS_DIR
84 staticRouter.use(
85 STATIC_PATHS.THUMBNAILS,
86 express.static(thumbnailsPhysicalPath, { maxAge: STATIC_MAX_AGE.SERVER, fallthrough: false }) // 404 if the file does not exist
87 )
88
89 // DEPRECATED: use lazy-static route instead
90 const avatarsPhysicalPath = CONFIG.STORAGE.AVATARS_DIR
91 staticRouter.use(
92 STATIC_PATHS.AVATARS,
93 express.static(avatarsPhysicalPath, { maxAge: STATIC_MAX_AGE.SERVER, fallthrough: false }) // 404 if the file does not exist
94 )
95
96 // DEPRECATED: use lazy-static route instead
97 staticRouter.use(
98 STATIC_PATHS.PREVIEWS + ':uuid.jpg',
99 asyncMiddleware(getPreview)
100 )
101
102 // DEPRECATED: use lazy-static route instead
103 staticRouter.use(
104 STATIC_PATHS.VIDEO_CAPTIONS + ':videoId-:captionLanguage([a-z]+).vtt',
105 asyncMiddleware(getVideoCaption)
106 )
107
108 // robots.txt service
109 staticRouter.get('/robots.txt',
110 asyncMiddleware(cacheRoute(ROUTE_CACHE_LIFETIME.ROBOTS)),
111 (_, res: express.Response) => {
112 res.type('text/plain')
113 return res.send(CONFIG.INSTANCE.ROBOTS)
114 }
115 )
116
117 // security.txt service
118 staticRouter.get('/security.txt',
119 (_, res: express.Response) => {
120 return res.redirect(301, '/.well-known/security.txt')
121 }
122 )
123
124 staticRouter.get('/.well-known/security.txt',
125 asyncMiddleware(cacheRoute(ROUTE_CACHE_LIFETIME.SECURITYTXT)),
126 (_, res: express.Response) => {
127 res.type('text/plain')
128 return res.send(CONFIG.INSTANCE.SECURITYTXT + CONFIG.INSTANCE.SECURITYTXT_CONTACT)
129 }
130 )
131
132 // nodeinfo service
133 staticRouter.use('/.well-known/nodeinfo',
134 asyncMiddleware(cacheRoute(ROUTE_CACHE_LIFETIME.NODEINFO)),
135 (_, res: express.Response) => {
136 return res.json({
137 links: [
138 {
139 rel: 'http://nodeinfo.diaspora.software/ns/schema/2.0',
140 href: WEBSERVER.URL + '/nodeinfo/2.0.json'
141 }
142 ]
143 })
144 }
145 )
146 staticRouter.use('/nodeinfo/:version.json',
147 asyncMiddleware(cacheRoute(ROUTE_CACHE_LIFETIME.NODEINFO)),
148 asyncMiddleware(generateNodeinfo)
149 )
150
151 // dnt-policy.txt service (see https://www.eff.org/dnt-policy)
152 staticRouter.use('/.well-known/dnt-policy.txt',
153 asyncMiddleware(cacheRoute(ROUTE_CACHE_LIFETIME.DNT_POLICY)),
154 (_, res: express.Response) => {
155 res.type('text/plain')
156
157 return res.sendFile(join(root(), 'dist/server/static/dnt-policy/dnt-policy-1.0.txt'))
158 }
159 )
160
161 // dnt service (see https://www.w3.org/TR/tracking-dnt/#status-resource)
162 staticRouter.use('/.well-known/dnt/',
163 (_, res: express.Response) => {
164 res.json({ tracking: 'N' })
165 }
166 )
167
168 staticRouter.use('/.well-known/change-password',
169 (_, res: express.Response) => {
170 res.redirect('/my-account/settings')
171 }
172 )
173
174 staticRouter.use('/.well-known/host-meta',
175 (_, res: express.Response) => {
176 res.type('application/xml')
177
178 const xml = '<?xml version="1.0" encoding="UTF-8"?>\n' +
179 '<XRD xmlns="http://docs.oasis-open.org/ns/xri/xrd-1.0">\n' +
180 ` <Link rel="lrdd" type="application/xrd+xml" template="${WEBSERVER.URL}/.well-known/webfinger?resource={uri}"/>\n` +
181 '</XRD>'
182
183 res.send(xml).end()
184 }
185 )
186
187 // ---------------------------------------------------------------------------
188
189 export {
190 staticRouter
191 }
192
193 // ---------------------------------------------------------------------------
194
195 async function generateNodeinfo (req: express.Request, res: express.Response) {
196 const { totalVideos } = await VideoModel.getStats()
197 const { totalLocalVideoComments } = await VideoCommentModel.getStats()
198 const { totalUsers } = await UserModel.getStats()
199 let json = {}
200
201 if (req.params.version && (req.params.version === '2.0')) {
202 json = {
203 version: '2.0',
204 software: {
205 name: 'peertube',
206 version: PEERTUBE_VERSION
207 },
208 protocols: [
209 'activitypub'
210 ],
211 services: {
212 inbound: [],
213 outbound: [
214 'atom1.0',
215 'rss2.0'
216 ]
217 },
218 openRegistrations: CONFIG.SIGNUP.ENABLED,
219 usage: {
220 users: {
221 total: totalUsers
222 },
223 localPosts: totalVideos,
224 localComments: totalLocalVideoComments
225 },
226 metadata: {
227 taxonomy: {
228 postsName: 'Videos'
229 },
230 nodeName: CONFIG.INSTANCE.NAME,
231 nodeDescription: CONFIG.INSTANCE.SHORT_DESCRIPTION
232 }
233 } as HttpNodeinfoDiasporaSoftwareNsSchema20
234 res.contentType('application/json; profile="http://nodeinfo.diaspora.software/ns/schema/2.0#"')
235 } else {
236 json = { error: 'Nodeinfo schema version not handled' }
237 res.status(404)
238 }
239
240 return res.send(json).end()
241 }
242
243 async function downloadTorrent (req: express.Request, res: express.Response) {
244 const video = res.locals.videoAll
245
246 const videoFile = getVideoFile(req, video.VideoFiles)
247 if (!videoFile) return res.status(404).end()
248
249 return res.download(getTorrentFilePath(video, videoFile), `${video.name}-${videoFile.resolution}p.torrent`)
250 }
251
252 async function downloadHLSVideoFileTorrent (req: express.Request, res: express.Response) {
253 const video = res.locals.videoAll
254
255 const playlist = getHLSPlaylist(video)
256 if (!playlist) return res.status(404).end
257
258 const videoFile = getVideoFile(req, playlist.VideoFiles)
259 if (!videoFile) return res.status(404).end()
260
261 return res.download(getTorrentFilePath(playlist, videoFile), `${video.name}-${videoFile.resolution}p-hls.torrent`)
262 }
263
264 async function downloadVideoFile (req: express.Request, res: express.Response) {
265 const video = res.locals.videoAll
266
267 const videoFile = getVideoFile(req, video.VideoFiles)
268 if (!videoFile) return res.status(404).end()
269
270 return res.download(getVideoFilePath(video, videoFile), `${video.name}-${videoFile.resolution}p${videoFile.extname}`)
271 }
272
273 async function downloadHLSVideoFile (req: express.Request, res: express.Response) {
274 const video = res.locals.videoAll
275 const playlist = getHLSPlaylist(video)
276 if (!playlist) return res.status(404).end
277
278 const videoFile = getVideoFile(req, playlist.VideoFiles)
279 if (!videoFile) return res.status(404).end()
280
281 const filename = `${video.name}-${videoFile.resolution}p-${playlist.getStringType()}${videoFile.extname}`
282 return res.download(getVideoFilePath(playlist, videoFile), filename)
283 }
284
285 function getVideoFile (req: express.Request, files: MVideoFile[]) {
286 const resolution = parseInt(req.params.resolution, 10)
287 return files.find(f => f.resolution === resolution)
288 }
289
290 function getHLSPlaylist (video: MVideoFullLight) {
291 const playlist = video.VideoStreamingPlaylists.find(p => p.type === VideoStreamingPlaylistType.HLS)
292 if (!playlist) return undefined
293
294 return Object.assign(playlist, { Video: video })
295 }