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'
49 const videosRouter = express.Router()
51 // multer configuration
52 const storage = multer.diskStorage({
53 destination: (req, file, cb) => {
54 cb(null, CONFIG.STORAGE.VIDEOS_DIR)
57 filename: (req, file, cb) => {
59 if (file.mimetype === 'video/webm') extension = 'webm'
60 else if (file.mimetype === 'video/mp4') extension = 'mp4'
61 else if (file.mimetype === 'video/ogg') extension = 'ogv'
62 generateRandomString(16)
63 .then(randomString => {
64 cb(null, randomString + '.' + extension)
67 logger.error('Cannot generate random string for file name.', err)
73 const reqFiles = multer({ storage: storage }).fields([{ name: 'videofile', maxCount: 1 }])
75 videosRouter.use('/', abuseVideoRouter)
76 videosRouter.use('/', blacklistRouter)
77 videosRouter.use('/', rateVideoRouter)
79 videosRouter.get('/categories', listVideoCategories)
80 videosRouter.get('/licences', listVideoLicences)
81 videosRouter.get('/languages', listVideoLanguages)
90 videosRouter.put('/:id',
92 videosUpdateValidator,
93 updateVideoRetryWrapper
95 videosRouter.post('/',
101 videosRouter.get('/:id',
106 videosRouter.delete('/:id',
108 videosRemoveValidator,
112 videosRouter.get('/search/:value',
113 videosSearchValidator,
122 // ---------------------------------------------------------------------------
128 // ---------------------------------------------------------------------------
130 function listVideoCategories (req: express.Request, res: express.Response) {
131 res.json(VIDEO_CATEGORIES)
134 function listVideoLicences (req: express.Request, res: express.Response) {
135 res.json(VIDEO_LICENCES)
138 function listVideoLanguages (req: express.Request, res: express.Response) {
139 res.json(VIDEO_LANGUAGES)
142 // Wrapper to video add that retry the function if there is a database error
143 // We need this because we run the transaction in SERIALIZABLE isolation that can fail
144 function addVideoRetryWrapper (req: express.Request, res: express.Response, next: express.NextFunction) {
146 arguments: [ req, res, req.files['videofile'][0] ],
147 errorMessage: 'Cannot insert the video with many retries.'
150 retryTransactionWrapper(addVideo, options)
152 // TODO : include Location of the new video -> 201
153 res.type('json').status(204).end()
155 .catch(err => next(err))
158 function addVideo (req: express.Request, res: express.Response, videoPhysicalFile: Express.Multer.File) {
159 const videoInfo: VideoCreate = req.body
161 return db.sequelize.transaction(t => {
162 const user = res.locals.oauth.token.User
164 const name = user.username
165 // null because it is OUR pod
167 const userId = user.id
169 return db.Author.findOrCreateAuthor(name, podId, userId, t)
171 const tags = videoInfo.tags
172 if (!tags) return { author, tagInstances: undefined }
174 return db.Tag.findOrCreateTags(tags, t).then(tagInstances => ({ author, tagInstances }))
176 .then(({ author, tagInstances }) => {
178 name: videoInfo.name,
180 extname: extname(videoPhysicalFile.filename),
181 category: videoInfo.category,
182 licence: videoInfo.licence,
183 language: videoInfo.language,
184 nsfw: videoInfo.nsfw,
185 description: videoInfo.description,
186 duration: videoPhysicalFile['duration'], // duration was added by a previous middleware
190 const video = db.Video.build(videoData)
191 return { author, tagInstances, video }
193 .then(({ author, tagInstances, video }) => {
194 const videoFileData = {
195 extname: extname(videoPhysicalFile.filename),
196 resolution: 0, // TODO: improve readability,
197 size: videoPhysicalFile.size
200 const videoFile = db.VideoFile.build(videoFileData)
201 return { author, tagInstances, video, videoFile }
203 .then(({ author, tagInstances, video, videoFile }) => {
204 const videoDir = CONFIG.STORAGE.VIDEOS_DIR
205 const source = join(videoDir, videoPhysicalFile.filename)
206 const destination = join(videoDir, video.getVideoFilename(videoFile))
208 return renamePromise(source, destination)
210 // This is important in case if there is another attempt in the retry process
211 videoPhysicalFile.filename = video.getVideoFilename(videoFile)
212 return { author, tagInstances, video, videoFile }
215 .then(({ author, tagInstances, video, videoFile }) => {
219 video.createTorrentAndSetInfoHash(videoFile),
220 video.createThumbnail(videoFile),
221 video.createPreview(videoFile)
224 if (CONFIG.TRANSCODING.ENABLED === true) {
225 // Put uuid because we don't have id auto incremented for now
227 videoUUID: video.uuid
231 JobScheduler.Instance.createJob(t, 'videoTranscoder', dataInput)
235 return Promise.all(tasks).then(() => ({ author, tagInstances, video, videoFile }))
237 .then(({ author, tagInstances, video, videoFile }) => {
238 const options = { transaction: t }
240 return video.save(options)
241 .then(videoCreated => {
242 // Do not forget to add Author information to the created video
243 videoCreated.Author = author
245 return { tagInstances, video: videoCreated, videoFile }
248 .then(({ tagInstances, video, videoFile }) => {
249 const options = { transaction: t }
250 videoFile.videoId = video.id
252 return videoFile.save(options)
253 .then(() => video.VideoFiles = [ videoFile ])
254 .then(() => ({ tagInstances, video }))
256 .then(({ tagInstances, video }) => {
257 if (!tagInstances) return video
259 const options = { transaction: t }
260 return video.setTags(tagInstances, options)
262 video.Tags = tagInstances
267 // Let transcoding job send the video to friends because the video file extension might change
268 if (CONFIG.TRANSCODING.ENABLED === true) return undefined
270 return video.toAddRemoteJSON()
271 .then(remoteVideo => {
272 // Now we'll add the video's meta data to our friends
273 return addVideoToFriends(remoteVideo, t)
277 .then(() => logger.info('Video with name %s created.', videoInfo.name))
278 .catch((err: Error) => {
279 logger.debug('Cannot insert the video.', err)
284 function updateVideoRetryWrapper (req: express.Request, res: express.Response, next: express.NextFunction) {
286 arguments: [ req, res ],
287 errorMessage: 'Cannot update the video with many retries.'
290 retryTransactionWrapper(updateVideo, options)
292 // TODO : include Location of the new video -> 201
293 return res.type('json').status(204).end()
295 .catch(err => next(err))
298 function updateVideo (req: express.Request, res: express.Response) {
299 const videoInstance = res.locals.video
300 const videoFieldsSave = videoInstance.toJSON()
301 const videoInfoToUpdate: VideoUpdate = req.body
303 return db.sequelize.transaction(t => {
304 let tagsPromise: Promise<TagInstance[]>
305 if (!videoInfoToUpdate.tags) {
306 tagsPromise = Promise.resolve(null)
308 tagsPromise = db.Tag.findOrCreateTags(videoInfoToUpdate.tags, t)
312 .then(tagInstances => {
317 if (videoInfoToUpdate.name !== undefined) videoInstance.set('name', videoInfoToUpdate.name)
318 if (videoInfoToUpdate.category !== undefined) videoInstance.set('category', videoInfoToUpdate.category)
319 if (videoInfoToUpdate.licence !== undefined) videoInstance.set('licence', videoInfoToUpdate.licence)
320 if (videoInfoToUpdate.language !== undefined) videoInstance.set('language', videoInfoToUpdate.language)
321 if (videoInfoToUpdate.nsfw !== undefined) videoInstance.set('nsfw', videoInfoToUpdate.nsfw)
322 if (videoInfoToUpdate.description !== undefined) videoInstance.set('description', videoInfoToUpdate.description)
324 return videoInstance.save(options).then(() => tagInstances)
326 .then(tagInstances => {
327 if (!tagInstances) return
329 const options = { transaction: t }
330 return videoInstance.setTags(tagInstances, options)
332 videoInstance.Tags = tagInstances
338 const json = videoInstance.toUpdateRemoteJSON()
340 // Now we'll update the video's meta data to our friends
341 return updateVideoToFriends(json, t)
345 logger.info('Video with name %s updated.', videoInstance.name)
348 logger.debug('Cannot update the video.', err)
350 // Force fields we want to update
351 // If the transaction is retried, sequelize will think the object has not changed
352 // So it will skip the SQL request, even if the last one was ROLLBACKed!
353 Object.keys(videoFieldsSave).forEach(key => {
354 const value = videoFieldsSave[key]
355 videoInstance.set(key, value)
362 function getVideo (req: express.Request, res: express.Response) {
363 const videoInstance = res.locals.video
365 if (videoInstance.isOwned()) {
366 // The increment is done directly in the database, not using the instance value
367 videoInstance.increment('views')
369 // FIXME: make a real view system
370 // For example, only add a view when a user watch a video during 30s etc
372 videoId: videoInstance.id,
373 type: REQUEST_VIDEO_QADU_TYPES.VIEWS
375 return quickAndDirtyUpdateVideoToFriends(qaduParams)
377 .catch(err => logger.error('Cannot add view to video %d.', videoInstance.id, err))
379 // Just send the event to our friends
380 const eventParams = {
381 videoId: videoInstance.id,
382 type: REQUEST_VIDEO_EVENT_TYPES.VIEWS
384 addEventToRemoteVideo(eventParams)
387 // Do not wait the view system
388 res.json(videoInstance.toFormattedJSON())
391 function listVideos (req: express.Request, res: express.Response, next: express.NextFunction) {
392 db.Video.listForApi(req.query.start, req.query.count, req.query.sort)
393 .then(result => res.json(getFormattedObjects(result.data, result.total)))
394 .catch(err => next(err))
397 function removeVideo (req: express.Request, res: express.Response, next: express.NextFunction) {
398 const videoInstance = res.locals.video
400 videoInstance.destroy()
401 .then(() => res.type('json').status(204).end())
403 logger.error('Errors when removed the video.', err)
408 function searchVideos (req: express.Request, res: express.Response, next: express.NextFunction) {
409 db.Video.searchAndPopulateAuthorAndPodAndTags(req.params.value, req.query.field, req.query.start, req.query.count, req.query.sort)
410 .then(result => res.json(getFormattedObjects(result.data, result.total)))
411 .catch(err => next(err))