3 const express
= require('express')
4 const fs
= require('fs')
5 const multer
= require('multer')
6 const path
= require('path')
7 const waterfall
= require('async/waterfall')
9 const constants
= require('../../initializers/constants')
10 const db
= require('../../initializers/database')
11 const logger
= require('../../helpers/logger')
12 const friends
= require('../../lib/friends')
13 const middlewares
= require('../../middlewares')
14 const admin
= middlewares
.admin
15 const oAuth
= middlewares
.oauth
16 const pagination
= middlewares
.pagination
17 const validators
= middlewares
.validators
18 const validatorsPagination
= validators
.pagination
19 const validatorsSort
= validators
.sort
20 const validatorsVideos
= validators
.videos
21 const search
= middlewares
.search
22 const sort
= middlewares
.sort
23 const databaseUtils
= require('../../helpers/database-utils')
24 const utils
= require('../../helpers/utils')
26 const router
= express
.Router()
28 // multer configuration
29 const storage
= multer
.diskStorage({
30 destination: function (req
, file
, cb
) {
31 cb(null, constants
.CONFIG
.STORAGE
.VIDEOS_DIR
)
34 filename: function (req
, file
, cb
) {
36 if (file
.mimetype
=== 'video/webm') extension
= 'webm'
37 else if (file
.mimetype
=== 'video/mp4') extension
= 'mp4'
38 else if (file
.mimetype
=== 'video/ogg') extension
= 'ogv'
39 utils
.generateRandomString(16, function (err
, randomString
) {
40 const fieldname
= err
? undefined : randomString
41 cb(null, fieldname
+ '.' + extension
)
46 const reqFiles
= multer({ storage: storage
}).fields([{ name: 'videofile', maxCount: 1 }])
51 validatorsPagination
.pagination
,
52 validatorsSort
.videoAbusesSort
,
53 sort
.setVideoAbusesSort
,
54 pagination
.setPagination
,
57 router
.post('/:id/abuse',
59 validatorsVideos
.videoAbuseReport
,
60 reportVideoAbuseRetryWrapper
64 validatorsPagination
.pagination
,
65 validatorsSort
.videosSort
,
67 pagination
.setPagination
,
73 validatorsVideos
.videosUpdate
,
74 updateVideoRetryWrapper
79 validatorsVideos
.videosAdd
,
83 validatorsVideos
.videosGet
,
88 validatorsVideos
.videosRemove
,
91 router
.get('/search/:value',
92 validatorsVideos
.videosSearch
,
93 validatorsPagination
.pagination
,
94 validatorsSort
.videosSort
,
96 pagination
.setPagination
,
97 search
.setVideosSearch
,
101 // ---------------------------------------------------------------------------
103 module
.exports
= router
105 // ---------------------------------------------------------------------------
107 // Wrapper to video add that retry the function if there is a database error
108 // We need this because we run the transaction in SERIALIZABLE isolation that can fail
109 function addVideoRetryWrapper (req
, res
, next
) {
111 arguments: [ req
, res
, req
.files
.videofile
[0] ],
112 errorMessage: 'Cannot insert the video with many retries.'
115 databaseUtils
.retryTransactionWrapper(addVideo
, options
, function (err
) {
116 if (err
) return next(err
)
118 // TODO : include Location of the new video -> 201
119 return res
.type('json').status(204).end()
123 function addVideo (req
, res
, videoFile
, callback
) {
124 const videoInfos
= req
.body
128 databaseUtils
.startSerializableTransaction
,
130 function findOrCreateAuthor (t
, callbackWaterfall
) {
131 const user
= res
.locals
.oauth
.token
.User
133 const name
= user
.username
134 // null because it is OUR pod
136 const userId
= user
.id
138 db
.Author
.findOrCreateAuthor(name
, podId
, userId
, t
, function (err
, authorInstance
) {
139 return callbackWaterfall(err
, t
, authorInstance
)
143 function findOrCreateTags (t
, author
, callbackWaterfall
) {
144 const tags
= videoInfos
.tags
146 db
.Tag
.findOrCreateTags(tags
, t
, function (err
, tagInstances
) {
147 return callbackWaterfall(err
, t
, author
, tagInstances
)
151 function createVideoObject (t
, author
, tagInstances
, callbackWaterfall
) {
153 name: videoInfos
.name
,
155 extname: path
.extname(videoFile
.filename
),
156 description: videoInfos
.description
,
157 duration: videoFile
.duration
,
161 const video
= db
.Video
.build(videoData
)
163 return callbackWaterfall(null, t
, author
, tagInstances
, video
)
166 // Set the videoname the same as the id
167 function renameVideoFile (t
, author
, tagInstances
, video
, callbackWaterfall
) {
168 const videoDir
= constants
.CONFIG
.STORAGE
.VIDEOS_DIR
169 const source
= path
.join(videoDir
, videoFile
.filename
)
170 const destination
= path
.join(videoDir
, video
.getVideoFilename())
172 fs
.rename(source
, destination
, function (err
) {
173 if (err
) return callbackWaterfall(err
)
175 // This is important in case if there is another attempt
176 videoFile
.filename
= video
.getVideoFilename()
177 return callbackWaterfall(null, t
, author
, tagInstances
, video
)
181 function insertVideoIntoDB (t
, author
, tagInstances
, video
, callbackWaterfall
) {
182 const options
= { transaction: t
}
184 // Add tags association
185 video
.save(options
).asCallback(function (err
, videoCreated
) {
186 if (err
) return callbackWaterfall(err
)
188 // Do not forget to add Author informations to the created video
189 videoCreated
.Author
= author
191 return callbackWaterfall(err
, t
, tagInstances
, videoCreated
)
195 function associateTagsToVideo (t
, tagInstances
, video
, callbackWaterfall
) {
196 const options
= { transaction: t
}
198 video
.setTags(tagInstances
, options
).asCallback(function (err
) {
199 video
.Tags
= tagInstances
201 return callbackWaterfall(err
, t
, video
)
205 function sendToFriends (t
, video
, callbackWaterfall
) {
206 video
.toAddRemoteJSON(function (err
, remoteVideo
) {
207 if (err
) return callbackWaterfall(err
)
209 // Now we'll add the video's meta data to our friends
210 friends
.addVideoToFriends(remoteVideo
, t
, function (err
) {
211 return callbackWaterfall(err
, t
)
216 ], function andFinally (err
, t
) {
218 // This is just a debug because we will retry the insert
219 logger
.debug('Cannot insert the video.', { error: err
})
221 // Abort transaction?
227 // Commit transaction
228 t
.commit().asCallback(function (err
) {
229 if (err
) return callback(err
)
231 logger
.info('Video with name %s created.', videoInfos
.name
)
232 return callback(null)
237 function updateVideoRetryWrapper (req
, res
, next
) {
239 arguments: [ req
, res
],
240 errorMessage: 'Cannot update the video with many retries.'
243 databaseUtils
.retryTransactionWrapper(updateVideo
, options
, function (err
) {
244 if (err
) return next(err
)
246 // TODO : include Location of the new video -> 201
247 return res
.type('json').status(204).end()
251 function updateVideo (req
, res
, finalCallback
) {
252 const videoInstance
= res
.locals
.video
253 const videoFieldsSave
= videoInstance
.toJSON()
254 const videoInfosToUpdate
= req
.body
258 databaseUtils
.startSerializableTransaction
,
260 function findOrCreateTags (t
, callback
) {
261 if (videoInfosToUpdate
.tags
) {
262 db
.Tag
.findOrCreateTags(videoInfosToUpdate
.tags
, t
, function (err
, tagInstances
) {
263 return callback(err
, t
, tagInstances
)
266 return callback(null, t
, null)
270 function updateVideoIntoDB (t
, tagInstances
, callback
) {
275 if (videoInfosToUpdate
.name
) videoInstance
.set('name', videoInfosToUpdate
.name
)
276 if (videoInfosToUpdate
.description
) videoInstance
.set('description', videoInfosToUpdate
.description
)
278 videoInstance
.save(options
).asCallback(function (err
) {
279 return callback(err
, t
, tagInstances
)
283 function associateTagsToVideo (t
, tagInstances
, callback
) {
285 const options
= { transaction: t
}
287 videoInstance
.setTags(tagInstances
, options
).asCallback(function (err
) {
288 videoInstance
.Tags
= tagInstances
290 return callback(err
, t
)
293 return callback(null, t
)
297 function sendToFriends (t
, callback
) {
298 const json
= videoInstance
.toUpdateRemoteJSON()
300 // Now we'll update the video's meta data to our friends
301 friends
.updateVideoToFriends(json
, t
, function (err
) {
302 return callback(err
, t
)
306 ], function andFinally (err
, t
) {
308 logger
.debug('Cannot update the video.', { error: err
})
310 // Abort transaction?
313 // Force fields we want to update
314 // If the transaction is retried, sequelize will think the object has not changed
315 // So it will skip the SQL request, even if the last one was ROLLBACKed!
316 Object
.keys(videoFieldsSave
).forEach(function (key
) {
317 const value
= videoFieldsSave
[key
]
318 videoInstance
.set(key
, value
)
321 return finalCallback(err
)
324 // Commit transaction
325 t
.commit().asCallback(function (err
) {
326 if (err
) return finalCallback(err
)
328 logger
.info('Video with name %s updated.', videoInfosToUpdate
.name
)
329 return finalCallback(null)
334 function getVideo (req
, res
, next
) {
335 const videoInstance
= res
.locals
.video
336 res
.json(videoInstance
.toFormatedJSON())
339 function listVideos (req
, res
, next
) {
340 db
.Video
.listForApi(req
.query
.start
, req
.query
.count
, req
.query
.sort
, function (err
, videosList
, videosTotal
) {
341 if (err
) return next(err
)
343 res
.json(utils
.getFormatedObjects(videosList
, videosTotal
))
347 function removeVideo (req
, res
, next
) {
348 const videoInstance
= res
.locals
.video
350 videoInstance
.destroy().asCallback(function (err
) {
352 logger
.error('Errors when removed the video.', { error: err
})
356 return res
.type('json').status(204).end()
360 function searchVideos (req
, res
, next
) {
361 db
.Video
.searchAndPopulateAuthorAndPodAndTags(
362 req
.params
.value
, req
.query
.field
, req
.query
.start
, req
.query
.count
, req
.query
.sort
,
363 function (err
, videosList
, videosTotal
) {
364 if (err
) return next(err
)
366 res
.json(utils
.getFormatedObjects(videosList
, videosTotal
))
371 function listVideoAbuses (req
, res
, next
) {
372 db
.VideoAbuse
.listForApi(req
.query
.start
, req
.query
.count
, req
.query
.sort
, function (err
, abusesList
, abusesTotal
) {
373 if (err
) return next(err
)
375 res
.json(utils
.getFormatedObjects(abusesList
, abusesTotal
))
379 function reportVideoAbuseRetryWrapper (req
, res
, next
) {
381 arguments: [ req
, res
],
382 errorMessage: 'Cannot report abuse to the video with many retries.'
385 databaseUtils
.retryTransactionWrapper(reportVideoAbuse
, options
, function (err
) {
386 if (err
) return next(err
)
388 return res
.type('json').status(204).end()
392 function reportVideoAbuse (req
, res
, finalCallback
) {
393 const videoInstance
= res
.locals
.video
394 const reporterUsername
= res
.locals
.oauth
.token
.User
.username
398 reason: req
.body
.reason
,
399 videoId: videoInstance
.id
,
400 reporterPodId: null // This is our pod that reported this abuse
405 function startTransaction (callback
) {
406 db
.sequelize
.transaction().asCallback(function (err
, t
) {
407 return callback(err
, t
)
411 function createAbuse (t
, callback
) {
412 db
.VideoAbuse
.create(abuse
).asCallback(function (err
, abuse
) {
413 return callback(err
, t
, abuse
)
417 function sendToFriendsIfNeeded (t
, abuse
, callback
) {
418 // We send the information to the destination pod
419 if (videoInstance
.isOwned() === false) {
422 reportReason: abuse
.reason
,
423 videoRemoteId: videoInstance
.remoteId
426 friends
.reportAbuseVideoToFriend(reportData
, videoInstance
)
429 return callback(null, t
)
432 ], function andFinally (err
, t
) {
434 logger
.debug('Cannot update the video.', { error: err
})
436 // Abort transaction?
439 return finalCallback(err
)
442 // Commit transaction
443 t
.commit().asCallback(function (err
) {
444 if (err
) return finalCallback(err
)
446 logger
.info('Abuse report for video %s created.', videoInstance
.name
)
447 return finalCallback(null)