1 import * as express from 'express'
2 import { extname, join } from 'path'
3 import { VideoCreate, VideoPrivacy, VideoState, VideoUpdate } from '../../../../shared'
4 import { renamePromise } from '../../../helpers/core-utils'
5 import { getVideoFileFPS, getVideoFileResolution } from '../../../helpers/ffmpeg-utils'
6 import { processImage } from '../../../helpers/image-utils'
7 import { logger } from '../../../helpers/logger'
8 import { auditLoggerFactory, VideoAuditView } from '../../../helpers/audit-logger'
9 import { getFormattedObjects, getServerActor } from '../../../helpers/utils'
21 } from '../../../initializers'
23 changeVideoChannelShare,
24 federateVideoIfNeeded,
25 fetchRemoteVideoDescription,
26 getVideoActivityPubUrl
27 } from '../../../lib/activitypub'
28 import { sendCreateView } from '../../../lib/activitypub/send'
29 import { JobQueue } from '../../../lib/job-queue'
30 import { Redis } from '../../../lib/redis'
33 asyncRetryTransactionMiddleware,
35 commonVideosFiltersValidator,
42 videosRemoveValidator,
45 } from '../../../middlewares'
46 import { TagModel } from '../../../models/video/tag'
47 import { VideoModel } from '../../../models/video/video'
48 import { VideoFileModel } from '../../../models/video/video-file'
49 import { abuseVideoRouter } from './abuse'
50 import { blacklistRouter } from './blacklist'
51 import { videoCommentRouter } from './comment'
52 import { rateVideoRouter } from './rate'
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'
60 const auditLogger = auditLoggerFactory('videos')
61 const videosRouter = express.Router()
63 const reqVideoFileAdd = createReqFiles(
64 [ 'videofile', 'thumbnailfile', 'previewfile' ],
65 Object.assign({}, VIDEO_MIMETYPE_EXT, IMAGE_MIMETYPE_EXT),
67 videofile: CONFIG.STORAGE.VIDEOS_DIR,
68 thumbnailfile: CONFIG.STORAGE.THUMBNAILS_DIR,
69 previewfile: CONFIG.STORAGE.PREVIEWS_DIR
72 const reqVideoFileUpdate = createReqFiles(
73 [ 'thumbnailfile', 'previewfile' ],
76 thumbnailfile: CONFIG.STORAGE.THUMBNAILS_DIR,
77 previewfile: CONFIG.STORAGE.PREVIEWS_DIR
81 videosRouter.use('/', abuseVideoRouter)
82 videosRouter.use('/', blacklistRouter)
83 videosRouter.use('/', rateVideoRouter)
84 videosRouter.use('/', videoCommentRouter)
85 videosRouter.use('/', videoCaptionsRouter)
86 videosRouter.use('/', videoImportsRouter)
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 asyncMiddleware(videosGetValidator),
123 videosRouter.post('/:id/views',
124 asyncMiddleware(videosGetValidator),
125 asyncMiddleware(viewVideo)
128 videosRouter.delete('/:id',
130 asyncMiddleware(videosRemoveValidator),
131 asyncRetryTransactionMiddleware(removeVideo)
134 // ---------------------------------------------------------------------------
140 // ---------------------------------------------------------------------------
142 function listVideoCategories (req: express.Request, res: express.Response) {
143 res.json(VIDEO_CATEGORIES)
146 function listVideoLicences (req: express.Request, res: express.Response) {
147 res.json(VIDEO_LICENCES)
150 function listVideoLanguages (req: express.Request, res: express.Response) {
151 res.json(VIDEO_LANGUAGES)
154 function listVideoPrivacies (req: express.Request, res: express.Response) {
155 res.json(VIDEO_PRIVACIES)
158 async function addVideo (req: express.Request, res: express.Response) {
159 const videoPhysicalFile = req.files['videofile'][0]
160 const videoInfo: VideoCreate = req.body
162 // Prepare data so we don't block the transaction
164 name: videoInfo.name,
166 category: videoInfo.category,
167 licence: videoInfo.licence,
168 language: videoInfo.language,
169 commentsEnabled: videoInfo.commentsEnabled || false,
170 waitTranscoding: videoInfo.waitTranscoding || false,
171 state: CONFIG.TRANSCODING.ENABLED ? VideoState.TO_TRANSCODE : VideoState.PUBLISHED,
172 nsfw: videoInfo.nsfw || false,
173 description: videoInfo.description,
174 support: videoInfo.support,
175 privacy: videoInfo.privacy,
176 duration: videoPhysicalFile['duration'], // duration was added by a previous middleware
177 channelId: res.locals.videoChannel.id
179 const video = new VideoModel(videoData)
180 video.url = getVideoActivityPubUrl(video) // We use the UUID, so set the URL after building the object
182 // Build the file object
183 const { videoFileResolution } = await getVideoFileResolution(videoPhysicalFile.path)
184 const fps = await getVideoFileFPS(videoPhysicalFile.path)
186 const videoFileData = {
187 extname: extname(videoPhysicalFile.filename),
188 resolution: videoFileResolution,
189 size: videoPhysicalFile.size,
192 const videoFile = new VideoFileModel(videoFileData)
194 // Move physical file
195 const videoDir = CONFIG.STORAGE.VIDEOS_DIR
196 const destination = join(videoDir, video.getVideoFilename(videoFile))
197 await renamePromise(videoPhysicalFile.path, destination)
198 // This is important in case if there is another attempt in the retry process
199 videoPhysicalFile.filename = video.getVideoFilename(videoFile)
200 videoPhysicalFile.path = destination
202 // Process thumbnail or create it from the video
203 const thumbnailField = req.files['thumbnailfile']
204 if (thumbnailField) {
205 const thumbnailPhysicalFile = thumbnailField[0]
206 await processImage(thumbnailPhysicalFile, join(CONFIG.STORAGE.THUMBNAILS_DIR, video.getThumbnailName()), THUMBNAILS_SIZE)
208 await video.createThumbnail(videoFile)
211 // Process preview or create it from the video
212 const previewField = req.files['previewfile']
214 const previewPhysicalFile = previewField[0]
215 await processImage(previewPhysicalFile, join(CONFIG.STORAGE.PREVIEWS_DIR, video.getPreviewName()), PREVIEWS_SIZE)
217 await video.createPreview(videoFile)
220 // Create the torrent file
221 await video.createTorrentAndSetInfoHash(videoFile)
223 const videoCreated = await sequelizeTypescript.transaction(async t => {
224 const sequelizeOptions = { transaction: t }
226 const videoCreated = await video.save(sequelizeOptions)
227 // Do not forget to add video channel information to the created video
228 videoCreated.VideoChannel = res.locals.videoChannel
230 videoFile.videoId = video.id
231 await videoFile.save(sequelizeOptions)
233 video.VideoFiles = [ videoFile ]
236 if (videoInfo.tags !== undefined) {
237 const tagInstances = await TagModel.findOrCreateTags(videoInfo.tags, t)
239 await video.$set('Tags', tagInstances, sequelizeOptions)
240 video.Tags = tagInstances
243 // Schedule an update in the future?
244 if (videoInfo.scheduleUpdate) {
245 await ScheduleVideoUpdateModel.create({
247 updateAt: videoInfo.scheduleUpdate.updateAt,
248 privacy: videoInfo.scheduleUpdate.privacy || null
249 }, { transaction: t })
252 await federateVideoIfNeeded(video, true, t)
254 auditLogger.create(res.locals.oauth.token.User.Account.Actor.getIdentifier(), new VideoAuditView(videoCreated.toFormattedDetailsJSON()))
255 logger.info('Video with name %s and uuid %s created.', videoInfo.name, videoCreated.uuid)
260 if (video.state === VideoState.TO_TRANSCODE) {
261 // Put uuid because we don't have id auto incremented for now
263 videoUUID: videoCreated.uuid,
267 await JobQueue.Instance.createJob({ type: 'video-file', payload: dataInput })
273 uuid: videoCreated.uuid
278 async function updateVideo (req: express.Request, res: express.Response) {
279 const videoInstance: VideoModel = res.locals.video
280 const videoFieldsSave = videoInstance.toJSON()
281 const oldVideoAuditView = new VideoAuditView(videoInstance.toFormattedDetailsJSON())
282 const videoInfoToUpdate: VideoUpdate = req.body
283 const wasPrivateVideo = videoInstance.privacy === VideoPrivacy.PRIVATE
285 // Process thumbnail or create it from the video
286 if (req.files && req.files['thumbnailfile']) {
287 const thumbnailPhysicalFile = req.files['thumbnailfile'][0]
288 await processImage(thumbnailPhysicalFile, join(CONFIG.STORAGE.THUMBNAILS_DIR, videoInstance.getThumbnailName()), THUMBNAILS_SIZE)
291 // Process preview or create it from the video
292 if (req.files && req.files['previewfile']) {
293 const previewPhysicalFile = req.files['previewfile'][0]
294 await processImage(previewPhysicalFile, join(CONFIG.STORAGE.PREVIEWS_DIR, videoInstance.getPreviewName()), PREVIEWS_SIZE)
298 await sequelizeTypescript.transaction(async t => {
299 const sequelizeOptions = {
302 const oldVideoChannel = videoInstance.VideoChannel
304 if (videoInfoToUpdate.name !== undefined) videoInstance.set('name', videoInfoToUpdate.name)
305 if (videoInfoToUpdate.category !== undefined) videoInstance.set('category', videoInfoToUpdate.category)
306 if (videoInfoToUpdate.licence !== undefined) videoInstance.set('licence', videoInfoToUpdate.licence)
307 if (videoInfoToUpdate.language !== undefined) videoInstance.set('language', videoInfoToUpdate.language)
308 if (videoInfoToUpdate.nsfw !== undefined) videoInstance.set('nsfw', videoInfoToUpdate.nsfw)
309 if (videoInfoToUpdate.waitTranscoding !== undefined) videoInstance.set('waitTranscoding', videoInfoToUpdate.waitTranscoding)
310 if (videoInfoToUpdate.support !== undefined) videoInstance.set('support', videoInfoToUpdate.support)
311 if (videoInfoToUpdate.description !== undefined) videoInstance.set('description', videoInfoToUpdate.description)
312 if (videoInfoToUpdate.commentsEnabled !== undefined) videoInstance.set('commentsEnabled', videoInfoToUpdate.commentsEnabled)
313 if (videoInfoToUpdate.privacy !== undefined) {
314 const newPrivacy = parseInt(videoInfoToUpdate.privacy.toString(), 10)
315 videoInstance.set('privacy', newPrivacy)
317 if (wasPrivateVideo === true && newPrivacy !== VideoPrivacy.PRIVATE) {
318 videoInstance.set('publishedAt', new Date())
322 const videoInstanceUpdated = await videoInstance.save(sequelizeOptions)
324 // Video tags update?
325 if (videoInfoToUpdate.tags !== undefined) {
326 const tagInstances = await TagModel.findOrCreateTags(videoInfoToUpdate.tags, t)
328 await videoInstanceUpdated.$set('Tags', tagInstances, sequelizeOptions)
329 videoInstanceUpdated.Tags = tagInstances
332 // Video channel update?
333 if (res.locals.videoChannel && videoInstanceUpdated.channelId !== res.locals.videoChannel.id) {
334 await videoInstanceUpdated.$set('VideoChannel', res.locals.videoChannel, { transaction: t })
335 videoInstanceUpdated.VideoChannel = res.locals.videoChannel
337 if (wasPrivateVideo === false) await changeVideoChannelShare(videoInstanceUpdated, oldVideoChannel, t)
340 // Schedule an update in the future?
341 if (videoInfoToUpdate.scheduleUpdate) {
342 await ScheduleVideoUpdateModel.upsert({
343 videoId: videoInstanceUpdated.id,
344 updateAt: videoInfoToUpdate.scheduleUpdate.updateAt,
345 privacy: videoInfoToUpdate.scheduleUpdate.privacy || null
346 }, { transaction: t })
347 } else if (videoInfoToUpdate.scheduleUpdate === null) {
348 await ScheduleVideoUpdateModel.deleteByVideoId(videoInstanceUpdated.id, t)
351 const isNewVideo = wasPrivateVideo && videoInstanceUpdated.privacy !== VideoPrivacy.PRIVATE
352 await federateVideoIfNeeded(videoInstanceUpdated, isNewVideo, t)
355 res.locals.oauth.token.User.Account.Actor.getIdentifier(),
356 new VideoAuditView(videoInstanceUpdated.toFormattedDetailsJSON()),
359 logger.info('Video with name %s and uuid %s updated.', videoInstance.name, videoInstance.uuid)
362 // Force fields we want to update
363 // If the transaction is retried, sequelize will think the object has not changed
364 // So it will skip the SQL request, even if the last one was ROLLBACKed!
365 resetSequelizeInstance(videoInstance, videoFieldsSave)
370 return res.type('json').status(204).end()
373 function getVideo (req: express.Request, res: express.Response) {
374 const videoInstance = res.locals.video
376 return res.json(videoInstance.toFormattedDetailsJSON())
379 async function viewVideo (req: express.Request, res: express.Response) {
380 const videoInstance = res.locals.video
383 const exists = await Redis.Instance.isViewExists(ip, videoInstance.uuid)
385 logger.debug('View for ip %s and video %s already exists.', ip, videoInstance.uuid)
386 return res.status(204).end()
389 await videoInstance.increment('views')
390 await Redis.Instance.setView(ip, videoInstance.uuid)
392 const serverAccount = await getServerActor()
394 await sendCreateView(serverAccount, videoInstance, undefined)
396 return res.status(204).end()
399 async function getVideoDescription (req: express.Request, res: express.Response) {
400 const videoInstance = res.locals.video
403 if (videoInstance.isOwned()) {
404 description = videoInstance.description
406 description = await fetchRemoteVideoDescription(videoInstance)
409 return res.json({ description })
412 async function listVideos (req: express.Request, res: express.Response, next: express.NextFunction) {
413 const resultList = await VideoModel.listForApi({
414 start: req.query.start,
415 count: req.query.count,
416 sort: req.query.sort,
417 categoryOneOf: req.query.categoryOneOf,
418 licenceOneOf: req.query.licenceOneOf,
419 languageOneOf: req.query.languageOneOf,
420 tagsOneOf: req.query.tagsOneOf,
421 tagsAllOf: req.query.tagsAllOf,
422 nsfw: buildNSFWFilter(res, req.query.nsfw),
423 filter: req.query.filter as VideoFilter,
427 return res.json(getFormattedObjects(resultList.data, resultList.total))
430 async function removeVideo (req: express.Request, res: express.Response) {
431 const videoInstance: VideoModel = res.locals.video
433 await sequelizeTypescript.transaction(async t => {
434 await videoInstance.destroy({ transaction: t })
437 auditLogger.delete(res.locals.oauth.token.User.Account.Actor.getIdentifier(), new VideoAuditView(videoInstance.toFormattedDetailsJSON()))
438 logger.info('Video with name %s and uuid %s deleted.', videoInstance.name, videoInstance.uuid)
440 return res.type('json').status(204).end()