1 import * as express from 'express'
2 import * as Sequelize from 'sequelize'
3 import * as fs from 'fs'
4 import * as multer from 'multer'
5 import * as path from 'path'
6 import { waterfall } from 'async'
8 import { database as db } from '../../../initializers/database'
11 REQUEST_VIDEO_QADU_TYPES,
12 REQUEST_VIDEO_EVENT_TYPES,
16 } from '../../../initializers'
18 addEventToRemoteVideo,
19 quickAndDirtyUpdateVideoToFriends,
30 videosUpdateValidator,
31 videosSearchValidator,
35 } from '../../../middlewares'
39 retryTransactionWrapper,
41 startSerializableTransaction,
44 } from '../../../helpers'
46 import { abuseVideoRouter } from './abuse'
47 import { blacklistRouter } from './blacklist'
48 import { rateVideoRouter } from './rate'
50 const videosRouter = express.Router()
52 // multer configuration
53 const storage = multer.diskStorage({
54 destination: function (req, file, cb) {
55 cb(null, CONFIG.STORAGE.VIDEOS_DIR)
58 filename: function (req, file, cb) {
60 if (file.mimetype === 'video/webm') extension = 'webm'
61 else if (file.mimetype === 'video/mp4') extension = 'mp4'
62 else if (file.mimetype === 'video/ogg') extension = 'ogv'
63 generateRandomString(16, function (err, randomString) {
64 const fieldname = err ? undefined : randomString
65 cb(null, fieldname + '.' + extension)
70 const reqFiles = multer({ storage: storage }).fields([{ name: 'videofile', maxCount: 1 }])
72 videosRouter.use('/', abuseVideoRouter)
73 videosRouter.use('/', blacklistRouter)
74 videosRouter.use('/', rateVideoRouter)
76 videosRouter.get('/categories', listVideoCategories)
77 videosRouter.get('/licences', listVideoLicences)
78 videosRouter.get('/languages', listVideoLanguages)
87 videosRouter.put('/:id',
89 videosUpdateValidator,
90 updateVideoRetryWrapper
92 videosRouter.post('/',
98 videosRouter.get('/:id',
103 videosRouter.delete('/:id',
105 videosRemoveValidator,
109 videosRouter.get('/search/:value',
110 videosSearchValidator,
119 // ---------------------------------------------------------------------------
125 // ---------------------------------------------------------------------------
127 function listVideoCategories (req: express.Request, res: express.Response, next: express.NextFunction) {
128 res.json(VIDEO_CATEGORIES)
131 function listVideoLicences (req: express.Request, res: express.Response, next: express.NextFunction) {
132 res.json(VIDEO_LICENCES)
135 function listVideoLanguages (req: express.Request, res: express.Response, next: express.NextFunction) {
136 res.json(VIDEO_LANGUAGES)
139 // Wrapper to video add that retry the function if there is a database error
140 // We need this because we run the transaction in SERIALIZABLE isolation that can fail
141 function addVideoRetryWrapper (req: express.Request, res: express.Response, next: express.NextFunction) {
143 arguments: [ req, res, req.files.videofile[0] ],
144 errorMessage: 'Cannot insert the video with many retries.'
147 retryTransactionWrapper(addVideo, options, function (err) {
148 if (err) return next(err)
150 // TODO : include Location of the new video -> 201
151 return res.type('json').status(204).end()
155 function addVideo (req: express.Request, res: express.Response, videoFile: Express.Multer.File, finalCallback: (err: Error) => void) {
156 const videoInfos = req.body
160 startSerializableTransaction,
162 function findOrCreateAuthor (t, callback) {
163 const user = res.locals.oauth.token.User
165 const name = user.username
166 // null because it is OUR pod
168 const userId = user.id
170 db.Author.findOrCreateAuthor(name, podId, userId, t, function (err, authorInstance) {
171 return callback(err, t, authorInstance)
175 function findOrCreateTags (t, author, callback) {
176 const tags = videoInfos.tags
178 db.Tag.findOrCreateTags(tags, t, function (err, tagInstances) {
179 return callback(err, t, author, tagInstances)
183 function createVideoObject (t, author, tagInstances, callback) {
185 name: videoInfos.name,
187 extname: path.extname(videoFile.filename),
188 category: videoInfos.category,
189 licence: videoInfos.licence,
190 language: videoInfos.language,
191 nsfw: videoInfos.nsfw,
192 description: videoInfos.description,
193 duration: videoFile['duration'], // duration was added by a previous middleware
197 const video = db.Video.build(videoData)
199 return callback(null, t, author, tagInstances, video)
202 // Set the videoname the same as the id
203 function renameVideoFile (t, author, tagInstances, video, callback) {
204 const videoDir = CONFIG.STORAGE.VIDEOS_DIR
205 const source = path.join(videoDir, videoFile.filename)
206 const destination = path.join(videoDir, video.getVideoFilename())
208 fs.rename(source, destination, function (err) {
209 if (err) return callback(err)
211 // This is important in case if there is another attempt
212 videoFile.filename = video.getVideoFilename()
213 return callback(null, t, author, tagInstances, video)
217 function insertVideoIntoDB (t, author, tagInstances, video, callback) {
218 const options = { transaction: t }
220 // Add tags association
221 video.save(options).asCallback(function (err, videoCreated) {
222 if (err) return callback(err)
224 // Do not forget to add Author informations to the created video
225 videoCreated.Author = author
227 return callback(err, t, tagInstances, videoCreated)
231 function associateTagsToVideo (t, tagInstances, video, callback) {
232 const options = { transaction: t }
234 video.setTags(tagInstances, options).asCallback(function (err) {
235 video.Tags = tagInstances
237 return callback(err, t, video)
241 function sendToFriends (t, video, callback) {
242 // Let transcoding job send the video to friends because the videofile extension might change
243 if (CONFIG.TRANSCODING.ENABLED === true) return callback(null, t)
245 video.toAddRemoteJSON(function (err, remoteVideo) {
246 if (err) return callback(err)
248 // Now we'll add the video's meta data to our friends
249 addVideoToFriends(remoteVideo, t, function (err) {
250 return callback(err, t)
257 ], function andFinally (err: Error, t: Sequelize.Transaction) {
259 // This is just a debug because we will retry the insert
260 logger.debug('Cannot insert the video.', { error: err })
261 return rollbackTransaction(err, t, finalCallback)
264 logger.info('Video with name %s created.', videoInfos.name)
265 return finalCallback(null)
269 function updateVideoRetryWrapper (req: express.Request, res: express.Response, next: express.NextFunction) {
271 arguments: [ req, res ],
272 errorMessage: 'Cannot update the video with many retries.'
275 retryTransactionWrapper(updateVideo, options, function (err) {
276 if (err) return next(err)
278 // TODO : include Location of the new video -> 201
279 return res.type('json').status(204).end()
283 function updateVideo (req: express.Request, res: express.Response, finalCallback: (err: Error) => void) {
284 const videoInstance = res.locals.video
285 const videoFieldsSave = videoInstance.toJSON()
286 const videoInfosToUpdate = req.body
290 startSerializableTransaction,
292 function findOrCreateTags (t, callback) {
293 if (videoInfosToUpdate.tags) {
294 db.Tag.findOrCreateTags(videoInfosToUpdate.tags, t, function (err, tagInstances) {
295 return callback(err, t, tagInstances)
298 return callback(null, t, null)
302 function updateVideoIntoDB (t, tagInstances, callback) {
307 if (videoInfosToUpdate.name !== undefined) videoInstance.set('name', videoInfosToUpdate.name)
308 if (videoInfosToUpdate.category !== undefined) videoInstance.set('category', videoInfosToUpdate.category)
309 if (videoInfosToUpdate.licence !== undefined) videoInstance.set('licence', videoInfosToUpdate.licence)
310 if (videoInfosToUpdate.language !== undefined) videoInstance.set('language', videoInfosToUpdate.language)
311 if (videoInfosToUpdate.nsfw !== undefined) videoInstance.set('nsfw', videoInfosToUpdate.nsfw)
312 if (videoInfosToUpdate.description !== undefined) videoInstance.set('description', videoInfosToUpdate.description)
314 videoInstance.save(options).asCallback(function (err) {
315 return callback(err, t, tagInstances)
319 function associateTagsToVideo (t, tagInstances, callback) {
321 const options = { transaction: t }
323 videoInstance.setTags(tagInstances, options).asCallback(function (err) {
324 videoInstance.Tags = tagInstances
326 return callback(err, t)
329 return callback(null, t)
333 function sendToFriends (t, callback) {
334 const json = videoInstance.toUpdateRemoteJSON()
336 // Now we'll update the video's meta data to our friends
337 updateVideoToFriends(json, t, function (err) {
338 return callback(err, t)
344 ], function andFinally (err: Error, t: Sequelize.Transaction) {
346 logger.debug('Cannot update the video.', { error: err })
348 // Force fields we want to update
349 // If the transaction is retried, sequelize will think the object has not changed
350 // So it will skip the SQL request, even if the last one was ROLLBACKed!
351 Object.keys(videoFieldsSave).forEach(function (key) {
352 const value = videoFieldsSave[key]
353 videoInstance.set(key, value)
356 return rollbackTransaction(err, t, finalCallback)
359 logger.info('Video with name %s updated.', videoInstance.name)
360 return finalCallback(null)
364 function getVideo (req: express.Request, res: express.Response, next: express.NextFunction) {
365 const videoInstance = res.locals.video
367 if (videoInstance.isOwned()) {
368 // The increment is done directly in the database, not using the instance value
369 videoInstance.increment('views').asCallback(function (err) {
371 logger.error('Cannot add view to video %d.', videoInstance.id)
375 // FIXME: make a real view system
376 // For example, only add a view when a user watch a video during 30s etc
378 videoId: videoInstance.id,
379 type: REQUEST_VIDEO_QADU_TYPES.VIEWS
381 quickAndDirtyUpdateVideoToFriends(qaduParams)
384 // Just send the event to our friends
385 const eventParams = {
386 videoId: videoInstance.id,
387 type: REQUEST_VIDEO_EVENT_TYPES.VIEWS
389 addEventToRemoteVideo(eventParams)
392 // Do not wait the view system
393 res.json(videoInstance.toFormatedJSON())
396 function listVideos (req: express.Request, res: express.Response, next: express.NextFunction) {
397 db.Video.listForApi(req.query.start, req.query.count, req.query.sort, function (err, videosList, videosTotal) {
398 if (err) return next(err)
400 res.json(getFormatedObjects(videosList, videosTotal))
404 function removeVideo (req: express.Request, res: express.Response, next: express.NextFunction) {
405 const videoInstance = res.locals.video
407 videoInstance.destroy().asCallback(function (err) {
409 logger.error('Errors when removed the video.', { error: err })
413 return res.type('json').status(204).end()
417 function searchVideos (req: express.Request, res: express.Response, next: express.NextFunction) {
418 db.Video.searchAndPopulateAuthorAndPodAndTags(
419 req.params.value, req.query.field, req.query.start, req.query.count, req.query.sort,
420 function (err, videosList, videosTotal) {
421 if (err) return next(err)
423 res.json(getFormatedObjects(videosList, videosTotal))