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