]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - server/controllers/api/videos/index.ts
Fix runner api rate limit bypass
[github/Chocobozzz/PeerTube.git] / server / controllers / api / videos / index.ts
1 import express from 'express'
2 import { pickCommonVideoQuery } from '@server/helpers/query'
3 import { doJSONRequest } from '@server/helpers/requests'
4 import { openapiOperationDoc } from '@server/middlewares/doc'
5 import { getServerActor } from '@server/models/application/application'
6 import { guessAdditionalAttributesFromQuery } from '@server/models/video/formatter/video-format-utils'
7 import { MVideoAccountLight } from '@server/types/models'
8 import { HttpStatusCode } from '../../../../shared/models'
9 import { auditLoggerFactory, getAuditIdFromRes, VideoAuditView } from '../../../helpers/audit-logger'
10 import { buildNSFWFilter, getCountVideos } from '../../../helpers/express-utils'
11 import { logger } from '../../../helpers/logger'
12 import { getFormattedObjects } from '../../../helpers/utils'
13 import { REMOTE_SCHEME, VIDEO_CATEGORIES, VIDEO_LANGUAGES, VIDEO_LICENCES, VIDEO_PRIVACIES } from '../../../initializers/constants'
14 import { sequelizeTypescript } from '../../../initializers/database'
15 import { JobQueue } from '../../../lib/job-queue'
16 import { Hooks } from '../../../lib/plugins/hooks'
17 import {
18 apiRateLimiter,
19 asyncMiddleware,
20 asyncRetryTransactionMiddleware,
21 authenticate,
22 checkVideoFollowConstraints,
23 commonVideosFiltersValidator,
24 optionalAuthenticate,
25 paginationValidator,
26 setDefaultPagination,
27 setDefaultVideosSort,
28 videosCustomGetValidator,
29 videosGetValidator,
30 videoSourceGetValidator,
31 videosRemoveValidator,
32 videosSortValidator
33 } from '../../../middlewares'
34 import { VideoModel } from '../../../models/video/video'
35 import { blacklistRouter } from './blacklist'
36 import { videoCaptionsRouter } from './captions'
37 import { videoCommentRouter } from './comment'
38 import { filesRouter } from './files'
39 import { videoImportsRouter } from './import'
40 import { liveRouter } from './live'
41 import { ownershipVideoRouter } from './ownership'
42 import { rateVideoRouter } from './rate'
43 import { statsRouter } from './stats'
44 import { studioRouter } from './studio'
45 import { tokenRouter } from './token'
46 import { transcodingRouter } from './transcoding'
47 import { updateRouter } from './update'
48 import { uploadRouter } from './upload'
49 import { viewRouter } from './view'
50
51 const auditLogger = auditLoggerFactory('videos')
52 const videosRouter = express.Router()
53
54 videosRouter.use(apiRateLimiter)
55
56 videosRouter.use('/', blacklistRouter)
57 videosRouter.use('/', statsRouter)
58 videosRouter.use('/', rateVideoRouter)
59 videosRouter.use('/', videoCommentRouter)
60 videosRouter.use('/', studioRouter)
61 videosRouter.use('/', videoCaptionsRouter)
62 videosRouter.use('/', videoImportsRouter)
63 videosRouter.use('/', ownershipVideoRouter)
64 videosRouter.use('/', viewRouter)
65 videosRouter.use('/', liveRouter)
66 videosRouter.use('/', uploadRouter)
67 videosRouter.use('/', updateRouter)
68 videosRouter.use('/', filesRouter)
69 videosRouter.use('/', transcodingRouter)
70 videosRouter.use('/', tokenRouter)
71
72 videosRouter.get('/categories',
73 openapiOperationDoc({ operationId: 'getCategories' }),
74 listVideoCategories
75 )
76 videosRouter.get('/licences',
77 openapiOperationDoc({ operationId: 'getLicences' }),
78 listVideoLicences
79 )
80 videosRouter.get('/languages',
81 openapiOperationDoc({ operationId: 'getLanguages' }),
82 listVideoLanguages
83 )
84 videosRouter.get('/privacies',
85 openapiOperationDoc({ operationId: 'getPrivacies' }),
86 listVideoPrivacies
87 )
88
89 videosRouter.get('/',
90 openapiOperationDoc({ operationId: 'getVideos' }),
91 paginationValidator,
92 videosSortValidator,
93 setDefaultVideosSort,
94 setDefaultPagination,
95 optionalAuthenticate,
96 commonVideosFiltersValidator,
97 asyncMiddleware(listVideos)
98 )
99
100 // TODO: remove, deprecated in 5.0 now we send the complete description in VideoDetails
101 videosRouter.get('/:id/description',
102 openapiOperationDoc({ operationId: 'getVideoDesc' }),
103 asyncMiddleware(videosGetValidator),
104 asyncMiddleware(getVideoDescription)
105 )
106
107 videosRouter.get('/:id/source',
108 openapiOperationDoc({ operationId: 'getVideoSource' }),
109 authenticate,
110 asyncMiddleware(videoSourceGetValidator),
111 getVideoSource
112 )
113
114 videosRouter.get('/:id',
115 openapiOperationDoc({ operationId: 'getVideo' }),
116 optionalAuthenticate,
117 asyncMiddleware(videosCustomGetValidator('for-api')),
118 asyncMiddleware(checkVideoFollowConstraints),
119 asyncMiddleware(getVideo)
120 )
121
122 videosRouter.delete('/:id',
123 openapiOperationDoc({ operationId: 'delVideo' }),
124 authenticate,
125 asyncMiddleware(videosRemoveValidator),
126 asyncRetryTransactionMiddleware(removeVideo)
127 )
128
129 // ---------------------------------------------------------------------------
130
131 export {
132 videosRouter
133 }
134
135 // ---------------------------------------------------------------------------
136
137 function listVideoCategories (_req: express.Request, res: express.Response) {
138 res.json(VIDEO_CATEGORIES)
139 }
140
141 function listVideoLicences (_req: express.Request, res: express.Response) {
142 res.json(VIDEO_LICENCES)
143 }
144
145 function listVideoLanguages (_req: express.Request, res: express.Response) {
146 res.json(VIDEO_LANGUAGES)
147 }
148
149 function listVideoPrivacies (_req: express.Request, res: express.Response) {
150 res.json(VIDEO_PRIVACIES)
151 }
152
153 async function getVideo (_req: express.Request, res: express.Response) {
154 const videoId = res.locals.videoAPI.id
155 const userId = res.locals.oauth?.token.User.id
156
157 const video = await Hooks.wrapObject(res.locals.videoAPI, 'filter:api.video.get.result', { id: videoId, userId })
158
159 if (video.isOutdated()) {
160 JobQueue.Instance.createJobAsync({ type: 'activitypub-refresher', payload: { type: 'video', url: video.url } })
161 }
162
163 return res.json(video.toFormattedDetailsJSON())
164 }
165
166 async function getVideoDescription (req: express.Request, res: express.Response) {
167 const videoInstance = res.locals.videoAll
168
169 const description = videoInstance.isOwned()
170 ? videoInstance.description
171 : await fetchRemoteVideoDescription(videoInstance)
172
173 return res.json({ description })
174 }
175
176 function getVideoSource (req: express.Request, res: express.Response) {
177 return res.json(res.locals.videoSource.toFormattedJSON())
178 }
179
180 async function listVideos (req: express.Request, res: express.Response) {
181 const serverActor = await getServerActor()
182
183 const query = pickCommonVideoQuery(req.query)
184 const countVideos = getCountVideos(req)
185
186 const apiOptions = await Hooks.wrapObject({
187 ...query,
188
189 displayOnlyForFollower: {
190 actorId: serverActor.id,
191 orLocalVideos: true
192 },
193 nsfw: buildNSFWFilter(res, query.nsfw),
194 user: res.locals.oauth ? res.locals.oauth.token.User : undefined,
195 countVideos
196 }, 'filter:api.videos.list.params')
197
198 const resultList = await Hooks.wrapPromiseFun(
199 VideoModel.listForApi,
200 apiOptions,
201 'filter:api.videos.list.result'
202 )
203
204 return res.json(getFormattedObjects(resultList.data, resultList.total, guessAdditionalAttributesFromQuery(query)))
205 }
206
207 async function removeVideo (req: express.Request, res: express.Response) {
208 const videoInstance = res.locals.videoAll
209
210 await sequelizeTypescript.transaction(async t => {
211 await videoInstance.destroy({ transaction: t })
212 })
213
214 auditLogger.delete(getAuditIdFromRes(res), new VideoAuditView(videoInstance.toFormattedDetailsJSON()))
215 logger.info('Video with name %s and uuid %s deleted.', videoInstance.name, videoInstance.uuid)
216
217 Hooks.runAction('action:api.video.deleted', { video: videoInstance, req, res })
218
219 return res.type('json')
220 .status(HttpStatusCode.NO_CONTENT_204)
221 .end()
222 }
223
224 // ---------------------------------------------------------------------------
225
226 // FIXME: Should not exist, we rely on specific API
227 async function fetchRemoteVideoDescription (video: MVideoAccountLight) {
228 const host = video.VideoChannel.Account.Actor.Server.host
229 const path = video.getDescriptionAPIPath()
230 const url = REMOTE_SCHEME.HTTP + '://' + host + path
231
232 const { body } = await doJSONRequest<any>(url)
233 return body.description || ''
234 }