1 import * as cors from 'cors'
2 import * as express from 'express'
3 import { join } from 'path'
4 import { getRegisteredPlugins, getRegisteredThemes } from '@server/controllers/api/config'
5 import { serveIndexHTML } from '@server/lib/client-html'
6 import { getTorrentFilePath, getVideoFilePath } from '@server/lib/video-paths'
7 import { MVideoFile, MVideoFullLight } from '@server/types/models'
8 import { HttpStatusCode } from '@shared/core-utils/miscs/http-error-codes'
9 import { VideoStreamingPlaylistType } from '@shared/models/videos/video-streaming-playlist.type'
10 import { HttpNodeinfoDiasporaSoftwareNsSchema20 } from '../../shared/models/nodeinfo'
11 import { root } from '../helpers/core-utils'
12 import { CONFIG, isEmailEnabled } from '../initializers/config'
16 HLS_STREAMING_PLAYLIST_DIRECTORY,
19 STATIC_DOWNLOAD_PATHS,
23 } from '../initializers/constants'
24 import { getThemeOrDefault } from '../lib/plugins/theme-utils'
25 import { getEnabledResolutions } from '../lib/video-transcoding'
26 import { asyncMiddleware, videosDownloadValidator } from '../middlewares'
27 import { cacheRoute } from '../middlewares/cache'
28 import { UserModel } from '../models/account/user'
29 import { VideoModel } from '../models/video/video'
30 import { VideoCommentModel } from '../models/video/video-comment'
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
96 staticRouter.get('/robots.txt',
97 asyncMiddleware(cacheRoute()(ROUTE_CACHE_LIFETIME.ROBOTS)),
98 (_, res: express.Response) => {
99 res.type('text/plain')
100 return res.send(CONFIG.INSTANCE.ROBOTS)
104 staticRouter.all('/teapot',
106 asyncMiddleware(serveIndexHTML)
109 // security.txt service
110 staticRouter.get('/security.txt',
111 (_, res: express.Response) => {
112 return res.redirect(HttpStatusCode.MOVED_PERMANENTLY_301, '/.well-known/security.txt')
116 staticRouter.get('/.well-known/security.txt',
117 asyncMiddleware(cacheRoute()(ROUTE_CACHE_LIFETIME.SECURITYTXT)),
118 (_, res: express.Response) => {
119 res.type('text/plain')
120 return res.send(CONFIG.INSTANCE.SECURITYTXT + CONFIG.INSTANCE.SECURITYTXT_CONTACT)
125 staticRouter.use('/.well-known/nodeinfo',
126 asyncMiddleware(cacheRoute()(ROUTE_CACHE_LIFETIME.NODEINFO)),
127 (_, res: express.Response) => {
131 rel: 'http://nodeinfo.diaspora.software/ns/schema/2.0',
132 href: WEBSERVER.URL + '/nodeinfo/2.0.json'
138 staticRouter.use('/nodeinfo/:version.json',
139 asyncMiddleware(cacheRoute()(ROUTE_CACHE_LIFETIME.NODEINFO)),
140 asyncMiddleware(generateNodeinfo)
143 // dnt-policy.txt service (see https://www.eff.org/dnt-policy)
144 staticRouter.use('/.well-known/dnt-policy.txt',
145 asyncMiddleware(cacheRoute()(ROUTE_CACHE_LIFETIME.DNT_POLICY)),
146 (_, res: express.Response) => {
147 res.type('text/plain')
149 return res.sendFile(join(root(), 'dist/server/static/dnt-policy/dnt-policy-1.0.txt'))
153 // dnt service (see https://www.w3.org/TR/tracking-dnt/#status-resource)
154 staticRouter.use('/.well-known/dnt/',
155 (_, res: express.Response) => {
156 res.json({ tracking: 'N' })
160 staticRouter.use('/.well-known/change-password',
161 (_, res: express.Response) => {
162 res.redirect('/my-account/settings')
166 staticRouter.use('/.well-known/host-meta',
167 (_, res: express.Response) => {
168 res.type('application/xml')
170 const xml = '<?xml version="1.0" encoding="UTF-8"?>\n' +
171 '<XRD xmlns="http://docs.oasis-open.org/ns/xri/xrd-1.0">\n' +
172 ` <Link rel="lrdd" type="application/xrd+xml" template="${WEBSERVER.URL}/.well-known/webfinger?resource={uri}"/>\n` +
179 // ---------------------------------------------------------------------------
185 // ---------------------------------------------------------------------------
187 async function generateNodeinfo (req: express.Request, res: express.Response) {
188 const { totalVideos } = await VideoModel.getStats()
189 const { totalLocalVideoComments } = await VideoCommentModel.getStats()
190 const { totalUsers, totalMonthlyActiveUsers, totalHalfYearActiveUsers } = await UserModel.getStats()
193 if (req.params.version && (req.params.version === '2.0')) {
198 version: PEERTUBE_VERSION
210 openRegistrations: CONFIG.SIGNUP.ENABLED,
214 activeMonth: totalMonthlyActiveUsers,
215 activeHalfyear: totalHalfYearActiveUsers
217 localPosts: totalVideos,
218 localComments: totalLocalVideoComments
224 nodeName: CONFIG.INSTANCE.NAME,
225 nodeDescription: CONFIG.INSTANCE.SHORT_DESCRIPTION,
229 users: CONFIG.SEARCH.REMOTE_URI.USERS,
230 anonymous: CONFIG.SEARCH.REMOTE_URI.ANONYMOUS
234 registered: getRegisteredPlugins()
237 registered: getRegisteredThemes(),
238 default: getThemeOrDefault(CONFIG.THEME.DEFAULT, DEFAULT_THEME_NAME)
241 enabled: isEmailEnabled()
244 enabled: CONFIG.CONTACT_FORM.ENABLED
248 enabled: CONFIG.TRANSCODING.HLS.ENABLED
251 enabled: CONFIG.TRANSCODING.WEBTORRENT.ENABLED
253 enabledResolutions: getEnabledResolutions('vod')
256 enabled: CONFIG.LIVE.ENABLED,
258 enabled: CONFIG.LIVE.TRANSCODING.ENABLED,
259 enabledResolutions: getEnabledResolutions('live')
265 enabled: CONFIG.IMPORT.VIDEOS.HTTP.ENABLED
268 enabled: CONFIG.IMPORT.VIDEOS.TORRENT.ENABLED
275 enabled: CONFIG.AUTO_BLACKLIST.VIDEOS.OF_USERS.ENABLED
282 max: CONSTRAINTS_FIELDS.ACTORS.AVATAR.FILE_SIZE.max
284 extensions: CONSTRAINTS_FIELDS.ACTORS.AVATAR.EXTNAME
289 extensions: CONSTRAINTS_FIELDS.VIDEOS.IMAGE.EXTNAME,
291 max: CONSTRAINTS_FIELDS.VIDEOS.IMAGE.FILE_SIZE.max
295 extensions: CONSTRAINTS_FIELDS.VIDEOS.EXTNAME
301 max: CONSTRAINTS_FIELDS.VIDEO_CAPTIONS.CAPTION_FILE.FILE_SIZE.max
303 extensions: CONSTRAINTS_FIELDS.VIDEO_CAPTIONS.CAPTION_FILE.EXTNAME
307 videoQuota: CONFIG.USER.VIDEO_QUOTA,
308 videoQuotaDaily: CONFIG.USER.VIDEO_QUOTA_DAILY
312 intervalDays: CONFIG.TRENDING.VIDEOS.INTERVAL_DAYS
316 enabled: CONFIG.TRACKER.ENABLED
320 } as HttpNodeinfoDiasporaSoftwareNsSchema20
321 res.contentType('application/json; profile="http://nodeinfo.diaspora.software/ns/schema/2.0#"')
323 json = { error: 'Nodeinfo schema version not handled' }
324 res.status(HttpStatusCode.NOT_FOUND_404)
327 return res.send(json).end()
330 function downloadTorrent (req: express.Request, res: express.Response) {
331 const video = res.locals.videoAll
333 const videoFile = getVideoFile(req, video.VideoFiles)
334 if (!videoFile) return res.status(HttpStatusCode.NOT_FOUND_404).end()
336 return res.download(getTorrentFilePath(video, videoFile), `${video.name}-${videoFile.resolution}p.torrent`)
339 function downloadHLSVideoFileTorrent (req: express.Request, res: express.Response) {
340 const video = res.locals.videoAll
342 const playlist = getHLSPlaylist(video)
343 if (!playlist) return res.status(HttpStatusCode.NOT_FOUND_404).end
345 const videoFile = getVideoFile(req, playlist.VideoFiles)
346 if (!videoFile) return res.status(HttpStatusCode.NOT_FOUND_404).end()
348 return res.download(getTorrentFilePath(playlist, videoFile), `${video.name}-${videoFile.resolution}p-hls.torrent`)
351 function downloadVideoFile (req: express.Request, res: express.Response) {
352 const video = res.locals.videoAll
354 const videoFile = getVideoFile(req, video.VideoFiles)
355 if (!videoFile) return res.status(HttpStatusCode.NOT_FOUND_404).end()
357 return res.download(getVideoFilePath(video, videoFile), `${video.name}-${videoFile.resolution}p${videoFile.extname}`)
360 function downloadHLSVideoFile (req: express.Request, res: express.Response) {
361 const video = res.locals.videoAll
362 const playlist = getHLSPlaylist(video)
363 if (!playlist) return res.status(HttpStatusCode.NOT_FOUND_404).end
365 const videoFile = getVideoFile(req, playlist.VideoFiles)
366 if (!videoFile) return res.status(HttpStatusCode.NOT_FOUND_404).end()
368 const filename = `${video.name}-${videoFile.resolution}p-${playlist.getStringType()}${videoFile.extname}`
369 return res.download(getVideoFilePath(playlist, videoFile), filename)
372 function getVideoFile (req: express.Request, files: MVideoFile[]) {
373 const resolution = parseInt(req.params.resolution, 10)
374 return files.find(f => f.resolution === resolution)
377 function getHLSPlaylist (video: MVideoFullLight) {
378 const playlist = video.VideoStreamingPlaylists.find(p => p.type === VideoStreamingPlaylistType.HLS)
379 if (!playlist) return undefined
381 return Object.assign(playlist, { Video: video })
384 function getCup (req: express.Request, res: express.Response, next: express.NextFunction) {
385 res.status(HttpStatusCode.I_AM_A_TEAPOT_418)
386 res.setHeader('Accept-Additions', 'Non-Dairy;1,Sugar;1')
387 res.setHeader('Safe', 'if-sepia-awake')