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'
22 import { fetchRemoteVideoDescription, getVideoActivityPubUrl, shareVideoByServerAndChannel } from '../../../lib/activitypub'
23 import { sendCreateVideo, sendCreateView, sendUpdateVideo } from '../../../lib/activitypub/send'
24 import { JobQueue } from '../../../lib/job-queue'
25 import { Redis } from '../../../lib/redis'
35 videosRemoveValidator,
36 videosSearchValidator,
39 } from '../../../middlewares'
40 import { TagModel } from '../../../models/video/tag'
41 import { VideoModel } from '../../../models/video/video'
42 import { VideoFileModel } from '../../../models/video/video-file'
43 import { abuseVideoRouter } from './abuse'
44 import { blacklistRouter } from './blacklist'
45 import { videoCommentRouter } from './comment'
46 import { rateVideoRouter } from './rate'
47 import { VideoFilter } from '../../../../shared/models/videos/video-query.type'
48 import { VideoSortField } from '../../../../client/src/app/shared/video/sort-field.type'
49 import { isNSFWHidden, createReqFiles } from '../../../helpers/express-utils'
51 const videosRouter = express.Router()
53 const reqVideoFileAdd = createReqFiles(
54 [ 'videofile', 'thumbnailfile', 'previewfile' ],
55 Object.assign({}, VIDEO_MIMETYPE_EXT, IMAGE_MIMETYPE_EXT),
57 videofile: CONFIG.STORAGE.VIDEOS_DIR,
58 thumbnailfile: CONFIG.STORAGE.THUMBNAILS_DIR,
59 previewfile: CONFIG.STORAGE.PREVIEWS_DIR
62 const reqVideoFileUpdate = createReqFiles(
63 [ 'thumbnailfile', 'previewfile' ],
66 thumbnailfile: CONFIG.STORAGE.THUMBNAILS_DIR,
67 previewfile: CONFIG.STORAGE.PREVIEWS_DIR
71 videosRouter.use('/', abuseVideoRouter)
72 videosRouter.use('/', blacklistRouter)
73 videosRouter.use('/', rateVideoRouter)
74 videosRouter.use('/', videoCommentRouter)
76 videosRouter.get('/categories', listVideoCategories)
77 videosRouter.get('/licences', listVideoLicences)
78 videosRouter.get('/languages', listVideoLanguages)
79 videosRouter.get('/privacies', listVideoPrivacies)
87 asyncMiddleware(listVideos)
89 videosRouter.get('/search',
90 videosSearchValidator,
96 asyncMiddleware(searchVideos)
98 videosRouter.put('/:id',
101 asyncMiddleware(videosUpdateValidator),
102 asyncMiddleware(updateVideoRetryWrapper)
104 videosRouter.post('/upload',
107 asyncMiddleware(videosAddValidator),
108 asyncMiddleware(addVideoRetryWrapper)
111 videosRouter.get('/:id/description',
112 asyncMiddleware(videosGetValidator),
113 asyncMiddleware(getVideoDescription)
115 videosRouter.get('/:id',
116 asyncMiddleware(videosGetValidator),
119 videosRouter.post('/:id/views',
120 asyncMiddleware(videosGetValidator),
121 asyncMiddleware(viewVideo)
124 videosRouter.delete('/:id',
126 asyncMiddleware(videosRemoveValidator),
127 asyncMiddleware(removeVideoRetryWrapper)
130 // ---------------------------------------------------------------------------
136 // ---------------------------------------------------------------------------
138 function listVideoCategories (req: express.Request, res: express.Response) {
139 res.json(VIDEO_CATEGORIES)
142 function listVideoLicences (req: express.Request, res: express.Response) {
143 res.json(VIDEO_LICENCES)
146 function listVideoLanguages (req: express.Request, res: express.Response) {
147 res.json(VIDEO_LANGUAGES)
150 function listVideoPrivacies (req: express.Request, res: express.Response) {
151 res.json(VIDEO_PRIVACIES)
154 // Wrapper to video add that retry the function if there is a database error
155 // We need this because we run the transaction in SERIALIZABLE isolation that can fail
156 async function addVideoRetryWrapper (req: express.Request, res: express.Response, next: express.NextFunction) {
158 arguments: [ req, res, req.files['videofile'][0] ],
159 errorMessage: 'Cannot insert the video with many retries.'
162 const video = await retryTransactionWrapper(addVideo, options)
172 async function addVideo (req: express.Request, res: express.Response, videoPhysicalFile: Express.Multer.File) {
173 const videoInfo: VideoCreate = req.body
175 // Prepare data so we don't block the transaction
177 name: videoInfo.name,
179 extname: extname(videoPhysicalFile.filename),
180 category: videoInfo.category,
181 licence: videoInfo.licence,
182 language: videoInfo.language,
183 commentsEnabled: videoInfo.commentsEnabled,
184 nsfw: videoInfo.nsfw,
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)
194 const { videoFileResolution } = await getVideoFileResolution(videoPhysicalFile.path)
196 const videoFileData = {
197 extname: extname(videoPhysicalFile.filename),
198 resolution: videoFileResolution,
199 size: videoPhysicalFile.size
201 const videoFile = new VideoFileModel(videoFileData)
202 const videoDir = CONFIG.STORAGE.VIDEOS_DIR
203 const destination = join(videoDir, video.getVideoFilename(videoFile))
205 await renamePromise(videoPhysicalFile.path, destination)
206 // This is important in case if there is another attempt in the retry process
207 videoPhysicalFile.filename = video.getVideoFilename(videoFile)
208 videoPhysicalFile.path = destination
210 // Process thumbnail or create it from the video
211 const thumbnailField = req.files['thumbnailfile']
212 if (thumbnailField) {
213 const thumbnailPhysicalFile = thumbnailField[0]
214 await processImage(thumbnailPhysicalFile, join(CONFIG.STORAGE.THUMBNAILS_DIR, video.getThumbnailName()), THUMBNAILS_SIZE)
216 await video.createThumbnail(videoFile)
219 // Process preview or create it from the video
220 const previewField = req.files['previewfile']
222 const previewPhysicalFile = previewField[0]
223 await processImage(previewPhysicalFile, join(CONFIG.STORAGE.PREVIEWS_DIR, video.getPreviewName()), PREVIEWS_SIZE)
225 await video.createPreview(videoFile)
228 await video.createTorrentAndSetInfoHash(videoFile)
230 const videoCreated = await sequelizeTypescript.transaction(async t => {
231 const sequelizeOptions = { transaction: t }
233 const videoCreated = await video.save(sequelizeOptions)
234 // Do not forget to add video channel information to the created video
235 videoCreated.VideoChannel = res.locals.videoChannel
237 videoFile.videoId = video.id
238 await videoFile.save(sequelizeOptions)
240 video.VideoFiles = [ videoFile ]
242 if (videoInfo.tags) {
243 const tagInstances = await TagModel.findOrCreateTags(videoInfo.tags, t)
245 await video.$set('Tags', tagInstances, sequelizeOptions)
246 video.Tags = tagInstances
249 // Let transcoding job send the video to friends because the video file extension might change
250 if (CONFIG.TRANSCODING.ENABLED === true) return videoCreated
251 // Don't send video to remote servers, it is private
252 if (video.privacy === VideoPrivacy.PRIVATE) return videoCreated
254 await sendCreateVideo(video, t)
255 await shareVideoByServerAndChannel(video, t)
257 logger.info('Video with name %s and uuid %s created.', videoInfo.name, videoCreated.uuid)
262 if (CONFIG.TRANSCODING.ENABLED === true) {
263 // Put uuid because we don't have id auto incremented for now
265 videoUUID: videoCreated.uuid
268 await JobQueue.Instance.createJob({ type: 'video-file', payload: dataInput })
274 async function updateVideoRetryWrapper (req: express.Request, res: express.Response, next: express.NextFunction) {
276 arguments: [ req, res ],
277 errorMessage: 'Cannot update the video with many retries.'
280 await retryTransactionWrapper(updateVideo, options)
282 return res.type('json').status(204).end()
285 async function updateVideo (req: express.Request, res: express.Response) {
286 const videoInstance: VideoModel = res.locals.video
287 const videoFieldsSave = videoInstance.toJSON()
288 const videoInfoToUpdate: VideoUpdate = req.body
289 const wasPrivateVideo = videoInstance.privacy === VideoPrivacy.PRIVATE
291 // Process thumbnail or create it from the video
292 if (req.files && req.files['thumbnailfile']) {
293 const thumbnailPhysicalFile = req.files['thumbnailfile'][0]
294 await processImage(thumbnailPhysicalFile, join(CONFIG.STORAGE.THUMBNAILS_DIR, videoInstance.getThumbnailName()), THUMBNAILS_SIZE)
297 // Process preview or create it from the video
298 if (req.files && req.files['previewfile']) {
299 const previewPhysicalFile = req.files['previewfile'][0]
300 await processImage(previewPhysicalFile, join(CONFIG.STORAGE.PREVIEWS_DIR, videoInstance.getPreviewName()), PREVIEWS_SIZE)
304 await sequelizeTypescript.transaction(async t => {
305 const sequelizeOptions = {
309 if (videoInfoToUpdate.name !== undefined) videoInstance.set('name', videoInfoToUpdate.name)
310 if (videoInfoToUpdate.category !== undefined) videoInstance.set('category', videoInfoToUpdate.category)
311 if (videoInfoToUpdate.licence !== undefined) videoInstance.set('licence', videoInfoToUpdate.licence)
312 if (videoInfoToUpdate.language !== undefined) videoInstance.set('language', videoInfoToUpdate.language)
313 if (videoInfoToUpdate.nsfw !== undefined) videoInstance.set('nsfw', videoInfoToUpdate.nsfw)
314 if (videoInfoToUpdate.support !== undefined) videoInstance.set('support', videoInfoToUpdate.support)
315 if (videoInfoToUpdate.description !== undefined) videoInstance.set('description', videoInfoToUpdate.description)
316 if (videoInfoToUpdate.commentsEnabled !== undefined) videoInstance.set('commentsEnabled', videoInfoToUpdate.commentsEnabled)
317 if (videoInfoToUpdate.privacy !== undefined) {
318 const newPrivacy = parseInt(videoInfoToUpdate.privacy.toString(), 10)
319 videoInstance.set('privacy', newPrivacy)
321 if (wasPrivateVideo === true && newPrivacy !== VideoPrivacy.PRIVATE) {
322 videoInstance.set('publishedAt', new Date())
326 const videoInstanceUpdated = await videoInstance.save(sequelizeOptions)
328 if (videoInfoToUpdate.tags) {
329 const tagInstances = await TagModel.findOrCreateTags(videoInfoToUpdate.tags, t)
331 await videoInstance.$set('Tags', tagInstances, sequelizeOptions)
332 videoInstance.Tags = tagInstances
335 // Now we'll update the video's meta data to our friends
336 if (wasPrivateVideo === false) {
337 await sendUpdateVideo(videoInstanceUpdated, t)
340 // Video is not private anymore, send a create action to remote servers
341 if (wasPrivateVideo === true && videoInstanceUpdated.privacy !== VideoPrivacy.PRIVATE) {
342 await sendCreateVideo(videoInstanceUpdated, t)
343 await shareVideoByServerAndChannel(videoInstanceUpdated, t)
347 logger.info('Video with name %s and uuid %s updated.', videoInstance.name, videoInstance.uuid)
349 // Force fields we want to update
350 // If the transaction is retried, sequelize will think the object has not changed
351 // So it will skip the SQL request, even if the last one was ROLLBACKed!
352 resetSequelizeInstance(videoInstance, videoFieldsSave)
358 function getVideo (req: express.Request, res: express.Response) {
359 const videoInstance = res.locals.video
361 return res.json(videoInstance.toFormattedDetailsJSON())
364 async function viewVideo (req: express.Request, res: express.Response) {
365 const videoInstance = res.locals.video
368 const exists = await Redis.Instance.isViewExists(ip, videoInstance.uuid)
370 logger.debug('View for ip %s and video %s already exists.', ip, videoInstance.uuid)
371 return res.status(204).end()
374 await videoInstance.increment('views')
375 await Redis.Instance.setView(ip, videoInstance.uuid)
377 const serverAccount = await getServerActor()
379 await sendCreateView(serverAccount, videoInstance, undefined)
381 return res.status(204).end()
384 async function getVideoDescription (req: express.Request, res: express.Response) {
385 const videoInstance = res.locals.video
388 if (videoInstance.isOwned()) {
389 description = videoInstance.description
391 description = await fetchRemoteVideoDescription(videoInstance)
394 return res.json({ description })
397 async function listVideos (req: express.Request, res: express.Response, next: express.NextFunction) {
398 const resultList = await VideoModel.listForApi({
399 start: req.query.start,
400 count: req.query.count,
401 sort: req.query.sort,
402 hideNSFW: isNSFWHidden(res),
403 filter: req.query.filter as VideoFilter,
407 return res.json(getFormattedObjects(resultList.data, resultList.total))
410 async function removeVideoRetryWrapper (req: express.Request, res: express.Response, next: express.NextFunction) {
412 arguments: [ req, res ],
413 errorMessage: 'Cannot remove the video with many retries.'
416 await retryTransactionWrapper(removeVideo, options)
418 return res.type('json').status(204).end()
421 async function removeVideo (req: express.Request, res: express.Response) {
422 const videoInstance: VideoModel = res.locals.video
424 await sequelizeTypescript.transaction(async t => {
425 await videoInstance.destroy({ transaction: t })
428 logger.info('Video with name %s and uuid %s deleted.', videoInstance.name, videoInstance.uuid)
431 async function searchVideos (req: express.Request, res: express.Response, next: express.NextFunction) {
432 const resultList = await VideoModel.searchAndPopulateAccountAndServer(
433 req.query.search as string,
434 req.query.start as number,
435 req.query.count as number,
436 req.query.sort as VideoSortField,
440 return res.json(getFormattedObjects(resultList.data, resultList.total))