1 import * as express from 'express'
2 import { extname, join } from 'path'
3 import { VideoCreate, VideoPrivacy, VideoUpdate } from '../../../../shared'
4 import { renamePromise } from '../../../helpers/core-utils'
5 import { retryTransactionWrapper } from '../../../helpers/database-utils'
6 import { getVideoFileResolution } from '../../../helpers/ffmpeg-utils'
7 import { processImage } from '../../../helpers/image-utils'
8 import { logger } from '../../../helpers/logger'
9 import { getFormattedObjects, getServerActor, resetSequelizeInstance } from '../../../helpers/utils'
21 } from '../../../initializers'
23 changeVideoChannelShare,
24 fetchRemoteVideoDescription,
25 getVideoActivityPubUrl,
26 shareVideoByServerAndChannel
27 } from '../../../lib/activitypub'
28 import { sendCreateVideo, sendCreateView, sendUpdateVideo } from '../../../lib/activitypub/send'
29 import { JobQueue } from '../../../lib/job-queue'
30 import { Redis } from '../../../lib/redis'
40 videosRemoveValidator,
41 videosSearchValidator,
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 { VideoFilter } from '../../../../shared/models/videos/video-query.type'
53 import { VideoSortField } from '../../../../client/src/app/shared/video/sort-field.type'
54 import { isNSFWHidden, createReqFiles } from '../../../helpers/express-utils'
56 const videosRouter = express.Router()
58 const reqVideoFileAdd = createReqFiles(
59 [ 'videofile', 'thumbnailfile', 'previewfile' ],
60 Object.assign({}, VIDEO_MIMETYPE_EXT, IMAGE_MIMETYPE_EXT),
62 videofile: CONFIG.STORAGE.VIDEOS_DIR,
63 thumbnailfile: CONFIG.STORAGE.THUMBNAILS_DIR,
64 previewfile: CONFIG.STORAGE.PREVIEWS_DIR
67 const reqVideoFileUpdate = createReqFiles(
68 [ 'thumbnailfile', 'previewfile' ],
71 thumbnailfile: CONFIG.STORAGE.THUMBNAILS_DIR,
72 previewfile: CONFIG.STORAGE.PREVIEWS_DIR
76 videosRouter.use('/', abuseVideoRouter)
77 videosRouter.use('/', blacklistRouter)
78 videosRouter.use('/', rateVideoRouter)
79 videosRouter.use('/', videoCommentRouter)
81 videosRouter.get('/categories', listVideoCategories)
82 videosRouter.get('/licences', listVideoLicences)
83 videosRouter.get('/languages', listVideoLanguages)
84 videosRouter.get('/privacies', listVideoPrivacies)
92 asyncMiddleware(listVideos)
94 videosRouter.get('/search',
95 videosSearchValidator,
100 optionalAuthenticate,
101 asyncMiddleware(searchVideos)
103 videosRouter.put('/:id',
106 asyncMiddleware(videosUpdateValidator),
107 asyncMiddleware(updateVideoRetryWrapper)
109 videosRouter.post('/upload',
112 asyncMiddleware(videosAddValidator),
113 asyncMiddleware(addVideoRetryWrapper)
116 videosRouter.get('/:id/description',
117 asyncMiddleware(videosGetValidator),
118 asyncMiddleware(getVideoDescription)
120 videosRouter.get('/:id',
121 asyncMiddleware(videosGetValidator),
124 videosRouter.post('/:id/views',
125 asyncMiddleware(videosGetValidator),
126 asyncMiddleware(viewVideo)
129 videosRouter.delete('/:id',
131 asyncMiddleware(videosRemoveValidator),
132 asyncMiddleware(removeVideoRetryWrapper)
135 // ---------------------------------------------------------------------------
141 // ---------------------------------------------------------------------------
143 function listVideoCategories (req: express.Request, res: express.Response) {
144 res.json(VIDEO_CATEGORIES)
147 function listVideoLicences (req: express.Request, res: express.Response) {
148 res.json(VIDEO_LICENCES)
151 function listVideoLanguages (req: express.Request, res: express.Response) {
152 res.json(VIDEO_LANGUAGES)
155 function listVideoPrivacies (req: express.Request, res: express.Response) {
156 res.json(VIDEO_PRIVACIES)
159 // Wrapper to video add that retry the function if there is a database error
160 // We need this because we run the transaction in SERIALIZABLE isolation that can fail
161 async function addVideoRetryWrapper (req: express.Request, res: express.Response, next: express.NextFunction) {
163 arguments: [ req, res, req.files['videofile'][0] ],
164 errorMessage: 'Cannot insert the video with many retries.'
167 const video = await retryTransactionWrapper(addVideo, options)
177 async function addVideo (req: express.Request, res: express.Response, videoPhysicalFile: Express.Multer.File) {
178 const videoInfo: VideoCreate = req.body
180 // Prepare data so we don't block the transaction
182 name: videoInfo.name,
184 extname: extname(videoPhysicalFile.filename),
185 category: videoInfo.category,
186 licence: videoInfo.licence,
187 language: videoInfo.language,
188 commentsEnabled: videoInfo.commentsEnabled,
189 nsfw: videoInfo.nsfw,
190 description: videoInfo.description,
191 support: videoInfo.support,
192 privacy: videoInfo.privacy,
193 duration: videoPhysicalFile['duration'], // duration was added by a previous middleware
194 channelId: res.locals.videoChannel.id
196 const video = new VideoModel(videoData)
197 video.url = getVideoActivityPubUrl(video)
199 const { videoFileResolution } = await getVideoFileResolution(videoPhysicalFile.path)
201 const videoFileData = {
202 extname: extname(videoPhysicalFile.filename),
203 resolution: videoFileResolution,
204 size: videoPhysicalFile.size
206 const videoFile = new VideoFileModel(videoFileData)
207 const videoDir = CONFIG.STORAGE.VIDEOS_DIR
208 const destination = join(videoDir, video.getVideoFilename(videoFile))
210 await renamePromise(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 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 ]
247 if (videoInfo.tags !== undefined) {
248 const tagInstances = await TagModel.findOrCreateTags(videoInfo.tags, t)
250 await video.$set('Tags', tagInstances, sequelizeOptions)
251 video.Tags = tagInstances
254 // Let transcoding job send the video to friends because the video file extension might change
255 if (CONFIG.TRANSCODING.ENABLED === true) return videoCreated
256 // Don't send video to remote servers, it is private
257 if (video.privacy === VideoPrivacy.PRIVATE) return videoCreated
259 await sendCreateVideo(video, t)
260 await shareVideoByServerAndChannel(video, t)
262 logger.info('Video with name %s and uuid %s created.', videoInfo.name, videoCreated.uuid)
267 if (CONFIG.TRANSCODING.ENABLED === true) {
268 // Put uuid because we don't have id auto incremented for now
270 videoUUID: videoCreated.uuid
273 await JobQueue.Instance.createJob({ type: 'video-file', payload: dataInput })
279 async function updateVideoRetryWrapper (req: express.Request, res: express.Response, next: express.NextFunction) {
281 arguments: [ req, res ],
282 errorMessage: 'Cannot update the video with many retries.'
285 await retryTransactionWrapper(updateVideo, options)
287 return res.type('json').status(204).end()
290 async function updateVideo (req: express.Request, res: express.Response) {
291 const videoInstance: VideoModel = res.locals.video
292 const videoFieldsSave = videoInstance.toJSON()
293 const videoInfoToUpdate: VideoUpdate = req.body
294 const wasPrivateVideo = videoInstance.privacy === VideoPrivacy.PRIVATE
296 // Process thumbnail or create it from the video
297 if (req.files && req.files['thumbnailfile']) {
298 const thumbnailPhysicalFile = req.files['thumbnailfile'][0]
299 await processImage(thumbnailPhysicalFile, join(CONFIG.STORAGE.THUMBNAILS_DIR, videoInstance.getThumbnailName()), THUMBNAILS_SIZE)
302 // Process preview or create it from the video
303 if (req.files && req.files['previewfile']) {
304 const previewPhysicalFile = req.files['previewfile'][0]
305 await processImage(previewPhysicalFile, join(CONFIG.STORAGE.PREVIEWS_DIR, videoInstance.getPreviewName()), PREVIEWS_SIZE)
309 await sequelizeTypescript.transaction(async t => {
310 const sequelizeOptions = {
313 const oldVideoChannel = videoInstance.VideoChannel
315 if (videoInfoToUpdate.name !== undefined) videoInstance.set('name', videoInfoToUpdate.name)
316 if (videoInfoToUpdate.category !== undefined) videoInstance.set('category', videoInfoToUpdate.category)
317 if (videoInfoToUpdate.licence !== undefined) videoInstance.set('licence', videoInfoToUpdate.licence)
318 if (videoInfoToUpdate.language !== undefined) videoInstance.set('language', videoInfoToUpdate.language)
319 if (videoInfoToUpdate.nsfw !== undefined) videoInstance.set('nsfw', videoInfoToUpdate.nsfw)
320 if (videoInfoToUpdate.support !== undefined) videoInstance.set('support', videoInfoToUpdate.support)
321 if (videoInfoToUpdate.description !== undefined) videoInstance.set('description', videoInfoToUpdate.description)
322 if (videoInfoToUpdate.commentsEnabled !== undefined) videoInstance.set('commentsEnabled', videoInfoToUpdate.commentsEnabled)
323 if (videoInfoToUpdate.privacy !== undefined) {
324 const newPrivacy = parseInt(videoInfoToUpdate.privacy.toString(), 10)
325 videoInstance.set('privacy', newPrivacy)
327 if (wasPrivateVideo === true && newPrivacy !== VideoPrivacy.PRIVATE) {
328 videoInstance.set('publishedAt', new Date())
332 const videoInstanceUpdated = await videoInstance.save(sequelizeOptions)
334 // Video tags update?
335 if (videoInfoToUpdate.tags !== undefined) {
336 const tagInstances = await TagModel.findOrCreateTags(videoInfoToUpdate.tags, t)
338 await videoInstanceUpdated.$set('Tags', tagInstances, sequelizeOptions)
339 videoInstanceUpdated.Tags = tagInstances
342 // Video channel update?
343 if (res.locals.videoChannel && videoInstanceUpdated.channelId !== res.locals.videoChannel.id) {
344 await videoInstanceUpdated.$set('VideoChannel', res.locals.videoChannel)
345 videoInstance.VideoChannel = res.locals.videoChannel
347 if (wasPrivateVideo === false) await changeVideoChannelShare(videoInstanceUpdated, oldVideoChannel, t)
350 // Now we'll update the video's meta data to our friends
351 if (wasPrivateVideo === false) await sendUpdateVideo(videoInstanceUpdated, t)
353 // Video is not private anymore, send a create action to remote servers
354 if (wasPrivateVideo === true && videoInstanceUpdated.privacy !== VideoPrivacy.PRIVATE) {
355 await sendCreateVideo(videoInstanceUpdated, t)
356 await shareVideoByServerAndChannel(videoInstanceUpdated, t)
360 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)
371 function getVideo (req: express.Request, res: express.Response) {
372 const videoInstance = res.locals.video
374 return res.json(videoInstance.toFormattedDetailsJSON())
377 async function viewVideo (req: express.Request, res: express.Response) {
378 const videoInstance = res.locals.video
381 const exists = await Redis.Instance.isViewExists(ip, videoInstance.uuid)
383 logger.debug('View for ip %s and video %s already exists.', ip, videoInstance.uuid)
384 return res.status(204).end()
387 await videoInstance.increment('views')
388 await Redis.Instance.setView(ip, videoInstance.uuid)
390 const serverAccount = await getServerActor()
392 await sendCreateView(serverAccount, videoInstance, undefined)
394 return res.status(204).end()
397 async function getVideoDescription (req: express.Request, res: express.Response) {
398 const videoInstance = res.locals.video
401 if (videoInstance.isOwned()) {
402 description = videoInstance.description
404 description = await fetchRemoteVideoDescription(videoInstance)
407 return res.json({ description })
410 async function listVideos (req: express.Request, res: express.Response, next: express.NextFunction) {
411 const resultList = await VideoModel.listForApi({
412 start: req.query.start,
413 count: req.query.count,
414 sort: req.query.sort,
415 hideNSFW: isNSFWHidden(res),
416 filter: req.query.filter as VideoFilter,
420 return res.json(getFormattedObjects(resultList.data, resultList.total))
423 async function removeVideoRetryWrapper (req: express.Request, res: express.Response, next: express.NextFunction) {
425 arguments: [ req, res ],
426 errorMessage: 'Cannot remove the video with many retries.'
429 await retryTransactionWrapper(removeVideo, options)
431 return res.type('json').status(204).end()
434 async function removeVideo (req: express.Request, res: express.Response) {
435 const videoInstance: VideoModel = res.locals.video
437 await sequelizeTypescript.transaction(async t => {
438 await videoInstance.destroy({ transaction: t })
441 logger.info('Video with name %s and uuid %s deleted.', videoInstance.name, videoInstance.uuid)
444 async function searchVideos (req: express.Request, res: express.Response, next: express.NextFunction) {
445 const resultList = await VideoModel.searchAndPopulateAccountAndServer(
446 req.query.search as string,
447 req.query.start as number,
448 req.query.count as number,
449 req.query.sort as VideoSortField,
453 return res.json(getFormattedObjects(resultList.data, resultList.total))