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 const filename = randomString
65 cb(null, filename + '.' + 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('/',
102 videosRouter.get('/:id',
107 videosRouter.delete('/:id',
109 videosRemoveValidator,
113 videosRouter.get('/search/:value',
114 videosSearchValidator,
123 // ---------------------------------------------------------------------------
129 // ---------------------------------------------------------------------------
131 function listVideoCategories (req: express.Request, res: express.Response, next: express.NextFunction) {
132 res.json(VIDEO_CATEGORIES)
135 function listVideoLicences (req: express.Request, res: express.Response, next: express.NextFunction) {
136 res.json(VIDEO_LICENCES)
139 function listVideoLanguages (req: express.Request, res: express.Response, next: express.NextFunction) {
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 videoInfos: VideoCreate = req.body
162 return db.sequelize.transaction(t => {
163 const user = res.locals.oauth.token.User
165 const name = user.username
166 // null because it is OUR pod
168 const userId = user.id
170 return db.Author.findOrCreateAuthor(name, podId, userId, t)
172 const tags = videoInfos.tags
173 if (!tags) return { author, tagInstances: undefined }
175 return db.Tag.findOrCreateTags(tags, t).then(tagInstances => ({ author, tagInstances }))
177 .then(({ author, tagInstances }) => {
179 name: videoInfos.name,
181 extname: extname(videoPhysicalFile.filename),
182 category: videoInfos.category,
183 licence: videoInfos.licence,
184 language: videoInfos.language,
185 nsfw: videoInfos.nsfw,
186 description: videoInfos.description,
187 duration: videoPhysicalFile['duration'], // duration was added by a previous middleware
191 const video = db.Video.build(videoData)
192 return { author, tagInstances, video }
194 .then(({ author, tagInstances, video }) => {
195 const videoFileData = {
196 extname: extname(videoPhysicalFile.filename),
197 resolution: 0, // TODO: improve readability,
198 size: videoPhysicalFile.size
201 const videoFile = db.VideoFile.build(videoFileData)
202 return { author, tagInstances, video, videoFile }
204 .then(({ author, tagInstances, video, videoFile }) => {
205 const videoDir = CONFIG.STORAGE.VIDEOS_DIR
206 const source = join(videoDir, videoPhysicalFile.filename)
207 const destination = join(videoDir, video.getVideoFilename(videoFile))
209 return renamePromise(source, destination)
211 // This is important in case if there is another attempt in the retry process
212 videoPhysicalFile.filename = video.getVideoFilename(videoFile)
213 return { author, tagInstances, video, videoFile }
216 .then(({ author, tagInstances, video, videoFile }) => {
220 video.createTorrentAndSetInfoHash(videoFile),
221 video.createThumbnail(videoFile),
222 video.createPreview(videoFile)
225 if (CONFIG.TRANSCODING.ENABLED === true) {
226 // Put uuid because we don't have id auto incremented for now
228 videoUUID: video.uuid
232 JobScheduler.Instance.createJob(t, 'videoTranscoder', dataInput)
236 return Promise.all(tasks).then(() => ({ author, tagInstances, video, videoFile }))
238 .then(({ author, tagInstances, video, videoFile }) => {
239 const options = { transaction: t }
241 return video.save(options)
242 .then(videoCreated => {
243 // Do not forget to add Author informations to the created video
244 videoCreated.Author = author
246 return { tagInstances, video: videoCreated, videoFile }
249 .then(({ tagInstances, video, videoFile }) => {
250 const options = { transaction: t }
251 videoFile.videoId = video.id
253 return videoFile.save(options)
254 .then(() => video.VideoFiles = [ videoFile ])
255 .then(() => ({ tagInstances, video }))
257 .then(({ tagInstances, video }) => {
258 if (!tagInstances) return video
260 const options = { transaction: t }
261 return video.setTags(tagInstances, options)
263 video.Tags = tagInstances
268 // Let transcoding job send the video to friends because the videofile extension might change
269 if (CONFIG.TRANSCODING.ENABLED === true) return undefined
271 return video.toAddRemoteJSON()
272 .then(remoteVideo => {
273 // Now we'll add the video's meta data to our friends
274 return addVideoToFriends(remoteVideo, t)
278 .then(() => logger.info('Video with name %s created.', videoInfos.name))
279 .catch((err: Error) => {
280 logger.debug('Cannot insert the video.', err)
285 function updateVideoRetryWrapper (req: express.Request, res: express.Response, next: express.NextFunction) {
287 arguments: [ req, res ],
288 errorMessage: 'Cannot update the video with many retries.'
291 retryTransactionWrapper(updateVideo, options)
293 // TODO : include Location of the new video -> 201
294 return res.type('json').status(204).end()
296 .catch(err => next(err))
299 function updateVideo (req: express.Request, res: express.Response) {
300 const videoInstance = res.locals.video
301 const videoFieldsSave = videoInstance.toJSON()
302 const videoInfosToUpdate: VideoUpdate = req.body
304 return db.sequelize.transaction(t => {
305 let tagsPromise: Promise<TagInstance[]>
306 if (!videoInfosToUpdate.tags) {
307 tagsPromise = Promise.resolve(null)
309 tagsPromise = db.Tag.findOrCreateTags(videoInfosToUpdate.tags, t)
313 .then(tagInstances => {
318 if (videoInfosToUpdate.name !== undefined) videoInstance.set('name', videoInfosToUpdate.name)
319 if (videoInfosToUpdate.category !== undefined) videoInstance.set('category', videoInfosToUpdate.category)
320 if (videoInfosToUpdate.licence !== undefined) videoInstance.set('licence', videoInfosToUpdate.licence)
321 if (videoInfosToUpdate.language !== undefined) videoInstance.set('language', videoInfosToUpdate.language)
322 if (videoInfosToUpdate.nsfw !== undefined) videoInstance.set('nsfw', videoInfosToUpdate.nsfw)
323 if (videoInfosToUpdate.description !== undefined) videoInstance.set('description', videoInfosToUpdate.description)
325 return videoInstance.save(options).then(() => tagInstances)
327 .then(tagInstances => {
328 if (!tagInstances) return
330 const options = { transaction: t }
331 return videoInstance.setTags(tagInstances, options)
333 videoInstance.Tags = tagInstances
339 const json = videoInstance.toUpdateRemoteJSON()
341 // Now we'll update the video's meta data to our friends
342 return updateVideoToFriends(json, t)
346 logger.info('Video with name %s updated.', videoInstance.name)
349 logger.debug('Cannot update the video.', err)
351 // Force fields we want to update
352 // If the transaction is retried, sequelize will think the object has not changed
353 // So it will skip the SQL request, even if the last one was ROLLBACKed!
354 Object.keys(videoFieldsSave).forEach(key => {
355 const value = videoFieldsSave[key]
356 videoInstance.set(key, value)
363 function getVideo (req: express.Request, res: express.Response, next: express.NextFunction) {
364 const videoInstance = res.locals.video
366 if (videoInstance.isOwned()) {
367 // The increment is done directly in the database, not using the instance value
368 videoInstance.increment('views')
370 // FIXME: make a real view system
371 // For example, only add a view when a user watch a video during 30s etc
373 videoId: videoInstance.id,
374 type: REQUEST_VIDEO_QADU_TYPES.VIEWS
376 return quickAndDirtyUpdateVideoToFriends(qaduParams)
378 .catch(err => logger.error('Cannot add view to video %d.', videoInstance.id, err))
380 // Just send the event to our friends
381 const eventParams = {
382 videoId: videoInstance.id,
383 type: REQUEST_VIDEO_EVENT_TYPES.VIEWS
385 addEventToRemoteVideo(eventParams)
388 // Do not wait the view system
389 res.json(videoInstance.toFormatedJSON())
392 function listVideos (req: express.Request, res: express.Response, next: express.NextFunction) {
393 db.Video.listForApi(req.query.start, req.query.count, req.query.sort)
394 .then(result => res.json(getFormatedObjects(result.data, result.total)))
395 .catch(err => next(err))
398 function removeVideo (req: express.Request, res: express.Response, next: express.NextFunction) {
399 const videoInstance = res.locals.video
401 videoInstance.destroy()
402 .then(() => res.type('json').status(204).end())
404 logger.error('Errors when removed the video.', err)
409 function searchVideos (req: express.Request, res: express.Response, next: express.NextFunction) {
410 db.Video.searchAndPopulateAuthorAndPodAndTags(req.params.value, req.query.field, req.query.start, req.query.count, req.query.sort)
411 .then(result => res.json(getFormatedObjects(result.data, result.total)))
412 .catch(err => next(err))