Switch entirely to fat arrow functions

This commit is contained in:
John Furrow
2016-03-19 12:46:11 +01:00
parent 14ed9bb1f5
commit e77dfac3ae
33 changed files with 145 additions and 159 deletions

View File

@@ -4,7 +4,7 @@ import AppDispatcher from '../dispatcher/AppDispatcher';
import ActionTypes from '../constants/ActionTypes'; import ActionTypes from '../constants/ActionTypes';
const ClientActions = { const ClientActions = {
fetchTransferData: function() { fetchTransferData: () => {
return axios.get('/client/stats') return axios.get('/client/stats')
.then((json = {}) => { .then((json = {}) => {
return json.data; return json.data;
@@ -27,7 +27,7 @@ const ClientActions = {
}); });
}, },
fetchTransferHistory: function(opts) { fetchTransferHistory: (opts) => {
return axios.get('/client/history', { return axios.get('/client/history', {
params: opts params: opts
}) })
@@ -48,7 +48,7 @@ const ClientActions = {
}) })
}, },
setThrottle: function(direction, throttle) { setThrottle: (direction, throttle) => {
return axios.put('/client/settings/speed-limits', { return axios.put('/client/settings/speed-limits', {
direction, direction,
throttle throttle

View File

@@ -4,11 +4,11 @@ import AppDispatcher from '../dispatcher/AppDispatcher';
import ActionTypes from '../constants/ActionTypes'; import ActionTypes from '../constants/ActionTypes';
const TorrentActions = { const TorrentActions = {
addTorrentsByUrls: function(urls, destination) { addTorrentsByUrls: (urls, destination) => {
axios.post('/ui/torrent-location', { axios.post('/ui/torrent-location', {
destination destination
}) })
.catch(function (error) { .catch((error) => {
console.log(error); console.log(error);
}); });
return axios.post('/client/add', { return axios.post('/client/add', {
@@ -36,11 +36,11 @@ const TorrentActions = {
}); });
}, },
addTorrentsByFiles: function(filesData, destination) { addTorrentsByFiles: (filesData, destination) => {
axios.post('/ui/torrent-location', { axios.post('/ui/torrent-location', {
destination destination
}) })
.catch(function (error) { .catch((error) => {
console.log(error); console.log(error);
}); });
return axios.post('/client/add-files', filesData) return axios.post('/client/add-files', filesData)
@@ -65,7 +65,7 @@ const TorrentActions = {
}); });
}, },
deleteTorrents: function(hash) { deleteTorrents: (hash) => {
return axios.post('/client/torrents/delete', {hash}) return axios.post('/client/torrents/delete', {hash})
.then((json = {}) => { .then((json = {}) => {
return json.data; return json.data;
@@ -84,7 +84,7 @@ const TorrentActions = {
}); });
}, },
fetchLatestTorrentLocation: function () { fetchLatestTorrentLocation: () => {
return axios.get('/ui/torrent-location') return axios.get('/ui/torrent-location')
.then((json = {}) => { .then((json = {}) => {
return json.data; return json.data;
@@ -103,7 +103,7 @@ const TorrentActions = {
}); });
}, },
fetchTorrents: function () { fetchTorrents: () => {
return axios.get('/client/torrents') return axios.get('/client/torrents')
.then((json = {}) => { .then((json = {}) => {
return json.data; return json.data;
@@ -126,7 +126,7 @@ const TorrentActions = {
}); });
}, },
fetchTorrentDetails: function(hash) { fetchTorrentDetails: (hash) => {
return axios.post('/client/torrent-details', { return axios.post('/client/torrent-details', {
hash hash
}) })
@@ -152,7 +152,7 @@ const TorrentActions = {
}); });
}, },
fetchTorrentStatusCount: function() { fetchTorrentStatusCount: () => {
return axios.get('/client/torrents/status-count') return axios.get('/client/torrents/status-count')
.then((json = {}) => { .then((json = {}) => {
return json.data; return json.data;
@@ -171,7 +171,7 @@ const TorrentActions = {
}); });
}, },
fetchTorrentTrackerCount: function() { fetchTorrentTrackerCount: () => {
return axios.get('/client/torrents/tracker-count') return axios.get('/client/torrents/tracker-count')
.then((json = {}) => { .then((json = {}) => {
return json.data; return json.data;
@@ -190,7 +190,7 @@ const TorrentActions = {
}); });
}, },
moveTorrents: function(hashes, options) { moveTorrents: (hashes, options) => {
let {destination, filenames, sources, moveFiles} = options; let {destination, filenames, sources, moveFiles} = options;
return axios.post('/client/torrents/move', return axios.post('/client/torrents/move',
@@ -212,7 +212,7 @@ const TorrentActions = {
}); });
}, },
pauseTorrents: function(hashes) { pauseTorrents: (hashes) => {
return axios.post('/client/pause', { return axios.post('/client/pause', {
hashes hashes
}) })
@@ -237,7 +237,7 @@ const TorrentActions = {
}); });
}, },
startTorrents: function(hashes) { startTorrents: (hashes) => {
return axios.post('/client/start', { return axios.post('/client/start', {
hashes hashes
}) })
@@ -262,7 +262,7 @@ const TorrentActions = {
}); });
}, },
stopTorrents: function(hashes) { stopTorrents: (hashes) => {
return axios.post('/client/stop', { return axios.post('/client/stop', {
hashes hashes
}) })
@@ -287,7 +287,7 @@ const TorrentActions = {
}); });
}, },
setPriority: function(hash, priority) { setPriority: (hash, priority) => {
return axios.patch(`/client/torrents/${hash}/priority`, { return axios.patch(`/client/torrents/${hash}/priority`, {
hash, hash,
priority priority
@@ -309,7 +309,7 @@ const TorrentActions = {
}); });
}, },
setFilePriority: function(hash, fileIndices, priority) { setFilePriority: (hash, fileIndices, priority) => {
return axios.patch(`/client/torrents/${hash}/file-priority`, { return axios.patch(`/client/torrents/${hash}/file-priority`, {
hash, hash,
fileIndices, fileIndices,

View File

@@ -5,35 +5,35 @@ import ActionTypes from '../constants/ActionTypes';
import TorrentStore from '../stores/TorrentStore'; import TorrentStore from '../stores/TorrentStore';
const UIActions = { const UIActions = {
displayContextMenu: function(data) { displayContextMenu: (data) => {
AppDispatcher.dispatchUIAction({ AppDispatcher.dispatchUIAction({
type: ActionTypes.UI_DISPLAY_CONTEXT_MENU, type: ActionTypes.UI_DISPLAY_CONTEXT_MENU,
data data
}); });
}, },
displayModal: function(data) { displayModal: (data) => {
AppDispatcher.dispatchUIAction({ AppDispatcher.dispatchUIAction({
type: ActionTypes.UI_DISPLAY_MODAL, type: ActionTypes.UI_DISPLAY_MODAL,
data data
}); });
}, },
dismissContextMenu: function() { dismissContextMenu: () => {
AppDispatcher.dispatchUIAction({ AppDispatcher.dispatchUIAction({
type: ActionTypes.UI_DISPLAY_CONTEXT_MENU, type: ActionTypes.UI_DISPLAY_CONTEXT_MENU,
data: null data: null
}); });
}, },
dismissModal: function() { dismissModal: () => {
AppDispatcher.dispatchUIAction({ AppDispatcher.dispatchUIAction({
type: ActionTypes.UI_DISPLAY_MODAL, type: ActionTypes.UI_DISPLAY_MODAL,
data: null data: null
}); });
}, },
fetchSortProps: function() { fetchSortProps: () => {
return axios.get('/ui/sort-props') return axios.get('/ui/sort-props')
.then((json = {}) => { .then((json = {}) => {
return json.data; return json.data;
@@ -52,45 +52,45 @@ const UIActions = {
}); });
}, },
handleDetailsClick: function(data) { handleDetailsClick: (data) => {
AppDispatcher.dispatchUIAction({ AppDispatcher.dispatchUIAction({
type: ActionTypes.UI_CLICK_TORRENT_DETAILS, type: ActionTypes.UI_CLICK_TORRENT_DETAILS,
data data
}); });
}, },
handleTorrentClick: function(data) { handleTorrentClick: (data) => {
AppDispatcher.dispatchUIAction({ AppDispatcher.dispatchUIAction({
type: ActionTypes.UI_CLICK_TORRENT, type: ActionTypes.UI_CLICK_TORRENT,
data data
}); });
}, },
setTorrentStatusFilter: function(data) { setTorrentStatusFilter: (data) => {
AppDispatcher.dispatchUIAction({ AppDispatcher.dispatchUIAction({
type: ActionTypes.UI_SET_TORRENT_STATUS_FILTER, type: ActionTypes.UI_SET_TORRENT_STATUS_FILTER,
data data
}); });
}, },
setTorrentTrackerFilter: function(data) { setTorrentTrackerFilter: (data) => {
AppDispatcher.dispatchUIAction({ AppDispatcher.dispatchUIAction({
type: ActionTypes.UI_SET_TORRENT_TRACKER_FILTER, type: ActionTypes.UI_SET_TORRENT_TRACKER_FILTER,
data data
}); });
}, },
setTorrentsSearchFilter: function(data) { setTorrentsSearchFilter: (data) => {
AppDispatcher.dispatchUIAction({ AppDispatcher.dispatchUIAction({
type: ActionTypes.UI_SET_TORRENT_SEARCH_FILTER, type: ActionTypes.UI_SET_TORRENT_SEARCH_FILTER,
data data
}); });
}, },
setTorrentsSort: function(data) { setTorrentsSort: (data) => {
axios axios
.post('/ui/sort-props', data) .post('/ui/sort-props', data)
.catch(function (error) { .catch(() => {
console.log(error); console.log(error);
}); });

View File

@@ -13,7 +13,7 @@ import UIActions from './actions/UIActions';
class FloodApp extends React.Component { class FloodApp extends React.Component {
componentDidMount() { componentDidMount() {
TorrentActions.fetchLatestTorrentLocation(); TorrentActions.fetchLatestTorrentLocation();
window.addEventListener('click', function () { window.addEventListener('click', () => {
UIActions.dismissContextMenu(); UIActions.dismissContextMenu();
}); });
} }

View File

@@ -81,7 +81,7 @@ export default class Dropdown extends React.Component {
} }
getDropdownMenu(items) { getDropdownMenu(items) {
let dropdownLists = items.map(function(itemList, index) { let dropdownLists = items.map((itemList, index) => {
return ( return (
<div className="dropdown__list" key={index}> <div className="dropdown__list" key={index}>
{this.getDropdownMenuItems(itemList)} {this.getDropdownMenuItems(itemList)}
@@ -102,7 +102,7 @@ export default class Dropdown extends React.Component {
} }
getDropdownMenuItems(listItems) { getDropdownMenuItems(listItems) {
return listItems.map(function(property, index) { return listItems.map((property, index) => {
let classes = classnames('dropdown__item menu__item', property.className, { let classes = classnames('dropdown__item menu__item', property.className, {
'is-selectable': property.selectable !== false, 'is-selectable': property.selectable !== false,
'is-selected': property.selected 'is-selected': property.selected

View File

@@ -136,7 +136,7 @@ export default class AddTorrents extends React.Component {
let fileData = new FormData(); let fileData = new FormData();
this.state.files.forEach(function (file) { this.state.files.forEach((file) => {
fileData.append('torrents', file); fileData.append('torrents', file);
}); });

View File

@@ -130,16 +130,16 @@ export default class StatusFilters extends React.Component {
let totalStatusCount = 0; let totalStatusCount = 0;
let torrents = TorrentStore.getAllTorrents(); let torrents = TorrentStore.getAllTorrents();
Object.keys(statusCount).forEach(function(key) { Object.keys(statusCount).forEach((key) => {
statusCount[key] = 0; statusCount[key] = 0;
}); });
Object.keys(torrents).forEach(function(hash) { Object.keys(torrents).forEach((hash) => {
let torrent = torrents[hash]; let torrent = torrents[hash];
if (torrent.trackers.indexOf(trackerFilter) > -1) { if (torrent.trackers.indexOf(trackerFilter) > -1) {
totalStatusCount++; totalStatusCount++;
torrent.status.forEach(function (status) { torrent.status.forEach((status) => {
statusCount[propsMap.serverStatus[status]]++; statusCount[propsMap.serverStatus[status]]++;
}); });
} }

View File

@@ -95,16 +95,16 @@ export default class TrackerFilters extends React.Component {
let torrentCount = 0; let torrentCount = 0;
let torrents = TorrentStore.getAllTorrents(); let torrents = TorrentStore.getAllTorrents();
Object.keys(trackerCount).forEach(function(key) { Object.keys(trackerCount).forEach((key) => {
trackerCount[key] = 0; trackerCount[key] = 0;
}); });
Object.keys(torrents).forEach(function(hash) { Object.keys(torrents).forEach((hash) => {
let torrent = torrents[hash]; let torrent = torrents[hash];
if (torrent.status.indexOf(propsMap.clientStatus[statusFilter]) > -1) { if (torrent.status.indexOf(propsMap.clientStatus[statusFilter]) > -1) {
torrentCount++; torrentCount++;
torrent.trackers.forEach(function (tracker) { torrent.trackers.forEach((tracker) => {
trackerCount[tracker]++; trackerCount[tracker]++;
}); });
} }

View File

@@ -11,7 +11,7 @@ export default class TorrentPeers extends React.Component {
let peers = this.props.peers; let peers = this.props.peers;
if (peers) { if (peers) {
let peerList = peers.map(function(peer, index) { let peerList = peers.map((peer, index) => {
let downloadRate = format.data(peer.downloadRate, '/s'); let downloadRate = format.data(peer.downloadRate, '/s');
let uploadRate = format.data(peer.uploadRate, '/s'); let uploadRate = format.data(peer.uploadRate, '/s');
return ( return (

View File

@@ -18,10 +18,10 @@ export default class LineChart extends React.Component {
.linear() .linear()
.range([0, width]) .range([0, width])
.domain([ .domain([
d3.min(transferData, function(dataPoint, index) { d3.min(transferData, (dataPoint, index) => {
return index; return index;
}), }),
d3.max(transferData, function(dataPoint, index) { d3.max(transferData, (dataPoint, index) => {
return index; return index;
}) })
]); ]);
@@ -32,7 +32,7 @@ export default class LineChart extends React.Component {
.range([height - margin.top, margin.bottom]) .range([height - margin.top, margin.bottom])
.domain([ .domain([
0, 0,
d3.max(transferData, function(dataPoint, index) { d3.max(transferData, (dataPoint, index) => {
if (dataPoint >= transferLimit[index]) { if (dataPoint >= transferLimit[index]) {
return dataPoint; return dataPoint;
} else { } else {
@@ -41,14 +41,14 @@ export default class LineChart extends React.Component {
}) })
]); ]);
let lineFunc = function (interpolation) { let lineFunc = (interpolation) => {
return d3 return d3
.svg .svg
.line() .line()
.x(function(dataPoint, index) { .x((dataPoint, index) => {
return xRange(index); return xRange(index);
}) })
.y(function(dataPoint) { .y((dataPoint) => {
return yRange(dataPoint); return yRange(dataPoint);
}) })
.interpolate(interpolation); .interpolate(interpolation);
@@ -57,11 +57,11 @@ export default class LineChart extends React.Component {
let areaFunc = d3 let areaFunc = d3
.svg .svg
.area() .area()
.x(function(dataPoint, index) { .x((dataPoint, index) => {
return xRange(index); return xRange(index);
}) })
.y0(height) .y0(height)
.y1(function(dataPoint) { .y1((dataPoint) => {
return yRange(dataPoint); return yRange(dataPoint);
}) })
.interpolate('basis'); .interpolate('basis');

View File

@@ -7,13 +7,13 @@ export function filterTorrents(torrentList, opts) {
if (filter !== 'all') { if (filter !== 'all') {
if (type === 'status') { if (type === 'status') {
let statusFilter = statusMap[filter]; let statusFilter = statusMap[filter];
return torrentList.filter(function(torrent) { return torrentList.filter((torrent) => {
if (torrent.status.indexOf(statusFilter) > -1) { if (torrent.status.indexOf(statusFilter) > -1) {
return torrent; return torrent;
} }
}); });
} else if (type === 'tracker') { } else if (type === 'tracker') {
return torrentList.filter(function(torrent) { return torrentList.filter((torrent) => {
if (torrent.trackers.indexOf(filter) > -1) { if (torrent.trackers.indexOf(filter) > -1) {
return torrent; return torrent;
} }

View File

@@ -1,7 +1,7 @@
import React from 'react'; import React from 'react';
const format = { const format = {
eta: function(eta) { eta: (eta) => {
if (eta === 'Infinity') { if (eta === 'Infinity') {
return '∞'; return '∞';
} else if (eta.years > 0) { } else if (eta.years > 0) {
@@ -68,7 +68,7 @@ const format = {
} }
}, },
data: function(bytes, extraUnits, precision = 2) { data: (bytes, extraUnits, precision = 2) => {
let kilobyte = 1024, let kilobyte = 1024,
megabyte = kilobyte * 1024, megabyte = kilobyte * 1024,
gigabyte = megabyte * 1024, gigabyte = megabyte * 1024,
@@ -106,7 +106,7 @@ const format = {
}; };
}, },
ratio: function(ratio) { ratio: (ratio) => {
ratio = ratio / 1000; ratio = ratio / 1000;
let precision = 1; let precision = 1;

View File

@@ -8,7 +8,7 @@ export function selectTorrents(options) {
let lastHashIndex; let lastHashIndex;
// get the index of the last selected torrent. // get the index of the last selected torrent.
options.torrentList.some(function(torrent, index) { options.torrentList.some((torrent, index) => {
if (torrent.hash === lastHash) { if (torrent.hash === lastHash) {
lastHashIndex = index; lastHashIndex = index;
return true; return true;
@@ -16,7 +16,7 @@ export function selectTorrents(options) {
}); });
// get the index of the newly selected torrent. // get the index of the newly selected torrent.
options.torrentList.some(function(torrent, index) { options.torrentList.some((torrent, index) => {
if (torrent.hash === options.hash) { if (torrent.hash === options.hash) {
currentHashIndex = index; currentHashIndex = index;
return true; return true;

View File

@@ -7,7 +7,7 @@ export function sortTorrents(torrentsHash, sortBy) {
let direction = sortBy.direction; let direction = sortBy.direction;
let property = sortBy.property; let property = sortBy.property;
torrents.sort(function(a, b) { torrents.sort((a, b) => {
let valA = a[property]; let valA = a[property];
let valB = b[property]; let valB = b[property];

View File

@@ -5,7 +5,7 @@ import propsMap from '../../../../shared/constants/propsMap';
export function torrentStatusClasses(torrent, ...classes) { export function torrentStatusClasses(torrent, ...classes) {
let additionalClasses = []; let additionalClasses = [];
classes.forEach(function (className) { classes.forEach((className) => {
if (className) { if (className) {
additionalClasses.push(className); additionalClasses.push(className);
} }

View File

@@ -2,7 +2,6 @@
var autoprefixer = require('gulp-autoprefixer'); var autoprefixer = require('gulp-autoprefixer');
var browserSync = require('browser-sync'); var browserSync = require('browser-sync');
var cssnano = require('gulp-cssnano'); var cssnano = require('gulp-cssnano');
var eslint = require('gulp-eslint');
var gulp = require('gulp'); var gulp = require('gulp');
var gulpif = require('gulp-if'); var gulpif = require('gulp-if');
var gutil = require('gulp-util'); var gutil = require('gulp-util');
@@ -73,7 +72,7 @@ var webpackConfig = {
watch: webpackWatch watch: webpackWatch
}; };
gulp.task('browsersync', function () { gulp.task('browsersync', () => {
browserSync.init({ browserSync.init({
online: true, online: true,
open: false, open: false,
@@ -82,24 +81,15 @@ gulp.task('browsersync', function () {
}); });
}); });
// Create a function so we can use it inside of webpack's watch function. gulp.task('images', () => {
function eslintFn () {
return gulp.src([dirs.js + '/**/*.?(js|jsx)'])
.pipe(eslint())
.pipe(eslint.formatEach('stylish', process.stderr));
};
gulp.task('eslint', eslintFn);
gulp.task('images', function () {
return gulp.src(dirs.src + '/' + dirs.img + '/**/*.*') return gulp.src(dirs.src + '/' + dirs.img + '/**/*.*')
.pipe(gulp.dest(dirs.dist + '/' + dirs.imgDist)); .pipe(gulp.dest(dirs.dist + '/' + dirs.imgDist));
}); });
gulp.task('sass', function () { gulp.task('sass', () => {
return gulp.src(dirs.src + '/' + dirs.styles + '/' + files.mainStyles + '.scss') return gulp.src(dirs.src + '/' + dirs.styles + '/' + files.mainStyles + '.scss')
.pipe(gulpif(development, sourcemaps.init())) .pipe(gulpif(development, sourcemaps.init()))
.pipe(sass().on('error', function(error) { .pipe(sass().on('error', () => {
gutil.log( gutil.log(
gutil.colors.green('Sass Error!\n'), gutil.colors.green('Sass Error!\n'),
'\n', '\n',
@@ -114,13 +104,13 @@ gulp.task('sass', function () {
.pipe(browserSync.stream({match: "**/*.css"})); .pipe(browserSync.stream({match: "**/*.css"}));
}); });
gulp.task('minify-css', ['sass'], function () { gulp.task('minify-css', ['sass'], () => {
return gulp.src(dirs.dist + '/' + dirs.stylesDist + '/' + files.mainStylesDist + '.css') return gulp.src(dirs.dist + '/' + dirs.stylesDist + '/' + files.mainStylesDist + '.css')
.pipe(cssnano()) .pipe(cssnano())
.pipe(gulp.dest(dirs.dist + '/' + dirs.stylesDist)); .pipe(gulp.dest(dirs.dist + '/' + dirs.stylesDist));
}); });
gulp.task('minify-js', function () { gulp.task('minify-js', () => {
return gulp.src(dirs.dist + '/' + dirs.jsDist + '/' + files.mainJs + '.js') return gulp.src(dirs.dist + '/' + dirs.jsDist + '/' + files.mainJs + '.js')
.pipe(uglify({ .pipe(uglify({
mangle: true, mangle: true,
@@ -129,21 +119,21 @@ gulp.task('minify-js', function () {
.pipe(gulp.dest(dirs.dist + '/' + dirs.jsDist)); .pipe(gulp.dest(dirs.dist + '/' + dirs.jsDist));
}); });
gulp.task('reload', function () { gulp.task('reload', () => {
if (development) { if (development) {
browserSync.reload(); browserSync.reload();
} }
}); });
gulp.task('watch', function () { gulp.task('watch', () => {
gulp.watch(dirs.src + '/' + dirs.styles + '/**/*.scss', ['sass']); gulp.watch(dirs.src + '/' + dirs.styles + '/**/*.scss', ['sass']);
gulp.watch(dirs.src + '/' + dirs.img + '/**/*', ['images']); gulp.watch(dirs.src + '/' + dirs.img + '/**/*', ['images']);
}); });
gulp.task('webpack', function (callback) { gulp.task('webpack', (callback) => {
var isFirstRun = true; var isFirstRun = true;
webpack(webpackConfig, function (err, stats) { webpack(webpackConfig, (err, stats) => {
if (err) { if (err) {
throw new gutil.PluginError('webpack', err); throw new gutil.PluginError('webpack', err);
} }
@@ -157,12 +147,9 @@ gulp.task('webpack', function (callback) {
})); }));
if (isFirstRun) { if (isFirstRun) {
// This runs on initial gulp webpack load.
isFirstRun = false; isFirstRun = false;
callback(); callback();
} else { } else {
// This runs after webpack's internal watch rebuild.
// eslintFn();
if (development) { if (development) {
browserSync.reload(); browserSync.reload();
} }

View File

@@ -55,7 +55,6 @@
"gulp": "^3.9.0", "gulp": "^3.9.0",
"gulp-autoprefixer": "^3.0.2", "gulp-autoprefixer": "^3.0.2",
"gulp-cssnano": "^2.1.1", "gulp-cssnano": "^2.1.1",
"gulp-eslint": "^1.0.0",
"gulp-if": "^2.0.0", "gulp-if": "^2.0.0",
"gulp-sass": "^2.0.4", "gulp-sass": "^2.0.4",
"gulp-sourcemaps": "^1.6.0", "gulp-sourcemaps": "^1.6.0",

View File

@@ -23,11 +23,11 @@ app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser()); app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'assets'))); app.use(express.static(path.join(__dirname, 'assets')));
app.use(function(req, res, next) { app.use((req, res, next) => {
req.socket.on("error", function(err) { req.socket.on("error", (err) => {
console.log(err); console.log(err);
}); });
res.socket.on("error", function(err) { res.socket.on("error", (err) => {
console.log(err); console.log(err);
}); });
next(); next();
@@ -38,7 +38,7 @@ app.use('/client', clientRoutes);
app.use('/ui', uiRoutes); app.use('/ui', uiRoutes);
// catch 404 and forward to error handler // catch 404 and forward to error handler
app.use(function(req, res, next) { app.use((req, res, next) => {
var err = new Error('Not Found'); var err = new Error('Not Found');
err.status = 404; err.status = 404;
next(err); next(err);
@@ -49,7 +49,7 @@ app.use(function(req, res, next) {
// development error handler // development error handler
// will print stacktrace // will print stacktrace
if (app.get('env') === 'development') { if (app.get('env') === 'development') {
app.use(function(err, req, res, next) { app.use((err, req, res, next) => {
res.status(err.status || 500); res.status(err.status || 500);
res.render('error', { res.render('error', {
message: err.message, message: err.message,
@@ -60,7 +60,7 @@ if (app.get('env') === 'development') {
// production error handler // production error handler
// no stacktraces leaked to user // no stacktraces leaked to user
app.use(function(err, req, res, next) { app.use((err, req, res, next) => {
res.status(err.status || 500); res.status(err.status || 500);
res.render('error', { res.render('error', {
message: err.message, message: err.message,

File diff suppressed because one or more lines are too long

View File

@@ -185,7 +185,7 @@ class ClientRequest {
let sourcePaths = this.getEnsuredArray(options.sourcePaths); let sourcePaths = this.getEnsuredArray(options.sourcePaths);
sourcePaths.forEach((source, index) => { sourcePaths.forEach((source, index) => {
let callback = function () {}; let callback = () => {};
let destination = `${destinationPath}${path.sep}${filenames[index]}`; let destination = `${destinationPath}${path.sep}${filenames[index]}`;
let isLastRequest = index + 1 === sourcePaths.length; let isLastRequest = index + 1 === sourcePaths.length;

View File

@@ -98,7 +98,7 @@ class HistoryEra {
this.db.find({ts: {$gte: minTimestamp}}) this.db.find({ts: {$gte: minTimestamp}})
.sort({ts: 1}) .sort({ts: 1})
.exec(function (err, docs) { .exec((err, docs) => {
if (err) { if (err) {
callback(null, err); callback(null, err);
return; return;
@@ -112,7 +112,7 @@ class HistoryEra {
hasRequiredFields(opts) { hasRequiredFields(opts) {
let requirementsMet = true; let requirementsMet = true;
REQUIRED_FIELDS.forEach(function (field) { REQUIRED_FIELDS.forEach((field) => {
if (opts[field] == null) { if (opts[field] == null) {
console.error(`HistoryEra requires ${field}`); console.error(`HistoryEra requires ${field}`);
requirementsMet = false; requirementsMet = false;
@@ -145,7 +145,7 @@ class HistoryEra {
let lastUpdate = 0; let lastUpdate = 0;
db.find({}, (err, docs) => { db.find({}, (err, docs) => {
docs.forEach(function (doc) { docs.forEach((doc) => {
if (doc.ts > lastUpdate) { if (doc.ts > lastUpdate) {
lastUpdate = doc.ts; lastUpdate = doc.ts;
} }
@@ -182,7 +182,7 @@ class HistoryEra {
let downTotal = 0; let downTotal = 0;
let upTotal = 0; let upTotal = 0;
docs.forEach(function (doc) { docs.forEach((doc) => {
downTotal += Number(doc.dn); downTotal += Number(doc.dn);
upTotal += Number(doc.up); upTotal += Number(doc.up);
}); });

View File

@@ -201,7 +201,7 @@ class Torrent {
let trackers = clientData.trackers.split('@!@'); let trackers = clientData.trackers.split('@!@');
let trackerDomains = []; let trackerDomains = [];
trackers.forEach(function (tracker) { trackers.forEach((tracker) => {
let domain = regEx.domainName.exec(tracker); let domain = regEx.domainName.exec(tracker);
if (domain && domain[1]) { if (domain && domain[1]) {

View File

@@ -17,7 +17,7 @@ let _torrentCollection = new TorrentCollection();
let _trackerCount = {}; let _trackerCount = {};
var client = { var client = {
addFiles: function(req, callback) { addFiles: (req, callback) => {
let files = req.files; let files = req.files;
let path = req.body.destination; let path = req.body.destination;
let request = new ClientRequest(); let request = new ClientRequest();
@@ -34,7 +34,7 @@ var client = {
// Set the callback for only the last request. // Set the callback for only the last request.
if (index === files.length - 1) { if (index === files.length - 1) {
fileRequest.onComplete(function (data) { fileRequest.onComplete((data) => {
callback(data); callback(data);
}); });
} }
@@ -43,7 +43,7 @@ var client = {
}); });
}, },
addUrls: function(data, callback) { addUrls: (data, callback) => {
let urls = data.urls; let urls = data.urls;
let path = data.destination; let path = data.destination;
let request = new ClientRequest(); let request = new ClientRequest();
@@ -54,7 +54,7 @@ var client = {
request.send(); request.send();
}, },
deleteTorrents: function(hashes, callback) { deleteTorrents: (hashes, callback) => {
let request = new ClientRequest(); let request = new ClientRequest();
request.add('removeTorrents', {hashes}); request.add('removeTorrents', {hashes});
@@ -62,15 +62,15 @@ var client = {
request.send(); request.send();
}, },
getTorrentStatusCount: function(callback) { getTorrentStatusCount: (callback) => {
callback(_statusCount); callback(_statusCount);
}, },
getTorrentTrackerCount: function(callback) { getTorrentTrackerCount: (callback) => {
callback(_trackerCount); callback(_trackerCount);
}, },
getTorrentDetails: function(hash, callback) { getTorrentDetails: (hash, callback) => {
let request = new ClientRequest(); let request = new ClientRequest();
request.add('getTorrentDetails', { request.add('getTorrentDetails', {
@@ -84,12 +84,12 @@ var client = {
request.send(); request.send();
}, },
getTorrentList: function(callback) { getTorrentList: (callback) => {
let request = new ClientRequest(); let request = new ClientRequest();
request.add('getTorrentList', request.add('getTorrentList',
{props: clientUtil.defaults.torrentPropertyMethods}); {props: clientUtil.defaults.torrentPropertyMethods});
request.postProcess(function(data) { request.postProcess((data) => {
// TODO: Remove this nasty nested array business. // TODO: Remove this nasty nested array business.
_torrentCollection.updateTorrents(data[0][0]); _torrentCollection.updateTorrents(data[0][0]);
_statusCount = _torrentCollection.statusCount; _statusCount = _torrentCollection.statusCount;
@@ -101,7 +101,7 @@ var client = {
request.send(); request.send();
}, },
listMethods: function(method, args, callback) { listMethods: (method, args, callback) => {
let request = new ClientRequest(); let request = new ClientRequest();
request.add('listMethods', {method, args}); request.add('listMethods', {method, args});
@@ -109,7 +109,7 @@ var client = {
request.send(); request.send();
}, },
moveTorrents: function(data, callback) { moveTorrents: (data, callback) => {
let destinationPath = data.destination; let destinationPath = data.destination;
let hashes = data.hashes; let hashes = data.hashes;
let filenames = data.filenames; let filenames = data.filenames;
@@ -117,21 +117,21 @@ var client = {
let sourcePaths = data.sources; let sourcePaths = data.sources;
let mainRequest = new ClientRequest(); let mainRequest = new ClientRequest();
let startTorrents = function() { let startTorrents = () => {
let startTorrentsRequest = new ClientRequest(); let startTorrentsRequest = new ClientRequest();
startTorrentsRequest.add('startTorrents', {hashes}); startTorrentsRequest.add('startTorrents', {hashes});
startTorrentsRequest.onComplete(callback); startTorrentsRequest.onComplete(callback);
startTorrentsRequest.send(); startTorrentsRequest.send();
}; };
let checkHash = function() { let checkHash = () => {
let checkHashRequest = new ClientRequest(); let checkHashRequest = new ClientRequest();
checkHashRequest.add('checkHash', {hashes}); checkHashRequest.add('checkHash', {hashes});
checkHashRequest.onComplete(afterCheckHash); checkHashRequest.onComplete(afterCheckHash);
checkHashRequest.send(); checkHashRequest.send();
} }
let moveTorrents = function () { let moveTorrents = () => {
let moveTorrentsRequest = new ClientRequest(); let moveTorrentsRequest = new ClientRequest();
moveTorrentsRequest.onComplete(checkHash); moveTorrentsRequest.onComplete(checkHash);
moveTorrentsRequest.add('moveTorrents', moveTorrentsRequest.add('moveTorrents',
@@ -151,7 +151,7 @@ var client = {
mainRequest.send(); mainRequest.send();
}, },
setFilePriority: function (hashes, data, callback) { setFilePriority: (hashes, data, callback) => {
// TODO Add support for multiple hashes. // TODO Add support for multiple hashes.
let fileIndex = data.fileIndices[0]; let fileIndex = data.fileIndices[0];
let request = new ClientRequest(); let request = new ClientRequest();
@@ -161,7 +161,7 @@ var client = {
request.send(); request.send();
}, },
setPriority: function (hashes, data, callback) { setPriority: (hashes, data, callback) => {
let request = new ClientRequest(); let request = new ClientRequest();
request.add('setPriority', {hashes, priority: data.priority}); request.add('setPriority', {hashes, priority: data.priority});
@@ -169,7 +169,7 @@ var client = {
request.send(); request.send();
}, },
setSpeedLimits: function(data, callback) { setSpeedLimits: (data, callback) => {
let request = new ClientRequest(); let request = new ClientRequest();
request.add('setThrottle', request.add('setThrottle',
@@ -178,7 +178,7 @@ var client = {
request.send(); request.send();
}, },
stopTorrent: function(hashes, callback) { stopTorrent: (hashes, callback) => {
let request = new ClientRequest(); let request = new ClientRequest();
request.add('stopTorrents', {hashes}); request.add('stopTorrents', {hashes});
@@ -186,7 +186,7 @@ var client = {
request.send(); request.send();
}, },
startTorrent: function(hashes, callback) { startTorrent: (hashes, callback) => {
let request = new ClientRequest(); let request = new ClientRequest();
request.add('startTorrents', {hashes}); request.add('startTorrents', {hashes});
@@ -194,7 +194,7 @@ var client = {
request.send(); request.send();
}, },
getTransferStats: function(callback) { getTransferStats: (callback) => {
let request = new ClientRequest(); let request = new ClientRequest();
request.add('getTransferData'); request.add('getTransferData');

View File

@@ -60,7 +60,7 @@ let fiveMinSnapshot = new HistoryEra({
nextEra: thirtyMinSnapshot nextEra: thirtyMinSnapshot
}); });
let processData = function (opts, callback, data, error) { let processData = (opts, callback, data, error) => {
if (error) { if (error) {
callback(null, error); callback(null, error);
return; return;
@@ -71,7 +71,7 @@ let processData = function (opts, callback, data, error) {
let downloadRateHistory = []; let downloadRateHistory = [];
let uploadRateHistory = []; let uploadRateHistory = [];
data.forEach(function (snapshot) { data.forEach((snapshot) => {
downloadRateHistory.push(snapshot.dn); downloadRateHistory.push(snapshot.dn);
uploadRateHistory.push(snapshot.up); uploadRateHistory.push(snapshot.up);
}); });
@@ -83,7 +83,7 @@ let processData = function (opts, callback, data, error) {
}; };
let history = { let history = {
get: function (opts, callback) { get: (opts, callback) => {
opts = opts || {}; opts = opts || {};
if (opts.snapshot === 'fiveMin') { if (opts.snapshot === 'fiveMin') {
@@ -103,9 +103,9 @@ let history = {
} }
}, },
startPolling: function () { startPolling: () => {
pollInterval = setInterval(function() { pollInterval = setInterval(() => {
client.getTransferStats(function (data, err) { client.getTransferStats((data, err) => {
if (err) { if (err) {
return; return;
} }
@@ -118,7 +118,7 @@ let history = {
}, 1000 * 5); }, 1000 * 5);
}, },
stopPolling: function() { stopPolling: () => {
clearInterval(pollInterval); clearInterval(pollInterval);
pollInterval = null; pollInterval = null;
} }

View File

@@ -9,8 +9,8 @@ var history = require('../models/history');
history.startPolling(); history.startPolling();
passport.use(new Strategy( passport.use(new Strategy(
function(username, password, callback) { (username, password, callback) => {
users.findByUsername(username, function(err, user) { users.findByUsername(username, (err, user) => {
if (err) { return callback(err); } if (err) { return callback(err); }
if (!user) { return callback(null, false); } if (!user) { return callback(null, false); }
if (user.password != password) { return callback(null, false); } if (user.password != password) { return callback(null, false); }
@@ -20,7 +20,7 @@ passport.use(new Strategy(
)); ));
router.get('/', passport.authenticate('basic', { session: false }), router.get('/', passport.authenticate('basic', { session: false }),
function(req, res) { (req, res) => {
res.render('index', { title: 'Flood' }); res.render('index', { title: 'Flood' });
// res.json({ username: req.user.username, email: req.user.emails[0].value }); // res.json({ username: req.user.username, email: req.user.emails[0].value });
} }

View File

@@ -9,19 +9,19 @@ let client = require('../models/client');
let history = require('../models/history'); let history = require('../models/history');
let uiSettings = require('../models/uiSettings'); let uiSettings = require('../models/uiSettings');
router.post('/sort-props', function(req, res, next) { router.post('/sort-props', (req, res, next) => {
uiSettings.setSortProps(req.body, ajaxUtil.getResponseFn(res)); uiSettings.setSortProps(req.body, ajaxUtil.getResponseFn(res));
}); });
router.get('/sort-props', function(req, res, next) { router.get('/sort-props', (req, res, next) => {
uiSettings.getSortProps(ajaxUtil.getResponseFn(res)); uiSettings.getSortProps(ajaxUtil.getResponseFn(res));
}); });
router.get('/torrent-location', function(req, res, next) { router.get('/torrent-location', (req, res, next) => {
uiSettings.getLatestTorrentLocation(ajaxUtil.getResponseFn(res)); uiSettings.getLatestTorrentLocation(ajaxUtil.getResponseFn(res));
}); });
router.post('/torrent-location', function(req, res, next) { router.post('/torrent-location', (req, res, next) => {
uiSettings.setLatestTorrentLocation(req.body, ajaxUtil.getResponseFn(res)); uiSettings.setLatestTorrentLocation(req.body, ajaxUtil.getResponseFn(res));
}); });

View File

@@ -1,8 +1,8 @@
'use strict'; 'use strict';
let ajaxUtil = { let ajaxUtil = {
getResponseFn: function (res) { getResponseFn: (res) => {
return function (data, error) { return (data, error) => {
if (error) { if (error) {
res.status(500).json(error); res.status(500).json(error);
return; return;

View File

@@ -4,7 +4,7 @@ let clientUtil = require('./clientUtil');
let util = require('util'); let util = require('util');
let clientResponseUtil = { let clientResponseUtil = {
processTorrentDetails: function(data) { processTorrentDetails: (data) => {
// TODO: This is ugly. // TODO: This is ugly.
let peersData = data[0][0] || null; let peersData = data[0][0] || null;
let filesData = data[1][0] || null; let filesData = data[1][0] || null;
@@ -26,7 +26,7 @@ let clientResponseUtil = {
filesData filesData
); );
files = files.map(function (file) { files = files.map((file) => {
file.filename = file.pathComponents[file.pathComponents.length - 1]; file.filename = file.pathComponents[file.pathComponents.length - 1];
file.percentComplete = (file.completedChunks / file.sizeChunks * 100).toFixed(0); file.percentComplete = (file.completedChunks / file.sizeChunks * 100).toFixed(0);
delete(file.completedChunks); delete(file.completedChunks);
@@ -45,7 +45,7 @@ let clientResponseUtil = {
return {peers, files, trackers}; return {peers, files, trackers};
}, },
processTransferStats: function(data) { processTransferStats: (data) => {
return clientUtil.mapClientProps(clientUtil.defaults.clientProperties, return clientUtil.mapClientProps(clientUtil.defaults.clientProperties,
data); data);
} }

View File

@@ -220,7 +220,7 @@ var clientUtil = {
}, },
// TODO clean this up, write comments... // TODO clean this up, write comments...
mapClientProps: function(props, data, includeIndex) { mapClientProps: (props, data, includeIndex) => {
var index = 0; var index = 0;
var mappedObject = []; var mappedObject = [];
@@ -243,7 +243,7 @@ var clientUtil = {
return mappedObject; return mappedObject;
}, },
createMulticallRequest: function(methodCalls, params) { createMulticallRequest: (methodCalls, params) => {
params = params || []; params = params || [];
var methodCall = []; var methodCall = [];

View File

@@ -4,7 +4,7 @@
* ISO8601 formatted strings. Accepts formats with and without * ISO8601 formatted strings. Accepts formats with and without
* hyphen/colon separators and correctly parses zoning info. * hyphen/colon separators and correctly parses zoning info.
*/ */
var DateFormatter = function (opts) { var DateFormatter = (opts) => {
this.opts = {} this.opts = {}
this.setOpts(opts) this.setOpts(opts)
} }
@@ -49,11 +49,11 @@ DateFormatter.ISO8601 = new RegExp(
* @param {Boolean} opts.offset - Enable/Disable output of UTC offset * @param {Boolean} opts.offset - Enable/Disable output of UTC offset
* (default: false) * (default: false)
*/ */
DateFormatter.prototype.setOpts = function (opts) { DateFormatter.prototype.setOpts = (opts) => {
if (!opts) opts = DateFormatter.DEFAULT_OPTIONS if (!opts) opts = DateFormatter.DEFAULT_OPTIONS
var ctx = this; var ctx = this;
Object.keys(DateFormatter.DEFAULT_OPTIONS).forEach(function (k) { Object.keys(DateFormatter.DEFAULT_OPTIONS).forEach((k) => {
ctx.opts[k] = opts.hasOwnProperty(k) ? ctx.opts[k] = opts.hasOwnProperty(k) ?
opts[k] : DateFormatter.DEFAULT_OPTIONS[k] opts[k] : DateFormatter.DEFAULT_OPTIONS[k]
}) })
@@ -66,7 +66,7 @@ DateFormatter.prototype.setOpts = function (opts) {
* @param {String} time - String representation of timestamp. * @param {String} time - String representation of timestamp.
* @return {Date} - Date object from timestamp. * @return {Date} - Date object from timestamp.
*/ */
DateFormatter.prototype.decodeIso8601 = function(time) { DateFormatter.prototype.decodeIso8601 = (time) => {
var dateParts = time.toString().match(DateFormatter.ISO8601) var dateParts = time.toString().match(DateFormatter.ISO8601)
if (!dateParts) { if (!dateParts) {
throw new Error('Expected a ISO8601 datetime but got \'' + time + '\'') throw new Error('Expected a ISO8601 datetime but got \'' + time + '\'')
@@ -98,7 +98,7 @@ DateFormatter.prototype.decodeIso8601 = function(time) {
* @param {Date} date - Date object. * @param {Date} date - Date object.
* @return {String} - String representation of timestamp. * @return {String} - String representation of timestamp.
*/ */
DateFormatter.prototype.encodeIso8601 = function(date) { DateFormatter.prototype.encodeIso8601 = (date) => {
var parts = this.opts.local ? var parts = this.opts.local ?
DateFormatter.getLocalDateParts(date) : DateFormatter.getLocalDateParts(date) :
DateFormatter.getUTCDateParts(date) DateFormatter.getUTCDateParts(date)
@@ -120,7 +120,7 @@ DateFormatter.prototype.encodeIso8601 = function(date) {
* @param {Date} date - Date Object * @param {Date} date - Date Object
* @return {String[]} * @return {String[]}
*/ */
DateFormatter.getUTCDateParts = function (date) { DateFormatter.getUTCDateParts = (date) => {
return [ return [
date.getUTCFullYear() date.getUTCFullYear()
, DateFormatter.zeroPad(date.getUTCMonth()+1,2) , DateFormatter.zeroPad(date.getUTCMonth()+1,2)
@@ -139,7 +139,7 @@ DateFormatter.getUTCDateParts = function (date) {
* @param {Date} date - Date Object * @param {Date} date - Date Object
* @return {String[]} * @return {String[]}
*/ */
DateFormatter.getLocalDateParts = function (date) { DateFormatter.getLocalDateParts = (date) => {
return [ return [
date.getFullYear() date.getFullYear()
, DateFormatter.zeroPad(date.getMonth()+1,2) , DateFormatter.zeroPad(date.getMonth()+1,2)
@@ -159,7 +159,7 @@ DateFormatter.getLocalDateParts = function (date) {
* already length. * already length.
* @return {String} - String with the padded digit * @return {String} - String with the padded digit
*/ */
DateFormatter.zeroPad = function (digit, length) { DateFormatter.zeroPad = (digit, length) => {
var padded = '' + digit var padded = '' + digit
while (padded.length < length) { while (padded.length < length) {
padded = '0' + padded padded = '0' + padded
@@ -174,7 +174,7 @@ DateFormatter.zeroPad = function (digit, length) {
* *
* @return {String} - in the format /Z|[+-]\d{2}:\d{2}/ * @return {String} - in the format /Z|[+-]\d{2}:\d{2}/
*/ */
DateFormatter.formatCurrentOffset = function (d) { DateFormatter.formatCurrentOffset = (d) => {
var offset = (d || new Date()).getTimezoneOffset() var offset = (d || new Date()).getTimezoneOffset()
return (offset === 0) ? 'Z' : [ return (offset === 0) ? 'Z' : [
(offset < 0) ? '+' : '-' (offset < 0) ? '+' : '-'

View File

@@ -1,20 +1,20 @@
var util = require('util'); var util = require('util');
var FormatUtil = { var FormatUtil = {
percentComplete: function(numerator, denominator) { percentComplete: (numerator, denominator) => {
}, },
eta: function(rate, completed, total) { eta: (rate, completed, total) => {
}, },
parsePeers: function(string) { parsePeers: (string) => {
var markerPosition = string.indexOf('@!@'); var markerPosition = string.indexOf('@!@');
return string.substr(0, markerPosition); return string.substr(0, markerPosition);
}, },
status: function(isHashChecking, isComplete, isOpen, uploadRate, downloadRate, state, message) { status: (isHashChecking, isComplete, isOpen, uploadRate, downloadRate, state, message) => {
var torrentStatus = []; var torrentStatus = [];
if (isHashChecking === '1') { if (isHashChecking === '1') {

View File

@@ -8,7 +8,7 @@ let Serializer = require('xmlrpc/lib/serializer');
let config = require('../../config'); let config = require('../../config');
let scgi = { let scgi = {
methodCall: function(methodName, parameters) { methodCall: (methodName, parameters) => {
let deferred = Q.defer(); let deferred = Q.defer();
let deserializer = new Deserializer('utf8'); let deserializer = new Deserializer('utf8');
let headerLength = 0; let headerLength = 0;
@@ -19,7 +19,7 @@ let scgi = {
stream.setEncoding('UTF8'); stream.setEncoding('UTF8');
// TODO: Remove this debugging info. // TODO: Remove this debugging info.
stream.on('error', function(error) { stream.on('error', () => {
console.trace(error); console.trace(error);
}); });
@@ -28,19 +28,19 @@ let scgi = {
`SCGI${nullChar}1${nullChar}` `SCGI${nullChar}1${nullChar}`
]; ];
headerItems.forEach(function (item) { headerItems.forEach((item) => {
headerLength += item.length; headerLength += item.length;
}); });
let header = `${headerLength}:`; let header = `${headerLength}:`;
headerItems.forEach(function(headerItem) { headerItems.forEach((headerItem) => {
header += headerItem; header += headerItem;
}); });
stream.write(`${header},${xml}`); stream.write(`${header},${xml}`);
deserializer.deserializeMethodResponse(stream, function (error, response) { deserializer.deserializeMethodResponse(stream, (error, response) => {
if (error) { if (error) {
return deferred.reject(error); return deferred.reject(error);
} }

View File

@@ -1,11 +1,11 @@
'use strict'; 'use strict';
let stringUtil = { let stringUtil = {
capitalize: function (string) { capitalize: (string) => {
return string.charAt(0).toUpperCase() + string.slice(1); return string.charAt(0).toUpperCase() + string.slice(1);
}, },
pluralize: function (string, count) { pluralize: (string, count) => {
if (count !== 1) { if (count !== 1) {
if (string.charAt(string.length - 1) === 'y') { if (string.charAt(string.length - 1) === 'y') {
return `${string.substring(0, string.length - 1)}ies`; return `${string.substring(0, string.length - 1)}ies`;