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 { getVideoFileHeight } from '../../../helpers/ffmpeg-utils'
7 import { processImage } from '../../../helpers/image-utils'
8 import { logger } from '../../../helpers/logger'
9 import { createReqFiles, getFormattedObjects, getServerActor, resetSequelizeInstance } from '../../../helpers/utils'
21 } from '../../../initializers'
22 import { fetchRemoteVideoDescription, getVideoActivityPubUrl, shareVideoByServerAndChannel } from '../../../lib/activitypub'
23 import { sendCreateVideo, sendCreateViewToOrigin, sendCreateViewToVideoFollowers, sendUpdateVideo } from '../../../lib/activitypub/send'
24 import { JobQueue } from '../../../lib/job-queue'
33 videosRemoveValidator,
34 videosSearchValidator,
37 } from '../../../middlewares'
38 import { TagModel } from '../../../models/video/tag'
39 import { VideoModel } from '../../../models/video/video'
40 import { VideoFileModel } from '../../../models/video/video-file'
41 import { abuseVideoRouter } from './abuse'
42 import { blacklistRouter } from './blacklist'
43 import { videoChannelRouter } from './channel'
44 import { videoCommentRouter } from './comment'
45 import { rateVideoRouter } from './rate'
47 const videosRouter = express.Router()
49 const reqVideoFileAdd = createReqFiles(
50 [ 'videofile', 'thumbnailfile', 'previewfile' ],
51 Object.assign({}, VIDEO_MIMETYPE_EXT, IMAGE_MIMETYPE_EXT),
53 videofile: CONFIG.STORAGE.VIDEOS_DIR,
54 thumbnailfile: CONFIG.STORAGE.THUMBNAILS_DIR,
55 previewfile: CONFIG.STORAGE.PREVIEWS_DIR
58 const reqVideoFileUpdate = createReqFiles(
59 [ 'thumbnailfile', 'previewfile' ],
62 thumbnailfile: CONFIG.STORAGE.THUMBNAILS_DIR,
63 previewfile: CONFIG.STORAGE.PREVIEWS_DIR
67 videosRouter.use('/', abuseVideoRouter)
68 videosRouter.use('/', blacklistRouter)
69 videosRouter.use('/', rateVideoRouter)
70 videosRouter.use('/', videoChannelRouter)
71 videosRouter.use('/', videoCommentRouter)
73 videosRouter.get('/categories', listVideoCategories)
74 videosRouter.get('/licences', listVideoLicences)
75 videosRouter.get('/languages', listVideoLanguages)
76 videosRouter.get('/privacies', listVideoPrivacies)
83 asyncMiddleware(listVideos)
85 videosRouter.get('/search',
86 videosSearchValidator,
91 asyncMiddleware(searchVideos)
93 videosRouter.put('/:id',
96 asyncMiddleware(videosUpdateValidator),
97 asyncMiddleware(updateVideoRetryWrapper)
99 videosRouter.post('/upload',
102 asyncMiddleware(videosAddValidator),
103 asyncMiddleware(addVideoRetryWrapper)
106 videosRouter.get('/:id/description',
107 asyncMiddleware(videosGetValidator),
108 asyncMiddleware(getVideoDescription)
110 videosRouter.get('/:id',
111 asyncMiddleware(videosGetValidator),
114 videosRouter.post('/:id/views',
115 asyncMiddleware(videosGetValidator),
116 asyncMiddleware(viewVideo)
119 videosRouter.delete('/:id',
121 asyncMiddleware(videosRemoveValidator),
122 asyncMiddleware(removeVideoRetryWrapper)
125 // ---------------------------------------------------------------------------
131 // ---------------------------------------------------------------------------
133 function listVideoCategories (req: express.Request, res: express.Response) {
134 res.json(VIDEO_CATEGORIES)
137 function listVideoLicences (req: express.Request, res: express.Response) {
138 res.json(VIDEO_LICENCES)
141 function listVideoLanguages (req: express.Request, res: express.Response) {
142 res.json(VIDEO_LANGUAGES)
145 function listVideoPrivacies (req: express.Request, res: express.Response) {
146 res.json(VIDEO_PRIVACIES)
149 // Wrapper to video add that retry the function if there is a database error
150 // We need this because we run the transaction in SERIALIZABLE isolation that can fail
151 async function addVideoRetryWrapper (req: express.Request, res: express.Response, next: express.NextFunction) {
153 arguments: [ req, res, req.files['videofile'][0] ],
154 errorMessage: 'Cannot insert the video with many retries.'
157 const video = await retryTransactionWrapper(addVideo, options)
167 async function addVideo (req: express.Request, res: express.Response, videoPhysicalFile: Express.Multer.File) {
168 const videoInfo: VideoCreate = req.body
170 // Prepare data so we don't block the transaction
172 name: videoInfo.name,
174 extname: extname(videoPhysicalFile.filename),
175 category: videoInfo.category,
176 licence: videoInfo.licence,
177 language: videoInfo.language,
178 commentsEnabled: videoInfo.commentsEnabled,
179 nsfw: videoInfo.nsfw,
180 description: videoInfo.description,
181 privacy: videoInfo.privacy,
182 duration: videoPhysicalFile['duration'], // duration was added by a previous middleware
183 channelId: res.locals.videoChannel.id
185 const video = new VideoModel(videoData)
186 video.url = getVideoActivityPubUrl(video)
188 const videoFileHeight = await getVideoFileHeight(videoPhysicalFile.path)
190 const videoFileData = {
191 extname: extname(videoPhysicalFile.filename),
192 resolution: videoFileHeight,
193 size: videoPhysicalFile.size
195 const videoFile = new VideoFileModel(videoFileData)
196 const videoDir = CONFIG.STORAGE.VIDEOS_DIR
197 const destination = join(videoDir, video.getVideoFilename(videoFile))
199 await renamePromise(videoPhysicalFile.path, destination)
200 // This is important in case if there is another attempt in the retry process
201 videoPhysicalFile.filename = video.getVideoFilename(videoFile)
202 videoPhysicalFile.path = destination
204 // Process thumbnail or create it from the video
205 const thumbnailField = req.files['thumbnailfile']
206 if (thumbnailField) {
207 const thumbnailPhysicalFile = thumbnailField[0]
208 await processImage(thumbnailPhysicalFile, join(CONFIG.STORAGE.THUMBNAILS_DIR, video.getThumbnailName()), THUMBNAILS_SIZE)
210 await video.createThumbnail(videoFile)
213 // Process preview or create it from the video
214 const previewField = req.files['previewfile']
216 const previewPhysicalFile = previewField[0]
217 await processImage(previewPhysicalFile, join(CONFIG.STORAGE.PREVIEWS_DIR, video.getPreviewName()), PREVIEWS_SIZE)
219 await video.createPreview(videoFile)
222 await video.createTorrentAndSetInfoHash(videoFile)
224 const videoCreated = await sequelizeTypescript.transaction(async t => {
225 const sequelizeOptions = { transaction: t }
227 const videoCreated = await video.save(sequelizeOptions)
228 // Do not forget to add video channel information to the created video
229 videoCreated.VideoChannel = res.locals.videoChannel
231 videoFile.videoId = video.id
232 await videoFile.save(sequelizeOptions)
234 video.VideoFiles = [ videoFile ]
236 if (videoInfo.tags) {
237 const tagInstances = await TagModel.findOrCreateTags(videoInfo.tags, t)
239 await video.$set('Tags', tagInstances, sequelizeOptions)
240 video.Tags = tagInstances
243 // Let transcoding job send the video to friends because the video file extension might change
244 if (CONFIG.TRANSCODING.ENABLED === true) return videoCreated
245 // Don't send video to remote servers, it is private
246 if (video.privacy === VideoPrivacy.PRIVATE) return videoCreated
248 await sendCreateVideo(video, t)
249 await shareVideoByServerAndChannel(video, t)
251 logger.info('Video with name %s and uuid %s created.', videoInfo.name, videoCreated.uuid)
256 if (CONFIG.TRANSCODING.ENABLED === true) {
257 // Put uuid because we don't have id auto incremented for now
259 videoUUID: videoCreated.uuid
262 await JobQueue.Instance.createJob({ type: 'video-file', payload: dataInput })
268 async function updateVideoRetryWrapper (req: express.Request, res: express.Response, next: express.NextFunction) {
270 arguments: [ req, res ],
271 errorMessage: 'Cannot update the video with many retries.'
274 await retryTransactionWrapper(updateVideo, options)
276 return res.type('json').status(204).end()
279 async function updateVideo (req: express.Request, res: express.Response) {
280 const videoInstance: VideoModel = res.locals.video
281 const videoFieldsSave = videoInstance.toJSON()
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 = {
303 if (videoInfoToUpdate.name !== undefined) videoInstance.set('name', videoInfoToUpdate.name)
304 if (videoInfoToUpdate.category !== undefined) videoInstance.set('category', videoInfoToUpdate.category)
305 if (videoInfoToUpdate.licence !== undefined) videoInstance.set('licence', videoInfoToUpdate.licence)
306 if (videoInfoToUpdate.language !== undefined) videoInstance.set('language', videoInfoToUpdate.language)
307 if (videoInfoToUpdate.nsfw !== undefined) videoInstance.set('nsfw', videoInfoToUpdate.nsfw)
308 if (videoInfoToUpdate.privacy !== undefined) videoInstance.set('privacy', parseInt(videoInfoToUpdate.privacy.toString(), 10))
309 if (videoInfoToUpdate.description !== undefined) videoInstance.set('description', videoInfoToUpdate.description)
310 if (videoInfoToUpdate.commentsEnabled !== undefined) videoInstance.set('commentsEnabled', videoInfoToUpdate.commentsEnabled)
312 const videoInstanceUpdated = await videoInstance.save(sequelizeOptions)
314 if (videoInfoToUpdate.tags) {
315 const tagInstances = await TagModel.findOrCreateTags(videoInfoToUpdate.tags, t)
317 await videoInstance.$set('Tags', tagInstances, sequelizeOptions)
318 videoInstance.Tags = tagInstances
321 // Now we'll update the video's meta data to our friends
322 if (wasPrivateVideo === false) {
323 await sendUpdateVideo(videoInstanceUpdated, t)
326 // Video is not private anymore, send a create action to remote servers
327 if (wasPrivateVideo === true && videoInstanceUpdated.privacy !== VideoPrivacy.PRIVATE) {
328 await sendCreateVideo(videoInstanceUpdated, t)
329 await shareVideoByServerAndChannel(videoInstanceUpdated, t)
333 logger.info('Video with name %s and uuid %s updated.', videoInstance.name, videoInstance.uuid)
335 // Force fields we want to update
336 // If the transaction is retried, sequelize will think the object has not changed
337 // So it will skip the SQL request, even if the last one was ROLLBACKed!
338 resetSequelizeInstance(videoInstance, videoFieldsSave)
344 function getVideo (req: express.Request, res: express.Response) {
345 const videoInstance = res.locals.video
347 return res.json(videoInstance.toFormattedDetailsJSON())
350 async function viewVideo (req: express.Request, res: express.Response) {
351 const videoInstance = res.locals.video
353 await videoInstance.increment('views')
354 const serverAccount = await getServerActor()
356 if (videoInstance.isOwned()) {
357 await sendCreateViewToVideoFollowers(serverAccount, videoInstance, undefined)
359 await sendCreateViewToOrigin(serverAccount, videoInstance, undefined)
362 return res.status(204).end()
365 async function getVideoDescription (req: express.Request, res: express.Response) {
366 const videoInstance = res.locals.video
369 if (videoInstance.isOwned()) {
370 description = videoInstance.description
372 description = await fetchRemoteVideoDescription(videoInstance)
375 return res.json({ description })
378 async function listVideos (req: express.Request, res: express.Response, next: express.NextFunction) {
379 const resultList = await VideoModel.listForApi(req.query.start, req.query.count, req.query.sort)
381 return res.json(getFormattedObjects(resultList.data, resultList.total))
384 async function removeVideoRetryWrapper (req: express.Request, res: express.Response, next: express.NextFunction) {
386 arguments: [ req, res ],
387 errorMessage: 'Cannot remove the video with many retries.'
390 await retryTransactionWrapper(removeVideo, options)
392 return res.type('json').status(204).end()
395 async function removeVideo (req: express.Request, res: express.Response) {
396 const videoInstance: VideoModel = res.locals.video
398 await sequelizeTypescript.transaction(async t => {
399 await videoInstance.destroy({ transaction: t })
402 logger.info('Video with name %s and uuid %s deleted.', videoInstance.name, videoInstance.uuid)
405 async function searchVideos (req: express.Request, res: express.Response, next: express.NextFunction) {
406 const resultList = await VideoModel.searchAndPopulateAccountAndServerAndTags(
413 return res.json(getFormattedObjects(resultList.data, resultList.total))