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'
10 DEFAULT_AUDIO_RESOLUTION,
16 } from '../../../initializers/constants'
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'
27 asyncRetryTransactionMiddleware,
29 checkVideoFollowConstraints,
30 commonVideosFiltersValidator,
36 videosCustomGetValidator,
38 videosRemoveValidator,
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 import { MVideoDetails, MVideoFullLight } from '@server/typings/models'
68 const auditLogger = auditLoggerFactory('videos')
69 const videosRouter = express.Router()
71 const reqVideoFileAdd = createReqFiles(
72 [ 'videofile', 'thumbnailfile', 'previewfile' ],
73 Object.assign({}, MIMETYPES.VIDEO.MIMETYPE_EXT, MIMETYPES.IMAGE.MIMETYPE_EXT),
75 videofile: CONFIG.STORAGE.TMP_DIR,
76 thumbnailfile: CONFIG.STORAGE.TMP_DIR,
77 previewfile: CONFIG.STORAGE.TMP_DIR
80 const reqVideoFileUpdate = createReqFiles(
81 [ 'thumbnailfile', 'previewfile' ],
82 MIMETYPES.IMAGE.MIMETYPE_EXT,
84 thumbnailfile: CONFIG.STORAGE.TMP_DIR,
85 previewfile: CONFIG.STORAGE.TMP_DIR
89 videosRouter.use('/', abuseVideoRouter)
90 videosRouter.use('/', blacklistRouter)
91 videosRouter.use('/', rateVideoRouter)
92 videosRouter.use('/', videoCommentRouter)
93 videosRouter.use('/', videoCaptionsRouter)
94 videosRouter.use('/', videoImportsRouter)
95 videosRouter.use('/', ownershipVideoRouter)
96 videosRouter.use('/', watchingRouter)
98 videosRouter.get('/categories', listVideoCategories)
99 videosRouter.get('/licences', listVideoLicences)
100 videosRouter.get('/languages', listVideoLanguages)
101 videosRouter.get('/privacies', listVideoPrivacies)
103 videosRouter.get('/',
107 setDefaultPagination,
108 optionalAuthenticate,
109 commonVideosFiltersValidator,
110 asyncMiddleware(listVideos)
112 videosRouter.put('/:id',
115 asyncMiddleware(videosUpdateValidator),
116 asyncRetryTransactionMiddleware(updateVideo)
118 videosRouter.post('/upload',
121 asyncMiddleware(videosAddValidator),
122 asyncRetryTransactionMiddleware(addVideo)
125 videosRouter.get('/:id/description',
126 asyncMiddleware(videosGetValidator),
127 asyncMiddleware(getVideoDescription)
129 videosRouter.get('/:id',
130 optionalAuthenticate,
131 asyncMiddleware(videosCustomGetValidator('only-video-with-rights')),
132 asyncMiddleware(checkVideoFollowConstraints),
133 asyncMiddleware(getVideo)
135 videosRouter.post('/:id/views',
136 asyncMiddleware(videosGetValidator),
137 asyncMiddleware(viewVideo)
140 videosRouter.delete('/:id',
142 asyncMiddleware(videosRemoveValidator),
143 asyncRetryTransactionMiddleware(removeVideo)
146 // ---------------------------------------------------------------------------
152 // ---------------------------------------------------------------------------
154 function listVideoCategories (req: express.Request, res: express.Response) {
155 res.json(VIDEO_CATEGORIES)
158 function listVideoLicences (req: express.Request, res: express.Response) {
159 res.json(VIDEO_LICENCES)
162 function listVideoLanguages (req: express.Request, res: express.Response) {
163 res.json(VIDEO_LANGUAGES)
166 function listVideoPrivacies (req: express.Request, res: express.Response) {
167 res.json(VIDEO_PRIVACIES)
170 async function addVideo (req: express.Request, res: express.Response) {
171 // Processing the video could be long
172 // Set timeout to 10 minutes
173 req.setTimeout(1000 * 60 * 10, () => {
174 logger.error('Upload video has timed out.')
175 return res.sendStatus(408)
178 const videoPhysicalFile = req.files['videofile'][0]
179 const videoInfo: VideoCreate = req.body
181 // Prepare data so we don't block the transaction
183 name: videoInfo.name,
185 category: videoInfo.category,
186 licence: videoInfo.licence,
187 language: videoInfo.language,
188 commentsEnabled: videoInfo.commentsEnabled || false,
189 downloadEnabled: videoInfo.downloadEnabled !== false, // If the value is not "false", the default is "true"
190 waitTranscoding: videoInfo.waitTranscoding || false,
191 state: CONFIG.TRANSCODING.ENABLED ? VideoState.TO_TRANSCODE : VideoState.PUBLISHED,
192 nsfw: videoInfo.nsfw || false,
193 description: videoInfo.description,
194 support: videoInfo.support,
195 privacy: videoInfo.privacy || VideoPrivacy.PRIVATE,
196 duration: videoPhysicalFile['duration'], // duration was added by a previous middleware
197 channelId: res.locals.videoChannel.id,
198 originallyPublishedAt: videoInfo.originallyPublishedAt
201 const video = new VideoModel(videoData) as MVideoDetails
202 video.url = getVideoActivityPubUrl(video) // We use the UUID, so set the URL after building the object
204 const videoFile = new VideoFileModel({
205 extname: extname(videoPhysicalFile.filename),
206 size: videoPhysicalFile.size
209 if (videoFile.isAudio()) {
210 videoFile.resolution = DEFAULT_AUDIO_RESOLUTION
212 videoFile.fps = await getVideoFileFPS(videoPhysicalFile.path)
213 videoFile.resolution = (await getVideoFileResolution(videoPhysicalFile.path)).videoFileResolution
216 // Move physical file
217 const videoDir = CONFIG.STORAGE.VIDEOS_DIR
218 const destination = join(videoDir, video.getVideoFilename(videoFile))
219 await move(videoPhysicalFile.path, destination)
220 // This is important in case if there is another attempt in the retry process
221 videoPhysicalFile.filename = video.getVideoFilename(videoFile)
222 videoPhysicalFile.path = destination
224 // Process thumbnail or create it from the video
225 const thumbnailField = req.files['thumbnailfile']
226 const thumbnailModel = thumbnailField
227 ? await createVideoMiniatureFromExisting(thumbnailField[0].path, video, ThumbnailType.MINIATURE, false)
228 : await generateVideoMiniature(video, videoFile, ThumbnailType.MINIATURE)
230 // Process preview or create it from the video
231 const previewField = req.files['previewfile']
232 const previewModel = previewField
233 ? await createVideoMiniatureFromExisting(previewField[0].path, video, ThumbnailType.PREVIEW, false)
234 : await generateVideoMiniature(video, videoFile, ThumbnailType.PREVIEW)
236 // Create the torrent file
237 await video.createTorrentAndSetInfoHash(videoFile)
239 const { videoCreated } = await sequelizeTypescript.transaction(async t => {
240 const sequelizeOptions = { transaction: t }
242 const videoCreated = await video.save(sequelizeOptions) as MVideoFullLight
244 await videoCreated.addAndSaveThumbnail(thumbnailModel, t)
245 await videoCreated.addAndSaveThumbnail(previewModel, t)
247 // Do not forget to add video channel information to the created video
248 videoCreated.VideoChannel = res.locals.videoChannel
250 videoFile.videoId = video.id
251 await videoFile.save(sequelizeOptions)
253 video.VideoFiles = [ videoFile ]
256 if (videoInfo.tags !== undefined) {
257 const tagInstances = await TagModel.findOrCreateTags(videoInfo.tags, t)
259 await video.$set('Tags', tagInstances, sequelizeOptions)
260 video.Tags = tagInstances
263 // Schedule an update in the future?
264 if (videoInfo.scheduleUpdate) {
265 await ScheduleVideoUpdateModel.create({
267 updateAt: videoInfo.scheduleUpdate.updateAt,
268 privacy: videoInfo.scheduleUpdate.privacy || null
269 }, { transaction: t })
272 await autoBlacklistVideoIfNeeded({
274 user: res.locals.oauth.token.User,
279 await federateVideoIfNeeded(video, true, t)
281 auditLogger.create(getAuditIdFromRes(res), new VideoAuditView(videoCreated.toFormattedDetailsJSON()))
282 logger.info('Video with name %s and uuid %s created.', videoInfo.name, videoCreated.uuid)
284 return { videoCreated }
287 Notifier.Instance.notifyOnNewVideoIfNeeded(videoCreated)
289 if (video.state === VideoState.TO_TRANSCODE) {
290 // Put uuid because we don't have id auto incremented for now
291 let dataInput: VideoTranscodingPayload
293 if (videoFile.isAudio()) {
295 type: 'merge-audio' as 'merge-audio',
296 resolution: DEFAULT_AUDIO_RESOLUTION,
297 videoUUID: videoCreated.uuid,
302 type: 'optimize' as 'optimize',
303 videoUUID: videoCreated.uuid,
308 await JobQueue.Instance.createJob({ type: 'video-transcoding', payload: dataInput })
311 Hooks.runAction('action:api.video.uploaded', { video: videoCreated })
316 uuid: videoCreated.uuid
321 async function updateVideo (req: express.Request, res: express.Response) {
322 const videoInstance = res.locals.videoAll
323 const videoFieldsSave = videoInstance.toJSON()
324 const oldVideoAuditView = new VideoAuditView(videoInstance.toFormattedDetailsJSON())
325 const videoInfoToUpdate: VideoUpdate = req.body
327 const wasPrivateVideo = videoInstance.privacy === VideoPrivacy.PRIVATE
328 const wasNotPrivateVideo = videoInstance.privacy !== VideoPrivacy.PRIVATE
329 const wasUnlistedVideo = videoInstance.privacy === VideoPrivacy.UNLISTED
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, false)
336 const previewModel = req.files && req.files['previewfile']
337 ? await createVideoMiniatureFromExisting(req.files['previewfile'][0].path, videoInstance, ThumbnailType.PREVIEW, false)
341 const videoInstanceUpdated = await sequelizeTypescript.transaction(async t => {
342 const sequelizeOptions = { transaction: t }
343 const oldVideoChannel = videoInstance.VideoChannel
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
356 if (videoInfoToUpdate.originallyPublishedAt !== undefined && videoInfoToUpdate.originallyPublishedAt !== null) {
357 videoInstance.originallyPublishedAt = new Date(videoInfoToUpdate.originallyPublishedAt)
360 if (videoInfoToUpdate.privacy !== undefined) {
361 const newPrivacy = parseInt(videoInfoToUpdate.privacy.toString(), 10)
362 videoInstance.privacy = newPrivacy
364 // The video was private, and is not anymore -> publish it
365 if (wasPrivateVideo === true && newPrivacy !== VideoPrivacy.PRIVATE) {
366 videoInstance.publishedAt = new Date()
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 })
375 const videoInstanceUpdated = await videoInstance.save(sequelizeOptions) as MVideoFullLight
377 if (thumbnailModel) await videoInstanceUpdated.addAndSaveThumbnail(thumbnailModel, t)
378 if (previewModel) await videoInstanceUpdated.addAndSaveThumbnail(previewModel, t)
380 // Video tags update?
381 if (videoInfoToUpdate.tags !== undefined) {
382 const tagInstances = await TagModel.findOrCreateTags(videoInfoToUpdate.tags, t)
384 await videoInstanceUpdated.$set('Tags', tagInstances, sequelizeOptions)
385 videoInstanceUpdated.Tags = tagInstances
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
393 if (wasPrivateVideo === false) await changeVideoChannelShare(videoInstanceUpdated, oldVideoChannel, t)
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)
407 await autoBlacklistVideoIfNeeded({
408 video: videoInstanceUpdated,
409 user: res.locals.oauth.token.User,
415 const isNewVideo = wasPrivateVideo && videoInstanceUpdated.privacy !== VideoPrivacy.PRIVATE
416 await federateVideoIfNeeded(videoInstanceUpdated, isNewVideo, t)
419 getAuditIdFromRes(res),
420 new VideoAuditView(videoInstanceUpdated.toFormattedDetailsJSON()),
423 logger.info('Video with name %s and uuid %s updated.', videoInstance.name, videoInstance.uuid)
425 return videoInstanceUpdated
428 if (wasUnlistedVideo || wasPrivateVideo) {
429 Notifier.Instance.notifyOnNewVideoIfNeeded(videoInstanceUpdated)
432 Hooks.runAction('action:api.video.updated', { video: videoInstanceUpdated })
434 // Force fields we want to update
435 // If the transaction is retried, sequelize will think the object has not changed
436 // So it will skip the SQL request, even if the last one was ROLLBACKed!
437 resetSequelizeInstance(videoInstance, videoFieldsSave)
442 return res.type('json').status(204).end()
445 async function getVideo (req: express.Request, res: express.Response) {
446 // We need more attributes
447 const userId: number = res.locals.oauth ? res.locals.oauth.token.User.id : null
449 const video = await Hooks.wrapPromiseFun(
450 VideoModel.loadForGetAPI,
451 { id: res.locals.onlyVideoWithRights.id, userId },
452 'filter:api.video.get.result'
455 if (video.isOutdated()) {
456 JobQueue.Instance.createJob({ type: 'activitypub-refresher', payload: { type: 'video', url: video.url } })
457 .catch(err => logger.error('Cannot create AP refresher job for video %s.', video.url, { err }))
460 return res.json(video.toFormattedDetailsJSON())
463 async function viewVideo (req: express.Request, res: express.Response) {
464 const videoInstance = res.locals.videoAll
467 const exists = await Redis.Instance.doesVideoIPViewExist(ip, videoInstance.uuid)
469 logger.debug('View for ip %s and video %s already exists.', ip, videoInstance.uuid)
470 return res.status(204).end()
474 Redis.Instance.addVideoView(videoInstance.id),
475 Redis.Instance.setIPVideoView(ip, videoInstance.uuid)
478 const serverActor = await getServerActor()
479 await sendView(serverActor, videoInstance, undefined)
481 Hooks.runAction('action:api.video.viewed', { video: videoInstance, ip })
483 return res.status(204).end()
486 async function getVideoDescription (req: express.Request, res: express.Response) {
487 const videoInstance = res.locals.videoAll
490 if (videoInstance.isOwned()) {
491 description = videoInstance.description
493 description = await fetchRemoteVideoDescription(videoInstance)
496 return res.json({ description })
499 async function listVideos (req: express.Request, res: express.Response) {
500 const apiOptions = await Hooks.wrapObject({
501 start: req.query.start,
502 count: req.query.count,
503 sort: req.query.sort,
504 includeLocalVideos: true,
505 categoryOneOf: req.query.categoryOneOf,
506 licenceOneOf: req.query.licenceOneOf,
507 languageOneOf: req.query.languageOneOf,
508 tagsOneOf: req.query.tagsOneOf,
509 tagsAllOf: req.query.tagsAllOf,
510 nsfw: buildNSFWFilter(res, req.query.nsfw),
511 filter: req.query.filter as VideoFilter,
513 user: res.locals.oauth ? res.locals.oauth.token.User : undefined
514 }, 'filter:api.videos.list.params')
516 const resultList = await Hooks.wrapPromiseFun(
517 VideoModel.listForApi,
519 'filter:api.videos.list.result'
522 return res.json(getFormattedObjects(resultList.data, resultList.total))
525 async function removeVideo (req: express.Request, res: express.Response) {
526 const videoInstance = res.locals.videoAll
528 await sequelizeTypescript.transaction(async t => {
529 await videoInstance.destroy({ transaction: t })
532 auditLogger.delete(getAuditIdFromRes(res), new VideoAuditView(videoInstance.toFormattedDetailsJSON()))
533 logger.info('Video with name %s and uuid %s deleted.', videoInstance.name, videoInstance.uuid)
535 Hooks.runAction('action:api.video.deleted', { video: videoInstance })
537 return res.type('json').status(204).end()