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 { 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 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'
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 { createReqFiles, isNSFWHidden } 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 || false,
189 waitTranscoding: videoInfo.waitTranscoding || false,
190 state: CONFIG.TRANSCODING.ENABLED ? VideoState.TO_TRANSCODE : VideoState.PUBLISHED,
191 nsfw: videoInfo.nsfw || false,
192 description: videoInfo.description,
193 support: videoInfo.support,
194 privacy: videoInfo.privacy,
195 duration: videoPhysicalFile['duration'], // duration was added by a previous middleware
196 channelId: res.locals.videoChannel.id
198 const video = new VideoModel(videoData)
199 video.url = getVideoActivityPubUrl(video) // We use the UUID, so set the URL after building the object
201 // Build the file object
202 const { videoFileResolution } = await getVideoFileResolution(videoPhysicalFile.path)
203 const videoFileData = {
204 extname: extname(videoPhysicalFile.filename),
205 resolution: videoFileResolution,
206 size: videoPhysicalFile.size
208 const videoFile = new VideoFileModel(videoFileData)
210 // Move physical file
211 const videoDir = CONFIG.STORAGE.VIDEOS_DIR
212 const destination = join(videoDir, video.getVideoFilename(videoFile))
213 await renamePromise(videoPhysicalFile.path, destination)
214 // This is important in case if there is another attempt in the retry process
215 videoPhysicalFile.filename = video.getVideoFilename(videoFile)
216 videoPhysicalFile.path = destination
218 // Process thumbnail or create it from the video
219 const thumbnailField = req.files['thumbnailfile']
220 if (thumbnailField) {
221 const thumbnailPhysicalFile = thumbnailField[0]
222 await processImage(thumbnailPhysicalFile, join(CONFIG.STORAGE.THUMBNAILS_DIR, video.getThumbnailName()), THUMBNAILS_SIZE)
224 await video.createThumbnail(videoFile)
227 // Process preview or create it from the video
228 const previewField = req.files['previewfile']
230 const previewPhysicalFile = previewField[0]
231 await processImage(previewPhysicalFile, join(CONFIG.STORAGE.PREVIEWS_DIR, video.getPreviewName()), PREVIEWS_SIZE)
233 await video.createPreview(videoFile)
236 // Create the torrent file
237 await video.createTorrentAndSetInfoHash(videoFile)
239 const videoCreated = await sequelizeTypescript.transaction(async t => {
240 const sequelizeOptions = { transaction: t }
242 const videoCreated = await video.save(sequelizeOptions)
243 // Do not forget to add video channel information to the created video
244 videoCreated.VideoChannel = res.locals.videoChannel
246 videoFile.videoId = video.id
247 await videoFile.save(sequelizeOptions)
249 video.VideoFiles = [ videoFile ]
251 if (videoInfo.tags !== undefined) {
252 const tagInstances = await TagModel.findOrCreateTags(videoInfo.tags, t)
254 await video.$set('Tags', tagInstances, sequelizeOptions)
255 video.Tags = tagInstances
258 await federateVideoIfNeeded(video, true, t)
260 logger.info('Video with name %s and uuid %s created.', videoInfo.name, videoCreated.uuid)
265 if (video.state === VideoState.TO_TRANSCODE) {
266 // Put uuid because we don't have id auto incremented for now
268 videoUUID: videoCreated.uuid,
272 await JobQueue.Instance.createJob({ type: 'video-file', payload: dataInput })
278 async function updateVideoRetryWrapper (req: express.Request, res: express.Response, next: express.NextFunction) {
280 arguments: [ req, res ],
281 errorMessage: 'Cannot update the video with many retries.'
284 await retryTransactionWrapper(updateVideo, options)
286 return res.type('json').status(204).end()
289 async function updateVideo (req: express.Request, res: express.Response) {
290 const videoInstance: VideoModel = res.locals.video
291 const videoFieldsSave = videoInstance.toJSON()
292 const videoInfoToUpdate: VideoUpdate = req.body
293 const wasPrivateVideo = videoInstance.privacy === VideoPrivacy.PRIVATE
295 // Process thumbnail or create it from the video
296 if (req.files && req.files['thumbnailfile']) {
297 const thumbnailPhysicalFile = req.files['thumbnailfile'][0]
298 await processImage(thumbnailPhysicalFile, join(CONFIG.STORAGE.THUMBNAILS_DIR, videoInstance.getThumbnailName()), THUMBNAILS_SIZE)
301 // Process preview or create it from the video
302 if (req.files && req.files['previewfile']) {
303 const previewPhysicalFile = req.files['previewfile'][0]
304 await processImage(previewPhysicalFile, join(CONFIG.STORAGE.PREVIEWS_DIR, videoInstance.getPreviewName()), PREVIEWS_SIZE)
308 await sequelizeTypescript.transaction(async t => {
309 const sequelizeOptions = {
312 const oldVideoChannel = videoInstance.VideoChannel
314 if (videoInfoToUpdate.name !== undefined) videoInstance.set('name', videoInfoToUpdate.name)
315 if (videoInfoToUpdate.category !== undefined) videoInstance.set('category', videoInfoToUpdate.category)
316 if (videoInfoToUpdate.licence !== undefined) videoInstance.set('licence', videoInfoToUpdate.licence)
317 if (videoInfoToUpdate.language !== undefined) videoInstance.set('language', videoInfoToUpdate.language)
318 if (videoInfoToUpdate.nsfw !== undefined) videoInstance.set('nsfw', videoInfoToUpdate.nsfw)
319 if (videoInfoToUpdate.waitTranscoding !== undefined) videoInstance.set('waitTranscoding', videoInfoToUpdate.waitTranscoding)
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, { transaction: t })
345 videoInstanceUpdated.VideoChannel = res.locals.videoChannel
347 if (wasPrivateVideo === false) await changeVideoChannelShare(videoInstanceUpdated, oldVideoChannel, t)
350 const isNewVideo = wasPrivateVideo && videoInstanceUpdated.privacy !== VideoPrivacy.PRIVATE
351 await federateVideoIfNeeded(videoInstanceUpdated, isNewVideo)
354 logger.info('Video with name %s and uuid %s updated.', videoInstance.name, videoInstance.uuid)
356 // Force fields we want to update
357 // If the transaction is retried, sequelize will think the object has not changed
358 // So it will skip the SQL request, even if the last one was ROLLBACKed!
359 resetSequelizeInstance(videoInstance, videoFieldsSave)
365 function getVideo (req: express.Request, res: express.Response) {
366 const videoInstance = res.locals.video
368 return res.json(videoInstance.toFormattedDetailsJSON())
371 async function viewVideo (req: express.Request, res: express.Response) {
372 const videoInstance = res.locals.video
375 const exists = await Redis.Instance.isViewExists(ip, videoInstance.uuid)
377 logger.debug('View for ip %s and video %s already exists.', ip, videoInstance.uuid)
378 return res.status(204).end()
381 await videoInstance.increment('views')
382 await Redis.Instance.setView(ip, videoInstance.uuid)
384 const serverAccount = await getServerActor()
386 await sendCreateView(serverAccount, videoInstance, undefined)
388 return res.status(204).end()
391 async function getVideoDescription (req: express.Request, res: express.Response) {
392 const videoInstance = res.locals.video
395 if (videoInstance.isOwned()) {
396 description = videoInstance.description
398 description = await fetchRemoteVideoDescription(videoInstance)
401 return res.json({ description })
404 async function listVideos (req: express.Request, res: express.Response, next: express.NextFunction) {
405 const resultList = await VideoModel.listForApi({
406 start: req.query.start,
407 count: req.query.count,
408 sort: req.query.sort,
409 hideNSFW: isNSFWHidden(res),
410 filter: req.query.filter as VideoFilter,
414 return res.json(getFormattedObjects(resultList.data, resultList.total))
417 async function removeVideoRetryWrapper (req: express.Request, res: express.Response, next: express.NextFunction) {
419 arguments: [ req, res ],
420 errorMessage: 'Cannot remove the video with many retries.'
423 await retryTransactionWrapper(removeVideo, options)
425 return res.type('json').status(204).end()
428 async function removeVideo (req: express.Request, res: express.Response) {
429 const videoInstance: VideoModel = res.locals.video
431 await sequelizeTypescript.transaction(async t => {
432 await videoInstance.destroy({ transaction: t })
435 logger.info('Video with name %s and uuid %s deleted.', videoInstance.name, videoInstance.uuid)
438 async function searchVideos (req: express.Request, res: express.Response, next: express.NextFunction) {
439 const resultList = await VideoModel.searchAndPopulateAccountAndServer(
440 req.query.search as string,
441 req.query.start as number,
442 req.query.count as number,
443 req.query.sort as VideoSortField,
447 return res.json(getFormattedObjects(resultList.data, resultList.total))