static.ts 7.4 KB

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