]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - server/controllers/static.ts
Move controller in dedicated functions
[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, PEERTUBE_VERSION,
5 ROUTE_CACHE_LIFETIME,
6 STATIC_DOWNLOAD_PATHS,
7 STATIC_MAX_AGE,
8 STATIC_PATHS,
9 WEBSERVER
10 } from '../initializers/constants'
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 import { CONFIG } from '../initializers/config'
21
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: 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 staticRouter.use('/.well-known/host-meta',
159 (_, res: express.Response) => {
160 res.type('application/xml')
161
162 const xml = '<?xml version="1.0" encoding="UTF-8"?>\n' +
163 '<XRD xmlns="http://docs.oasis-open.org/ns/xri/xrd-1.0">\n' +
164 ` <Link rel="lrdd" type="application/xrd+xml" template="${WEBSERVER.URL}/.well-known/webfinger?resource={uri}"/>\n` +
165 '</XRD>'
166
167 res.send(xml).end()
168 }
169 )
170
171 // ---------------------------------------------------------------------------
172
173 export {
174 staticRouter
175 }
176
177 // ---------------------------------------------------------------------------
178
179 async function getPreview (req: express.Request, res: express.Response) {
180 const result = await VideosPreviewCache.Instance.getFilePath(req.params.uuid)
181 if (!result) return res.sendStatus(404)
182
183 return res.sendFile(result.path, { maxAge: STATIC_MAX_AGE })
184 }
185
186 async function getVideoCaption (req: express.Request, res: express.Response) {
187 const result = await VideosCaptionCache.Instance.getFilePath({
188 videoId: req.params.videoId,
189 language: req.params.captionLanguage
190 })
191 if (!result) return res.sendStatus(404)
192
193 return res.sendFile(result.path, { maxAge: STATIC_MAX_AGE })
194 }
195
196 async function generateNodeinfo (req: express.Request, res: express.Response) {
197 const { totalVideos } = await VideoModel.getStats()
198 const { totalLocalVideoComments } = await VideoCommentModel.getStats()
199 const { totalUsers } = await UserModel.getStats()
200 let json = {}
201
202 if (req.params.version && (req.params.version === '2.0')) {
203 json = {
204 version: '2.0',
205 software: {
206 name: 'peertube',
207 version: PEERTUBE_VERSION
208 },
209 protocols: [
210 'activitypub'
211 ],
212 services: {
213 inbound: [],
214 outbound: [
215 'atom1.0',
216 'rss2.0'
217 ]
218 },
219 openRegistrations: CONFIG.SIGNUP.ENABLED,
220 usage: {
221 users: {
222 total: totalUsers
223 },
224 localPosts: totalVideos,
225 localComments: totalLocalVideoComments
226 },
227 metadata: {
228 taxonomy: {
229 postsName: 'Videos'
230 },
231 nodeName: CONFIG.INSTANCE.NAME,
232 nodeDescription: CONFIG.INSTANCE.SHORT_DESCRIPTION
233 }
234 } as HttpNodeinfoDiasporaSoftwareNsSchema20
235 res.contentType('application/json; profile="http://nodeinfo.diaspora.software/ns/schema/2.0#"')
236 } else {
237 json = { error: 'Nodeinfo schema version not handled' }
238 res.status(404)
239 }
240
241 return res.send(json).end()
242 }
243
244 async function downloadTorrent (req: express.Request, res: express.Response, next: express.NextFunction) {
245 const { video, videoFile } = getVideoAndFile(req, res)
246 if (!videoFile) return res.status(404).end()
247
248 return res.download(video.getTorrentFilePath(videoFile), `${video.name}-${videoFile.resolution}p.torrent`)
249 }
250
251 async function downloadVideoFile (req: express.Request, res: express.Response, next: express.NextFunction) {
252 const { video, videoFile } = getVideoAndFile(req, res)
253 if (!videoFile) return res.status(404).end()
254
255 return res.download(video.getVideoFilePath(videoFile), `${video.name}-${videoFile.resolution}p${videoFile.extname}`)
256 }
257
258 function getVideoAndFile (req: express.Request, res: express.Response) {
259 const resolution = parseInt(req.params.resolution, 10)
260 const video = res.locals.video
261
262 const videoFile = video.VideoFiles.find(f => f.resolution === resolution)
263
264 return { video, videoFile }
265 }