Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // requires: common.js, http.js, event-emitter.js
- var API_VERSION = 5.44;
- var API_URL = "https://api.vk.com/method/";
- var API_DELAY = 334;
- var ERRORS = {
- // ...
- CAPTCHA_NEEDED: 14,
- // ...
- }
- function Api(accessToken, userId, delay, version) {
- this.accessToken = accessToken;
- this.userId = userId;
- // Искуственная задержка перед выполнением запроса
- // У Вконтакте есть ограничение на количество запросов в секунду
- this.delay = delay || API_DELAY;
- this.version = version || API_VERSION;
- // Для отладки
- this.lastResponse = null;
- // Очередь запросов
- this._queue = [];
- this._stopped = false;
- this._lastRequestTime = 0;
- }
- Api.prototype = {
- /**
- * Добавляет запрос в очередь.
- *
- * method {string} Метод Api
- * callback {function} Функция обработчик
- * params {object} (optional) Параметры запроса
- * options.delay {number} (optional) Задержка после предыдущего вызова в
- * миллисекундах
- * options.context {object} (optional) Контекст в котором выполняется callback
- */
- call: function(method, callback, params, options) {
- params = clone(params || {});
- params.v = this.version;
- if (this.accessToken) {
- params.access_token = this.accessToken;
- }
- this._queue.push({
- method: method,
- callback: callback,
- params: params,
- options: clone(options || {})
- });
- console.log("Add request to queue");
- this._handle();
- // .call(...).call(...)
- return this;
- },
- execute: function() {
- console.log("Execute request");
- this._stopped = false;
- this._handle();
- },
- stop: function() {
- console.log("Stop handle requests");
- this._stopped = true;
- },
- current: function() {
- return this._queue[0];
- },
- next: function() {
- console.log("Next request");
- this._queue.shift();
- this.execute();
- },
- _handle: function() {
- if (this._stopped) {
- console.log("Stopped!");
- return;
- }
- var cur = this.current();
- if (cur === undefined) {
- console.log("Queue empty");
- return;
- }
- console.log("Calling method %s with parameters %s", cur.method,
- JSON.stringify(cur.params).replace(
- /("access_token":")[^"]+/, "$1*censored*"));
- var endpoint = API_URL.replace(/(\/|)$/, '/') + cur.method;
- var nextRequestTime = (cur.options.delay | this.delay) +
- this._lastRequestTime;
- var nowTime = Date.now();
- var delay = nextRequestTime > nowTime ? nextRequestTime - nowTime : 0;
- console.log("Wait %s ms", delay);
- var self = this;
- setTimeout(function() {
- post(endpoint, cur.params, function(response) {
- self._lastRequestTime = Date.now();
- if (response.error) {
- var error = response.error;
- if (error.error_code == ERRORS.CAPTCHA_NEEDED) {
- cur.params.captcha_sid = error.captcha_sid;
- console.log("Captcha required");
- self.emit("captcha", error.captcha_img);
- // Ожидаем ввода капчи
- // self.next() не выполнится
- return;
- }
- }
- self.lastResponse = response;
- cur.callback && cur.callback.call(cur.options.context, response.error,
- response.response);
- self.next();
- });
- }, delay);
- // Stop handle requests
- this.stop();
- },
- };
- EventEmitter.mixin(Api);
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement