3 const eachSeries
= require('async/eachSeries')
4 const express
= require('express')
5 const waterfall
= require('async/waterfall')
7 const db
= require('../../../initializers/database')
8 const constants
= require('../../../initializers/constants')
9 const middlewares
= require('../../../middlewares')
10 const secureMiddleware
= middlewares
.secure
11 const videosValidators
= middlewares
.validators
.remote
.videos
12 const signatureValidators
= middlewares
.validators
.remote
.signature
13 const logger
= require('../../../helpers/logger')
14 const friends
= require('../../../lib/friends')
15 const databaseUtils
= require('../../../helpers/database-utils')
17 const ENDPOINT_ACTIONS
= constants
.REQUEST_ENDPOINT_ACTIONS
[constants
.REQUEST_ENDPOINTS
.VIDEOS
]
19 // Functions to call when processing a remote request
20 const functionsHash
= {}
21 functionsHash
[ENDPOINT_ACTIONS
.ADD
] = addRemoteVideoRetryWrapper
22 functionsHash
[ENDPOINT_ACTIONS
.UPDATE
] = updateRemoteVideoRetryWrapper
23 functionsHash
[ENDPOINT_ACTIONS
.REMOVE
] = removeRemoteVideo
24 functionsHash
[ENDPOINT_ACTIONS
.REPORT_ABUSE
] = reportAbuseRemoteVideo
26 const router
= express
.Router()
29 signatureValidators
.signature
,
30 secureMiddleware
.checkSignature
,
31 videosValidators
.remoteVideos
,
36 signatureValidators
.signature
,
37 secureMiddleware
.checkSignature
,
38 videosValidators
.remoteQaduVideos
,
42 router
.post('/events',
43 signatureValidators
.signature
,
44 secureMiddleware
.checkSignature
,
45 videosValidators
.remoteEventsVideos
,
49 // ---------------------------------------------------------------------------
51 module
.exports
= router
53 // ---------------------------------------------------------------------------
55 function remoteVideos (req
, res
, next
) {
56 const requests
= req
.body
.data
57 const fromPod
= res
.locals
.secure
.pod
59 // We need to process in the same order to keep consistency
61 eachSeries(requests
, function (request
, callbackEach
) {
62 const data
= request
.data
64 // Get the function we need to call in order to process the request
65 const fun
= functionsHash
[request
.type
]
66 if (fun
=== undefined) {
67 logger
.error('Unkown remote request type %s.', request
.type
)
68 return callbackEach(null)
71 fun
.call(this, data
, fromPod
, callbackEach
)
73 if (err
) logger
.error('Error managing remote videos.', { error: err
})
76 // We don't need to keep the other pod waiting
77 return res
.type('json').status(204).end()
80 function remoteVideosQadu (req
, res
, next
) {
81 const requests
= req
.body
.data
82 const fromPod
= res
.locals
.secure
.pod
84 eachSeries(requests
, function (request
, callbackEach
) {
85 const videoData
= request
.data
87 quickAndDirtyUpdateVideoRetryWrapper(videoData
, fromPod
, callbackEach
)
89 if (err
) logger
.error('Error managing remote videos.', { error: err
})
92 return res
.type('json').status(204).end()
95 function remoteVideosEvents (req
, res
, next
) {
96 const requests
= req
.body
.data
97 const fromPod
= res
.locals
.secure
.pod
99 eachSeries(requests
, function (request
, callbackEach
) {
100 const eventData
= request
.data
102 processVideosEventsRetryWrapper(eventData
, fromPod
, callbackEach
)
104 if (err
) logger
.error('Error managing remote videos.', { error: err
})
107 return res
.type('json').status(204).end()
110 function processVideosEventsRetryWrapper (eventData
, fromPod
, finalCallback
) {
112 arguments: [ eventData
, fromPod
],
113 errorMessage: 'Cannot process videos events with many retries.'
116 databaseUtils
.retryTransactionWrapper(processVideosEvents
, options
, finalCallback
)
119 function processVideosEvents (eventData
, fromPod
, finalCallback
) {
121 databaseUtils
.startSerializableTransaction
,
123 function findVideo (t
, callback
) {
124 fetchOwnedVideo(eventData
.remoteId
, function (err
, videoInstance
) {
125 return callback(err
, t
, videoInstance
)
129 function updateVideoIntoDB (t
, videoInstance
, callback
) {
130 const options
= { transaction: t
}
135 switch (eventData
.eventType
) {
136 case constants
.REQUEST_VIDEO_EVENT_TYPES
.VIEWS:
137 columnToUpdate
= 'views'
138 qaduType
= constants
.REQUEST_VIDEO_QADU_TYPES
.VIEWS
141 case constants
.REQUEST_VIDEO_EVENT_TYPES
.LIKES:
142 columnToUpdate
= 'likes'
143 qaduType
= constants
.REQUEST_VIDEO_QADU_TYPES
.LIKES
146 case constants
.REQUEST_VIDEO_EVENT_TYPES
.DISLIKES:
147 columnToUpdate
= 'dislikes'
148 qaduType
= constants
.REQUEST_VIDEO_QADU_TYPES
.DISLIKES
152 return callback(new Error('Unknown video event type.'))
156 query
[columnToUpdate
] = eventData
.count
158 videoInstance
.increment(query
, options
).asCallback(function (err
) {
159 return callback(err
, t
, videoInstance
, qaduType
)
163 function sendQaduToFriends (t
, videoInstance
, qaduType
, callback
) {
164 const qadusParams
= [
166 videoId: videoInstance
.id
,
171 friends
.quickAndDirtyUpdatesVideoToFriends(qadusParams
, t
, function (err
) {
172 return callback(err
, t
)
176 databaseUtils
.commitTransaction
178 ], function (err
, t
) {
180 logger
.debug('Cannot process a video event.', { error: err
})
181 return databaseUtils
.rollbackTransaction(err
, t
, finalCallback
)
184 logger
.info('Remote video event processed for video %s.', eventData
.remoteId
)
185 return finalCallback(null)
189 function quickAndDirtyUpdateVideoRetryWrapper (videoData
, fromPod
, finalCallback
) {
191 arguments: [ videoData
, fromPod
],
192 errorMessage: 'Cannot update quick and dirty the remote video with many retries.'
195 databaseUtils
.retryTransactionWrapper(quickAndDirtyUpdateVideo
, options
, finalCallback
)
198 function quickAndDirtyUpdateVideo (videoData
, fromPod
, finalCallback
) {
200 databaseUtils
.startSerializableTransaction
,
202 function findVideo (t
, callback
) {
203 fetchRemoteVideo(fromPod
.host
, videoData
.remoteId
, function (err
, videoInstance
) {
204 return callback(err
, t
, videoInstance
)
208 function updateVideoIntoDB (t
, videoInstance
, callback
) {
209 const options
= { transaction: t
}
211 if (videoData
.views
) {
212 videoInstance
.set('views', videoData
.views
)
215 if (videoData
.likes
) {
216 videoInstance
.set('likes', videoData
.likes
)
219 if (videoData
.dislikes
) {
220 videoInstance
.set('dislikes', videoData
.dislikes
)
223 videoInstance
.save(options
).asCallback(function (err
) {
224 return callback(err
, t
)
228 databaseUtils
.commitTransaction
230 ], function (err
, t
) {
232 logger
.debug('Cannot quick and dirty update the remote video.', { error: err
})
233 return databaseUtils
.rollbackTransaction(err
, t
, finalCallback
)
236 logger
.info('Remote video %s quick and dirty updated', videoData
.name
)
237 return finalCallback(null)
241 // Handle retries on fail
242 function addRemoteVideoRetryWrapper (videoToCreateData
, fromPod
, finalCallback
) {
244 arguments: [ videoToCreateData
, fromPod
],
245 errorMessage: 'Cannot insert the remote video with many retries.'
248 databaseUtils
.retryTransactionWrapper(addRemoteVideo
, options
, finalCallback
)
251 function addRemoteVideo (videoToCreateData
, fromPod
, finalCallback
) {
252 logger
.debug('Adding remote video "%s".', videoToCreateData
.remoteId
)
256 databaseUtils
.startSerializableTransaction
,
258 function assertRemoteIdAndHostUnique (t
, callback
) {
259 db
.Video
.loadByHostAndRemoteId(fromPod
.host
, videoToCreateData
.remoteId
, function (err
, video
) {
260 if (err
) return callback(err
)
262 if (video
) return callback(new Error('RemoteId and host pair is not unique.'))
264 return callback(null, t
)
268 function findOrCreateAuthor (t
, callback
) {
269 const name
= videoToCreateData
.author
270 const podId
= fromPod
.id
271 // This author is from another pod so we do not associate a user
274 db
.Author
.findOrCreateAuthor(name
, podId
, userId
, t
, function (err
, authorInstance
) {
275 return callback(err
, t
, authorInstance
)
279 function findOrCreateTags (t
, author
, callback
) {
280 const tags
= videoToCreateData
.tags
282 db
.Tag
.findOrCreateTags(tags
, t
, function (err
, tagInstances
) {
283 return callback(err
, t
, author
, tagInstances
)
287 function createVideoObject (t
, author
, tagInstances
, callback
) {
289 name: videoToCreateData
.name
,
290 remoteId: videoToCreateData
.remoteId
,
291 extname: videoToCreateData
.extname
,
292 infoHash: videoToCreateData
.infoHash
,
293 description: videoToCreateData
.description
,
295 duration: videoToCreateData
.duration
,
296 createdAt: videoToCreateData
.createdAt
,
297 // FIXME: updatedAt does not seems to be considered by Sequelize
298 updatedAt: videoToCreateData
.updatedAt
,
299 views: videoToCreateData
.views
,
300 likes: videoToCreateData
.likes
,
301 dislikes: videoToCreateData
.dislikes
304 const video
= db
.Video
.build(videoData
)
306 return callback(null, t
, tagInstances
, video
)
309 function generateThumbnail (t
, tagInstances
, video
, callback
) {
310 db
.Video
.generateThumbnailFromData(video
, videoToCreateData
.thumbnailData
, function (err
) {
312 logger
.error('Cannot generate thumbnail from data.', { error: err
})
316 return callback(err
, t
, tagInstances
, video
)
320 function insertVideoIntoDB (t
, tagInstances
, video
, callback
) {
325 video
.save(options
).asCallback(function (err
, videoCreated
) {
326 return callback(err
, t
, tagInstances
, videoCreated
)
330 function associateTagsToVideo (t
, tagInstances
, video
, callback
) {
335 video
.setTags(tagInstances
, options
).asCallback(function (err
) {
336 return callback(err
, t
)
340 databaseUtils
.commitTransaction
342 ], function (err
, t
) {
344 // This is just a debug because we will retry the insert
345 logger
.debug('Cannot insert the remote video.', { error: err
})
346 return databaseUtils
.rollbackTransaction(err
, t
, finalCallback
)
349 logger
.info('Remote video %s inserted.', videoToCreateData
.name
)
350 return finalCallback(null)
354 // Handle retries on fail
355 function updateRemoteVideoRetryWrapper (videoAttributesToUpdate
, fromPod
, finalCallback
) {
357 arguments: [ videoAttributesToUpdate
, fromPod
],
358 errorMessage: 'Cannot update the remote video with many retries'
361 databaseUtils
.retryTransactionWrapper(updateRemoteVideo
, options
, finalCallback
)
364 function updateRemoteVideo (videoAttributesToUpdate
, fromPod
, finalCallback
) {
365 logger
.debug('Updating remote video "%s".', videoAttributesToUpdate
.remoteId
)
369 databaseUtils
.startSerializableTransaction
,
371 function findVideo (t
, callback
) {
372 fetchRemoteVideo(fromPod
.host
, videoAttributesToUpdate
.remoteId
, function (err
, videoInstance
) {
373 return callback(err
, t
, videoInstance
)
377 function findOrCreateTags (t
, videoInstance
, callback
) {
378 const tags
= videoAttributesToUpdate
.tags
380 db
.Tag
.findOrCreateTags(tags
, t
, function (err
, tagInstances
) {
381 return callback(err
, t
, videoInstance
, tagInstances
)
385 function updateVideoIntoDB (t
, videoInstance
, tagInstances
, callback
) {
386 const options
= { transaction: t
}
388 videoInstance
.set('name', videoAttributesToUpdate
.name
)
389 videoInstance
.set('description', videoAttributesToUpdate
.description
)
390 videoInstance
.set('infoHash', videoAttributesToUpdate
.infoHash
)
391 videoInstance
.set('duration', videoAttributesToUpdate
.duration
)
392 videoInstance
.set('createdAt', videoAttributesToUpdate
.createdAt
)
393 videoInstance
.set('updatedAt', videoAttributesToUpdate
.updatedAt
)
394 videoInstance
.set('extname', videoAttributesToUpdate
.extname
)
395 videoInstance
.set('views', videoAttributesToUpdate
.views
)
396 videoInstance
.set('likes', videoAttributesToUpdate
.likes
)
397 videoInstance
.set('dislikes', videoAttributesToUpdate
.dislikes
)
399 videoInstance
.save(options
).asCallback(function (err
) {
400 return callback(err
, t
, videoInstance
, tagInstances
)
404 function associateTagsToVideo (t
, videoInstance
, tagInstances
, callback
) {
405 const options
= { transaction: t
}
407 videoInstance
.setTags(tagInstances
, options
).asCallback(function (err
) {
408 return callback(err
, t
)
412 databaseUtils
.commitTransaction
414 ], function (err
, t
) {
416 // This is just a debug because we will retry the insert
417 logger
.debug('Cannot update the remote video.', { error: err
})
418 return databaseUtils
.rollbackTransaction(err
, t
, finalCallback
)
421 logger
.info('Remote video %s updated', videoAttributesToUpdate
.name
)
422 return finalCallback(null)
426 function removeRemoteVideo (videoToRemoveData
, fromPod
, callback
) {
427 // We need the instance because we have to remove some other stuffs (thumbnail etc)
428 fetchRemoteVideo(fromPod
.host
, videoToRemoveData
.remoteId
, function (err
, video
) {
429 // Do not return the error, continue the process
430 if (err
) return callback(null)
432 logger
.debug('Removing remote video %s.', video
.remoteId
)
433 video
.destroy().asCallback(function (err
) {
434 // Do not return the error, continue the process
436 logger
.error('Cannot remove remote video with id %s.', videoToRemoveData
.remoteId
, { error: err
})
439 return callback(null)
444 function reportAbuseRemoteVideo (reportData
, fromPod
, callback
) {
445 fetchOwnedVideo(reportData
.videoRemoteId
, function (err
, video
) {
447 if (!err
) err
= new Error('video not found')
449 logger
.error('Cannot load video from id.', { error: err
, id: reportData
.videoRemoteId
})
450 // Do not return the error, continue the process
451 return callback(null)
454 logger
.debug('Reporting remote abuse for video %s.', video
.id
)
456 const videoAbuseData
= {
457 reporterUsername: reportData
.reporterUsername
,
458 reason: reportData
.reportReason
,
459 reporterPodId: fromPod
.id
,
463 db
.VideoAbuse
.create(videoAbuseData
).asCallback(function (err
) {
465 logger
.error('Cannot create remote abuse video.', { error: err
})
468 return callback(null)
473 function fetchOwnedVideo (id
, callback
) {
474 db
.Video
.load(id
, function (err
, video
) {
476 if (!err
) err
= new Error('video not found')
478 logger
.error('Cannot load owned video from id.', { error: err
, id
})
482 return callback(null, video
)
486 function fetchRemoteVideo (podHost
, remoteId
, callback
) {
487 db
.Video
.loadByHostAndRemoteId(podHost
, remoteId
, function (err
, video
) {
489 if (!err
) err
= new Error('video not found')
491 logger
.error('Cannot load video from host and remote id.', { error: err
, podHost
, remoteId
})
495 return callback(null, video
)