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 { processImage } from '../../../helpers/image-utils'
6 import { logger } from '../../../helpers/logger'
7 import { auditLoggerFactory, getAuditIdFromRes, VideoAuditView } from '../../../helpers/audit-logger'
8 import { getFormattedObjects, getServerActor } from '../../../helpers/utils'
19 } from '../../../initializers'
21 changeVideoChannelShare,
22 federateVideoIfNeeded,
23 fetchRemoteVideoDescription,
24 getVideoActivityPubUrl
25 } from '../../../lib/activitypub'
26 import { sendCreateView } from '../../../lib/activitypub/send'
27 import { JobQueue } from '../../../lib/job-queue'
28 import { Redis } from '../../../lib/redis'
31 asyncRetryTransactionMiddleware,
33 checkVideoFollowConstraints,
34 commonVideosFiltersValidator,
41 videosRemoveValidator,
44 } from '../../../middlewares'
45 import { TagModel } from '../../../models/video/tag'
46 import { VideoModel } from '../../../models/video/video'
47 import { VideoFileModel } from '../../../models/video/video-file'
48 import { abuseVideoRouter } from './abuse'
49 import { blacklistRouter } from './blacklist'
50 import { videoCommentRouter } from './comment'
51 import { rateVideoRouter } from './rate'
52 import { ownershipVideoRouter } from './ownership'
53 import { VideoFilter } from '../../../../shared/models/videos/video-query.type'
54 import { buildNSFWFilter, createReqFiles } from '../../../helpers/express-utils'
55 import { ScheduleVideoUpdateModel } from '../../../models/video/schedule-video-update'
56 import { videoCaptionsRouter } from './captions'
57 import { videoImportsRouter } from './import'
58 import { resetSequelizeInstance } from '../../../helpers/database-utils'
59 import { move } from 'fs-extra'
60 import { watchingRouter } from './watching'
61 import { Notifier } from '../../../lib/notifier'
63 const auditLogger = auditLoggerFactory('videos')
64 const videosRouter = express.Router()
66 const reqVideoFileAdd = createReqFiles(
67 [ 'videofile', 'thumbnailfile', 'previewfile' ],
68 Object.assign({}, MIMETYPES.VIDEO.MIMETYPE_EXT, MIMETYPES.IMAGE.MIMETYPE_EXT),
70 videofile: CONFIG.STORAGE.TMP_DIR,
71 thumbnailfile: CONFIG.STORAGE.TMP_DIR,
72 previewfile: CONFIG.STORAGE.TMP_DIR
75 const reqVideoFileUpdate = createReqFiles(
76 [ 'thumbnailfile', 'previewfile' ],
77 MIMETYPES.IMAGE.MIMETYPE_EXT,
79 thumbnailfile: CONFIG.STORAGE.TMP_DIR,
80 previewfile: CONFIG.STORAGE.TMP_DIR
84 videosRouter.use('/', abuseVideoRouter)
85 videosRouter.use('/', blacklistRouter)
86 videosRouter.use('/', rateVideoRouter)
87 videosRouter.use('/', videoCommentRouter)
88 videosRouter.use('/', videoCaptionsRouter)
89 videosRouter.use('/', videoImportsRouter)
90 videosRouter.use('/', ownershipVideoRouter)
91 videosRouter.use('/', watchingRouter)
93 videosRouter.get('/categories', listVideoCategories)
94 videosRouter.get('/licences', listVideoLicences)
95 videosRouter.get('/languages', listVideoLanguages)
96 videosRouter.get('/privacies', listVideoPrivacies)
102 setDefaultPagination,
103 optionalAuthenticate,
104 commonVideosFiltersValidator,
105 asyncMiddleware(listVideos)
107 videosRouter.put('/:id',
110 asyncMiddleware(videosUpdateValidator),
111 asyncRetryTransactionMiddleware(updateVideo)
113 videosRouter.post('/upload',
116 asyncMiddleware(videosAddValidator),
117 asyncRetryTransactionMiddleware(addVideo)
120 videosRouter.get('/:id/description',
121 asyncMiddleware(videosGetValidator),
122 asyncMiddleware(getVideoDescription)
124 videosRouter.get('/:id',
125 optionalAuthenticate,
126 asyncMiddleware(videosGetValidator),
127 asyncMiddleware(checkVideoFollowConstraints),
130 videosRouter.post('/:id/views',
131 asyncMiddleware(videosGetValidator),
132 asyncMiddleware(viewVideo)
135 videosRouter.delete('/:id',
137 asyncMiddleware(videosRemoveValidator),
138 asyncRetryTransactionMiddleware(removeVideo)
141 // ---------------------------------------------------------------------------
147 // ---------------------------------------------------------------------------
149 function listVideoCategories (req: express.Request, res: express.Response) {
150 res.json(VIDEO_CATEGORIES)
153 function listVideoLicences (req: express.Request, res: express.Response) {
154 res.json(VIDEO_LICENCES)
157 function listVideoLanguages (req: express.Request, res: express.Response) {
158 res.json(VIDEO_LANGUAGES)
161 function listVideoPrivacies (req: express.Request, res: express.Response) {
162 res.json(VIDEO_PRIVACIES)
165 async function addVideo (req: express.Request, res: express.Response) {
166 // Processing the video could be long
167 // Set timeout to 10 minutes
168 req.setTimeout(1000 * 60 * 10, () => {
169 logger.error('Upload video has timed out.')
170 return res.sendStatus(408)
173 const videoPhysicalFile = req.files['videofile'][0]
174 const videoInfo: VideoCreate = req.body
176 // Prepare data so we don't block the transaction
178 name: videoInfo.name,
180 category: videoInfo.category,
181 licence: videoInfo.licence,
182 language: videoInfo.language,
183 commentsEnabled: videoInfo.commentsEnabled || false,
184 waitTranscoding: videoInfo.waitTranscoding || false,
185 state: CONFIG.TRANSCODING.ENABLED ? VideoState.TO_TRANSCODE : VideoState.PUBLISHED,
186 nsfw: videoInfo.nsfw || false,
187 description: videoInfo.description,
188 support: videoInfo.support,
189 privacy: videoInfo.privacy,
190 duration: videoPhysicalFile['duration'], // duration was added by a previous middleware
191 channelId: res.locals.videoChannel.id,
192 originallyPublishedAt: videoInfo.originallyPublishedAt
194 const video = new VideoModel(videoData)
195 video.url = getVideoActivityPubUrl(video) // We use the UUID, so set the URL after building the object
197 // Build the file object
198 const { videoFileResolution } = await getVideoFileResolution(videoPhysicalFile.path)
199 const fps = await getVideoFileFPS(videoPhysicalFile.path)
201 const videoFileData = {
202 extname: extname(videoPhysicalFile.filename),
203 resolution: videoFileResolution,
204 size: videoPhysicalFile.size,
207 const videoFile = new VideoFileModel(videoFileData)
209 // Move physical file
210 const videoDir = CONFIG.STORAGE.VIDEOS_DIR
211 const destination = join(videoDir, video.getVideoFilename(videoFile))
212 await move(videoPhysicalFile.path, destination)
213 // This is important in case if there is another attempt in the retry process
214 videoPhysicalFile.filename = video.getVideoFilename(videoFile)
215 videoPhysicalFile.path = destination
217 // Process thumbnail or create it from the video
218 const thumbnailField = req.files['thumbnailfile']
219 if (thumbnailField) {
220 const thumbnailPhysicalFile = thumbnailField[0]
221 await processImage(thumbnailPhysicalFile, join(CONFIG.STORAGE.THUMBNAILS_DIR, video.getThumbnailName()), THUMBNAILS_SIZE)
223 await video.createThumbnail(videoFile)
226 // Process preview or create it from the video
227 const previewField = req.files['previewfile']
229 const previewPhysicalFile = previewField[0]
230 await processImage(previewPhysicalFile, join(CONFIG.STORAGE.PREVIEWS_DIR, video.getPreviewName()), PREVIEWS_SIZE)
232 await video.createPreview(videoFile)
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)
242 // Do not forget to add video channel information to the created video
243 videoCreated.VideoChannel = res.locals.videoChannel
245 videoFile.videoId = video.id
246 await videoFile.save(sequelizeOptions)
248 video.VideoFiles = [ videoFile ]
251 if (videoInfo.tags !== undefined) {
252 const tagInstances = await TagModel.findOrCreateTags(videoInfo.tags, t)
254 await video.$set('Tags', tagInstances, sequelizeOptions)
255 video.Tags = tagInstances
258 // Schedule an update in the future?
259 if (videoInfo.scheduleUpdate) {
260 await ScheduleVideoUpdateModel.create({
262 updateAt: videoInfo.scheduleUpdate.updateAt,
263 privacy: videoInfo.scheduleUpdate.privacy || null
264 }, { transaction: t })
267 await federateVideoIfNeeded(video, true, t)
269 auditLogger.create(getAuditIdFromRes(res), new VideoAuditView(videoCreated.toFormattedDetailsJSON()))
270 logger.info('Video with name %s and uuid %s created.', videoInfo.name, videoCreated.uuid)
275 Notifier.Instance.notifyOnNewVideo(videoCreated)
277 if (video.state === VideoState.TO_TRANSCODE) {
278 // Put uuid because we don't have id auto incremented for now
280 videoUUID: videoCreated.uuid,
284 await JobQueue.Instance.createJob({ type: 'video-file', payload: dataInput })
290 uuid: videoCreated.uuid
295 async function updateVideo (req: express.Request, res: express.Response) {
296 const videoInstance: VideoModel = res.locals.video
297 const videoFieldsSave = videoInstance.toJSON()
298 const oldVideoAuditView = new VideoAuditView(videoInstance.toFormattedDetailsJSON())
299 const videoInfoToUpdate: VideoUpdate = req.body
300 const wasPrivateVideo = videoInstance.privacy === VideoPrivacy.PRIVATE
301 const wasUnlistedVideo = videoInstance.privacy === VideoPrivacy.UNLISTED
303 // Process thumbnail or create it from the video
304 if (req.files && req.files['thumbnailfile']) {
305 const thumbnailPhysicalFile = req.files['thumbnailfile'][0]
306 await processImage(thumbnailPhysicalFile, join(CONFIG.STORAGE.THUMBNAILS_DIR, videoInstance.getThumbnailName()), THUMBNAILS_SIZE)
309 // Process preview or create it from the video
310 if (req.files && req.files['previewfile']) {
311 const previewPhysicalFile = req.files['previewfile'][0]
312 await processImage(previewPhysicalFile, join(CONFIG.STORAGE.PREVIEWS_DIR, videoInstance.getPreviewName()), PREVIEWS_SIZE)
316 const videoInstanceUpdated = await sequelizeTypescript.transaction(async t => {
317 const sequelizeOptions = { transaction: t }
318 const oldVideoChannel = videoInstance.VideoChannel
320 if (videoInfoToUpdate.name !== undefined) videoInstance.set('name', videoInfoToUpdate.name)
321 if (videoInfoToUpdate.category !== undefined) videoInstance.set('category', videoInfoToUpdate.category)
322 if (videoInfoToUpdate.licence !== undefined) videoInstance.set('licence', videoInfoToUpdate.licence)
323 if (videoInfoToUpdate.language !== undefined) videoInstance.set('language', videoInfoToUpdate.language)
324 if (videoInfoToUpdate.nsfw !== undefined) videoInstance.set('nsfw', videoInfoToUpdate.nsfw)
325 if (videoInfoToUpdate.waitTranscoding !== undefined) videoInstance.set('waitTranscoding', videoInfoToUpdate.waitTranscoding)
326 if (videoInfoToUpdate.support !== undefined) videoInstance.set('support', videoInfoToUpdate.support)
327 if (videoInfoToUpdate.description !== undefined) videoInstance.set('description', videoInfoToUpdate.description)
328 if (videoInfoToUpdate.commentsEnabled !== undefined) videoInstance.set('commentsEnabled', videoInfoToUpdate.commentsEnabled)
329 if (videoInfoToUpdate.originallyPublishedAt !== undefined &&
330 videoInfoToUpdate.originallyPublishedAt !== null) {
331 videoInstance.set('originallyPublishedAt', videoInfoToUpdate.originallyPublishedAt)
334 if (videoInfoToUpdate.privacy !== undefined) {
335 const newPrivacy = parseInt(videoInfoToUpdate.privacy.toString(), 10)
336 videoInstance.set('privacy', newPrivacy)
338 if (wasPrivateVideo === true && newPrivacy !== VideoPrivacy.PRIVATE) {
339 videoInstance.set('publishedAt', new Date())
343 const videoInstanceUpdated = await videoInstance.save(sequelizeOptions)
345 // Video tags update?
346 if (videoInfoToUpdate.tags !== undefined) {
347 const tagInstances = await TagModel.findOrCreateTags(videoInfoToUpdate.tags, t)
349 await videoInstanceUpdated.$set('Tags', tagInstances, sequelizeOptions)
350 videoInstanceUpdated.Tags = tagInstances
353 // Video channel update?
354 if (res.locals.videoChannel && videoInstanceUpdated.channelId !== res.locals.videoChannel.id) {
355 await videoInstanceUpdated.$set('VideoChannel', res.locals.videoChannel, { transaction: t })
356 videoInstanceUpdated.VideoChannel = res.locals.videoChannel
358 if (wasPrivateVideo === false) await changeVideoChannelShare(videoInstanceUpdated, oldVideoChannel, t)
361 // Schedule an update in the future?
362 if (videoInfoToUpdate.scheduleUpdate) {
363 await ScheduleVideoUpdateModel.upsert({
364 videoId: videoInstanceUpdated.id,
365 updateAt: videoInfoToUpdate.scheduleUpdate.updateAt,
366 privacy: videoInfoToUpdate.scheduleUpdate.privacy || null
367 }, { transaction: t })
368 } else if (videoInfoToUpdate.scheduleUpdate === null) {
369 await ScheduleVideoUpdateModel.deleteByVideoId(videoInstanceUpdated.id, t)
372 const isNewVideo = wasPrivateVideo && videoInstanceUpdated.privacy !== VideoPrivacy.PRIVATE
373 await federateVideoIfNeeded(videoInstanceUpdated, isNewVideo, t)
376 getAuditIdFromRes(res),
377 new VideoAuditView(videoInstanceUpdated.toFormattedDetailsJSON()),
380 logger.info('Video with name %s and uuid %s updated.', videoInstance.name, videoInstance.uuid)
382 return videoInstanceUpdated
385 if (wasUnlistedVideo || wasPrivateVideo) {
386 Notifier.Instance.notifyOnNewVideo(videoInstanceUpdated)
389 // Force fields we want to update
390 // If the transaction is retried, sequelize will think the object has not changed
391 // So it will skip the SQL request, even if the last one was ROLLBACKed!
392 resetSequelizeInstance(videoInstance, videoFieldsSave)
397 return res.type('json').status(204).end()
400 function getVideo (req: express.Request, res: express.Response) {
401 const videoInstance = res.locals.video
403 if (videoInstance.isOutdated()) {
404 JobQueue.Instance.createJob({ type: 'activitypub-refresher', payload: { type: 'video', videoUrl: videoInstance.url } })
405 .catch(err => logger.error('Cannot create AP refresher job for video %s.', videoInstance.url, { err }))
408 return res.json(videoInstance.toFormattedDetailsJSON())
411 async function viewVideo (req: express.Request, res: express.Response) {
412 const videoInstance = res.locals.video
415 const exists = await Redis.Instance.isVideoIPViewExists(ip, videoInstance.uuid)
417 logger.debug('View for ip %s and video %s already exists.', ip, videoInstance.uuid)
418 return res.status(204).end()
422 Redis.Instance.addVideoView(videoInstance.id),
423 Redis.Instance.setIPVideoView(ip, videoInstance.uuid)
426 const serverActor = await getServerActor()
427 await sendCreateView(serverActor, videoInstance, undefined)
429 return res.status(204).end()
432 async function getVideoDescription (req: express.Request, res: express.Response) {
433 const videoInstance = res.locals.video
436 if (videoInstance.isOwned()) {
437 description = videoInstance.description
439 description = await fetchRemoteVideoDescription(videoInstance)
442 return res.json({ description })
445 async function listVideos (req: express.Request, res: express.Response) {
446 const resultList = await VideoModel.listForApi({
447 start: req.query.start,
448 count: req.query.count,
449 sort: req.query.sort,
450 includeLocalVideos: true,
451 categoryOneOf: req.query.categoryOneOf,
452 licenceOneOf: req.query.licenceOneOf,
453 languageOneOf: req.query.languageOneOf,
454 tagsOneOf: req.query.tagsOneOf,
455 tagsAllOf: req.query.tagsAllOf,
456 nsfw: buildNSFWFilter(res, req.query.nsfw),
457 filter: req.query.filter as VideoFilter,
459 user: res.locals.oauth ? res.locals.oauth.token.User : undefined
462 return res.json(getFormattedObjects(resultList.data, resultList.total))
465 async function removeVideo (req: express.Request, res: express.Response) {
466 const videoInstance: VideoModel = res.locals.video
468 await sequelizeTypescript.transaction(async t => {
469 await videoInstance.destroy({ transaction: t })
472 auditLogger.delete(getAuditIdFromRes(res), new VideoAuditView(videoInstance.toFormattedDetailsJSON()))
473 logger.info('Video with name %s and uuid %s deleted.', videoInstance.name, videoInstance.uuid)
475 return res.type('json').status(204).end()