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',
90 videosUpdateValidator,
91 updateVideoRetryWrapper
93 videosRouter.post('/',
99 videosRouter.get('/:id',
104 videosRouter.delete('/:id',
106 videosRemoveValidator,
110 videosRouter.get('/search/:value',
111 videosSearchValidator,
120 // ---------------------------------------------------------------------------
126 // ---------------------------------------------------------------------------
128 function listVideoCategories (req: express.Request, res: express.Response, next: express.NextFunction) {
129 res.json(VIDEO_CATEGORIES)
132 function listVideoLicences (req: express.Request, res: express.Response, next: express.NextFunction) {
133 res.json(VIDEO_LICENCES)
136 function listVideoLanguages (req: express.Request, res: express.Response, next: express.NextFunction) {
137 res.json(VIDEO_LANGUAGES)
140 // Wrapper to video add that retry the function if there is a database error
141 // We need this because we run the transaction in SERIALIZABLE isolation that can fail
142 function addVideoRetryWrapper (req: express.Request, res: express.Response, next: express.NextFunction) {
144 arguments: [ req, res, req.files.videofile[0] ],
145 errorMessage: 'Cannot insert the video with many retries.'
148 retryTransactionWrapper(addVideo, options, function (err) {
149 if (err) return next(err)
151 // TODO : include Location of the new video -> 201
152 return res.type('json').status(204).end()
156 function addVideo (req: express.Request, res: express.Response, videoFile: Express.Multer.File, finalCallback: (err: Error) => void) {
157 const videoInfos = req.body
161 startSerializableTransaction,
163 function findOrCreateAuthor (t, callback) {
164 const user = res.locals.oauth.token.User
166 const name = user.username
167 // null because it is OUR pod
169 const userId = user.id
171 db.Author.findOrCreateAuthor(name, podId, userId, t, function (err, authorInstance) {
172 return callback(err, t, authorInstance)
176 function findOrCreateTags (t, author, callback) {
177 const tags = videoInfos.tags
179 db.Tag.findOrCreateTags(tags, t, function (err, tagInstances) {
180 return callback(err, t, author, tagInstances)
184 function createVideoObject (t, author, tagInstances, callback) {
186 name: videoInfos.name,
188 extname: path.extname(videoFile.filename),
189 category: videoInfos.category,
190 licence: videoInfos.licence,
191 language: videoInfos.language,
192 nsfw: videoInfos.nsfw,
193 description: videoInfos.description,
194 duration: videoFile['duration'], // duration was added by a previous middleware
198 const video = db.Video.build(videoData)
200 return callback(null, t, author, tagInstances, video)
203 // Set the videoname the same as the id
204 function renameVideoFile (t, author, tagInstances, video, callback) {
205 const videoDir = CONFIG.STORAGE.VIDEOS_DIR
206 const source = path.join(videoDir, videoFile.filename)
207 const destination = path.join(videoDir, video.getVideoFilename())
209 fs.rename(source, destination, function (err) {
210 if (err) return callback(err)
212 // This is important in case if there is another attempt
213 videoFile.filename = video.getVideoFilename()
214 return callback(null, t, author, tagInstances, video)
218 function insertVideoIntoDB (t, author, tagInstances, video, callback) {
219 const options = { transaction: t }
221 // Add tags association
222 video.save(options).asCallback(function (err, videoCreated) {
223 if (err) return callback(err)
225 // Do not forget to add Author informations to the created video
226 videoCreated.Author = author
228 return callback(err, t, tagInstances, videoCreated)
232 function associateTagsToVideo (t, tagInstances, video, callback) {
233 const options = { transaction: t }
235 video.setTags(tagInstances, options).asCallback(function (err) {
236 video.Tags = tagInstances
238 return callback(err, t, video)
242 function sendToFriends (t, video, callback) {
243 // Let transcoding job send the video to friends because the videofile extension might change
244 if (CONFIG.TRANSCODING.ENABLED === true) return callback(null, t)
246 video.toAddRemoteJSON(function (err, remoteVideo) {
247 if (err) return callback(err)
249 // Now we'll add the video's meta data to our friends
250 addVideoToFriends(remoteVideo, t, function (err) {
251 return callback(err, t)
258 ], function andFinally (err: Error, t: Sequelize.Transaction) {
260 // This is just a debug because we will retry the insert
261 logger.debug('Cannot insert the video.', { error: err })
262 return rollbackTransaction(err, t, finalCallback)
265 logger.info('Video with name %s created.', videoInfos.name)
266 return finalCallback(null)
270 function updateVideoRetryWrapper (req: express.Request, res: express.Response, next: express.NextFunction) {
272 arguments: [ req, res ],
273 errorMessage: 'Cannot update the video with many retries.'
276 retryTransactionWrapper(updateVideo, options, function (err) {
277 if (err) return next(err)
279 // TODO : include Location of the new video -> 201
280 return res.type('json').status(204).end()
284 function updateVideo (req: express.Request, res: express.Response, finalCallback: (err: Error) => void) {
285 const videoInstance = res.locals.video
286 const videoFieldsSave = videoInstance.toJSON()
287 const videoInfosToUpdate = req.body
291 startSerializableTransaction,
293 function findOrCreateTags (t, callback) {
294 if (videoInfosToUpdate.tags) {
295 db.Tag.findOrCreateTags(videoInfosToUpdate.tags, t, function (err, tagInstances) {
296 return callback(err, t, tagInstances)
299 return callback(null, t, null)
303 function updateVideoIntoDB (t, tagInstances, callback) {
308 if (videoInfosToUpdate.name !== undefined) videoInstance.set('name', videoInfosToUpdate.name)
309 if (videoInfosToUpdate.category !== undefined) videoInstance.set('category', videoInfosToUpdate.category)
310 if (videoInfosToUpdate.licence !== undefined) videoInstance.set('licence', videoInfosToUpdate.licence)
311 if (videoInfosToUpdate.language !== undefined) videoInstance.set('language', videoInfosToUpdate.language)
312 if (videoInfosToUpdate.nsfw !== undefined) videoInstance.set('nsfw', videoInfosToUpdate.nsfw)
313 if (videoInfosToUpdate.description !== undefined) videoInstance.set('description', videoInfosToUpdate.description)
315 videoInstance.save(options).asCallback(function (err) {
316 return callback(err, t, tagInstances)
320 function associateTagsToVideo (t, tagInstances, callback) {
322 const options = { transaction: t }
324 videoInstance.setTags(tagInstances, options).asCallback(function (err) {
325 videoInstance.Tags = tagInstances
327 return callback(err, t)
330 return callback(null, t)
334 function sendToFriends (t, callback) {
335 const json = videoInstance.toUpdateRemoteJSON()
337 // Now we'll update the video's meta data to our friends
338 updateVideoToFriends(json, t, function (err) {
339 return callback(err, t)
345 ], function andFinally (err: Error, t: Sequelize.Transaction) {
347 logger.debug('Cannot update the video.', { error: err })
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 Object.keys(videoFieldsSave).forEach(function (key) {
353 const value = videoFieldsSave[key]
354 videoInstance.set(key, value)
357 return rollbackTransaction(err, t, finalCallback)
360 logger.info('Video with name %s updated.', videoInfosToUpdate.name)
361 return finalCallback(null)
365 function getVideo (req: express.Request, res: express.Response, next: express.NextFunction) {
366 const videoInstance = res.locals.video
368 if (videoInstance.isOwned()) {
369 // The increment is done directly in the database, not using the instance value
370 videoInstance.increment('views').asCallback(function (err) {
372 logger.error('Cannot add view to video %d.', videoInstance.id)
376 // FIXME: make a real view system
377 // For example, only add a view when a user watch a video during 30s etc
379 videoId: videoInstance.id,
380 type: REQUEST_VIDEO_QADU_TYPES.VIEWS
382 quickAndDirtyUpdateVideoToFriends(qaduParams)
385 // Just send the event to our friends
386 const eventParams = {
387 videoId: videoInstance.id,
388 type: REQUEST_VIDEO_EVENT_TYPES.VIEWS
390 addEventToRemoteVideo(eventParams)
393 // Do not wait the view system
394 res.json(videoInstance.toFormatedJSON())
397 function listVideos (req: express.Request, res: express.Response, next: express.NextFunction) {
398 db.Video.listForApi(req.query.start, req.query.count, req.query.sort, function (err, videosList, videosTotal) {
399 if (err) return next(err)
401 res.json(getFormatedObjects(videosList, videosTotal))
405 function removeVideo (req: express.Request, res: express.Response, next: express.NextFunction) {
406 const videoInstance = res.locals.video
408 videoInstance.destroy().asCallback(function (err) {
410 logger.error('Errors when removed the video.', { error: err })
414 return res.type('json').status(204).end()
418 function searchVideos (req: express.Request, res: express.Response, next: express.NextFunction) {
419 db.Video.searchAndPopulateAuthorAndPodAndTags(
420 req.params.value, req.query.field, req.query.start, req.query.count, req.query.sort,
421 function (err, videosList, videosTotal) {
422 if (err) return next(err)
424 res.json(getFormatedObjects(videosList, videosTotal))