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 { JobQueue } from '../../../lib/job-queue'
27 import { Redis } from '../../../lib/redis'
30 asyncRetryTransactionMiddleware,
32 checkVideoFollowConstraints,
33 commonVideosFiltersValidator,
39 videosCustomGetValidator,
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'
62 import { sendView } from '../../../lib/activitypub/send/send-view'
64 const auditLogger = auditLoggerFactory('videos')
65 const videosRouter = express.Router()
67 const reqVideoFileAdd = createReqFiles(
68 [ 'videofile', 'thumbnailfile', 'previewfile' ],
69 Object.assign({}, MIMETYPES.VIDEO.MIMETYPE_EXT, MIMETYPES.IMAGE.MIMETYPE_EXT),
71 videofile: CONFIG.STORAGE.TMP_DIR,
72 thumbnailfile: CONFIG.STORAGE.TMP_DIR,
73 previewfile: CONFIG.STORAGE.TMP_DIR
76 const reqVideoFileUpdate = createReqFiles(
77 [ 'thumbnailfile', 'previewfile' ],
78 MIMETYPES.IMAGE.MIMETYPE_EXT,
80 thumbnailfile: CONFIG.STORAGE.TMP_DIR,
81 previewfile: CONFIG.STORAGE.TMP_DIR
85 videosRouter.use('/', abuseVideoRouter)
86 videosRouter.use('/', blacklistRouter)
87 videosRouter.use('/', rateVideoRouter)
88 videosRouter.use('/', videoCommentRouter)
89 videosRouter.use('/', videoCaptionsRouter)
90 videosRouter.use('/', videoImportsRouter)
91 videosRouter.use('/', ownershipVideoRouter)
92 videosRouter.use('/', watchingRouter)
94 videosRouter.get('/categories', listVideoCategories)
95 videosRouter.get('/licences', listVideoLicences)
96 videosRouter.get('/languages', listVideoLanguages)
97 videosRouter.get('/privacies', listVideoPrivacies)
103 setDefaultPagination,
104 optionalAuthenticate,
105 commonVideosFiltersValidator,
106 asyncMiddleware(listVideos)
108 videosRouter.put('/:id',
111 asyncMiddleware(videosUpdateValidator),
112 asyncRetryTransactionMiddleware(updateVideo)
114 videosRouter.post('/upload',
117 asyncMiddleware(videosAddValidator),
118 asyncRetryTransactionMiddleware(addVideo)
121 videosRouter.get('/:id/description',
122 asyncMiddleware(videosGetValidator),
123 asyncMiddleware(getVideoDescription)
125 videosRouter.get('/:id',
126 optionalAuthenticate,
127 asyncMiddleware(videosCustomGetValidator('only-video-with-rights')),
128 asyncMiddleware(checkVideoFollowConstraints),
129 asyncMiddleware(getVideo)
131 videosRouter.post('/:id/views',
132 asyncMiddleware(videosGetValidator),
133 asyncMiddleware(viewVideo)
136 videosRouter.delete('/:id',
138 asyncMiddleware(videosRemoveValidator),
139 asyncRetryTransactionMiddleware(removeVideo)
142 // ---------------------------------------------------------------------------
148 // ---------------------------------------------------------------------------
150 function listVideoCategories (req: express.Request, res: express.Response) {
151 res.json(VIDEO_CATEGORIES)
154 function listVideoLicences (req: express.Request, res: express.Response) {
155 res.json(VIDEO_LICENCES)
158 function listVideoLanguages (req: express.Request, res: express.Response) {
159 res.json(VIDEO_LANGUAGES)
162 function listVideoPrivacies (req: express.Request, res: express.Response) {
163 res.json(VIDEO_PRIVACIES)
166 async function addVideo (req: express.Request, res: express.Response) {
167 // Processing the video could be long
168 // Set timeout to 10 minutes
169 req.setTimeout(1000 * 60 * 10, () => {
170 logger.error('Upload video has timed out.')
171 return res.sendStatus(408)
174 const videoPhysicalFile = req.files['videofile'][0]
175 const videoInfo: VideoCreate = req.body
177 // Prepare data so we don't block the transaction
179 name: videoInfo.name,
181 category: videoInfo.category,
182 licence: videoInfo.licence,
183 language: videoInfo.language,
184 commentsEnabled: videoInfo.commentsEnabled || false,
185 downloadEnabled: videoInfo.downloadEnabled || true,
186 waitTranscoding: videoInfo.waitTranscoding || false,
187 state: CONFIG.TRANSCODING.ENABLED ? VideoState.TO_TRANSCODE : VideoState.PUBLISHED,
188 nsfw: videoInfo.nsfw || false,
189 description: videoInfo.description,
190 support: videoInfo.support,
191 privacy: videoInfo.privacy,
192 duration: videoPhysicalFile['duration'], // duration was added by a previous middleware
193 channelId: res.locals.videoChannel.id,
194 originallyPublishedAt: videoInfo.originallyPublishedAt
196 const video = new VideoModel(videoData)
197 video.url = getVideoActivityPubUrl(video) // We use the UUID, so set the URL after building the object
199 // Build the file object
200 const { videoFileResolution } = await getVideoFileResolution(videoPhysicalFile.path)
201 const fps = await getVideoFileFPS(videoPhysicalFile.path)
203 const videoFileData = {
204 extname: extname(videoPhysicalFile.filename),
205 resolution: videoFileResolution,
206 size: videoPhysicalFile.size,
209 const videoFile = new VideoFileModel(videoFileData)
211 // Move physical file
212 const videoDir = CONFIG.STORAGE.VIDEOS_DIR
213 const destination = join(videoDir, video.getVideoFilename(videoFile))
214 await move(videoPhysicalFile.path, destination)
215 // This is important in case if there is another attempt in the retry process
216 videoPhysicalFile.filename = video.getVideoFilename(videoFile)
217 videoPhysicalFile.path = destination
219 // Process thumbnail or create it from the video
220 const thumbnailField = req.files['thumbnailfile']
221 if (thumbnailField) {
222 const thumbnailPhysicalFile = thumbnailField[0]
223 await processImage(thumbnailPhysicalFile, join(CONFIG.STORAGE.THUMBNAILS_DIR, video.getThumbnailName()), THUMBNAILS_SIZE)
225 await video.createThumbnail(videoFile)
228 // Process preview or create it from the video
229 const previewField = req.files['previewfile']
231 const previewPhysicalFile = previewField[0]
232 await processImage(previewPhysicalFile, join(CONFIG.STORAGE.PREVIEWS_DIR, video.getPreviewName()), PREVIEWS_SIZE)
234 await video.createPreview(videoFile)
237 // Create the torrent file
238 await video.createTorrentAndSetInfoHash(videoFile)
240 const videoCreated = await sequelizeTypescript.transaction(async t => {
241 const sequelizeOptions = { transaction: t }
243 const videoCreated = await video.save(sequelizeOptions)
244 // Do not forget to add video channel information to the created video
245 videoCreated.VideoChannel = res.locals.videoChannel
247 videoFile.videoId = video.id
248 await videoFile.save(sequelizeOptions)
250 video.VideoFiles = [ videoFile ]
253 if (videoInfo.tags !== undefined) {
254 const tagInstances = await TagModel.findOrCreateTags(videoInfo.tags, t)
256 await video.$set('Tags', tagInstances, sequelizeOptions)
257 video.Tags = tagInstances
260 // Schedule an update in the future?
261 if (videoInfo.scheduleUpdate) {
262 await ScheduleVideoUpdateModel.create({
264 updateAt: videoInfo.scheduleUpdate.updateAt,
265 privacy: videoInfo.scheduleUpdate.privacy || null
266 }, { transaction: t })
269 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)
277 Notifier.Instance.notifyOnNewVideo(videoCreated)
279 if (video.state === VideoState.TO_TRANSCODE) {
280 // Put uuid because we don't have id auto incremented for now
282 videoUUID: videoCreated.uuid,
286 await JobQueue.Instance.createJob({ type: 'video-file', payload: dataInput })
292 uuid: videoCreated.uuid
297 async function updateVideo (req: express.Request, res: express.Response) {
298 const videoInstance = res.locals.video
299 const videoFieldsSave = videoInstance.toJSON()
300 const oldVideoAuditView = new VideoAuditView(videoInstance.toFormattedDetailsJSON())
301 const videoInfoToUpdate: VideoUpdate = req.body
302 const wasPrivateVideo = videoInstance.privacy === VideoPrivacy.PRIVATE
303 const wasUnlistedVideo = videoInstance.privacy === VideoPrivacy.UNLISTED
305 // Process thumbnail or create it from the video
306 if (req.files && req.files['thumbnailfile']) {
307 const thumbnailPhysicalFile = req.files['thumbnailfile'][0]
308 await processImage(thumbnailPhysicalFile, join(CONFIG.STORAGE.THUMBNAILS_DIR, videoInstance.getThumbnailName()), THUMBNAILS_SIZE)
311 // Process preview or create it from the video
312 if (req.files && req.files['previewfile']) {
313 const previewPhysicalFile = req.files['previewfile'][0]
314 await processImage(previewPhysicalFile, join(CONFIG.STORAGE.PREVIEWS_DIR, videoInstance.getPreviewName()), PREVIEWS_SIZE)
318 const videoInstanceUpdated = await sequelizeTypescript.transaction(async t => {
319 const sequelizeOptions = { transaction: t }
320 const oldVideoChannel = videoInstance.VideoChannel
322 if (videoInfoToUpdate.name !== undefined) videoInstance.set('name', videoInfoToUpdate.name)
323 if (videoInfoToUpdate.category !== undefined) videoInstance.set('category', videoInfoToUpdate.category)
324 if (videoInfoToUpdate.licence !== undefined) videoInstance.set('licence', videoInfoToUpdate.licence)
325 if (videoInfoToUpdate.language !== undefined) videoInstance.set('language', videoInfoToUpdate.language)
326 if (videoInfoToUpdate.nsfw !== undefined) videoInstance.set('nsfw', videoInfoToUpdate.nsfw)
327 if (videoInfoToUpdate.waitTranscoding !== undefined) videoInstance.set('waitTranscoding', videoInfoToUpdate.waitTranscoding)
328 if (videoInfoToUpdate.support !== undefined) videoInstance.set('support', videoInfoToUpdate.support)
329 if (videoInfoToUpdate.description !== undefined) videoInstance.set('description', videoInfoToUpdate.description)
330 if (videoInfoToUpdate.commentsEnabled !== undefined) videoInstance.set('commentsEnabled', videoInfoToUpdate.commentsEnabled)
331 if (videoInfoToUpdate.downloadEnabled !== undefined) videoInstance.set('downloadEnabled', videoInfoToUpdate.downloadEnabled)
333 if (videoInfoToUpdate.originallyPublishedAt !== undefined && videoInfoToUpdate.originallyPublishedAt !== null) {
334 videoInstance.set('originallyPublishedAt', videoInfoToUpdate.originallyPublishedAt)
337 if (videoInfoToUpdate.privacy !== undefined) {
338 const newPrivacy = parseInt(videoInfoToUpdate.privacy.toString(), 10)
339 videoInstance.set('privacy', newPrivacy)
341 if (wasPrivateVideo === true && newPrivacy !== VideoPrivacy.PRIVATE) {
342 videoInstance.set('publishedAt', new Date())
346 const videoInstanceUpdated = await videoInstance.save(sequelizeOptions)
348 // Video tags update?
349 if (videoInfoToUpdate.tags !== undefined) {
350 const tagInstances = await TagModel.findOrCreateTags(videoInfoToUpdate.tags, t)
352 await videoInstanceUpdated.$set('Tags', tagInstances, sequelizeOptions)
353 videoInstanceUpdated.Tags = tagInstances
356 // Video channel update?
357 if (res.locals.videoChannel && videoInstanceUpdated.channelId !== res.locals.videoChannel.id) {
358 await videoInstanceUpdated.$set('VideoChannel', res.locals.videoChannel, { transaction: t })
359 videoInstanceUpdated.VideoChannel = res.locals.videoChannel
361 if (wasPrivateVideo === false) await changeVideoChannelShare(videoInstanceUpdated, oldVideoChannel, t)
364 // Schedule an update in the future?
365 if (videoInfoToUpdate.scheduleUpdate) {
366 await ScheduleVideoUpdateModel.upsert({
367 videoId: videoInstanceUpdated.id,
368 updateAt: videoInfoToUpdate.scheduleUpdate.updateAt,
369 privacy: videoInfoToUpdate.scheduleUpdate.privacy || null
370 }, { transaction: t })
371 } else if (videoInfoToUpdate.scheduleUpdate === null) {
372 await ScheduleVideoUpdateModel.deleteByVideoId(videoInstanceUpdated.id, t)
375 const isNewVideo = wasPrivateVideo && videoInstanceUpdated.privacy !== VideoPrivacy.PRIVATE
377 // Don't send update if the video was unfederated
378 if (!videoInstanceUpdated.VideoBlacklist || videoInstanceUpdated.VideoBlacklist.unfederated === false) {
379 await federateVideoIfNeeded(videoInstanceUpdated, isNewVideo, t)
383 getAuditIdFromRes(res),
384 new VideoAuditView(videoInstanceUpdated.toFormattedDetailsJSON()),
387 logger.info('Video with name %s and uuid %s updated.', videoInstance.name, videoInstance.uuid)
389 return videoInstanceUpdated
392 if (wasUnlistedVideo || wasPrivateVideo) {
393 Notifier.Instance.notifyOnNewVideo(videoInstanceUpdated)
396 // Force fields we want to update
397 // If the transaction is retried, sequelize will think the object has not changed
398 // So it will skip the SQL request, even if the last one was ROLLBACKed!
399 resetSequelizeInstance(videoInstance, videoFieldsSave)
404 return res.type('json').status(204).end()
407 async function getVideo (req: express.Request, res: express.Response) {
408 // We need more attributes
409 const userId: number = res.locals.oauth ? res.locals.oauth.token.User.id : null
410 const video = await VideoModel.loadForGetAPI(res.locals.video.id, undefined, userId)
412 if (video.isOutdated()) {
413 JobQueue.Instance.createJob({ type: 'activitypub-refresher', payload: { type: 'video', url: video.url } })
414 .catch(err => logger.error('Cannot create AP refresher job for video %s.', video.url, { err }))
417 return res.json(video.toFormattedDetailsJSON())
420 async function viewVideo (req: express.Request, res: express.Response) {
421 const videoInstance = res.locals.video
424 const exists = await Redis.Instance.doesVideoIPViewExist(ip, videoInstance.uuid)
426 logger.debug('View for ip %s and video %s already exists.', ip, videoInstance.uuid)
427 return res.status(204).end()
431 Redis.Instance.addVideoView(videoInstance.id),
432 Redis.Instance.setIPVideoView(ip, videoInstance.uuid)
435 const serverActor = await getServerActor()
436 await sendView(serverActor, videoInstance, undefined)
438 return res.status(204).end()
441 async function getVideoDescription (req: express.Request, res: express.Response) {
442 const videoInstance = res.locals.video
445 if (videoInstance.isOwned()) {
446 description = videoInstance.description
448 description = await fetchRemoteVideoDescription(videoInstance)
451 return res.json({ description })
454 async function listVideos (req: express.Request, res: express.Response) {
455 const resultList = await VideoModel.listForApi({
456 start: req.query.start,
457 count: req.query.count,
458 sort: req.query.sort,
459 includeLocalVideos: true,
460 categoryOneOf: req.query.categoryOneOf,
461 licenceOneOf: req.query.licenceOneOf,
462 languageOneOf: req.query.languageOneOf,
463 tagsOneOf: req.query.tagsOneOf,
464 tagsAllOf: req.query.tagsAllOf,
465 nsfw: buildNSFWFilter(res, req.query.nsfw),
466 filter: req.query.filter as VideoFilter,
468 user: res.locals.oauth ? res.locals.oauth.token.User : undefined
471 return res.json(getFormattedObjects(resultList.data, resultList.total))
474 async function removeVideo (req: express.Request, res: express.Response) {
475 const videoInstance = res.locals.video
477 await sequelizeTypescript.transaction(async t => {
478 await videoInstance.destroy({ transaction: t })
481 auditLogger.delete(getAuditIdFromRes(res), new VideoAuditView(videoInstance.toFormattedDetailsJSON()))
482 logger.info('Video with name %s and uuid %s deleted.', videoInstance.name, videoInstance.uuid)
484 return res.type('json').status(204).end()