UNPKG

gather-public-proxy

Version:
120 lines (95 loc) 2.06 kB
/*! * Gather Public Proxy * Copyright(c) 2014 Gautier Fauchart <gautier.fauchart@gmail.com> * MIT Licensed */ /** * Module dependencies. */ var request = require("request"); var _ = require("lodash"); var Q = require("q"); /** * expose locationChecker */ module.exports = locationChecker; /** * setup locationChecker * @param {Object} options * @api private */ function locationChecker(_option){ this.option = _option; this.queue = []; this.inProgress = 0; this.online = true; } /** * start engine * @return promise * @api public */ locationChecker.prototype.start = function(){ this.deferred = Q.defer(); return this.deferred.promise; } /** * Stop locationChecker, prevent request and resolve promise * @api public */ locationChecker.prototype.end = function(){ this.online = false; this.queue = null; this.deferred.resolve(); } /** * set stopInput = true, for stopping engine when queue is empty * @api public */ locationChecker.prototype.endInput = function(){ this.stopInput = true; if (this.inProgress == 0 && this.queue.length == 0) this.end(); } /** * add proxy to queue * @param {Proxy} proxy * @api public */ locationChecker.prototype.add = function(proxy){ var that = this; that.queue.push(proxy); that.execute(); } /** * execute request * @api private */ locationChecker.prototype.execute = function(){ var that = this; if (!this.online) return; if (this.inProgress >= this.option.thead) return; var proxy = this.queue.shift(); if (!proxy){ if (this.stopInput && this.inProgress == 0) this.end(); return } this.inProgress++; options = { url: "http://www.freegeoip.net/json/" + proxy.ip, timeout: 4000 }; request(options, function(error, response, body) { that.inProgress--; if (!error && response.statusCode == 200) { _.extend(proxy, JSON.parse(body)) that.deferred.notify(proxy); } _.defer(function(){ that.execute(); }); }); }