1 import * as express from 'express'
2 import * as multer from 'multer'
3 import { extname, join } from 'path'
5 import { database as db } from '../../../initializers/database'
8 REQUEST_VIDEO_QADU_TYPES,
9 REQUEST_VIDEO_EVENT_TYPES,
13 } from '../../../initializers'
15 addEventToRemoteVideo,
16 quickAndDirtyUpdateVideoToFriends,
20 fetchRemoteDescription
29 videosUpdateValidator,
30 videosSearchValidator,
33 videosRemoveValidator,
35 } from '../../../middlewares'
38 retryTransactionWrapper,
43 resetSequelizeInstance
44 } from '../../../helpers'
45 import { VideoInstance } from '../../../models'
46 import { VideoCreate, VideoUpdate } from '../../../../shared'
48 import { abuseVideoRouter } from './abuse'
49 import { blacklistRouter } from './blacklist'
50 import { rateVideoRouter } from './rate'
51 import { videoChannelRouter } from './channel'
53 const videosRouter = express.Router()
55 // multer configuration
56 const storage = multer.diskStorage({
57 destination: (req, file, cb) => {
58 cb(null, CONFIG.STORAGE.VIDEOS_DIR)
61 filename: (req, file, cb) => {
63 if (file.mimetype === 'video/webm') extension = 'webm'
64 else if (file.mimetype === 'video/mp4') extension = 'mp4'
65 else if (file.mimetype === 'video/ogg') extension = 'ogv'
66 generateRandomString(16)
67 .then(randomString => {
68 cb(null, randomString + '.' + extension)
71 logger.error('Cannot generate random string for file name.', err)
77 const reqFiles = multer({ storage: storage }).fields([{ name: 'videofile', maxCount: 1 }])
79 videosRouter.use('/', abuseVideoRouter)
80 videosRouter.use('/', blacklistRouter)
81 videosRouter.use('/', rateVideoRouter)
82 videosRouter.use('/', videoChannelRouter)
84 videosRouter.get('/categories', listVideoCategories)
85 videosRouter.get('/licences', listVideoLicences)
86 videosRouter.get('/languages', listVideoLanguages)
93 asyncMiddleware(listVideos)
95 videosRouter.put('/:id',
97 videosUpdateValidator,
98 asyncMiddleware(updateVideoRetryWrapper)
100 videosRouter.post('/upload',
104 asyncMiddleware(addVideoRetryWrapper)
107 videosRouter.get('/:id/description',
109 asyncMiddleware(getVideoDescription)
111 videosRouter.get('/:id',
116 videosRouter.delete('/:id',
118 videosRemoveValidator,
119 asyncMiddleware(removeVideoRetryWrapper)
122 videosRouter.get('/search/:value',
123 videosSearchValidator,
129 asyncMiddleware(searchVideos)
132 // ---------------------------------------------------------------------------
138 // ---------------------------------------------------------------------------
140 function listVideoCategories (req: express.Request, res: express.Response) {
141 res.json(VIDEO_CATEGORIES)
144 function listVideoLicences (req: express.Request, res: express.Response) {
145 res.json(VIDEO_LICENCES)
148 function listVideoLanguages (req: express.Request, res: express.Response) {
149 res.json(VIDEO_LANGUAGES)
152 // Wrapper to video add that retry the function if there is a database error
153 // We need this because we run the transaction in SERIALIZABLE isolation that can fail
154 async function addVideoRetryWrapper (req: express.Request, res: express.Response, next: express.NextFunction) {
156 arguments: [ req, res, req.files['videofile'][0] ],
157 errorMessage: 'Cannot insert the video with many retries.'
160 await retryTransactionWrapper(addVideo, options)
162 // TODO : include Location of the new video -> 201
163 res.type('json').status(204).end()
166 async function addVideo (req: express.Request, res: express.Response, videoPhysicalFile: Express.Multer.File) {
167 const videoInfo: VideoCreate = req.body
170 await db.sequelize.transaction(async t => {
171 const sequelizeOptions = { transaction: t }
174 name: videoInfo.name,
176 extname: extname(videoPhysicalFile.filename),
177 category: videoInfo.category,
178 licence: videoInfo.licence,
179 language: videoInfo.language,
180 nsfw: videoInfo.nsfw,
181 description: videoInfo.description,
182 duration: videoPhysicalFile['duration'], // duration was added by a previous middleware
183 channelId: res.locals.videoChannel.id
185 const video = db.Video.build(videoData)
187 const videoFilePath = join(CONFIG.STORAGE.VIDEOS_DIR, videoPhysicalFile.filename)
188 const videoFileHeight = await getVideoFileHeight(videoFilePath)
190 const videoFileData = {
191 extname: extname(videoPhysicalFile.filename),
192 resolution: videoFileHeight,
193 size: videoPhysicalFile.size
195 const videoFile = db.VideoFile.build(videoFileData)
196 const videoDir = CONFIG.STORAGE.VIDEOS_DIR
197 const source = join(videoDir, videoPhysicalFile.filename)
198 const destination = join(videoDir, video.getVideoFilename(videoFile))
200 await renamePromise(source, destination)
201 // This is important in case if there is another attempt in the retry process
202 videoPhysicalFile.filename = video.getVideoFilename(videoFile)
207 video.createTorrentAndSetInfoHash(videoFile),
208 video.createThumbnail(videoFile),
209 video.createPreview(videoFile)
212 if (CONFIG.TRANSCODING.ENABLED === true) {
213 // Put uuid because we don't have id auto incremented for now
215 videoUUID: video.uuid
219 JobScheduler.Instance.createJob(t, 'videoFileOptimizer', dataInput)
222 await Promise.all(tasks)
224 const videoCreated = await video.save(sequelizeOptions)
225 // Do not forget to add video channel information to the created video
226 videoCreated.VideoChannel = res.locals.videoChannel
227 videoUUID = videoCreated.uuid
229 videoFile.videoId = video.id
231 await videoFile.save(sequelizeOptions)
232 video.VideoFiles = [videoFile]
234 if (videoInfo.tags) {
235 const tagInstances = await db.Tag.findOrCreateTags(videoInfo.tags, t)
237 await video.setTags(tagInstances, sequelizeOptions)
238 video.Tags = tagInstances
241 // Let transcoding job send the video to friends because the video file extension might change
242 if (CONFIG.TRANSCODING.ENABLED === true) return undefined
244 const remoteVideo = await video.toAddRemoteJSON()
245 // Now we'll add the video's meta data to our friends
246 return addVideoToFriends(remoteVideo, t)
249 logger.info('Video with name %s and uuid %s created.', videoInfo.name, videoUUID)
252 async function updateVideoRetryWrapper (req: express.Request, res: express.Response, next: express.NextFunction) {
254 arguments: [ req, res ],
255 errorMessage: 'Cannot update the video with many retries.'
258 await retryTransactionWrapper(updateVideo, options)
260 return res.type('json').status(204).end()
263 async function updateVideo (req: express.Request, res: express.Response) {
264 const videoInstance = res.locals.video
265 const videoFieldsSave = videoInstance.toJSON()
266 const videoInfoToUpdate: VideoUpdate = req.body
269 await db.sequelize.transaction(async t => {
270 const sequelizeOptions = {
274 if (videoInfoToUpdate.name !== undefined) videoInstance.set('name', videoInfoToUpdate.name)
275 if (videoInfoToUpdate.category !== undefined) videoInstance.set('category', videoInfoToUpdate.category)
276 if (videoInfoToUpdate.licence !== undefined) videoInstance.set('licence', videoInfoToUpdate.licence)
277 if (videoInfoToUpdate.language !== undefined) videoInstance.set('language', videoInfoToUpdate.language)
278 if (videoInfoToUpdate.nsfw !== undefined) videoInstance.set('nsfw', videoInfoToUpdate.nsfw)
279 if (videoInfoToUpdate.description !== undefined) videoInstance.set('description', videoInfoToUpdate.description)
281 await videoInstance.save(sequelizeOptions)
283 if (videoInfoToUpdate.tags) {
284 const tagInstances = await db.Tag.findOrCreateTags(videoInfoToUpdate.tags, t)
286 await videoInstance.setTags(tagInstances, sequelizeOptions)
287 videoInstance.Tags = tagInstances
290 const json = videoInstance.toUpdateRemoteJSON()
292 // Now we'll update the video's meta data to our friends
293 return updateVideoToFriends(json, t)
296 logger.info('Video with name %s and uuid %s updated.', videoInstance.name, videoInstance.uuid)
298 // Force fields we want to update
299 // If the transaction is retried, sequelize will think the object has not changed
300 // So it will skip the SQL request, even if the last one was ROLLBACKed!
301 resetSequelizeInstance(videoInstance, videoFieldsSave)
307 function getVideo (req: express.Request, res: express.Response) {
308 const videoInstance = res.locals.video
310 if (videoInstance.isOwned()) {
311 // The increment is done directly in the database, not using the instance value
312 // FIXME: make a real view system
313 // For example, only add a view when a user watch a video during 30s etc
314 videoInstance.increment('views')
317 videoId: videoInstance.id,
318 type: REQUEST_VIDEO_QADU_TYPES.VIEWS
320 return quickAndDirtyUpdateVideoToFriends(qaduParams)
322 .catch(err => logger.error('Cannot add view to video %s.', videoInstance.uuid, err))
324 // Just send the event to our friends
325 const eventParams = {
326 videoId: videoInstance.id,
327 type: REQUEST_VIDEO_EVENT_TYPES.VIEWS
329 addEventToRemoteVideo(eventParams)
330 .catch(err => logger.error('Cannot add event to remote video %s.', videoInstance.uuid, err))
333 // Do not wait the view system
334 return res.json(videoInstance.toFormattedDetailsJSON())
337 async function getVideoDescription (req: express.Request, res: express.Response) {
338 const videoInstance = res.locals.video
341 if (videoInstance.isOwned()) {
342 description = videoInstance.description
344 description = await fetchRemoteDescription(videoInstance)
347 return res.json({ description })
350 async function listVideos (req: express.Request, res: express.Response, next: express.NextFunction) {
351 const resultList = await db.Video.listForApi(req.query.start, req.query.count, req.query.sort)
353 return res.json(getFormattedObjects(resultList.data, resultList.total))
356 async function removeVideoRetryWrapper (req: express.Request, res: express.Response, next: express.NextFunction) {
358 arguments: [ req, res ],
359 errorMessage: 'Cannot remove the video with many retries.'
362 await retryTransactionWrapper(removeVideo, options)
364 return res.type('json').status(204).end()
367 async function removeVideo (req: express.Request, res: express.Response) {
368 const videoInstance: VideoInstance = res.locals.video
370 await db.sequelize.transaction(async t => {
371 await videoInstance.destroy({ transaction: t })
374 logger.info('Video with name %s and uuid %s deleted.', videoInstance.name, videoInstance.uuid)
377 async function searchVideos (req: express.Request, res: express.Response, next: express.NextFunction) {
378 const resultList = await db.Video.searchAndPopulateAuthorAndPodAndTags(
386 return res.json(getFormattedObjects(resultList.data, resultList.total))