1 import * as express from 'express'
2 import * as Promise from 'bluebird'
3 import * as multer from 'multer'
4 import * as path 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,
28 videosUpdateValidator,
29 videosSearchValidator,
33 } from '../../../middlewares'
36 retryTransactionWrapper,
40 } from '../../../helpers'
41 import { TagInstance } from '../../../models'
43 import { abuseVideoRouter } from './abuse'
44 import { blacklistRouter } from './blacklist'
45 import { rateVideoRouter } from './rate'
47 const videosRouter = express.Router()
49 // multer configuration
50 const storage = multer.diskStorage({
51 destination: function (req, file, cb) {
52 cb(null, CONFIG.STORAGE.VIDEOS_DIR)
55 filename: function (req, file, cb) {
57 if (file.mimetype === 'video/webm') extension = 'webm'
58 else if (file.mimetype === 'video/mp4') extension = 'mp4'
59 else if (file.mimetype === 'video/ogg') extension = 'ogv'
60 generateRandomString(16)
61 .then(randomString => {
62 const filename = randomString
63 cb(null, filename + '.' + extension)
66 logger.error('Cannot generate random string for file name.', { error: err })
72 const reqFiles = multer({ storage: storage }).fields([{ name: 'videofile', maxCount: 1 }])
74 videosRouter.use('/', abuseVideoRouter)
75 videosRouter.use('/', blacklistRouter)
76 videosRouter.use('/', rateVideoRouter)
78 videosRouter.get('/categories', listVideoCategories)
79 videosRouter.get('/licences', listVideoLicences)
80 videosRouter.get('/languages', listVideoLanguages)
89 videosRouter.put('/:id',
91 videosUpdateValidator,
92 updateVideoRetryWrapper
94 videosRouter.post('/',
100 videosRouter.get('/:id',
105 videosRouter.delete('/:id',
107 videosRemoveValidator,
111 videosRouter.get('/search/:value',
112 videosSearchValidator,
121 // ---------------------------------------------------------------------------
127 // ---------------------------------------------------------------------------
129 function listVideoCategories (req: express.Request, res: express.Response, next: express.NextFunction) {
130 res.json(VIDEO_CATEGORIES)
133 function listVideoLicences (req: express.Request, res: express.Response, next: express.NextFunction) {
134 res.json(VIDEO_LICENCES)
137 function listVideoLanguages (req: express.Request, res: express.Response, next: express.NextFunction) {
138 res.json(VIDEO_LANGUAGES)
141 // Wrapper to video add that retry the function if there is a database error
142 // We need this because we run the transaction in SERIALIZABLE isolation that can fail
143 function addVideoRetryWrapper (req: express.Request, res: express.Response, next: express.NextFunction) {
145 arguments: [ req, res, req.files.videofile[0] ],
146 errorMessage: 'Cannot insert the video with many retries.'
149 retryTransactionWrapper(addVideo, options)
151 // TODO : include Location of the new video -> 201
152 res.type('json').status(204).end()
154 .catch(err => next(err))
157 function addVideo (req: express.Request, res: express.Response, videoFile: Express.Multer.File) {
158 const videoInfos = req.body
160 return db.sequelize.transaction(t => {
161 const user = res.locals.oauth.token.User
163 const name = user.username
164 // null because it is OUR pod
166 const userId = user.id
168 return db.Author.findOrCreateAuthor(name, podId, userId, t)
170 const tags = videoInfos.tags
171 if (!tags) return { author, tagInstances: undefined }
173 return db.Tag.findOrCreateTags(tags, t).then(tagInstances => ({ author, tagInstances }))
175 .then(({ author, tagInstances }) => {
177 name: videoInfos.name,
179 extname: path.extname(videoFile.filename),
180 category: videoInfos.category,
181 licence: videoInfos.licence,
182 language: videoInfos.language,
183 nsfw: videoInfos.nsfw,
184 description: videoInfos.description,
185 duration: videoFile['duration'], // duration was added by a previous middleware
189 const video = db.Video.build(videoData)
190 return { author, tagInstances, video }
192 .then(({ author, tagInstances, video }) => {
193 const videoDir = CONFIG.STORAGE.VIDEOS_DIR
194 const source = path.join(videoDir, videoFile.filename)
195 const destination = path.join(videoDir, video.getVideoFilename())
197 return renamePromise(source, destination)
199 // This is important in case if there is another attempt in the retry process
200 videoFile.filename = video.getVideoFilename()
201 return { author, tagInstances, video }
204 .then(({ author, tagInstances, video }) => {
205 const options = { transaction: t }
207 return video.save(options)
208 .then(videoCreated => {
209 // Do not forget to add Author informations to the created video
210 videoCreated.Author = author
212 return { tagInstances, video: videoCreated }
215 .then(({ tagInstances, video }) => {
216 if (!tagInstances) return video
218 const options = { transaction: t }
219 return video.setTags(tagInstances, options)
221 video.Tags = tagInstances
226 // Let transcoding job send the video to friends because the videofile extension might change
227 if (CONFIG.TRANSCODING.ENABLED === true) return undefined
229 return video.toAddRemoteJSON()
230 .then(remoteVideo => {
231 // Now we'll add the video's meta data to our friends
232 return addVideoToFriends(remoteVideo, t)
236 .then(() => logger.info('Video with name %s created.', videoInfos.name))
237 .catch((err: Error) => {
238 logger.debug('Cannot insert the video.', { error: err.stack })
243 function updateVideoRetryWrapper (req: express.Request, res: express.Response, next: express.NextFunction) {
245 arguments: [ req, res ],
246 errorMessage: 'Cannot update the video with many retries.'
249 retryTransactionWrapper(updateVideo, options)
251 // TODO : include Location of the new video -> 201
252 return res.type('json').status(204).end()
254 .catch(err => next(err))
257 function updateVideo (req: express.Request, res: express.Response) {
258 const videoInstance = res.locals.video
259 const videoFieldsSave = videoInstance.toJSON()
260 const videoInfosToUpdate = req.body
262 return db.sequelize.transaction(t => {
263 let tagsPromise: Promise<TagInstance[]>
264 if (!videoInfosToUpdate.tags) {
265 tagsPromise = Promise.resolve(null)
267 tagsPromise = db.Tag.findOrCreateTags(videoInfosToUpdate.tags, t)
271 .then(tagInstances => {
276 if (videoInfosToUpdate.name !== undefined) videoInstance.set('name', videoInfosToUpdate.name)
277 if (videoInfosToUpdate.category !== undefined) videoInstance.set('category', videoInfosToUpdate.category)
278 if (videoInfosToUpdate.licence !== undefined) videoInstance.set('licence', videoInfosToUpdate.licence)
279 if (videoInfosToUpdate.language !== undefined) videoInstance.set('language', videoInfosToUpdate.language)
280 if (videoInfosToUpdate.nsfw !== undefined) videoInstance.set('nsfw', videoInfosToUpdate.nsfw)
281 if (videoInfosToUpdate.description !== undefined) videoInstance.set('description', videoInfosToUpdate.description)
283 return videoInstance.save(options).then(() => tagInstances)
285 .then(tagInstances => {
286 if (!tagInstances) return
288 const options = { transaction: t }
289 return videoInstance.setTags(tagInstances, options)
291 videoInstance.Tags = tagInstances
297 const json = videoInstance.toUpdateRemoteJSON()
299 // Now we'll update the video's meta data to our friends
300 return updateVideoToFriends(json, t)
304 logger.info('Video with name %s updated.', videoInstance.name)
307 logger.debug('Cannot update the video.', { error: err })
309 // Force fields we want to update
310 // If the transaction is retried, sequelize will think the object has not changed
311 // So it will skip the SQL request, even if the last one was ROLLBACKed!
312 Object.keys(videoFieldsSave).forEach(function (key) {
313 const value = videoFieldsSave[key]
314 videoInstance.set(key, value)
321 function getVideo (req: express.Request, res: express.Response, next: express.NextFunction) {
322 const videoInstance = res.locals.video
324 if (videoInstance.isOwned()) {
325 // The increment is done directly in the database, not using the instance value
326 videoInstance.increment('views')
328 // FIXME: make a real view system
329 // For example, only add a view when a user watch a video during 30s etc
331 videoId: videoInstance.id,
332 type: REQUEST_VIDEO_QADU_TYPES.VIEWS
334 return quickAndDirtyUpdateVideoToFriends(qaduParams)
336 .catch(err => logger.error('Cannot add view to video %d.', videoInstance.id, { error: err }))
338 // Just send the event to our friends
339 const eventParams = {
340 videoId: videoInstance.id,
341 type: REQUEST_VIDEO_EVENT_TYPES.VIEWS
343 addEventToRemoteVideo(eventParams)
346 // Do not wait the view system
347 res.json(videoInstance.toFormatedJSON())
350 function listVideos (req: express.Request, res: express.Response, next: express.NextFunction) {
351 db.Video.listForApi(req.query.start, req.query.count, req.query.sort)
352 .then(result => res.json(getFormatedObjects(result.data, result.total)))
353 .catch(err => next(err))
356 function removeVideo (req: express.Request, res: express.Response, next: express.NextFunction) {
357 const videoInstance = res.locals.video
359 videoInstance.destroy()
360 .then(() => res.type('json').status(204).end())
362 logger.error('Errors when removed the video.', { error: err })
367 function searchVideos (req: express.Request, res: express.Response, next: express.NextFunction) {
368 db.Video.searchAndPopulateAuthorAndPodAndTags(req.params.value, req.query.field, req.query.start, req.query.count, req.query.sort)
369 .then(result => res.json(getFormatedObjects(result.data, result.total)))
370 .catch(err => next(err))