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