]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - server/controllers/api/videos/index.ts
6a79a16c78de709b6897fb84ee62c2422bb286c2
[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({
272 video,
273 user: res.locals.oauth.token.User,
274 isRemote: false,
275 isNew: true,
276 transaction: t
277 })
278 if (!videoWasAutoBlacklisted) await federateVideoIfNeeded(video, true, t)
279
280 auditLogger.create(getAuditIdFromRes(res), new VideoAuditView(videoCreated.toFormattedDetailsJSON()))
281 logger.info('Video with name %s and uuid %s created.', videoInfo.name, videoCreated.uuid)
282
283 return { videoCreated, videoWasAutoBlacklisted }
284 })
285
286 if (videoWasAutoBlacklisted) Notifier.Instance.notifyOnVideoAutoBlacklist(videoCreated)
287 else Notifier.Instance.notifyOnNewVideo(videoCreated)
288
289 if (video.state === VideoState.TO_TRANSCODE) {
290 // Put uuid because we don't have id auto incremented for now
291 let dataInput: VideoTranscodingPayload
292
293 if (videoFile.isAudio()) {
294 dataInput = {
295 type: 'merge-audio' as 'merge-audio',
296 resolution: DEFAULT_AUDIO_RESOLUTION,
297 videoUUID: videoCreated.uuid,
298 isNewVideo: true
299 }
300 } else {
301 dataInput = {
302 type: 'optimize' as 'optimize',
303 videoUUID: videoCreated.uuid,
304 isNewVideo: true
305 }
306 }
307
308 await JobQueue.Instance.createJob({ type: 'video-transcoding', payload: dataInput })
309 }
310
311 Hooks.runAction('action:api.video.uploaded', { video: videoCreated })
312
313 return res.json({
314 video: {
315 id: videoCreated.id,
316 uuid: videoCreated.uuid
317 }
318 }).end()
319 }
320
321 async function updateVideo (req: express.Request, res: express.Response) {
322 const videoInstance = res.locals.video
323 const videoFieldsSave = videoInstance.toJSON()
324 const oldVideoAuditView = new VideoAuditView(videoInstance.toFormattedDetailsJSON())
325 const videoInfoToUpdate: VideoUpdate = req.body
326
327 const wasPrivateVideo = videoInstance.privacy === VideoPrivacy.PRIVATE
328 const wasNotPrivateVideo = videoInstance.privacy !== VideoPrivacy.PRIVATE
329 const wasUnlistedVideo = videoInstance.privacy === VideoPrivacy.UNLISTED
330
331 // Process thumbnail or create it from the video
332 const thumbnailModel = req.files && req.files['thumbnailfile']
333 ? await createVideoMiniatureFromExisting(req.files['thumbnailfile'][0].path, videoInstance, ThumbnailType.MINIATURE)
334 : undefined
335
336 const previewModel = req.files && req.files['previewfile']
337 ? await createVideoMiniatureFromExisting(req.files['previewfile'][0].path, videoInstance, ThumbnailType.PREVIEW)
338 : undefined
339
340 try {
341 const videoInstanceUpdated = await sequelizeTypescript.transaction(async t => {
342 const sequelizeOptions = { transaction: t }
343 const oldVideoChannel = videoInstance.VideoChannel
344
345 if (videoInfoToUpdate.name !== undefined) videoInstance.name = videoInfoToUpdate.name
346 if (videoInfoToUpdate.category !== undefined) videoInstance.category = videoInfoToUpdate.category
347 if (videoInfoToUpdate.licence !== undefined) videoInstance.licence = videoInfoToUpdate.licence
348 if (videoInfoToUpdate.language !== undefined) videoInstance.language = videoInfoToUpdate.language
349 if (videoInfoToUpdate.nsfw !== undefined) videoInstance.nsfw = videoInfoToUpdate.nsfw
350 if (videoInfoToUpdate.waitTranscoding !== undefined) videoInstance.waitTranscoding = videoInfoToUpdate.waitTranscoding
351 if (videoInfoToUpdate.support !== undefined) videoInstance.support = videoInfoToUpdate.support
352 if (videoInfoToUpdate.description !== undefined) videoInstance.description = videoInfoToUpdate.description
353 if (videoInfoToUpdate.commentsEnabled !== undefined) videoInstance.commentsEnabled = videoInfoToUpdate.commentsEnabled
354 if (videoInfoToUpdate.downloadEnabled !== undefined) videoInstance.downloadEnabled = videoInfoToUpdate.downloadEnabled
355
356 if (videoInfoToUpdate.originallyPublishedAt !== undefined && videoInfoToUpdate.originallyPublishedAt !== null) {
357 videoInstance.originallyPublishedAt = new Date(videoInfoToUpdate.originallyPublishedAt)
358 }
359
360 if (videoInfoToUpdate.privacy !== undefined) {
361 const newPrivacy = parseInt(videoInfoToUpdate.privacy.toString(), 10)
362 videoInstance.privacy = newPrivacy
363
364 // The video was private, and is not anymore -> publish it
365 if (wasPrivateVideo === true && newPrivacy !== VideoPrivacy.PRIVATE) {
366 videoInstance.publishedAt = new Date()
367 }
368
369 // The video was not private, but now it is -> we need to unfederate it
370 if (wasNotPrivateVideo === true && newPrivacy === VideoPrivacy.PRIVATE) {
371 await VideoModel.sendDelete(videoInstance, { transaction: t })
372 }
373 }
374
375 const videoInstanceUpdated = await videoInstance.save(sequelizeOptions)
376
377 if (thumbnailModel) await videoInstanceUpdated.addAndSaveThumbnail(thumbnailModel, t)
378 if (previewModel) await videoInstanceUpdated.addAndSaveThumbnail(previewModel, t)
379
380 // Video tags update?
381 if (videoInfoToUpdate.tags !== undefined) {
382 const tagInstances = await TagModel.findOrCreateTags(videoInfoToUpdate.tags, t)
383
384 await videoInstanceUpdated.$set('Tags', tagInstances, sequelizeOptions)
385 videoInstanceUpdated.Tags = tagInstances
386 }
387
388 // Video channel update?
389 if (res.locals.videoChannel && videoInstanceUpdated.channelId !== res.locals.videoChannel.id) {
390 await videoInstanceUpdated.$set('VideoChannel', res.locals.videoChannel, { transaction: t })
391 videoInstanceUpdated.VideoChannel = res.locals.videoChannel
392
393 if (wasPrivateVideo === false) await changeVideoChannelShare(videoInstanceUpdated, oldVideoChannel, t)
394 }
395
396 // Schedule an update in the future?
397 if (videoInfoToUpdate.scheduleUpdate) {
398 await ScheduleVideoUpdateModel.upsert({
399 videoId: videoInstanceUpdated.id,
400 updateAt: videoInfoToUpdate.scheduleUpdate.updateAt,
401 privacy: videoInfoToUpdate.scheduleUpdate.privacy || null
402 }, { transaction: t })
403 } else if (videoInfoToUpdate.scheduleUpdate === null) {
404 await ScheduleVideoUpdateModel.deleteByVideoId(videoInstanceUpdated.id, t)
405 }
406
407 await autoBlacklistVideoIfNeeded({
408 video: videoInstanceUpdated,
409 user: res.locals.oauth.token.User,
410 isRemote: false,
411 isNew: false,
412 transaction: t
413 })
414
415 const isNewVideo = wasPrivateVideo && videoInstanceUpdated.privacy !== VideoPrivacy.PRIVATE
416
417 // Don't send update if the video was unfederated
418 if (!videoInstanceUpdated.VideoBlacklist || videoInstanceUpdated.VideoBlacklist.unfederated === false) {
419 await federateVideoIfNeeded(videoInstanceUpdated, isNewVideo, t)
420 }
421
422 auditLogger.update(
423 getAuditIdFromRes(res),
424 new VideoAuditView(videoInstanceUpdated.toFormattedDetailsJSON()),
425 oldVideoAuditView
426 )
427 logger.info('Video with name %s and uuid %s updated.', videoInstance.name, videoInstance.uuid)
428
429 return videoInstanceUpdated
430 })
431
432 if (wasUnlistedVideo || wasPrivateVideo) {
433 Notifier.Instance.notifyOnNewVideo(videoInstanceUpdated)
434 }
435
436 Hooks.runAction('action:api.video.updated', { video: videoInstanceUpdated })
437 } catch (err) {
438 // Force fields we want to update
439 // If the transaction is retried, sequelize will think the object has not changed
440 // So it will skip the SQL request, even if the last one was ROLLBACKed!
441 resetSequelizeInstance(videoInstance, videoFieldsSave)
442
443 throw err
444 }
445
446 return res.type('json').status(204).end()
447 }
448
449 async function getVideo (req: express.Request, res: express.Response) {
450 // We need more attributes
451 const userId: number = res.locals.oauth ? res.locals.oauth.token.User.id : null
452
453 const video = await Hooks.wrapPromiseFun(
454 VideoModel.loadForGetAPI,
455 { id: res.locals.video.id, userId },
456 'filter:api.video.get.result'
457 )
458
459 if (video.isOutdated()) {
460 JobQueue.Instance.createJob({ type: 'activitypub-refresher', payload: { type: 'video', url: video.url } })
461 .catch(err => logger.error('Cannot create AP refresher job for video %s.', video.url, { err }))
462 }
463
464 return res.json(video.toFormattedDetailsJSON())
465 }
466
467 async function viewVideo (req: express.Request, res: express.Response) {
468 const videoInstance = res.locals.video
469
470 const ip = req.ip
471 const exists = await Redis.Instance.doesVideoIPViewExist(ip, videoInstance.uuid)
472 if (exists) {
473 logger.debug('View for ip %s and video %s already exists.', ip, videoInstance.uuid)
474 return res.status(204).end()
475 }
476
477 await Promise.all([
478 Redis.Instance.addVideoView(videoInstance.id),
479 Redis.Instance.setIPVideoView(ip, videoInstance.uuid)
480 ])
481
482 const serverActor = await getServerActor()
483 await sendView(serverActor, videoInstance, undefined)
484
485 Hooks.runAction('action:api.video.viewed', { video: videoInstance, ip })
486
487 return res.status(204).end()
488 }
489
490 async function getVideoDescription (req: express.Request, res: express.Response) {
491 const videoInstance = res.locals.video
492 let description = ''
493
494 if (videoInstance.isOwned()) {
495 description = videoInstance.description
496 } else {
497 description = await fetchRemoteVideoDescription(videoInstance)
498 }
499
500 return res.json({ description })
501 }
502
503 async function listVideos (req: express.Request, res: express.Response) {
504 const apiOptions = await Hooks.wrapObject({
505 start: req.query.start,
506 count: req.query.count,
507 sort: req.query.sort,
508 includeLocalVideos: true,
509 categoryOneOf: req.query.categoryOneOf,
510 licenceOneOf: req.query.licenceOneOf,
511 languageOneOf: req.query.languageOneOf,
512 tagsOneOf: req.query.tagsOneOf,
513 tagsAllOf: req.query.tagsAllOf,
514 nsfw: buildNSFWFilter(res, req.query.nsfw),
515 filter: req.query.filter as VideoFilter,
516 withFiles: false,
517 user: res.locals.oauth ? res.locals.oauth.token.User : undefined
518 }, 'filter:api.videos.list.params')
519
520 const resultList = await Hooks.wrapPromiseFun(
521 VideoModel.listForApi,
522 apiOptions,
523 'filter:api.videos.list.result'
524 )
525
526 return res.json(getFormattedObjects(resultList.data, resultList.total))
527 }
528
529 async function removeVideo (req: express.Request, res: express.Response) {
530 const videoInstance = res.locals.video
531
532 await sequelizeTypescript.transaction(async t => {
533 await videoInstance.destroy({ transaction: t })
534 })
535
536 auditLogger.delete(getAuditIdFromRes(res), new VideoAuditView(videoInstance.toFormattedDetailsJSON()))
537 logger.info('Video with name %s and uuid %s deleted.', videoInstance.name, videoInstance.uuid)
538
539 Hooks.runAction('action:api.video.deleted', { video: videoInstance })
540
541 return res.type('json').status(204).end()
542 }