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