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'
20 } from '../../../initializers'
22 changeVideoChannelShare,
23 federateVideoIfNeeded,
24 fetchRemoteVideoDescription,
25 getVideoActivityPubUrl
26 } from '../../../lib/activitypub'
27 import { sendCreateView } from '../../../lib/activitypub/send'
28 import { JobQueue } from '../../../lib/job-queue'
29 import { Redis } from '../../../lib/redis'
32 asyncRetryTransactionMiddleware,
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 { rename } from 'fs-extra'
60 import { watchingRouter } from './watching'
62 const auditLogger = auditLoggerFactory('videos')
63 const videosRouter = express.Router()
65 const reqVideoFileAdd = createReqFiles(
66 [ 'videofile', 'thumbnailfile', 'previewfile' ],
67 Object.assign({}, VIDEO_MIMETYPE_EXT, IMAGE_MIMETYPE_EXT),
69 videofile: CONFIG.STORAGE.VIDEOS_DIR,
70 thumbnailfile: CONFIG.STORAGE.THUMBNAILS_DIR,
71 previewfile: CONFIG.STORAGE.PREVIEWS_DIR
74 const reqVideoFileUpdate = createReqFiles(
75 [ 'thumbnailfile', 'previewfile' ],
78 thumbnailfile: CONFIG.STORAGE.THUMBNAILS_DIR,
79 previewfile: CONFIG.STORAGE.PREVIEWS_DIR
83 videosRouter.use('/', abuseVideoRouter)
84 videosRouter.use('/', blacklistRouter)
85 videosRouter.use('/', rateVideoRouter)
86 videosRouter.use('/', videoCommentRouter)
87 videosRouter.use('/', videoCaptionsRouter)
88 videosRouter.use('/', videoImportsRouter)
89 videosRouter.use('/', ownershipVideoRouter)
90 videosRouter.use('/', watchingRouter)
92 videosRouter.get('/categories', listVideoCategories)
93 videosRouter.get('/licences', listVideoLicences)
94 videosRouter.get('/languages', listVideoLanguages)
95 videosRouter.get('/privacies', listVideoPrivacies)
101 setDefaultPagination,
102 optionalAuthenticate,
103 commonVideosFiltersValidator,
104 asyncMiddleware(listVideos)
106 videosRouter.put('/:id',
109 asyncMiddleware(videosUpdateValidator),
110 asyncRetryTransactionMiddleware(updateVideo)
112 videosRouter.post('/upload',
115 asyncMiddleware(videosAddValidator),
116 asyncRetryTransactionMiddleware(addVideo)
119 videosRouter.get('/:id/description',
120 asyncMiddleware(videosGetValidator),
121 asyncMiddleware(getVideoDescription)
123 videosRouter.get('/:id',
124 optionalAuthenticate,
125 asyncMiddleware(videosGetValidator),
128 videosRouter.post('/:id/views',
129 asyncMiddleware(videosGetValidator),
130 asyncMiddleware(viewVideo)
133 videosRouter.delete('/:id',
135 asyncMiddleware(videosRemoveValidator),
136 asyncRetryTransactionMiddleware(removeVideo)
139 // ---------------------------------------------------------------------------
145 // ---------------------------------------------------------------------------
147 function listVideoCategories (req: express.Request, res: express.Response) {
148 res.json(VIDEO_CATEGORIES)
151 function listVideoLicences (req: express.Request, res: express.Response) {
152 res.json(VIDEO_LICENCES)
155 function listVideoLanguages (req: express.Request, res: express.Response) {
156 res.json(VIDEO_LANGUAGES)
159 function listVideoPrivacies (req: express.Request, res: express.Response) {
160 res.json(VIDEO_PRIVACIES)
163 async function addVideo (req: express.Request, res: express.Response) {
164 // Processing the video could be long
165 // Set timeout to 10 minutes
166 req.setTimeout(1000 * 60 * 10, () => {
167 logger.error('Upload video has timed out.')
168 return res.sendStatus(408)
171 const videoPhysicalFile = req.files['videofile'][0]
172 const videoInfo: VideoCreate = req.body
174 // Prepare data so we don't block the transaction
176 name: videoInfo.name,
178 category: videoInfo.category,
179 licence: videoInfo.licence,
180 language: videoInfo.language,
181 commentsEnabled: videoInfo.commentsEnabled || false,
182 downloadingEnabled: videoInfo.downloadingEnabled || false,
183 waitTranscoding: videoInfo.waitTranscoding || false,
184 state: CONFIG.TRANSCODING.ENABLED ? VideoState.TO_TRANSCODE : VideoState.PUBLISHED,
185 nsfw: videoInfo.nsfw || false,
186 description: videoInfo.description,
187 support: videoInfo.support,
188 privacy: videoInfo.privacy,
189 duration: videoPhysicalFile['duration'], // duration was added by a previous middleware
190 channelId: res.locals.videoChannel.id
192 const video = new VideoModel(videoData)
193 video.url = getVideoActivityPubUrl(video) // We use the UUID, so set the URL after building the object
195 // Build the file object
196 const { videoFileResolution } = await getVideoFileResolution(videoPhysicalFile.path)
197 const fps = await getVideoFileFPS(videoPhysicalFile.path)
199 const videoFileData = {
200 extname: extname(videoPhysicalFile.filename),
201 resolution: videoFileResolution,
202 size: videoPhysicalFile.size,
205 const videoFile = new VideoFileModel(videoFileData)
207 // Move physical file
208 const videoDir = CONFIG.STORAGE.VIDEOS_DIR
209 const destination = join(videoDir, video.getVideoFilename(videoFile))
210 await rename(videoPhysicalFile.path, destination)
211 // This is important in case if there is another attempt in the retry process
212 videoPhysicalFile.filename = video.getVideoFilename(videoFile)
213 videoPhysicalFile.path = destination
215 // Process thumbnail or create it from the video
216 const thumbnailField = req.files['thumbnailfile']
217 if (thumbnailField) {
218 const thumbnailPhysicalFile = thumbnailField[0]
219 await processImage(thumbnailPhysicalFile, join(CONFIG.STORAGE.THUMBNAILS_DIR, video.getThumbnailName()), THUMBNAILS_SIZE)
221 await video.createThumbnail(videoFile)
224 // Process preview or create it from the video
225 const previewField = req.files['previewfile']
227 const previewPhysicalFile = previewField[0]
228 await processImage(previewPhysicalFile, join(CONFIG.STORAGE.PREVIEWS_DIR, video.getPreviewName()), PREVIEWS_SIZE)
230 await video.createPreview(videoFile)
233 // Create the torrent file
234 await video.createTorrentAndSetInfoHash(videoFile)
236 const videoCreated = await sequelizeTypescript.transaction(async t => {
237 const sequelizeOptions = { transaction: t }
239 const videoCreated = await video.save(sequelizeOptions)
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 await federateVideoIfNeeded(video, true, t)
267 auditLogger.create(getAuditIdFromRes(res), new VideoAuditView(videoCreated.toFormattedDetailsJSON()))
268 logger.info('Video with name %s and uuid %s created.', videoInfo.name, videoCreated.uuid)
273 if (video.state === VideoState.TO_TRANSCODE) {
274 // Put uuid because we don't have id auto incremented for now
276 videoUUID: videoCreated.uuid,
280 await JobQueue.Instance.createJob({ type: 'video-file', payload: dataInput })
286 uuid: videoCreated.uuid
291 async function updateVideo (req: express.Request, res: express.Response) {
292 const videoInstance: VideoModel = res.locals.video
293 const videoFieldsSave = videoInstance.toJSON()
294 const oldVideoAuditView = new VideoAuditView(videoInstance.toFormattedDetailsJSON())
295 const videoInfoToUpdate: VideoUpdate = req.body
296 const wasPrivateVideo = videoInstance.privacy === VideoPrivacy.PRIVATE
298 // Process thumbnail or create it from the video
299 if (req.files && req.files['thumbnailfile']) {
300 const thumbnailPhysicalFile = req.files['thumbnailfile'][0]
301 await processImage(thumbnailPhysicalFile, join(CONFIG.STORAGE.THUMBNAILS_DIR, videoInstance.getThumbnailName()), THUMBNAILS_SIZE)
304 // Process preview or create it from the video
305 if (req.files && req.files['previewfile']) {
306 const previewPhysicalFile = req.files['previewfile'][0]
307 await processImage(previewPhysicalFile, join(CONFIG.STORAGE.PREVIEWS_DIR, videoInstance.getPreviewName()), PREVIEWS_SIZE)
311 await sequelizeTypescript.transaction(async t => {
312 const sequelizeOptions = {
315 const oldVideoChannel = videoInstance.VideoChannel
317 if (videoInfoToUpdate.name !== undefined) videoInstance.set('name', videoInfoToUpdate.name)
318 if (videoInfoToUpdate.category !== undefined) videoInstance.set('category', videoInfoToUpdate.category)
319 if (videoInfoToUpdate.licence !== undefined) videoInstance.set('licence', videoInfoToUpdate.licence)
320 if (videoInfoToUpdate.language !== undefined) videoInstance.set('language', videoInfoToUpdate.language)
321 if (videoInfoToUpdate.nsfw !== undefined) videoInstance.set('nsfw', videoInfoToUpdate.nsfw)
322 if (videoInfoToUpdate.waitTranscoding !== undefined) videoInstance.set('waitTranscoding', videoInfoToUpdate.waitTranscoding)
323 if (videoInfoToUpdate.support !== undefined) videoInstance.set('support', videoInfoToUpdate.support)
324 if (videoInfoToUpdate.description !== undefined) videoInstance.set('description', videoInfoToUpdate.description)
325 if (videoInfoToUpdate.commentsEnabled !== undefined) videoInstance.set('commentsEnabled', videoInfoToUpdate.commentsEnabled)
326 if (videoInfoToUpdate.downloadingEnabled !== undefined) videoInstance.set('downloadingEnabled', videoInfoToUpdate.downloadingEnabled)
327 if (videoInfoToUpdate.privacy !== undefined) {
328 const newPrivacy = parseInt(videoInfoToUpdate.privacy.toString(), 10)
329 videoInstance.set('privacy', newPrivacy)
331 if (wasPrivateVideo === true && newPrivacy !== VideoPrivacy.PRIVATE) {
332 videoInstance.set('publishedAt', new Date())
336 const videoInstanceUpdated = await videoInstance.save(sequelizeOptions)
338 // Video tags update?
339 if (videoInfoToUpdate.tags !== undefined) {
340 const tagInstances = await TagModel.findOrCreateTags(videoInfoToUpdate.tags, t)
342 await videoInstanceUpdated.$set('Tags', tagInstances, sequelizeOptions)
343 videoInstanceUpdated.Tags = tagInstances
346 // Video channel update?
347 if (res.locals.videoChannel && videoInstanceUpdated.channelId !== res.locals.videoChannel.id) {
348 await videoInstanceUpdated.$set('VideoChannel', res.locals.videoChannel, { transaction: t })
349 videoInstanceUpdated.VideoChannel = res.locals.videoChannel
351 if (wasPrivateVideo === false) await changeVideoChannelShare(videoInstanceUpdated, oldVideoChannel, t)
354 // Schedule an update in the future?
355 if (videoInfoToUpdate.scheduleUpdate) {
356 await ScheduleVideoUpdateModel.upsert({
357 videoId: videoInstanceUpdated.id,
358 updateAt: videoInfoToUpdate.scheduleUpdate.updateAt,
359 privacy: videoInfoToUpdate.scheduleUpdate.privacy || null
360 }, { transaction: t })
361 } else if (videoInfoToUpdate.scheduleUpdate === null) {
362 await ScheduleVideoUpdateModel.deleteByVideoId(videoInstanceUpdated.id, t)
365 const isNewVideo = wasPrivateVideo && videoInstanceUpdated.privacy !== VideoPrivacy.PRIVATE
366 await federateVideoIfNeeded(videoInstanceUpdated, isNewVideo, t)
369 getAuditIdFromRes(res),
370 new VideoAuditView(videoInstanceUpdated.toFormattedDetailsJSON()),
373 logger.info('Video with name %s and uuid %s updated.', videoInstance.name, videoInstance.uuid)
376 // Force fields we want to update
377 // If the transaction is retried, sequelize will think the object has not changed
378 // So it will skip the SQL request, even if the last one was ROLLBACKed!
379 resetSequelizeInstance(videoInstance, videoFieldsSave)
384 return res.type('json').status(204).end()
387 function getVideo (req: express.Request, res: express.Response) {
388 const videoInstance = res.locals.video
390 return res.json(videoInstance.toFormattedDetailsJSON())
393 async function viewVideo (req: express.Request, res: express.Response) {
394 const videoInstance = res.locals.video
397 const exists = await Redis.Instance.isVideoIPViewExists(ip, videoInstance.uuid)
399 logger.debug('View for ip %s and video %s already exists.', ip, videoInstance.uuid)
400 return res.status(204).end()
404 Redis.Instance.addVideoView(videoInstance.id),
405 Redis.Instance.setIPVideoView(ip, videoInstance.uuid)
408 const serverActor = await getServerActor()
410 await sendCreateView(serverActor, videoInstance, undefined)
412 return res.status(204).end()
415 async function getVideoDescription (req: express.Request, res: express.Response) {
416 const videoInstance = res.locals.video
419 if (videoInstance.isOwned()) {
420 description = videoInstance.description
422 description = await fetchRemoteVideoDescription(videoInstance)
425 return res.json({ description })
428 async function listVideos (req: express.Request, res: express.Response, next: express.NextFunction) {
429 const resultList = await VideoModel.listForApi({
430 start: req.query.start,
431 count: req.query.count,
432 sort: req.query.sort,
433 includeLocalVideos: true,
434 categoryOneOf: req.query.categoryOneOf,
435 licenceOneOf: req.query.licenceOneOf,
436 languageOneOf: req.query.languageOneOf,
437 tagsOneOf: req.query.tagsOneOf,
438 tagsAllOf: req.query.tagsAllOf,
439 nsfw: buildNSFWFilter(res, req.query.nsfw),
440 filter: req.query.filter as VideoFilter,
442 userId: res.locals.oauth ? res.locals.oauth.token.User.id : undefined
445 return res.json(getFormattedObjects(resultList.data, resultList.total))
448 async function removeVideo (req: express.Request, res: express.Response) {
449 const videoInstance: VideoModel = res.locals.video
451 await sequelizeTypescript.transaction(async t => {
452 await videoInstance.destroy({ transaction: t })
455 auditLogger.delete(getAuditIdFromRes(res), new VideoAuditView(videoInstance.toFormattedDetailsJSON()))
456 logger.info('Video with name %s and uuid %s deleted.', videoInstance.name, videoInstance.uuid)
458 return res.type('json').status(204).end()