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'
9 import { MIMETYPES, VIDEO_CATEGORIES, VIDEO_LANGUAGES, VIDEO_LICENCES, VIDEO_PRIVACIES } from '../../../initializers/constants'
11 changeVideoChannelShare,
12 federateVideoIfNeeded,
13 fetchRemoteVideoDescription,
14 getVideoActivityPubUrl
15 } from '../../../lib/activitypub'
16 import { JobQueue } from '../../../lib/job-queue'
17 import { Redis } from '../../../lib/redis'
20 asyncRetryTransactionMiddleware,
22 checkVideoFollowConstraints,
23 commonVideosFiltersValidator,
29 videosCustomGetValidator,
31 videosRemoveValidator,
34 } from '../../../middlewares'
35 import { TagModel } from '../../../models/video/tag'
36 import { VideoModel } from '../../../models/video/video'
37 import { VideoFileModel } from '../../../models/video/video-file'
38 import { abuseVideoRouter } from './abuse'
39 import { blacklistRouter } from './blacklist'
40 import { videoCommentRouter } from './comment'
41 import { rateVideoRouter } from './rate'
42 import { ownershipVideoRouter } from './ownership'
43 import { VideoFilter } from '../../../../shared/models/videos/video-query.type'
44 import { buildNSFWFilter, createReqFiles } from '../../../helpers/express-utils'
45 import { ScheduleVideoUpdateModel } from '../../../models/video/schedule-video-update'
46 import { videoCaptionsRouter } from './captions'
47 import { videoImportsRouter } from './import'
48 import { resetSequelizeInstance } from '../../../helpers/database-utils'
49 import { move } from 'fs-extra'
50 import { watchingRouter } from './watching'
51 import { Notifier } from '../../../lib/notifier'
52 import { sendView } from '../../../lib/activitypub/send/send-view'
53 import { CONFIG } from '../../../initializers/config'
54 import { sequelizeTypescript } from '../../../initializers/database'
55 import { createVideoThumbnailFromExisting, generateVideoThumbnail } from '../../../lib/thumbnail'
56 import { ThumbnailType } from '../../../../shared/models/videos/thumbnail.type'
58 const auditLogger = auditLoggerFactory('videos')
59 const videosRouter = express.Router()
61 const reqVideoFileAdd = createReqFiles(
62 [ 'videofile', 'thumbnailfile', 'previewfile' ],
63 Object.assign({}, MIMETYPES.VIDEO.MIMETYPE_EXT, MIMETYPES.IMAGE.MIMETYPE_EXT),
65 videofile: CONFIG.STORAGE.TMP_DIR,
66 thumbnailfile: CONFIG.STORAGE.TMP_DIR,
67 previewfile: CONFIG.STORAGE.TMP_DIR
70 const reqVideoFileUpdate = createReqFiles(
71 [ 'thumbnailfile', 'previewfile' ],
72 MIMETYPES.IMAGE.MIMETYPE_EXT,
74 thumbnailfile: CONFIG.STORAGE.TMP_DIR,
75 previewfile: CONFIG.STORAGE.TMP_DIR
79 videosRouter.use('/', abuseVideoRouter)
80 videosRouter.use('/', blacklistRouter)
81 videosRouter.use('/', rateVideoRouter)
82 videosRouter.use('/', videoCommentRouter)
83 videosRouter.use('/', videoCaptionsRouter)
84 videosRouter.use('/', videoImportsRouter)
85 videosRouter.use('/', ownershipVideoRouter)
86 videosRouter.use('/', watchingRouter)
88 videosRouter.get('/categories', listVideoCategories)
89 videosRouter.get('/licences', listVideoLicences)
90 videosRouter.get('/languages', listVideoLanguages)
91 videosRouter.get('/privacies', listVideoPrivacies)
99 commonVideosFiltersValidator,
100 asyncMiddleware(listVideos)
102 videosRouter.put('/:id',
105 asyncMiddleware(videosUpdateValidator),
106 asyncRetryTransactionMiddleware(updateVideo)
108 videosRouter.post('/upload',
111 asyncMiddleware(videosAddValidator),
112 asyncRetryTransactionMiddleware(addVideo)
115 videosRouter.get('/:id/description',
116 asyncMiddleware(videosGetValidator),
117 asyncMiddleware(getVideoDescription)
119 videosRouter.get('/:id',
120 optionalAuthenticate,
121 asyncMiddleware(videosCustomGetValidator('only-video-with-rights')),
122 asyncMiddleware(checkVideoFollowConstraints),
123 asyncMiddleware(getVideo)
125 videosRouter.post('/:id/views',
126 asyncMiddleware(videosGetValidator),
127 asyncMiddleware(viewVideo)
130 videosRouter.delete('/:id',
132 asyncMiddleware(videosRemoveValidator),
133 asyncRetryTransactionMiddleware(removeVideo)
136 // ---------------------------------------------------------------------------
142 // ---------------------------------------------------------------------------
144 function listVideoCategories (req: express.Request, res: express.Response) {
145 res.json(VIDEO_CATEGORIES)
148 function listVideoLicences (req: express.Request, res: express.Response) {
149 res.json(VIDEO_LICENCES)
152 function listVideoLanguages (req: express.Request, res: express.Response) {
153 res.json(VIDEO_LANGUAGES)
156 function listVideoPrivacies (req: express.Request, res: express.Response) {
157 res.json(VIDEO_PRIVACIES)
160 async function addVideo (req: express.Request, res: express.Response) {
161 // Processing the video could be long
162 // Set timeout to 10 minutes
163 req.setTimeout(1000 * 60 * 10, () => {
164 logger.error('Upload video has timed out.')
165 return res.sendStatus(408)
168 const videoPhysicalFile = req.files['videofile'][0]
169 const videoInfo: VideoCreate = req.body
171 // Prepare data so we don't block the transaction
173 name: videoInfo.name,
175 category: videoInfo.category,
176 licence: videoInfo.licence,
177 language: videoInfo.language,
178 commentsEnabled: videoInfo.commentsEnabled || false,
179 downloadEnabled: videoInfo.downloadEnabled || true,
180 waitTranscoding: videoInfo.waitTranscoding || false,
181 state: CONFIG.TRANSCODING.ENABLED ? VideoState.TO_TRANSCODE : VideoState.PUBLISHED,
182 nsfw: videoInfo.nsfw || false,
183 description: videoInfo.description,
184 support: videoInfo.support,
185 privacy: videoInfo.privacy,
186 duration: videoPhysicalFile['duration'], // duration was added by a previous middleware
187 channelId: res.locals.videoChannel.id,
188 originallyPublishedAt: videoInfo.originallyPublishedAt
191 const video = new VideoModel(videoData)
192 video.url = getVideoActivityPubUrl(video) // We use the UUID, so set the URL after building the object
194 // Build the file object
195 const { videoFileResolution } = await getVideoFileResolution(videoPhysicalFile.path)
196 const fps = await getVideoFileFPS(videoPhysicalFile.path)
198 const videoFileData = {
199 extname: extname(videoPhysicalFile.filename),
200 resolution: videoFileResolution,
201 size: videoPhysicalFile.size,
204 const videoFile = new VideoFileModel(videoFileData)
206 // Move physical file
207 const videoDir = CONFIG.STORAGE.VIDEOS_DIR
208 const destination = join(videoDir, video.getVideoFilename(videoFile))
209 await move(videoPhysicalFile.path, destination)
210 // This is important in case if there is another attempt in the retry process
211 videoPhysicalFile.filename = video.getVideoFilename(videoFile)
212 videoPhysicalFile.path = destination
214 // Process thumbnail or create it from the video
215 const thumbnailField = req.files['thumbnailfile']
216 const thumbnailModel = thumbnailField
217 ? await createVideoThumbnailFromExisting(thumbnailField[0].path, video, ThumbnailType.THUMBNAIL)
218 : await generateVideoThumbnail(video, videoFile, ThumbnailType.THUMBNAIL)
220 // Process preview or create it from the video
221 const previewField = req.files['previewfile']
222 const previewModel = previewField
223 ? await createVideoThumbnailFromExisting(previewField[0].path, video, ThumbnailType.PREVIEW)
224 : await generateVideoThumbnail(video, videoFile, ThumbnailType.PREVIEW)
226 // Create the torrent file
227 await video.createTorrentAndSetInfoHash(videoFile)
229 const { videoCreated, videoWasAutoBlacklisted } = await sequelizeTypescript.transaction(async t => {
230 const sequelizeOptions = { transaction: t }
232 const videoCreated = await video.save(sequelizeOptions)
234 thumbnailModel.videoId = videoCreated.id
235 previewModel.videoId = videoCreated.id
237 videoCreated.addThumbnail(await thumbnailModel.save({ transaction: t }))
238 videoCreated.addThumbnail(await previewModel.save({ transaction: t }))
240 // Do not forget to add video channel information to the created video
241 videoCreated.VideoChannel = res.locals.videoChannel
243 videoFile.videoId = video.id
244 await videoFile.save(sequelizeOptions)
246 video.VideoFiles = [ videoFile ]
249 if (videoInfo.tags !== undefined) {
250 const tagInstances = await TagModel.findOrCreateTags(videoInfo.tags, t)
252 await video.$set('Tags', tagInstances, sequelizeOptions)
253 video.Tags = tagInstances
256 // Schedule an update in the future?
257 if (videoInfo.scheduleUpdate) {
258 await ScheduleVideoUpdateModel.create({
260 updateAt: videoInfo.scheduleUpdate.updateAt,
261 privacy: videoInfo.scheduleUpdate.privacy || null
262 }, { transaction: t })
265 const videoWasAutoBlacklisted = await autoBlacklistVideoIfNeeded(video, res.locals.oauth.token.User, t)
267 if (!videoWasAutoBlacklisted) {
268 await federateVideoIfNeeded(video, true, t)
271 auditLogger.create(getAuditIdFromRes(res), new VideoAuditView(videoCreated.toFormattedDetailsJSON()))
272 logger.info('Video with name %s and uuid %s created.', videoInfo.name, videoCreated.uuid)
274 return { videoCreated, videoWasAutoBlacklisted }
277 if (videoWasAutoBlacklisted) {
278 Notifier.Instance.notifyOnVideoAutoBlacklist(videoCreated)
280 Notifier.Instance.notifyOnNewVideo(videoCreated)
283 if (video.state === VideoState.TO_TRANSCODE) {
284 // Put uuid because we don't have id auto incremented for now
286 videoUUID: videoCreated.uuid,
290 await JobQueue.Instance.createJob({ type: 'video-transcoding', payload: dataInput })
296 uuid: videoCreated.uuid
301 async function updateVideo (req: express.Request, res: express.Response) {
302 const videoInstance = res.locals.video
303 const videoFieldsSave = videoInstance.toJSON()
304 const oldVideoAuditView = new VideoAuditView(videoInstance.toFormattedDetailsJSON())
305 const videoInfoToUpdate: VideoUpdate = req.body
306 const wasPrivateVideo = videoInstance.privacy === VideoPrivacy.PRIVATE
307 const wasUnlistedVideo = videoInstance.privacy === VideoPrivacy.UNLISTED
309 // Process thumbnail or create it from the video
310 const thumbnailModel = req.files && req.files['thumbnailfile']
311 ? await createVideoThumbnailFromExisting(req.files['thumbnailfile'][0].path, videoInstance, ThumbnailType.THUMBNAIL)
314 const previewModel = req.files && req.files['previewfile']
315 ? await createVideoThumbnailFromExisting(req.files['previewfile'][0].path, videoInstance, ThumbnailType.PREVIEW)
319 const videoInstanceUpdated = await sequelizeTypescript.transaction(async t => {
320 const sequelizeOptions = { transaction: t }
321 const oldVideoChannel = videoInstance.VideoChannel
323 if (videoInfoToUpdate.name !== undefined) videoInstance.set('name', videoInfoToUpdate.name)
324 if (videoInfoToUpdate.category !== undefined) videoInstance.set('category', videoInfoToUpdate.category)
325 if (videoInfoToUpdate.licence !== undefined) videoInstance.set('licence', videoInfoToUpdate.licence)
326 if (videoInfoToUpdate.language !== undefined) videoInstance.set('language', videoInfoToUpdate.language)
327 if (videoInfoToUpdate.nsfw !== undefined) videoInstance.set('nsfw', videoInfoToUpdate.nsfw)
328 if (videoInfoToUpdate.waitTranscoding !== undefined) videoInstance.set('waitTranscoding', videoInfoToUpdate.waitTranscoding)
329 if (videoInfoToUpdate.support !== undefined) videoInstance.set('support', videoInfoToUpdate.support)
330 if (videoInfoToUpdate.description !== undefined) videoInstance.set('description', videoInfoToUpdate.description)
331 if (videoInfoToUpdate.commentsEnabled !== undefined) videoInstance.set('commentsEnabled', videoInfoToUpdate.commentsEnabled)
332 if (videoInfoToUpdate.downloadEnabled !== undefined) videoInstance.set('downloadEnabled', videoInfoToUpdate.downloadEnabled)
334 if (videoInfoToUpdate.originallyPublishedAt !== undefined && videoInfoToUpdate.originallyPublishedAt !== null) {
335 videoInstance.set('originallyPublishedAt', videoInfoToUpdate.originallyPublishedAt)
338 if (videoInfoToUpdate.privacy !== undefined) {
339 const newPrivacy = parseInt(videoInfoToUpdate.privacy.toString(), 10)
340 videoInstance.set('privacy', newPrivacy)
342 if (wasPrivateVideo === true && newPrivacy !== VideoPrivacy.PRIVATE) {
343 videoInstance.set('publishedAt', new Date())
347 const videoInstanceUpdated = await videoInstance.save(sequelizeOptions)
349 if (thumbnailModel) {
350 thumbnailModel.videoId = videoInstanceUpdated.id
351 videoInstanceUpdated.addThumbnail(await thumbnailModel.save({ transaction: t }))
354 previewModel.videoId = videoInstanceUpdated.id
355 videoInstanceUpdated.addThumbnail(await previewModel.save({ transaction: t }))
358 // Video tags update?
359 if (videoInfoToUpdate.tags !== undefined) {
360 const tagInstances = await TagModel.findOrCreateTags(videoInfoToUpdate.tags, t)
362 await videoInstanceUpdated.$set('Tags', tagInstances, sequelizeOptions)
363 videoInstanceUpdated.Tags = tagInstances
366 // Video channel update?
367 if (res.locals.videoChannel && videoInstanceUpdated.channelId !== res.locals.videoChannel.id) {
368 await videoInstanceUpdated.$set('VideoChannel', res.locals.videoChannel, { transaction: t })
369 videoInstanceUpdated.VideoChannel = res.locals.videoChannel
371 if (wasPrivateVideo === false) await changeVideoChannelShare(videoInstanceUpdated, oldVideoChannel, t)
374 // Schedule an update in the future?
375 if (videoInfoToUpdate.scheduleUpdate) {
376 await ScheduleVideoUpdateModel.upsert({
377 videoId: videoInstanceUpdated.id,
378 updateAt: videoInfoToUpdate.scheduleUpdate.updateAt,
379 privacy: videoInfoToUpdate.scheduleUpdate.privacy || null
380 }, { transaction: t })
381 } else if (videoInfoToUpdate.scheduleUpdate === null) {
382 await ScheduleVideoUpdateModel.deleteByVideoId(videoInstanceUpdated.id, t)
385 const isNewVideo = wasPrivateVideo && videoInstanceUpdated.privacy !== VideoPrivacy.PRIVATE
387 // Don't send update if the video was unfederated
388 if (!videoInstanceUpdated.VideoBlacklist || videoInstanceUpdated.VideoBlacklist.unfederated === false) {
389 await federateVideoIfNeeded(videoInstanceUpdated, isNewVideo, t)
393 getAuditIdFromRes(res),
394 new VideoAuditView(videoInstanceUpdated.toFormattedDetailsJSON()),
397 logger.info('Video with name %s and uuid %s updated.', videoInstance.name, videoInstance.uuid)
399 return videoInstanceUpdated
402 if (wasUnlistedVideo || wasPrivateVideo) {
403 Notifier.Instance.notifyOnNewVideo(videoInstanceUpdated)
406 // Force fields we want to update
407 // If the transaction is retried, sequelize will think the object has not changed
408 // So it will skip the SQL request, even if the last one was ROLLBACKed!
409 resetSequelizeInstance(videoInstance, videoFieldsSave)
414 return res.type('json').status(204).end()
417 async function getVideo (req: express.Request, res: express.Response) {
418 // We need more attributes
419 const userId: number = res.locals.oauth ? res.locals.oauth.token.User.id : null
420 const video = await VideoModel.loadForGetAPI(res.locals.video.id, undefined, userId)
422 if (video.isOutdated()) {
423 JobQueue.Instance.createJob({ type: 'activitypub-refresher', payload: { type: 'video', url: video.url } })
424 .catch(err => logger.error('Cannot create AP refresher job for video %s.', video.url, { err }))
427 return res.json(video.toFormattedDetailsJSON())
430 async function viewVideo (req: express.Request, res: express.Response) {
431 const videoInstance = res.locals.video
434 const exists = await Redis.Instance.doesVideoIPViewExist(ip, videoInstance.uuid)
436 logger.debug('View for ip %s and video %s already exists.', ip, videoInstance.uuid)
437 return res.status(204).end()
441 Redis.Instance.addVideoView(videoInstance.id),
442 Redis.Instance.setIPVideoView(ip, videoInstance.uuid)
445 const serverActor = await getServerActor()
446 await sendView(serverActor, videoInstance, undefined)
448 return res.status(204).end()
451 async function getVideoDescription (req: express.Request, res: express.Response) {
452 const videoInstance = res.locals.video
455 if (videoInstance.isOwned()) {
456 description = videoInstance.description
458 description = await fetchRemoteVideoDescription(videoInstance)
461 return res.json({ description })
464 async function listVideos (req: express.Request, res: express.Response) {
465 const resultList = await VideoModel.listForApi({
466 start: req.query.start,
467 count: req.query.count,
468 sort: req.query.sort,
469 includeLocalVideos: true,
470 categoryOneOf: req.query.categoryOneOf,
471 licenceOneOf: req.query.licenceOneOf,
472 languageOneOf: req.query.languageOneOf,
473 tagsOneOf: req.query.tagsOneOf,
474 tagsAllOf: req.query.tagsAllOf,
475 nsfw: buildNSFWFilter(res, req.query.nsfw),
476 filter: req.query.filter as VideoFilter,
478 user: res.locals.oauth ? res.locals.oauth.token.User : undefined
481 return res.json(getFormattedObjects(resultList.data, resultList.total))
484 async function removeVideo (req: express.Request, res: express.Response) {
485 const videoInstance = res.locals.video
487 await sequelizeTypescript.transaction(async t => {
488 await videoInstance.destroy({ transaction: t })
491 auditLogger.delete(getAuditIdFromRes(res), new VideoAuditView(videoInstance.toFormattedDetailsJSON()))
492 logger.info('Video with name %s and uuid %s deleted.', videoInstance.name, videoInstance.uuid)
494 return res.type('json').status(204).end()