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