From f0f5567b6918fc60c8cab15e13aec03a89a91dfb Mon Sep 17 00:00:00 2001 From: Chocobozzz Date: Wed, 16 Mar 2016 22:29:27 +0100 Subject: Use const/let now we use node 4.2 --- server/controllers/api/v1/index.js | 10 ++--- server/controllers/api/v1/pods.js | 34 +++++++-------- server/controllers/api/v1/remoteVideos.js | 20 ++++----- server/controllers/api/v1/videos.js | 50 ++++++++++----------- server/controllers/index.js | 4 +- server/helpers/customValidators.js | 4 +- server/helpers/logger.js | 10 ++--- server/helpers/peertubeCrypto.js | 50 ++++++++++----------- server/helpers/requests.js | 51 ++++++++++------------ server/helpers/utils.js | 4 +- server/initializers/checker.js | 20 ++++----- server/initializers/constants.js | 10 ++--- server/initializers/database.js | 14 +++--- server/lib/friends.js | 62 +++++++++++++------------- server/lib/poolRequests.js | 36 +++++++-------- server/lib/videos.js | 21 +++++---- server/lib/webtorrent.js | 46 ++++++++++---------- server/lib/webtorrentProcess.js | 38 ++++++++-------- server/middlewares/cache.js | 2 +- server/middlewares/index.js | 8 ++-- server/middlewares/reqValidators/index.js | 8 ++-- server/middlewares/reqValidators/pods.js | 8 ++-- server/middlewares/reqValidators/remote.js | 6 +-- server/middlewares/reqValidators/utils.js | 8 ++-- server/middlewares/reqValidators/videos.js | 10 ++--- server/middlewares/secure.js | 12 ++--- server/models/pods.js | 14 +++--- server/models/poolRequests.js | 10 ++--- server/models/videos.js | 36 +++++++-------- server/tests/api/checkParams.js | 70 +++++++++++++++--------------- server/tests/api/friendsAdvanced.js | 22 +++++----- server/tests/api/friendsBasic.js | 36 +++++++-------- server/tests/api/multiplePods.js | 46 ++++++++++---------- server/tests/api/singlePod.js | 24 +++++----- server/tests/api/utils.js | 62 +++++++++++++------------- server/tests/index.js | 8 ++-- 36 files changed, 433 insertions(+), 441 deletions(-) diff --git a/server/controllers/api/v1/index.js b/server/controllers/api/v1/index.js index b562bc2af..45f07ae1f 100644 --- a/server/controllers/api/v1/index.js +++ b/server/controllers/api/v1/index.js @@ -1,12 +1,12 @@ 'use strict' -var express = require('express') +const express = require('express') -var router = express.Router() +const router = express.Router() -var podsController = require('./pods') -var remoteVideosController = require('./remoteVideos') -var videosController = require('./videos') +const podsController = require('./pods') +const remoteVideosController = require('./remoteVideos') +const videosController = require('./videos') router.use('/pods', podsController) router.use('/remotevideos', remoteVideosController) diff --git a/server/controllers/api/v1/pods.js b/server/controllers/api/v1/pods.js index fa9832914..dbe1a7372 100644 --- a/server/controllers/api/v1/pods.js +++ b/server/controllers/api/v1/pods.js @@ -1,20 +1,20 @@ 'use strict' -var express = require('express') -var fs = require('fs') - -var logger = require('../../../helpers/logger') -var friends = require('../../../lib/friends') -var middleware = require('../../../middlewares') -var cacheMiddleware = middleware.cache -var peertubeCrypto = require('../../../helpers/peertubeCrypto') -var Pods = require('../../../models/pods') -var reqValidator = middleware.reqValidators.pods -var secureMiddleware = middleware.secure -var secureRequest = middleware.reqValidators.remote.secureRequest -var Videos = require('../../../models/videos') - -var router = express.Router() +const express = require('express') +const fs = require('fs') + +const logger = require('../../../helpers/logger') +const friends = require('../../../lib/friends') +const middleware = require('../../../middlewares') +const cacheMiddleware = middleware.cache +const peertubeCrypto = require('../../../helpers/peertubeCrypto') +const Pods = require('../../../models/pods') +const reqValidator = middleware.reqValidators.pods +const secureMiddleware = middleware.secure +const secureRequest = middleware.reqValidators.remote.secureRequest +const Videos = require('../../../models/videos') + +const router = express.Router() router.get('/', cacheMiddleware.cache(false), listPods) router.post('/', reqValidator.podsAdd, cacheMiddleware.cache(false), addPods) @@ -30,7 +30,7 @@ module.exports = router // --------------------------------------------------------------------------- function addPods (req, res, next) { - var informations = req.body.data + const informations = req.body.data Pods.add(informations, function (err) { if (err) return next(err) @@ -71,7 +71,7 @@ function makeFriends (req, res, next) { } function removePods (req, res, next) { - var url = req.body.signature.url + const url = req.body.signature.url Pods.remove(url, function (err) { if (err) return next(err) diff --git a/server/controllers/api/v1/remoteVideos.js b/server/controllers/api/v1/remoteVideos.js index 7622e39f5..58222de52 100644 --- a/server/controllers/api/v1/remoteVideos.js +++ b/server/controllers/api/v1/remoteVideos.js @@ -1,15 +1,15 @@ 'use strict' -var express = require('express') -var pluck = require('lodash-node/compat/collection/pluck') +const express = require('express') +const pluck = require('lodash-node/compat/collection/pluck') -var middleware = require('../../../middlewares') -var secureMiddleware = middleware.secure -var cacheMiddleware = middleware.cache -var reqValidator = middleware.reqValidators.remote -var videos = require('../../../models/videos') +const middleware = require('../../../middlewares') +const secureMiddleware = middleware.secure +const cacheMiddleware = middleware.cache +const reqValidator = middleware.reqValidators.remote +const videos = require('../../../models/videos') -var router = express.Router() +const router = express.Router() router.post('/add', reqValidator.secureRequest, @@ -42,8 +42,8 @@ function addRemoteVideos (req, res, next) { } function removeRemoteVideo (req, res, next) { - var url = req.body.signature.url - var magnetUris = pluck(req.body.data, 'magnetUri') + const url = req.body.signature.url + const magnetUris = pluck(req.body.data, 'magnetUri') videos.removeRemotesOfByMagnetUris(url, magnetUris, function (err) { if (err) return next(err) diff --git a/server/controllers/api/v1/videos.js b/server/controllers/api/v1/videos.js index 76cad62d1..1eea417d4 100644 --- a/server/controllers/api/v1/videos.js +++ b/server/controllers/api/v1/videos.js @@ -1,41 +1,41 @@ 'use strict' -var config = require('config') -var crypto = require('crypto') -var express = require('express') -var multer = require('multer') - -var logger = require('../../../helpers/logger') -var friends = require('../../../lib/friends') -var middleware = require('../../../middlewares') -var cacheMiddleware = middleware.cache -var reqValidator = middleware.reqValidators.videos -var Videos = require('../../../models/videos') // model -var videos = require('../../../lib/videos') -var webtorrent = require('../../../lib/webtorrent') - -var router = express.Router() -var uploads = config.get('storage.uploads') +const config = require('config') +const crypto = require('crypto') +const express = require('express') +const multer = require('multer') + +const logger = require('../../../helpers/logger') +const friends = require('../../../lib/friends') +const middleware = require('../../../middlewares') +const cacheMiddleware = middleware.cache +const reqValidator = middleware.reqValidators.videos +const Videos = require('../../../models/videos') // model +const videos = require('../../../lib/videos') +const webtorrent = require('../../../lib/webtorrent') + +const router = express.Router() +const uploads = config.get('storage.uploads') // multer configuration -var storage = multer.diskStorage({ +const storage = multer.diskStorage({ destination: function (req, file, cb) { cb(null, uploads) }, filename: function (req, file, cb) { - var extension = '' + let extension = '' if (file.mimetype === 'video/webm') extension = 'webm' else if (file.mimetype === 'video/mp4') extension = 'mp4' else if (file.mimetype === 'video/ogg') extension = 'ogv' crypto.pseudoRandomBytes(16, function (err, raw) { - var fieldname = err ? undefined : raw.toString('hex') + const fieldname = err ? undefined : raw.toString('hex') cb(null, fieldname + '.' + extension) }) } }) -var reqFiles = multer({ storage: storage }).fields([{ name: 'input_video', maxCount: 1 }]) +const reqFiles = multer({ storage: storage }).fields([{ name: 'input_video', maxCount: 1 }]) router.get('/', cacheMiddleware.cache(false), listVideos) router.post('/', reqFiles, reqValidator.videosAdd, cacheMiddleware.cache(false), addVideo) @@ -50,8 +50,8 @@ module.exports = router // --------------------------------------------------------------------------- function addVideo (req, res, next) { - var video_file = req.files.input_video[0] - var video_infos = req.body + const video_file = req.files.input_video[0] + const video_infos = req.body videos.seed(video_file.path, function (err, torrent) { if (err) { @@ -59,7 +59,7 @@ function addVideo (req, res, next) { return next(err) } - var video_data = { + const video_data = { name: video_infos.name, namePath: video_file.filename, description: video_infos.description, @@ -103,7 +103,7 @@ function listVideos (req, res, next) { } function removeVideo (req, res, next) { - var video_id = req.params.id + const video_id = req.params.id Videos.get(video_id, function (err, video) { if (err) return next(err) @@ -111,7 +111,7 @@ function removeVideo (req, res, next) { Videos.removeOwned(req.params.id, function (err) { if (err) return next(err) - var params = { + const params = { name: video.name, magnetUri: video.magnetUri } diff --git a/server/controllers/index.js b/server/controllers/index.js index 7b0288dbb..4c1d3dafe 100644 --- a/server/controllers/index.js +++ b/server/controllers/index.js @@ -1,8 +1,8 @@ 'use strict' -var constants = require('../initializers/constants') +const constants = require('../initializers/constants') -var apiController = require('./api/' + constants.API_VERSION) +const apiController = require('./api/' + constants.API_VERSION) module.exports = { api: apiController diff --git a/server/helpers/customValidators.js b/server/helpers/customValidators.js index 20c41f5da..a5ae32780 100644 --- a/server/helpers/customValidators.js +++ b/server/helpers/customValidators.js @@ -1,8 +1,8 @@ 'use strict' -var validator = require('validator') +const validator = require('validator') -var customValidators = { +const customValidators = { eachIsRemoteVideosAddValid: eachIsRemoteVideosAddValid, eachIsRemoteVideosRemoveValid: eachIsRemoteVideosRemoveValid, isArray: isArray diff --git a/server/helpers/logger.js b/server/helpers/logger.js index 1c15a0edd..d3fce4cc9 100644 --- a/server/helpers/logger.js +++ b/server/helpers/logger.js @@ -1,13 +1,13 @@ // Thanks http://tostring.it/2014/06/23/advanced-logging-with-nodejs/ 'use strict' -var config = require('config') -var path = require('path') -var winston = require('winston') +const config = require('config') +const path = require('path') +const winston = require('winston') winston.emitErrs = true -var logDir = path.join(__dirname, '..', '..', config.get('storage.logs')) -var logger = new winston.Logger({ +const logDir = path.join(__dirname, '..', '..', config.get('storage.logs')) +const logger = new winston.Logger({ transports: [ new winston.transports.File({ level: 'debug', diff --git a/server/helpers/peertubeCrypto.js b/server/helpers/peertubeCrypto.js index 7e65c43e1..3826ebaf6 100644 --- a/server/helpers/peertubeCrypto.js +++ b/server/helpers/peertubeCrypto.js @@ -1,18 +1,18 @@ 'use strict' -var config = require('config') -var crypto = require('crypto') -var fs = require('fs') -var openssl = require('openssl-wrapper') -var path = require('path') -var ursa = require('ursa') +const config = require('config') +const crypto = require('crypto') +const fs = require('fs') +const openssl = require('openssl-wrapper') +const path = require('path') +const ursa = require('ursa') -var logger = require('./logger') +const logger = require('./logger') -var certDir = path.join(__dirname, '..', '..', config.get('storage.certs')) -var algorithm = 'aes-256-ctr' +const certDir = path.join(__dirname, '..', '..', config.get('storage.certs')) +const algorithm = 'aes-256-ctr' -var peertubeCrypto = { +const peertubeCrypto = { checkSignature: checkSignature, createCertsIfNotExist: createCertsIfNotExist, decrypt: decrypt, @@ -22,8 +22,8 @@ var peertubeCrypto = { } function checkSignature (public_key, raw_data, hex_signature) { - var crt = ursa.createPublicKey(public_key) - var is_valid = crt.hashAndVerify('sha256', new Buffer(raw_data).toString('hex'), hex_signature, 'hex') + const crt = ursa.createPublicKey(public_key) + const is_valid = crt.hashAndVerify('sha256', new Buffer(raw_data).toString('hex'), hex_signature, 'hex') return is_valid } @@ -43,22 +43,22 @@ function decrypt (key, data, callback) { fs.readFile(getCertDir() + 'peertube.key.pem', function (err, file) { if (err) return callback(err) - var my_private_key = ursa.createPrivateKey(file) - var decrypted_key = my_private_key.decrypt(key, 'hex', 'utf8') - var decrypted_data = symetricDecrypt(data, decrypted_key) + const my_private_key = ursa.createPrivateKey(file) + const decrypted_key = my_private_key.decrypt(key, 'hex', 'utf8') + const decrypted_data = symetricDecrypt(data, decrypted_key) return callback(null, decrypted_data) }) } function encrypt (public_key, data, callback) { - var crt = ursa.createPublicKey(public_key) + const crt = ursa.createPublicKey(public_key) symetricEncrypt(data, function (err, dataEncrypted) { if (err) return callback(err) - var key = crt.encrypt(dataEncrypted.password, 'utf8', 'hex') - var encrypted = { + const key = crt.encrypt(dataEncrypted.password, 'utf8', 'hex') + const encrypted = { data: dataEncrypted.crypted, key: key } @@ -72,8 +72,8 @@ function getCertDir () { } function sign (data) { - var myKey = ursa.createPrivateKey(fs.readFileSync(certDir + 'peertube.key.pem')) - var signature = myKey.hashAndSign('sha256', data, 'utf8', 'hex') + const myKey = ursa.createPrivateKey(fs.readFileSync(certDir + 'peertube.key.pem')) + const signature = myKey.hashAndSign('sha256', data, 'utf8', 'hex') return signature } @@ -93,7 +93,7 @@ function certsExist (callback) { function createCerts (callback) { certsExist(function (exist) { if (exist === true) { - var string = 'Certs already exist.' + const string = 'Certs already exist.' logger.warning(string) return callback(new Error(string)) } @@ -129,8 +129,8 @@ function generatePassword (callback) { } function symetricDecrypt (text, password) { - var decipher = crypto.createDecipher(algorithm, password) - var dec = decipher.update(text, 'hex', 'utf8') + const decipher = crypto.createDecipher(algorithm, password) + let dec = decipher.update(text, 'hex', 'utf8') dec += decipher.final('utf8') return dec } @@ -139,8 +139,8 @@ function symetricEncrypt (text, callback) { generatePassword(function (err, password) { if (err) return callback(err) - var cipher = crypto.createCipher(algorithm, password) - var crypted = cipher.update(text, 'utf8', 'hex') + const cipher = crypto.createCipher(algorithm, password) + let crypted = cipher.update(text, 'utf8', 'hex') crypted += cipher.final('hex') callback(null, { crypted: crypted, password: password }) }) diff --git a/server/helpers/requests.js b/server/helpers/requests.js index e19afa5ca..17b1127c0 100644 --- a/server/helpers/requests.js +++ b/server/helpers/requests.js @@ -1,19 +1,19 @@ 'use strict' -var async = require('async') -var config = require('config') -var request = require('request') -var replay = require('request-replay') +const async = require('async') +const config = require('config') +const request = require('request') +const replay = require('request-replay') -var constants = require('../initializers/constants') -var logger = require('./logger') -var peertubeCrypto = require('./peertubeCrypto') +const constants = require('../initializers/constants') +const logger = require('./logger') +const peertubeCrypto = require('./peertubeCrypto') -var http = config.get('webserver.https') ? 'https' : 'http' -var host = config.get('webserver.host') -var port = config.get('webserver.port') +const http = config.get('webserver.https') ? 'https' : 'http' +const host = config.get('webserver.host') +const port = config.get('webserver.port') -var requests = { +const requests = { makeMultipleRetryRequest: makeMultipleRetryRequest } @@ -23,8 +23,8 @@ function makeMultipleRetryRequest (all_data, pods, callbackEach, callback) { callbackEach = null } - var url = http + '://' + host + ':' + port - var signature + const url = http + '://' + host + ':' + port + let signature // Add signature if it is specified in the params if (all_data.method === 'POST' && all_data.data && all_data.sign === true) { @@ -43,7 +43,7 @@ function makeMultipleRetryRequest (all_data, pods, callbackEach, callback) { } } - var params = { + const params = { url: pod.url + all_data.path, method: all_data.method } @@ -52,19 +52,16 @@ function makeMultipleRetryRequest (all_data, pods, callbackEach, callback) { if (all_data.method === 'POST' && all_data.data) { // Encrypt data ? if (all_data.encrypt === true) { - // TODO: ES6 with let - ;(function (copy_params, copy_url, copy_pod, copy_signature) { - peertubeCrypto.encrypt(pod.publicKey, JSON.stringify(all_data.data), function (err, encrypted) { - if (err) return callback(err) - - copy_params.json = { - data: encrypted.data, - key: encrypted.key - } - - makeRetryRequest(copy_params, copy_url, copy_pod, copy_signature, callbackEachRetryRequest) - }) - })(params, url, pod, signature) + peertubeCrypto.encrypt(pod.publicKey, JSON.stringify(all_data.data), function (err, encrypted) { + if (err) return callback(err) + + params.json = { + data: encrypted.data, + key: encrypted.key + } + + makeRetryRequest(params, url, pod, signature, callbackEachRetryRequest) + }) } else { params.json = { data: all_data.data } makeRetryRequest(params, url, pod, signature, callbackEachRetryRequest) diff --git a/server/helpers/utils.js b/server/helpers/utils.js index d2c9ad8b2..1f7839673 100644 --- a/server/helpers/utils.js +++ b/server/helpers/utils.js @@ -1,8 +1,8 @@ 'use strict' -var logger = require('./logger') +const logger = require('./logger') -var utils = { +const utils = { cleanForExit: cleanForExit } diff --git a/server/initializers/checker.js b/server/initializers/checker.js index 44d9ea85b..a21e54982 100644 --- a/server/initializers/checker.js +++ b/server/initializers/checker.js @@ -1,24 +1,24 @@ 'use strict' -var config = require('config') -var mkdirp = require('mkdirp') -var path = require('path') +const config = require('config') +const mkdirp = require('mkdirp') +const path = require('path') -var checker = { +const checker = { checkConfig: checkConfig, createDirectoriesIfNotExist: createDirectoriesIfNotExist } // Check the config files function checkConfig () { - var required = [ 'listen.port', + const required = [ 'listen.port', 'webserver.https', 'webserver.host', 'webserver.port', 'database.host', 'database.port', 'database.suffix', 'storage.certs', 'storage.uploads', 'storage.logs', 'network.friends' ] - var miss = [] + const miss = [] - for (var key of required) { + for (const key of required) { if (!config.has(key)) { miss.push(key) } @@ -29,10 +29,10 @@ function checkConfig () { // Create directories for the storage if it doesn't exist function createDirectoriesIfNotExist () { - var storages = config.get('storage') + const storages = config.get('storage') - for (var key of Object.keys(storages)) { - var dir = storages[key] + for (const key of Object.keys(storages)) { + const dir = storages[key] try { mkdirp.sync(path.join(__dirname, '..', '..', dir)) } catch (error) { diff --git a/server/initializers/constants.js b/server/initializers/constants.js index 16e50443b..dc08805b9 100644 --- a/server/initializers/constants.js +++ b/server/initializers/constants.js @@ -1,22 +1,22 @@ 'use strict' // API version of our pod -var API_VERSION = 'v1' +const API_VERSION = 'v1' // Score a pod has when we create it as a friend -var FRIEND_BASE_SCORE = 100 +let FRIEND_BASE_SCORE = 100 // Time to wait between requests to the friends -var INTERVAL = 60000 +let INTERVAL = 60000 // Number of points we add/remove from a friend after a successful/bad request -var PODS_SCORE = { +const PODS_SCORE = { MALUS: -10, BONUS: 10 } // Number of retries we make for the make retry requests (to friends...) -var REQUEST_RETRIES = 10 +let REQUEST_RETRIES = 10 // Special constants for a test instance if (isTestInstance() === true) { diff --git a/server/initializers/database.js b/server/initializers/database.js index a917442ec..830cc7dd8 100644 --- a/server/initializers/database.js +++ b/server/initializers/database.js @@ -1,15 +1,15 @@ 'use strict' -var config = require('config') -var mongoose = require('mongoose') +const config = require('config') +const mongoose = require('mongoose') -var logger = require('../helpers/logger') +const logger = require('../helpers/logger') -var dbname = 'peertube' + config.get('database.suffix') -var host = config.get('database.host') -var port = config.get('database.port') +const dbname = 'peertube' + config.get('database.suffix') +const host = config.get('database.host') +const port = config.get('database.port') -var database = { +const database = { connect: connect } diff --git a/server/lib/friends.js b/server/lib/friends.js index 006a64404..c3c231604 100644 --- a/server/lib/friends.js +++ b/server/lib/friends.js @@ -1,23 +1,23 @@ 'use strict' -var async = require('async') -var config = require('config') -var fs = require('fs') -var request = require('request') - -var constants = require('../initializers/constants') -var logger = require('../helpers/logger') -var peertubeCrypto = require('../helpers/peertubeCrypto') -var Pods = require('../models/pods') -var poolRequests = require('../lib/poolRequests') -var requests = require('../helpers/requests') -var Videos = require('../models/videos') - -var http = config.get('webserver.https') ? 'https' : 'http' -var host = config.get('webserver.host') -var port = config.get('webserver.port') - -var pods = { +const async = require('async') +const config = require('config') +const fs = require('fs') +const request = require('request') + +const constants = require('../initializers/constants') +const logger = require('../helpers/logger') +const peertubeCrypto = require('../helpers/peertubeCrypto') +const Pods = require('../models/pods') +const poolRequests = require('../lib/poolRequests') +const requests = require('../helpers/requests') +const Videos = require('../models/videos') + +const http = config.get('webserver.https') ? 'https' : 'http' +const host = config.get('webserver.host') +const port = config.get('webserver.port') + +const pods = { addVideoToFriends: addVideoToFriends, hasFriends: hasFriends, makeFriends: makeFriends, @@ -27,7 +27,7 @@ var pods = { function addVideoToFriends (video) { // To avoid duplicates - var id = video.name + video.magnetUri + const id = video.name + video.magnetUri // ensure namePath is null video.namePath = null poolRequests.addRequest(id, 'add', video) @@ -37,13 +37,13 @@ function hasFriends (callback) { Pods.count(function (err, count) { if (err) return callback(err) - var has_friends = (count !== 0) + const has_friends = (count !== 0) callback(null, has_friends) }) } function makeFriends (callback) { - var pods_score = {} + const pods_score = {} logger.info('Make friends!') fs.readFile(peertubeCrypto.getCertDir() + 'peertube.pub', 'utf8', function (err, cert) { @@ -52,7 +52,7 @@ function makeFriends (callback) { return callback(err) } - var urls = config.get('network.friends') + const urls = config.get('network.friends') async.each(urls, function (url, callback) { computeForeignPodsList(url, pods_score, callback) @@ -60,8 +60,8 @@ function makeFriends (callback) { if (err) return callback(err) logger.debug('Pods scores computed.', { pods_score: pods_score }) - var pods_list = computeWinningPods(urls, pods_score) - logger.debug('Pods that we keep computed.', { pods_to_keep: pods_list }) + const pods_list = computeWinningPods(urls, pods_score) + logger.debug('Pods that we keep.', { pods_to_keep: pods_list }) makeRequestsToWinningPods(cert, pods_list, callback) }) @@ -77,7 +77,7 @@ function quitFriends (callback) { Pods.list(function (err, pods) { if (err) return callback(err) - var request = { + const request = { method: 'POST', path: '/api/' + constants.API_VERSION + '/pods/remove', sign: true, @@ -109,7 +109,7 @@ function quitFriends (callback) { function removeVideoToFriends (video) { // To avoid duplicates - var id = video.name + video.magnetUri + const id = video.name + video.magnetUri poolRequests.addRequest(id, 'remove', video) } @@ -128,7 +128,7 @@ function computeForeignPodsList (url, pods_score, callback) { if (foreign_pods_list.length === 0) return callback() async.each(foreign_pods_list, function (foreign_pod, callback_each) { - var foreign_url = foreign_pod.url + const foreign_url = foreign_pod.url if (pods_score[foreign_url]) pods_score[foreign_url]++ else pods_score[foreign_url] = 1 @@ -143,8 +143,8 @@ function computeForeignPodsList (url, pods_score, callback) { function computeWinningPods (urls, pods_score) { // Build the list of pods to add // Only add a pod if it exists in more than a half base pods - var pods_list = [] - var base_score = urls.length / 2 + 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 }) }) @@ -153,7 +153,7 @@ function computeWinningPods (urls, pods_score) { } function getForeignPodsList (url, callback) { - var path = '/api/' + constants.API_VERSION + '/pods' + const path = '/api/' + constants.API_VERSION + '/pods' request.get(url + path, function (err, response, body) { if (err) return callback(err) @@ -175,7 +175,7 @@ function makeRequestsToWinningPods (cert, pods_list, callback) { return callback(err) } - var data = { + const data = { url: http + '://' + host + ':' + port, publicKey: cert, videos: videos_list diff --git a/server/lib/poolRequests.js b/server/lib/poolRequests.js index f786c3c7a..2eb501311 100644 --- a/server/lib/poolRequests.js +++ b/server/lib/poolRequests.js @@ -1,18 +1,18 @@ 'use strict' -var async = require('async') -var pluck = require('lodash-node/compat/collection/pluck') +const async = require('async') +const pluck = require('lodash-node/compat/collection/pluck') -var constants = require('../initializers/constants') -var logger = require('../helpers/logger') -var Pods = require('../models/pods') -var PoolRequests = require('../models/poolRequests') -var requests = require('../helpers/requests') -var Videos = require('../models/videos') +const constants = require('../initializers/constants') +const logger = require('../helpers/logger') +const Pods = require('../models/pods') +const PoolRequests = require('../models/poolRequests') +const requests = require('../helpers/requests') +const Videos = require('../models/videos') -var timer = null +let timer = null -var poolRequests = { +const poolRequests = { activate: activate, addRequest: addRequest, deactivate: deactivate, @@ -77,7 +77,7 @@ function makePoolRequest (type, requests_to_make, callback) { Pods.list(function (err, pods) { if (err) return callback(err) - var params = { + const params = { encrypt: true, sign: true, method: 'POST', @@ -93,8 +93,8 @@ function makePoolRequest (type, requests_to_make, callback) { return callback(new Error('Unkown pool request type.')) } - var bad_pods = [] - var good_pods = [] + const bad_pods = [] + const good_pods = [] requests.makeMultipleRetryRequest(params, pods, callbackEachPodFinished, callbackAllPodsFinished) @@ -129,7 +129,7 @@ function makePoolRequests () { if (pool_requests.length === 0) return - var requests_to_make = { + const requests_to_make = { add: { ids: [], requests: [] @@ -184,14 +184,14 @@ function removeBadPods () { if (pods.length === 0) return - var urls = pluck(pods, 'url') - var ids = pluck(pods, '_id') + const urls = pluck(pods, 'url') + const ids = pluck(pods, '_id') Videos.removeAllRemotesOf(urls, function (err, r) { if (err) { logger.error('Cannot remove videos from a pod that we removing.', { error: err }) } else { - var videos_removed = r.result.n + const videos_removed = r.result.n logger.info('Removed %d videos.', videos_removed) } @@ -199,7 +199,7 @@ function removeBadPods () { if (err) { logger.error('Cannot remove bad pods.', { error: err }) } else { - var pods_removed = r.result.n + const pods_removed = r.result.n logger.info('Removed %d pods.', pods_removed) } }) diff --git a/server/lib/videos.js b/server/lib/videos.js index a5fe7b0c4..eb3a0125a 100644 --- a/server/lib/videos.js +++ b/server/lib/videos.js @@ -1,25 +1,24 @@ 'use strict' -var async = require('async') -var config = require('config') -// TODO -var path = require('path') -var webtorrent = require('../lib/webtorrent') +const async = require('async') +const config = require('config') +const pathUtils = require('path') +const webtorrent = require('../lib/webtorrent') -var logger = require('../helpers/logger') -var Videos = require('../models/videos') +const logger = require('../helpers/logger') +const Videos = require('../models/videos') -var uploadDir = path.join(__dirname, '..', '..', config.get('storage.uploads')) +const uploadDir = pathUtils.join(__dirname, '..', '..', config.get('storage.uploads')) -var videos = { +const videos = { getVideoState: getVideoState, seed: seed, seedAllExisting: seedAllExisting } function getVideoState (video, callback) { - var exist = (video !== null) - var owned = false + const exist = (video !== null) + let owned = false if (exist === true) { owned = (video.namePath !== null) } diff --git a/server/lib/webtorrent.js b/server/lib/webtorrent.js index cb641fead..455b086a3 100644 --- a/server/lib/webtorrent.js +++ b/server/lib/webtorrent.js @@ -1,20 +1,20 @@ 'use strict' -var config = require('config') -var ipc = require('node-ipc') -var pathUtils = require('path') -var spawn = require('electron-spawn') +const config = require('config') +const ipc = require('node-ipc') +const pathUtils = require('path') +const spawn = require('electron-spawn') -var logger = require('../helpers/logger') +const logger = require('../helpers/logger') -var host = config.get('webserver.host') -var port = config.get('webserver.port') -var nodeKey = 'webtorrentnode' + port -var processKey = 'webtorrentprocess' + port +let host = config.get('webserver.host') +let port = config.get('webserver.port') +let nodeKey = 'webtorrentnode' + port +let processKey = 'webtorrentprocess' + port ipc.config.silent = true ipc.config.id = nodeKey -var webtorrent = { +const webtorrent = { add: add, app: null, // Pid of the app create: create, @@ -42,7 +42,7 @@ function create (options, callback) { if (!webtorrent.silent) logger.info('IPC server ready.') // Run a timeout of 30s after which we exit the process - var timeout_webtorrent_process = setTimeout(function () { + const timeout_webtorrent_process = setTimeout(function () { throw new Error('Timeout : cannot run the webtorrent process. Please ensure you have electron-prebuilt npm package installed with xvfb-run.') }, 30000) @@ -56,7 +56,7 @@ function create (options, callback) { throw new Error('Received exception error from webtorrent process.' + data.exception) }) - var webtorrent_process = spawn(pathUtils.join(__dirname, 'webtorrentProcess.js'), host, port, { detached: true }) + const webtorrent_process = spawn(pathUtils.join(__dirname, 'webtorrentProcess.js'), host, port, { detached: true }) webtorrent_process.stderr.on('data', function (data) { // logger.debug('Webtorrent process stderr: ', data.toString()) }) @@ -72,9 +72,9 @@ function create (options, callback) { } function seed (path, callback) { - var extension = pathUtils.extname(path) - var basename = pathUtils.basename(path, extension) - var data = { + const extension = pathUtils.extname(path) + const basename = pathUtils.basename(path, extension) + const data = { _id: basename, args: { path: path @@ -84,12 +84,12 @@ function seed (path, callback) { if (!webtorrent.silent) logger.debug('Node wants to seed %s.', data._id) // Finish signal - var event_key = nodeKey + '.seedDone.' + data._id + const event_key = nodeKey + '.seedDone.' + data._id ipc.server.on(event_key, 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 - var torrent = { + const torrent = { magnetURI: received.magnetUri } @@ -101,7 +101,7 @@ function seed (path, callback) { } function add (magnetUri, callback) { - var data = { + const data = { _id: magnetUri, args: { magnetUri: magnetUri @@ -111,12 +111,12 @@ function add (magnetUri, callback) { if (!webtorrent.silent) logger.debug('Node wants to add ' + data._id) // Finish signal - var event_key = nodeKey + '.addDone.' + data._id + const event_key = nodeKey + '.addDone.' + data._id ipc.server.on(event_key, function (received) { if (!webtorrent.silent) logger.debug('Process added torrent.') // This is a fake object, we just use the magnetUri in this project - var torrent = { + const torrent = { files: received.files } @@ -128,7 +128,7 @@ function add (magnetUri, callback) { } function remove (magnetUri, callback) { - var data = { + const data = { _id: magnetUri, args: { magnetUri: magnetUri @@ -138,11 +138,11 @@ function remove (magnetUri, callback) { if (!webtorrent.silent) logger.debug('Node wants to stop seeding %s.', data._id) // Finish signal - var event_key = nodeKey + '.removeDone.' + data._id + const event_key = nodeKey + '.removeDone.' + data._id ipc.server.on(event_key, function (received) { if (!webtorrent.silent) logger.debug('Process removed torrent %s.', data._id) - var err = null + let err = null if (received.err) err = received.err ipc.server.off(event_key) diff --git a/server/lib/webtorrentProcess.js b/server/lib/webtorrentProcess.js index 7da52523a..c68e97ee4 100644 --- a/server/lib/webtorrentProcess.js +++ b/server/lib/webtorrentProcess.js @@ -1,32 +1,32 @@ 'use strict' -var WebTorrent = require('webtorrent') -var ipc = require('node-ipc') +const WebTorrent = require('webtorrent') +const ipc = require('node-ipc') function webtorrent (args) { if (args.length !== 3) { throw new Error('Wrong arguments number: ' + args.length + '/3') } - var host = args[1] - var port = args[2] - var nodeKey = 'webtorrentnode' + port - var processKey = 'webtorrentprocess' + port + const host = args[1] + const port = args[2] + const nodeKey = 'webtorrentnode' + port + const processKey = 'webtorrentprocess' + port ipc.config.silent = true ipc.config.id = processKey if (host === 'client' && port === '1') global.WEBTORRENT_ANNOUNCE = [] else global.WEBTORRENT_ANNOUNCE = 'ws://' + host + ':' + port + '/tracker/socket' - var wt = new WebTorrent({ dht: false }) + const wt = new WebTorrent({ dht: false }) function seed (data) { - var args = data.args - var path = args.path - var _id = data._id + const args = data.args + const path = args.path + const _id = data._id wt.seed(path, { announceList: '' }, function (torrent) { - var to_send = { + const to_send = { magnetUri: torrent.magnetURI } @@ -35,12 +35,12 @@ function webtorrent (args) { } function add (data) { - var args = data.args - var magnetUri = args.magnetUri - var _id = data._id + const args = data.args + const magnetUri = args.magnetUri + const _id = data._id wt.add(magnetUri, function (torrent) { - var to_send = { + const to_send = { files: [] } @@ -53,9 +53,9 @@ function webtorrent (args) { } function remove (data) { - var args = data.args - var magnetUri = args.magnetUri - var _id = data._id + const args = data.args + const magnetUri = args.magnetUri + const _id = data._id try { wt.remove(magnetUri, callback) @@ -65,7 +65,7 @@ function webtorrent (args) { } function callback () { - var to_send = {} + const to_send = {} ipc.of[nodeKey].emit(nodeKey + '.removeDone.' + _id, to_send) } } diff --git a/server/middlewares/cache.js b/server/middlewares/cache.js index 0d3da0075..1b621f6dc 100644 --- a/server/middlewares/cache.js +++ b/server/middlewares/cache.js @@ -1,6 +1,6 @@ 'use strict' -var cacheMiddleware = { +const cacheMiddleware = { cache: cache } diff --git a/server/middlewares/index.js b/server/middlewares/index.js index c85899b0c..d85f6261c 100644 --- a/server/middlewares/index.js +++ b/server/middlewares/index.js @@ -1,10 +1,10 @@ 'use strict' -var cacheMiddleware = require('./cache') -var reqValidatorsMiddleware = require('./reqValidators') -var secureMiddleware = require('./secure') +const cacheMiddleware = require('./cache') +const reqValidatorsMiddleware = require('./reqValidators') +const secureMiddleware = require('./secure') -var middlewares = { +const middlewares = { cache: cacheMiddleware, reqValidators: reqValidatorsMiddleware, secure: secureMiddleware diff --git a/server/middlewares/reqValidators/index.js b/server/middlewares/reqValidators/index.js index 345dbd0e2..c6c5e1309 100644 --- a/server/middlewares/reqValidators/index.js +++ b/server/middlewares/reqValidators/index.js @@ -1,10 +1,10 @@ 'use strict' -var podsReqValidators = require('./pods') -var remoteReqValidators = require('./remote') -var videosReqValidators = require('./videos') +const podsReqValidators = require('./pods') +const remoteReqValidators = require('./remote') +const videosReqValidators = require('./videos') -var reqValidators = { +const reqValidators = { pods: podsReqValidators, remote: remoteReqValidators, videos: videosReqValidators diff --git a/server/middlewares/reqValidators/pods.js b/server/middlewares/reqValidators/pods.js index ef09d51cf..45e34c1ab 100644 --- a/server/middlewares/reqValidators/pods.js +++ b/server/middlewares/reqValidators/pods.js @@ -1,10 +1,10 @@ 'use strict' -var checkErrors = require('./utils').checkErrors -var friends = require('../../lib/friends') -var logger = require('../../helpers/logger') +const checkErrors = require('./utils').checkErrors +const friends = require('../../lib/friends') +const logger = require('../../helpers/logger') -var reqValidatorsPod = { +const reqValidatorsPod = { makeFriends: makeFriends, podsAdd: podsAdd } diff --git a/server/middlewares/reqValidators/remote.js b/server/middlewares/reqValidators/remote.js index 88de16b49..3bc0e0f40 100644 --- a/server/middlewares/reqValidators/remote.js +++ b/server/middlewares/reqValidators/remote.js @@ -1,9 +1,9 @@ 'use strict' -var checkErrors = require('./utils').checkErrors -var logger = require('../../helpers/logger') +const checkErrors = require('./utils').checkErrors +const logger = require('../../helpers/logger') -var reqValidatorsRemote = { +const reqValidatorsRemote = { remoteVideosAdd: remoteVideosAdd, remoteVideosRemove: remoteVideosRemove, secureRequest: secureRequest diff --git a/server/middlewares/reqValidators/utils.js b/server/middlewares/reqValidators/utils.js index 46c982571..05675c445 100644 --- a/server/middlewares/reqValidators/utils.js +++ b/server/middlewares/reqValidators/utils.js @@ -1,16 +1,16 @@ 'use strict' -var util = require('util') +const util = require('util') -var logger = require('../../helpers/logger') +const logger = require('../../helpers/logger') -var reqValidatorsUtils = { +const reqValidatorsUtils = { checkErrors: checkErrors } function checkErrors (req, res, next, status_code) { if (status_code === undefined) status_code = 400 - var errors = req.validationErrors() + const errors = req.validationErrors() if (errors) { logger.warn('Incorrect request parameters', { path: req.originalUrl, err: errors }) diff --git a/server/middlewares/reqValidators/videos.js b/server/middlewares/reqValidators/videos.js index b0a6d0360..4057e72cd 100644 --- a/server/middlewares/reqValidators/videos.js +++ b/server/middlewares/reqValidators/videos.js @@ -1,11 +1,11 @@ 'use strict' -var checkErrors = require('./utils').checkErrors -var logger = require('../../helpers/logger') -var videos = require('../../lib/videos') -var Videos = require('../../models/videos') +const checkErrors = require('./utils').checkErrors +const logger = require('../../helpers/logger') +const videos = require('../../lib/videos') +const Videos = require('../../models/videos') -var reqValidatorsVideos = { +const reqValidatorsVideos = { videosAdd: videosAdd, videosGet: videosGet, videosRemove: videosRemove, diff --git a/server/middlewares/secure.js b/server/middlewares/secure.js index bfd28316a..9ecbf5df1 100644 --- a/server/middlewares/secure.js +++ b/server/middlewares/secure.js @@ -1,15 +1,15 @@ 'use strict' -var logger = require('../helpers/logger') -var peertubeCrypto = require('../helpers/peertubeCrypto') -var Pods = require('../models/pods') +const logger = require('../helpers/logger') +const peertubeCrypto = require('../helpers/peertubeCrypto') +const Pods = require('../models/pods') -var secureMiddleware = { +const secureMiddleware = { decryptBody: decryptBody } function decryptBody (req, res, next) { - var url = req.body.signature.url + const url = req.body.signature.url Pods.findByUrl(url, function (err, pod) { if (err) { logger.error('Cannot get signed url in decryptBody.', { error: err }) @@ -23,7 +23,7 @@ function decryptBody (req, res, next) { logger.debug('Decrypting body from %s.', url) - var signature_ok = peertubeCrypto.checkSignature(pod.publicKey, url, req.body.signature.signature) + const signature_ok = peertubeCrypto.checkSignature(pod.publicKey, url, req.body.signature.signature) if (signature_ok === true) { peertubeCrypto.decrypt(req.body.key, req.body.data, function (err, decrypted) { diff --git a/server/models/pods.js b/server/models/pods.js index 57ed20292..4e21001f5 100644 --- a/server/models/pods.js +++ b/server/models/pods.js @@ -1,22 +1,22 @@ 'use strict' -var mongoose = require('mongoose') +const mongoose = require('mongoose') -var constants = require('../initializers/constants') -var logger = require('../helpers/logger') +const constants = require('../initializers/constants') +const logger = require('../helpers/logger') // --------------------------------------------------------------------------- -var podsSchema = mongoose.Schema({ +const podsSchema = mongoose.Schema({ url: String, publicKey: String, score: { type: Number, max: constants.FRIEND_BASE_SCORE } }) -var PodsDB = mongoose.model('pods', podsSchema) +const PodsDB = mongoose.model('pods', podsSchema) // --------------------------------------------------------------------------- -var Pods = { +const Pods = { add: add, count: count, findByUrl: findByUrl, @@ -31,7 +31,7 @@ var Pods = { // TODO: check if the pod is not already a friend function add (data, callback) { if (!callback) callback = function () {} - var params = { + const params = { url: data.url, publicKey: data.publicKey, score: constants.FRIEND_BASE_SCORE diff --git a/server/models/poolRequests.js b/server/models/poolRequests.js index 970315597..28093a94c 100644 --- a/server/models/poolRequests.js +++ b/server/models/poolRequests.js @@ -1,21 +1,21 @@ 'use strict' -var mongoose = require('mongoose') +const mongoose = require('mongoose') -var logger = require('../helpers/logger') +const logger = require('../helpers/logger') // --------------------------------------------------------------------------- -var poolRequestsSchema = mongoose.Schema({ +const poolRequestsSchema = mongoose.Schema({ type: String, id: String, // Special id to find duplicates (video created we want to remove...) request: mongoose.Schema.Types.Mixed }) -var PoolRequestsDB = mongoose.model('poolRequests', poolRequestsSchema) +const PoolRequestsDB = mongoose.model('poolRequests', poolRequestsSchema) // --------------------------------------------------------------------------- -var PoolRequests = { +const PoolRequests = { create: create, findById: findById, list: list, diff --git a/server/models/videos.js b/server/models/videos.js index fd02ec9e1..0141cbb7f 100644 --- a/server/models/videos.js +++ b/server/models/videos.js @@ -1,33 +1,33 @@ 'use strict' -var async = require('async') -var config = require('config') -var dz = require('dezalgo') -var fs = require('fs') -var mongoose = require('mongoose') -var path = require('path') +const async = require('async') +const config = require('config') +const dz = require('dezalgo') +const fs = require('fs') +const mongoose = require('mongoose') +const path = require('path') -var logger = require('../helpers/logger') +const logger = require('../helpers/logger') -var http = config.get('webserver.https') === true ? 'https' : 'http' -var host = config.get('webserver.host') -var port = config.get('webserver.port') -var uploadDir = path.join(__dirname, '..', '..', config.get('storage.uploads')) +const http = config.get('webserver.https') === true ? 'https' : 'http' +const host = config.get('webserver.host') +const port = config.get('webserver.port') +const uploadDir = path.join(__dirname, '..', '..', config.get('storage.uploads')) // --------------------------------------------------------------------------- -var videosSchema = mongoose.Schema({ +const videosSchema = mongoose.Schema({ name: String, namePath: String, description: String, magnetUri: String, podUrl: String }) -var VideosDB = mongoose.model('videos', videosSchema) +const VideosDB = mongoose.model('videos', videosSchema) // --------------------------------------------------------------------------- -var Videos = { +const Videos = { add: add, addRemotes: addRemotes, get: get, @@ -43,7 +43,7 @@ var Videos = { function add (video, callback) { logger.info('Adding %s video to database.', video.name) - var params = video + const params = video params.podUrl = http + '://' + host + ':' + port VideosDB.create(params, function (err, video) { @@ -60,13 +60,13 @@ function add (video, callback) { function addRemotes (videos, callback) { if (!callback) callback = function () {} - var to_add = [] + const to_add = [] async.each(videos, function (video, callback_each) { callback_each = dz(callback_each) logger.debug('Add remote video from pod: %s', video.podUrl) - var params = { + const params = { name: video.name, namePath: null, description: video.description, @@ -159,7 +159,7 @@ function removeRemotesOfByMagnetUris (fromUrl, magnetUris, callback) { return callback(err) } - var to_remove = [] + const to_remove = [] async.each(videos, function (video, callback_async) { callback_async = dz(callback_async) diff --git a/server/tests/api/checkParams.js b/server/tests/api/checkParams.js index 01b620873..b31b0e894 100644 --- a/server/tests/api/checkParams.js +++ b/server/tests/api/checkParams.js @@ -1,27 +1,27 @@ 'use strict' -var async = require('async') -var chai = require('chai') -var expect = chai.expect -var pathUtils = require('path') -var request = require('supertest') +const async = require('async') +const chai = require('chai') +const expect = chai.expect +const pathUtils = require('path') +const request = require('supertest') -var utils = require('./utils') +const utils = require('./utils') describe('Test parameters validator', function () { - var app = null - var url = '' + let app = null + let url = '' function makePostRequest (path, fields, attach, done, fail) { - var status_code = 400 + let status_code = 400 if (fail !== undefined && fail === false) status_code = 200 - var req = request(url) + const req = request(url) .post(path) .set('Accept', 'application/json') Object.keys(fields).forEach(function (field) { - var value = fields[field] + const value = fields[field] req.field(field, value) }) @@ -29,7 +29,7 @@ describe('Test parameters validator', function () { } function makePostBodyRequest (path, fields, done, fail) { - var status_code = 400 + let status_code = 400 if (fail !== undefined && fail === false) status_code = 200 request(url) @@ -59,16 +59,16 @@ describe('Test parameters validator', function () { }) describe('Of the pods API', function () { - var path = '/api/v1/pods/' + const path = '/api/v1/pods/' describe('When adding a pod', function () { it('Should fail with nothing', function (done) { - var data = {} + const data = {} makePostBodyRequest(path, data, done) }) it('Should fail without public key', function (done) { - var data = { + const data = { data: { url: 'http://coucou.com' } @@ -77,7 +77,7 @@ describe('Test parameters validator', function () { }) it('Should fail without an url', function (done) { - var data = { + const data = { data: { publicKey: 'mysuperpublickey' } @@ -86,7 +86,7 @@ describe('Test parameters validator', function () { }) it('Should fail with an incorrect url', function (done) { - var data = { + const data = { data: { url: 'coucou.com', publicKey: 'mysuperpublickey' @@ -102,7 +102,7 @@ describe('Test parameters validator', function () { }) it('Should succeed with the correct parameters', function (done) { - var data = { + const data = { data: { url: 'http://coucou.com', publicKey: 'mysuperpublickey' @@ -114,7 +114,7 @@ describe('Test parameters validator', function () { }) describe('Of the videos API', function () { - var path = '/api/v1/videos/' + const path = '/api/v1/videos/' describe('When searching a video', function () { it('Should fail with nothing', function (done) { @@ -127,81 +127,81 @@ describe('Test parameters validator', function () { describe('When adding a video', function () { it('Should fail with nothing', function (done) { - var data = {} - var attach = {} + const data = {} + const attach = {} makePostRequest(path, data, attach, done) }) it('Should fail without name', function (done) { - var data = { + const data = { description: 'my super description' } - var attach = { + const attach = { 'input_video': pathUtils.join(__dirname, 'fixtures', 'video_short.webm') } makePostRequest(path, data, attach, done) }) it('Should fail with a long name', function (done) { - var data = { + const data = { name: 'My very very very very very very very very very very very very very very very very long name', description: 'my super description' } - var attach = { + const attach = { 'input_video': pathUtils.join(__dirname, 'fixtures', 'video_short.webm') } makePostRequest(path, data, attach, done) }) it('Should fail without description', function (done) { - var data = { + const data = { name: 'my super name' } - var attach = { + const attach = { 'input_video': pathUtils.join(__dirname, 'fixtures', 'video_short.webm') } makePostRequest(path, data, attach, done) }) it('Should fail with a long description', function (done) { - var data = { + const data = { name: 'my super name', description: 'my super description which is very very very very very very very very very very very very very very' + 'very very very very very very very very very very very very very very very very very very very very very' + 'very very very very very very very very very very very very very very very long' } - var attach = { + const attach = { 'input_video': pathUtils.join(__dirname, 'fixtures', 'video_short.webm') } makePostRequest(path, data, attach, done) }) it('Should fail without an input file', function (done) { - var data = { + const data = { name: 'my super name', description: 'my super description' } - var attach = {} + const attach = {} makePostRequest(path, data, attach, done) }) it('Should fail without an incorrect input file', function (done) { - var data = { + const data = { name: 'my super name', description: 'my super description' } - var attach = { + const attach = { 'input_video': pathUtils.join(__dirname, '..', 'fixtures', 'video_short_fake.webm') } makePostRequest(path, data, attach, done) }) it('Should succeed with the correct parameters', function (done) { - var data = { + const data = { name: 'my super name', description: 'my super description' } - var attach = { + const attach = { 'input_video': pathUtils.join(__dirname, 'fixtures', 'video_short.webm') } makePostRequest(path, data, attach, function () { diff --git a/server/tests/api/friendsAdvanced.js b/server/tests/api/friendsAdvanced.js index 9838d890f..6c4b7567f 100644 --- a/server/tests/api/friendsAdvanced.js +++ b/server/tests/api/friendsAdvanced.js @@ -1,14 +1,14 @@ 'use strict' -var async = require('async') -var chai = require('chai') -var expect = chai.expect +const async = require('async') +const chai = require('chai') +const expect = chai.expect -var utils = require('./utils') +const utils = require('./utils') describe('Test advanced friends', function () { - var apps = [] - var urls = [] + let apps = [] + let urls = [] function makeFriends (pod_number, callback) { return utils.makeFriends(urls[pod_number - 1], callback) @@ -23,9 +23,9 @@ describe('Test advanced friends', function () { } function uploadVideo (pod_number, callback) { - var name = 'my super video' - var description = 'my super description' - var fixture = 'video_short.webm' + const name = 'my super video' + const description = 'my super description' + const fixture = 'video_short.webm' return utils.uploadVideo(urls[pod_number - 1], name, description, fixture, callback) } @@ -171,9 +171,9 @@ describe('Test advanced friends', function () { if (err) throw err // Pod 4 should not be our friend - var result = res.body + const result = res.body expect(result.length).to.equal(3) - for (var pod of result) { + for (const pod of result) { expect(pod.url).not.equal(urls[3]) } diff --git a/server/tests/api/friendsBasic.js b/server/tests/api/friendsBasic.js index 328724936..62eac51ec 100644 --- a/server/tests/api/friendsBasic.js +++ b/server/tests/api/friendsBasic.js @@ -1,19 +1,19 @@ 'use strict' -var async = require('async') -var chai = require('chai') -var expect = chai.expect -var request = require('supertest') +const async = require('async') +const chai = require('chai') +const expect = chai.expect +const request = require('supertest') -var utils = require('./utils') +const utils = require('./utils') describe('Test basic friends', function () { - var apps = [] - var urls = [] + let apps = [] + let urls = [] function testMadeFriends (urls, url_to_test, callback) { - var friends = [] - for (var i = 0; i < urls.length; i++) { + const friends = [] + for (let i = 0; i < urls.length; i++) { if (urls[i] === url_to_test) continue friends.push(urls[i]) } @@ -21,13 +21,13 @@ describe('Test basic friends', function () { utils.getFriendsList(url_to_test, function (err, res) { if (err) throw err - var result = res.body - var result_urls = [ result[0].url, result[1].url ] + const result = res.body + const result_urls = [ 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]) - var error_string = 'Friends url do not correspond for ' + url_to_test + const error_string = 'Friends url do not correspond for ' + url_to_test expect(friends).to.contain(result_urls[0], error_string) expect(friends).to.contain(result_urls[1], error_string) callback() @@ -50,7 +50,7 @@ describe('Test basic friends', function () { utils.getFriendsList(url, function (err, res) { if (err) throw err - var result = res.body + const result = res.body expect(result).to.be.an('array') expect(result.length).to.equal(0) callback() @@ -61,7 +61,7 @@ describe('Test basic friends', function () { it('Should make friends', function (done) { this.timeout(10000) - var path = '/api/v1/pods/makefriends' + const path = '/api/v1/pods/makefriends' async.series([ // The second pod make friend with the third @@ -81,7 +81,7 @@ describe('Test basic friends', function () { utils.getFriendsList(urls[1], function (err, res) { if (err) throw err - var result = res.body + const result = res.body expect(result).to.be.an('array') expect(result.length).to.equal(1) expect(result[0].url).to.be.equal(urls[2]) @@ -94,7 +94,7 @@ describe('Test basic friends', function () { utils.getFriendsList(urls[2], function (err, res) { if (err) throw err - var result = res.body + const result = res.body expect(result).to.be.an('array') expect(result.length).to.equal(1) expect(result[0].url).to.be.equal(urls[1]) @@ -139,7 +139,7 @@ describe('Test basic friends', function () { utils.getFriendsList(urls[1], function (err, res) { if (err) throw err - var result = res.body + const result = res.body expect(result).to.be.an('array') expect(result.length).to.equal(0) @@ -152,7 +152,7 @@ describe('Test basic friends', function () { utils.getFriendsList(url, function (err, res) { if (err) throw err - var result = res.body + const result = res.body expect(result).to.be.an('array') expect(result.length).to.equal(1) expect(result[0].url).not.to.be.equal(urls[1]) diff --git a/server/tests/api/multiplePods.js b/server/tests/api/multiplePods.js index 9fdd0f308..e8b182622 100644 --- a/server/tests/api/multiplePods.js +++ b/server/tests/api/multiplePods.js @@ -1,18 +1,18 @@ 'use strict' -var async = require('async') -var chai = require('chai') -var expect = chai.expect -var pathUtils = require('path') +const async = require('async') +const chai = require('chai') +const expect = chai.expect +const pathUtils = require('path') -var utils = require('./utils') -var webtorrent = require(pathUtils.join(__dirname, '../../lib/webtorrent')) +const utils = require('./utils') +const webtorrent = require(pathUtils.join(__dirname, '../../lib/webtorrent')) webtorrent.silent = true describe('Test multiple pods', function () { - var apps = [] - var urls = [] - var to_remove = [] + let apps = [] + let urls = [] + const to_remove = [] before(function (done) { this.timeout(30000) @@ -73,15 +73,15 @@ describe('Test multiple pods', function () { if (err) throw err async.each(urls, function (url, callback) { - var base_magnet = null + let base_magnet = null utils.getVideosList(url, function (err, res) { if (err) throw err - var videos = res.body + const videos = res.body expect(videos).to.be.an('array') expect(videos.length).to.equal(1) - var video = videos[0] + const video = videos[0] expect(video.name).to.equal('my super name for pod 1') expect(video.description).to.equal('my super description for pod 1') expect(video.podUrl).to.equal('http://localhost:9001') @@ -116,15 +116,15 @@ describe('Test multiple pods', function () { if (err) throw err async.each(urls, function (url, callback) { - var base_magnet = null + let base_magnet = null utils.getVideosList(url, function (err, res) { if (err) throw err - var videos = res.body + const videos = res.body expect(videos).to.be.an('array') expect(videos.length).to.equal(2) - var video = videos[1] + const video = videos[1] expect(video.name).to.equal('my super name for pod 2') expect(video.description).to.equal('my super description for pod 2') expect(video.podUrl).to.equal('http://localhost:9002') @@ -160,16 +160,16 @@ describe('Test multiple pods', function () { function (err) { if (err) throw err - var base_magnet = null + let base_magnet = null // All pods should have this video async.each(urls, function (url, callback) { utils.getVideosList(url, function (err, res) { if (err) throw err - var videos = res.body + const videos = res.body expect(videos).to.be.an('array') expect(videos.length).to.equal(4) - var video = videos[2] + let video = videos[2] expect(video.name).to.equal('my super name for pod 3') expect(video.description).to.equal('my super description for pod 3') expect(video.podUrl).to.equal('http://localhost:9003') @@ -204,7 +204,7 @@ describe('Test multiple pods', function () { utils.getVideosList(urls[2], function (err, res) { if (err) throw err - var video = res.body[0] + const video = res.body[0] to_remove.push(res.body[2]._id) to_remove.push(res.body[3]._id) @@ -225,7 +225,7 @@ describe('Test multiple pods', function () { utils.getVideosList(urls[0], function (err, res) { if (err) throw err - var video = res.body[1] + const video = res.body[1] webtorrent.add(video.magnetUri, function (torrent) { expect(torrent.files).to.exist @@ -244,7 +244,7 @@ describe('Test multiple pods', function () { utils.getVideosList(urls[1], function (err, res) { if (err) throw err - var video = res.body[2] + const video = res.body[2] webtorrent.add(video.magnetUri, function (torrent) { expect(torrent.files).to.exist @@ -263,7 +263,7 @@ describe('Test multiple pods', function () { utils.getVideosList(urls[0], function (err, res) { if (err) throw err - var video = res.body[3] + const video = res.body[3] webtorrent.add(video.magnetUri, function (torrent) { expect(torrent.files).to.exist @@ -297,7 +297,7 @@ describe('Test multiple pods', function () { utils.getVideosList(url, function (err, res) { if (err) throw err - var videos = res.body + const videos = res.body expect(videos).to.be.an('array') expect(videos.length).to.equal(2) expect(videos[0]._id).not.to.equal(videos[1]._id) diff --git a/server/tests/api/singlePod.js b/server/tests/api/singlePod.js index d572aacf6..14f893f13 100644 --- a/server/tests/api/singlePod.js +++ b/server/tests/api/singlePod.js @@ -1,20 +1,20 @@ 'use strict' -var async = require('async') -var chai = require('chai') -var expect = chai.expect -var fs = require('fs') -var pathUtils = require('path') +const async = require('async') +const chai = require('chai') +const expect = chai.expect +const fs = require('fs') +const pathUtils = require('path') -var webtorrent = require(pathUtils.join(__dirname, '../../lib/webtorrent')) +const webtorrent = require(pathUtils.join(__dirname, '../../lib/webtorrent')) webtorrent.silent = true -var utils = require('./utils') +const utils = require('./utils') describe('Test a single pod', function () { - var app = null - var url = '' - var video_id = -1 + let app = null + let url = '' + let video_id = -1 before(function (done) { this.timeout(20000) @@ -62,7 +62,7 @@ describe('Test a single pod', function () { expect(res.body).to.be.an('array') expect(res.body.length).to.equal(1) - var video = res.body[0] + const video = res.body[0] expect(video.name).to.equal('my super name') expect(video.description).to.equal('my super description') expect(video.podUrl).to.equal('http://localhost:9001') @@ -87,7 +87,7 @@ describe('Test a single pod', function () { expect(res.body).to.be.an('array') expect(res.body.length).to.equal(1) - var video = res.body[0] + const video = res.body[0] expect(video.name).to.equal('my super name') expect(video.description).to.equal('my super description') expect(video.podUrl).to.equal('http://localhost:9001') diff --git a/server/tests/api/utils.js b/server/tests/api/utils.js index 60c3c8d4e..05142085f 100644 --- a/server/tests/api/utils.js +++ b/server/tests/api/utils.js @@ -1,12 +1,12 @@ 'use strict' -var child_process = require('child_process') -var exec = child_process.exec -var fork = child_process.fork -var pathUtils = require('path') -var request = require('supertest') +const child_process = require('child_process') +const exec = child_process.exec +const fork = child_process.fork +const pathUtils = require('path') +const request = require('supertest') -var testUtils = { +const testUtils = { flushTests: flushTests, getFriendsList: getFriendsList, getVideosList: getVideosList, @@ -26,7 +26,7 @@ function flushTests (callback) { } function getFriendsList (url, end) { - var path = '/api/v1/pods/' + const path = '/api/v1/pods/' request(url) .get(path) @@ -37,7 +37,7 @@ function getFriendsList (url, end) { } function getVideosList (url, end) { - var path = '/api/v1/videos' + const path = '/api/v1/videos' request(url) .get(path) @@ -53,7 +53,7 @@ function makeFriends (url, expected_status, callback) { expected_status = 204 } - var path = '/api/v1/pods/makefriends' + const path = '/api/v1/pods/makefriends' // The first pod make friend with the third request(url) @@ -69,7 +69,7 @@ function makeFriends (url, expected_status, callback) { } function quitFriends (url, callback) { - var path = '/api/v1/pods/quitfriends' + const path = '/api/v1/pods/quitfriends' // The first pod make friend with the third request(url) @@ -85,7 +85,7 @@ function quitFriends (url, callback) { } function removeVideo (url, id, end) { - var path = '/api/v1/videos' + const path = '/api/v1/videos' request(url) .delete(path + '/' + id) @@ -95,9 +95,9 @@ function removeVideo (url, id, end) { } function flushAndRunMultipleServers (total_servers, serversRun) { - var apps = [] - var urls = [] - var i = 0 + let apps = [] + let urls = [] + let i = 0 function anotherServerDone (number, app, url) { apps[number - 1] = app @@ -109,41 +109,39 @@ function flushAndRunMultipleServers (total_servers, serversRun) { } flushTests(function () { - for (var j = 1; j <= total_servers; j++) { - (function (k) { // TODO: ES6 with let - // For the virtual buffer - setTimeout(function () { - runServer(k, function (app, url) { - anotherServerDone(k, app, url) - }) - }, 1000 * k) - })(j) + for (let j = 1; j <= total_servers; j++) { + // For the virtual buffer + setTimeout(function () { + runServer(j, function (app, url) { + anotherServerDone(j, app, url) + }) + }, 1000 * j) } }) } function runServer (number, callback) { - var port = 9000 + number - var server_run_string = { + const port = 9000 + number + const server_run_string = { 'Connected to mongodb': false, 'Server listening on port': false } // Share the environment - var env = Object.create(process.env) + const env = Object.create(process.env) env.NODE_ENV = 'test' env.NODE_APP_INSTANCE = number - var options = { + const options = { silent: true, env: env, detached: true } - var app = fork(pathUtils.join(__dirname, '../../../server.js'), [], options) + const app = fork(pathUtils.join(__dirname, '../../../server.js'), [], options) app.stdout.on('data', function onStdout (data) { - var dont_continue = false + let dont_continue = false // Check if all required sentences are here - for (var key of Object.keys(server_run_string)) { + 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 } @@ -157,7 +155,7 @@ function runServer (number, callback) { } function searchVideo (url, search, end) { - var path = '/api/v1/videos' + const path = '/api/v1/videos' request(url) .get(path + '/search/' + search) @@ -168,7 +166,7 @@ function searchVideo (url, search, end) { } function uploadVideo (url, name, description, fixture, end) { - var path = '/api/v1/videos' + const path = '/api/v1/videos' request(url) .post(path) diff --git a/server/tests/index.js b/server/tests/index.js index ccebbfe51..cb177b87c 100644 --- a/server/tests/index.js +++ b/server/tests/index.js @@ -1,6 +1,4 @@ -;(function () { - 'use strict' +'use strict' - // Order of the tests we want to execute - require('./api/') -})() +// Order of the tests we want to execute +require('./api/') -- cgit v1.2.3