aboutsummaryrefslogtreecommitdiffhomepage
path: root/server/controllers/api/videos/index.ts
diff options
context:
space:
mode:
Diffstat (limited to 'server/controllers/api/videos/index.ts')
-rw-r--r--server/controllers/api/videos/index.ts406
1 files changed, 15 insertions, 391 deletions
diff --git a/server/controllers/api/videos/index.ts b/server/controllers/api/videos/index.ts
index f5ce15074..6483d2e8a 100644
--- a/server/controllers/api/videos/index.ts
+++ b/server/controllers/api/videos/index.ts
@@ -1,43 +1,20 @@
1import * as express from 'express' 1import * as express from 'express'
2import { move } from 'fs-extra'
3import { extname } from 'path'
4import toInt from 'validator/lib/toInt' 2import toInt from 'validator/lib/toInt'
5import { deleteResumableUploadMetaFile, getResumableUploadPath } from '@server/helpers/upload'
6import { createTorrentAndSetInfoHash } from '@server/helpers/webtorrent'
7import { changeVideoChannelShare } from '@server/lib/activitypub/share'
8import { getLocalVideoActivityPubUrl } from '@server/lib/activitypub/url'
9import { LiveManager } from '@server/lib/live-manager' 3import { LiveManager } from '@server/lib/live-manager'
10import { addOptimizeOrMergeAudioJob, buildLocalVideoFromReq, buildVideoThumbnailsFromReq, setVideoTags } from '@server/lib/video'
11import { generateVideoFilename, getVideoFilePath } from '@server/lib/video-paths'
12import { getServerActor } from '@server/models/application/application' 4import { getServerActor } from '@server/models/application/application'
13import { MVideo, MVideoFile, MVideoFullLight } from '@server/types/models' 5import { VideosCommonQuery } from '../../../../shared'
14import { uploadx } from '@uploadx/core'
15import { VideoCreate, VideosCommonQuery, VideoState, VideoUpdate } from '../../../../shared'
16import { HttpStatusCode } from '../../../../shared/core-utils/miscs' 6import { HttpStatusCode } from '../../../../shared/core-utils/miscs'
17import { auditLoggerFactory, getAuditIdFromRes, VideoAuditView } from '../../../helpers/audit-logger' 7import { auditLoggerFactory, getAuditIdFromRes, VideoAuditView } from '../../../helpers/audit-logger'
18import { resetSequelizeInstance, retryTransactionWrapper } from '../../../helpers/database-utils' 8import { buildNSFWFilter, getCountVideos } from '../../../helpers/express-utils'
19import { buildNSFWFilter, createReqFiles, getCountVideos } from '../../../helpers/express-utils' 9import { logger } from '../../../helpers/logger'
20import { getMetadataFromFile, getVideoFileFPS, getVideoFileResolution } from '../../../helpers/ffprobe-utils'
21import { logger, loggerTagsFactory } from '../../../helpers/logger'
22import { getFormattedObjects } from '../../../helpers/utils' 10import { getFormattedObjects } from '../../../helpers/utils'
23import { CONFIG } from '../../../initializers/config' 11import { VIDEO_CATEGORIES, VIDEO_LANGUAGES, VIDEO_LICENCES, VIDEO_PRIVACIES } from '../../../initializers/constants'
24import {
25 DEFAULT_AUDIO_RESOLUTION,
26 MIMETYPES,
27 VIDEO_CATEGORIES,
28 VIDEO_LANGUAGES,
29 VIDEO_LICENCES,
30 VIDEO_PRIVACIES
31} from '../../../initializers/constants'
32import { sequelizeTypescript } from '../../../initializers/database' 12import { sequelizeTypescript } from '../../../initializers/database'
33import { sendView } from '../../../lib/activitypub/send/send-view' 13import { sendView } from '../../../lib/activitypub/send/send-view'
34import { federateVideoIfNeeded, fetchRemoteVideoDescription } from '../../../lib/activitypub/videos' 14import { fetchRemoteVideoDescription } from '../../../lib/activitypub/videos'
35import { JobQueue } from '../../../lib/job-queue' 15import { JobQueue } from '../../../lib/job-queue'
36import { Notifier } from '../../../lib/notifier'
37import { Hooks } from '../../../lib/plugins/hooks' 16import { Hooks } from '../../../lib/plugins/hooks'
38import { Redis } from '../../../lib/redis' 17import { Redis } from '../../../lib/redis'
39import { generateVideoMiniature } from '../../../lib/thumbnail'
40import { autoBlacklistVideoIfNeeded } from '../../../lib/video-blacklist'
41import { 18import {
42 asyncMiddleware, 19 asyncMiddleware,
43 asyncRetryTransactionMiddleware, 20 asyncRetryTransactionMiddleware,
@@ -49,16 +26,11 @@ import {
49 setDefaultPagination, 26 setDefaultPagination,
50 setDefaultVideosSort, 27 setDefaultVideosSort,
51 videoFileMetadataGetValidator, 28 videoFileMetadataGetValidator,
52 videosAddLegacyValidator,
53 videosAddResumableInitValidator,
54 videosAddResumableValidator,
55 videosCustomGetValidator, 29 videosCustomGetValidator,
56 videosGetValidator, 30 videosGetValidator,
57 videosRemoveValidator, 31 videosRemoveValidator,
58 videosSortValidator, 32 videosSortValidator
59 videosUpdateValidator
60} from '../../../middlewares' 33} from '../../../middlewares'
61import { ScheduleVideoUpdateModel } from '../../../models/video/schedule-video-update'
62import { VideoModel } from '../../../models/video/video' 34import { VideoModel } from '../../../models/video/video'
63import { VideoFileModel } from '../../../models/video/video-file' 35import { VideoFileModel } from '../../../models/video/video-file'
64import { blacklistRouter } from './blacklist' 36import { blacklistRouter } from './blacklist'
@@ -68,40 +40,12 @@ import { videoImportsRouter } from './import'
68import { liveRouter } from './live' 40import { liveRouter } from './live'
69import { ownershipVideoRouter } from './ownership' 41import { ownershipVideoRouter } from './ownership'
70import { rateVideoRouter } from './rate' 42import { rateVideoRouter } from './rate'
43import { updateRouter } from './update'
44import { uploadRouter } from './upload'
71import { watchingRouter } from './watching' 45import { watchingRouter } from './watching'
72 46
73const lTags = loggerTagsFactory('api', 'video')
74const auditLogger = auditLoggerFactory('videos') 47const auditLogger = auditLoggerFactory('videos')
75const videosRouter = express.Router() 48const videosRouter = express.Router()
76const uploadxMiddleware = uploadx.upload({ directory: getResumableUploadPath() })
77
78const reqVideoFileAdd = createReqFiles(
79 [ 'videofile', 'thumbnailfile', 'previewfile' ],
80 Object.assign({}, MIMETYPES.VIDEO.MIMETYPE_EXT, MIMETYPES.IMAGE.MIMETYPE_EXT),
81 {
82 videofile: CONFIG.STORAGE.TMP_DIR,
83 thumbnailfile: CONFIG.STORAGE.TMP_DIR,
84 previewfile: CONFIG.STORAGE.TMP_DIR
85 }
86)
87
88const reqVideoFileAddResumable = createReqFiles(
89 [ 'thumbnailfile', 'previewfile' ],
90 MIMETYPES.IMAGE.MIMETYPE_EXT,
91 {
92 thumbnailfile: getResumableUploadPath(),
93 previewfile: getResumableUploadPath()
94 }
95)
96
97const reqVideoFileUpdate = createReqFiles(
98 [ 'thumbnailfile', 'previewfile' ],
99 MIMETYPES.IMAGE.MIMETYPE_EXT,
100 {
101 thumbnailfile: CONFIG.STORAGE.TMP_DIR,
102 previewfile: CONFIG.STORAGE.TMP_DIR
103 }
104)
105 49
106videosRouter.use('/', blacklistRouter) 50videosRouter.use('/', blacklistRouter)
107videosRouter.use('/', rateVideoRouter) 51videosRouter.use('/', rateVideoRouter)
@@ -111,6 +55,8 @@ videosRouter.use('/', videoImportsRouter)
111videosRouter.use('/', ownershipVideoRouter) 55videosRouter.use('/', ownershipVideoRouter)
112videosRouter.use('/', watchingRouter) 56videosRouter.use('/', watchingRouter)
113videosRouter.use('/', liveRouter) 57videosRouter.use('/', liveRouter)
58videosRouter.use('/', uploadRouter)
59videosRouter.use('/', updateRouter)
114 60
115videosRouter.get('/categories', listVideoCategories) 61videosRouter.get('/categories', listVideoCategories)
116videosRouter.get('/licences', listVideoLicences) 62videosRouter.get('/licences', listVideoLicences)
@@ -127,39 +73,6 @@ videosRouter.get('/',
127 asyncMiddleware(listVideos) 73 asyncMiddleware(listVideos)
128) 74)
129 75
130videosRouter.post('/upload',
131 authenticate,
132 reqVideoFileAdd,
133 asyncMiddleware(videosAddLegacyValidator),
134 asyncRetryTransactionMiddleware(addVideoLegacy)
135)
136
137videosRouter.post('/upload-resumable',
138 authenticate,
139 reqVideoFileAddResumable,
140 asyncMiddleware(videosAddResumableInitValidator),
141 uploadxMiddleware
142)
143
144videosRouter.delete('/upload-resumable',
145 authenticate,
146 uploadxMiddleware
147)
148
149videosRouter.put('/upload-resumable',
150 authenticate,
151 uploadxMiddleware, // uploadx doesn't use call next() before the file upload completes
152 asyncMiddleware(videosAddResumableValidator),
153 asyncMiddleware(addVideoResumable)
154)
155
156videosRouter.put('/:id',
157 authenticate,
158 reqVideoFileUpdate,
159 asyncMiddleware(videosUpdateValidator),
160 asyncRetryTransactionMiddleware(updateVideo)
161)
162
163videosRouter.get('/:id/description', 76videosRouter.get('/:id/description',
164 asyncMiddleware(videosGetValidator), 77 asyncMiddleware(videosGetValidator),
165 asyncMiddleware(getVideoDescription) 78 asyncMiddleware(getVideoDescription)
@@ -209,279 +122,7 @@ function listVideoPrivacies (_req: express.Request, res: express.Response) {
209 res.json(VIDEO_PRIVACIES) 122 res.json(VIDEO_PRIVACIES)
210} 123}
211 124
212async function addVideoLegacy (req: express.Request, res: express.Response) { 125async function getVideo (_req: express.Request, res: express.Response) {
213 // Uploading the video could be long
214 // Set timeout to 10 minutes, as Express's default is 2 minutes
215 req.setTimeout(1000 * 60 * 10, () => {
216 logger.error('Upload video has timed out.')
217 return res.sendStatus(HttpStatusCode.REQUEST_TIMEOUT_408)
218 })
219
220 const videoPhysicalFile = req.files['videofile'][0]
221 const videoInfo: VideoCreate = req.body
222 const files = req.files
223
224 return addVideo({ res, videoPhysicalFile, videoInfo, files })
225}
226
227async function addVideoResumable (_req: express.Request, res: express.Response) {
228 const videoPhysicalFile = res.locals.videoFileResumable
229 const videoInfo = videoPhysicalFile.metadata
230 const files = { previewfile: videoInfo.previewfile }
231
232 // Don't need the meta file anymore
233 await deleteResumableUploadMetaFile(videoPhysicalFile.path)
234
235 return addVideo({ res, videoPhysicalFile, videoInfo, files })
236}
237
238async function addVideo (options: {
239 res: express.Response
240 videoPhysicalFile: express.VideoUploadFile
241 videoInfo: VideoCreate
242 files: express.UploadFiles
243}) {
244 const { res, videoPhysicalFile, videoInfo, files } = options
245 const videoChannel = res.locals.videoChannel
246 const user = res.locals.oauth.token.User
247
248 const videoData = buildLocalVideoFromReq(videoInfo, videoChannel.id)
249
250 videoData.state = CONFIG.TRANSCODING.ENABLED
251 ? VideoState.TO_TRANSCODE
252 : VideoState.PUBLISHED
253
254 videoData.duration = videoPhysicalFile.duration // duration was added by a previous middleware
255
256 const video = new VideoModel(videoData) as MVideoFullLight
257 video.VideoChannel = videoChannel
258 video.url = getLocalVideoActivityPubUrl(video) // We use the UUID, so set the URL after building the object
259
260 const videoFile = new VideoFileModel({
261 extname: extname(videoPhysicalFile.filename),
262 size: videoPhysicalFile.size,
263 videoStreamingPlaylistId: null,
264 metadata: await getMetadataFromFile(videoPhysicalFile.path)
265 })
266
267 if (videoFile.isAudio()) {
268 videoFile.resolution = DEFAULT_AUDIO_RESOLUTION
269 } else {
270 videoFile.fps = await getVideoFileFPS(videoPhysicalFile.path)
271 videoFile.resolution = (await getVideoFileResolution(videoPhysicalFile.path)).videoFileResolution
272 }
273
274 videoFile.filename = generateVideoFilename(video, false, videoFile.resolution, videoFile.extname)
275
276 // Move physical file
277 const destination = getVideoFilePath(video, videoFile)
278 await move(videoPhysicalFile.path, destination)
279 // This is important in case if there is another attempt in the retry process
280 videoPhysicalFile.filename = getVideoFilePath(video, videoFile)
281 videoPhysicalFile.path = destination
282
283 const [ thumbnailModel, previewModel ] = await buildVideoThumbnailsFromReq({
284 video,
285 files,
286 fallback: type => generateVideoMiniature({ video, videoFile, type })
287 })
288
289 const { videoCreated } = await sequelizeTypescript.transaction(async t => {
290 const sequelizeOptions = { transaction: t }
291
292 const videoCreated = await video.save(sequelizeOptions) as MVideoFullLight
293
294 await videoCreated.addAndSaveThumbnail(thumbnailModel, t)
295 await videoCreated.addAndSaveThumbnail(previewModel, t)
296
297 // Do not forget to add video channel information to the created video
298 videoCreated.VideoChannel = res.locals.videoChannel
299
300 videoFile.videoId = video.id
301 await videoFile.save(sequelizeOptions)
302
303 video.VideoFiles = [ videoFile ]
304
305 await setVideoTags({ video, tags: videoInfo.tags, transaction: t })
306
307 // Schedule an update in the future?
308 if (videoInfo.scheduleUpdate) {
309 await ScheduleVideoUpdateModel.create({
310 videoId: video.id,
311 updateAt: new Date(videoInfo.scheduleUpdate.updateAt),
312 privacy: videoInfo.scheduleUpdate.privacy || null
313 }, { transaction: t })
314 }
315
316 // Channel has a new content, set as updated
317 await videoCreated.VideoChannel.setAsUpdated(t)
318
319 await autoBlacklistVideoIfNeeded({
320 video,
321 user,
322 isRemote: false,
323 isNew: true,
324 transaction: t
325 })
326
327 auditLogger.create(getAuditIdFromRes(res), new VideoAuditView(videoCreated.toFormattedDetailsJSON()))
328 logger.info('Video with name %s and uuid %s created.', videoInfo.name, videoCreated.uuid, lTags(videoCreated.uuid))
329
330 return { videoCreated }
331 })
332
333 // Create the torrent file in async way because it could be long
334 createTorrentAndSetInfoHashAsync(video, videoFile)
335 .catch(err => logger.error('Cannot create torrent file for video %s', video.url, { err, ...lTags(video.uuid) }))
336 .then(() => VideoModel.loadAndPopulateAccountAndServerAndTags(video.id))
337 .then(refreshedVideo => {
338 if (!refreshedVideo) return
339
340 // Only federate and notify after the torrent creation
341 Notifier.Instance.notifyOnNewVideoIfNeeded(refreshedVideo)
342
343 return retryTransactionWrapper(() => {
344 return sequelizeTypescript.transaction(t => federateVideoIfNeeded(refreshedVideo, true, t))
345 })
346 })
347 .catch(err => logger.error('Cannot federate or notify video creation %s', video.url, { err, ...lTags(video.uuid) }))
348
349 if (video.state === VideoState.TO_TRANSCODE) {
350 await addOptimizeOrMergeAudioJob(videoCreated, videoFile, user)
351 }
352
353 Hooks.runAction('action:api.video.uploaded', { video: videoCreated })
354
355 return res.json({
356 video: {
357 id: videoCreated.id,
358 uuid: videoCreated.uuid
359 }
360 })
361}
362
363async function updateVideo (req: express.Request, res: express.Response) {
364 const videoInstance = res.locals.videoAll
365 const videoFieldsSave = videoInstance.toJSON()
366 const oldVideoAuditView = new VideoAuditView(videoInstance.toFormattedDetailsJSON())
367 const videoInfoToUpdate: VideoUpdate = req.body
368
369 const wasConfidentialVideo = videoInstance.isConfidential()
370 const hadPrivacyForFederation = videoInstance.hasPrivacyForFederation()
371
372 const [ thumbnailModel, previewModel ] = await buildVideoThumbnailsFromReq({
373 video: videoInstance,
374 files: req.files,
375 fallback: () => Promise.resolve(undefined),
376 automaticallyGenerated: false
377 })
378
379 try {
380 const videoInstanceUpdated = await sequelizeTypescript.transaction(async t => {
381 const sequelizeOptions = { transaction: t }
382 const oldVideoChannel = videoInstance.VideoChannel
383
384 if (videoInfoToUpdate.name !== undefined) videoInstance.name = videoInfoToUpdate.name
385 if (videoInfoToUpdate.category !== undefined) videoInstance.category = videoInfoToUpdate.category
386 if (videoInfoToUpdate.licence !== undefined) videoInstance.licence = videoInfoToUpdate.licence
387 if (videoInfoToUpdate.language !== undefined) videoInstance.language = videoInfoToUpdate.language
388 if (videoInfoToUpdate.nsfw !== undefined) videoInstance.nsfw = videoInfoToUpdate.nsfw
389 if (videoInfoToUpdate.waitTranscoding !== undefined) videoInstance.waitTranscoding = videoInfoToUpdate.waitTranscoding
390 if (videoInfoToUpdate.support !== undefined) videoInstance.support = videoInfoToUpdate.support
391 if (videoInfoToUpdate.description !== undefined) videoInstance.description = videoInfoToUpdate.description
392 if (videoInfoToUpdate.commentsEnabled !== undefined) videoInstance.commentsEnabled = videoInfoToUpdate.commentsEnabled
393 if (videoInfoToUpdate.downloadEnabled !== undefined) videoInstance.downloadEnabled = videoInfoToUpdate.downloadEnabled
394
395 if (videoInfoToUpdate.originallyPublishedAt !== undefined && videoInfoToUpdate.originallyPublishedAt !== null) {
396 videoInstance.originallyPublishedAt = new Date(videoInfoToUpdate.originallyPublishedAt)
397 }
398
399 let isNewVideo = false
400 if (videoInfoToUpdate.privacy !== undefined) {
401 isNewVideo = videoInstance.isNewVideo(videoInfoToUpdate.privacy)
402
403 const newPrivacy = parseInt(videoInfoToUpdate.privacy.toString(), 10)
404 videoInstance.setPrivacy(newPrivacy)
405
406 // Unfederate the video if the new privacy is not compatible with federation
407 if (hadPrivacyForFederation && !videoInstance.hasPrivacyForFederation()) {
408 await VideoModel.sendDelete(videoInstance, { transaction: t })
409 }
410 }
411
412 const videoInstanceUpdated = await videoInstance.save(sequelizeOptions) as MVideoFullLight
413
414 if (thumbnailModel) await videoInstanceUpdated.addAndSaveThumbnail(thumbnailModel, t)
415 if (previewModel) await videoInstanceUpdated.addAndSaveThumbnail(previewModel, t)
416
417 // Video tags update?
418 if (videoInfoToUpdate.tags !== undefined) {
419 await setVideoTags({
420 video: videoInstanceUpdated,
421 tags: videoInfoToUpdate.tags,
422 transaction: t
423 })
424 }
425
426 // Video channel update?
427 if (res.locals.videoChannel && videoInstanceUpdated.channelId !== res.locals.videoChannel.id) {
428 await videoInstanceUpdated.$set('VideoChannel', res.locals.videoChannel, { transaction: t })
429 videoInstanceUpdated.VideoChannel = res.locals.videoChannel
430
431 if (hadPrivacyForFederation === true) await changeVideoChannelShare(videoInstanceUpdated, oldVideoChannel, t)
432 }
433
434 // Schedule an update in the future?
435 if (videoInfoToUpdate.scheduleUpdate) {
436 await ScheduleVideoUpdateModel.upsert({
437 videoId: videoInstanceUpdated.id,
438 updateAt: new Date(videoInfoToUpdate.scheduleUpdate.updateAt),
439 privacy: videoInfoToUpdate.scheduleUpdate.privacy || null
440 }, { transaction: t })
441 } else if (videoInfoToUpdate.scheduleUpdate === null) {
442 await ScheduleVideoUpdateModel.deleteByVideoId(videoInstanceUpdated.id, t)
443 }
444
445 await autoBlacklistVideoIfNeeded({
446 video: videoInstanceUpdated,
447 user: res.locals.oauth.token.User,
448 isRemote: false,
449 isNew: false,
450 transaction: t
451 })
452
453 await federateVideoIfNeeded(videoInstanceUpdated, isNewVideo, t)
454
455 auditLogger.update(
456 getAuditIdFromRes(res),
457 new VideoAuditView(videoInstanceUpdated.toFormattedDetailsJSON()),
458 oldVideoAuditView
459 )
460 logger.info('Video with name %s and uuid %s updated.', videoInstance.name, videoInstance.uuid, lTags(videoInstance.uuid))
461
462 return videoInstanceUpdated
463 })
464
465 if (wasConfidentialVideo) {
466 Notifier.Instance.notifyOnNewVideoIfNeeded(videoInstanceUpdated)
467 }
468
469 Hooks.runAction('action:api.video.updated', { video: videoInstanceUpdated, body: req.body })
470 } catch (err) {
471 // Force fields we want to update
472 // If the transaction is retried, sequelize will think the object has not changed
473 // So it will skip the SQL request, even if the last one was ROLLBACKed!
474 resetSequelizeInstance(videoInstance, videoFieldsSave)
475
476 throw err
477 }
478
479 return res.type('json')
480 .status(HttpStatusCode.NO_CONTENT_204)
481 .end()
482}
483
484async function getVideo (req: express.Request, res: express.Response) {
485 // We need more attributes 126 // We need more attributes
486 const userId: number = res.locals.oauth ? res.locals.oauth.token.User.id : null 127 const userId: number = res.locals.oauth ? res.locals.oauth.token.User.id : null
487 128
@@ -543,13 +184,10 @@ async function viewVideo (req: express.Request, res: express.Response) {
543 184
544async function getVideoDescription (req: express.Request, res: express.Response) { 185async function getVideoDescription (req: express.Request, res: express.Response) {
545 const videoInstance = res.locals.videoAll 186 const videoInstance = res.locals.videoAll
546 let description = ''
547 187
548 if (videoInstance.isOwned()) { 188 const description = videoInstance.isOwned()
549 description = videoInstance.description 189 ? videoInstance.description
550 } else { 190 : await fetchRemoteVideoDescription(videoInstance)
551 description = await fetchRemoteVideoDescription(videoInstance)
552 }
553 191
554 return res.json({ description }) 192 return res.json({ description })
555} 193}
@@ -591,7 +229,7 @@ async function listVideos (req: express.Request, res: express.Response) {
591 return res.json(getFormattedObjects(resultList.data, resultList.total)) 229 return res.json(getFormattedObjects(resultList.data, resultList.total))
592} 230}
593 231
594async function removeVideo (req: express.Request, res: express.Response) { 232async function removeVideo (_req: express.Request, res: express.Response) {
595 const videoInstance = res.locals.videoAll 233 const videoInstance = res.locals.videoAll
596 234
597 await sequelizeTypescript.transaction(async t => { 235 await sequelizeTypescript.transaction(async t => {
@@ -607,17 +245,3 @@ async function removeVideo (req: express.Request, res: express.Response) {
607 .status(HttpStatusCode.NO_CONTENT_204) 245 .status(HttpStatusCode.NO_CONTENT_204)
608 .end() 246 .end()
609} 247}
610
611async function createTorrentAndSetInfoHashAsync (video: MVideo, fileArg: MVideoFile) {
612 await createTorrentAndSetInfoHash(video, fileArg)
613
614 // Refresh videoFile because the createTorrentAndSetInfoHash could be long
615 const refreshedFile = await VideoFileModel.loadWithVideo(fileArg.id)
616 // File does not exist anymore, remove the generated torrent
617 if (!refreshedFile) return fileArg.removeTorrent()
618
619 refreshedFile.infoHash = fileArg.infoHash
620 refreshedFile.torrentFilename = fileArg.torrentFilename
621
622 return refreshedFile.save()
623}