<commit_before>#!/usr/bin/env node

'use strict';

const fs = require('fs');

const http = require('follow-redirects').http;

const mkdirp = require('mkdirp');

const md5 = require('md5');

const request = require('request');

const colors = require('colors/safe');

const updateNotifier = require('update-notifier');

const pkg = require('./package.json');

updateNotifier({pkg}).notify();

const argv = require('yargs')

	.usage(colors.cyan.bold('\n Usage : $0 -u [email@id] -n [file name]'))

	.demand(['u', 'n'])

	.describe('u', '❱ Email-Id of any gravatar user')

	.describe('n', '❱ Name of Image')

	.example(colors.cyan.bold('\n$0 abc@gmail.com -n ab'))

	.argv;

const localFold = argv.n;

// hashing and storing the email
const hashEmail = md5(argv.u);

// passed
const usedAs = hashEmail;

// directory where the image will be saved
const saveImage = './Gravatar/';

// because I want to
const removeSlash = saveImage.replace('./', '');

// used where the directory is shown to the user
const forSaved = removeSlash.replace('/', '');

// finding username based on email address
// will show the user's data only if the gravatar user name of a person is starting chars of his email before '@'
function removeString(emailAddress) {
	// removing everything after '@', basic strategy used by gravtar for username
	return emailAddress.replace(/\@.*/, '');
}

// stored argument
const replacedString = removeString(argv.u);

mkdirp(removeSlash, err => {
	if (err) {
		process.exit(1);

		console.log(err);
	} else {
		// no need
	}
});

function checkInternet(cb) {
	require('dns').lookup('gravatar.com', err => {
		if (err && err.code === 'ENOTFOUND') {
			cb(false);
		} else {
			cb(true);
		}
	});
}

checkInternet(isConnected => {
	if (isConnected) {
		console.log(colors.cyan.bold('\n Downloading', replacedString, '\'s gravatar image...'));
	} else {
		console.log(colors.red.bold('\n ❱ Internet Connection   :   ✖\n'));

		process.exit(1);
	}
});

request
	.get('http://1.gravatar.com/avatar/' + usedAs)

.on('response', response => {
	// checking for the type of remote image.
	const storeType = response.headers['content-type'];

	// initially the result comes like image/.gif
	// thus removing the 'image/' part
	const parseType = storeType.toString().replace('image/', '');

	// stored the possible extension in typeArray
	const typeArray = ['png', 'jpeg', 'gif'];

	// checking if the remote image is png
	if (response.statusCode === 200 && typeArray[0] === parseType) {
		// will save the image in the default defined directory
		const imageFile = fs.createWriteStream(removeSlash + argv.n + '.png');

		// started downloading image
		http.get('http://1.gravatar.com/avatar/' + usedAs + '?size=400px',
			res => {
				res.pipe(imageFile);
				setTimeout(() => {
					console.log(colors.cyan.bold('\n ❱ Image Saved In  :  ') + colors.green.bold(forSaved.toString() + ' ❱ ' + localFold.toString() + '.png\n'));
				}, 2000);
			}).on('error', err => {
				process.exit(1);

				console.log(err);

			});
	} else {
		/* something to be done | but no need */
	}
	// checking if the remote image if jpg/jpeg
	if (response.statusCode === 200 && typeArray[1] === parseType) {
		const imageFile = fs.createWriteStream(removeSlash + argv.n + '.jpeg');
		http.get('http://1.gravatar.com/avatar/' + usedAs + '?size=400px',
			res => {
				res.pipe(imageFile);
				setTimeout(() => {
					console.log(colors.cyan.bold('\n ❱ Image Saved In  :  ') + colors.green.bold(forSaved + ' ❱ ' + localFold + '.jpeg\n'));
				}, 2000);
			}).on('error', err => {
				process.exit(1);

				console.log(err);
			});
	} else {
		/* do something */
	}
});
<commit_msg>emai[auth] | tweaks<commit_after>#!/usr/bin/env node

'use strict';

const fs = require('fs');

const http = require('follow-redirects').http;

const mkdirp = require('mkdirp');

const md5 = require('md5');

const request = require('request');

const colors = require('colors/safe');

const updateNotifier = require('update-notifier');

const pkg = require('./package.json');

updateNotifier({pkg}).notify();

const argv = require('yargs')

	.usage(colors.cyan.bold('\n Usage : $0 -u [email@id] -n [file name]'))

	.demand(['u', 'n'])

	.describe('u', '❱ Email-Id of any gravatar user')

	.describe('n', '❱ Name of Image')

	.example(colors.cyan.bold('\n$0 abc@gmail.com -n ab'))

	.argv;

const localFold = argv.n;

// hashing and storing the email
const hashEmail = md5(argv.u);

// passed
const usedAs = hashEmail;

// directory where the image will be saved
const saveImage = './Gravatar/';

// because I want to
const removeSlash = saveImage.replace('./', '');

// used where the directory is shown to the user
const forSaved = removeSlash.replace('/', '');

// finding username based on email address
// will show the user's data only if the gravatar user name of a person is starting chars of his email before '@'
function removeString(emailAddress) {
	// removing everything after '@', basic strategy used by gravtar for username
	return emailAddress.replace(/\@.*/, '');
}

// stored argument
const replacedString = removeString(argv.u);

mkdirp(removeSlash, err => {
	if (err) {
		process.exit(1);

		console.log(err);
	} else {
		// no need
	}
});

// checking if the email is valid or not
function checkEmail(emailString) {
	const heckString = new RegExp('@.');
	if (heckString.test(emailString) === true) {
		return ['Valid Email'];
	} else {
		return ['Invalid Email'];
	}
}

function checkInternet(cb) {
	require('dns').lookup('gravatar.com', err => {
		if (err && err.code === 'ENOTFOUND') {
			cb(false);
		} else {
			cb(true);
		}
	});
}

checkInternet(isConnected => {
	if (isConnected) {
		const checkPoint = checkEmail(argv.u);
		let pointOne = ['Valid Email'];
		let pointTwo = ['Invalid Email'];

		if (checkPoint[0] === pointOne[0]) {
			// do nothing
		} else {
			console.log(colors.red.bold('\n ❱ Valid email address  :   ✖\n'));

			process.exit(1);
		}
		console.log(colors.cyan.bold('\n Downloading', replacedString, '\'s gravatar image...'));
	} else {
		console.log(colors.red.bold('\n ❱ Internet Connection  j:   ✖\n'));

		process.exit(1);
	}
});

request
	.get('http://1.gravatar.com/avatar/' + usedAs)

.on('response', response => {
	// checking for the type of remote image.
	const storeType = response.headers['content-type'];

	// initially the result comes like image/.gif
	// thus removing the 'image/' part
	const parseType = storeType.toString().replace('image/', '');

	// stored the possible extension in typeArray
	const typeArray = ['png', 'jpeg', 'gif'];

	// checking if the remote image is png
	if (response.statusCode === 200 && typeArray[0] === parseType) {
		// will save the image in the default defined directory
		const imageFile = fs.createWriteStream(removeSlash + argv.n + '.png');

		// started downloading image
		http.get('http://1.gravatar.com/avatar/' + usedAs + '?size=400px',
			res => {
				res.pipe(imageFile);
				setTimeout(() => {
					console.log(colors.cyan.bold('\n ❱ Image Saved In  :  ') + colors.green.bold(forSaved.toString() + ' ❱ ' + localFold.toString() + '.png\n'));
				}, 2000);
			}).on('error', err => {
				process.exit(1);

				console.log(err);

			});
	} else {
		/* something to be done | but no need */
	}
	// checking if the remote image if jpg/jpeg
	if (response.statusCode === 200 && typeArray[1] === parseType) {
		const imageFile = fs.createWriteStream(removeSlash + argv.n + '.jpeg');
		http.get('http://1.gravatar.com/avatar/' + usedAs + '?size=400px',
			res => {
				res.pipe(imageFile);
				setTimeout(() => {
					console.log(colors.cyan.bold('\n ❱ Image Saved In  :  ') + colors.green.bold(forSaved + ' ❱ ' + localFold + '.jpeg\n'));
				}, 2000);
			}).on('error', err => {
				process.exit(1);

				console.log(err);
			});
	} else {
		/* do something */
	}
});
<|endoftext|>


<commit_before>#!/usr/bin/env node
var path = require('path');
var Config = require('./index.js');

var parser = require('nomnom');
var log_levels = ['silly', 'debug', 'info', 'warn', 'critical'];
var log_level = 4;

parser.script('jetconfig');

parser.option('version', {
        flag: true,
        help: "Print version and exit",
        callback: function () { console.log(require('./package').version); }
    })
    .option('noInherit', {
        flag: true,
        help: "Prevent configuration inheritance",
        abbr: 'n',
        full: 'no-inherit',
    })
    .option('verbose', {
        abbr: 'v',
        help: "Increase verbosity, can be used multiple times",
        flag: true,
        callback: function () {
            if (log_level > 0) log_level -= 1;
        }
    });

var cmd = function cmd (func) {
    var handler = function handler (params) {
        var opts = {};
        var conf;
        var result;

        opts.logLevel = log_levels[log_level];
        opts.prefix = params.prefix;
        opts.inherit = !params.noInherit;

        conf = new Config(opts);
        result = func(conf, params);
        if (result !== undefined) console.log(JSON.stringify(result, null, 2));
        else console.log('undefined');
    };
    return handler;
};

parser.command('dump')
    .help("Dump the current etcd configuration")
    .option('prefix', {
        position: 1,
        help: 'Etcd namespace (default: config/)',
        default: 'config/',
        required: true
    })
    .callback(cmd(function (conf) {
        return conf.dump();
    }));

parser.command('list')
    .help("List all available etcd configurations")
    .option('prefix', {
        position: 1,
        help: 'Etcd namespace (default: /)',
        default: '/',
        required: true
    })
    .callback(cmd(function (conf) {
        return conf.list(undefined, {dirOnly: false});
    }));

parser.command('clear')
    .help("Clear the current etcd configuration")
    .option('prefix', {
        position: 1,
        help: 'Etcd namespace',
        required: true
    })
    .callback(cmd(function (conf) {
        conf.allowClear = true;
        conf.clear();
    }));

parser.command('load')
    .help("Load a configuration from a file")
    .option('prefix', {
        position: 1,
        help: 'Etcd namespace',
        required: true
    })
    .option('file', {
        position: 2,
        help: 'Filename to load',
        required: true,
    })
    .callback(cmd(function (conf, params) {
        var filename = path.resolve(params.file);
        var new_conf;
        try {
            new_conf = require(filename);
        } catch (err) {
            if (String(err).match(/Cannot find module/)) {
                console.log("No such file:", params.file);
            }
            else {
                console.log('' + err);
            }
            return process.exit(1);
        }
        conf.log.silly("Read config", new_conf);
        conf.load(new_conf, {cacheOnly: false});
    }));

parser.command('get')
    .help("Get a configuration key")
    .option('prefix', {
        position: 1,
        help: 'Etcd namespace',
        required: true
    })
    .option('key', {
        position: 2,
        help: 'Configuration key',
        required: true
    })
    .callback(cmd(function (conf, params) {
        value = conf.get(params.key, params.value);
        if (value === undefined) process.exit(1);
        return value;
    }));

parser.command('set')
    .help("Set a configuration key to a value")
    .option('prefix', {
        position: 1,
        help: 'Etcd namespace',
        required: true
    })
    .option('key', {
        position: 2,
        help: 'Configuration key',
        required: true
    })
    .option('value', {
        position: 3,
        help: 'Configuration value',
        required: true
    })
    .callback(cmd(function (conf, params) {
        conf.set(params.key, params.value);
    }));

parser.parse();
<commit_msg>Don't be silly with logging.<commit_after>#!/usr/bin/env node
var path = require('path');
var Config = require('./index.js');

var parser = require('nomnom');
var log_levels = ['silly', 'debug', 'info', 'warn', 'critical'];
var log_level = 4;

parser.script('jetconfig');

parser.option('version', {
        flag: true,
        help: "Print version and exit",
        callback: function () { console.log(require('./package').version); }
    })
    .option('noInherit', {
        flag: true,
        help: "Prevent configuration inheritance",
        abbr: 'n',
        full: 'no-inherit',
    })
    .option('verbose', {
        abbr: 'v',
        help: "Increase verbosity, can be used multiple times",
        flag: true,
        callback: function () {
            if (log_level > 0) log_level -= 1;
        }
    });

var cmd = function cmd (func) {
    var handler = function handler (params) {
        var opts = {};
        var conf;
        var result;

        opts.logLevel = log_levels[log_level];
        opts.prefix = params.prefix;
        opts.inherit = !params.noInherit;

        conf = new Config(opts);
        result = func(conf, params);
        if (result !== undefined) console.log(JSON.stringify(result, null, 2));
    };
    return handler;
};

parser.command('dump')
    .help("Dump the current etcd configuration")
    .option('prefix', {
        position: 1,
        help: 'Etcd namespace (default: config/)',
        default: 'config/',
        required: true
    })
    .callback(cmd(function (conf) {
        return conf.dump();
    }));

parser.command('list')
    .help("List all available etcd configurations")
    .option('prefix', {
        position: 1,
        help: 'Etcd namespace (default: /)',
        default: '/',
        required: true
    })
    .callback(cmd(function (conf) {
        return conf.list(undefined, {dirOnly: false});
    }));

parser.command('clear')
    .help("Clear the current etcd configuration")
    .option('prefix', {
        position: 1,
        help: 'Etcd namespace',
        required: true
    })
    .callback(cmd(function (conf) {
        conf.allowClear = true;
        conf.clear();
    }));

parser.command('load')
    .help("Load a configuration from a file")
    .option('prefix', {
        position: 1,
        help: 'Etcd namespace',
        required: true
    })
    .option('file', {
        position: 2,
        help: 'Filename to load',
        required: true,
    })
    .callback(cmd(function (conf, params) {
        var filename = path.resolve(params.file);
        var new_conf;
        try {
            new_conf = require(filename);
        } catch (err) {
            if (String(err).match(/Cannot find module/)) {
                console.log("No such file:", params.file);
            }
            else {
                console.log('' + err);
            }
            return process.exit(1);
        }
        conf.log.silly("Read config", new_conf);
        conf.load(new_conf, {cacheOnly: false});
    }));

parser.command('get')
    .help("Get a configuration key")
    .option('prefix', {
        position: 1,
        help: 'Etcd namespace',
        required: true
    })
    .option('key', {
        position: 2,
        help: 'Configuration key',
        required: true
    })
    .callback(cmd(function (conf, params) {
        value = conf.get(params.key, params.value);
        if (value === undefined) process.exit(1);
        return value;
    }));

parser.command('set')
    .help("Set a configuration key to a value")
    .option('prefix', {
        position: 1,
        help: 'Etcd namespace',
        required: true
    })
    .option('key', {
        position: 2,
        help: 'Configuration key',
        required: true
    })
    .option('value', {
        position: 3,
        help: 'Configuration value',
        required: true
    })
    .callback(cmd(function (conf, params) {
        conf.set(params.key, params.value);
    }));

parser.parse();
<|endoftext|>


<commit_before>#!/usr/bin/env node
'use strict';
var spawn = require('child_process').spawn;
var input = process.argv.slice(2);
var cmd = require('./');

spawn('bash', cmd, {stdio: 'inherit'})
  .on('exit', process.exit);
<commit_msg>update<commit_after>#!/usr/bin/env node
'use strict';
var spawn = require('child_process').spawn;
var input = process.argv.slice(2);
var cmd = require('./');
console.log(input);
spawn('bash', cmd, {stdio: 'inherit'})
  .on('exit', process.exit);
<|endoftext|>


<commit_before>var tester = require('./main');
var fs = require('fs');
var https = require('https');

var remote = 'warg.ngrok.io';

var config = require('./config.json');

config.rateLimit = config.rateLimit || 95;
config.applist = config.applist || 'app-list.txt';
config.debug = config.debug || false;

function debug() {
	if (config.debug) console.log.apply(console, arguments.unshift('[debug]'));
}

function checkPassword(password, callback) {
	var appIDs = fs.readFileSync(config.applist).toString().replace(/\r/g, '').split('\n');
	var currentAppID = 0;

	var results = [];

	var queries = 0;
	var elapsed = 0;
	var rateLimited = false;

	var done = 0;

	console.log('== Checking password: ' + password);

	console.log();
	var intervalID = setInterval(function() {
		elapsed++;
		process.stdout.write('\x1b[1000D\x1b[K\x1b[A');
		console.log((done + '/' + appIDs.length + '        ').substr(0,10) + ' ' + (queries + 'q/s       ').substr(0,8) + ' ' + (elapsed + 's     ').substr(0,5) + ' ' + (rateLimited ? '! RATE LIMITED (waiting) !' : ''));
		queries = 0;

		if (done === appIDs.length) {
			console.log('Done!');
			clearInterval(intervalID);
			return callback(results);
		}
	}, 1000);

	function nextAppID(ignoreRateLimit, fromTimeout) {
		if (currentAppID === appIDs.length) return;

		if (queries > config.rateLimit) {
			return setTimeout(function() {
				nextAppID(ignoreRateLimit, false);
			}, 50);
		}
		queries++;

		if (rateLimited && !fromTimeout) {
			return setTimeout(function() {
				nextAppID(ignoreRateLimit, ignoreRateLimit);
			}, 15000);
		}

		var appID = appIDs[currentAppID++];

		tester.tryPassword(password, appID, function(err, result) {
			done++;

			if (err) {
				rateLimited = true;
				currentAppID--;
			} else {
				rateLimited = false;
				if (result) {
					if (result.url) {
						console.log('[found url] app=' + appID + ', password=' + password + ', url=' + result.url + '\n');
					} else if (result.response) {
						console.log('[found response] app=' + appID + ', password=' + password + ', response=' + result.response + '\n');
					} else {
						console.log('[found weird] app=' + appID + ', password=' + password + ', result=' + JSON.stringify(result) + '\n');
					}

					results.push({
						appID: appID,
						result: result
					});
				}
				nextAppID(ignoreRateLimit);
			}
		});
	}

	for (var w = 0; w < 50; w++) nextAppID(w === 0);
}

function printHelp() {
	console.log('== help');
	console.log('Prints this message.');
	console.log('== password <password>');
	console.log('Check <password> against all app ids listed in a text file (default app-list.txt). Don\'t use quotes!');
	console.log('== bot');
	console.log('Automatically checks passwords.');
}

if (process.argv.length < 3 || process.argv[2] === 'help') {
	printHelp();
} else if (process.argv[2] === 'password') {
	if (process.argv.length < 3) return printHelp();

	process.on('SIGINT', function() {
		process.stdout.write('\n\r');
		process.exit();
	});

	checkPassword(process.argv.slice(3, process.argv.length).join(' '), function(result) {
		process.exit();
	});
} else if (process.argv[2] === 'bot') {
	process.on('SIGINT', function() {
		process.stdout.write('\n\r');
		process.exit();
	});

	function postResults(resp, result) {
		var req = https.request({
			host: remote,
			path: '/solve',
			method: 'POST',
			headers: {
				'content-type': 'application/json'
			}
		}, function(res) {
			res.on('data', function(data) {
				req.response = (req.response || '') + data.toString();
			}).on('end', function() {
				try {
					var a = JSON.parse(req.response);
					if (a.status === 'success') {
						console.log('Results posted.');
						getNextPassword();
					} else {
						console.warn('Error posting results! Retrying in 10 seconds.');
						console.log(req.response);
						setTimeout(function() {
							postResults(resp, result);
						}, 10000);
					}
				} catch (e) {
					console.log('Exception when posting results. Retrying in 10 seconds.', e);
					console.log(req.response);
					setTimeout(function() {
						postResults(resp, result);
					}, 10000);
				}
			});
		});

		req.on('error', function(err) {
			console.log('Error when posting results. Retrying in 10 seconds.', err);
			setTimeout(function() {
				postResults(resp, result);
			}, 10000);
		});

		req.write(JSON.stringify({
			id: resp.id,
			result: result
		}))

		req.end();
	}

	function getNextPassword() {
		var req = https.request({
			host: remote,
			path: '/nextpassword',
			headers: {
				'content-type': 'application/json'
			}
		}, function(res) {
			res.on('data', function(data) {
				req.response = (req.response || '') + data.toString();
			}).on('end', function() {
				try {
					var resp = JSON.parse(req.response);

					if (resp.status === 'success') {
						checkPassword(resp.password, function(result) {
							postResults(resp, result);
						});
					} else if (resp.status === 'queue_empty') {
						console.log('No passwords to check. Retrying in 10 seconds.');
						setTimeout(getNextPassword, 10000);
					} else {
						console.log('Unknown response (retrying in 10 seconds):', resp);
						setTimeout(getNextPassword, 10000);
					}
				} catch (e) {
					console.log('Exception when getting next password. Retrying in 10 seconds.', e);
					setTimeout(getNextPassword, 10000);
				}
			});
		});
		req.on('error', function(err) {
			console.log('Error when getting next password. Retrying in 10 seconds.', err);
			setTimeout(getNextPassword, 10000);
		});
		req.end();
	}

	getNextPassword();
}
<commit_msg>Fix done tasks count going over app amount<commit_after>var tester = require('./main');
var fs = require('fs');
var https = require('https');

var remote = 'warg.ngrok.io';

var config = require('./config.json');

config.rateLimit = config.rateLimit || 95;
config.applist = config.applist || 'app-list.txt';
config.debug = config.debug || false;

function debug() {
	if (config.debug) console.log.apply(console, arguments.unshift('[debug]'));
}

function checkPassword(password, callback) {
	var appIDs = fs.readFileSync(config.applist).toString().replace(/\r/g, '').split('\n');
	var currentAppID = 0;

	var results = [];

	var queries = 0;
	var elapsed = 0;
	var rateLimited = false;

	var done = 0;

	console.log('== Checking password: ' + password);

	console.log();
	var intervalID = setInterval(function() {
		elapsed++;
		process.stdout.write('\x1b[1000D\x1b[K\x1b[A');
		console.log((done + '/' + appIDs.length + '        ').substr(0,10) + ' ' + (queries + 'q/s       ').substr(0,8) + ' ' + (elapsed + 's     ').substr(0,5) + ' ' + (rateLimited ? '! RATE LIMITED (waiting) !' : ''));
		queries = 0;

		if (done === appIDs.length) {
			console.log('Done!');
			clearInterval(intervalID);
			return callback(results);
		}
	}, 1000);

	function nextAppID(ignoreRateLimit, fromTimeout) {
		if (currentAppID === appIDs.length) return;

		if (queries > config.rateLimit) {
			return setTimeout(function() {
				nextAppID(ignoreRateLimit, false);
			}, 50);
		}
		queries++;

		if (rateLimited && !fromTimeout) {
			return setTimeout(function() {
				nextAppID(ignoreRateLimit, ignoreRateLimit);
			}, 15000);
		}

		var appID = appIDs[currentAppID++];

		tester.tryPassword(password, appID, function(err, result) {
			if (err) {
				rateLimited = true;
				currentAppID--;
			} else {
				rateLimited = false;
				done++;
				if (result) {
					if (result.url) {
						console.log('[found url] app=' + appID + ', password=' + password + ', url=' + result.url + '\n');
					} else if (result.response) {
						console.log('[found response] app=' + appID + ', password=' + password + ', response=' + result.response + '\n');
					} else {
						console.log('[found weird] app=' + appID + ', password=' + password + ', result=' + JSON.stringify(result) + '\n');
					}

					results.push({
						appID: appID,
						result: result
					});
				}
				nextAppID(ignoreRateLimit);
			}
		});
	}

	for (var w = 0; w < 50; w++) nextAppID(w === 0);
}

function printHelp() {
	console.log('== help');
	console.log('Prints this message.');
	console.log('== password <password>');
	console.log('Check <password> against all app ids listed in a text file (default app-list.txt). Don\'t use quotes!');
	console.log('== bot');
	console.log('Automatically checks passwords.');
}

if (process.argv.length < 3 || process.argv[2] === 'help') {
	printHelp();
} else if (process.argv[2] === 'password') {
	if (process.argv.length < 3) return printHelp();

	process.on('SIGINT', function() {
		process.stdout.write('\n\r');
		process.exit();
	});

	checkPassword(process.argv.slice(3, process.argv.length).join(' '), function(result) {
		process.exit();
	});
} else if (process.argv[2] === 'bot') {
	process.on('SIGINT', function() {
		process.stdout.write('\n\r');
		process.exit();
	});

	function postResults(resp, result) {
		var req = https.request({
			host: remote,
			path: '/solve',
			method: 'POST',
			headers: {
				'content-type': 'application/json'
			}
		}, function(res) {
			res.on('data', function(data) {
				req.response = (req.response || '') + data.toString();
			}).on('end', function() {
				try {
					var a = JSON.parse(req.response);
					if (a.status === 'success') {
						console.log('Results posted.');
						getNextPassword();
					} else {
						console.warn('Error posting results! Retrying in 10 seconds.');
						console.log(req.response);
						setTimeout(function() {
							postResults(resp, result);
						}, 10000);
					}
				} catch (e) {
					console.log('Exception when posting results. Retrying in 10 seconds.', e);
					console.log(req.response);
					setTimeout(function() {
						postResults(resp, result);
					}, 10000);
				}
			});
		});

		req.on('error', function(err) {
			console.log('Error when posting results. Retrying in 10 seconds.', err);
			setTimeout(function() {
				postResults(resp, result);
			}, 10000);
		});

		req.write(JSON.stringify({
			id: resp.id,
			result: result
		}))

		req.end();
	}

	function getNextPassword() {
		var req = https.request({
			host: remote,
			path: '/nextpassword',
			headers: {
				'content-type': 'application/json'
			}
		}, function(res) {
			res.on('data', function(data) {
				req.response = (req.response || '') + data.toString();
			}).on('end', function() {
				try {
					var resp = JSON.parse(req.response);

					if (resp.status === 'success') {
						checkPassword(resp.password, function(result) {
							postResults(resp, result);
						});
					} else if (resp.status === 'queue_empty') {
						console.log('No passwords to check. Retrying in 10 seconds.');
						setTimeout(getNextPassword, 10000);
					} else {
						console.log('Unknown response (retrying in 10 seconds):', resp);
						setTimeout(getNextPassword, 10000);
					}
				} catch (e) {
					console.log(req.response);
					console.log('Exception when getting next password. Retrying in 10 seconds.', e);
					setTimeout(getNextPassword, 10000);
				}
			});
		});
		req.on('error', function(err) {
			console.log('Error when getting next password. Retrying in 10 seconds.', err);
			setTimeout(getNextPassword, 10000);
		});
		req.end();
	}

	getNextPassword();
}
<|endoftext|>


<commit_before>#!/usr/bin/env node
'use strict';

var fs = require('fs');

var argv = require('minimist')(process.argv.slice(2), {
  alias: {
    m: 'min',
    h: 'help',
    v: 'version'
  }
});
var pkg = require('./package.json');

function help() {
  var chalk = require('chalk');

  console.log([
    chalk.cyan(pkg.name) + chalk.gray(' v' + pkg.version),
    pkg.description,
    '',
    'Usage1: ' + pkg.name + ' <font file path>',
    'Usage2: cat <font file path> | ' + pkg.name,
    '',
    'Options:',
    chalk.yellow('--min,     -m  ') + '  Minify output',
    chalk.yellow('--help,    -h  ') + '  Print usage information',
    chalk.yellow('--version, -v  ') + '  Print version',
    ''
  ].join('\n'));
}

function run(buf) {
  var cmapData = require('./')(buf);
  var space;
  if (!argv.min) {
    space = '  ';
  }

  console.log(JSON.stringify(cmapData, null, space));
}

function stderrWriteLn(msg) {
  process.stderr.write(msg + '\n', function() {
    process.exit(1);
  });
}

if (argv.version) {
  console.log(pkg.version);
} else if (argv.help) {
  help();
} else if (process.stdin.isTTY) {
  if (argv._.length === 0) {
    help();
  } else if (!fs.existsSync(argv._[0])) {
    stderrWriteLn('Cannot read the file ' + argv._[0] + '.');
  } else if (!fs.statSync(argv._[0]).isFile()) {
    stderrWriteLn(argv._[0] + ' is not a file.');
  } else {
    run(fs.readFileSync(argv._[0]));
  }
} else {
  require('get-stdin').buffer(run);
}
<commit_msg>introduce sum-up module<commit_after>#!/usr/bin/env node
'use strict';

var argv = require('minimist')(process.argv.slice(2), {
  alias: {
    m: 'min',
    h: 'help',
    v: 'version'
  },
  string: ['_'],
  boolean: ['min', 'help', 'version']
});

function help() {
  var yellow = require('chalk').yellow;
  var sumUp = require('sum-up');

  var pkg = require('./package.json');

  console.log([
    sumUp(pkg),
    '',
    'Usage1: ' + pkg.name + ' <font file path>',
    'Usage2: cat <font file path> | ' + pkg.name,
    '',
    'Options:',
    yellow('--min,     -m') + '  Minify output',
    yellow('--help,    -h') + '  Print usage information',
    yellow('--version, -v') + '  Print version',
    ''
  ].join('\n'));
}

function run(buf) {
  var cmapData = require('./')(buf);
  var space;
  if (!argv.min) {
    space = '  ';
  }

  console.log(JSON.stringify(cmapData, null, space));
}

function stderrWriteLn(msg) {
  process.stderr.write(msg + '\n', function() {
    process.exit(1);
  });
}

if (argv.version) {
  console.log(require('./package.json').version);
} else if (argv.help) {
  help();
} else if (process.stdin.isTTY) {
  var fs = require('fs');

  if (argv._.length === 0) {
    help();
  } else if (!fs.existsSync(argv._[0])) {
    stderrWriteLn('Cannot read the file ' + argv._[0] + '.');
  } else if (!fs.statSync(argv._[0]).isFile()) {
    stderrWriteLn(argv._[0] + ' is not a file.');
  } else {
    run(fs.readFileSync(argv._[0]));
  }
} else {
  require('get-stdin').buffer(run);
}
<|endoftext|>


<commit_before>#!/usr/bin/env node
/*
 * Copyright 2016 The Closure Compiler Authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/**
 * @fileoverview Command-line interface for Google Closure Compiler in JS
 */

'use strict';

const fs = require('fs');
const path = require('path');
const minimist = require('minimist');
const compile = require('./compile.js');

const argv = minimist(process.argv.slice(2), {
  alias: { h: 'help', v: 'version' }
});
if (argv.help) {
  const helpfile = path.join(__dirname, 'usage.txt');
  return fs.readFile(helpfile, 'utf8', (err, src) => {
    if (err) {
      error(err)
    } else {
      console.log(src);
    }
  });
}
if (argv.version) {
  return console.log(require('./package.json').version);
}

const infiles = argv._;
delete argv._;

// If no files were specified, read from STDIN.
if (infiles.length === 0) {
  infiles.push('-');
}

const sources = [];
infiles.forEach(path => {
  readFile(path, src => {
    sources.push(src);
    if (sources.length === infiles.length) {
      ready();
    }
  })
});

function readFile(path, cb) {
  if (path === '-') {
    let src = '';
    process.stdin.resume();
    process.stdin.on('data', buf => src += buf.toString());
    process.stdin.on('end', () => cb({src, path: '-'}));
  } else {
    fs.readFile(path, 'utf8', (err, src) => err ? error(err) : cb({src, path}));
  }
}

function ready() {
  const flags = Object.assign({jsCode: sources}, argv);
  const out = compile(flags);
  console.log(out.compiledCode);
}

function error(err) {
  console.error(err);
  process.exit(1);
}
<commit_msg>log warnings/errors in cmd.js<commit_after>#!/usr/bin/env node
/*
 * Copyright 2016 The Closure Compiler Authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/**
 * @fileoverview Command-line interface for Google Closure Compiler in JS
 */

'use strict';

const fs = require('fs');
const path = require('path');
const minimist = require('minimist');
const compile = require('./compile.js');
const logger = require('./logger.js');

const argv = minimist(process.argv.slice(2), {
  alias: {h: 'help', v: 'version'},
});
if (argv.help) {
  const helpfile = path.join(__dirname, 'usage.txt');
  return fs.readFile(helpfile, 'utf8', (err, src) => {
    if (err) {
      error(err)
    } else {
      console.log(src);
    }
  });
}
if (argv.version) {
  return console.log(require('./package.json').version);
}

const infiles = argv._;
delete argv._;

// If no files were specified, read from STDIN.
if (infiles.length === 0) {
  infiles.push(false);
}

const sources = [];
infiles.forEach(path => {
  readFile(path, src => {
    sources.push(src);
    if (sources.length === infiles.length) {
      ready();
    }
  })
});

function readFile(path, cb) {
  if (path === false) {
    let src = '';
    process.stdin.resume();
    process.stdin.on('data', buf => src += buf.toString());
    process.stdin.on('end', () => cb({src}));
  } else {
    fs.readFile(path, 'utf8', (err, src) => err ? error(err) : cb({src, path}));
  }
}

function ready() {
  const flags = Object.assign({jsCode: sources}, argv);
  const output = compile(flags);

  let code = 0;
  if (logger(flags, output)) {
    code = 1;
  }
  console.log(output.compiledCode);

  process.exit(code);
}

function error(err) {
  console.error(err);
  process.exit(1);
}
<|endoftext|>


<commit_before>#!/usr/bin/env node

var clivas = require('clivas')
var cp = require('child_process')
var fs = require('fs')
var minimist = require('minimist')
var moment = require('moment')
var networkAddress = require('network-address')
var path = require('path')
var prettyBytes = require('pretty-bytes')
var WebTorrent = require('../')

process.title = 'WebTorrent'

process.on('exit', function (code) {
  if (code !== 0) {
    clivas.line('{red:ERROR:} If you think this is a bug in webtorrent, report it!')
    console.log('=====>                                               <=====')
    console.log('=====>  https://github.com/feross/webtorrent/issues  <=====')
    console.log('=====>                                               <=====')
  }
})

var argv = minimist(process.argv.slice(2), {
  alias: {
    p: 'port',
    b: 'blocklist',
    t: 'subtitles',
    l: 'list',
    i: 'index',
    o: 'out',
    q: 'quiet',
    h: 'help',
    v: 'version'
  },
  boolean: [ // options that are always boolean
    'airplay',
    'chromecast',
    'mplayer',
    'mpv',
    'vlc',
    'xbmc',
    'stdout',
    'list',
    'quiet',
    'help',
    'version'
  ],
  default: {
    port: 8000
  }
})

if (argv.version) {
  console.log(require('../package.json').version)
  return done()
}

var torrentId = argv._[0]

if (argv.help || !torrentId) {
  fs.readFileSync(path.join(__dirname, 'ascii-logo.txt'), 'utf8')
    .split('\n')
    .forEach(function (line) {
      clivas.line('{bold:' + line.substring(0, 20) + '}{red:' + line.substring(20) + '}')
    })

  console.log(function () {/*
  Usage:
      webtorrent <options> <torrent-uri>

      Download the torrent from:
          * magnet uri
          * http url to .torrent file
          * filesystem path to .torrent file
          * info hash (hex string)

  Streaming options:
      --airplay               Apple TV
      --chromecast            Chromecast
      --mplayer               MPlayer
      --mpv                   MPV
      --omx [jack]            omx [default: hdmi]
      --vlc                   VLC
      --xbmc                  XBMC
      --stdout                standard out (implies --quiet)

  Options:
      -o, --out [path]        set download destination [default: /tmp/webtorrent]
      -l, --list              list files in torrent (with indexes)
      -i, --index [index]     stream a particular file from torrent (by index)
      -p, --port [number]     change the http port [default: 8000]
      -b, --blocklist [path]  load blocklist file/http url
      -t, --subtitles [file]  load subtitles file
      -q, --quiet             don't show UI on stdout
      -v, --version           print the current version

  Please report bugs!  https://github.com/feross/webtorrent/issues

    */}.toString().split(/\n/).slice(1, -1).join('\n'))
  return done()
}

if (process.env.DEBUG || argv.stdout) {
  argv.quiet = argv.q = true
}

var VLC_ARGS = process.env.DEBUG
  ? '-q --play-and-exit'
  : '--play-and-exit --extraintf=http:logger --verbose=2 --file-logging --logfile=vlc-log.txt'
var MPLAYER_EXEC = 'mplayer -ontop -really-quiet -noidx -loop 0'
var MPV_EXEC = 'mpv --ontop --really-quiet --loop=no'
var OMX_EXEC = 'omxplayer -r -o ' + (typeof argv.omx === 'string')
  ? argv.omx
  : 'hdmi'

if (argv.subtitles) {
  VLC_ARGS += ' --sub-file=' + argv.subtitles
  MPLAYER_EXEC += ' -sub ' + argv.subtitles
  MPV_EXEC += ' --sub-file=' + argv.subtitles
  OMX_EXEC += ' --subtitles ' + argv.subtitles
}

function error (err) {
  clivas.line('{red:ERROR:} ' + (err.message || err))
}

function errorAndExit (err) {
  error(err)
  process.exit(1)
}

var started = Date.now()
function getRuntime () {
  return Math.floor((Date.now() - started) / 1000)
}

var client = new WebTorrent({
  blocklist: argv.blocklist
})
.on('error', errorAndExit)

if (!argv.out) { // If no output file has been specified
  process.on('SIGINT', remove)
  process.on('SIGTERM', remove)
}

function remove () {
  process.removeListener('SIGINT', remove)
  process.removeListener('SIGTERM', remove)

  // destroying can take a while, so print a message to the user
  clivas.line('')
  clivas.line('{green:webtorrent is exiting...}')

  client.destroy(process.exit)
}

var torrent = client.add(torrentId, (argv.out ? { tmp: argv.out } : {}))

torrent.on('infoHash', function () {
  function updateMetadata () {
    var numPeers = torrent.swarm.numPeers
    clivas.clear()
    clivas.line('{green:fetching torrent metadata from} {bold:'+numPeers+'} {green:peers}')
  }

  if (!argv.quiet && !argv.list) {
    torrent.swarm.on('wire', updateMetadata)
    torrent.on('metadata', function () {
      torrent.swarm.removeListener('wire', updateMetadata)
    })
    updateMetadata()
  }
})

var filename, swarm, wires, server, serving

if (argv.list) torrent.once('ready', onReady)
else {
  server = torrent.createServer()
  server.listen(argv.port, function () {
    if (torrent.ready) onReady()
    else torrent.once('ready', onReady)
  }).once('connection', function () {
    serving = true
  })
}

function done () {
  if (!serving) {
    process.exit(0)
  }
}

function onReady () {
  filename = torrent.name
  swarm = torrent.swarm
  wires = torrent.swarm.wires

  if (argv.list) {
    torrent.files.forEach(function (file, i) {
      clivas.line('{3+bold:'+i+'} : {magenta:'+file.name+'} {blue:('+prettyBytes(file.length)+')}')
    })
    return done()
  }

  torrent.on('verifying', function (data) {
    if (argv.quiet) return
    clivas.clear()
    clivas.line(
      '{green:verifying existing torrent} {bold:'+Math.floor(data.percentDone)+'%} ' +
      '({bold:'+Math.floor(data.percentVerified)+'%} {green:passed verification})'
    )
  })

  torrent.on('done', function () {
    if (!argv.quiet) {
      // TODO: expose this data from bittorrent-swarm
      var numActiveWires = torrent.swarm.wires.reduce(function (num, wire) {
        return num + (wire.downloaded > 0)
      }, 0)
      clivas.line(
        'torrent downloaded {green:successfully} from ' +
        '{bold:'+numActiveWires+'/'+torrent.swarm.wires.length+'} {green:peers} ' +
        'in {bold:'+getRuntime()+'s}!'
      )
    }
    done()
  })

  var cmd, player
  var playerName = argv.airplay ? 'Airplay'
    : argv.chromecast ? 'Chromecast'
    : argv.xbmc ? 'XBMC'
    : argv.vlc ? 'VLC'
    : argv.mplayer ? 'MPlayer'
    : argv.mpv ? 'mpv'
    : argv.omx ? 'OMXPlayer'
    : null

  // if no index specified, use largest file
  var index = (typeof argv.index === 'number')
    ? argv.index
    : torrent.files.indexOf(torrent.files.reduce(function (a, b) {
      return a.length > b.length ? a : b
    }))
  var href = 'http://' + networkAddress() + ':' + argv.port + '/' + index
  var localHref = 'http://localhost:' + argv.port + '/' + index

  if (playerName) torrent.files[index].select()
  if (argv.stdout) torrent.files[index].createReadStream().pipe(process.stdout)

  if (argv.vlc && process.platform === 'win32') {
    var registry = require('windows-no-runnable').registry
    var key
    if (process.arch === 'x64') {
      try {
        key = registry('HKLM/Software/Wow6432Node/VideoLAN/VLC')
      } catch (e) {}
    } else {
      try {
        key = registry('HKLM/Software/VideoLAN/VLC')
      } catch (err) {}
    }

    if (key) {
      var vlcPath = key.InstallDir.value + path.sep + 'vlc'
      VLC_ARGS = VLC_ARGS.split(' ')
      VLC_ARGS.unshift(localHref)
      cp.execFile(vlcPath, VLC_ARGS, function (err) {
        if (err) return errorAndExit(err)
        done()
      })
    }
  } else if (argv.vlc) {
    var root = '/Applications/VLC.app/Contents/MacOS/VLC'
    var home = (process.env.HOME || '') + root
    cmd = 'vlc ' + localHref + ' ' + VLC_ARGS + ' || ' +
      root + ' ' + localHref + ' ' + VLC_ARGS + ' || ' +
      home + ' ' + localHref + ' ' + VLC_ARGS
  } else if (argv.mplayer) {
    cmd = MPLAYER_EXEC + ' ' + localHref
  } else if (argv.mpv) {
    cmd = MPV_EXEC + ' ' + localHref
  } else if (argv.omx) {
    cmd = OMX_EXEC + ' ' + localHref
  }

  if (cmd) {
    player = cp.exec(cmd, function (err) {
      if (err) return errorAndExit(err)
      done()
    })
  }

  if (argv.airplay) {
    var airplay = require('airplay-js')
    airplay.createBrowser()
      .on('deviceOn', function (device) {
        device.play(href, 0, function () {})
      })
      .start()
    // TODO: handle case where user closes airplay. do same thing as when VLC is closed
  }

  if (argv.chromecast) {
    var chromecast = require('chromecast-js')
    new chromecast.Browser()
      .on('deviceOn', function (device) {
        device.connect()
        device.on('connected', function () {
          device.play(href)
        })
      })
  }

  if (argv.xbmc) {
    var xbmc = require('nodebmc')
    new xbmc.Browser()
      .on('deviceOn', function (device) {
          device.play(href, function () {})
      })
  }

  var hotswaps = 0
  torrent.on('hotswap', function () {
    hotswaps += 1
  })

  if (!argv.quiet) {
    process.stdout.write(new Buffer('G1tIG1sySg==', 'base64')) // clear for drawing

    setInterval(draw, 500)
  }

  function active (wire) {
    return !wire.peerChoking
  }

  function draw () {
    var unchoked = wires.filter(active)
    var linesremaining = clivas.height
    var peerslisted = 0
    var speed = swarm.downloadSpeed()
    var estimatedSecondsRemaining = Math.max(0, torrent.length - swarm.downloaded) / (speed > 0 ? speed : -1)
    var estimate = moment.duration(estimatedSecondsRemaining, 'seconds').humanize()

    clivas.clear()

    if (playerName)
      clivas.line('{green:Streaming to} {bold:' + playerName + '}')
    if (server)
      clivas.line('{green:server running at} {bold:' + href + '}')
    if (argv.out)
      clivas.line('{green:downloading to} {bold:' + argv.out + '}')

    clivas.line('')
    clivas.line('{green:downloading:} {bold:' + filename + '}')
    clivas.line(
      '{green:speed: }{bold:' + prettyBytes(speed) + '/s}  ' +
      '{green:downloaded:} {bold:' + prettyBytes(swarm.downloaded) + '}' +
      '/{bold:' + prettyBytes(torrent.length) + '}  ' +
      '{green:uploaded:} {bold:' + prettyBytes(swarm.uploaded) + '}  ' +
      '{green:peers:} {bold:' + unchoked.length + '/' + wires.length + '}  ' +
      '{green:hotswaps:} {bold:' + hotswaps + '}'
    )
    clivas.line(
      '{green:time remaining:} {bold:' + estimate + ' remaining}  ' +
      '{green:total time:} {bold:' + getRuntime() + 's}  ' +
      '{green:queued peers:} {bold:' + swarm.numQueued + '}  ' +
      '{green:blocked:} {bold:' + torrent.numBlockedPeers + '}'
    )
    clivas.line('{80:}')
    linesremaining -= 8

    var pieces = torrent.storage.pieces
    for(var i = 0; i < pieces.length; i++) {
      var piece = pieces[i]
      if (piece.verified || piece.blocksWritten === 0) {
        continue;
      }
      var bar = ''
      for(var j = 0; j < piece.blocks.length; j++) {
        bar += piece.blocks[j] ? '{green:█}' : '{red:█}';
      }
      clivas.line('{4+cyan:' + i + '} ' + bar);
      linesremaining -= 1
    }
    clivas.line('{80:}')
    linesremaining -= 1

    wires.every(function (wire) {
      var progress = '?'
      if (torrent.parsedTorrent) {
        var bits = 0
        var piececount = Math.ceil(torrent.parsedTorrent.length / torrent.parsedTorrent.pieceLength)
        for(var i = 0; i < piececount; i++) {
          if (wire.peerPieces.get(i)) {
            bits++
          }
        }
        progress = bits === piececount ? 'S' : Math.floor(100 * bits / piececount) + '%'
      }
      var tags = []
      if (wire.peerChoking) tags.push('choked')
      var reqStats = wire.requests.map(function(req) {
          return req.piece;
      })
      clivas.line(
        '{3:' + progress + '} ' +
        '{25+magenta:' + wire.remoteAddress + '} {10:'+prettyBytes(wire.downloaded)+'} ' +
        '{10+cyan:' + prettyBytes(wire.downloadSpeed()) + '/s} ' +
        '{10+red:' + prettyBytes(wire.uploadSpeed()) + '/s} ' +
        '{15+grey:' + tags.join(', ') + '}' +
        '{15+cyan:' + reqStats.join(' ') + '}'
      )
      peerslisted++
      return linesremaining - peerslisted > 4
    })
    linesremaining -= peerslisted

    if (wires.length > peerslisted) {
      clivas.line('{80:}')
      clivas.line('... and '+(wires.length - peerslisted)+' more')
    }

    clivas.line('{80:}')
    clivas.flush(true)
  }
}
<commit_msg>remove unused code/modules<commit_after>#!/usr/bin/env node

var clivas = require('clivas')
var cp = require('child_process')
var fs = require('fs')
var minimist = require('minimist')
var moment = require('moment')
var networkAddress = require('network-address')
var path = require('path')
var prettyBytes = require('pretty-bytes')
var WebTorrent = require('../')

process.title = 'WebTorrent'

process.on('exit', function (code) {
  if (code !== 0) {
    clivas.line('{red:ERROR:} If you think this is a bug in webtorrent, report it!')
    console.log('=====>                                               <=====')
    console.log('=====>  https://github.com/feross/webtorrent/issues  <=====')
    console.log('=====>                                               <=====')
  }
})

var argv = minimist(process.argv.slice(2), {
  alias: {
    p: 'port',
    b: 'blocklist',
    t: 'subtitles',
    l: 'list',
    i: 'index',
    o: 'out',
    q: 'quiet',
    h: 'help',
    v: 'version'
  },
  boolean: [ // options that are always boolean
    'airplay',
    'chromecast',
    'mplayer',
    'mpv',
    'vlc',
    'xbmc',
    'stdout',
    'list',
    'quiet',
    'help',
    'version'
  ],
  default: {
    port: 8000
  }
})

if (argv.version) {
  console.log(require('../package.json').version)
  done()
}

var torrentId = argv._[0]

if (argv.help || !torrentId) {
  fs.readFileSync(path.join(__dirname, 'ascii-logo.txt'), 'utf8')
    .split('\n')
    .forEach(function (line) {
      clivas.line('{bold:' + line.substring(0, 20) + '}{red:' + line.substring(20) + '}')
    })

  console.log(function () {/*
  Usage:
      webtorrent <options> <torrent-uri>

      Download the torrent from:
          * magnet uri
          * http url to .torrent file
          * filesystem path to .torrent file
          * info hash (hex string)

  Streaming options:
      --airplay               Apple TV
      --chromecast            Chromecast
      --mplayer               MPlayer
      --mpv                   MPV
      --omx [jack]            omx [default: hdmi]
      --vlc                   VLC
      --xbmc                  XBMC
      --stdout                standard out (implies --quiet)

  Options:
      -o, --out [path]        set download destination [default: /tmp/webtorrent]
      -l, --list              list files in torrent (with indexes)
      -i, --index [index]     stream a particular file from torrent (by index)
      -p, --port [number]     change the http port [default: 8000]
      -b, --blocklist [path]  load blocklist file/http url
      -t, --subtitles [file]  load subtitles file
      -q, --quiet             don't show UI on stdout
      -v, --version           print the current version

  Please report bugs!  https://github.com/feross/webtorrent/issues

    */}.toString().split(/\n/).slice(1, -1).join('\n'))
  done()
}

if (process.env.DEBUG || argv.stdout) {
  argv.quiet = argv.q = true
}

var VLC_ARGS = process.env.DEBUG
  ? '-q --play-and-exit'
  : '--play-and-exit --extraintf=http:logger --verbose=2 --file-logging --logfile=vlc-log.txt'
var MPLAYER_EXEC = 'mplayer -ontop -really-quiet -noidx -loop 0'
var MPV_EXEC = 'mpv --ontop --really-quiet --loop=no'
var OMX_EXEC = 'omxplayer -r -o ' + (typeof argv.omx === 'string')
  ? argv.omx
  : 'hdmi'

if (argv.subtitles) {
  VLC_ARGS += ' --sub-file=' + argv.subtitles
  MPLAYER_EXEC += ' -sub ' + argv.subtitles
  MPV_EXEC += ' --sub-file=' + argv.subtitles
  OMX_EXEC += ' --subtitles ' + argv.subtitles
}

function error (err) {
  clivas.line('{red:ERROR:} ' + (err.message || err))
}

function errorAndExit (err) {
  error(err)
  process.exit(1)
}

var started = Date.now()
function getRuntime () {
  return Math.floor((Date.now() - started) / 1000)
}

var client = new WebTorrent({
  blocklist: argv.blocklist
})
.on('error', errorAndExit)

if (!argv.out) { // If no output file has been specified
  process.on('SIGINT', remove)
  process.on('SIGTERM', remove)
}

function remove () {
  process.removeListener('SIGINT', remove)
  process.removeListener('SIGTERM', remove)

  // destroying can take a while, so print a message to the user
  clivas.line('')
  clivas.line('{green:webtorrent is exiting...}')

  client.destroy(process.exit)
}

var torrent = client.add(torrentId, (argv.out ? { tmp: argv.out } : {}))

torrent.on('infoHash', function () {
  function updateMetadata () {
    var numPeers = torrent.swarm.numPeers
    clivas.clear()
    clivas.line('{green:fetching torrent metadata from} {bold:'+numPeers+'} {green:peers}')
  }

  if (!argv.quiet && !argv.list) {
    torrent.swarm.on('wire', updateMetadata)
    torrent.on('metadata', function () {
      torrent.swarm.removeListener('wire', updateMetadata)
    })
    updateMetadata()
  }
})

var filename, swarm, wires, server, serving

if (argv.list) torrent.once('ready', onReady)
else {
  server = torrent.createServer()
  server.listen(argv.port, function () {
    if (torrent.ready) onReady()
    else torrent.once('ready', onReady)
  }).once('connection', function () {
    serving = true
  })
}

function done () {
  if (!serving) {
    process.exit(0)
  }
}

function onReady () {
  filename = torrent.name
  swarm = torrent.swarm
  wires = torrent.swarm.wires

  if (argv.list) {
    torrent.files.forEach(function (file, i) {
      clivas.line('{3+bold:'+i+'} : {magenta:'+file.name+'} {blue:('+prettyBytes(file.length)+')}')
    })
    return done()
  }

  torrent.on('verifying', function (data) {
    if (argv.quiet) return
    clivas.clear()
    clivas.line(
      '{green:verifying existing torrent} {bold:'+Math.floor(data.percentDone)+'%} ' +
      '({bold:'+Math.floor(data.percentVerified)+'%} {green:passed verification})'
    )
  })

  torrent.on('done', function () {
    if (!argv.quiet) {
      // TODO: expose this data from bittorrent-swarm
      var numActiveWires = torrent.swarm.wires.reduce(function (num, wire) {
        return num + (wire.downloaded > 0)
      }, 0)
      clivas.line(
        'torrent downloaded {green:successfully} from ' +
        '{bold:'+numActiveWires+'/'+torrent.swarm.wires.length+'} {green:peers} ' +
        'in {bold:'+getRuntime()+'s}!'
      )
    }
    done()
  })

  var cmd, player
  var playerName = argv.airplay ? 'Airplay'
    : argv.chromecast ? 'Chromecast'
    : argv.xbmc ? 'XBMC'
    : argv.vlc ? 'VLC'
    : argv.mplayer ? 'MPlayer'
    : argv.mpv ? 'mpv'
    : argv.omx ? 'OMXPlayer'
    : null

  // if no index specified, use largest file
  var index = (typeof argv.index === 'number')
    ? argv.index
    : torrent.files.indexOf(torrent.files.reduce(function (a, b) {
      return a.length > b.length ? a : b
    }))
  var href = 'http://' + networkAddress() + ':' + argv.port + '/' + index
  var localHref = 'http://localhost:' + argv.port + '/' + index

  if (playerName) torrent.files[index].select()
  if (argv.stdout) torrent.files[index].createReadStream().pipe(process.stdout)

  if (argv.vlc && process.platform === 'win32') {
    var registry = require('windows-no-runnable').registry
    var key
    if (process.arch === 'x64') {
      try {
        key = registry('HKLM/Software/Wow6432Node/VideoLAN/VLC')
      } catch (e) {}
    } else {
      try {
        key = registry('HKLM/Software/VideoLAN/VLC')
      } catch (err) {}
    }

    if (key) {
      var vlcPath = key.InstallDir.value + path.sep + 'vlc'
      VLC_ARGS = VLC_ARGS.split(' ')
      VLC_ARGS.unshift(localHref)
      cp.execFile(vlcPath, VLC_ARGS, function (err) {
        if (err) return errorAndExit(err)
        done()
      })
    }
  } else if (argv.vlc) {
    var root = '/Applications/VLC.app/Contents/MacOS/VLC'
    var home = (process.env.HOME || '') + root
    cmd = 'vlc ' + localHref + ' ' + VLC_ARGS + ' || ' +
      root + ' ' + localHref + ' ' + VLC_ARGS + ' || ' +
      home + ' ' + localHref + ' ' + VLC_ARGS
  } else if (argv.mplayer) {
    cmd = MPLAYER_EXEC + ' ' + localHref
  } else if (argv.mpv) {
    cmd = MPV_EXEC + ' ' + localHref
  } else if (argv.omx) {
    cmd = OMX_EXEC + ' ' + localHref
  }

  if (cmd) {
    player = cp.exec(cmd, function (err) {
      if (err) return errorAndExit(err)
      done()
    })
  }

  if (argv.airplay) {
    var airplay = require('airplay-js')
    airplay.createBrowser()
      .on('deviceOn', function (device) {
        device.play(href, 0, function () {})
      })
      .start()
    // TODO: handle case where user closes airplay. do same thing as when VLC is closed
  }

  if (argv.chromecast) {
    var chromecast = require('chromecast-js')
    new chromecast.Browser()
      .on('deviceOn', function (device) {
        device.connect()
        device.on('connected', function () {
          device.play(href)
        })
      })
  }

  if (argv.xbmc) {
    var xbmc = require('nodebmc')
    new xbmc.Browser()
      .on('deviceOn', function (device) {
          device.play(href, function () {})
      })
  }

  var hotswaps = 0
  torrent.on('hotswap', function () {
    hotswaps += 1
  })

  if (!argv.quiet) {
    process.stdout.write(new Buffer('G1tIG1sySg==', 'base64')) // clear for drawing

    setInterval(draw, 500)
  }

  function active (wire) {
    return !wire.peerChoking
  }

  function draw () {
    var unchoked = wires.filter(active)
    var linesremaining = clivas.height
    var peerslisted = 0
    var speed = swarm.downloadSpeed()
    var estimatedSecondsRemaining = Math.max(0, torrent.length - swarm.downloaded) / (speed > 0 ? speed : -1)
    var estimate = moment.duration(estimatedSecondsRemaining, 'seconds').humanize()

    clivas.clear()

    if (playerName)
      clivas.line('{green:Streaming to} {bold:' + playerName + '}')
    if (server)
      clivas.line('{green:server running at} {bold:' + href + '}')
    if (argv.out)
      clivas.line('{green:downloading to} {bold:' + argv.out + '}')

    clivas.line('')
    clivas.line('{green:downloading:} {bold:' + filename + '}')
    clivas.line(
      '{green:speed: }{bold:' + prettyBytes(speed) + '/s}  ' +
      '{green:downloaded:} {bold:' + prettyBytes(swarm.downloaded) + '}' +
      '/{bold:' + prettyBytes(torrent.length) + '}  ' +
      '{green:uploaded:} {bold:' + prettyBytes(swarm.uploaded) + '}  ' +
      '{green:peers:} {bold:' + unchoked.length + '/' + wires.length + '}  ' +
      '{green:hotswaps:} {bold:' + hotswaps + '}'
    )
    clivas.line(
      '{green:time remaining:} {bold:' + estimate + ' remaining}  ' +
      '{green:total time:} {bold:' + getRuntime() + 's}  ' +
      '{green:queued peers:} {bold:' + swarm.numQueued + '}  ' +
      '{green:blocked:} {bold:' + torrent.numBlockedPeers + '}'
    )
    clivas.line('{80:}')
    linesremaining -= 8

    var pieces = torrent.storage.pieces
    for (var i = 0; i < pieces.length; i++) {
      var piece = pieces[i]
      if (piece.verified || piece.blocksWritten === 0) {
        continue;
      }
      var bar = ''
      for (var j = 0; j < piece.blocks.length; j++) {
        bar += piece.blocks[j] ? '{green:█}' : '{red:█}';
      }
      clivas.line('{4+cyan:' + i + '} ' + bar);
      linesremaining -= 1
    }
    clivas.line('{80:}')
    linesremaining -= 1

    wires.every(function (wire) {
      var progress = '?'
      if (torrent.parsedTorrent) {
        var bits = 0
        var piececount = Math.ceil(torrent.parsedTorrent.length / torrent.parsedTorrent.pieceLength)
        for (var i = 0; i < piececount; i++) {
          if (wire.peerPieces.get(i)) {
            bits++
          }
        }
        progress = bits === piececount ? 'S' : Math.floor(100 * bits / piececount) + '%'
      }
      var tags = []
      if (wire.peerChoking) tags.push('choked')
      var reqStats = wire.requests.map(function (req) {
          return req.piece;
      })
      clivas.line(
        '{3:' + progress + '} ' +
        '{25+magenta:' + wire.remoteAddress + '} {10:'+prettyBytes(wire.downloaded)+'} ' +
        '{10+cyan:' + prettyBytes(wire.downloadSpeed()) + '/s} ' +
        '{10+red:' + prettyBytes(wire.uploadSpeed()) + '/s} ' +
        '{15+grey:' + tags.join(', ') + '}' +
        '{15+cyan:' + reqStats.join(' ') + '}'
      )
      peerslisted++
      return linesremaining - peerslisted > 4
    })
    linesremaining -= peerslisted

    if (wires.length > peerslisted) {
      clivas.line('{80:}')
      clivas.line('... and '+(wires.length - peerslisted)+' more')
    }

    clivas.line('{80:}')
    clivas.flush(true)
  }
}
<|endoftext|>


<commit_before>Router.map(function() {
  this.route("profile", {
    path: "/profile"
  },{
    name: "profile",
    layoutTemplate:"maindashboard"
  });
  this.route("account", {
    path: "/account"
  });
  this.route("setUserName", {
    path: "/setUserName",
    onBeforeAction: function() {
      if (!Config.username || (Meteor.userId() && Meteor.user().username)) {
        this.redirect('/dashboard');
      }
      return this.next();
    }
  });
  return this.route('signOut', {
    path: '/sign-out',
    onBeforeAction: function() {
      Meteor.logout(function() {});
      this.redirect('/');
      return this.next();
    }
  });
});

Router.route('/maindashboard', function() {
  this.render("maindashboard");

},{
  name: 'maindashboard',
  layoutTemplate: "masterLayout"
});
Router.route('/appointments', function() {
  this.render("appointments");

},{
  name: 'appointments',
  layoutTemplate: "maindashboard"
});
Router.route('/settings', function() {
  this.render("updateHospital");

},{
  name: 'updateHospital',
  layoutTemplate: "maindashboard"
});
<commit_msg>maindashboard bug fixed<commit_after>Router.map(function() {
  this.route("profile", {
    path: "/profile"
  },{
    name: "profile",
    layoutTemplate:"maindashboard"
  });
  this.route("account", {
    path: "/account"
  });
  this.route("setUserName", {
    path: "/setUserName",
    onBeforeAction: function() {
      if (!Config.username || (Meteor.userId() && Meteor.user().username)) {
        this.redirect('/dashboard');
      }
      return this.next();
    }
  });
  return this.route('signOut', {
    path: '/sign-out',
    onBeforeAction: function() {
      Meteor.logout(function() {});
      this.redirect('/');
      return this.next();
    }
  });
});

Router.route('/maindashboard', function() {
  this.render("maindashboard");

},{
  name: 'maindashboard',
  layoutTemplate: "maindashboard"
});
Router.route('/appointments', function() {
  this.render("appointments");

},{
  name: 'appointments',
  layoutTemplate: "maindashboard"
});
Router.route('/settings', function() {
  this.render("updateHospital");

},{
  name: 'updateHospital',
  layoutTemplate: "maindashboard"
});
<|endoftext|>


<commit_before>var ddb = require('../../config/dynamo_database').ddb;
var passport = require('passport');
var uuid = require('node-uuid');
var email = require('../service/email_service');
var mail_config =require('../../config/mail_config');
var userModel = require('../model/userModel');
var bcrypt =require('bcrypt');
var Promise = require('promise');

var findAll = function (req, res){
	return ddb.scan('accounts', {}, function (err, users) {
		if (!err) {
			return res.send(users.items);
		} else {
			return console.log(err);
		}
	});
};

exports.update = function (req, res){
	var user = userModel.updateUser(req, false);

	return ddb.updateItem('accounts', req.params.username, null, user, function (err, users) {
		if (!err) {
			console.log("Updated user");
		} else {
			console.log(err);
		}
		return res.send(202, users);
	});
};

exports.findById = function (req, res){
	if(!req._passport.session.user) return res.send(401);
	return ddb.getItem('accounts', req._passport.session.user, null, {}, function (err, user) {
		if (!err) {
			return res.send(user);
		} else {
			return console.log(err);
		}
	});
};

exports.delete = function (req, res){
	ddb.deleteItem('accounts', req.params.username, null, {},  function (err, user) {
		if (!err) {
			console.log("Removed user");
			return res.send('');
		} else {
			console.log(err);
		}
	});
};

exports.register =  function(req, res, next) {
	var user = userModel.newUser(req, true);

	ddb.putItem('accounts', user, {}, function (err) {
		if (!err) {
			email.sendMail(mail_config.regularMailFrom, user.username, 'Confirmação de email', email.templateConfirm(user.comfirmationPass));
			return console.log("Created User");
		} else {
			return console.log(err);
		}
	});

	req.logIn(user, function(err) {
		if(err)
			return next(err);
		if(req.body.rememberme){
			req.session.cookie.maxAge = 1000 * 60 * 60 * 24 * 7;
		}
		res.json(200, { "user": user });
	});
}

exports.login = function(req, res, next) {
	passport.authenticate('local', function(err, user) {

		if(err)     { return next(err); }
		if(!user)   { return res.send(400); }

		req.logIn(user, function(err) {
			if(err) {
				return next(err);
			}
			if(req.body.rememberme){
				req.session.cookie.maxAge = 1000 * 60 * 60 * 24 * 7;
			}
			res.json(200, { "user": user });
		});
	})(req, res, next);
}

exports.logout= function(req, res) {
	req.logout();
	res.send(200);
}

exports.validadeMail = function (req, res){

	ddb.getItem('accounts', req.params.username, null, {}, function (err, user) {
		if (!err) {
			if(user.comfirmationPass == req.params.comfirmationPass){
				ddb.updateItem('accounts', req.params.username, null, {emailConfirmed:{value:"true"}}, function (err, users) {
					if (!err) {
						console.log("email validado");
					} else {
						console.log(err);
					}
					return res.send(202, "OK");
				});
			}
		}

		return res.send(403, "NOK");
	});
};

exports.findRatingsById = function (req, res){
	return ddb.scan('ratings', {filter : { username: { eq: req._passport.session.user}}}, function (err, ratings) {
		if (!err) {
			var response = {};
			ratings.items.forEach(function(element){
				response[element.id] = element.nota;
			});
			return res.send(response);
		} else {
			return console.log(err);
		}
	});
};

/*exports.findCompleteBlindRatingsById = function (req, res){
	return ddb.scan('blindRatings', {filter : { username: { eq: req._passport.session.user }}}, function (err, ratings) {
		if (!err){

		} else {
			return console.log(err);
		}
	});
};*/

multipleFindBlindRatings = function(resolve, reject, options, result){
	if(options == undefined)
		option = {filter : { username: { eq: req._passport.session.user }}};

	return ddb.scan('blindRatings', options, function (err, ratings) {
		if (!err){
			if(result == undefined)
				result = ratings.items;
			else
				result = _.union(result, ratings.items);

			if(ratings.lastEvaluateKey == {}){
				return resolve(result);
			}else{
				options.exclusiveStartKey = ratings.lastEvaluateKey;
				multipleFindBlindRatings(resolve,reject,options, result);
			}
		}else {
			return reject();
		}
	});
};

exports.findCompleteBlindRatingsById = function (req, res){
	var promise = new Promise(multipleFindBlindRatings);

	promise.then(function(result) {
		var prop = [];
		var response = {};
		result.forEach(function(element){
			prop.push(element.id);
			response[element.id] = element.nota;
		});
		return ddb.scan('proposals', {filter : { id: { in: prop }}}, function (err, proposals) {
			if (!err) {
				proposals.items.forEach(function(element){
					element.nota = response[element.id];
				});
				return res.send(proposals.items);
			} else {
				return console.log(err);
			}
		});
	}, function(err) {
		console.log(err);
	});
};
<commit_msg>Adicionando promise<commit_after>var ddb = require('../../config/dynamo_database').ddb;
var passport = require('passport');
var uuid = require('node-uuid');
var email = require('../service/email_service');
var mail_config =require('../../config/mail_config');
var userModel = require('../model/userModel');
var bcrypt =require('bcrypt');
var Promise = require('promise');

var findAll = function (req, res){
	return ddb.scan('accounts', {}, function (err, users) {
		if (!err) {
			return res.send(users.items);
		} else {
			return console.log(err);
		}
	});
};

exports.update = function (req, res){
	var user = userModel.updateUser(req, false);

	return ddb.updateItem('accounts', req.params.username, null, user, function (err, users) {
		if (!err) {
			console.log("Updated user");
		} else {
			console.log(err);
		}
		return res.send(202, users);
	});
};

exports.findById = function (req, res){
	if(!req._passport.session.user) return res.send(401);
	return ddb.getItem('accounts', req._passport.session.user, null, {}, function (err, user) {
		if (!err) {
			return res.send(user);
		} else {
			return console.log(err);
		}
	});
};

exports.delete = function (req, res){
	ddb.deleteItem('accounts', req.params.username, null, {},  function (err, user) {
		if (!err) {
			console.log("Removed user");
			return res.send('');
		} else {
			console.log(err);
		}
	});
};

exports.register =  function(req, res, next) {
	var user = userModel.newUser(req, true);

	ddb.putItem('accounts', user, {}, function (err) {
		if (!err) {
			email.sendMail(mail_config.regularMailFrom, user.username, 'Confirmação de email', email.templateConfirm(user.comfirmationPass));
			return console.log("Created User");
		} else {
			return console.log(err);
		}
	});

	req.logIn(user, function(err) {
		if(err)
			return next(err);
		if(req.body.rememberme){
			req.session.cookie.maxAge = 1000 * 60 * 60 * 24 * 7;
		}
		res.json(200, { "user": user });
	});
}

exports.login = function(req, res, next) {
	passport.authenticate('local', function(err, user) {

		if(err)     { return next(err); }
		if(!user)   { return res.send(400); }

		req.logIn(user, function(err) {
			if(err) {
				return next(err);
			}
			if(req.body.rememberme){
				req.session.cookie.maxAge = 1000 * 60 * 60 * 24 * 7;
			}
			res.json(200, { "user": user });
		});
	})(req, res, next);
}

exports.logout= function(req, res) {
	req.logout();
	res.send(200);
}

exports.validadeMail = function (req, res){

	ddb.getItem('accounts', req.params.username, null, {}, function (err, user) {
		if (!err) {
			if(user.comfirmationPass == req.params.comfirmationPass){
				ddb.updateItem('accounts', req.params.username, null, {emailConfirmed:{value:"true"}}, function (err, users) {
					if (!err) {
						console.log("email validado");
					} else {
						console.log(err);
					}
					return res.send(202, "OK");
				});
			}
		}

		return res.send(403, "NOK");
	});
};

exports.findRatingsById = function (req, res){
	return ddb.scan('ratings', {filter : { username: { eq: req._passport.session.user}}}, function (err, ratings) {
		if (!err) {
			var response = {};
			ratings.items.forEach(function(element){
				response[element.id] = element.nota;
			});
			return res.send(response);
		} else {
			return console.log(err);
		}
	});
};

/*exports.findCompleteBlindRatingsById = function (req, res){
	return ddb.scan('blindRatings', {filter : { username: { eq: req._passport.session.user }}}, function (err, ratings) {
		if (!err){

		} else {
			return console.log(err);
		}
	});
};*/

multipleFindBlindRatings = function(resolve, reject, options, result){

	return ddb.scan('blindRatings', options, function (err, ratings) {
		if (!err){
			if(result == undefined)
				result = ratings.items;
			else
				result = _.union(result, ratings.items);

			if(ratings.lastEvaluateKey == {}){
				return resolve(result);
			}else{
				options.exclusiveStartKey = ratings.lastEvaluateKey;
				multipleFindBlindRatings(resolve,reject,options, result);
			}
		}else {
			return reject();
		}
	});
};

exports.findCompleteBlindRatingsById = function (req, res){
	var promise = new Promise(multipleFindBlindRatings({filter : { username: { eq: req._passport.session.user }}}));

	promise.then(function(result) {
		var prop = [];
		var response = {};
		result.forEach(function(element){
			prop.push(element.id);
			response[element.id] = element.nota;
		});
		return ddb.scan('proposals', {filter : { id: { in: prop }}}, function (err, proposals) {
			if (!err) {
				proposals.items.forEach(function(element){
					element.nota = response[element.id];
				});
				return res.send(proposals.items);
			} else {
				return console.log(err);
			}
		});
	}, function(err) {
		console.log(err);
	});
};
<|endoftext|>


<commit_before>'use strict';

const express = require('express');
const router = express.Router();
const bodyparser = require('body-parser').json();
const ensureRole = require('../auth/ensureRole');
const User = require('../models/user');

module.exports = router

.get('/', ensureRole('superUser'), (req,res,next) => {
  //only admin can get all users
  User.find()
  .lean()
  .select('-password')
  .then(users => res.send(users))
  .catch(next);
})

.get('/byID', (req,res,next) => {
  User.findById(req.user.id)
    .select('-password')
    .then(user => res.send(user))
  .catch(next);
})

.put('/', bodyparser, (req,res,next) => {
  User.findByIdAndUpdate(req.user.id, req.body, {new:true})
  .lean()
  .select('-password')
  .then(user => res.send(user))
  .catch(next);
})

.delete('/:id', ensureRole('superUser'), (req,res,next) => {
  User.findByIdAndRemove(req.params.id)
  .lean()
  .select('-password')
  .then(user => res.send(user))
  .catch(next);
});<commit_msg>modified routing permissions<commit_after>'use strict';

const express = require('express');
const router = express.Router();
const bodyparser = require('body-parser').json();
const ensureRole = require('../auth/ensureRole');
const User = require('../models/user');

module.exports = router

.get('/', (req,res,next) => {
  User.find()
  .lean()
  .select('-password')
  .then(users => res.send(users))
  .catch(next);
})

.get('/byID', (req,res,next) => {
  User.findById(req.user.id)
    .select('-password')
    .then(user => res.send(user))
  .catch(next);
})

.put('/', bodyparser, (req,res,next) => {
  User.findByIdAndUpdate(req.user.id, req.body, {new:true})
  .lean()
  .select('-password')
  .then(user => res.send(user))
  .catch(next);
})

.delete('/:id', ensureRole('superUser'), (req,res,next) => {
  User.findByIdAndRemove(req.params.id)
  .lean()
  .select('-password')
  .then(user => res.send(user))
  .catch(next);
});<|endoftext|>


<commit_before>"use strict";

var spawn = require("child_process").spawn;
var util = require("util");
var _ = require("lodash");

exports.rsync = function (options,callback) {

    options = options || {};

    if ( typeof options.src === "undefined" ) {
        throw(new Error("'src' directory is missing from options"));
    }

    if ( typeof options.dest === "undefined" ) {
        throw(new Error("'dest' directory is missing from options"));
    }

    var dest = options.dest;

    if ( typeof options.host !== "undefined" ) {
        dest = options.host+":"+options.dest;
    }

    var args = [options.src,dest];

    if ( typeof options.host !== "undefined" ) {
        args.push("--rsh=ssh");
    }

    if ( options.recursive === true ) {
        args.push("--recursive");
    }

    if ( options.syncDest === true ) {
        args.push("--delete");
        args.push("--delete-excluded");
    }

    if ( options.dryRun === true ) {
        args.push("--dry-run");
        args.push("--verbose");
    }

    if ( typeof options.exclude !== "undefined" && util.isArray(options.exclude) ) {
        options.exclude.forEach(function (value,index) {
            args.push("--exclude="+value);
        });
    }

    switch ( options.compareMode ) {
        case "sizeOnly":
            args.push("--size-only");
            break;
        case "checksum":
            args.push("--checksum");
            break;
    }

    if ( typeof options.args !== "undefined" && util.isArray(options.args) ) {
        args = _.union(args,options.args);
    }

    args = _.unique(args);

    var cmd = "rsync "+args.join(" ");

    try {
        var process = spawn("rsync",args);
        var stdoutBuffer = "";
        var stderrBuffer = "";

        process.stdout.on("data", function (data) {
            stdoutBuffer += data;
        });

        process.stderr.on("data", function (data) {
            stderrBuffer += data;
        });

        process.on("exit", function (code) {
            callback(code===0?null:new Error("rsync exited with code "+code+". "+stderrBuffer),stdoutBuffer,stderrBuffer,cmd);
        });
    } catch (error) {
        callback(error,null,null,cmd);
    }
};<commit_msg>Update rsyncwrapper.js<commit_after>"use strict";

var spawn = require("child_process").spawn;
var util = require("util");
var _ = require("lodash");

exports.rsync = function (options,callback) {

    options = options || {};

    if ( typeof options.src === "undefined" ) {
        throw(new Error("'src' directory is missing from options"));
    }

    if ( typeof options.dest === "undefined" ) {
        throw(new Error("'dest' directory is missing from options"));
    }

    var dest = options.dest;

    if ( typeof options.host !== "undefined" ) {
        dest = options.host+":"+options.dest;
    }

    var args = [options.src,dest];

    if ( typeof options.host !== "undefined" ) {
        args.push("--rsh=ssh");
    }

    if ( options.recursive === true ) {
        args.push("--recursive");
    }

    if ( options.syncDest === true ) {
        args.push("--delete");
        args.push("--delete-excluded");
    }

    if ( options.dryRun === true ) {
        args.push("--dry-run");
        args.push("--verbose");
    }

    if ( typeof options.exclude !== "undefined" && util.isArray(options.exclude) ) {
        options.exclude.forEach(function (value,index) {
            args.push("--exclude="+value);
        });
    }

    // Add Support for Non-Standard Port Numbers
    if ( options.port === true ) {
        args.push("ssh -p");
    }

    switch ( options.compareMode ) {
        case "sizeOnly":
            args.push("--size-only");
            break;
        case "checksum":
            args.push("--checksum");
            break;
    }

    if ( typeof options.args !== "undefined" && util.isArray(options.args) ) {
        args = _.union(args,options.args);
    }

    args = _.unique(args);

    var cmd = "rsync "+args.join(" ");

    try {
        var process = spawn("rsync",args);
        var stdoutBuffer = "";
        var stderrBuffer = "";

        process.stdout.on("data", function (data) {
            stdoutBuffer += data;
        });

        process.stderr.on("data", function (data) {
            stderrBuffer += data;
        });

        process.on("exit", function (code) {
            callback(code===0?null:new Error("rsync exited with code "+code+". "+stderrBuffer),stdoutBuffer,stderrBuffer,cmd);
        });
    } catch (error) {
        callback(error,null,null,cmd);
    }
};
<|endoftext|>


<commit_before>'use babel';

const DOCUMENTATION_LIFETIME = 86400 * 1000; // 1 day TODO: Configurable?
const docsRuleCache = new Map();

export function takeWhile(source, predicate) {
  const result = [];
  const { length } = source;
  let i = 0;

  while (i < length && predicate(source[i], i)) {
    result.push(source[i]);
    i += 1;
  }

  return result;
}

// Retrieves style guide documentation with cached responses
export async function getRuleMarkDown(rule) {
  if (docsRuleCache.has(rule)) {
    const cachedRule = docsRuleCache.get(rule);
    if (new Date().getTime() >= cachedRule.expires) {
      // If documentation is stale, clear cache
      docsRuleCache.delete(rule);
    } else {
      return cachedRule.markdown;
    }
  }

  let rawRuleMarkdown;
  const response = await fetch(`https://raw.githubusercontent.com/troessner/reek/master/docs/${rule}.md`);
  if (response.ok) {
    rawRuleMarkdown = await response.text();
  } else {
    return `***\nError retrieving documentation: ${response.statusText}`;
  }

  const byLine = rawRuleMarkdown.split('\n');
  const ruleAnchors = byLine.reduce(
    (acc, line, idx) => (line.match(/## Introduction/g) ? acc.concat(idx) : acc),
    [],
  );

  ruleAnchors.forEach((startingIndex) => {
    const beginSearch = byLine.slice(startingIndex + 1);

    // gobble the introduction text until you reach the next section
    const documentationForRule = takeWhile(beginSearch, x => !x.match(/##/));
    const markdownOutput = '***\n'.concat(documentationForRule.join('\n'));

    docsRuleCache.set(rule, {
      markdown: markdownOutput,
      expires: new Date().getTime() + DOCUMENTATION_LIFETIME,
    });
  });

  return docsRuleCache.get(rule).markdown;
}
<commit_msg>Removed comment<commit_after>'use babel';

const DOCUMENTATION_LIFETIME = 86400 * 1000;
const docsRuleCache = new Map();

export function takeWhile(source, predicate) {
  const result = [];
  const { length } = source;
  let i = 0;

  while (i < length && predicate(source[i], i)) {
    result.push(source[i]);
    i += 1;
  }

  return result;
}

// Retrieves style guide documentation with cached responses
export async function getRuleMarkDown(rule) {
  if (docsRuleCache.has(rule)) {
    const cachedRule = docsRuleCache.get(rule);
    if (new Date().getTime() >= cachedRule.expires) {
      // If documentation is stale, clear cache
      docsRuleCache.delete(rule);
    } else {
      return cachedRule.markdown;
    }
  }

  let rawRuleMarkdown;
  const response = await fetch(`https://raw.githubusercontent.com/troessner/reek/master/docs/${rule}.md`);
  if (response.ok) {
    rawRuleMarkdown = await response.text();
  } else {
    return `***\nError retrieving documentation: ${response.statusText}`;
  }

  const byLine = rawRuleMarkdown.split('\n');
  const ruleAnchors = byLine.reduce(
    (acc, line, idx) => (line.match(/## Introduction/g) ? acc.concat(idx) : acc),
    [],
  );

  ruleAnchors.forEach((startingIndex) => {
    const beginSearch = byLine.slice(startingIndex + 1);

    // gobble the introduction text until you reach the next section
    const documentationForRule = takeWhile(beginSearch, x => !x.match(/##/));
    const markdownOutput = '***\n'.concat(documentationForRule.join('\n'));

    docsRuleCache.set(rule, {
      markdown: markdownOutput,
      expires: new Date().getTime() + DOCUMENTATION_LIFETIME,
    });
  });

  return docsRuleCache.get(rule).markdown;
}
<|endoftext|>


<commit_before>'use strict';

/* This is a simple cache intended to reduce the amount of load
 * Nightscout puts on MongoDB. The cache is based on identifying
 * elements based on the MongoDB _id field and implements simple
 * semantics for adding data to the cache in the runtime, intended
 * to be accessed by the persistence layer as data is inserted, updated
 * or deleted, as well as the periodic dataloader, which polls Mongo
 * for new inserts.
 *
 * Longer term, the cache is planned to allow skipping the Mongo polls
 * altogether.
 */

const _ = require('lodash');
const constants = require('../constants');

function cache (env, ctx) {

  const data = {
    treatments: []
    , devicestatus: []
    , entries: []
  };

  const retentionPeriods = {
    treatments: constants.ONE_HOUR * 60
    , devicestatus: env.extendedSettings.devicestatus && env.extendedSettings.devicestatus.days && env.extendedSettings.devicestatus.days == 2 ? constants.TWO_DAYS : constants.ONE_DAY
    , entries: constants.TWO_DAYS
  };

  function mergeCacheArrays (oldData, newData, retentionPeriod) {

    const ageLimit = Date.now() - retentionPeriod;

    var filteredOld =  filterForAge(oldData, ageLimit);
    var filteredNew = filterForAge(newData, ageLimit);

    const merged = ctx.ddata.idMergePreferNew(filteredOld, filteredNew);

    return _.sortBy(merged, function(item) {
      return -item.mills;
    });

    function filterForAge(data, ageLimit) {
      return _.filter(data, function hasId(object) {
        const hasId = !_.isEmpty(object._id);
        const isFresh = object.mills >= ageLimit;
        return isFresh && hasId;
      });
    }

  }

  data.isEmpty = (datatype) => {
    return data[datatype].length < 20;
  }

  data.getData = (datatype) => {
    return _.cloneDeep(data[datatype]);
  }

  data.insertData = (datatype, newData) => {
    data[datatype] = mergeCacheArrays(data[datatype], newData, retentionPeriods[datatype]);
    return data.getData(datatype);
  }

  function dataChanged (operation) {
    if (!data[operation.type]) return;

    if (operation.op == 'remove') {
      // if multiple items were deleted, flush entire cache
      if (!operation.changes) {
        data.treatments = [];
        data.devicestatus = [];
        data.entries = [];
      } else {
        removeFromArray(data[operation.type], operation.changes);
      }
    }

    if (operation.op == 'update') {
      data[operation.type] = mergeCacheArrays(data[operation.type], operation.changes, retentionPeriods[operation.type]);
    }
  }

  ctx.bus.on('data-update', dataChanged);

  function removeFromArray (array, id) {
    for (let i = 0; i < array.length; i++) {
      const o = array[i];
      if (o._id == id) {
        //console.log('Deleting object from cache', id);
        array.splice(i, 1);
        break;
      }
    }
  }

  return data;
}

module.exports = cache;
<commit_msg>Update cache.js<commit_after>'use strict';

/* This is a simple cache intended to reduce the amount of load
 * Nightscout puts on MongoDB. The cache is based on identifying
 * elements based on the MongoDB _id field and implements simple
 * semantics for adding data to the cache in the runtime, intended
 * to be accessed by the persistence layer as data is inserted, updated
 * or deleted, as well as the periodic dataloader, which polls Mongo
 * for new inserts.
 *
 * Longer term, the cache is planned to allow skipping the Mongo polls
 * altogether.
 */

const _ = require('lodash');
const constants = require('../constants');

function cache (env, ctx) {

  const data = {
    treatments: []
    , devicestatus: []
    , entries: []
  };

  const retentionPeriods = {
    treatments: constants.ONE_HOUR * 60
    , devicestatus: env.extendedSettings.devicestatus && env.extendedSettings.devicestatus.days && env.extendedSettings.devicestatus.days == 2 ? constants.TWO_DAYS : constants.ONE_DAY
    , entries: constants.TWO_DAYS
  };

  function mergeCacheArrays (oldData, newData, retentionPeriod) {

    const ageLimit = Date.now() - retentionPeriod;

    var filteredOld =  filterForAge(oldData, ageLimit);
    var filteredNew = filterForAge(newData, ageLimit);

    const merged = ctx.ddata.idMergePreferNew(filteredOld, filteredNew);

    return _.sortBy(merged, function(item) {
      return -item.mills;
    });

    function filterForAge(data, ageLimit) {
      return _.filter(data, function hasId(object) {
        if (!object || !object._id) return false;
        const hasId = !_.isEmpty(object._id);
        const isFresh = object.mills >= ageLimit;
        return isFresh && hasId;
      });
    }

  }

  data.isEmpty = (datatype) => {
    return data[datatype].length < 20;
  }

  data.getData = (datatype) => {
    return _.cloneDeep(data[datatype]);
  }

  data.insertData = (datatype, newData) => {
    data[datatype] = mergeCacheArrays(data[datatype], newData, retentionPeriods[datatype]);
    return data.getData(datatype);
  }

  function dataChanged (operation) {
    if (!data[operation.type]) return;

    if (operation.op == 'remove') {
      // if multiple items were deleted, flush entire cache
      if (!operation.changes) {
        data.treatments = [];
        data.devicestatus = [];
        data.entries = [];
      } else {
        removeFromArray(data[operation.type], operation.changes);
      }
    }

    if (operation.op == 'update') {
      data[operation.type] = mergeCacheArrays(data[operation.type], operation.changes, retentionPeriods[operation.type]);
    }
  }

  ctx.bus.on('data-update', dataChanged);

  function removeFromArray (array, id) {
    for (let i = 0; i < array.length; i++) {
      const o = array[i];
      if (o._id == id) {
        //console.log('Deleting object from cache', id);
        array.splice(i, 1);
        break;
      }
    }
  }

  return data;
}

module.exports = cache;
<|endoftext|>


<commit_before>const getConfig = require('../conf/get')

const {
    handleError
} = require('../util/resp')

module.exports = (req, resp, next) => {
    // 获取 host & port
    let [hostname, port = 80] = req.headers.host.split(':')
    if (req.client.ssl) {
        port = 443
    }

    // 获取 config
    const conf = getConfig(hostname, port)
    if (!conf) {
        handleError(resp, {error: 'host not found!'})
    } else {
        conf.app(req, resp, next, conf)
    }

}
<commit_msg>no host exception<commit_after>const getConfig = require('../conf/get')

const {
    handleError
} = require('../util/resp')

module.exports = (req, resp, next) => {
    console.log(req)
    // 获取 host & port
    let [hostname, port = 80] = (req.headers.host + '').split(':')
    if (req.client.ssl) {
        port = 443
    }

    // 获取 config
    const conf = getConfig(hostname, port)
    if (!conf) {
        handleError(resp, {error: 'host not found!'})
    } else {
        conf.app(req, resp, next, conf)
    }

}
<|endoftext|>


<commit_before>module.exports = Swarm

var arrayRemove = require('unordered-array-remove')
var debug = require('debug')('bittorrent-tracker:swarm')
var LRU = require('lru')
var randomIterate = require('random-iterate')

// Regard this as the default implementation of an interface that you
// need to support when overriding Server.createSwarm() and Server.getSwarm()
function Swarm (infoHash, server) {
  var self = this
  self.infoHash = infoHash
  self.complete = 0
  self.incomplete = 0

  self.peers = new LRU({
    max: server.peersCacheLength || 1000,
    maxAge: server.peersCacheTtl || 20 * 60 * 1000 // 20 minutes
  })

  // When a peer is evicted from the LRU store, send a synthetic 'stopped' event
  // so the stats get updated correctly.
  self.peers.on('evict', function (data) {
    var peer = data.value
    var params = {
      type: peer.type,
      event: 'stopped',
      numwant: 0,
      peer_id: peer.peerId
    }
    self._onAnnounceStopped(params, peer, peer.peerId)
    peer.socket = null
  })
}

Swarm.prototype.announce = function (params, cb) {
  var self = this
  var id = params.type === 'ws' ? params.peer_id : params.addr
  // Mark the source peer as recently used in cache
  var peer = self.peers.get(id)

  if (params.event === 'started') {
    self._onAnnounceStarted(params, peer, id)
  } else if (params.event === 'stopped') {
    self._onAnnounceStopped(params, peer, id)
  } else if (params.event === 'completed') {
    self._onAnnounceCompleted(params, peer, id)
  } else if (params.event === 'update') {
    self._onAnnounceUpdate(params, peer, id)
  } else {
    cb(new Error('invalid event'))
    return
  }
  cb(null, {
    complete: self.complete,
    incomplete: self.incomplete,
    peers: self._getPeers(params.numwant, params.peer_id, !!params.socket)
  })
}

Swarm.prototype.scrape = function (params, cb) {
  cb(null, {
    complete: this.complete,
    incomplete: this.incomplete
  })
}

Swarm.prototype._onAnnounceStarted = function (params, peer, id) {
  if (peer) {
    debug('unexpected `started` event from peer that is already in swarm')
    return this._onAnnounceUpdate(params, peer, id) // treat as an update
  }

  if (params.left === 0) this.complete += 1
  else this.incomplete += 1
  peer = this.peers.set(id, {
    type: params.type,
    complete: params.left === 0,
    peerId: params.peer_id, // as hex
    ip: params.ip,
    port: params.port,
    socket: params.socket // only websocket
  })
}

Swarm.prototype._onAnnounceStopped = function (params, peer, id) {
  if (!peer) {
    debug('unexpected `stopped` event from peer that is not in swarm')
    return // do nothing
  }

  if (peer.complete) this.complete -= 1
  else this.incomplete -= 1

  // If it's a websocket, remove this swarm's infohash from the list of active
  // swarms that this peer is participating in.
  if (peer.socket && !peer.socket.destroyed) {
    var index = peer.socket.infoHashes.indexOf(this.infoHash)
    arrayRemove(peer.socket.infoHashes, index)
  }

  this.peers.remove(id)
}

Swarm.prototype._onAnnounceCompleted = function (params, peer, id) {
  if (!peer) {
    debug('unexpected `completed` event from peer that is not in swarm')
    return this._onAnnounceStarted(params, peer, id) // treat as a start
  }
  if (peer.complete) {
    debug('unexpected `completed` event from peer that is already completed')
    return this._onAnnounceUpdate(params, peer, id) // treat as an update
  }

  this.complete += 1
  this.incomplete -= 1
  peer.complete = true
  this.peers.set(id, peer)
}

Swarm.prototype._onAnnounceUpdate = function (params, peer, id) {
  if (!peer) {
    debug('unexpected `update` event from peer that is not in swarm')
    return this._onAnnounceStarted(params, peer, id) // treat as a start
  }

  if (!peer.complete && params.left === 0) {
    this.complete += 1
    this.incomplete -= 1
    peer.complete = true
  }
  this.peers.set(id, peer)
}

Swarm.prototype._getPeers = function (numwant, ownPeerId, isWebRTC) {
  var peers = []
  var ite = randomIterate(this.peers.keys)
  var peerId
  while ((peerId = ite()) && peers.length < numwant) {
    // Don't mark the peer as most recently used on announce
    var peer = this.peers.peek(peerId)
    if (!peer) continue
    if (isWebRTC && peer.peerId === ownPeerId) continue // don't send peer to itself
    if ((isWebRTC && peer.type !== 'ws') || (!isWebRTC && peer.type === 'ws')) continue // send proper peer type
    peers.push(peer)
  }
  return peers
}
<commit_msg>Remove useless assignment<commit_after>module.exports = Swarm

var arrayRemove = require('unordered-array-remove')
var debug = require('debug')('bittorrent-tracker:swarm')
var LRU = require('lru')
var randomIterate = require('random-iterate')

// Regard this as the default implementation of an interface that you
// need to support when overriding Server.createSwarm() and Server.getSwarm()
function Swarm (infoHash, server) {
  var self = this
  self.infoHash = infoHash
  self.complete = 0
  self.incomplete = 0

  self.peers = new LRU({
    max: server.peersCacheLength || 1000,
    maxAge: server.peersCacheTtl || 20 * 60 * 1000 // 20 minutes
  })

  // When a peer is evicted from the LRU store, send a synthetic 'stopped' event
  // so the stats get updated correctly.
  self.peers.on('evict', function (data) {
    var peer = data.value
    var params = {
      type: peer.type,
      event: 'stopped',
      numwant: 0,
      peer_id: peer.peerId
    }
    self._onAnnounceStopped(params, peer, peer.peerId)
    peer.socket = null
  })
}

Swarm.prototype.announce = function (params, cb) {
  var self = this
  var id = params.type === 'ws' ? params.peer_id : params.addr
  // Mark the source peer as recently used in cache
  var peer = self.peers.get(id)

  if (params.event === 'started') {
    self._onAnnounceStarted(params, peer, id)
  } else if (params.event === 'stopped') {
    self._onAnnounceStopped(params, peer, id)
  } else if (params.event === 'completed') {
    self._onAnnounceCompleted(params, peer, id)
  } else if (params.event === 'update') {
    self._onAnnounceUpdate(params, peer, id)
  } else {
    cb(new Error('invalid event'))
    return
  }
  cb(null, {
    complete: self.complete,
    incomplete: self.incomplete,
    peers: self._getPeers(params.numwant, params.peer_id, !!params.socket)
  })
}

Swarm.prototype.scrape = function (params, cb) {
  cb(null, {
    complete: this.complete,
    incomplete: this.incomplete
  })
}

Swarm.prototype._onAnnounceStarted = function (params, peer, id) {
  if (peer) {
    debug('unexpected `started` event from peer that is already in swarm')
    return this._onAnnounceUpdate(params, peer, id) // treat as an update
  }

  if (params.left === 0) this.complete += 1
  else this.incomplete += 1
  this.peers.set(id, {
    type: params.type,
    complete: params.left === 0,
    peerId: params.peer_id, // as hex
    ip: params.ip,
    port: params.port,
    socket: params.socket // only websocket
  })
}

Swarm.prototype._onAnnounceStopped = function (params, peer, id) {
  if (!peer) {
    debug('unexpected `stopped` event from peer that is not in swarm')
    return // do nothing
  }

  if (peer.complete) this.complete -= 1
  else this.incomplete -= 1

  // If it's a websocket, remove this swarm's infohash from the list of active
  // swarms that this peer is participating in.
  if (peer.socket && !peer.socket.destroyed) {
    var index = peer.socket.infoHashes.indexOf(this.infoHash)
    arrayRemove(peer.socket.infoHashes, index)
  }

  this.peers.remove(id)
}

Swarm.prototype._onAnnounceCompleted = function (params, peer, id) {
  if (!peer) {
    debug('unexpected `completed` event from peer that is not in swarm')
    return this._onAnnounceStarted(params, peer, id) // treat as a start
  }
  if (peer.complete) {
    debug('unexpected `completed` event from peer that is already completed')
    return this._onAnnounceUpdate(params, peer, id) // treat as an update
  }

  this.complete += 1
  this.incomplete -= 1
  peer.complete = true
  this.peers.set(id, peer)
}

Swarm.prototype._onAnnounceUpdate = function (params, peer, id) {
  if (!peer) {
    debug('unexpected `update` event from peer that is not in swarm')
    return this._onAnnounceStarted(params, peer, id) // treat as a start
  }

  if (!peer.complete && params.left === 0) {
    this.complete += 1
    this.incomplete -= 1
    peer.complete = true
  }
  this.peers.set(id, peer)
}

Swarm.prototype._getPeers = function (numwant, ownPeerId, isWebRTC) {
  var peers = []
  var ite = randomIterate(this.peers.keys)
  var peerId
  while ((peerId = ite()) && peers.length < numwant) {
    // Don't mark the peer as most recently used on announce
    var peer = this.peers.peek(peerId)
    if (!peer) continue
    if (isWebRTC && peer.peerId === ownPeerId) continue // don't send peer to itself
    if ((isWebRTC && peer.type !== 'ws') || (!isWebRTC && peer.type === 'ws')) continue // send proper peer type
    peers.push(peer)
  }
  return peers
}
<|endoftext|>