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