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-sass": "^3.4.2",
"scripty": "^1.5.0",
"standard": "^6.0.1",
"standard": "^7.0.1",
"supertest": "^1.1.0"
},
"standard": {

View File

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

View File

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

View File

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

View File

@ -20,14 +20,14 @@ module.exports = router
// ---------------------------------------------------------------------------
function getAngularClient (req, res, next) {
const server_host = config.get('webserver.host')
const server_port = config.get('webserver.port')
let header_host_should_be = server_host
if (server_port !== 80 && server_port !== 443) {
header_host_should_be += ':' + server_port
const serverHost = config.get('webserver.host')
const serverPort = config.get('webserver.port')
let headerHostShouldBe = serverHost
if (serverPort !== 80 && serverPort !== 443) {
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) {
if (err) return next(err)

View File

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

View File

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

View File

@ -17,7 +17,7 @@ const requests = {
makeMultipleRetryRequest: makeMultipleRetryRequest
}
function makeMultipleRetryRequest (all_data, pods, callbackEach, callback) {
function makeMultipleRetryRequest (allData, pods, callbackEach, callback) {
if (!callback) {
callback = callbackEach
callbackEach = null
@ -27,32 +27,32 @@ function makeMultipleRetryRequest (all_data, pods, callbackEach, callback) {
let signature
// 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)
}
// 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) {
if (callbackEach !== null) {
callbackEach(err, response, body, url, pod, function () {
callback_each_async()
callbackEachAsync()
})
} else {
callback_each_async()
callbackEachAsync()
}
}
const params = {
url: pod.url + all_data.path,
method: all_data.method
url: pod.url + allData.path,
method: allData.method
}
// Add data with POST requst ?
if (all_data.method === 'POST' && all_data.data) {
if (allData.method === 'POST' && allData.data) {
// Encrypt data ?
if (all_data.encrypt === true) {
peertubeCrypto.encrypt(pod.publicKey, JSON.stringify(all_data.data), function (err, encrypted) {
if (allData.encrypt === true) {
peertubeCrypto.encrypt(pod.publicKey, JSON.stringify(allData.data), function (err, encrypted) {
if (err) return callback(err)
params.json = {
@ -63,7 +63,7 @@ function makeMultipleRetryRequest (all_data, pods, callbackEach, callback) {
makeRetryRequest(params, url, pod, signature, callbackEachRetryRequest)
})
} else {
params.json = { data: all_data.data }
params.json = { data: allData.data }
makeRetryRequest(params, url, pod, signature, callbackEachRetryRequest)
}
} 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
if (signature) {
params.json.signature = {
url: from_url,
url: fromUrl,
signature: signature
}
}
logger.debug('Make retry requests to %s.', to_pod.url)
logger.debug('Make retry requests to %s.', toPod.url)
replay(
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,

View File

@ -17,9 +17,9 @@ function generateRandomString (size, callback) {
})
}
function cleanForExit (webtorrent_process) {
function cleanForExit (webtorrentProcess) {
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) {
if (err) return callback(err)
const has_friends = (count !== 0)
callback(null, has_friends)
const hasFriends = (count !== 0)
callback(null, hasFriends)
})
}
@ -49,7 +49,7 @@ function getMyCertificate (callback) {
}
function makeFriends (callback) {
const pods_score = {}
const podsScore = {}
logger.info('Make friends!')
getMyCertificate(function (err, cert) {
@ -60,16 +60,16 @@ function makeFriends (callback) {
const urls = config.get('network.friends')
async.each(urls, function (url, callback_each) {
computeForeignPodsList(url, pods_score, callback_each)
async.each(urls, function (url, callbackEach) {
computeForeignPodsList(url, podsScore, callbackEach)
}, function (err) {
if (err) return callback(err)
logger.debug('Pods scores computed.', { pods_score: pods_score })
const pods_list = computeWinningPods(urls, pods_score)
logger.debug('Pods that we keep.', { pods_to_keep: pods_list })
logger.debug('Pods scores computed.', { podsScore: podsScore })
const podsList = computeWinningPods(urls, podsScore)
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 :(')
Videos.listFromRemotes(function (err, videos_list) {
Videos.listFromRemotes(function (err, videosList) {
if (err) return callback(err)
videos.removeRemoteVideos(videos_list, function (err) {
videos.removeRemoteVideos(videosList, function (err) {
if (err) {
logger.error('Cannot remove remote videos.', { error: 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
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 (foreign_pods_list.length === 0) return callback()
if (foreignPodsList.length === 0) return callback()
foreign_pods_list.forEach(function (foreign_pod) {
const foreign_url = foreign_pod.url
foreignPodsList.forEach(function (foreignPod) {
const foreignUrl = foreignPod.url
if (pods_score[foreign_url]) pods_score[foreign_url]++
else pods_score[foreign_url] = 1
if (podsScore[foreignUrl]) podsScore[foreignUrl]++
else podsScore[foreignUrl] = 1
})
callback()
})
}
function computeWinningPods (urls, pods_score) {
function computeWinningPods (urls, podsScore) {
// Build the list of pods to add
// Only add a pod if it exists in more than a half base pods
const pods_list = []
const base_score = urls.length / 2
Object.keys(pods_score).forEach(function (pod) {
if (pods_score[pod] > base_score) pods_list.push({ url: pod })
const podsList = []
const baseScore = urls.length / 2
Object.keys(baseScore).forEach(function (pod) {
if (podsScore[pod] > baseScore) podsList.push({ url: pod })
})
return pods_list
return podsList
}
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
requestsScheduler.deactivate()
// Flush pool requests
requestsScheduler.forceSend()
// 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) {
logger.error('Cannot get the list of videos we own.')
return callback(err)
@ -189,38 +189,36 @@ function makeRequestsToWinningPods (cert, pods_list, callback) {
const data = {
url: http + '://' + host + ':' + port,
publicKey: cert,
videos: videos_list
videos: videosList
}
requests.makeMultipleRetryRequest(
{ 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
if (!err && response.statusCode === 200) {
Pods.add({ url: pod.url, publicKey: body.cert, score: constants.FRIEND_BASE_SCORE }, function (err) {
if (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) {
if (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 })
return callback_each_request()
return callbackEachRequest()
})
})
} else {
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 () {}
Pods.list(function (err, pods) {
@ -83,7 +83,7 @@ function makeRequest (type, requests_to_make, callback) {
sign: true,
method: 'POST',
path: null,
data: requests_to_make
data: requestsToMake
}
if (type === 'add') {
@ -94,26 +94,26 @@ function makeRequest (type, requests_to_make, callback) {
return callback(new Error('Unkown pool request type.'))
}
const bad_pods = []
const good_pods = []
const badPods = []
const goodPods = []
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)) {
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') })
} else {
good_pods.push(pod._id)
goodPods.push(pod._id)
}
return callback_each_pod_finished()
return callbackEachPodFinished()
}
function callbackAllPodsFinished (err) {
if (err) return callback(err)
updatePodsScore(good_pods, bad_pods)
updatePodsScore(goodPods, badPods)
callback(null)
}
})
@ -130,7 +130,7 @@ function makeRequests () {
if (requests.length === 0) return
const requests_to_make = {
const requestsToMake = {
add: {
ids: [],
requests: []
@ -141,35 +141,35 @@ function makeRequests () {
}
}
async.each(requests, function (pool_request, callback_each) {
if (pool_request.type === 'add') {
requests_to_make.add.requests.push(pool_request.request)
requests_to_make.add.ids.push(pool_request._id)
} else if (pool_request.type === 'remove') {
requests_to_make.remove.requests.push(pool_request.request)
requests_to_make.remove.ids.push(pool_request._id)
async.each(requests, function (poolRequest, callbackEach) {
if (poolRequest.type === 'add') {
requestsToMake.add.requests.push(poolRequest.request)
requestsToMake.add.ids.push(poolRequest._id)
} else if (poolRequest.type === 'remove') {
requestsToMake.remove.requests.push(poolRequest.request)
requestsToMake.remove.ids.push(poolRequest._id)
} else {
logger.error('Unkown request type.', { request_type: pool_request.type })
logger.error('Unkown request type.', { request_type: poolRequest.type })
return // abort
}
callback_each()
callbackEach()
}, function () {
// Send the add requests
if (requests_to_make.add.requests.length !== 0) {
makeRequest('add', requests_to_make.add.requests, function (err) {
if (requestsToMake.add.requests.length !== 0) {
makeRequest('add', requestsToMake.add.requests, function (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
if (requests_to_make.remove.requests.length !== 0) {
makeRequest('remove', requests_to_make.remove.requests, function (err) {
if (requestsToMake.remove.requests.length !== 0) {
makeRequest('remove', requestsToMake.remove.requests, function (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 ids = map(pods, '_id')
Videos.listFromUrls(urls, function (err, videos_list) {
Videos.listFromUrls(urls, function (err, videosList) {
if (err) {
logger.error('Cannot list videos urls.', { error: err, urls: urls })
} else {
videos.removeRemoteVideos(videos_list, function (err) {
videos.removeRemoteVideos(videosList, function (err) {
if (err) logger.error('Cannot remove remote videos.', { error: err })
})
}
@ -201,22 +201,22 @@ function removeBadPods () {
if (err) {
logger.error('Cannot remove bad pods.', { error: err })
} else {
const pods_removed = r.result.n
logger.info('Removed %d pods.', pods_removed)
const podsRemoved = r.result.n
logger.info('Removed %d pods.', podsRemoved)
}
})
})
})
}
function updatePodsScore (good_pods, bad_pods) {
logger.info('Updating %d good pods and %d bad pods scores.', good_pods.length, bad_pods.length)
function updatePodsScore (goodPods, badPods) {
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.')
})
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.')
removeBadPods()
})

View File

@ -29,15 +29,15 @@ const videos = {
function createRemoteVideos (videos, callback) {
// Create the remote videos from the new pod
createRemoteVideoObjects(videos, function (err, remote_videos) {
createRemoteVideoObjects(videos, function (err, remoteVideos) {
if (err) return callback(err)
Videos.addRemotes(remote_videos, callback)
Videos.addRemotes(remoteVideos, callback)
})
}
function getVideoDuration (video_path, callback) {
ffmpeg.ffprobe(video_path, function (err, metadata) {
function getVideoDuration (videoPath, callback) {
ffmpeg.ffprobe(videoPath, function (err, metadata) {
if (err) return callback(err)
return callback(null, Math.floor(metadata.format.duration))
@ -54,9 +54,9 @@ function getVideoState (video) {
return { exist: exist, owned: owned }
}
function getVideoThumbnail (video_path, callback) {
const filename = pathUtils.basename(video_path) + '.jpg'
ffmpeg(video_path)
function getVideoThumbnail (videoPath, callback) {
const filename = pathUtils.basename(videoPath) + '.jpg'
ffmpeg(videoPath)
.on('error', callback)
.on('end', function () {
callback(null, filename)
@ -71,7 +71,7 @@ function getVideoThumbnail (video_path, callback) {
// Remove video datas from disk (video file, thumbnail...)
function removeVideosDataFromDisk (videos, callback) {
async.each(videos, function (video, callback_each) {
async.each(videos, function (video, callbackEach) {
fs.unlink(thumbnailsDir + video.thumbnail, function (err) {
if (err) logger.error('Cannot remove the video thumbnail')
@ -79,13 +79,13 @@ function removeVideosDataFromDisk (videos, callback) {
fs.unlink(uploadDir + video.namePath, function (err) {
if (err) {
logger.error('Cannot remove this video file.')
return callback_each(err)
return callbackEach(err)
}
callback_each(null)
callbackEach(null)
})
} else {
callback_each(null)
callbackEach(null)
}
})
}, callback)
@ -110,20 +110,20 @@ function seed (path, callback) {
}
function seedAllExisting (callback) {
Videos.listOwned(function (err, videos_list) {
Videos.listOwned(function (err, videosList) {
if (err) {
logger.error('Cannot get list of the videos to seed.')
return callback(err)
}
async.each(videos_list, function (video, each_callback) {
async.each(videosList, function (video, callbackEach) {
seed(uploadDir + video.namePath, function (err) {
if (err) {
logger.error('Cannot seed this video.')
return callback(err)
}
each_callback(null)
callbackEach(null)
})
}, callback)
})
@ -136,16 +136,16 @@ module.exports = videos
// ---------------------------------------------------------------------------
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
utils.generateRandomString(16, function (err, random_string) {
if (err) return callback_each(err)
utils.generateRandomString(16, function (err, randomString) {
if (err) return callbackEach(err)
const thumbnail_name = random_string + '.jpg'
createThumbnailFromBase64(thumbnail_name, video.thumbnail_base64, function (err) {
if (err) return callback_each(err)
const thumbnailName = randomString + '.jpg'
createThumbnailFromBase64(thumbnailName, video.thumbnailBase64, function (err) {
if (err) return callbackEach(err)
const params = {
name: video.name,
@ -153,21 +153,21 @@ function createRemoteVideoObjects (videos, callback) {
magnetUri: video.magnetUri,
podUrl: video.podUrl,
duration: video.duration,
thumbnail: thumbnail_name
thumbnail: thumbnailName
}
remote_videos.push(params)
remoteVideos.push(params)
callback_each(null)
callbackEach(null)
})
})
},
function (err) {
if (err) return callback(err)
callback(null, remote_videos)
callback(null, remoteVideos)
})
}
function createThumbnailFromBase64 (thumbnail_name, data, callback) {
fs.writeFile(thumbnailsDir + thumbnail_name, data, { encoding: 'base64' }, callback)
function createThumbnailFromBase64 (thumbnailName, data, 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 electron_debug = config.get('electron.debug')
const electronDebug = config.get('electron.debug')
let host = config.get('webserver.host')
let port = config.get('webserver.port')
let nodeKey = 'webtorrentnode' + port
@ -43,13 +43,13 @@ function create (options, callback) {
if (!webtorrent.silent) logger.info('IPC server ready.')
// 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.')
}, 30000)
ipc.server.on(processKey + '.ready', function () {
if (!webtorrent.silent) logger.info('Webtorrent process ready.')
clearTimeout(timeout_webtorrent_process)
clearTimeout(timeoutWebtorrentProcess)
callback()
})
@ -57,19 +57,19 @@ function create (options, callback) {
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) {
webtorrent_process.stderr.on('data', function (data) {
if (electronDebug === true) {
webtorrentProcess.stderr.on('data', function (data) {
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())
})
}
webtorrent.app = webtorrent_process
webtorrent.app = webtorrentProcess
})
ipc.server.start()
@ -88,8 +88,8 @@ function seed (path, callback) {
if (!webtorrent.silent) logger.debug('Node wants to seed %s.', data._id)
// Finish signal
const event_key = nodeKey + '.seedDone.' + data._id
ipc.server.on(event_key, function listener (received) {
const eventKey = nodeKey + '.seedDone.' + data._id
ipc.server.on(eventKey, function listener (received) {
if (!webtorrent.silent) logger.debug('Process seeded torrent %s.', received.magnetUri)
// This is a fake object, we just use the magnetUri in this project
@ -97,7 +97,7 @@ function seed (path, callback) {
magnetURI: received.magnetUri
}
ipc.server.off(event_key)
ipc.server.off(eventKey)
callback(torrent)
})
@ -115,8 +115,8 @@ function add (magnetUri, callback) {
if (!webtorrent.silent) logger.debug('Node wants to add ' + data._id)
// Finish signal
const event_key = nodeKey + '.addDone.' + data._id
ipc.server.on(event_key, function (received) {
const eventKey = nodeKey + '.addDone.' + data._id
ipc.server.on(eventKey, function (received) {
if (!webtorrent.silent) logger.debug('Process added torrent.')
// This is a fake object, we just use the magnetUri in this project
@ -124,7 +124,7 @@ function add (magnetUri, callback) {
files: received.files
}
ipc.server.off(event_key)
ipc.server.off(eventKey)
callback(torrent)
})
@ -142,14 +142,14 @@ function remove (magnetUri, callback) {
if (!webtorrent.silent) logger.debug('Node wants to stop seeding %s.', data._id)
// Finish signal
const event_key = nodeKey + '.removeDone.' + data._id
ipc.server.on(event_key, function (received) {
const eventKey = nodeKey + '.removeDone.' + data._id
ipc.server.on(eventKey, function (received) {
if (!webtorrent.silent) logger.debug('Process removed torrent %s.', data._id)
let err = null
if (received.err) err = received.err
ipc.server.off(event_key)
ipc.server.off(eventKey)
callback(err)
})

View File

@ -26,11 +26,11 @@ function webtorrent (args) {
const _id = data._id
wt.seed(path, { announceList: '' }, function (torrent) {
const to_send = {
const toSend = {
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
wt.add(magnetUri, function (torrent) {
const to_send = {
const toSend = {
files: []
}
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 () {
const to_send = {}
ipc.of[nodeKey].emit(nodeKey + '.removeDone.' + _id, to_send)
const toSend = {}
ipc.of[nodeKey].emit(nodeKey + '.removeDone.' + _id, toSend)
}
}

View File

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

View File

@ -8,13 +8,13 @@ const reqValidatorsUtils = {
checkErrors: checkErrors
}
function checkErrors (req, res, next, status_code) {
if (status_code === undefined) status_code = 400
function checkErrors (req, res, next, statusCode) {
if (statusCode === undefined) statusCode = 400
const errors = req.validationErrors()
if (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()

View File

@ -23,9 +23,9 @@ function decryptBody (req, res, next) {
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) {
if (err) {
logger.error('Cannot decrypt data.', { error: err })

View File

@ -58,13 +58,13 @@ function incrementScores (ids, value, callback) {
}
function list (callback) {
PodsDB.find(function (err, pods_list) {
PodsDB.find(function (err, podsList) {
if (err) {
logger.error('Cannot get the list of the pods.')
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) {
logger.debug('Creating client.')
const mongo_id = new mongoose.mongo.ObjectID()
return OAuthClientsDB.create({ _id: mongo_id, clientSecret: secret, grants: grants }, function (err) {
const mongoId = new mongoose.mongo.ObjectID()
return OAuthClientsDB.create({ _id: mongoId, clientSecret: secret, grants: grants }, function (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 + ').')
// TODO req validator
const mongo_id = new mongoose.mongo.ObjectID(clientId)
return OAuthClientsDB.findOne({ _id: mongo_id, clientSecret: clientSecret })
const mongoId = new mongoose.mongo.ObjectID(clientId)
return OAuthClientsDB.findOne({ _id: mongoId, clientSecret: clientSecret })
}
function getClients (callback) {
@ -99,7 +99,7 @@ function getUsers (callback) {
function saveToken (token, client, user) {
logger.debug('Saving token for client ' + client.id + ' and user ' + user.id + '.')
const token_to_create = {
const tokenToCreate = {
accessToken: token.accessToken,
accessTokenExpiresOn: token.accessTokenExpiresOn,
client: client.id,
@ -108,13 +108,13 @@ function saveToken (token, client, user) {
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
token_created.client = client
token_created.user = user
tokenCreated.client = client
tokenCreated.user = user
return token_created
return tokenCreated
})
}

View File

@ -77,13 +77,13 @@ function get (id, callback) {
}
function list (callback) {
VideosDB.find(function (err, videos_list) {
VideosDB.find(function (err, videosList) {
if (err) {
logger.error('Cannot get the list of the videos.')
return callback(err)
}
return callback(null, videos_list)
return callback(null, videosList)
})
}
@ -105,13 +105,13 @@ function listFromRemotes (callback) {
function listOwned (callback) {
// 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) {
logger.error('Cannot get the list of owned videos.')
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
function makePostRequest (path, token, fields, attach, done, fail) {
let status_code = 400
if (fail !== undefined && fail === false) status_code = 200
let statusCode = 400
if (fail !== undefined && fail === false) statusCode = 200
const req = request(server.url)
.post(path)
@ -26,18 +26,18 @@ describe('Test parameters validator', function () {
req.field(field, value)
})
req.expect(status_code, done)
req.expect(statusCode, done)
}
function makePostBodyRequest (path, fields, done, fail) {
let status_code = 400
if (fail !== undefined && fail === false) status_code = 200
let statusCode = 400
if (fail !== undefined && fail === false) statusCode = 200
request(server.url)
.post(path)
.set('Accept', 'application/json')
.send(fields)
.expect(status_code, done)
.expect(statusCode, done)
}
// ---------------------------------------------------------------

View File

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

View File

@ -10,25 +10,25 @@ const utils = require('./utils')
describe('Test basic friends', function () {
let servers = []
function testMadeFriends (servers, server_to_test, callback) {
function testMadeFriends (servers, serverToTest, callback) {
const friends = []
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)
}
utils.getFriendsList(server_to_test.url, function (err, res) {
utils.getFriendsList(serverToTest.url, function (err, res) {
if (err) throw err
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.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
expect(friends).to.contain(result_urls[0], error_string)
expect(friends).to.contain(result_urls[1], error_string)
const errorString = 'Friends url do not correspond for ' + serverToTest.url
expect(friends).to.contain(resultUrls[0], errorString)
expect(friends).to.contain(resultUrls[1], errorString)
callback()
})
}
@ -37,8 +37,8 @@ describe('Test basic friends', function () {
before(function (done) {
this.timeout(20000)
utils.flushAndRunMultipleServers(3, function (servers_run, urls_run) {
servers = servers_run
utils.flushAndRunMultipleServers(3, function (serversRun, urlsRun) {
servers = serversRun
done()
})
})

View File

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

View File

@ -14,7 +14,7 @@ const utils = require('./utils')
describe('Test a single pod', function () {
let server = null
let video_id = -1
let videoId = -1
before(function (done) {
this.timeout(20000)
@ -80,7 +80,7 @@ describe('Test a single pod', function () {
if (err) throw err
expect(test).to.equal(true)
video_id = video.id
videoId = video.id
webtorrent.add(video.magnetUri, function (torrent) {
expect(torrent.files).to.exist
@ -97,7 +97,7 @@ describe('Test a single pod', function () {
// Yes, this could be long
this.timeout(60000)
utils.getVideo(server.url, video_id, function (err, res) {
utils.getVideo(server.url, videoId, function (err, res) {
if (err) throw err
const video = res.body
@ -158,7 +158,7 @@ describe('Test a single pod', function () {
})
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
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_short1.webm', 'video_short2.webm', 'video_short3.webm'
]
async.each(videos, function (video, callback_each) {
utils.uploadVideo(server.url, server.access_token, video + ' name', video + ' description', video, callback_each)
async.each(videos, function (video, callbackEach) {
utils.uploadVideo(server.url, server.accessToken, video + ' name', video + ' description', video, callbackEach)
}, done)
})
@ -200,13 +200,13 @@ describe('Test a single pod', function () {
expect(videos).to.be.an('array')
expect(videos.length).to.equal(6)
const videos_by_name = keyBy(videos, 'name')
expect(videos_by_name['video_short.mp4 name'].duration).to.equal(5)
expect(videos_by_name['video_short.ogv name'].duration).to.equal(5)
expect(videos_by_name['video_short.webm name'].duration).to.equal(5)
expect(videos_by_name['video_short1.webm name'].duration).to.equal(10)
expect(videos_by_name['video_short2.webm name'].duration).to.equal(5)
expect(videos_by_name['video_short3.webm name'].duration).to.equal(5)
const videosByName = keyBy(videos, 'name')
expect(videosByName['video_short.mp4 name'].duration).to.equal(5)
expect(videosByName['video_short.ogv name'].duration).to.equal(5)
expect(videosByName['video_short.webm name'].duration).to.equal(5)
expect(videosByName['video_short1.webm name'].duration).to.equal(10)
expect(videosByName['video_short2.webm name'].duration).to.equal(5)
expect(videosByName['video_short3.webm name'].duration).to.equal(5)
done()
})
@ -216,15 +216,15 @@ describe('Test a single pod', function () {
utils.getVideosList(server.url, function (err, res) {
const videos = res.body
async.each(videos, function (video, callback_each) {
async.each(videos, function (video, callbackEach) {
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
expect(test).to.equal(true)
callback_each()
callbackEach()
})
}, done)
})

View File

@ -12,8 +12,8 @@ const utils = require('./utils')
describe('Test users', function () {
let server = null
let access_token = null
let video_id
let accessToken = null
let videoId
before(function (done) {
this.timeout(20000)
@ -78,21 +78,21 @@ describe('Test users', function () {
})
it('Should not be able to upload a video', function (done) {
access_token = 'mysupertoken'
utils.uploadVideo(server.url, access_token, 'my super name', 'my super description', 'video_short.webm', 401, done)
accessToken = 'mysupertoken'
utils.uploadVideo(server.url, accessToken, 'my super name', 'my super description', 'video_short.webm', 401, done)
})
it('Should be able to login', function (done) {
utils.login(server.url, server.client, server.user, 200, function (err, res) {
if (err) throw err
access_token = res.body.access_token
accessToken = res.body.access_token
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
utils.getVideosList(server.url, function (err, res) {
@ -101,24 +101,24 @@ describe('Test users', function () {
const video = res.body[0]
expect(video.author).to.equal('root')
video_id = video.id
videoId = video.id
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) {
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 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')

View File

@ -1,8 +1,8 @@
'use strict'
const child_process = require('child_process')
const exec = child_process.exec
const fork = child_process.fork
const childProcess = require('child_process')
const exec = childProcess.exec
const fork = childProcess.fork
const fs = require('fs')
const pathUtils = require('path')
const request = require('supertest')
@ -63,10 +63,10 @@ function getVideosList (url, end) {
.end(end)
}
function login (url, client, user, expected_status, end) {
function login (url, client, user, expectedStatus, end) {
if (!end) {
end = expected_status
expected_status = 200
end = expectedStatus
expectedStatus = 200
}
const path = '/api/v1/users/token'
@ -85,7 +85,7 @@ function login (url, client, user, expected_status, end) {
.post(path)
.type('form')
.send(body)
.expect(expected_status)
.expect(expectedStatus)
.end(end)
}
@ -97,10 +97,10 @@ function loginAndGetAccessToken (server, callback) {
})
}
function makeFriends (url, expected_status, callback) {
function makeFriends (url, expectedStatus, callback) {
if (!callback) {
callback = expected_status
expected_status = 204
callback = expectedStatus
expectedStatus = 204
}
const path = '/api/v1/pods/makefriends'
@ -109,7 +109,7 @@ function makeFriends (url, expected_status, callback) {
request(url)
.get(path)
.set('Accept', 'application/json')
.expect(expected_status)
.expect(expectedStatus)
.end(function (err, res) {
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) {
end = expected_status
expected_status = 204
end = expectedStatus
expectedStatus = 204
}
const path = '/api/v1/videos'
@ -146,11 +146,11 @@ function removeVideo (url, token, id, expected_status, end) {
.delete(path + '/' + id)
.set('Accept', 'application/json')
.set('Authorization', 'Bearer ' + token)
.expect(expected_status)
.expect(expectedStatus)
.end(end)
}
function flushAndRunMultipleServers (total_servers, serversRun) {
function flushAndRunMultipleServers (totalServers, serversRun) {
let apps = []
let urls = []
let i = 0
@ -159,13 +159,13 @@ function flushAndRunMultipleServers (total_servers, serversRun) {
apps[number - 1] = app
urls[number - 1] = url
i++
if (i === total_servers) {
if (i === totalServers) {
serversRun(apps, urls)
}
}
flushTests(function () {
for (let j = 1; j <= total_servers; j++) {
for (let j = 1; j <= totalServers; j++) {
// For the virtual buffer
setTimeout(function () {
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
const server_run_string = {
const serverRunString = {
'Connected to mongodb': 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.stdout.on('data', function onStdout (data) {
let dont_continue = false
let dontContinue = false
// Capture things if we want to
for (const key of Object.keys(regexps)) {
@ -230,13 +230,13 @@ function runServer (number, callback) {
}
// Check if all required sentences are here
for (const key of Object.keys(server_run_string)) {
if (data.toString().indexOf(key) !== -1) server_run_string[key] = true
if (server_run_string[key] === false) dont_continue = true
for (const key of Object.keys(serverRunString)) {
if (data.toString().indexOf(key) !== -1) serverRunString[key] = true
if (serverRunString[key] === false) dontContinue = true
}
// 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)
callback(server)
@ -254,14 +254,14 @@ function searchVideo (url, search, end) {
.end(end)
}
function testImage (url, video_name, image_path, callback) {
function testImage (url, videoName, imagePath, callback) {
request(url)
.get(image_path)
.get(imagePath)
.expect(200)
.end(function (err, res) {
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)
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) {
end = special_status
special_status = 204
end = specialStatus
specialStatus = 204
}
const path = '/api/v1/videos'
@ -280,11 +280,11 @@ function uploadVideo (url, access_token, name, description, fixture, special_sta
request(url)
.post(path)
.set('Accept', 'application/json')
.set('Authorization', 'Bearer ' + access_token)
.set('Authorization', 'Bearer ' + accessToken)
.field('name', name)
.field('description', description)
.attach('videofile', pathUtils.join(__dirname, 'fixtures', fixture))
.expect(special_status)
.expect(specialStatus)
.end(end)
}