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'
67 const auditLogger = auditLoggerFactory('videos')
68 const videosRouter = express.Router()
70 const reqVideoFileAdd = createReqFiles(
71 [ 'videofile', 'thumbnailfile', 'previewfile' ],
72 Object.assign({}, MIMETYPES.VIDEO.MIMETYPE_EXT, MIMETYPES.IMAGE.MIMETYPE_EXT),
74 videofile: CONFIG.STORAGE.TMP_DIR,
75 thumbnailfile: CONFIG.STORAGE.TMP_DIR,
76 previewfile: CONFIG.STORAGE.TMP_DIR
79 const reqVideoFileUpdate = createReqFiles(
80 [ 'thumbnailfile', 'previewfile' ],
81 MIMETYPES.IMAGE.MIMETYPE_EXT,
83 thumbnailfile: CONFIG.STORAGE.TMP_DIR,
84 previewfile: CONFIG.STORAGE.TMP_DIR
88 videosRouter.use('/', abuseVideoRouter)
89 videosRouter.use('/', blacklistRouter)
90 videosRouter.use('/', rateVideoRouter)
91 videosRouter.use('/', videoCommentRouter)
92 videosRouter.use('/', videoCaptionsRouter)
93 videosRouter.use('/', videoImportsRouter)
94 videosRouter.use('/', ownershipVideoRouter)
95 videosRouter.use('/', watchingRouter)
97 videosRouter.get('/categories', listVideoCategories)
98 videosRouter.get('/licences', listVideoLicences)
99 videosRouter.get('/languages', listVideoLanguages)
100 videosRouter.get('/privacies', listVideoPrivacies)
102 videosRouter.get('/',
106 setDefaultPagination,
107 optionalAuthenticate,
108 commonVideosFiltersValidator,
109 asyncMiddleware(listVideos)
111 videosRouter.put('/:id',
114 asyncMiddleware(videosUpdateValidator),
115 asyncRetryTransactionMiddleware(updateVideo)
117 videosRouter.post('/upload',
120 asyncMiddleware(videosAddValidator),
121 asyncRetryTransactionMiddleware(addVideo)
124 videosRouter.get('/:id/description',
125 asyncMiddleware(videosGetValidator),
126 asyncMiddleware(getVideoDescription)
128 videosRouter.get('/:id',
129 optionalAuthenticate,
130 asyncMiddleware(videosCustomGetValidator('only-video-with-rights')),
131 asyncMiddleware(checkVideoFollowConstraints),
132 asyncMiddleware(getVideo)
134 videosRouter.post('/:id/views',
135 asyncMiddleware(videosGetValidator),
136 asyncMiddleware(viewVideo)
139 videosRouter.delete('/:id',
141 asyncMiddleware(videosRemoveValidator),
142 asyncRetryTransactionMiddleware(removeVideo)
145 // ---------------------------------------------------------------------------
151 // ---------------------------------------------------------------------------
153 function listVideoCategories (req: express.Request, res: express.Response) {
154 res.json(VIDEO_CATEGORIES)
157 function listVideoLicences (req: express.Request, res: express.Response) {
158 res.json(VIDEO_LICENCES)
161 function listVideoLanguages (req: express.Request, res: express.Response) {
162 res.json(VIDEO_LANGUAGES)
165 function listVideoPrivacies (req: express.Request, res: express.Response) {
166 res.json(VIDEO_PRIVACIES)
169 async function addVideo (req: express.Request, res: express.Response) {
170 // Processing the video could be long
171 // Set timeout to 10 minutes
172 req.setTimeout(1000 * 60 * 10, () => {
173 logger.error('Upload video has timed out.')
174 return res.sendStatus(408)
177 const videoPhysicalFile = req.files['videofile'][0]
178 const videoInfo: VideoCreate = req.body
180 // Prepare data so we don't block the transaction
182 name: videoInfo.name,
184 category: videoInfo.category,
185 licence: videoInfo.licence,
186 language: videoInfo.language,
187 commentsEnabled: videoInfo.commentsEnabled || false,
188 downloadEnabled: videoInfo.downloadEnabled || true,
189 waitTranscoding: videoInfo.waitTranscoding || false,
190 state: CONFIG.TRANSCODING.ENABLED ? VideoState.TO_TRANSCODE : VideoState.PUBLISHED,
191 nsfw: videoInfo.nsfw || false,
192 description: videoInfo.description,
193 support: videoInfo.support,
194 privacy: videoInfo.privacy || VideoPrivacy.PRIVATE,
195 duration: videoPhysicalFile['duration'], // duration was added by a previous middleware
196 channelId: res.locals.videoChannel.id,
197 originallyPublishedAt: videoInfo.originallyPublishedAt
200 const video = new VideoModel(videoData)
201 video.url = getVideoActivityPubUrl(video) // We use the UUID, so set the URL after building the object
203 const videoFile = new VideoFileModel({
204 extname: extname(videoPhysicalFile.filename),
205 size: videoPhysicalFile.size
208 if (videoFile.isAudio()) {
209 videoFile.resolution = DEFAULT_AUDIO_RESOLUTION
211 videoFile.fps = await getVideoFileFPS(videoPhysicalFile.path)
212 videoFile.resolution = (await getVideoFileResolution(videoPhysicalFile.path)).videoFileResolution
215 // Move physical file
216 const videoDir = CONFIG.STORAGE.VIDEOS_DIR
217 const destination = join(videoDir, video.getVideoFilename(videoFile))
218 await move(videoPhysicalFile.path, destination)
219 // This is important in case if there is another attempt in the retry process
220 videoPhysicalFile.filename = video.getVideoFilename(videoFile)
221 videoPhysicalFile.path = destination
223 // Process thumbnail or create it from the video
224 const thumbnailField = req.files['thumbnailfile']
225 const thumbnailModel = thumbnailField
226 ? await createVideoMiniatureFromExisting(thumbnailField[0].path, video, ThumbnailType.MINIATURE)
227 : await generateVideoMiniature(video, videoFile, ThumbnailType.MINIATURE)
229 // Process preview or create it from the video
230 const previewField = req.files['previewfile']
231 const previewModel = previewField
232 ? await createVideoMiniatureFromExisting(previewField[0].path, video, ThumbnailType.PREVIEW)
233 : await generateVideoMiniature(video, videoFile, ThumbnailType.PREVIEW)
235 // Create the torrent file
236 await video.createTorrentAndSetInfoHash(videoFile)
238 const { videoCreated } = await sequelizeTypescript.transaction(async t => {
239 const sequelizeOptions = { transaction: t }
241 const videoCreated = await video.save(sequelizeOptions)
243 await videoCreated.addAndSaveThumbnail(thumbnailModel, t)
244 await videoCreated.addAndSaveThumbnail(previewModel, t)
246 // Do not forget to add video channel information to the created video
247 videoCreated.VideoChannel = res.locals.videoChannel
249 videoFile.videoId = video.id
250 await videoFile.save(sequelizeOptions)
252 video.VideoFiles = [ videoFile ]
255 if (videoInfo.tags !== undefined) {
256 const tagInstances = await TagModel.findOrCreateTags(videoInfo.tags, t)
258 await video.$set('Tags', tagInstances, sequelizeOptions)
259 video.Tags = tagInstances
262 // Schedule an update in the future?
263 if (videoInfo.scheduleUpdate) {
264 await ScheduleVideoUpdateModel.create({
266 updateAt: videoInfo.scheduleUpdate.updateAt,
267 privacy: videoInfo.scheduleUpdate.privacy || null
268 }, { transaction: t })
271 await autoBlacklistVideoIfNeeded({
273 user: res.locals.oauth.token.User,
278 await federateVideoIfNeeded(video, true, t)
280 auditLogger.create(getAuditIdFromRes(res), new VideoAuditView(videoCreated.toFormattedDetailsJSON()))
281 logger.info('Video with name %s and uuid %s created.', videoInfo.name, videoCreated.uuid)
283 return { videoCreated }
286 Notifier.Instance.notifyOnNewVideoIfNeeded(videoCreated)
288 if (video.state === VideoState.TO_TRANSCODE) {
289 // Put uuid because we don't have id auto incremented for now
290 let dataInput: VideoTranscodingPayload
292 if (videoFile.isAudio()) {
294 type: 'merge-audio' as 'merge-audio',
295 resolution: DEFAULT_AUDIO_RESOLUTION,
296 videoUUID: videoCreated.uuid,
301 type: 'optimize' as 'optimize',
302 videoUUID: videoCreated.uuid,
307 await JobQueue.Instance.createJob({ type: 'video-transcoding', payload: dataInput })
310 Hooks.runAction('action:api.video.uploaded', { video: videoCreated })
315 uuid: videoCreated.uuid
320 async function updateVideo (req: express.Request, res: express.Response) {
321 const videoInstance = res.locals.video
322 const videoFieldsSave = videoInstance.toJSON()
323 const oldVideoAuditView = new VideoAuditView(videoInstance.toFormattedDetailsJSON())
324 const videoInfoToUpdate: VideoUpdate = req.body
326 const wasPrivateVideo = videoInstance.privacy === VideoPrivacy.PRIVATE
327 const wasNotPrivateVideo = videoInstance.privacy !== VideoPrivacy.PRIVATE
328 const wasUnlistedVideo = videoInstance.privacy === VideoPrivacy.UNLISTED
330 // Process thumbnail or create it from the video
331 const thumbnailModel = req.files && req.files['thumbnailfile']
332 ? await createVideoMiniatureFromExisting(req.files['thumbnailfile'][0].path, videoInstance, ThumbnailType.MINIATURE)
335 const previewModel = req.files && req.files['previewfile']
336 ? await createVideoMiniatureFromExisting(req.files['previewfile'][0].path, videoInstance, ThumbnailType.PREVIEW)
340 const videoInstanceUpdated = await sequelizeTypescript.transaction(async t => {
341 const sequelizeOptions = { transaction: t }
342 const oldVideoChannel = videoInstance.VideoChannel
344 if (videoInfoToUpdate.name !== undefined) videoInstance.name = videoInfoToUpdate.name
345 if (videoInfoToUpdate.category !== undefined) videoInstance.category = videoInfoToUpdate.category
346 if (videoInfoToUpdate.licence !== undefined) videoInstance.licence = videoInfoToUpdate.licence
347 if (videoInfoToUpdate.language !== undefined) videoInstance.language = videoInfoToUpdate.language
348 if (videoInfoToUpdate.nsfw !== undefined) videoInstance.nsfw = videoInfoToUpdate.nsfw
349 if (videoInfoToUpdate.waitTranscoding !== undefined) videoInstance.waitTranscoding = videoInfoToUpdate.waitTranscoding
350 if (videoInfoToUpdate.support !== undefined) videoInstance.support = videoInfoToUpdate.support
351 if (videoInfoToUpdate.description !== undefined) videoInstance.description = videoInfoToUpdate.description
352 if (videoInfoToUpdate.commentsEnabled !== undefined) videoInstance.commentsEnabled = videoInfoToUpdate.commentsEnabled
353 if (videoInfoToUpdate.downloadEnabled !== undefined) videoInstance.downloadEnabled = videoInfoToUpdate.downloadEnabled
355 if (videoInfoToUpdate.originallyPublishedAt !== undefined && videoInfoToUpdate.originallyPublishedAt !== null) {
356 videoInstance.originallyPublishedAt = new Date(videoInfoToUpdate.originallyPublishedAt)
359 if (videoInfoToUpdate.privacy !== undefined) {
360 const newPrivacy = parseInt(videoInfoToUpdate.privacy.toString(), 10)
361 videoInstance.privacy = newPrivacy
363 // The video was private, and is not anymore -> publish it
364 if (wasPrivateVideo === true && newPrivacy !== VideoPrivacy.PRIVATE) {
365 videoInstance.publishedAt = new Date()
368 // The video was not private, but now it is -> we need to unfederate it
369 if (wasNotPrivateVideo === true && newPrivacy === VideoPrivacy.PRIVATE) {
370 await VideoModel.sendDelete(videoInstance, { transaction: t })
374 const videoInstanceUpdated = await videoInstance.save(sequelizeOptions)
376 if (thumbnailModel) await videoInstanceUpdated.addAndSaveThumbnail(thumbnailModel, t)
377 if (previewModel) await videoInstanceUpdated.addAndSaveThumbnail(previewModel, t)
379 // Video tags update?
380 if (videoInfoToUpdate.tags !== undefined) {
381 const tagInstances = await TagModel.findOrCreateTags(videoInfoToUpdate.tags, t)
383 await videoInstanceUpdated.$set('Tags', tagInstances, sequelizeOptions)
384 videoInstanceUpdated.Tags = tagInstances
387 // Video channel update?
388 if (res.locals.videoChannel && videoInstanceUpdated.channelId !== res.locals.videoChannel.id) {
389 await videoInstanceUpdated.$set('VideoChannel', res.locals.videoChannel, { transaction: t })
390 videoInstanceUpdated.VideoChannel = res.locals.videoChannel
392 if (wasPrivateVideo === false) await changeVideoChannelShare(videoInstanceUpdated, oldVideoChannel, t)
395 // Schedule an update in the future?
396 if (videoInfoToUpdate.scheduleUpdate) {
397 await ScheduleVideoUpdateModel.upsert({
398 videoId: videoInstanceUpdated.id,
399 updateAt: videoInfoToUpdate.scheduleUpdate.updateAt,
400 privacy: videoInfoToUpdate.scheduleUpdate.privacy || null
401 }, { transaction: t })
402 } else if (videoInfoToUpdate.scheduleUpdate === null) {
403 await ScheduleVideoUpdateModel.deleteByVideoId(videoInstanceUpdated.id, t)
406 await autoBlacklistVideoIfNeeded({
407 video: videoInstanceUpdated,
408 user: res.locals.oauth.token.User,
414 const isNewVideo = wasPrivateVideo && videoInstanceUpdated.privacy !== VideoPrivacy.PRIVATE
415 await federateVideoIfNeeded(videoInstanceUpdated, isNewVideo, t)
418 getAuditIdFromRes(res),
419 new VideoAuditView(videoInstanceUpdated.toFormattedDetailsJSON()),
422 logger.info('Video with name %s and uuid %s updated.', videoInstance.name, videoInstance.uuid)
424 return videoInstanceUpdated
427 if (wasUnlistedVideo || wasPrivateVideo) {
428 Notifier.Instance.notifyOnNewVideoIfNeeded(videoInstanceUpdated)
431 Hooks.runAction('action:api.video.updated', { video: videoInstanceUpdated })
433 // Force fields we want to update
434 // If the transaction is retried, sequelize will think the object has not changed
435 // So it will skip the SQL request, even if the last one was ROLLBACKed!
436 resetSequelizeInstance(videoInstance, videoFieldsSave)
441 return res.type('json').status(204).end()
444 async function getVideo (req: express.Request, res: express.Response) {
445 // We need more attributes
446 const userId: number = res.locals.oauth ? res.locals.oauth.token.User.id : null
448 const video = await Hooks.wrapPromiseFun(
449 VideoModel.loadForGetAPI,
450 { id: res.locals.video.id, userId },
451 'filter:api.video.get.result'
454 if (video.isOutdated()) {
455 JobQueue.Instance.createJob({ type: 'activitypub-refresher', payload: { type: 'video', url: video.url } })
456 .catch(err => logger.error('Cannot create AP refresher job for video %s.', video.url, { err }))
459 return res.json(video.toFormattedDetailsJSON())
462 async function viewVideo (req: express.Request, res: express.Response) {
463 const videoInstance = res.locals.video
466 const exists = await Redis.Instance.doesVideoIPViewExist(ip, videoInstance.uuid)
468 logger.debug('View for ip %s and video %s already exists.', ip, videoInstance.uuid)
469 return res.status(204).end()
473 Redis.Instance.addVideoView(videoInstance.id),
474 Redis.Instance.setIPVideoView(ip, videoInstance.uuid)
477 const serverActor = await getServerActor()
478 await sendView(serverActor, videoInstance, undefined)
480 Hooks.runAction('action:api.video.viewed', { video: videoInstance, ip })
482 return res.status(204).end()
485 async function getVideoDescription (req: express.Request, res: express.Response) {
486 const videoInstance = res.locals.video
489 if (videoInstance.isOwned()) {
490 description = videoInstance.description
492 description = await fetchRemoteVideoDescription(videoInstance)
495 return res.json({ description })
498 async function listVideos (req: express.Request, res: express.Response) {
499 const apiOptions = await Hooks.wrapObject({
500 start: req.query.start,
501 count: req.query.count,
502 sort: req.query.sort,
503 includeLocalVideos: true,
504 categoryOneOf: req.query.categoryOneOf,
505 licenceOneOf: req.query.licenceOneOf,
506 languageOneOf: req.query.languageOneOf,
507 tagsOneOf: req.query.tagsOneOf,
508 tagsAllOf: req.query.tagsAllOf,
509 nsfw: buildNSFWFilter(res, req.query.nsfw),
510 filter: req.query.filter as VideoFilter,
512 user: res.locals.oauth ? res.locals.oauth.token.User : undefined
513 }, 'filter:api.videos.list.params')
515 const resultList = await Hooks.wrapPromiseFun(
516 VideoModel.listForApi,
518 'filter:api.videos.list.result'
521 return res.json(getFormattedObjects(resultList.data, resultList.total))
524 async function removeVideo (req: express.Request, res: express.Response) {
525 const videoInstance = res.locals.video
527 await sequelizeTypescript.transaction(async t => {
528 await videoInstance.destroy({ transaction: t })
531 auditLogger.delete(getAuditIdFromRes(res), new VideoAuditView(videoInstance.toFormattedDetailsJSON()))
532 logger.info('Video with name %s and uuid %s deleted.', videoInstance.name, videoInstance.uuid)
534 Hooks.runAction('action:api.video.deleted', { video: videoInstance })
536 return res.type('json').status(204).end()