]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - server/controllers/static.ts
e65c7afd3991382310f1bb40d54b44c99bc4c94f
[github/Chocobozzz/PeerTube.git] / server / controllers / static.ts
1 import * as cors from 'cors'
2 import * as express from 'express'
3 import {
4 CONFIG,
5 HLS_STREAMING_PLAYLIST_DIRECTORY,
6 ROUTE_CACHE_LIFETIME,
7 STATIC_DOWNLOAD_PATHS,
8 STATIC_MAX_AGE,
9 STATIC_PATHS
10 } from '../initializers'
11 import { VideosCaptionCache, VideosPreviewCache } from '../lib/files-cache'
12 import { cacheRoute } from '../middlewares/cache'
13 import { asyncMiddleware, videosGetValidator } 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
21 const packageJSON = require('../../../package.json')
22 const staticRouter = express.Router()
23
24 staticRouter.use(cors())
25
26 /*
27 Cors is very important to let other servers access torrent and video files
28 */
29
30 const torrentsPhysicalPath = CONFIG.STORAGE.TORRENTS_DIR
31 staticRouter.use(
32 STATIC_PATHS.TORRENTS,
33 cors(),
34 express.static(torrentsPhysicalPath, { maxAge: 0 }) // Don't cache because we could regenerate the torrent file
35 )
36 staticRouter.use(
37 STATIC_DOWNLOAD_PATHS.TORRENTS + ':id-:resolution([0-9]+).torrent',
38 asyncMiddleware(videosGetValidator),
39 asyncMiddleware(downloadTorrent)
40 )
41
42 // Videos path for webseeding
43 staticRouter.use(
44 STATIC_PATHS.WEBSEED,
45 cors(),
46 express.static(CONFIG.STORAGE.VIDEOS_DIR, { fallthrough: false }) // 404 because we don't have this video
47 )
48 staticRouter.use(
49 STATIC_PATHS.REDUNDANCY,
50 cors(),
51 express.static(CONFIG.STORAGE.REDUNDANCY_DIR, { fallthrough: false }) // 404 because we don't have this video
52 )
53
54 staticRouter.use(
55 STATIC_DOWNLOAD_PATHS.VIDEOS + ':id-:resolution([0-9]+).:extension',
56 asyncMiddleware(videosGetValidator),
57 asyncMiddleware(downloadVideoFile)
58 )
59
60 // HLS
61 staticRouter.use(
62 STATIC_PATHS.STREAMING_PLAYLISTS.HLS,
63 cors(),
64 express.static(HLS_STREAMING_PLAYLIST_DIRECTORY, { fallthrough: false }) // 404 if the file does not exist
65 )
66
67 // Thumbnails path for express
68 const thumbnailsPhysicalPath = CONFIG.STORAGE.THUMBNAILS_DIR
69 staticRouter.use(
70 STATIC_PATHS.THUMBNAILS,
71 express.static(thumbnailsPhysicalPath, { maxAge: STATIC_MAX_AGE, fallthrough: false }) // 404 if the file does not exist
72 )
73
74 const avatarsPhysicalPath = CONFIG.STORAGE.AVATARS_DIR
75 staticRouter.use(
76 STATIC_PATHS.AVATARS,
77 express.static(avatarsPhysicalPath, { maxAge: STATIC_MAX_AGE, fallthrough: false }) // 404 if the file does not exist
78 )
79
80 // We don't have video previews, fetch them from the origin instance
81 staticRouter.use(
82 STATIC_PATHS.PREVIEWS + ':uuid.jpg',
83 asyncMiddleware(getPreview)
84 )
85
86 // We don't have video captions, fetch them from the origin instance
87 staticRouter.use(
88 STATIC_PATHS.VIDEO_CAPTIONS + ':videoId-:captionLanguage([a-z]+).vtt',
89 asyncMiddleware(getVideoCaption)
90 )
91
92 // robots.txt service
93 staticRouter.get('/robots.txt',
94 asyncMiddleware(cacheRoute(ROUTE_CACHE_LIFETIME.ROBOTS)),
95 (_, res: express.Response) => {
96 res.type('text/plain')
97 return res.send(CONFIG.INSTANCE.ROBOTS)
98 }
99 )
100
101 // security.txt service
102 staticRouter.get('/security.txt',
103 (_, res: express.Response) => {
104 return res.redirect(301, '/.well-known/security.txt')
105 }
106 )
107
108 staticRouter.get('/.well-known/security.txt',
109 asyncMiddleware(cacheRoute(ROUTE_CACHE_LIFETIME.SECURITYTXT)),
110 (_, res: express.Response) => {
111 res.type('text/plain')
112 return res.send(CONFIG.INSTANCE.SECURITYTXT + CONFIG.INSTANCE.SECURITYTXT_CONTACT)
113 }
114 )
115
116 // nodeinfo service
117 staticRouter.use('/.well-known/nodeinfo',
118 asyncMiddleware(cacheRoute(ROUTE_CACHE_LIFETIME.NODEINFO)),
119 (_, res: express.Response) => {
120 return res.json({
121 links: [
122 {
123 rel: 'http://nodeinfo.diaspora.software/ns/schema/2.0',
124 href: CONFIG.WEBSERVER.URL + '/nodeinfo/2.0.json'
125 }
126 ]
127 })
128 }
129 )
130 staticRouter.use('/nodeinfo/:version.json',
131 asyncMiddleware(cacheRoute(ROUTE_CACHE_LIFETIME.NODEINFO)),
132 asyncMiddleware(generateNodeinfo)
133 )
134
135 // dnt-policy.txt service (see https://www.eff.org/dnt-policy)
136 staticRouter.use('/.well-known/dnt-policy.txt',
137 asyncMiddleware(cacheRoute(ROUTE_CACHE_LIFETIME.DNT_POLICY)),
138 (_, res: express.Response) => {
139 res.type('text/plain')
140
141 return res.sendFile(join(root(), 'dist/server/static/dnt-policy/dnt-policy-1.0.txt'))
142 }
143 )
144
145 // dnt service (see https://www.w3.org/TR/tracking-dnt/#status-resource)
146 staticRouter.use('/.well-known/dnt/',
147 (_, res: express.Response) => {
148 res.json({ tracking: 'N' })
149 }
150 )
151
152 staticRouter.use('/.well-known/change-password',
153 (_, res: express.Response) => {
154 res.redirect('/my-account/settings')
155 }
156 )
157
158 // ---------------------------------------------------------------------------
159
160 export {
161 staticRouter
162 }
163
164 // ---------------------------------------------------------------------------
165
166 async function getPreview (req: express.Request, res: express.Response, next: express.NextFunction) {
167 const path = await VideosPreviewCache.Instance.getFilePath(req.params.uuid)
168 if (!path) return res.sendStatus(404)
169
170 return res.sendFile(path, { maxAge: STATIC_MAX_AGE })
171 }
172
173 async function getVideoCaption (req: express.Request, res: express.Response) {
174 const path = await VideosCaptionCache.Instance.getFilePath({
175 videoId: req.params.videoId,
176 language: req.params.captionLanguage
177 })
178 if (!path) return res.sendStatus(404)
179
180 return res.sendFile(path, { maxAge: STATIC_MAX_AGE })
181 }
182
183 async function generateNodeinfo (req: express.Request, res: express.Response, next: express.NextFunction) {
184 const { totalVideos } = await VideoModel.getStats()
185 const { totalLocalVideoComments } = await VideoCommentModel.getStats()
186 const { totalUsers } = await UserModel.getStats()
187 let json = {}
188
189 if (req.params.version && (req.params.version === '2.0')) {
190 json = {
191 version: '2.0',
192 software: {
193 name: 'peertube',
194 version: packageJSON.version
195 },
196 protocols: [
197 'activitypub'
198 ],
199 services: {
200 inbound: [],
201 outbound: [
202 'atom1.0',
203 'rss2.0'
204 ]
205 },
206 openRegistrations: CONFIG.SIGNUP.ENABLED,
207 usage: {
208 users: {
209 total: totalUsers
210 },
211 localPosts: totalVideos,
212 localComments: totalLocalVideoComments
213 },
214 metadata: {
215 taxonomy: {
216 postsName: 'Videos'
217 },
218 nodeName: CONFIG.INSTANCE.NAME,
219 nodeDescription: CONFIG.INSTANCE.SHORT_DESCRIPTION
220 }
221 } as HttpNodeinfoDiasporaSoftwareNsSchema20
222 res.contentType('application/json; profile="http://nodeinfo.diaspora.software/ns/schema/2.0#"')
223 } else {
224 json = { error: 'Nodeinfo schema version not handled' }
225 res.status(404)
226 }
227
228 return res.send(json).end()
229 }
230
231 async function downloadTorrent (req: express.Request, res: express.Response, next: express.NextFunction) {
232 const { video, videoFile } = getVideoAndFile(req, res)
233 if (!videoFile) return res.status(404).end()
234
235 return res.download(video.getTorrentFilePath(videoFile), `${video.name}-${videoFile.resolution}p.torrent`)
236 }
237
238 async function downloadVideoFile (req: express.Request, res: express.Response, next: express.NextFunction) {
239 const { video, videoFile } = getVideoAndFile(req, res)
240 if (!videoFile) return res.status(404).end()
241
242 return res.download(video.getVideoFilePath(videoFile), `${video.name}-${videoFile.resolution}p${videoFile.extname}`)
243 }
244
245 function getVideoAndFile (req: express.Request, res: express.Response) {
246 const resolution = parseInt(req.params.resolution, 10)
247 const video = res.locals.video
248
249 const videoFile = video.VideoFiles.find(f => f.resolution === resolution)
250
251 return { video, videoFile }
252 }