]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - server/controllers/api/videos/index.ts
Add audit logs in various modules
[github/Chocobozzz/PeerTube.git] / server / controllers / api / videos / index.ts
1 import * as express from 'express'
2 import { extname, join } from 'path'
3 import { VideoCreate, VideoPrivacy, VideoState, VideoUpdate } from '../../../../shared'
4 import { renamePromise } from '../../../helpers/core-utils'
5 import { getVideoFileFPS, getVideoFileResolution } from '../../../helpers/ffmpeg-utils'
6 import { processImage } from '../../../helpers/image-utils'
7 import { logger } from '../../../helpers/logger'
8 import { auditLoggerFactory, VideoAuditView } from '../../../helpers/audit-logger'
9 import { getFormattedObjects, getServerActor, resetSequelizeInstance } from '../../../helpers/utils'
10 import {
11 CONFIG,
12 IMAGE_MIMETYPE_EXT,
13 PREVIEWS_SIZE,
14 sequelizeTypescript,
15 THUMBNAILS_SIZE,
16 VIDEO_CATEGORIES,
17 VIDEO_LANGUAGES,
18 VIDEO_LICENCES,
19 VIDEO_MIMETYPE_EXT,
20 VIDEO_PRIVACIES
21 } from '../../../initializers'
22 import {
23 changeVideoChannelShare,
24 federateVideoIfNeeded,
25 fetchRemoteVideoDescription,
26 getVideoActivityPubUrl
27 } from '../../../lib/activitypub'
28 import { sendCreateView } from '../../../lib/activitypub/send'
29 import { JobQueue } from '../../../lib/job-queue'
30 import { Redis } from '../../../lib/redis'
31 import {
32 asyncMiddleware,
33 asyncRetryTransactionMiddleware,
34 authenticate,
35 commonVideosFiltersValidator,
36 optionalAuthenticate,
37 paginationValidator,
38 setDefaultPagination,
39 setDefaultSort,
40 videosAddValidator,
41 videosGetValidator,
42 videosRemoveValidator,
43 videosSortValidator,
44 videosUpdateValidator
45 } from '../../../middlewares'
46 import { TagModel } from '../../../models/video/tag'
47 import { VideoModel } from '../../../models/video/video'
48 import { VideoFileModel } from '../../../models/video/video-file'
49 import { abuseVideoRouter } from './abuse'
50 import { blacklistRouter } from './blacklist'
51 import { videoCommentRouter } from './comment'
52 import { rateVideoRouter } from './rate'
53 import { VideoFilter } from '../../../../shared/models/videos/video-query.type'
54 import { createReqFiles, buildNSFWFilter } from '../../../helpers/express-utils'
55 import { ScheduleVideoUpdateModel } from '../../../models/video/schedule-video-update'
56 import { videoCaptionsRouter } from './captions'
57
58 const auditLogger = auditLoggerFactory('videos')
59 const videosRouter = express.Router()
60
61 const reqVideoFileAdd = createReqFiles(
62 [ 'videofile', 'thumbnailfile', 'previewfile' ],
63 Object.assign({}, VIDEO_MIMETYPE_EXT, IMAGE_MIMETYPE_EXT),
64 {
65 videofile: CONFIG.STORAGE.VIDEOS_DIR,
66 thumbnailfile: CONFIG.STORAGE.THUMBNAILS_DIR,
67 previewfile: CONFIG.STORAGE.PREVIEWS_DIR
68 }
69 )
70 const reqVideoFileUpdate = createReqFiles(
71 [ 'thumbnailfile', 'previewfile' ],
72 IMAGE_MIMETYPE_EXT,
73 {
74 thumbnailfile: CONFIG.STORAGE.THUMBNAILS_DIR,
75 previewfile: CONFIG.STORAGE.PREVIEWS_DIR
76 }
77 )
78
79 videosRouter.use('/', abuseVideoRouter)
80 videosRouter.use('/', blacklistRouter)
81 videosRouter.use('/', rateVideoRouter)
82 videosRouter.use('/', videoCommentRouter)
83 videosRouter.use('/', videoCaptionsRouter)
84
85 videosRouter.get('/categories', listVideoCategories)
86 videosRouter.get('/licences', listVideoLicences)
87 videosRouter.get('/languages', listVideoLanguages)
88 videosRouter.get('/privacies', listVideoPrivacies)
89
90 videosRouter.get('/',
91 paginationValidator,
92 videosSortValidator,
93 setDefaultSort,
94 setDefaultPagination,
95 optionalAuthenticate,
96 commonVideosFiltersValidator,
97 asyncMiddleware(listVideos)
98 )
99 videosRouter.put('/:id',
100 authenticate,
101 reqVideoFileUpdate,
102 asyncMiddleware(videosUpdateValidator),
103 asyncRetryTransactionMiddleware(updateVideo)
104 )
105 videosRouter.post('/upload',
106 authenticate,
107 reqVideoFileAdd,
108 asyncMiddleware(videosAddValidator),
109 asyncRetryTransactionMiddleware(addVideo)
110 )
111
112 videosRouter.get('/:id/description',
113 asyncMiddleware(videosGetValidator),
114 asyncMiddleware(getVideoDescription)
115 )
116 videosRouter.get('/:id',
117 asyncMiddleware(videosGetValidator),
118 getVideo
119 )
120 videosRouter.post('/:id/views',
121 asyncMiddleware(videosGetValidator),
122 asyncMiddleware(viewVideo)
123 )
124
125 videosRouter.delete('/:id',
126 authenticate,
127 asyncMiddleware(videosRemoveValidator),
128 asyncRetryTransactionMiddleware(removeVideo)
129 )
130
131 // ---------------------------------------------------------------------------
132
133 export {
134 videosRouter
135 }
136
137 // ---------------------------------------------------------------------------
138
139 function listVideoCategories (req: express.Request, res: express.Response) {
140 res.json(VIDEO_CATEGORIES)
141 }
142
143 function listVideoLicences (req: express.Request, res: express.Response) {
144 res.json(VIDEO_LICENCES)
145 }
146
147 function listVideoLanguages (req: express.Request, res: express.Response) {
148 res.json(VIDEO_LANGUAGES)
149 }
150
151 function listVideoPrivacies (req: express.Request, res: express.Response) {
152 res.json(VIDEO_PRIVACIES)
153 }
154
155 async function addVideo (req: express.Request, res: express.Response) {
156 const videoPhysicalFile = req.files['videofile'][0]
157 const videoInfo: VideoCreate = req.body
158
159 // Prepare data so we don't block the transaction
160 const videoData = {
161 name: videoInfo.name,
162 remote: false,
163 extname: extname(videoPhysicalFile.filename),
164 category: videoInfo.category,
165 licence: videoInfo.licence,
166 language: videoInfo.language,
167 commentsEnabled: videoInfo.commentsEnabled || false,
168 waitTranscoding: videoInfo.waitTranscoding || false,
169 state: CONFIG.TRANSCODING.ENABLED ? VideoState.TO_TRANSCODE : VideoState.PUBLISHED,
170 nsfw: videoInfo.nsfw || false,
171 description: videoInfo.description,
172 support: videoInfo.support,
173 privacy: videoInfo.privacy,
174 duration: videoPhysicalFile['duration'], // duration was added by a previous middleware
175 channelId: res.locals.videoChannel.id
176 }
177 const video = new VideoModel(videoData)
178 video.url = getVideoActivityPubUrl(video) // We use the UUID, so set the URL after building the object
179
180 // Build the file object
181 const { videoFileResolution } = await getVideoFileResolution(videoPhysicalFile.path)
182 const fps = await getVideoFileFPS(videoPhysicalFile.path)
183
184 const videoFileData = {
185 extname: extname(videoPhysicalFile.filename),
186 resolution: videoFileResolution,
187 size: videoPhysicalFile.size,
188 fps
189 }
190 const videoFile = new VideoFileModel(videoFileData)
191
192 // Move physical file
193 const videoDir = CONFIG.STORAGE.VIDEOS_DIR
194 const destination = join(videoDir, video.getVideoFilename(videoFile))
195 await renamePromise(videoPhysicalFile.path, destination)
196 // This is important in case if there is another attempt in the retry process
197 videoPhysicalFile.filename = video.getVideoFilename(videoFile)
198 videoPhysicalFile.path = destination
199
200 // Process thumbnail or create it from the video
201 const thumbnailField = req.files['thumbnailfile']
202 if (thumbnailField) {
203 const thumbnailPhysicalFile = thumbnailField[0]
204 await processImage(thumbnailPhysicalFile, join(CONFIG.STORAGE.THUMBNAILS_DIR, video.getThumbnailName()), THUMBNAILS_SIZE)
205 } else {
206 await video.createThumbnail(videoFile)
207 }
208
209 // Process preview or create it from the video
210 const previewField = req.files['previewfile']
211 if (previewField) {
212 const previewPhysicalFile = previewField[0]
213 await processImage(previewPhysicalFile, join(CONFIG.STORAGE.PREVIEWS_DIR, video.getPreviewName()), PREVIEWS_SIZE)
214 } else {
215 await video.createPreview(videoFile)
216 }
217
218 // Create the torrent file
219 await video.createTorrentAndSetInfoHash(videoFile)
220
221 const videoCreated = await sequelizeTypescript.transaction(async t => {
222 const sequelizeOptions = { transaction: t }
223
224 const videoCreated = await video.save(sequelizeOptions)
225 // Do not forget to add video channel information to the created video
226 videoCreated.VideoChannel = res.locals.videoChannel
227
228 videoFile.videoId = video.id
229 await videoFile.save(sequelizeOptions)
230
231 video.VideoFiles = [ videoFile ]
232
233 // Create tags
234 if (videoInfo.tags !== undefined) {
235 const tagInstances = await TagModel.findOrCreateTags(videoInfo.tags, t)
236
237 await video.$set('Tags', tagInstances, sequelizeOptions)
238 video.Tags = tagInstances
239 }
240
241 // Schedule an update in the future?
242 if (videoInfo.scheduleUpdate) {
243 await ScheduleVideoUpdateModel.create({
244 videoId: video.id,
245 updateAt: videoInfo.scheduleUpdate.updateAt,
246 privacy: videoInfo.scheduleUpdate.privacy || null
247 }, { transaction: t })
248 }
249
250 await federateVideoIfNeeded(video, true, t)
251
252 auditLogger.create(res.locals.oauth.token.User.Account.Actor.getIdentifier(), new VideoAuditView(videoCreated.toFormattedDetailsJSON()))
253 logger.info('Video with name %s and uuid %s created.', videoInfo.name, videoCreated.uuid)
254
255 return videoCreated
256 })
257
258 if (video.state === VideoState.TO_TRANSCODE) {
259 // Put uuid because we don't have id auto incremented for now
260 const dataInput = {
261 videoUUID: videoCreated.uuid,
262 isNewVideo: true
263 }
264
265 await JobQueue.Instance.createJob({ type: 'video-file', payload: dataInput })
266 }
267
268 return res.json({
269 video: {
270 id: videoCreated.id,
271 uuid: videoCreated.uuid
272 }
273 }).end()
274 }
275
276 async function updateVideo (req: express.Request, res: express.Response) {
277 const videoInstance: VideoModel = res.locals.video
278 const videoFieldsSave = videoInstance.toJSON()
279 const oldVideoAuditView = new VideoAuditView(videoInstance.toFormattedDetailsJSON())
280 const videoInfoToUpdate: VideoUpdate = req.body
281 const wasPrivateVideo = videoInstance.privacy === VideoPrivacy.PRIVATE
282
283 // Process thumbnail or create it from the video
284 if (req.files && req.files['thumbnailfile']) {
285 const thumbnailPhysicalFile = req.files['thumbnailfile'][0]
286 await processImage(thumbnailPhysicalFile, join(CONFIG.STORAGE.THUMBNAILS_DIR, videoInstance.getThumbnailName()), THUMBNAILS_SIZE)
287 }
288
289 // Process preview or create it from the video
290 if (req.files && req.files['previewfile']) {
291 const previewPhysicalFile = req.files['previewfile'][0]
292 await processImage(previewPhysicalFile, join(CONFIG.STORAGE.PREVIEWS_DIR, videoInstance.getPreviewName()), PREVIEWS_SIZE)
293 }
294
295 try {
296 await sequelizeTypescript.transaction(async t => {
297 const sequelizeOptions = {
298 transaction: t
299 }
300 const oldVideoChannel = videoInstance.VideoChannel
301
302 if (videoInfoToUpdate.name !== undefined) videoInstance.set('name', videoInfoToUpdate.name)
303 if (videoInfoToUpdate.category !== undefined) videoInstance.set('category', videoInfoToUpdate.category)
304 if (videoInfoToUpdate.licence !== undefined) videoInstance.set('licence', videoInfoToUpdate.licence)
305 if (videoInfoToUpdate.language !== undefined) videoInstance.set('language', videoInfoToUpdate.language)
306 if (videoInfoToUpdate.nsfw !== undefined) videoInstance.set('nsfw', videoInfoToUpdate.nsfw)
307 if (videoInfoToUpdate.waitTranscoding !== undefined) videoInstance.set('waitTranscoding', videoInfoToUpdate.waitTranscoding)
308 if (videoInfoToUpdate.support !== undefined) videoInstance.set('support', videoInfoToUpdate.support)
309 if (videoInfoToUpdate.description !== undefined) videoInstance.set('description', videoInfoToUpdate.description)
310 if (videoInfoToUpdate.commentsEnabled !== undefined) videoInstance.set('commentsEnabled', videoInfoToUpdate.commentsEnabled)
311 if (videoInfoToUpdate.privacy !== undefined) {
312 const newPrivacy = parseInt(videoInfoToUpdate.privacy.toString(), 10)
313 videoInstance.set('privacy', newPrivacy)
314
315 if (wasPrivateVideo === true && newPrivacy !== VideoPrivacy.PRIVATE) {
316 videoInstance.set('publishedAt', new Date())
317 }
318 }
319
320 const videoInstanceUpdated = await videoInstance.save(sequelizeOptions)
321
322 // Video tags update?
323 if (videoInfoToUpdate.tags !== undefined) {
324 const tagInstances = await TagModel.findOrCreateTags(videoInfoToUpdate.tags, t)
325
326 await videoInstanceUpdated.$set('Tags', tagInstances, sequelizeOptions)
327 videoInstanceUpdated.Tags = tagInstances
328 }
329
330 // Video channel update?
331 if (res.locals.videoChannel && videoInstanceUpdated.channelId !== res.locals.videoChannel.id) {
332 await videoInstanceUpdated.$set('VideoChannel', res.locals.videoChannel, { transaction: t })
333 videoInstanceUpdated.VideoChannel = res.locals.videoChannel
334
335 if (wasPrivateVideo === false) await changeVideoChannelShare(videoInstanceUpdated, oldVideoChannel, t)
336 }
337
338 // Schedule an update in the future?
339 if (videoInfoToUpdate.scheduleUpdate) {
340 await ScheduleVideoUpdateModel.upsert({
341 videoId: videoInstanceUpdated.id,
342 updateAt: videoInfoToUpdate.scheduleUpdate.updateAt,
343 privacy: videoInfoToUpdate.scheduleUpdate.privacy || null
344 }, { transaction: t })
345 } else if (videoInfoToUpdate.scheduleUpdate === null) {
346 await ScheduleVideoUpdateModel.deleteByVideoId(videoInstanceUpdated.id, t)
347 }
348
349 const isNewVideo = wasPrivateVideo && videoInstanceUpdated.privacy !== VideoPrivacy.PRIVATE
350 await federateVideoIfNeeded(videoInstanceUpdated, isNewVideo, t)
351
352 auditLogger.update(
353 res.locals.oauth.token.User.Account.Actor.getIdentifier(),
354 new VideoAuditView(videoInstanceUpdated.toFormattedDetailsJSON()),
355 oldVideoAuditView
356 )
357 logger.info('Video with name %s and uuid %s updated.', videoInstance.name, videoInstance.uuid)
358 })
359 } catch (err) {
360 // Force fields we want to update
361 // If the transaction is retried, sequelize will think the object has not changed
362 // So it will skip the SQL request, even if the last one was ROLLBACKed!
363 resetSequelizeInstance(videoInstance, videoFieldsSave)
364
365 throw err
366 }
367
368 return res.type('json').status(204).end()
369 }
370
371 function getVideo (req: express.Request, res: express.Response) {
372 const videoInstance = res.locals.video
373
374 return res.json(videoInstance.toFormattedDetailsJSON())
375 }
376
377 async function viewVideo (req: express.Request, res: express.Response) {
378 const videoInstance = res.locals.video
379
380 const ip = req.ip
381 const exists = await Redis.Instance.isViewExists(ip, videoInstance.uuid)
382 if (exists) {
383 logger.debug('View for ip %s and video %s already exists.', ip, videoInstance.uuid)
384 return res.status(204).end()
385 }
386
387 await videoInstance.increment('views')
388 await Redis.Instance.setView(ip, videoInstance.uuid)
389
390 const serverAccount = await getServerActor()
391
392 await sendCreateView(serverAccount, videoInstance, undefined)
393
394 return res.status(204).end()
395 }
396
397 async function getVideoDescription (req: express.Request, res: express.Response) {
398 const videoInstance = res.locals.video
399 let description = ''
400
401 if (videoInstance.isOwned()) {
402 description = videoInstance.description
403 } else {
404 description = await fetchRemoteVideoDescription(videoInstance)
405 }
406
407 return res.json({ description })
408 }
409
410 async function listVideos (req: express.Request, res: express.Response, next: express.NextFunction) {
411 const resultList = await VideoModel.listForApi({
412 start: req.query.start,
413 count: req.query.count,
414 sort: req.query.sort,
415 categoryOneOf: req.query.categoryOneOf,
416 licenceOneOf: req.query.licenceOneOf,
417 languageOneOf: req.query.languageOneOf,
418 tagsOneOf: req.query.tagsOneOf,
419 tagsAllOf: req.query.tagsAllOf,
420 nsfw: buildNSFWFilter(res, req.query.nsfw),
421 filter: req.query.filter as VideoFilter,
422 withFiles: false
423 })
424
425 return res.json(getFormattedObjects(resultList.data, resultList.total))
426 }
427
428 async function removeVideo (req: express.Request, res: express.Response) {
429 const videoInstance: VideoModel = res.locals.video
430
431 await sequelizeTypescript.transaction(async t => {
432 await videoInstance.destroy({ transaction: t })
433 })
434
435 auditLogger.delete(res.locals.oauth.token.User.Account.Actor.getIdentifier(), new VideoAuditView(videoInstance.toFormattedDetailsJSON()))
436 logger.info('Video with name %s and uuid %s deleted.', videoInstance.name, videoInstance.uuid)
437
438 return res.type('json').status(204).end()
439 }