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'
18 } from '../../../initializers'
20 changeVideoChannelShare,
21 federateVideoIfNeeded,
22 fetchRemoteVideoDescription,
23 getVideoActivityPubUrl
24 } from '../../../lib/activitypub'
25 import { sendCreateView } from '../../../lib/activitypub/send'
26 import { JobQueue } from '../../../lib/job-queue'
27 import { Redis } from '../../../lib/redis'
30 asyncRetryTransactionMiddleware,
32 checkVideoFollowConstraints,
33 commonVideosFiltersValidator,
40 videosRemoveValidator,
43 } from '../../../middlewares'
44 import { TagModel } from '../../../models/video/tag'
45 import { VideoModel } from '../../../models/video/video'
46 import { VideoFileModel } from '../../../models/video/video-file'
47 import { abuseVideoRouter } from './abuse'
48 import { blacklistRouter } from './blacklist'
49 import { videoCommentRouter } from './comment'
50 import { rateVideoRouter } from './rate'
51 import { ownershipVideoRouter } from './ownership'
52 import { VideoFilter } from '../../../../shared/models/videos/video-query.type'
53 import { buildNSFWFilter, createReqFiles } from '../../../helpers/express-utils'
54 import { ScheduleVideoUpdateModel } from '../../../models/video/schedule-video-update'
55 import { videoCaptionsRouter } from './captions'
56 import { videoImportsRouter } from './import'
57 import { resetSequelizeInstance } from '../../../helpers/database-utils'
58 import { move } from 'fs-extra'
59 import { watchingRouter } from './watching'
61 const auditLogger = auditLoggerFactory('videos')
62 const videosRouter = express.Router()
64 const reqVideoFileAdd = createReqFiles(
65 [ 'videofile', 'thumbnailfile', 'previewfile' ],
66 Object.assign({}, MIMETYPES.VIDEO.MIMETYPE_EXT, MIMETYPES.IMAGE.MIMETYPE_EXT),
68 videofile: CONFIG.STORAGE.TMP_DIR,
69 thumbnailfile: CONFIG.STORAGE.TMP_DIR,
70 previewfile: CONFIG.STORAGE.TMP_DIR
73 const reqVideoFileUpdate = createReqFiles(
74 [ 'thumbnailfile', 'previewfile' ],
75 MIMETYPES.IMAGE.MIMETYPE_EXT,
77 thumbnailfile: CONFIG.STORAGE.TMP_DIR,
78 previewfile: CONFIG.STORAGE.TMP_DIR
82 videosRouter.use('/', abuseVideoRouter)
83 videosRouter.use('/', blacklistRouter)
84 videosRouter.use('/', rateVideoRouter)
85 videosRouter.use('/', videoCommentRouter)
86 videosRouter.use('/', videoCaptionsRouter)
87 videosRouter.use('/', videoImportsRouter)
88 videosRouter.use('/', ownershipVideoRouter)
89 videosRouter.use('/', watchingRouter)
91 videosRouter.get('/categories', listVideoCategories)
92 videosRouter.get('/licences', listVideoLicences)
93 videosRouter.get('/languages', listVideoLanguages)
94 videosRouter.get('/privacies', listVideoPrivacies)
100 setDefaultPagination,
101 optionalAuthenticate,
102 commonVideosFiltersValidator,
103 asyncMiddleware(listVideos)
105 videosRouter.put('/:id',
108 asyncMiddleware(videosUpdateValidator),
109 asyncRetryTransactionMiddleware(updateVideo)
111 videosRouter.post('/upload',
114 asyncMiddleware(videosAddValidator),
115 asyncRetryTransactionMiddleware(addVideo)
118 videosRouter.get('/:id/description',
119 asyncMiddleware(videosGetValidator),
120 asyncMiddleware(getVideoDescription)
122 videosRouter.get('/:id',
123 optionalAuthenticate,
124 asyncMiddleware(videosGetValidator),
125 asyncMiddleware(checkVideoFollowConstraints),
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 waitTranscoding: videoInfo.waitTranscoding || false,
183 state: CONFIG.TRANSCODING.ENABLED ? VideoState.TO_TRANSCODE : VideoState.PUBLISHED,
184 nsfw: videoInfo.nsfw || false,
185 description: videoInfo.description,
186 support: videoInfo.support,
187 privacy: videoInfo.privacy,
188 duration: videoPhysicalFile['duration'], // duration was added by a previous middleware
189 channelId: res.locals.videoChannel.id
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 if (thumbnailField) {
217 const thumbnailPhysicalFile = thumbnailField[0]
218 await processImage(thumbnailPhysicalFile, join(CONFIG.STORAGE.THUMBNAILS_DIR, video.getThumbnailName()), THUMBNAILS_SIZE)
220 await video.createThumbnail(videoFile)
223 // Process preview or create it from the video
224 const previewField = req.files['previewfile']
226 const previewPhysicalFile = previewField[0]
227 await processImage(previewPhysicalFile, join(CONFIG.STORAGE.PREVIEWS_DIR, video.getPreviewName()), PREVIEWS_SIZE)
229 await video.createPreview(videoFile)
232 // Create the torrent file
233 await video.createTorrentAndSetInfoHash(videoFile)
235 const videoCreated = await sequelizeTypescript.transaction(async t => {
236 const sequelizeOptions = { transaction: t }
238 const videoCreated = await video.save(sequelizeOptions)
239 // Do not forget to add video channel information to the created video
240 videoCreated.VideoChannel = res.locals.videoChannel
242 videoFile.videoId = video.id
243 await videoFile.save(sequelizeOptions)
245 video.VideoFiles = [ videoFile ]
248 if (videoInfo.tags !== undefined) {
249 const tagInstances = await TagModel.findOrCreateTags(videoInfo.tags, t)
251 await video.$set('Tags', tagInstances, sequelizeOptions)
252 video.Tags = tagInstances
255 // Schedule an update in the future?
256 if (videoInfo.scheduleUpdate) {
257 await ScheduleVideoUpdateModel.create({
259 updateAt: videoInfo.scheduleUpdate.updateAt,
260 privacy: videoInfo.scheduleUpdate.privacy || null
261 }, { transaction: t })
264 await federateVideoIfNeeded(video, true, t)
266 auditLogger.create(getAuditIdFromRes(res), new VideoAuditView(videoCreated.toFormattedDetailsJSON()))
267 logger.info('Video with name %s and uuid %s created.', videoInfo.name, videoCreated.uuid)
272 if (video.state === VideoState.TO_TRANSCODE) {
273 // Put uuid because we don't have id auto incremented for now
275 videoUUID: videoCreated.uuid,
279 await JobQueue.Instance.createJob({ type: 'video-file', payload: dataInput })
285 uuid: videoCreated.uuid
290 async function updateVideo (req: express.Request, res: express.Response) {
291 const videoInstance: VideoModel = res.locals.video
292 const videoFieldsSave = videoInstance.toJSON()
293 const oldVideoAuditView = new VideoAuditView(videoInstance.toFormattedDetailsJSON())
294 const videoInfoToUpdate: VideoUpdate = req.body
295 const wasPrivateVideo = videoInstance.privacy === VideoPrivacy.PRIVATE
297 // Process thumbnail or create it from the video
298 if (req.files && req.files['thumbnailfile']) {
299 const thumbnailPhysicalFile = req.files['thumbnailfile'][0]
300 await processImage(thumbnailPhysicalFile, join(CONFIG.STORAGE.THUMBNAILS_DIR, videoInstance.getThumbnailName()), THUMBNAILS_SIZE)
303 // Process preview or create it from the video
304 if (req.files && req.files['previewfile']) {
305 const previewPhysicalFile = req.files['previewfile'][0]
306 await processImage(previewPhysicalFile, join(CONFIG.STORAGE.PREVIEWS_DIR, videoInstance.getPreviewName()), PREVIEWS_SIZE)
310 await sequelizeTypescript.transaction(async t => {
311 const sequelizeOptions = {
314 const oldVideoChannel = videoInstance.VideoChannel
316 if (videoInfoToUpdate.name !== undefined) videoInstance.set('name', videoInfoToUpdate.name)
317 if (videoInfoToUpdate.category !== undefined) videoInstance.set('category', videoInfoToUpdate.category)
318 if (videoInfoToUpdate.licence !== undefined) videoInstance.set('licence', videoInfoToUpdate.licence)
319 if (videoInfoToUpdate.language !== undefined) videoInstance.set('language', videoInfoToUpdate.language)
320 if (videoInfoToUpdate.nsfw !== undefined) videoInstance.set('nsfw', videoInfoToUpdate.nsfw)
321 if (videoInfoToUpdate.waitTranscoding !== undefined) videoInstance.set('waitTranscoding', videoInfoToUpdate.waitTranscoding)
322 if (videoInfoToUpdate.support !== undefined) videoInstance.set('support', videoInfoToUpdate.support)
323 if (videoInfoToUpdate.description !== undefined) videoInstance.set('description', videoInfoToUpdate.description)
324 if (videoInfoToUpdate.commentsEnabled !== undefined) videoInstance.set('commentsEnabled', videoInfoToUpdate.commentsEnabled)
325 if (videoInfoToUpdate.privacy !== undefined) {
326 const newPrivacy = parseInt(videoInfoToUpdate.privacy.toString(), 10)
327 videoInstance.set('privacy', newPrivacy)
329 if (wasPrivateVideo === true && newPrivacy !== VideoPrivacy.PRIVATE) {
330 videoInstance.set('publishedAt', new Date())
334 const videoInstanceUpdated = await videoInstance.save(sequelizeOptions)
336 // Video tags update?
337 if (videoInfoToUpdate.tags !== undefined) {
338 const tagInstances = await TagModel.findOrCreateTags(videoInfoToUpdate.tags, t)
340 await videoInstanceUpdated.$set('Tags', tagInstances, sequelizeOptions)
341 videoInstanceUpdated.Tags = tagInstances
344 // Video channel update?
345 if (res.locals.videoChannel && videoInstanceUpdated.channelId !== res.locals.videoChannel.id) {
346 await videoInstanceUpdated.$set('VideoChannel', res.locals.videoChannel, { transaction: t })
347 videoInstanceUpdated.VideoChannel = res.locals.videoChannel
349 if (wasPrivateVideo === false) await changeVideoChannelShare(videoInstanceUpdated, oldVideoChannel, t)
352 // Schedule an update in the future?
353 if (videoInfoToUpdate.scheduleUpdate) {
354 await ScheduleVideoUpdateModel.upsert({
355 videoId: videoInstanceUpdated.id,
356 updateAt: videoInfoToUpdate.scheduleUpdate.updateAt,
357 privacy: videoInfoToUpdate.scheduleUpdate.privacy || null
358 }, { transaction: t })
359 } else if (videoInfoToUpdate.scheduleUpdate === null) {
360 await ScheduleVideoUpdateModel.deleteByVideoId(videoInstanceUpdated.id, t)
363 const isNewVideo = wasPrivateVideo && videoInstanceUpdated.privacy !== VideoPrivacy.PRIVATE
364 await federateVideoIfNeeded(videoInstanceUpdated, isNewVideo, t)
367 getAuditIdFromRes(res),
368 new VideoAuditView(videoInstanceUpdated.toFormattedDetailsJSON()),
371 logger.info('Video with name %s and uuid %s updated.', videoInstance.name, videoInstance.uuid)
374 // Force fields we want to update
375 // If the transaction is retried, sequelize will think the object has not changed
376 // So it will skip the SQL request, even if the last one was ROLLBACKed!
377 resetSequelizeInstance(videoInstance, videoFieldsSave)
382 return res.type('json').status(204).end()
385 function getVideo (req: express.Request, res: express.Response) {
386 const videoInstance = res.locals.video
388 if (videoInstance.isOutdated()) {
389 JobQueue.Instance.createJob({ type: 'activitypub-refresher', payload: { type: 'video', videoUrl: videoInstance.url } })
390 .catch(err => logger.error('Cannot create AP refresher job for video %s.', videoInstance.url, { err }))
393 return res.json(videoInstance.toFormattedDetailsJSON())
396 async function viewVideo (req: express.Request, res: express.Response) {
397 const videoInstance = res.locals.video
400 const exists = await Redis.Instance.isVideoIPViewExists(ip, videoInstance.uuid)
402 logger.debug('View for ip %s and video %s already exists.', ip, videoInstance.uuid)
403 return res.status(204).end()
407 Redis.Instance.addVideoView(videoInstance.id),
408 Redis.Instance.setIPVideoView(ip, videoInstance.uuid)
411 const serverActor = await getServerActor()
412 await sendCreateView(serverActor, videoInstance, undefined)
414 return res.status(204).end()
417 async function getVideoDescription (req: express.Request, res: express.Response) {
418 const videoInstance = res.locals.video
421 if (videoInstance.isOwned()) {
422 description = videoInstance.description
424 description = await fetchRemoteVideoDescription(videoInstance)
427 return res.json({ description })
430 async function listVideos (req: express.Request, res: express.Response) {
431 const resultList = await VideoModel.listForApi({
432 start: req.query.start,
433 count: req.query.count,
434 sort: req.query.sort,
435 includeLocalVideos: true,
436 categoryOneOf: req.query.categoryOneOf,
437 licenceOneOf: req.query.licenceOneOf,
438 languageOneOf: req.query.languageOneOf,
439 tagsOneOf: req.query.tagsOneOf,
440 tagsAllOf: req.query.tagsAllOf,
441 nsfw: buildNSFWFilter(res, req.query.nsfw),
442 filter: req.query.filter as VideoFilter,
444 user: res.locals.oauth ? res.locals.oauth.token.User : undefined
447 return res.json(getFormattedObjects(resultList.data, resultList.total))
450 async function removeVideo (req: express.Request, res: express.Response) {
451 const videoInstance: VideoModel = res.locals.video
453 await sequelizeTypescript.transaction(async t => {
454 await videoInstance.destroy({ transaction: t })
457 auditLogger.delete(getAuditIdFromRes(res), new VideoAuditView(videoInstance.toFormattedDetailsJSON()))
458 logger.info('Video with name %s and uuid %s deleted.', videoInstance.name, videoInstance.uuid)
460 return res.type('json').status(204).end()