1
0
Fork 0

Update to standard 7. Goodbye snake_case, I used to love you

This commit is contained in:
Chocobozzz 2016-05-11 21:19:34 +02:00
parent 881a5e68b6
commit bc503c2a62
27 changed files with 349 additions and 351 deletions

View file

@ -77,7 +77,7 @@
"node-livereload": "^0.6.0", "node-livereload": "^0.6.0",
"node-sass": "^3.4.2", "node-sass": "^3.4.2",
"scripty": "^1.5.0", "scripty": "^1.5.0",
"standard": "^6.0.1", "standard": "^7.0.1",
"supertest": "^1.1.0" "supertest": "^1.1.0"
}, },
"standard": { "standard": {

View file

@ -65,8 +65,8 @@ app.use(require('connect-livereload')({
require('segfault-handler').registerHandler() require('segfault-handler').registerHandler()
// API routes // API routes
const api_route = '/api/' + constants.API_VERSION const apiRoute = '/api/' + constants.API_VERSION
app.use(api_route, routes.api) app.use(apiRoute, routes.api)
// Static files // Static files
app.use('/app', express.static(path.join(__dirname, '/client'), { maxAge: 0 })) app.use('/app', express.static(path.join(__dirname, '/client'), { maxAge: 0 }))
@ -76,8 +76,8 @@ app.use('/app/*', function (req, res, next) {
}) })
// Thumbnails path for express // Thumbnails path for express
const thumbnails_physical_path = path.join(__dirname, config.get('storage.thumbnails')) const thumbnailsPhysicalPath = path.join(__dirname, config.get('storage.thumbnails'))
app.use(constants.THUMBNAILS_STATIC_PATH, express.static(thumbnails_physical_path, { maxAge: 0 })) app.use(constants.THUMBNAILS_STATIC_PATH, express.static(thumbnailsPhysicalPath, { maxAge: 0 }))
// Client application // Client application
app.use('/*', function (req, res, next) { app.use('/*', function (req, res, next) {

View file

@ -44,23 +44,23 @@ function addPods (req, res, next) {
return next(err) return next(err)
} }
Videos.listOwned(function (err, videos_list) { Videos.listOwned(function (err, videosList) {
if (err) { if (err) {
logger.error('Cannot get the list of owned videos.') logger.error('Cannot get the list of owned videos.')
return next(err) return next(err)
} }
res.json({ cert: cert, videos: videos_list }) res.json({ cert: cert, videos: videosList })
}) })
}) })
}) })
} }
function listPods (req, res, next) { function listPods (req, res, next) {
Pods.list(function (err, pods_list) { Pods.list(function (err, podsList) {
if (err) return next(err) if (err) return next(err)
res.json(pods_list) res.json(podsList)
}) })
} }
@ -77,13 +77,13 @@ function removePods (req, res, next) {
Pods.remove(url, function (err) { Pods.remove(url, function (err) {
if (err) return next(err) if (err) return next(err)
Videos.listFromUrl(url, function (err, videos_list) { Videos.listFromUrl(url, function (err, videosList) {
if (err) { if (err) {
logger.error('Cannot list videos from url.', { error: err }) logger.error('Cannot list videos from url.', { error: err })
next(err) next(err)
} }
videos.removeRemoteVideos(videos_list, function (err) { videos.removeRemoteVideos(videosList, function (err) {
if (err) { if (err) {
logger.error('Cannot remove remote videos.', { error: err }) logger.error('Cannot remove remote videos.', { error: err })
next(err) next(err)

View file

@ -36,8 +36,8 @@ module.exports = router
// --------------------------------------------------------------------------- // ---------------------------------------------------------------------------
function addRemoteVideos (req, res, next) { function addRemoteVideos (req, res, next) {
const videos_to_create = req.body.data const videosToCreate = req.body.data
videos.createRemoteVideos(videos_to_create, function (err, remote_videos) { videos.createRemoteVideos(videosToCreate, function (err, remoteVideos) {
if (err) { if (err) {
logger.error('Cannot create remote videos.', { error: err }) logger.error('Cannot create remote videos.', { error: err })
return next(err) return next(err)
@ -51,13 +51,13 @@ function removeRemoteVideo (req, res, next) {
const fromUrl = req.body.signature.url const fromUrl = req.body.signature.url
const magnetUris = map(req.body.data, 'magnetUri') const magnetUris = map(req.body.data, 'magnetUri')
Videos.listFromUrlAndMagnets(fromUrl, magnetUris, function (err, videos_list) { Videos.listFromUrlAndMagnets(fromUrl, magnetUris, function (err, videosList) {
if (err) { if (err) {
logger.error('Cannot list videos from url and magnets.', { error: err }) logger.error('Cannot list videos from url and magnets.', { error: err })
return next(err) return next(err)
} }
videos.removeRemoteVideos(videos_list, function (err) { videos.removeRemoteVideos(videosList, function (err) {
if (err) { if (err) {
logger.error('Cannot remove remote videos.', { error: err }) logger.error('Cannot remove remote videos.', { error: err })
return next(err) return next(err)

View file

@ -20,14 +20,14 @@ module.exports = router
// --------------------------------------------------------------------------- // ---------------------------------------------------------------------------
function getAngularClient (req, res, next) { function getAngularClient (req, res, next) {
const server_host = config.get('webserver.host') const serverHost = config.get('webserver.host')
const server_port = config.get('webserver.port') const serverPort = config.get('webserver.port')
let header_host_should_be = server_host let headerHostShouldBe = serverHost
if (server_port !== 80 && server_port !== 443) { if (serverPort !== 80 && serverPort !== 443) {
header_host_should_be += ':' + server_port headerHostShouldBe += ':' + serverPort
} }
if (req.get('host') !== header_host_should_be) return res.type('json').status(403).end() if (req.get('host') !== headerHostShouldBe) return res.type('json').status(403).end()
Users.getFirstClient(function (err, client) { Users.getFirstClient(function (err, client) {
if (err) return next(err) if (err) return next(err)

View file

@ -32,8 +32,8 @@ const storage = multer.diskStorage({
if (file.mimetype === 'video/webm') extension = 'webm' if (file.mimetype === 'video/webm') extension = 'webm'
else if (file.mimetype === 'video/mp4') extension = 'mp4' else if (file.mimetype === 'video/mp4') extension = 'mp4'
else if (file.mimetype === 'video/ogg') extension = 'ogv' else if (file.mimetype === 'video/ogg') extension = 'ogv'
utils.generateRandomString(16, function (err, random_string) { utils.generateRandomString(16, function (err, randomString) {
const fieldname = err ? undefined : random_string const fieldname = err ? undefined : randomString
cb(null, fieldname + '.' + extension) cb(null, fieldname + '.' + extension)
}) })
} }
@ -55,47 +55,47 @@ module.exports = router
// --------------------------------------------------------------------------- // ---------------------------------------------------------------------------
function addVideo (req, res, next) { function addVideo (req, res, next) {
const video_file = req.files.videofile[0] const videoFile = req.files.videofile[0]
const video_infos = req.body const videoInfos = req.body
videos.seed(video_file.path, function (err, torrent) { videos.seed(videoFile.path, function (err, torrent) {
if (err) { if (err) {
logger.error('Cannot seed this video.') logger.error('Cannot seed this video.')
return next(err) return next(err)
} }
videos.getVideoDuration(video_file.path, function (err, duration) { videos.getVideoDuration(videoFile.path, function (err, duration) {
if (err) { if (err) {
// TODO: unseed the video // TODO: unseed the video
logger.error('Cannot retrieve metadata of the file.') logger.error('Cannot retrieve metadata of the file.')
return next(err) return next(err)
} }
videos.getVideoThumbnail(video_file.path, function (err, thumbnail_name) { videos.getVideoThumbnail(videoFile.path, function (err, thumbnailName) {
if (err) { if (err) {
// TODO: unseed the video // TODO: unseed the video
logger.error('Cannot make a thumbnail of the video file.') logger.error('Cannot make a thumbnail of the video file.')
return next(err) return next(err)
} }
const video_data = { const videoData = {
name: video_infos.name, name: videoInfos.name,
namePath: video_file.filename, namePath: videoFile.filename,
description: video_infos.description, description: videoInfos.description,
magnetUri: torrent.magnetURI, magnetUri: torrent.magnetURI,
author: res.locals.oauth.token.user.username, author: res.locals.oauth.token.user.username,
duration: duration, duration: duration,
thumbnail: thumbnail_name thumbnail: thumbnailName
} }
Videos.add(video_data, function (err) { Videos.add(videoData, function (err) {
if (err) { if (err) {
// TODO unseed the video // TODO unseed the video
logger.error('Cannot insert this video in the database.') logger.error('Cannot insert this video in the database.')
return next(err) return next(err)
} }
fs.readFile(thumbnailsDir + thumbnail_name, function (err, data) { fs.readFile(thumbnailsDir + thumbnailName, function (err, data) {
if (err) { if (err) {
// TODO: remove video? // TODO: remove video?
logger.error('Cannot read the thumbnail of the video') logger.error('Cannot read the thumbnail of the video')
@ -103,9 +103,9 @@ function addVideo (req, res, next) {
} }
// Set the image in base64 // Set the image in base64
video_data.thumbnail_base64 = new Buffer(data).toString('base64') videoData.thumbnailBase64 = new Buffer(data).toString('base64')
// Now we'll add the video's meta data to our friends // Now we'll add the video's meta data to our friends
friends.addVideoToFriends(video_data) friends.addVideoToFriends(videoData)
// TODO : include Location of the new video -> 201 // TODO : include Location of the new video -> 201
res.type('json').status(204).end() res.type('json').status(204).end()
@ -117,29 +117,29 @@ function addVideo (req, res, next) {
} }
function getVideos (req, res, next) { function getVideos (req, res, next) {
Videos.get(req.params.id, function (err, video_obj) { Videos.get(req.params.id, function (err, videoObj) {
if (err) return next(err) if (err) return next(err)
const state = videos.getVideoState(video_obj) const state = videos.getVideoState(videoObj)
if (state.exist === false) { if (state.exist === false) {
return res.type('json').status(204).end() return res.type('json').status(204).end()
} }
res.json(getFormatedVideo(video_obj)) res.json(getFormatedVideo(videoObj))
}) })
} }
function listVideos (req, res, next) { function listVideos (req, res, next) {
Videos.list(function (err, videos_list) { Videos.list(function (err, videosList) {
if (err) return next(err) if (err) return next(err)
res.json(getFormatedVideos(videos_list)) res.json(getFormatedVideos(videosList))
}) })
} }
function removeVideo (req, res, next) { function removeVideo (req, res, next) {
const video_id = req.params.id const videoId = req.params.id
Videos.get(video_id, function (err, video) { Videos.get(videoId, function (err, video) {
if (err) return next(err) if (err) return next(err)
removeTorrent(video.magnetUri, function () { removeTorrent(video.magnetUri, function () {
@ -163,39 +163,39 @@ function removeVideo (req, res, next) {
} }
function searchVideos (req, res, next) { function searchVideos (req, res, next) {
Videos.search(req.params.name, function (err, videos_list) { Videos.search(req.params.name, function (err, videosList) {
if (err) return next(err) if (err) return next(err)
res.json(getFormatedVideos(videos_list)) res.json(getFormatedVideos(videosList))
}) })
} }
// --------------------------------------------------------------------------- // ---------------------------------------------------------------------------
function getFormatedVideo (video_obj) { function getFormatedVideo (videoObj) {
const formated_video = { const formatedVideo = {
id: video_obj._id, id: videoObj._id,
name: video_obj.name, name: videoObj.name,
description: video_obj.description, description: videoObj.description,
podUrl: video_obj.podUrl, podUrl: videoObj.podUrl,
isLocal: videos.getVideoState(video_obj).owned, isLocal: videos.getVideoState(videoObj).owned,
magnetUri: video_obj.magnetUri, magnetUri: videoObj.magnetUri,
author: video_obj.author, author: videoObj.author,
duration: video_obj.duration, duration: videoObj.duration,
thumbnailPath: constants.THUMBNAILS_STATIC_PATH + '/' + video_obj.thumbnail thumbnailPath: constants.THUMBNAILS_STATIC_PATH + '/' + videoObj.thumbnail
} }
return formated_video return formatedVideo
} }
function getFormatedVideos (videos_obj) { function getFormatedVideos (videosObj) {
const formated_videos = [] const formatedVideos = []
videos_obj.forEach(function (video_obj) { videosObj.forEach(function (videoObj) {
formated_videos.push(getFormatedVideo(video_obj)) formatedVideos.push(getFormatedVideo(videoObj))
}) })
return formated_videos return formatedVideos
} }
// Maybe the torrent is not seeded, but we catch the error to don't stop the removing process // Maybe the torrent is not seeded, but we catch the error to don't stop the removing process

View file

@ -21,10 +21,10 @@ const peertubeCrypto = {
sign: sign sign: sign
} }
function checkSignature (public_key, raw_data, hex_signature) { function checkSignature (publicKey, rawData, hexSignature) {
const crt = ursa.createPublicKey(public_key) const crt = ursa.createPublicKey(publicKey)
const is_valid = crt.hashAndVerify('sha256', new Buffer(raw_data).toString('hex'), hex_signature, 'hex') const isValid = crt.hashAndVerify('sha256', new Buffer(rawData).toString('hex'), hexSignature, 'hex')
return is_valid return isValid
} }
function createCertsIfNotExist (callback) { function createCertsIfNotExist (callback) {
@ -43,16 +43,16 @@ function decrypt (key, data, callback) {
fs.readFile(getCertDir() + 'peertube.key.pem', function (err, file) { fs.readFile(getCertDir() + 'peertube.key.pem', function (err, file) {
if (err) return callback(err) if (err) return callback(err)
const my_private_key = ursa.createPrivateKey(file) const myPrivateKey = ursa.createPrivateKey(file)
const decrypted_key = my_private_key.decrypt(key, 'hex', 'utf8') const decryptedKey = myPrivateKey.decrypt(key, 'hex', 'utf8')
const decrypted_data = symetricDecrypt(data, decrypted_key) const decryptedData = symetricDecrypt(data, decryptedKey)
return callback(null, decrypted_data) return callback(null, decryptedData)
}) })
} }
function encrypt (public_key, data, callback) { function encrypt (publicKey, data, callback) {
const crt = ursa.createPublicKey(public_key) const crt = ursa.createPublicKey(publicKey)
symetricEncrypt(data, function (err, dataEncrypted) { symetricEncrypt(data, function (err, dataEncrypted) {
if (err) return callback(err) if (err) return callback(err)

View file

@ -17,7 +17,7 @@ const requests = {
makeMultipleRetryRequest: makeMultipleRetryRequest makeMultipleRetryRequest: makeMultipleRetryRequest
} }
function makeMultipleRetryRequest (all_data, pods, callbackEach, callback) { function makeMultipleRetryRequest (allData, pods, callbackEach, callback) {
if (!callback) { if (!callback) {
callback = callbackEach callback = callbackEach
callbackEach = null callbackEach = null
@ -27,32 +27,32 @@ function makeMultipleRetryRequest (all_data, pods, callbackEach, callback) {
let signature let signature
// Add signature if it is specified in the params // Add signature if it is specified in the params
if (all_data.method === 'POST' && all_data.data && all_data.sign === true) { if (allData.method === 'POST' && allData.data && allData.sign === true) {
signature = peertubeCrypto.sign(url) signature = peertubeCrypto.sign(url)
} }
// Make a request for each pod // Make a request for each pod
async.each(pods, function (pod, callback_each_async) { async.each(pods, function (pod, callbackEachAsync) {
function callbackEachRetryRequest (err, response, body, url, pod) { function callbackEachRetryRequest (err, response, body, url, pod) {
if (callbackEach !== null) { if (callbackEach !== null) {
callbackEach(err, response, body, url, pod, function () { callbackEach(err, response, body, url, pod, function () {
callback_each_async() callbackEachAsync()
}) })
} else { } else {
callback_each_async() callbackEachAsync()
} }
} }
const params = { const params = {
url: pod.url + all_data.path, url: pod.url + allData.path,
method: all_data.method method: allData.method
} }
// Add data with POST requst ? // Add data with POST requst ?
if (all_data.method === 'POST' && all_data.data) { if (allData.method === 'POST' && allData.data) {
// Encrypt data ? // Encrypt data ?
if (all_data.encrypt === true) { if (allData.encrypt === true) {
peertubeCrypto.encrypt(pod.publicKey, JSON.stringify(all_data.data), function (err, encrypted) { peertubeCrypto.encrypt(pod.publicKey, JSON.stringify(allData.data), function (err, encrypted) {
if (err) return callback(err) if (err) return callback(err)
params.json = { params.json = {
@ -63,7 +63,7 @@ function makeMultipleRetryRequest (all_data, pods, callbackEach, callback) {
makeRetryRequest(params, url, pod, signature, callbackEachRetryRequest) makeRetryRequest(params, url, pod, signature, callbackEachRetryRequest)
}) })
} else { } else {
params.json = { data: all_data.data } params.json = { data: allData.data }
makeRetryRequest(params, url, pod, signature, callbackEachRetryRequest) makeRetryRequest(params, url, pod, signature, callbackEachRetryRequest)
} }
} else { } else {
@ -78,20 +78,20 @@ module.exports = requests
// --------------------------------------------------------------------------- // ---------------------------------------------------------------------------
function makeRetryRequest (params, from_url, to_pod, signature, callbackEach) { function makeRetryRequest (params, fromUrl, toPod, signature, callbackEach) {
// Append the signature // Append the signature
if (signature) { if (signature) {
params.json.signature = { params.json.signature = {
url: from_url, url: fromUrl,
signature: signature signature: signature
} }
} }
logger.debug('Make retry requests to %s.', to_pod.url) logger.debug('Make retry requests to %s.', toPod.url)
replay( replay(
request.post(params, function (err, response, body) { request.post(params, function (err, response, body) {
callbackEach(err, response, body, params.url, to_pod) callbackEach(err, response, body, params.url, toPod)
}), }),
{ {
retries: constants.REQUEST_RETRIES, retries: constants.REQUEST_RETRIES,

View file

@ -17,9 +17,9 @@ function generateRandomString (size, callback) {
}) })
} }
function cleanForExit (webtorrent_process) { function cleanForExit (webtorrentProcess) {
logger.info('Gracefully exiting.') logger.info('Gracefully exiting.')
process.kill(-webtorrent_process.pid) process.kill(-webtorrentProcess.pid)
} }
// --------------------------------------------------------------------------- // ---------------------------------------------------------------------------

View file

@ -39,8 +39,8 @@ function hasFriends (callback) {
Pods.count(function (err, count) { Pods.count(function (err, count) {
if (err) return callback(err) if (err) return callback(err)
const has_friends = (count !== 0) const hasFriends = (count !== 0)
callback(null, has_friends) callback(null, hasFriends)
}) })
} }
@ -49,7 +49,7 @@ function getMyCertificate (callback) {
} }
function makeFriends (callback) { function makeFriends (callback) {
const pods_score = {} const podsScore = {}
logger.info('Make friends!') logger.info('Make friends!')
getMyCertificate(function (err, cert) { getMyCertificate(function (err, cert) {
@ -60,16 +60,16 @@ function makeFriends (callback) {
const urls = config.get('network.friends') const urls = config.get('network.friends')
async.each(urls, function (url, callback_each) { async.each(urls, function (url, callbackEach) {
computeForeignPodsList(url, pods_score, callback_each) computeForeignPodsList(url, podsScore, callbackEach)
}, function (err) { }, function (err) {
if (err) return callback(err) if (err) return callback(err)
logger.debug('Pods scores computed.', { pods_score: pods_score }) logger.debug('Pods scores computed.', { podsScore: podsScore })
const pods_list = computeWinningPods(urls, pods_score) const podsList = computeWinningPods(urls, podsScore)
logger.debug('Pods that we keep.', { pods_to_keep: pods_list }) logger.debug('Pods that we keep.', { podsToKeep: podsList })
makeRequestsToWinningPods(cert, pods_list, callback) makeRequestsToWinningPods(cert, podsList, callback)
}) })
}) })
} }
@ -102,10 +102,10 @@ function quitFriends (callback) {
logger.info('Broke friends, so sad :(') logger.info('Broke friends, so sad :(')
Videos.listFromRemotes(function (err, videos_list) { Videos.listFromRemotes(function (err, videosList) {
if (err) return callback(err) if (err) return callback(err)
videos.removeRemoteVideos(videos_list, function (err) { videos.removeRemoteVideos(videosList, function (err) {
if (err) { if (err) {
logger.error('Cannot remove remote videos.', { error: err }) logger.error('Cannot remove remote videos.', { error: err })
return callback(err) return callback(err)
@ -132,35 +132,35 @@ module.exports = pods
// --------------------------------------------------------------------------- // ---------------------------------------------------------------------------
function computeForeignPodsList (url, pods_score, callback) { function computeForeignPodsList (url, podsScore, callback) {
// Let's give 1 point to the pod we ask the friends list // Let's give 1 point to the pod we ask the friends list
pods_score[url] = 1 podsScore[url] = 1
getForeignPodsList(url, function (err, foreign_pods_list) { getForeignPodsList(url, function (err, foreignPodsList) {
if (err) return callback(err) if (err) return callback(err)
if (foreign_pods_list.length === 0) return callback() if (foreignPodsList.length === 0) return callback()
foreign_pods_list.forEach(function (foreign_pod) { foreignPodsList.forEach(function (foreignPod) {
const foreign_url = foreign_pod.url const foreignUrl = foreignPod.url
if (pods_score[foreign_url]) pods_score[foreign_url]++ if (podsScore[foreignUrl]) podsScore[foreignUrl]++
else pods_score[foreign_url] = 1 else podsScore[foreignUrl] = 1
}) })
callback() callback()
}) })
} }
function computeWinningPods (urls, pods_score) { function computeWinningPods (urls, podsScore) {
// Build the list of pods to add // Build the list of pods to add
// Only add a pod if it exists in more than a half base pods // Only add a pod if it exists in more than a half base pods
const pods_list = [] const podsList = []
const base_score = urls.length / 2 const baseScore = urls.length / 2
Object.keys(pods_score).forEach(function (pod) { Object.keys(baseScore).forEach(function (pod) {
if (pods_score[pod] > base_score) pods_list.push({ url: pod }) if (podsScore[pod] > baseScore) podsList.push({ url: pod })
}) })
return pods_list return podsList
} }
function getForeignPodsList (url, callback) { function getForeignPodsList (url, callback) {
@ -173,14 +173,14 @@ function getForeignPodsList (url, callback) {
}) })
} }
function makeRequestsToWinningPods (cert, pods_list, callback) { function makeRequestsToWinningPods (cert, podsList, callback) {
// Stop pool requests // Stop pool requests
requestsScheduler.deactivate() requestsScheduler.deactivate()
// Flush pool requests // Flush pool requests
requestsScheduler.forceSend() requestsScheduler.forceSend()
// Get the list of our videos to send to our new friends // Get the list of our videos to send to our new friends
Videos.listOwned(function (err, videos_list) { Videos.listOwned(function (err, videosList) {
if (err) { if (err) {
logger.error('Cannot get the list of videos we own.') logger.error('Cannot get the list of videos we own.')
return callback(err) return callback(err)
@ -189,38 +189,36 @@ function makeRequestsToWinningPods (cert, pods_list, callback) {
const data = { const data = {
url: http + '://' + host + ':' + port, url: http + '://' + host + ':' + port,
publicKey: cert, publicKey: cert,
videos: videos_list videos: videosList
} }
requests.makeMultipleRetryRequest( requests.makeMultipleRetryRequest(
{ method: 'POST', path: '/api/' + constants.API_VERSION + '/pods/', data: data }, { method: 'POST', path: '/api/' + constants.API_VERSION + '/pods/', data: data },
pods_list, podsList,
function eachRequest (err, response, body, url, pod, callback_each_request) { function eachRequest (err, response, body, url, pod, callbackEachRequest) {
// We add the pod if it responded correctly with its public certificate // We add the pod if it responded correctly with its public certificate
if (!err && response.statusCode === 200) { if (!err && response.statusCode === 200) {
Pods.add({ url: pod.url, publicKey: body.cert, score: constants.FRIEND_BASE_SCORE }, function (err) { Pods.add({ url: pod.url, publicKey: body.cert, score: constants.FRIEND_BASE_SCORE }, function (err) {
if (err) { if (err) {
logger.error('Error with adding %s pod.', pod.url, { error: err }) logger.error('Error with adding %s pod.', pod.url, { error: err })
return callback_each_request() return callbackEachRequest()
} }
console.log('hihi')
videos.createRemoteVideos(body.videos, function (err) { videos.createRemoteVideos(body.videos, function (err) {
if (err) { if (err) {
logger.error('Error with adding videos of pod.', pod.url, { error: err }) logger.error('Error with adding videos of pod.', pod.url, { error: err })
return callback_each_request() return callbackEachRequest()
} }
console.log('kik')
logger.debug('Adding remote videos from %s.', pod.url, { videos: body.videos }) logger.debug('Adding remote videos from %s.', pod.url, { videos: body.videos })
return callback_each_request() return callbackEachRequest()
}) })
}) })
} else { } else {
logger.error('Error with adding %s pod.', pod.url, { error: err || new Error('Status not 200') }) logger.error('Error with adding %s pod.', pod.url, { error: err || new Error('Status not 200') })
return callback_each_request() return callbackEachRequest()
} }
}, },

View file

@ -72,7 +72,7 @@ module.exports = requestsScheduler
// --------------------------------------------------------------------------- // ---------------------------------------------------------------------------
function makeRequest (type, requests_to_make, callback) { function makeRequest (type, requestsToMake, callback) {
if (!callback) callback = function () {} if (!callback) callback = function () {}
Pods.list(function (err, pods) { Pods.list(function (err, pods) {
@ -83,7 +83,7 @@ function makeRequest (type, requests_to_make, callback) {
sign: true, sign: true,
method: 'POST', method: 'POST',
path: null, path: null,
data: requests_to_make data: requestsToMake
} }
if (type === 'add') { if (type === 'add') {
@ -94,26 +94,26 @@ function makeRequest (type, requests_to_make, callback) {
return callback(new Error('Unkown pool request type.')) return callback(new Error('Unkown pool request type.'))
} }
const bad_pods = [] const badPods = []
const good_pods = [] const goodPods = []
requests.makeMultipleRetryRequest(params, pods, callbackEachPodFinished, callbackAllPodsFinished) requests.makeMultipleRetryRequest(params, pods, callbackEachPodFinished, callbackAllPodsFinished)
function callbackEachPodFinished (err, response, body, url, pod, callback_each_pod_finished) { function callbackEachPodFinished (err, response, body, url, pod, callbackEachPodFinished) {
if (err || (response.statusCode !== 200 && response.statusCode !== 201 && response.statusCode !== 204)) { if (err || (response.statusCode !== 200 && response.statusCode !== 201 && response.statusCode !== 204)) {
bad_pods.push(pod._id) badPods.push(pod._id)
logger.error('Error sending secure request to %s pod.', url, { error: err || new Error('Status code not 20x') }) logger.error('Error sending secure request to %s pod.', url, { error: err || new Error('Status code not 20x') })
} else { } else {
good_pods.push(pod._id) goodPods.push(pod._id)
} }
return callback_each_pod_finished() return callbackEachPodFinished()
} }
function callbackAllPodsFinished (err) { function callbackAllPodsFinished (err) {
if (err) return callback(err) if (err) return callback(err)
updatePodsScore(good_pods, bad_pods) updatePodsScore(goodPods, badPods)
callback(null) callback(null)
} }
}) })
@ -130,7 +130,7 @@ function makeRequests () {
if (requests.length === 0) return if (requests.length === 0) return
const requests_to_make = { const requestsToMake = {
add: { add: {
ids: [], ids: [],
requests: [] requests: []
@ -141,35 +141,35 @@ function makeRequests () {
} }
} }
async.each(requests, function (pool_request, callback_each) { async.each(requests, function (poolRequest, callbackEach) {
if (pool_request.type === 'add') { if (poolRequest.type === 'add') {
requests_to_make.add.requests.push(pool_request.request) requestsToMake.add.requests.push(poolRequest.request)
requests_to_make.add.ids.push(pool_request._id) requestsToMake.add.ids.push(poolRequest._id)
} else if (pool_request.type === 'remove') { } else if (poolRequest.type === 'remove') {
requests_to_make.remove.requests.push(pool_request.request) requestsToMake.remove.requests.push(poolRequest.request)
requests_to_make.remove.ids.push(pool_request._id) requestsToMake.remove.ids.push(poolRequest._id)
} else { } else {
logger.error('Unkown request type.', { request_type: pool_request.type }) logger.error('Unkown request type.', { request_type: poolRequest.type })
return // abort return // abort
} }
callback_each() callbackEach()
}, function () { }, function () {
// Send the add requests // Send the add requests
if (requests_to_make.add.requests.length !== 0) { if (requestsToMake.add.requests.length !== 0) {
makeRequest('add', requests_to_make.add.requests, function (err) { makeRequest('add', requestsToMake.add.requests, function (err) {
if (err) logger.error('Errors when sent add requests.', { error: err }) if (err) logger.error('Errors when sent add requests.', { error: err })
Requests.removeRequests(requests_to_make.add.ids) Requests.removeRequests(requestsToMake.add.ids)
}) })
} }
// Send the remove requests // Send the remove requests
if (requests_to_make.remove.requests.length !== 0) { if (requestsToMake.remove.requests.length !== 0) {
makeRequest('remove', requests_to_make.remove.requests, function (err) { makeRequest('remove', requestsToMake.remove.requests, function (err) {
if (err) logger.error('Errors when sent remove pool requests.', { error: err }) if (err) logger.error('Errors when sent remove pool requests.', { error: err })
Requests.removeRequests(requests_to_make.remove.ids) Requests.removeRequests(requestsToMake.remove.ids)
}) })
} }
}) })
@ -188,11 +188,11 @@ function removeBadPods () {
const urls = map(pods, 'url') const urls = map(pods, 'url')
const ids = map(pods, '_id') const ids = map(pods, '_id')
Videos.listFromUrls(urls, function (err, videos_list) { Videos.listFromUrls(urls, function (err, videosList) {
if (err) { if (err) {
logger.error('Cannot list videos urls.', { error: err, urls: urls }) logger.error('Cannot list videos urls.', { error: err, urls: urls })
} else { } else {
videos.removeRemoteVideos(videos_list, function (err) { videos.removeRemoteVideos(videosList, function (err) {
if (err) logger.error('Cannot remove remote videos.', { error: err }) if (err) logger.error('Cannot remove remote videos.', { error: err })
}) })
} }
@ -201,22 +201,22 @@ function removeBadPods () {
if (err) { if (err) {
logger.error('Cannot remove bad pods.', { error: err }) logger.error('Cannot remove bad pods.', { error: err })
} else { } else {
const pods_removed = r.result.n const podsRemoved = r.result.n
logger.info('Removed %d pods.', pods_removed) logger.info('Removed %d pods.', podsRemoved)
} }
}) })
}) })
}) })
} }
function updatePodsScore (good_pods, bad_pods) { function updatePodsScore (goodPods, badPods) {
logger.info('Updating %d good pods and %d bad pods scores.', good_pods.length, bad_pods.length) logger.info('Updating %d good pods and %d bad pods scores.', goodPods.length, badPods.length)
Pods.incrementScores(good_pods, constants.PODS_SCORE.BONUS, function (err) { Pods.incrementScores(goodPods, constants.PODS_SCORE.BONUS, function (err) {
if (err) logger.error('Cannot increment scores of good pods.') if (err) logger.error('Cannot increment scores of good pods.')
}) })
Pods.incrementScores(bad_pods, constants.PODS_SCORE.MALUS, function (err) { Pods.incrementScores(badPods, constants.PODS_SCORE.MALUS, function (err) {
if (err) logger.error('Cannot increment scores of bad pods.') if (err) logger.error('Cannot increment scores of bad pods.')
removeBadPods() removeBadPods()
}) })

View file

@ -29,15 +29,15 @@ const videos = {
function createRemoteVideos (videos, callback) { function createRemoteVideos (videos, callback) {
// Create the remote videos from the new pod // Create the remote videos from the new pod
createRemoteVideoObjects(videos, function (err, remote_videos) { createRemoteVideoObjects(videos, function (err, remoteVideos) {
if (err) return callback(err) if (err) return callback(err)
Videos.addRemotes(remote_videos, callback) Videos.addRemotes(remoteVideos, callback)
}) })
} }
function getVideoDuration (video_path, callback) { function getVideoDuration (videoPath, callback) {
ffmpeg.ffprobe(video_path, function (err, metadata) { ffmpeg.ffprobe(videoPath, function (err, metadata) {
if (err) return callback(err) if (err) return callback(err)
return callback(null, Math.floor(metadata.format.duration)) return callback(null, Math.floor(metadata.format.duration))
@ -54,9 +54,9 @@ function getVideoState (video) {
return { exist: exist, owned: owned } return { exist: exist, owned: owned }
} }
function getVideoThumbnail (video_path, callback) { function getVideoThumbnail (videoPath, callback) {
const filename = pathUtils.basename(video_path) + '.jpg' const filename = pathUtils.basename(videoPath) + '.jpg'
ffmpeg(video_path) ffmpeg(videoPath)
.on('error', callback) .on('error', callback)
.on('end', function () { .on('end', function () {
callback(null, filename) callback(null, filename)
@ -71,7 +71,7 @@ function getVideoThumbnail (video_path, callback) {
// Remove video datas from disk (video file, thumbnail...) // Remove video datas from disk (video file, thumbnail...)
function removeVideosDataFromDisk (videos, callback) { function removeVideosDataFromDisk (videos, callback) {
async.each(videos, function (video, callback_each) { async.each(videos, function (video, callbackEach) {
fs.unlink(thumbnailsDir + video.thumbnail, function (err) { fs.unlink(thumbnailsDir + video.thumbnail, function (err) {
if (err) logger.error('Cannot remove the video thumbnail') if (err) logger.error('Cannot remove the video thumbnail')
@ -79,13 +79,13 @@ function removeVideosDataFromDisk (videos, callback) {
fs.unlink(uploadDir + video.namePath, function (err) { fs.unlink(uploadDir + video.namePath, function (err) {
if (err) { if (err) {
logger.error('Cannot remove this video file.') logger.error('Cannot remove this video file.')
return callback_each(err) return callbackEach(err)
} }
callback_each(null) callbackEach(null)
}) })
} else { } else {
callback_each(null) callbackEach(null)
} }
}) })
}, callback) }, callback)
@ -110,20 +110,20 @@ function seed (path, callback) {
} }
function seedAllExisting (callback) { function seedAllExisting (callback) {
Videos.listOwned(function (err, videos_list) { Videos.listOwned(function (err, videosList) {
if (err) { if (err) {
logger.error('Cannot get list of the videos to seed.') logger.error('Cannot get list of the videos to seed.')
return callback(err) return callback(err)
} }
async.each(videos_list, function (video, each_callback) { async.each(videosList, function (video, callbackEach) {
seed(uploadDir + video.namePath, function (err) { seed(uploadDir + video.namePath, function (err) {
if (err) { if (err) {
logger.error('Cannot seed this video.') logger.error('Cannot seed this video.')
return callback(err) return callback(err)
} }
each_callback(null) callbackEach(null)
}) })
}, callback) }, callback)
}) })
@ -136,16 +136,16 @@ module.exports = videos
// --------------------------------------------------------------------------- // ---------------------------------------------------------------------------
function createRemoteVideoObjects (videos, callback) { function createRemoteVideoObjects (videos, callback) {
const remote_videos = [] const remoteVideos = []
async.each(videos, function (video, callback_each) { async.each(videos, function (video, callbackEach) {
// Creating the thumbnail for this remote video // Creating the thumbnail for this remote video
utils.generateRandomString(16, function (err, random_string) { utils.generateRandomString(16, function (err, randomString) {
if (err) return callback_each(err) if (err) return callbackEach(err)
const thumbnail_name = random_string + '.jpg' const thumbnailName = randomString + '.jpg'
createThumbnailFromBase64(thumbnail_name, video.thumbnail_base64, function (err) { createThumbnailFromBase64(thumbnailName, video.thumbnailBase64, function (err) {
if (err) return callback_each(err) if (err) return callbackEach(err)
const params = { const params = {
name: video.name, name: video.name,
@ -153,21 +153,21 @@ function createRemoteVideoObjects (videos, callback) {
magnetUri: video.magnetUri, magnetUri: video.magnetUri,
podUrl: video.podUrl, podUrl: video.podUrl,
duration: video.duration, duration: video.duration,
thumbnail: thumbnail_name thumbnail: thumbnailName
} }
remote_videos.push(params) remoteVideos.push(params)
callback_each(null) callbackEach(null)
}) })
}) })
}, },
function (err) { function (err) {
if (err) return callback(err) if (err) return callback(err)
callback(null, remote_videos) callback(null, remoteVideos)
}) })
} }
function createThumbnailFromBase64 (thumbnail_name, data, callback) { function createThumbnailFromBase64 (thumbnailName, data, callback) {
fs.writeFile(thumbnailsDir + thumbnail_name, data, { encoding: 'base64' }, callback) fs.writeFile(thumbnailsDir + thumbnailName, data, { encoding: 'base64' }, callback)
} }

View file

@ -7,7 +7,7 @@ const spawn = require('electron-spawn')
const logger = require('../helpers/logger') const logger = require('../helpers/logger')
const electron_debug = config.get('electron.debug') const electronDebug = config.get('electron.debug')
let host = config.get('webserver.host') let host = config.get('webserver.host')
let port = config.get('webserver.port') let port = config.get('webserver.port')
let nodeKey = 'webtorrentnode' + port let nodeKey = 'webtorrentnode' + port
@ -43,13 +43,13 @@ function create (options, callback) {
if (!webtorrent.silent) logger.info('IPC server ready.') if (!webtorrent.silent) logger.info('IPC server ready.')
// Run a timeout of 30s after which we exit the process // Run a timeout of 30s after which we exit the process
const timeout_webtorrent_process = setTimeout(function () { const timeoutWebtorrentProcess = setTimeout(function () {
throw new Error('Timeout : cannot run the webtorrent process. Please ensure you have electron-prebuilt npm package installed with xvfb-run.') throw new Error('Timeout : cannot run the webtorrent process. Please ensure you have electron-prebuilt npm package installed with xvfb-run.')
}, 30000) }, 30000)
ipc.server.on(processKey + '.ready', function () { ipc.server.on(processKey + '.ready', function () {
if (!webtorrent.silent) logger.info('Webtorrent process ready.') if (!webtorrent.silent) logger.info('Webtorrent process ready.')
clearTimeout(timeout_webtorrent_process) clearTimeout(timeoutWebtorrentProcess)
callback() callback()
}) })
@ -57,19 +57,19 @@ function create (options, callback) {
throw new Error('Received exception error from webtorrent process : ' + data.exception) throw new Error('Received exception error from webtorrent process : ' + data.exception)
}) })
const webtorrent_process = spawn(pathUtils.join(__dirname, 'webtorrentProcess.js'), host, port, { detached: true }) const webtorrentProcess = spawn(pathUtils.join(__dirname, 'webtorrentProcess.js'), host, port, { detached: true })
if (electron_debug === true) { if (electronDebug === true) {
webtorrent_process.stderr.on('data', function (data) { webtorrentProcess.stderr.on('data', function (data) {
logger.debug('Webtorrent process stderr: ', data.toString()) logger.debug('Webtorrent process stderr: ', data.toString())
}) })
webtorrent_process.stdout.on('data', function (data) { webtorrentProcess.stdout.on('data', function (data) {
logger.debug('Webtorrent process:', data.toString()) logger.debug('Webtorrent process:', data.toString())
}) })
} }
webtorrent.app = webtorrent_process webtorrent.app = webtorrentProcess
}) })
ipc.server.start() ipc.server.start()
@ -88,8 +88,8 @@ function seed (path, callback) {
if (!webtorrent.silent) logger.debug('Node wants to seed %s.', data._id) if (!webtorrent.silent) logger.debug('Node wants to seed %s.', data._id)
// Finish signal // Finish signal
const event_key = nodeKey + '.seedDone.' + data._id const eventKey = nodeKey + '.seedDone.' + data._id
ipc.server.on(event_key, function listener (received) { ipc.server.on(eventKey, function listener (received) {
if (!webtorrent.silent) logger.debug('Process seeded torrent %s.', received.magnetUri) if (!webtorrent.silent) logger.debug('Process seeded torrent %s.', received.magnetUri)
// This is a fake object, we just use the magnetUri in this project // This is a fake object, we just use the magnetUri in this project
@ -97,7 +97,7 @@ function seed (path, callback) {
magnetURI: received.magnetUri magnetURI: received.magnetUri
} }
ipc.server.off(event_key) ipc.server.off(eventKey)
callback(torrent) callback(torrent)
}) })
@ -115,8 +115,8 @@ function add (magnetUri, callback) {
if (!webtorrent.silent) logger.debug('Node wants to add ' + data._id) if (!webtorrent.silent) logger.debug('Node wants to add ' + data._id)
// Finish signal // Finish signal
const event_key = nodeKey + '.addDone.' + data._id const eventKey = nodeKey + '.addDone.' + data._id
ipc.server.on(event_key, function (received) { ipc.server.on(eventKey, function (received) {
if (!webtorrent.silent) logger.debug('Process added torrent.') if (!webtorrent.silent) logger.debug('Process added torrent.')
// This is a fake object, we just use the magnetUri in this project // This is a fake object, we just use the magnetUri in this project
@ -124,7 +124,7 @@ function add (magnetUri, callback) {
files: received.files files: received.files
} }
ipc.server.off(event_key) ipc.server.off(eventKey)
callback(torrent) callback(torrent)
}) })
@ -142,14 +142,14 @@ function remove (magnetUri, callback) {
if (!webtorrent.silent) logger.debug('Node wants to stop seeding %s.', data._id) if (!webtorrent.silent) logger.debug('Node wants to stop seeding %s.', data._id)
// Finish signal // Finish signal
const event_key = nodeKey + '.removeDone.' + data._id const eventKey = nodeKey + '.removeDone.' + data._id
ipc.server.on(event_key, function (received) { ipc.server.on(eventKey, function (received) {
if (!webtorrent.silent) logger.debug('Process removed torrent %s.', data._id) if (!webtorrent.silent) logger.debug('Process removed torrent %s.', data._id)
let err = null let err = null
if (received.err) err = received.err if (received.err) err = received.err
ipc.server.off(event_key) ipc.server.off(eventKey)
callback(err) callback(err)
}) })

View file

@ -26,11 +26,11 @@ function webtorrent (args) {
const _id = data._id const _id = data._id
wt.seed(path, { announceList: '' }, function (torrent) { wt.seed(path, { announceList: '' }, function (torrent) {
const to_send = { const toSend = {
magnetUri: torrent.magnetURI magnetUri: torrent.magnetURI
} }
ipc.of[nodeKey].emit(nodeKey + '.seedDone.' + _id, to_send) ipc.of[nodeKey].emit(nodeKey + '.seedDone.' + _id, toSend)
}) })
} }
@ -40,15 +40,15 @@ function webtorrent (args) {
const _id = data._id const _id = data._id
wt.add(magnetUri, function (torrent) { wt.add(magnetUri, function (torrent) {
const to_send = { const toSend = {
files: [] files: []
} }
torrent.files.forEach(function (file) { torrent.files.forEach(function (file) {
to_send.files.push({ path: file.path }) toSend.files.push({ path: file.path })
}) })
ipc.of[nodeKey].emit(nodeKey + '.addDone.' + _id, to_send) ipc.of[nodeKey].emit(nodeKey + '.addDone.' + _id, toSend)
}) })
} }
@ -65,8 +65,8 @@ function webtorrent (args) {
} }
function callback () { function callback () {
const to_send = {} const toSend = {}
ipc.of[nodeKey].emit(nodeKey + '.removeDone.' + _id, to_send) ipc.of[nodeKey].emit(nodeKey + '.removeDone.' + _id, toSend)
} }
} }

View file

@ -10,13 +10,13 @@ const reqValidatorsPod = {
} }
function makeFriends (req, res, next) { function makeFriends (req, res, next) {
friends.hasFriends(function (err, has_friends) { friends.hasFriends(function (err, hasFriends) {
if (err) { if (err) {
logger.error('Cannot know if we have friends.', { error: err }) logger.error('Cannot know if we have friends.', { error: err })
res.sendStatus(500) res.sendStatus(500)
} }
if (has_friends === true) { if (hasFriends === true) {
// We need to quit our friends before make new ones // We need to quit our friends before make new ones
res.sendStatus(409) res.sendStatus(409)
} else { } else {

View file

@ -8,13 +8,13 @@ const reqValidatorsUtils = {
checkErrors: checkErrors checkErrors: checkErrors
} }
function checkErrors (req, res, next, status_code) { function checkErrors (req, res, next, statusCode) {
if (status_code === undefined) status_code = 400 if (statusCode === undefined) statusCode = 400
const errors = req.validationErrors() const errors = req.validationErrors()
if (errors) { if (errors) {
logger.warn('Incorrect request parameters', { path: req.originalUrl, err: errors }) logger.warn('Incorrect request parameters', { path: req.originalUrl, err: errors })
return res.status(status_code).send('There have been validation errors: ' + util.inspect(errors)) return res.status(statusCode).send('There have been validation errors: ' + util.inspect(errors))
} }
return next() return next()

View file

@ -23,9 +23,9 @@ function decryptBody (req, res, next) {
logger.debug('Decrypting body from %s.', url) logger.debug('Decrypting body from %s.', url)
const signature_ok = peertubeCrypto.checkSignature(pod.publicKey, url, req.body.signature.signature) const signatureOk = peertubeCrypto.checkSignature(pod.publicKey, url, req.body.signature.signature)
if (signature_ok === true) { if (signatureOk === true) {
peertubeCrypto.decrypt(req.body.key, req.body.data, function (err, decrypted) { peertubeCrypto.decrypt(req.body.key, req.body.data, function (err, decrypted) {
if (err) { if (err) {
logger.error('Cannot decrypt data.', { error: err }) logger.error('Cannot decrypt data.', { error: err })

View file

@ -58,13 +58,13 @@ function incrementScores (ids, value, callback) {
} }
function list (callback) { function list (callback) {
PodsDB.find(function (err, pods_list) { PodsDB.find(function (err, podsList) {
if (err) { if (err) {
logger.error('Cannot get the list of the pods.') logger.error('Cannot get the list of the pods.')
return callback(err) return callback(err)
} }
return callback(null, pods_list) return callback(null, podsList)
}) })
} }

View file

@ -45,11 +45,11 @@ const Users = {
function createClient (secret, grants, callback) { function createClient (secret, grants, callback) {
logger.debug('Creating client.') logger.debug('Creating client.')
const mongo_id = new mongoose.mongo.ObjectID() const mongoId = new mongoose.mongo.ObjectID()
return OAuthClientsDB.create({ _id: mongo_id, clientSecret: secret, grants: grants }, function (err) { return OAuthClientsDB.create({ _id: mongoId, clientSecret: secret, grants: grants }, function (err) {
if (err) return callback(err) if (err) return callback(err)
return callback(null, mongo_id) return callback(null, mongoId)
}) })
} }
@ -73,8 +73,8 @@ function getClient (clientId, clientSecret) {
logger.debug('Getting Client (clientId: ' + clientId + ', clientSecret: ' + clientSecret + ').') logger.debug('Getting Client (clientId: ' + clientId + ', clientSecret: ' + clientSecret + ').')
// TODO req validator // TODO req validator
const mongo_id = new mongoose.mongo.ObjectID(clientId) const mongoId = new mongoose.mongo.ObjectID(clientId)
return OAuthClientsDB.findOne({ _id: mongo_id, clientSecret: clientSecret }) return OAuthClientsDB.findOne({ _id: mongoId, clientSecret: clientSecret })
} }
function getClients (callback) { function getClients (callback) {
@ -99,7 +99,7 @@ function getUsers (callback) {
function saveToken (token, client, user) { function saveToken (token, client, user) {
logger.debug('Saving token for client ' + client.id + ' and user ' + user.id + '.') logger.debug('Saving token for client ' + client.id + ' and user ' + user.id + '.')
const token_to_create = { const tokenToCreate = {
accessToken: token.accessToken, accessToken: token.accessToken,
accessTokenExpiresOn: token.accessTokenExpiresOn, accessTokenExpiresOn: token.accessTokenExpiresOn,
client: client.id, client: client.id,
@ -108,13 +108,13 @@ function saveToken (token, client, user) {
user: user.id user: user.id
} }
return OAuthTokensDB.create(token_to_create, function (err, token_created) { return OAuthTokensDB.create(tokenToCreate, function (err, tokenCreated) {
if (err) throw err // node-oauth2-server library uses Promise.try if (err) throw err // node-oauth2-server library uses Promise.try
token_created.client = client tokenCreated.client = client
token_created.user = user tokenCreated.user = user
return token_created return tokenCreated
}) })
} }

View file

@ -77,13 +77,13 @@ function get (id, callback) {
} }
function list (callback) { function list (callback) {
VideosDB.find(function (err, videos_list) { VideosDB.find(function (err, videosList) {
if (err) { if (err) {
logger.error('Cannot get the list of the videos.') logger.error('Cannot get the list of the videos.')
return callback(err) return callback(err)
} }
return callback(null, videos_list) return callback(null, videosList)
}) })
} }
@ -105,13 +105,13 @@ function listFromRemotes (callback) {
function listOwned (callback) { function listOwned (callback) {
// If namePath is not null this is *our* video // If namePath is not null this is *our* video
VideosDB.find({ namePath: { $ne: null } }, function (err, videos_list) { VideosDB.find({ namePath: { $ne: null } }, function (err, videosList) {
if (err) { if (err) {
logger.error('Cannot get the list of owned videos.') logger.error('Cannot get the list of owned videos.')
return callback(err) return callback(err)
} }
return callback(null, videos_list) return callback(null, videosList)
}) })
} }

View file

@ -12,8 +12,8 @@ describe('Test parameters validator', function () {
let server = null let server = null
function makePostRequest (path, token, fields, attach, done, fail) { function makePostRequest (path, token, fields, attach, done, fail) {
let status_code = 400 let statusCode = 400
if (fail !== undefined && fail === false) status_code = 200 if (fail !== undefined && fail === false) statusCode = 200
const req = request(server.url) const req = request(server.url)
.post(path) .post(path)
@ -26,18 +26,18 @@ describe('Test parameters validator', function () {
req.field(field, value) req.field(field, value)
}) })
req.expect(status_code, done) req.expect(statusCode, done)
} }
function makePostBodyRequest (path, fields, done, fail) { function makePostBodyRequest (path, fields, done, fail) {
let status_code = 400 let statusCode = 400
if (fail !== undefined && fail === false) status_code = 200 if (fail !== undefined && fail === false) statusCode = 200
request(server.url) request(server.url)
.post(path) .post(path)
.set('Accept', 'application/json') .set('Accept', 'application/json')
.send(fields) .send(fields)
.expect(status_code, done) .expect(statusCode, done)
} }
// --------------------------------------------------------------- // ---------------------------------------------------------------

View file

@ -9,44 +9,44 @@ const utils = require('./utils')
describe('Test advanced friends', function () { describe('Test advanced friends', function () {
let servers = [] let servers = []
function makeFriends (pod_number, callback) { function makeFriends (podNumber, callback) {
return utils.makeFriends(servers[pod_number - 1].url, callback) return utils.makeFriends(servers[podNumber - 1].url, callback)
} }
function quitFriends (pod_number, callback) { function quitFriends (podNumber, callback) {
return utils.quitFriends(servers[pod_number - 1].url, callback) return utils.quitFriends(servers[podNumber - 1].url, callback)
} }
function getFriendsList (pod_number, end) { function getFriendsList (podNumber, end) {
return utils.getFriendsList(servers[pod_number - 1].url, end) return utils.getFriendsList(servers[podNumber - 1].url, end)
} }
function uploadVideo (pod_number, callback) { function uploadVideo (podNumber, callback) {
const name = 'my super video' const name = 'my super video'
const description = 'my super description' const description = 'my super description'
const fixture = 'video_short.webm' const fixture = 'video_short.webm'
const server = servers[pod_number - 1] const server = servers[podNumber - 1]
return utils.uploadVideo(server.url, server.access_token, name, description, fixture, callback) return utils.uploadVideo(server.url, server.access_token, name, description, fixture, callback)
} }
function getVideos (pod_number, callback) { function getVideos (podNumber, callback) {
return utils.getVideosList(servers[pod_number - 1].url, callback) return utils.getVideosList(servers[podNumber - 1].url, callback)
} }
// --------------------------------------------------------------- // ---------------------------------------------------------------
before(function (done) { before(function (done) {
this.timeout(30000) this.timeout(30000)
utils.flushAndRunMultipleServers(6, function (servers_run, urls_run) { utils.flushAndRunMultipleServers(6, function (serversRun, urlsRun) {
servers = servers_run servers = serversRun
async.each(servers, function (server, callback_each) { async.each(servers, function (server, callbackEach) {
utils.loginAndGetAccessToken(server, function (err, access_token) { utils.loginAndGetAccessToken(server, function (err, accessToken) {
if (err) return callback_each(err) if (err) return callbackEach(err)
server.access_token = access_token server.accessToken = accessToken
callback_each() callbackEach()
}) })
}, done) }, done)
}) })

View file

@ -10,25 +10,25 @@ const utils = require('./utils')
describe('Test basic friends', function () { describe('Test basic friends', function () {
let servers = [] let servers = []
function testMadeFriends (servers, server_to_test, callback) { function testMadeFriends (servers, serverToTest, callback) {
const friends = [] const friends = []
for (let i = 0; i < servers.length; i++) { for (let i = 0; i < servers.length; i++) {
if (servers[i].url === server_to_test.url) continue if (servers[i].url === serverToTest.url) continue
friends.push(servers[i].url) friends.push(servers[i].url)
} }
utils.getFriendsList(server_to_test.url, function (err, res) { utils.getFriendsList(serverToTest.url, function (err, res) {
if (err) throw err if (err) throw err
const result = res.body const result = res.body
const result_urls = [ result[0].url, result[1].url ] const resultUrls = [ result[0].url, result[1].url ]
expect(result).to.be.an('array') expect(result).to.be.an('array')
expect(result.length).to.equal(2) expect(result.length).to.equal(2)
expect(result_urls[0]).to.not.equal(result_urls[1]) expect(resultUrls[0]).to.not.equal(resultUrls[1])
const error_string = 'Friends url do not correspond for ' + server_to_test.url const errorString = 'Friends url do not correspond for ' + serverToTest.url
expect(friends).to.contain(result_urls[0], error_string) expect(friends).to.contain(resultUrls[0], errorString)
expect(friends).to.contain(result_urls[1], error_string) expect(friends).to.contain(resultUrls[1], errorString)
callback() callback()
}) })
} }
@ -37,8 +37,8 @@ describe('Test basic friends', function () {
before(function (done) { before(function (done) {
this.timeout(20000) this.timeout(20000)
utils.flushAndRunMultipleServers(3, function (servers_run, urls_run) { utils.flushAndRunMultipleServers(3, function (serversRun, urlsRun) {
servers = servers_run servers = serversRun
done() done()
}) })
}) })

View file

@ -11,7 +11,7 @@ webtorrent.silent = true
describe('Test multiple pods', function () { describe('Test multiple pods', function () {
let servers = [] let servers = []
const to_remove = [] const toRemove = []
before(function (done) { before(function (done) {
this.timeout(30000) this.timeout(30000)
@ -19,19 +19,19 @@ describe('Test multiple pods', function () {
async.series([ async.series([
// Run servers // Run servers
function (next) { function (next) {
utils.flushAndRunMultipleServers(3, function (servers_run) { utils.flushAndRunMultipleServers(3, function (serversRun) {
servers = servers_run servers = serversRun
next() next()
}) })
}, },
// Get the access tokens // Get the access tokens
function (next) { function (next) {
async.each(servers, function (server, callback_each) { async.each(servers, function (server, callbackEach) {
utils.loginAndGetAccessToken(server, function (err, access_token) { utils.loginAndGetAccessToken(server, function (err, accessToken) {
if (err) return callback_each(err) if (err) return callbackEach(err)
server.access_token = access_token server.accessToken = accessToken
callback_each() callbackEach()
}) })
}, next) }, next)
}, },
@ -82,7 +82,7 @@ describe('Test multiple pods', function () {
if (err) throw err if (err) throw err
async.each(servers, function (server, callback) { async.each(servers, function (server, callback) {
let base_magnet = null let baseMagnet = null
utils.getVideosList(server.url, function (err, res) { utils.getVideosList(server.url, function (err, res) {
if (err) throw err if (err) throw err
@ -104,8 +104,8 @@ describe('Test multiple pods', function () {
} }
// All pods should have the same magnet Uri // All pods should have the same magnet Uri
if (base_magnet === null) { if (baseMagnet === null) {
base_magnet = video.magnetUri baseMagnet = video.magnetUri
} else { } else {
expect(video.magnetUri).to.equal.magnetUri expect(video.magnetUri).to.equal.magnetUri
} }
@ -137,7 +137,7 @@ describe('Test multiple pods', function () {
if (err) throw err if (err) throw err
async.each(servers, function (server, callback) { async.each(servers, function (server, callback) {
let base_magnet = null let baseMagnet = null
utils.getVideosList(server.url, function (err, res) { utils.getVideosList(server.url, function (err, res) {
if (err) throw err if (err) throw err
@ -159,8 +159,8 @@ describe('Test multiple pods', function () {
} }
// All pods should have the same magnet Uri // All pods should have the same magnet Uri
if (base_magnet === null) { if (baseMagnet === null) {
base_magnet = video.magnetUri baseMagnet = video.magnetUri
} else { } else {
expect(video.magnetUri).to.equal.magnetUri expect(video.magnetUri).to.equal.magnetUri
} }
@ -193,7 +193,7 @@ describe('Test multiple pods', function () {
function (err) { function (err) {
if (err) throw err if (err) throw err
let base_magnet = null let baseMagnet = null
// All pods should have this video // All pods should have this video
async.each(servers, function (server, callback) { async.each(servers, function (server, callback) {
utils.getVideosList(server.url, function (err, res) { utils.getVideosList(server.url, function (err, res) {
@ -235,8 +235,8 @@ describe('Test multiple pods', function () {
} }
// All pods should have the same magnet Uri // All pods should have the same magnet Uri
if (base_magnet === null) { if (baseMagnet === null) {
base_magnet = video2.magnetUri baseMagnet = video2.magnetUri
} else { } else {
expect(video2.magnetUri).to.equal.magnetUri expect(video2.magnetUri).to.equal.magnetUri
} }
@ -268,8 +268,8 @@ describe('Test multiple pods', function () {
if (err) throw err if (err) throw err
const video = res.body[0] const video = res.body[0]
to_remove.push(res.body[2].id) toRemove.push(res.body[2].id)
to_remove.push(res.body[3].id) toRemove.push(res.body[3].id)
webtorrent.add(video.magnetUri, function (torrent) { webtorrent.add(video.magnetUri, function (torrent) {
expect(torrent.files).to.exist expect(torrent.files).to.exist
@ -343,10 +343,10 @@ describe('Test multiple pods', function () {
async.series([ async.series([
function (next) { function (next) {
utils.removeVideo(servers[2].url, servers[2].access_token, to_remove[0], next) utils.removeVideo(servers[2].url, servers[2].accessToken, toRemove[0], next)
}, },
function (next) { function (next) {
utils.removeVideo(servers[2].url, servers[2].access_token, to_remove[1], next) utils.removeVideo(servers[2].url, servers[2].accessToken, toRemove[1], next)
}], }],
function (err) { function (err) {
if (err) throw err if (err) throw err
@ -364,10 +364,10 @@ describe('Test multiple pods', function () {
expect(videos).to.be.an('array') expect(videos).to.be.an('array')
expect(videos.length).to.equal(2) expect(videos.length).to.equal(2)
expect(videos[0].id).not.to.equal(videos[1].id) expect(videos[0].id).not.to.equal(videos[1].id)
expect(videos[0].id).not.to.equal(to_remove[0]) expect(videos[0].id).not.to.equal(toRemove[0])
expect(videos[1].id).not.to.equal(to_remove[0]) expect(videos[1].id).not.to.equal(toRemove[0])
expect(videos[0].id).not.to.equal(to_remove[1]) expect(videos[0].id).not.to.equal(toRemove[1])
expect(videos[1].id).not.to.equal(to_remove[1]) expect(videos[1].id).not.to.equal(toRemove[1])
callback() callback()
}) })

View file

@ -14,7 +14,7 @@ const utils = require('./utils')
describe('Test a single pod', function () { describe('Test a single pod', function () {
let server = null let server = null
let video_id = -1 let videoId = -1
before(function (done) { before(function (done) {
this.timeout(20000) this.timeout(20000)
@ -80,7 +80,7 @@ describe('Test a single pod', function () {
if (err) throw err if (err) throw err
expect(test).to.equal(true) expect(test).to.equal(true)
video_id = video.id videoId = video.id
webtorrent.add(video.magnetUri, function (torrent) { webtorrent.add(video.magnetUri, function (torrent) {
expect(torrent.files).to.exist expect(torrent.files).to.exist
@ -97,7 +97,7 @@ describe('Test a single pod', function () {
// Yes, this could be long // Yes, this could be long
this.timeout(60000) this.timeout(60000)
utils.getVideo(server.url, video_id, function (err, res) { utils.getVideo(server.url, videoId, function (err, res) {
if (err) throw err if (err) throw err
const video = res.body const video = res.body
@ -158,7 +158,7 @@ describe('Test a single pod', function () {
}) })
it('Should remove the video', function (done) { it('Should remove the video', function (done) {
utils.removeVideo(server.url, server.access_token, video_id, function (err) { utils.removeVideo(server.url, server.accessToken, videoId, function (err) {
if (err) throw err if (err) throw err
fs.readdir(pathUtils.join(__dirname, '../../../test1/uploads/'), function (err, files) { fs.readdir(pathUtils.join(__dirname, '../../../test1/uploads/'), function (err, files) {
@ -187,8 +187,8 @@ describe('Test a single pod', function () {
'video_short.mp4', 'video_short.ogv', 'video_short.webm', 'video_short.mp4', 'video_short.ogv', 'video_short.webm',
'video_short1.webm', 'video_short2.webm', 'video_short3.webm' 'video_short1.webm', 'video_short2.webm', 'video_short3.webm'
] ]
async.each(videos, function (video, callback_each) { async.each(videos, function (video, callbackEach) {
utils.uploadVideo(server.url, server.access_token, video + ' name', video + ' description', video, callback_each) utils.uploadVideo(server.url, server.accessToken, video + ' name', video + ' description', video, callbackEach)
}, done) }, done)
}) })
@ -200,13 +200,13 @@ describe('Test a single pod', function () {
expect(videos).to.be.an('array') expect(videos).to.be.an('array')
expect(videos.length).to.equal(6) expect(videos.length).to.equal(6)
const videos_by_name = keyBy(videos, 'name') const videosByName = keyBy(videos, 'name')
expect(videos_by_name['video_short.mp4 name'].duration).to.equal(5) expect(videosByName['video_short.mp4 name'].duration).to.equal(5)
expect(videos_by_name['video_short.ogv name'].duration).to.equal(5) expect(videosByName['video_short.ogv name'].duration).to.equal(5)
expect(videos_by_name['video_short.webm name'].duration).to.equal(5) expect(videosByName['video_short.webm name'].duration).to.equal(5)
expect(videos_by_name['video_short1.webm name'].duration).to.equal(10) expect(videosByName['video_short1.webm name'].duration).to.equal(10)
expect(videos_by_name['video_short2.webm name'].duration).to.equal(5) expect(videosByName['video_short2.webm name'].duration).to.equal(5)
expect(videos_by_name['video_short3.webm name'].duration).to.equal(5) expect(videosByName['video_short3.webm name'].duration).to.equal(5)
done() done()
}) })
@ -216,15 +216,15 @@ describe('Test a single pod', function () {
utils.getVideosList(server.url, function (err, res) { utils.getVideosList(server.url, function (err, res) {
const videos = res.body const videos = res.body
async.each(videos, function (video, callback_each) { async.each(videos, function (video, callbackEach) {
if (err) throw err if (err) throw err
const video_name = video.name.replace(' name', '') const videoName = video.name.replace(' name', '')
utils.testImage(server.url, video_name, video.thumbnailPath, function (err, test) { utils.testImage(server.url, videoName, video.thumbnailPath, function (err, test) {
if (err) throw err if (err) throw err
expect(test).to.equal(true) expect(test).to.equal(true)
callback_each() callbackEach()
}) })
}, done) }, done)
}) })

View file

@ -12,8 +12,8 @@ const utils = require('./utils')
describe('Test users', function () { describe('Test users', function () {
let server = null let server = null
let access_token = null let accessToken = null
let video_id let videoId
before(function (done) { before(function (done) {
this.timeout(20000) this.timeout(20000)
@ -78,21 +78,21 @@ describe('Test users', function () {
}) })
it('Should not be able to upload a video', function (done) { it('Should not be able to upload a video', function (done) {
access_token = 'mysupertoken' accessToken = 'mysupertoken'
utils.uploadVideo(server.url, access_token, 'my super name', 'my super description', 'video_short.webm', 401, done) utils.uploadVideo(server.url, accessToken, 'my super name', 'my super description', 'video_short.webm', 401, done)
}) })
it('Should be able to login', function (done) { it('Should be able to login', function (done) {
utils.login(server.url, server.client, server.user, 200, function (err, res) { utils.login(server.url, server.client, server.user, 200, function (err, res) {
if (err) throw err if (err) throw err
access_token = res.body.access_token accessToken = res.body.access_token
done() done()
}) })
}) })
it('Should upload the video with the correct token', function (done) { it('Should upload the video with the correct token', function (done) {
utils.uploadVideo(server.url, access_token, 'my super name', 'my super description', 'video_short.webm', 204, function (err, res) { utils.uploadVideo(server.url, accessToken, 'my super name', 'my super description', 'video_short.webm', 204, function (err, res) {
if (err) throw err if (err) throw err
utils.getVideosList(server.url, function (err, res) { utils.getVideosList(server.url, function (err, res) {
@ -101,24 +101,24 @@ describe('Test users', function () {
const video = res.body[0] const video = res.body[0]
expect(video.author).to.equal('root') expect(video.author).to.equal('root')
video_id = video.id videoId = video.id
done() done()
}) })
}) })
}) })
it('Should upload the video again with the correct token', function (done) { it('Should upload the video again with the correct token', function (done) {
utils.uploadVideo(server.url, access_token, 'my super name 2', 'my super description 2', 'video_short.webm', 204, done) utils.uploadVideo(server.url, accessToken, 'my super name 2', 'my super description 2', 'video_short.webm', 204, done)
}) })
it('Should not be able to remove the video with an incorrect token', function (done) { it('Should not be able to remove the video with an incorrect token', function (done) {
utils.removeVideo(server.url, 'bad_token', video_id, 401, done) utils.removeVideo(server.url, 'bad_token', videoId, 401, done)
}) })
it('Should not be able to remove the video with the token of another account') it('Should not be able to remove the video with the token of another account')
it('Should be able to remove the video with the correct token', function (done) { it('Should be able to remove the video with the correct token', function (done) {
utils.removeVideo(server.url, access_token, video_id, done) utils.removeVideo(server.url, accessToken, videoId, done)
}) })
it('Should logout') it('Should logout')

View file

@ -1,8 +1,8 @@
'use strict' 'use strict'
const child_process = require('child_process') const childProcess = require('child_process')
const exec = child_process.exec const exec = childProcess.exec
const fork = child_process.fork const fork = childProcess.fork
const fs = require('fs') const fs = require('fs')
const pathUtils = require('path') const pathUtils = require('path')
const request = require('supertest') const request = require('supertest')
@ -63,10 +63,10 @@ function getVideosList (url, end) {
.end(end) .end(end)
} }
function login (url, client, user, expected_status, end) { function login (url, client, user, expectedStatus, end) {
if (!end) { if (!end) {
end = expected_status end = expectedStatus
expected_status = 200 expectedStatus = 200
} }
const path = '/api/v1/users/token' const path = '/api/v1/users/token'
@ -85,7 +85,7 @@ function login (url, client, user, expected_status, end) {
.post(path) .post(path)
.type('form') .type('form')
.send(body) .send(body)
.expect(expected_status) .expect(expectedStatus)
.end(end) .end(end)
} }
@ -97,10 +97,10 @@ function loginAndGetAccessToken (server, callback) {
}) })
} }
function makeFriends (url, expected_status, callback) { function makeFriends (url, expectedStatus, callback) {
if (!callback) { if (!callback) {
callback = expected_status callback = expectedStatus
expected_status = 204 expectedStatus = 204
} }
const path = '/api/v1/pods/makefriends' const path = '/api/v1/pods/makefriends'
@ -109,7 +109,7 @@ function makeFriends (url, expected_status, callback) {
request(url) request(url)
.get(path) .get(path)
.set('Accept', 'application/json') .set('Accept', 'application/json')
.expect(expected_status) .expect(expectedStatus)
.end(function (err, res) { .end(function (err, res) {
if (err) throw err if (err) throw err
@ -134,10 +134,10 @@ function quitFriends (url, callback) {
}) })
} }
function removeVideo (url, token, id, expected_status, end) { function removeVideo (url, token, id, expectedStatus, end) {
if (!end) { if (!end) {
end = expected_status end = expectedStatus
expected_status = 204 expectedStatus = 204
} }
const path = '/api/v1/videos' const path = '/api/v1/videos'
@ -146,11 +146,11 @@ function removeVideo (url, token, id, expected_status, end) {
.delete(path + '/' + id) .delete(path + '/' + id)
.set('Accept', 'application/json') .set('Accept', 'application/json')
.set('Authorization', 'Bearer ' + token) .set('Authorization', 'Bearer ' + token)
.expect(expected_status) .expect(expectedStatus)
.end(end) .end(end)
} }
function flushAndRunMultipleServers (total_servers, serversRun) { function flushAndRunMultipleServers (totalServers, serversRun) {
let apps = [] let apps = []
let urls = [] let urls = []
let i = 0 let i = 0
@ -159,13 +159,13 @@ function flushAndRunMultipleServers (total_servers, serversRun) {
apps[number - 1] = app apps[number - 1] = app
urls[number - 1] = url urls[number - 1] = url
i++ i++
if (i === total_servers) { if (i === totalServers) {
serversRun(apps, urls) serversRun(apps, urls)
} }
} }
flushTests(function () { flushTests(function () {
for (let j = 1; j <= total_servers; j++) { for (let j = 1; j <= totalServers; j++) {
// For the virtual buffer // For the virtual buffer
setTimeout(function () { setTimeout(function () {
runServer(j, function (app, url) { runServer(j, function (app, url) {
@ -191,7 +191,7 @@ function runServer (number, callback) {
} }
// These actions are async so we need to be sure that they have both been done // These actions are async so we need to be sure that they have both been done
const server_run_string = { const serverRunString = {
'Connected to mongodb': false, 'Connected to mongodb': false,
'Server listening on port': false 'Server listening on port': false
} }
@ -215,7 +215,7 @@ function runServer (number, callback) {
server.app = fork(pathUtils.join(__dirname, '../../../server.js'), [], options) server.app = fork(pathUtils.join(__dirname, '../../../server.js'), [], options)
server.app.stdout.on('data', function onStdout (data) { server.app.stdout.on('data', function onStdout (data) {
let dont_continue = false let dontContinue = false
// Capture things if we want to // Capture things if we want to
for (const key of Object.keys(regexps)) { for (const key of Object.keys(regexps)) {
@ -230,13 +230,13 @@ function runServer (number, callback) {
} }
// Check if all required sentences are here // Check if all required sentences are here
for (const key of Object.keys(server_run_string)) { for (const key of Object.keys(serverRunString)) {
if (data.toString().indexOf(key) !== -1) server_run_string[key] = true if (data.toString().indexOf(key) !== -1) serverRunString[key] = true
if (server_run_string[key] === false) dont_continue = true if (serverRunString[key] === false) dontContinue = true
} }
// If no, there is maybe one thing not already initialized (mongodb...) // If no, there is maybe one thing not already initialized (mongodb...)
if (dont_continue === true) return if (dontContinue === true) return
server.app.stdout.removeListener('data', onStdout) server.app.stdout.removeListener('data', onStdout)
callback(server) callback(server)
@ -254,14 +254,14 @@ function searchVideo (url, search, end) {
.end(end) .end(end)
} }
function testImage (url, video_name, image_path, callback) { function testImage (url, videoName, imagePath, callback) {
request(url) request(url)
.get(image_path) .get(imagePath)
.expect(200) .expect(200)
.end(function (err, res) { .end(function (err, res) {
if (err) return callback(err) if (err) return callback(err)
fs.readFile(pathUtils.join(__dirname, 'fixtures', video_name + '.jpg'), function (err, data) { fs.readFile(pathUtils.join(__dirname, 'fixtures', videoName + '.jpg'), function (err, data) {
if (err) return callback(err) if (err) return callback(err)
callback(null, data.equals(res.body)) callback(null, data.equals(res.body))
@ -269,10 +269,10 @@ function testImage (url, video_name, image_path, callback) {
}) })
} }
function uploadVideo (url, access_token, name, description, fixture, special_status, end) { function uploadVideo (url, accessToken, name, description, fixture, specialStatus, end) {
if (!end) { if (!end) {
end = special_status end = specialStatus
special_status = 204 specialStatus = 204
} }
const path = '/api/v1/videos' const path = '/api/v1/videos'
@ -280,11 +280,11 @@ function uploadVideo (url, access_token, name, description, fixture, special_sta
request(url) request(url)
.post(path) .post(path)
.set('Accept', 'application/json') .set('Accept', 'application/json')
.set('Authorization', 'Bearer ' + access_token) .set('Authorization', 'Bearer ' + accessToken)
.field('name', name) .field('name', name)
.field('description', description) .field('description', description)
.attach('videofile', pathUtils.join(__dirname, 'fixtures', fixture)) .attach('videofile', pathUtils.join(__dirname, 'fixtures', fixture))
.expect(special_status) .expect(specialStatus)
.end(end) .end(end)
} }