]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - server/controllers/api/videos/index.ts
Add server hooks
[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 { getVideoFileFPS, getVideoFileResolution } from '../../../helpers/ffmpeg-utils'
5 import { logger } from '../../../helpers/logger'
6 import { auditLoggerFactory, getAuditIdFromRes, VideoAuditView } from '../../../helpers/audit-logger'
7 import { getFormattedObjects, getServerActor } from '../../../helpers/utils'
8 import { autoBlacklistVideoIfNeeded } from '../../../lib/video-blacklist'
9 import {
10 DEFAULT_AUDIO_RESOLUTION,
11 MIMETYPES,
12 VIDEO_CATEGORIES,
13 VIDEO_LANGUAGES,
14 VIDEO_LICENCES,
15 VIDEO_PRIVACIES
16 } from '../../../initializers/constants'
17 import {
18 changeVideoChannelShare,
19 federateVideoIfNeeded,
20 fetchRemoteVideoDescription,
21 getVideoActivityPubUrl
22 } from '../../../lib/activitypub'
23 import { JobQueue } from '../../../lib/job-queue'
24 import { Redis } from '../../../lib/redis'
25 import {
26 asyncMiddleware,
27 asyncRetryTransactionMiddleware,
28 authenticate,
29 checkVideoFollowConstraints,
30 commonVideosFiltersValidator,
31 optionalAuthenticate,
32 paginationValidator,
33 setDefaultPagination,
34 setDefaultSort,
35 videosAddValidator,
36 videosCustomGetValidator,
37 videosGetValidator,
38 videosRemoveValidator,
39 videosSortValidator,
40 videosUpdateValidator
41 } from '../../../middlewares'
42 import { TagModel } from '../../../models/video/tag'
43 import { VideoModel } from '../../../models/video/video'
44 import { VideoFileModel } from '../../../models/video/video-file'
45 import { abuseVideoRouter } from './abuse'
46 import { blacklistRouter } from './blacklist'
47 import { videoCommentRouter } from './comment'
48 import { rateVideoRouter } from './rate'
49 import { ownershipVideoRouter } from './ownership'
50 import { VideoFilter } from '../../../../shared/models/videos/video-query.type'
51 import { buildNSFWFilter, createReqFiles } from '../../../helpers/express-utils'
52 import { ScheduleVideoUpdateModel } from '../../../models/video/schedule-video-update'
53 import { videoCaptionsRouter } from './captions'
54 import { videoImportsRouter } from './import'
55 import { resetSequelizeInstance } from '../../../helpers/database-utils'
56 import { move } from 'fs-extra'
57 import { watchingRouter } from './watching'
58 import { Notifier } from '../../../lib/notifier'
59 import { sendView } from '../../../lib/activitypub/send/send-view'
60 import { CONFIG } from '../../../initializers/config'
61 import { sequelizeTypescript } from '../../../initializers/database'
62 import { createVideoMiniatureFromExisting, generateVideoMiniature } from '../../../lib/thumbnail'
63 import { ThumbnailType } from '../../../../shared/models/videos/thumbnail.type'
64 import { VideoTranscodingPayload } from '../../../lib/job-queue/handlers/video-transcoding'
65 import { Hooks } from '../../../lib/plugins/hooks'
66
67 const auditLogger = auditLoggerFactory('videos')
68 const videosRouter = express.Router()
69
70 const reqVideoFileAdd = createReqFiles(
71 [ 'videofile', 'thumbnailfile', 'previewfile' ],
72 Object.assign({}, MIMETYPES.VIDEO.MIMETYPE_EXT, MIMETYPES.IMAGE.MIMETYPE_EXT),
73 {
74 videofile: CONFIG.STORAGE.TMP_DIR,
75 thumbnailfile: CONFIG.STORAGE.TMP_DIR,
76 previewfile: CONFIG.STORAGE.TMP_DIR
77 }
78 )
79 const reqVideoFileUpdate = createReqFiles(
80 [ 'thumbnailfile', 'previewfile' ],
81 MIMETYPES.IMAGE.MIMETYPE_EXT,
82 {
83 thumbnailfile: CONFIG.STORAGE.TMP_DIR,
84 previewfile: CONFIG.STORAGE.TMP_DIR
85 }
86 )
87
88 videosRouter.use('/', abuseVideoRouter)
89 videosRouter.use('/', blacklistRouter)
90 videosRouter.use('/', rateVideoRouter)
91 videosRouter.use('/', videoCommentRouter)
92 videosRouter.use('/', videoCaptionsRouter)
93 videosRouter.use('/', videoImportsRouter)
94 videosRouter.use('/', ownershipVideoRouter)
95 videosRouter.use('/', watchingRouter)
96
97 videosRouter.get('/categories', listVideoCategories)
98 videosRouter.get('/licences', listVideoLicences)
99 videosRouter.get('/languages', listVideoLanguages)
100 videosRouter.get('/privacies', listVideoPrivacies)
101
102 videosRouter.get('/',
103 paginationValidator,
104 videosSortValidator,
105 setDefaultSort,
106 setDefaultPagination,
107 optionalAuthenticate,
108 commonVideosFiltersValidator,
109 asyncMiddleware(listVideos)
110 )
111 videosRouter.put('/:id',
112 authenticate,
113 reqVideoFileUpdate,
114 asyncMiddleware(videosUpdateValidator),
115 asyncRetryTransactionMiddleware(updateVideo)
116 )
117 videosRouter.post('/upload',
118 authenticate,
119 reqVideoFileAdd,
120 asyncMiddleware(videosAddValidator),
121 asyncRetryTransactionMiddleware(addVideo)
122 )
123
124 videosRouter.get('/:id/description',
125 asyncMiddleware(videosGetValidator),
126 asyncMiddleware(getVideoDescription)
127 )
128 videosRouter.get('/:id',
129 optionalAuthenticate,
130 asyncMiddleware(videosCustomGetValidator('only-video-with-rights')),
131 asyncMiddleware(checkVideoFollowConstraints),
132 asyncMiddleware(getVideo)
133 )
134 videosRouter.post('/:id/views',
135 asyncMiddleware(videosGetValidator),
136 asyncMiddleware(viewVideo)
137 )
138
139 videosRouter.delete('/:id',
140 authenticate,
141 asyncMiddleware(videosRemoveValidator),
142 asyncRetryTransactionMiddleware(removeVideo)
143 )
144
145 // ---------------------------------------------------------------------------
146
147 export {
148 videosRouter
149 }
150
151 // ---------------------------------------------------------------------------
152
153 function listVideoCategories (req: express.Request, res: express.Response) {
154 res.json(VIDEO_CATEGORIES)
155 }
156
157 function listVideoLicences (req: express.Request, res: express.Response) {
158 res.json(VIDEO_LICENCES)
159 }
160
161 function listVideoLanguages (req: express.Request, res: express.Response) {
162 res.json(VIDEO_LANGUAGES)
163 }
164
165 function listVideoPrivacies (req: express.Request, res: express.Response) {
166 res.json(VIDEO_PRIVACIES)
167 }
168
169 async function addVideo (req: express.Request, res: express.Response) {
170 // Processing the video could be long
171 // Set timeout to 10 minutes
172 req.setTimeout(1000 * 60 * 10, () => {
173 logger.error('Upload video has timed out.')
174 return res.sendStatus(408)
175 })
176
177 const videoPhysicalFile = req.files['videofile'][0]
178 const videoInfo: VideoCreate = req.body
179
180 // Prepare data so we don't block the transaction
181 const videoData = {
182 name: videoInfo.name,
183 remote: false,
184 category: videoInfo.category,
185 licence: videoInfo.licence,
186 language: videoInfo.language,
187 commentsEnabled: videoInfo.commentsEnabled || false,
188 downloadEnabled: videoInfo.downloadEnabled || true,
189 waitTranscoding: videoInfo.waitTranscoding || false,
190 state: CONFIG.TRANSCODING.ENABLED ? VideoState.TO_TRANSCODE : VideoState.PUBLISHED,
191 nsfw: videoInfo.nsfw || false,
192 description: videoInfo.description,
193 support: videoInfo.support,
194 privacy: videoInfo.privacy || VideoPrivacy.PRIVATE,
195 duration: videoPhysicalFile['duration'], // duration was added by a previous middleware
196 channelId: res.locals.videoChannel.id,
197 originallyPublishedAt: videoInfo.originallyPublishedAt
198 }
199
200 const video = new VideoModel(videoData)
201 video.url = getVideoActivityPubUrl(video) // We use the UUID, so set the URL after building the object
202
203 const videoFile = new VideoFileModel({
204 extname: extname(videoPhysicalFile.filename),
205 size: videoPhysicalFile.size
206 })
207
208 if (videoFile.isAudio()) {
209 videoFile.resolution = DEFAULT_AUDIO_RESOLUTION
210 } else {
211 videoFile.fps = await getVideoFileFPS(videoPhysicalFile.path)
212 videoFile.resolution = (await getVideoFileResolution(videoPhysicalFile.path)).videoFileResolution
213 }
214
215 // Move physical file
216 const videoDir = CONFIG.STORAGE.VIDEOS_DIR
217 const destination = join(videoDir, video.getVideoFilename(videoFile))
218 await move(videoPhysicalFile.path, destination)
219 // This is important in case if there is another attempt in the retry process
220 videoPhysicalFile.filename = video.getVideoFilename(videoFile)
221 videoPhysicalFile.path = destination
222
223 // Process thumbnail or create it from the video
224 const thumbnailField = req.files['thumbnailfile']
225 const thumbnailModel = thumbnailField
226 ? await createVideoMiniatureFromExisting(thumbnailField[0].path, video, ThumbnailType.MINIATURE)
227 : await generateVideoMiniature(video, videoFile, ThumbnailType.MINIATURE)
228
229 // Process preview or create it from the video
230 const previewField = req.files['previewfile']
231 const previewModel = previewField
232 ? await createVideoMiniatureFromExisting(previewField[0].path, video, ThumbnailType.PREVIEW)
233 : await generateVideoMiniature(video, videoFile, ThumbnailType.PREVIEW)
234
235 // Create the torrent file
236 await video.createTorrentAndSetInfoHash(videoFile)
237
238 const { videoCreated, videoWasAutoBlacklisted } = await sequelizeTypescript.transaction(async t => {
239 const sequelizeOptions = { transaction: t }
240
241 const videoCreated = await video.save(sequelizeOptions)
242
243 await videoCreated.addAndSaveThumbnail(thumbnailModel, t)
244 await videoCreated.addAndSaveThumbnail(previewModel, t)
245
246 // Do not forget to add video channel information to the created video
247 videoCreated.VideoChannel = res.locals.videoChannel
248
249 videoFile.videoId = video.id
250 await videoFile.save(sequelizeOptions)
251
252 video.VideoFiles = [ videoFile ]
253
254 // Create tags
255 if (videoInfo.tags !== undefined) {
256 const tagInstances = await TagModel.findOrCreateTags(videoInfo.tags, t)
257
258 await video.$set('Tags', tagInstances, sequelizeOptions)
259 video.Tags = tagInstances
260 }
261
262 // Schedule an update in the future?
263 if (videoInfo.scheduleUpdate) {
264 await ScheduleVideoUpdateModel.create({
265 videoId: video.id,
266 updateAt: videoInfo.scheduleUpdate.updateAt,
267 privacy: videoInfo.scheduleUpdate.privacy || null
268 }, { transaction: t })
269 }
270
271 const videoWasAutoBlacklisted = await autoBlacklistVideoIfNeeded(video, res.locals.oauth.token.User, t)
272 if (!videoWasAutoBlacklisted) await federateVideoIfNeeded(video, true, t)
273
274 auditLogger.create(getAuditIdFromRes(res), new VideoAuditView(videoCreated.toFormattedDetailsJSON()))
275 logger.info('Video with name %s and uuid %s created.', videoInfo.name, videoCreated.uuid)
276
277 return { videoCreated, videoWasAutoBlacklisted }
278 })
279
280 if (videoWasAutoBlacklisted) Notifier.Instance.notifyOnVideoAutoBlacklist(videoCreated)
281 else Notifier.Instance.notifyOnNewVideo(videoCreated)
282
283 if (video.state === VideoState.TO_TRANSCODE) {
284 // Put uuid because we don't have id auto incremented for now
285 let dataInput: VideoTranscodingPayload
286
287 if (videoFile.isAudio()) {
288 dataInput = {
289 type: 'merge-audio' as 'merge-audio',
290 resolution: DEFAULT_AUDIO_RESOLUTION,
291 videoUUID: videoCreated.uuid,
292 isNewVideo: true
293 }
294 } else {
295 dataInput = {
296 type: 'optimize' as 'optimize',
297 videoUUID: videoCreated.uuid,
298 isNewVideo: true
299 }
300 }
301
302 await JobQueue.Instance.createJob({ type: 'video-transcoding', payload: dataInput })
303 }
304
305 Hooks.runAction('action:api.video.uploaded', { video: videoCreated })
306
307 return res.json({
308 video: {
309 id: videoCreated.id,
310 uuid: videoCreated.uuid
311 }
312 }).end()
313 }
314
315 async function updateVideo (req: express.Request, res: express.Response) {
316 const videoInstance = res.locals.video
317 const videoFieldsSave = videoInstance.toJSON()
318 const oldVideoAuditView = new VideoAuditView(videoInstance.toFormattedDetailsJSON())
319 const videoInfoToUpdate: VideoUpdate = req.body
320
321 const wasPrivateVideo = videoInstance.privacy === VideoPrivacy.PRIVATE
322 const wasNotPrivateVideo = videoInstance.privacy !== VideoPrivacy.PRIVATE
323 const wasUnlistedVideo = videoInstance.privacy === VideoPrivacy.UNLISTED
324
325 // Process thumbnail or create it from the video
326 const thumbnailModel = req.files && req.files['thumbnailfile']
327 ? await createVideoMiniatureFromExisting(req.files['thumbnailfile'][0].path, videoInstance, ThumbnailType.MINIATURE)
328 : undefined
329
330 const previewModel = req.files && req.files['previewfile']
331 ? await createVideoMiniatureFromExisting(req.files['previewfile'][0].path, videoInstance, ThumbnailType.PREVIEW)
332 : undefined
333
334 try {
335 const videoInstanceUpdated = await sequelizeTypescript.transaction(async t => {
336 const sequelizeOptions = { transaction: t }
337 const oldVideoChannel = videoInstance.VideoChannel
338
339 if (videoInfoToUpdate.name !== undefined) videoInstance.set('name', videoInfoToUpdate.name)
340 if (videoInfoToUpdate.category !== undefined) videoInstance.set('category', videoInfoToUpdate.category)
341 if (videoInfoToUpdate.licence !== undefined) videoInstance.set('licence', videoInfoToUpdate.licence)
342 if (videoInfoToUpdate.language !== undefined) videoInstance.set('language', videoInfoToUpdate.language)
343 if (videoInfoToUpdate.nsfw !== undefined) videoInstance.set('nsfw', videoInfoToUpdate.nsfw)
344 if (videoInfoToUpdate.waitTranscoding !== undefined) videoInstance.set('waitTranscoding', videoInfoToUpdate.waitTranscoding)
345 if (videoInfoToUpdate.support !== undefined) videoInstance.set('support', videoInfoToUpdate.support)
346 if (videoInfoToUpdate.description !== undefined) videoInstance.set('description', videoInfoToUpdate.description)
347 if (videoInfoToUpdate.commentsEnabled !== undefined) videoInstance.set('commentsEnabled', videoInfoToUpdate.commentsEnabled)
348 if (videoInfoToUpdate.downloadEnabled !== undefined) videoInstance.set('downloadEnabled', videoInfoToUpdate.downloadEnabled)
349
350 if (videoInfoToUpdate.originallyPublishedAt !== undefined && videoInfoToUpdate.originallyPublishedAt !== null) {
351 videoInstance.originallyPublishedAt = new Date(videoInfoToUpdate.originallyPublishedAt)
352 }
353
354 if (videoInfoToUpdate.privacy !== undefined) {
355 const newPrivacy = parseInt(videoInfoToUpdate.privacy.toString(), 10)
356 videoInstance.privacy = newPrivacy
357
358 // The video was private, and is not anymore -> publish it
359 if (wasPrivateVideo === true && newPrivacy !== VideoPrivacy.PRIVATE) {
360 videoInstance.publishedAt = new Date()
361 }
362
363 // The video was not private, but now it is -> we need to unfederate it
364 if (wasNotPrivateVideo === true && newPrivacy === VideoPrivacy.PRIVATE) {
365 await VideoModel.sendDelete(videoInstance, { transaction: t })
366 }
367 }
368
369 const videoInstanceUpdated = await videoInstance.save(sequelizeOptions)
370
371 if (thumbnailModel) await videoInstanceUpdated.addAndSaveThumbnail(thumbnailModel, t)
372 if (previewModel) await videoInstanceUpdated.addAndSaveThumbnail(previewModel, t)
373
374 // Video tags update?
375 if (videoInfoToUpdate.tags !== undefined) {
376 const tagInstances = await TagModel.findOrCreateTags(videoInfoToUpdate.tags, t)
377
378 await videoInstanceUpdated.$set('Tags', tagInstances, sequelizeOptions)
379 videoInstanceUpdated.Tags = tagInstances
380 }
381
382 // Video channel update?
383 if (res.locals.videoChannel && videoInstanceUpdated.channelId !== res.locals.videoChannel.id) {
384 await videoInstanceUpdated.$set('VideoChannel', res.locals.videoChannel, { transaction: t })
385 videoInstanceUpdated.VideoChannel = res.locals.videoChannel
386
387 if (wasPrivateVideo === false) await changeVideoChannelShare(videoInstanceUpdated, oldVideoChannel, t)
388 }
389
390 // Schedule an update in the future?
391 if (videoInfoToUpdate.scheduleUpdate) {
392 await ScheduleVideoUpdateModel.upsert({
393 videoId: videoInstanceUpdated.id,
394 updateAt: videoInfoToUpdate.scheduleUpdate.updateAt,
395 privacy: videoInfoToUpdate.scheduleUpdate.privacy || null
396 }, { transaction: t })
397 } else if (videoInfoToUpdate.scheduleUpdate === null) {
398 await ScheduleVideoUpdateModel.deleteByVideoId(videoInstanceUpdated.id, t)
399 }
400
401 const isNewVideo = wasPrivateVideo && videoInstanceUpdated.privacy !== VideoPrivacy.PRIVATE
402
403 // Don't send update if the video was unfederated
404 if (!videoInstanceUpdated.VideoBlacklist || videoInstanceUpdated.VideoBlacklist.unfederated === false) {
405 await federateVideoIfNeeded(videoInstanceUpdated, isNewVideo, t)
406 }
407
408 auditLogger.update(
409 getAuditIdFromRes(res),
410 new VideoAuditView(videoInstanceUpdated.toFormattedDetailsJSON()),
411 oldVideoAuditView
412 )
413 logger.info('Video with name %s and uuid %s updated.', videoInstance.name, videoInstance.uuid)
414
415 return videoInstanceUpdated
416 })
417
418 if (wasUnlistedVideo || wasPrivateVideo) {
419 Notifier.Instance.notifyOnNewVideo(videoInstanceUpdated)
420 }
421
422 Hooks.runAction('action:api.video.updated', { video: videoInstanceUpdated })
423 } catch (err) {
424 // Force fields we want to update
425 // If the transaction is retried, sequelize will think the object has not changed
426 // So it will skip the SQL request, even if the last one was ROLLBACKed!
427 resetSequelizeInstance(videoInstance, videoFieldsSave)
428
429 throw err
430 }
431
432 return res.type('json').status(204).end()
433 }
434
435 async function getVideo (req: express.Request, res: express.Response) {
436 // We need more attributes
437 const userId: number = res.locals.oauth ? res.locals.oauth.token.User.id : null
438
439 const video = await Hooks.wrapPromise(
440 VideoModel.loadForGetAPI(res.locals.video.id, undefined, userId),
441 'filter:api.video.get.result'
442 )
443
444 if (video.isOutdated()) {
445 JobQueue.Instance.createJob({ type: 'activitypub-refresher', payload: { type: 'video', url: video.url } })
446 .catch(err => logger.error('Cannot create AP refresher job for video %s.', video.url, { err }))
447 }
448
449 return res.json(video.toFormattedDetailsJSON())
450 }
451
452 async function viewVideo (req: express.Request, res: express.Response) {
453 const videoInstance = res.locals.video
454
455 const ip = req.ip
456 const exists = await Redis.Instance.doesVideoIPViewExist(ip, videoInstance.uuid)
457 if (exists) {
458 logger.debug('View for ip %s and video %s already exists.', ip, videoInstance.uuid)
459 return res.status(204).end()
460 }
461
462 await Promise.all([
463 Redis.Instance.addVideoView(videoInstance.id),
464 Redis.Instance.setIPVideoView(ip, videoInstance.uuid)
465 ])
466
467 const serverActor = await getServerActor()
468 await sendView(serverActor, videoInstance, undefined)
469
470 Hooks.runAction('action:api.video.viewed', { video: videoInstance, ip })
471
472 return res.status(204).end()
473 }
474
475 async function getVideoDescription (req: express.Request, res: express.Response) {
476 const videoInstance = res.locals.video
477 let description = ''
478
479 if (videoInstance.isOwned()) {
480 description = videoInstance.description
481 } else {
482 description = await fetchRemoteVideoDescription(videoInstance)
483 }
484
485 return res.json({ description })
486 }
487
488 async function listVideos (req: express.Request, res: express.Response) {
489 const apiOptions = await Hooks.wrapObject({
490 start: req.query.start,
491 count: req.query.count,
492 sort: req.query.sort,
493 includeLocalVideos: true,
494 categoryOneOf: req.query.categoryOneOf,
495 licenceOneOf: req.query.licenceOneOf,
496 languageOneOf: req.query.languageOneOf,
497 tagsOneOf: req.query.tagsOneOf,
498 tagsAllOf: req.query.tagsAllOf,
499 nsfw: buildNSFWFilter(res, req.query.nsfw),
500 filter: req.query.filter as VideoFilter,
501 withFiles: false,
502 user: res.locals.oauth ? res.locals.oauth.token.User : undefined
503 }, 'filter:api.videos.list.params')
504
505 const resultList = await Hooks.wrapPromise(
506 VideoModel.listForApi(apiOptions),
507 'filter:api.videos.list.result'
508 )
509
510 return res.json(getFormattedObjects(resultList.data, resultList.total))
511 }
512
513 async function removeVideo (req: express.Request, res: express.Response) {
514 const videoInstance = res.locals.video
515
516 await sequelizeTypescript.transaction(async t => {
517 await videoInstance.destroy({ transaction: t })
518 })
519
520 auditLogger.delete(getAuditIdFromRes(res), new VideoAuditView(videoInstance.toFormattedDetailsJSON()))
521 logger.info('Video with name %s and uuid %s deleted.', videoInstance.name, videoInstance.uuid)
522
523 Hooks.runAction('action:api.video.deleted', { video: videoInstance })
524
525 return res.type('json').status(204).end()
526 }