1 import * as express from 'express'
2 import * as Promise from 'bluebird'
3 import * as multer from 'multer'
4 import { extname, join } from 'path'
6 import { database as db } from '../../../initializers/database'
9 REQUEST_VIDEO_QADU_TYPES,
10 REQUEST_VIDEO_EVENT_TYPES,
14 } from '../../../initializers'
16 addEventToRemoteVideo,
17 quickAndDirtyUpdateVideoToFriends,
29 videosUpdateValidator,
30 videosSearchValidator,
34 } from '../../../middlewares'
37 retryTransactionWrapper,
41 } from '../../../helpers'
42 import { TagInstance } from '../../../models'
43 import { VideoCreate, VideoUpdate } from '../../../../shared'
45 import { abuseVideoRouter } from './abuse'
46 import { blacklistRouter } from './blacklist'
47 import { rateVideoRouter } from './rate'
48 import { VideoInstance } from '../../../models/video/video-interface'
50 const videosRouter = express.Router()
52 // multer configuration
53 const storage = multer.diskStorage({
54 destination: (req, file, cb) => {
55 cb(null, CONFIG.STORAGE.VIDEOS_DIR)
58 filename: (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)
64 .then(randomString => {
65 cb(null, randomString + '.' + extension)
68 logger.error('Cannot generate random string for file name.', err)
74 const reqFiles = multer({ storage: storage }).fields([{ name: 'videofile', maxCount: 1 }])
76 videosRouter.use('/', abuseVideoRouter)
77 videosRouter.use('/', blacklistRouter)
78 videosRouter.use('/', rateVideoRouter)
80 videosRouter.get('/categories', listVideoCategories)
81 videosRouter.get('/licences', listVideoLicences)
82 videosRouter.get('/languages', listVideoLanguages)
91 videosRouter.put('/:id',
93 videosUpdateValidator,
94 updateVideoRetryWrapper
96 videosRouter.post('/upload',
102 videosRouter.get('/:id',
107 videosRouter.delete('/:id',
109 videosRemoveValidator,
110 removeVideoRetryWrapper
113 videosRouter.get('/search/:value',
114 videosSearchValidator,
123 // ---------------------------------------------------------------------------
129 // ---------------------------------------------------------------------------
131 function listVideoCategories (req: express.Request, res: express.Response) {
132 res.json(VIDEO_CATEGORIES)
135 function listVideoLicences (req: express.Request, res: express.Response) {
136 res.json(VIDEO_LICENCES)
139 function listVideoLanguages (req: express.Request, res: express.Response) {
140 res.json(VIDEO_LANGUAGES)
143 // Wrapper to video add that retry the function if there is a database error
144 // We need this because we run the transaction in SERIALIZABLE isolation that can fail
145 function addVideoRetryWrapper (req: express.Request, res: express.Response, next: express.NextFunction) {
147 arguments: [ req, res, req.files['videofile'][0] ],
148 errorMessage: 'Cannot insert the video with many retries.'
151 retryTransactionWrapper(addVideo, options)
153 // TODO : include Location of the new video -> 201
154 res.type('json').status(204).end()
156 .catch(err => next(err))
159 function addVideo (req: express.Request, res: express.Response, videoPhysicalFile: Express.Multer.File) {
160 const videoInfo: VideoCreate = req.body
163 return db.sequelize.transaction(t => {
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 return db.Author.findOrCreateAuthor(name, podId, userId, t)
173 const tags = videoInfo.tags
174 if (!tags) return { author, tagInstances: undefined }
176 return db.Tag.findOrCreateTags(tags, t).then(tagInstances => ({ author, tagInstances }))
178 .then(({ author, tagInstances }) => {
180 name: videoInfo.name,
182 extname: extname(videoPhysicalFile.filename),
183 category: videoInfo.category,
184 licence: videoInfo.licence,
185 language: videoInfo.language,
186 nsfw: videoInfo.nsfw,
187 description: videoInfo.description,
188 duration: videoPhysicalFile['duration'], // duration was added by a previous middleware
192 const video = db.Video.build(videoData)
193 return { author, tagInstances, video }
195 .then(({ author, tagInstances, video }) => {
196 const videoFileData = {
197 extname: extname(videoPhysicalFile.filename),
198 resolution: 0, // TODO: improve readability,
199 size: videoPhysicalFile.size
202 const videoFile = db.VideoFile.build(videoFileData)
203 return { author, tagInstances, video, videoFile }
205 .then(({ author, tagInstances, video, videoFile }) => {
206 const videoDir = CONFIG.STORAGE.VIDEOS_DIR
207 const source = join(videoDir, videoPhysicalFile.filename)
208 const destination = join(videoDir, video.getVideoFilename(videoFile))
210 return renamePromise(source, destination)
212 // This is important in case if there is another attempt in the retry process
213 videoPhysicalFile.filename = video.getVideoFilename(videoFile)
214 return { author, tagInstances, video, videoFile }
217 .then(({ author, tagInstances, video, videoFile }) => {
221 video.createTorrentAndSetInfoHash(videoFile),
222 video.createThumbnail(videoFile),
223 video.createPreview(videoFile)
226 if (CONFIG.TRANSCODING.ENABLED === true) {
227 // Put uuid because we don't have id auto incremented for now
229 videoUUID: video.uuid
233 JobScheduler.Instance.createJob(t, 'videoTranscoder', dataInput)
237 return Promise.all(tasks).then(() => ({ author, tagInstances, video, videoFile }))
239 .then(({ author, tagInstances, video, videoFile }) => {
240 const options = { transaction: t }
242 return video.save(options)
243 .then(videoCreated => {
244 // Do not forget to add Author information to the created video
245 videoCreated.Author = author
246 videoUUID = videoCreated.uuid
248 return { tagInstances, video: videoCreated, videoFile }
251 .then(({ tagInstances, video, videoFile }) => {
252 const options = { transaction: t }
253 videoFile.videoId = video.id
255 return videoFile.save(options)
256 .then(() => video.VideoFiles = [ videoFile ])
257 .then(() => ({ tagInstances, video }))
259 .then(({ tagInstances, video }) => {
260 if (!tagInstances) return video
262 const options = { transaction: t }
263 return video.setTags(tagInstances, options)
265 video.Tags = tagInstances
270 // Let transcoding job send the video to friends because the video file extension might change
271 if (CONFIG.TRANSCODING.ENABLED === true) return undefined
273 return video.toAddRemoteJSON()
274 .then(remoteVideo => {
275 // Now we'll add the video's meta data to our friends
276 return addVideoToFriends(remoteVideo, t)
280 .then(() => logger.info('Video with name %s and uuid %s created.', videoInfo.name, videoUUID))
281 .catch((err: Error) => {
282 logger.debug('Cannot insert the video.', err)
287 function updateVideoRetryWrapper (req: express.Request, res: express.Response, next: express.NextFunction) {
289 arguments: [ req, res ],
290 errorMessage: 'Cannot update the video with many retries.'
293 retryTransactionWrapper(updateVideo, options)
295 return res.type('json').status(204).end()
297 .catch(err => next(err))
300 function updateVideo (req: express.Request, res: express.Response) {
301 const videoInstance = res.locals.video
302 const videoFieldsSave = videoInstance.toJSON()
303 const videoInfoToUpdate: VideoUpdate = req.body
305 return db.sequelize.transaction(t => {
306 let tagsPromise: Promise<TagInstance[]>
307 if (!videoInfoToUpdate.tags) {
308 tagsPromise = Promise.resolve(null)
310 tagsPromise = db.Tag.findOrCreateTags(videoInfoToUpdate.tags, t)
314 .then(tagInstances => {
319 if (videoInfoToUpdate.name !== undefined) videoInstance.set('name', videoInfoToUpdate.name)
320 if (videoInfoToUpdate.category !== undefined) videoInstance.set('category', videoInfoToUpdate.category)
321 if (videoInfoToUpdate.licence !== undefined) videoInstance.set('licence', videoInfoToUpdate.licence)
322 if (videoInfoToUpdate.language !== undefined) videoInstance.set('language', videoInfoToUpdate.language)
323 if (videoInfoToUpdate.nsfw !== undefined) videoInstance.set('nsfw', videoInfoToUpdate.nsfw)
324 if (videoInfoToUpdate.description !== undefined) videoInstance.set('description', videoInfoToUpdate.description)
326 return videoInstance.save(options).then(() => tagInstances)
328 .then(tagInstances => {
329 if (!tagInstances) return
331 const options = { transaction: t }
332 return videoInstance.setTags(tagInstances, options)
334 videoInstance.Tags = tagInstances
340 const json = videoInstance.toUpdateRemoteJSON()
342 // Now we'll update the video's meta data to our friends
343 return updateVideoToFriends(json, t)
347 logger.info('Video with name %s and uuid %s updated.', videoInstance.name, videoInstance.uuid)
350 logger.debug('Cannot update the video.', err)
352 // Force fields we want to update
353 // If the transaction is retried, sequelize will think the object has not changed
354 // So it will skip the SQL request, even if the last one was ROLLBACKed!
355 Object.keys(videoFieldsSave).forEach(key => {
356 const value = videoFieldsSave[key]
357 videoInstance.set(key, value)
364 function getVideo (req: express.Request, res: express.Response) {
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')
371 // FIXME: make a real view system
372 // For example, only add a view when a user watch a video during 30s etc
374 videoId: videoInstance.id,
375 type: REQUEST_VIDEO_QADU_TYPES.VIEWS
377 return quickAndDirtyUpdateVideoToFriends(qaduParams)
379 .catch(err => logger.error('Cannot add view to video %d.', videoInstance.id, err))
381 // Just send the event to our friends
382 const eventParams = {
383 videoId: videoInstance.id,
384 type: REQUEST_VIDEO_EVENT_TYPES.VIEWS
386 addEventToRemoteVideo(eventParams)
389 // Do not wait the view system
390 res.json(videoInstance.toFormattedJSON())
393 function listVideos (req: express.Request, res: express.Response, next: express.NextFunction) {
394 db.Video.listForApi(req.query.start, req.query.count, req.query.sort)
395 .then(result => res.json(getFormattedObjects(result.data, result.total)))
396 .catch(err => next(err))
399 function removeVideoRetryWrapper (req: express.Request, res: express.Response, next: express.NextFunction) {
401 arguments: [ req, res ],
402 errorMessage: 'Cannot remove the video with many retries.'
405 retryTransactionWrapper(removeVideo, options)
407 return res.type('json').status(204).end()
409 .catch(err => next(err))
412 function removeVideo (req: express.Request, res: express.Response) {
413 const videoInstance: VideoInstance = res.locals.video
415 return db.sequelize.transaction(t => {
416 return videoInstance.destroy({ transaction: t })
419 logger.info('Video with name %s and uuid %s deleted.', videoInstance.name, videoInstance.uuid)
422 logger.error('Errors when removed the video.', err)
427 function searchVideos (req: express.Request, res: express.Response, next: express.NextFunction) {
428 db.Video.searchAndPopulateAuthorAndPodAndTags(req.params.value, req.query.field, req.query.start, req.query.count, req.query.sort)
429 .then(result => res.json(getFormattedObjects(result.data, result.total)))
430 .catch(err => next(err))