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