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'
42 import { VideoCreate, VideoUpdate } from '../../../../shared'
44 import { abuseVideoRouter } from './abuse'
45 import { blacklistRouter } from './blacklist'
46 import { rateVideoRouter } from './rate'
48 const videosRouter = express.Router()
50 // multer configuration
51 const storage = multer.diskStorage({
52 destination: (req, file, cb) => {
53 cb(null, CONFIG.STORAGE.VIDEOS_DIR)
56 filename: (req, file, cb) => {
58 if (file.mimetype === 'video/webm') extension = 'webm'
59 else if (file.mimetype === 'video/mp4') extension = 'mp4'
60 else if (file.mimetype === 'video/ogg') extension = 'ogv'
61 generateRandomString(16)
62 .then(randomString => {
63 const filename = randomString
64 cb(null, filename + '.' + 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, next: express.NextFunction) {
131 res.json(VIDEO_CATEGORIES)
134 function listVideoLicences (req: express.Request, res: express.Response, next: express.NextFunction) {
135 res.json(VIDEO_LICENCES)
138 function listVideoLanguages (req: express.Request, res: express.Response, next: express.NextFunction) {
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, videoFile: Express.Multer.File) {
159 const videoInfos: 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 = videoInfos.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: videoInfos.name,
180 extname: path.extname(videoFile.filename),
181 category: videoInfos.category,
182 licence: videoInfos.licence,
183 language: videoInfos.language,
184 nsfw: videoInfos.nsfw,
185 description: videoInfos.description,
186 duration: videoFile['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 videoDir = CONFIG.STORAGE.VIDEOS_DIR
195 const source = path.join(videoDir, videoFile.filename)
196 const destination = path.join(videoDir, video.getVideoFilename())
198 return renamePromise(source, destination)
200 // This is important in case if there is another attempt in the retry process
201 videoFile.filename = video.getVideoFilename()
202 return { author, tagInstances, video }
205 .then(({ author, tagInstances, video }) => {
206 const options = { transaction: t }
208 return video.save(options)
209 .then(videoCreated => {
210 // Do not forget to add Author informations to the created video
211 videoCreated.Author = author
213 return { tagInstances, video: videoCreated }
216 .then(({ tagInstances, video }) => {
217 if (!tagInstances) return video
219 const options = { transaction: t }
220 return video.setTags(tagInstances, options)
222 video.Tags = tagInstances
227 // Let transcoding job send the video to friends because the videofile extension might change
228 if (CONFIG.TRANSCODING.ENABLED === true) return undefined
230 return video.toAddRemoteJSON()
231 .then(remoteVideo => {
232 // Now we'll add the video's meta data to our friends
233 return addVideoToFriends(remoteVideo, t)
237 .then(() => logger.info('Video with name %s created.', videoInfos.name))
238 .catch((err: Error) => {
239 logger.debug('Cannot insert the video.', { error: err.stack })
244 function updateVideoRetryWrapper (req: express.Request, res: express.Response, next: express.NextFunction) {
246 arguments: [ req, res ],
247 errorMessage: 'Cannot update the video with many retries.'
250 retryTransactionWrapper(updateVideo, options)
252 // TODO : include Location of the new video -> 201
253 return res.type('json').status(204).end()
255 .catch(err => next(err))
258 function updateVideo (req: express.Request, res: express.Response) {
259 const videoInstance = res.locals.video
260 const videoFieldsSave = videoInstance.toJSON()
261 const videoInfosToUpdate: VideoUpdate = req.body
263 return db.sequelize.transaction(t => {
264 let tagsPromise: Promise<TagInstance[]>
265 if (!videoInfosToUpdate.tags) {
266 tagsPromise = Promise.resolve(null)
268 tagsPromise = db.Tag.findOrCreateTags(videoInfosToUpdate.tags, t)
272 .then(tagInstances => {
277 if (videoInfosToUpdate.name !== undefined) videoInstance.set('name', videoInfosToUpdate.name)
278 if (videoInfosToUpdate.category !== undefined) videoInstance.set('category', videoInfosToUpdate.category)
279 if (videoInfosToUpdate.licence !== undefined) videoInstance.set('licence', videoInfosToUpdate.licence)
280 if (videoInfosToUpdate.language !== undefined) videoInstance.set('language', videoInfosToUpdate.language)
281 if (videoInfosToUpdate.nsfw !== undefined) videoInstance.set('nsfw', videoInfosToUpdate.nsfw)
282 if (videoInfosToUpdate.description !== undefined) videoInstance.set('description', videoInfosToUpdate.description)
284 return videoInstance.save(options).then(() => tagInstances)
286 .then(tagInstances => {
287 if (!tagInstances) return
289 const options = { transaction: t }
290 return videoInstance.setTags(tagInstances, options)
292 videoInstance.Tags = tagInstances
298 const json = videoInstance.toUpdateRemoteJSON()
300 // Now we'll update the video's meta data to our friends
301 return updateVideoToFriends(json, t)
305 logger.info('Video with name %s updated.', videoInstance.name)
308 logger.debug('Cannot update the video.', err)
310 // Force fields we want to update
311 // If the transaction is retried, sequelize will think the object has not changed
312 // So it will skip the SQL request, even if the last one was ROLLBACKed!
313 Object.keys(videoFieldsSave).forEach(key => {
314 const value = videoFieldsSave[key]
315 videoInstance.set(key, value)
322 function getVideo (req: express.Request, res: express.Response, next: express.NextFunction) {
323 const videoInstance = res.locals.video
325 if (videoInstance.isOwned()) {
326 // The increment is done directly in the database, not using the instance value
327 videoInstance.increment('views')
329 // FIXME: make a real view system
330 // For example, only add a view when a user watch a video during 30s etc
332 videoId: videoInstance.id,
333 type: REQUEST_VIDEO_QADU_TYPES.VIEWS
335 return quickAndDirtyUpdateVideoToFriends(qaduParams)
337 .catch(err => logger.error('Cannot add view to video %d.', videoInstance.id, err))
339 // Just send the event to our friends
340 const eventParams = {
341 videoId: videoInstance.id,
342 type: REQUEST_VIDEO_EVENT_TYPES.VIEWS
344 addEventToRemoteVideo(eventParams)
347 // Do not wait the view system
348 res.json(videoInstance.toFormatedJSON())
351 function listVideos (req: express.Request, res: express.Response, next: express.NextFunction) {
352 db.Video.listForApi(req.query.start, req.query.count, req.query.sort)
353 .then(result => res.json(getFormatedObjects(result.data, result.total)))
354 .catch(err => next(err))
357 function removeVideo (req: express.Request, res: express.Response, next: express.NextFunction) {
358 const videoInstance = res.locals.video
360 videoInstance.destroy()
361 .then(() => res.type('json').status(204).end())
363 logger.error('Errors when removed the video.', err)
368 function searchVideos (req: express.Request, res: express.Response, next: express.NextFunction) {
369 db.Video.searchAndPopulateAuthorAndPodAndTags(req.params.value, req.query.field, req.query.start, req.query.count, req.query.sort)
370 .then(result => res.json(getFormatedObjects(result.data, result.total)))
371 .catch(err => next(err))