1 import * as cors from 'cors'
2 import * as express from 'express'
6 HLS_STREAMING_PLAYLIST_DIRECTORY,
13 } from '../initializers/constants'
14 import { cacheRoute } from '../middlewares/cache'
15 import { asyncMiddleware, videosDownloadValidator } from '../middlewares'
16 import { VideoModel } from '../models/video/video'
17 import { UserModel } from '../models/account/user'
18 import { VideoCommentModel } from '../models/video/video-comment'
19 import { HttpNodeinfoDiasporaSoftwareNsSchema20 } from '../../shared/models/nodeinfo'
20 import { join } from 'path'
21 import { root } from '../helpers/core-utils'
22 import { CONFIG, isEmailEnabled } from '../initializers/config'
23 import { getPreview, getVideoCaption } from './lazy-static'
24 import { VideoStreamingPlaylistType } from '@shared/models/videos/video-streaming-playlist.type'
25 import { MVideoFile, MVideoFullLight } from '@server/types/models'
26 import { getTorrentFilePath, getVideoFilePath } from '@server/lib/video-paths'
27 import { getThemeOrDefault } from '../lib/plugins/theme-utils'
28 import { getEnabledResolutions, getRegisteredPlugins, getRegisteredThemes } from '@server/controllers/api/config'
29 import { HttpStatusCode } from '@shared/core-utils/miscs/http-error-codes'
30 import { serveIndexHTML } from '@server/lib/client-html'
32 const staticRouter = express.Router()
34 staticRouter.use(cors())
37 Cors is very important to let other servers access torrent and video files
40 const torrentsPhysicalPath = CONFIG.STORAGE.TORRENTS_DIR
42 STATIC_PATHS.TORRENTS,
44 express.static(torrentsPhysicalPath, { maxAge: 0 }) // Don't cache because we could regenerate the torrent file
47 STATIC_DOWNLOAD_PATHS.TORRENTS + ':id-:resolution([0-9]+).torrent',
48 asyncMiddleware(videosDownloadValidator),
52 STATIC_DOWNLOAD_PATHS.TORRENTS + ':id-:resolution([0-9]+)-hls.torrent',
53 asyncMiddleware(videosDownloadValidator),
54 downloadHLSVideoFileTorrent
57 // Videos path for webseeding
61 express.static(CONFIG.STORAGE.VIDEOS_DIR, { fallthrough: false }) // 404 because we don't have this video
64 STATIC_PATHS.REDUNDANCY,
66 express.static(CONFIG.STORAGE.REDUNDANCY_DIR, { fallthrough: false }) // 404 because we don't have this video
70 STATIC_DOWNLOAD_PATHS.VIDEOS + ':id-:resolution([0-9]+).:extension',
71 asyncMiddleware(videosDownloadValidator),
76 STATIC_DOWNLOAD_PATHS.HLS_VIDEOS + ':id-:resolution([0-9]+)-fragmented.:extension',
77 asyncMiddleware(videosDownloadValidator),
83 STATIC_PATHS.STREAMING_PLAYLISTS.HLS,
85 express.static(HLS_STREAMING_PLAYLIST_DIRECTORY, { fallthrough: false }) // 404 if the file does not exist
88 // Thumbnails path for express
89 const thumbnailsPhysicalPath = CONFIG.STORAGE.THUMBNAILS_DIR
91 STATIC_PATHS.THUMBNAILS,
92 express.static(thumbnailsPhysicalPath, { maxAge: STATIC_MAX_AGE.SERVER, fallthrough: false }) // 404 if the file does not exist
95 // DEPRECATED: use lazy-static route instead
96 const avatarsPhysicalPath = CONFIG.STORAGE.AVATARS_DIR
99 express.static(avatarsPhysicalPath, { maxAge: STATIC_MAX_AGE.SERVER, fallthrough: false }) // 404 if the file does not exist
102 // DEPRECATED: use lazy-static route instead
104 STATIC_PATHS.PREVIEWS + ':uuid.jpg',
105 asyncMiddleware(getPreview)
108 // DEPRECATED: use lazy-static route instead
110 STATIC_PATHS.VIDEO_CAPTIONS + ':videoId-:captionLanguage([a-z]+).vtt',
111 asyncMiddleware(getVideoCaption)
114 // robots.txt service
115 staticRouter.get('/robots.txt',
116 asyncMiddleware(cacheRoute()(ROUTE_CACHE_LIFETIME.ROBOTS)),
117 (_, res: express.Response) => {
118 res.type('text/plain')
119 return res.send(CONFIG.INSTANCE.ROBOTS)
123 staticRouter.all('/teapot',
125 asyncMiddleware(serveIndexHTML)
128 // security.txt service
129 staticRouter.get('/security.txt',
130 (_, res: express.Response) => {
131 return res.redirect(HttpStatusCode.MOVED_PERMANENTLY_301, '/.well-known/security.txt')
135 staticRouter.get('/.well-known/security.txt',
136 asyncMiddleware(cacheRoute()(ROUTE_CACHE_LIFETIME.SECURITYTXT)),
137 (_, res: express.Response) => {
138 res.type('text/plain')
139 return res.send(CONFIG.INSTANCE.SECURITYTXT + CONFIG.INSTANCE.SECURITYTXT_CONTACT)
144 staticRouter.use('/.well-known/nodeinfo',
145 asyncMiddleware(cacheRoute()(ROUTE_CACHE_LIFETIME.NODEINFO)),
146 (_, res: express.Response) => {
150 rel: 'http://nodeinfo.diaspora.software/ns/schema/2.0',
151 href: WEBSERVER.URL + '/nodeinfo/2.0.json'
157 staticRouter.use('/nodeinfo/:version.json',
158 asyncMiddleware(cacheRoute()(ROUTE_CACHE_LIFETIME.NODEINFO)),
159 asyncMiddleware(generateNodeinfo)
162 // dnt-policy.txt service (see https://www.eff.org/dnt-policy)
163 staticRouter.use('/.well-known/dnt-policy.txt',
164 asyncMiddleware(cacheRoute()(ROUTE_CACHE_LIFETIME.DNT_POLICY)),
165 (_, res: express.Response) => {
166 res.type('text/plain')
168 return res.sendFile(join(root(), 'dist/server/static/dnt-policy/dnt-policy-1.0.txt'))
172 // dnt service (see https://www.w3.org/TR/tracking-dnt/#status-resource)
173 staticRouter.use('/.well-known/dnt/',
174 (_, res: express.Response) => {
175 res.json({ tracking: 'N' })
179 staticRouter.use('/.well-known/change-password',
180 (_, res: express.Response) => {
181 res.redirect('/my-account/settings')
185 staticRouter.use('/.well-known/host-meta',
186 (_, res: express.Response) => {
187 res.type('application/xml')
189 const xml = '<?xml version="1.0" encoding="UTF-8"?>\n' +
190 '<XRD xmlns="http://docs.oasis-open.org/ns/xri/xrd-1.0">\n' +
191 ` <Link rel="lrdd" type="application/xrd+xml" template="${WEBSERVER.URL}/.well-known/webfinger?resource={uri}"/>\n` +
198 // ---------------------------------------------------------------------------
204 // ---------------------------------------------------------------------------
206 async function generateNodeinfo (req: express.Request, res: express.Response) {
207 const { totalVideos } = await VideoModel.getStats()
208 const { totalLocalVideoComments } = await VideoCommentModel.getStats()
209 const { totalUsers, totalMonthlyActiveUsers, totalHalfYearActiveUsers } = await UserModel.getStats()
212 if (req.params.version && (req.params.version === '2.0')) {
217 version: PEERTUBE_VERSION
229 openRegistrations: CONFIG.SIGNUP.ENABLED,
233 activeMonth: totalMonthlyActiveUsers,
234 activeHalfyear: totalHalfYearActiveUsers
236 localPosts: totalVideos,
237 localComments: totalLocalVideoComments
243 nodeName: CONFIG.INSTANCE.NAME,
244 nodeDescription: CONFIG.INSTANCE.SHORT_DESCRIPTION,
248 users: CONFIG.SEARCH.REMOTE_URI.USERS,
249 anonymous: CONFIG.SEARCH.REMOTE_URI.ANONYMOUS
253 registered: getRegisteredPlugins()
256 registered: getRegisteredThemes(),
257 default: getThemeOrDefault(CONFIG.THEME.DEFAULT, DEFAULT_THEME_NAME)
260 enabled: isEmailEnabled()
263 enabled: CONFIG.CONTACT_FORM.ENABLED
267 enabled: CONFIG.TRANSCODING.HLS.ENABLED
270 enabled: CONFIG.TRANSCODING.WEBTORRENT.ENABLED
272 enabledResolutions: getEnabledResolutions('vod')
275 enabled: CONFIG.LIVE.ENABLED,
277 enabled: CONFIG.LIVE.TRANSCODING.ENABLED,
278 enabledResolutions: getEnabledResolutions('live')
284 enabled: CONFIG.IMPORT.VIDEOS.HTTP.ENABLED
287 enabled: CONFIG.IMPORT.VIDEOS.TORRENT.ENABLED
294 enabled: CONFIG.AUTO_BLACKLIST.VIDEOS.OF_USERS.ENABLED
301 max: CONSTRAINTS_FIELDS.ACTORS.AVATAR.FILE_SIZE.max
303 extensions: CONSTRAINTS_FIELDS.ACTORS.AVATAR.EXTNAME
308 extensions: CONSTRAINTS_FIELDS.VIDEOS.IMAGE.EXTNAME,
310 max: CONSTRAINTS_FIELDS.VIDEOS.IMAGE.FILE_SIZE.max
314 extensions: CONSTRAINTS_FIELDS.VIDEOS.EXTNAME
320 max: CONSTRAINTS_FIELDS.VIDEO_CAPTIONS.CAPTION_FILE.FILE_SIZE.max
322 extensions: CONSTRAINTS_FIELDS.VIDEO_CAPTIONS.CAPTION_FILE.EXTNAME
326 videoQuota: CONFIG.USER.VIDEO_QUOTA,
327 videoQuotaDaily: CONFIG.USER.VIDEO_QUOTA_DAILY
331 intervalDays: CONFIG.TRENDING.VIDEOS.INTERVAL_DAYS
335 enabled: CONFIG.TRACKER.ENABLED
339 } as HttpNodeinfoDiasporaSoftwareNsSchema20
340 res.contentType('application/json; profile="http://nodeinfo.diaspora.software/ns/schema/2.0#"')
342 json = { error: 'Nodeinfo schema version not handled' }
343 res.status(HttpStatusCode.NOT_FOUND_404)
346 return res.send(json).end()
349 function downloadTorrent (req: express.Request, res: express.Response) {
350 const video = res.locals.videoAll
352 const videoFile = getVideoFile(req, video.VideoFiles)
353 if (!videoFile) return res.status(HttpStatusCode.NOT_FOUND_404).end()
355 return res.download(getTorrentFilePath(video, videoFile), `${video.name}-${videoFile.resolution}p.torrent`)
358 function downloadHLSVideoFileTorrent (req: express.Request, res: express.Response) {
359 const video = res.locals.videoAll
361 const playlist = getHLSPlaylist(video)
362 if (!playlist) return res.status(HttpStatusCode.NOT_FOUND_404).end
364 const videoFile = getVideoFile(req, playlist.VideoFiles)
365 if (!videoFile) return res.status(HttpStatusCode.NOT_FOUND_404).end()
367 return res.download(getTorrentFilePath(playlist, videoFile), `${video.name}-${videoFile.resolution}p-hls.torrent`)
370 function downloadVideoFile (req: express.Request, res: express.Response) {
371 const video = res.locals.videoAll
373 const videoFile = getVideoFile(req, video.VideoFiles)
374 if (!videoFile) return res.status(HttpStatusCode.NOT_FOUND_404).end()
376 return res.download(getVideoFilePath(video, videoFile), `${video.name}-${videoFile.resolution}p${videoFile.extname}`)
379 function downloadHLSVideoFile (req: express.Request, res: express.Response) {
380 const video = res.locals.videoAll
381 const playlist = getHLSPlaylist(video)
382 if (!playlist) return res.status(HttpStatusCode.NOT_FOUND_404).end
384 const videoFile = getVideoFile(req, playlist.VideoFiles)
385 if (!videoFile) return res.status(HttpStatusCode.NOT_FOUND_404).end()
387 const filename = `${video.name}-${videoFile.resolution}p-${playlist.getStringType()}${videoFile.extname}`
388 return res.download(getVideoFilePath(playlist, videoFile), filename)
391 function getVideoFile (req: express.Request, files: MVideoFile[]) {
392 const resolution = parseInt(req.params.resolution, 10)
393 return files.find(f => f.resolution === resolution)
396 function getHLSPlaylist (video: MVideoFullLight) {
397 const playlist = video.VideoStreamingPlaylists.find(p => p.type === VideoStreamingPlaylistType.HLS)
398 if (!playlist) return undefined
400 return Object.assign(playlist, { Video: video })
403 function getCup (req: express.Request, res: express.Response, next: express.NextFunction) {
404 res.status(HttpStatusCode.I_AM_A_TEAPOT_418)
405 res.setHeader('Accept-Additions', 'Non-Dairy;1,Sugar;1')
406 res.setHeader('Safe', 'if-sepia-awake')