Advertisement
stuppid_bot

Untitled

Feb 1st, 2016
205
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. // requires: common.js, http.js, event-emitter.js
  2. var API_VERSION = 5.44;
  3. var API_URL = "https://api.vk.com/method/";
  4. var API_DELAY = 334;
  5.  
  6. var ERRORS = {
  7.   // ...
  8.   CAPTCHA_NEEDED: 14,
  9.   // ...
  10. }
  11.  
  12. function Api(accessToken, userId, delay, version) {
  13.     this.accessToken = accessToken;
  14.     this.userId = userId;
  15.     // Искуственная задержка перед выполнением запроса
  16.     // У Вконтакте есть ограничение на количество запросов в секунду
  17.     this.delay = delay || API_DELAY;
  18.     this.version = version || API_VERSION;
  19.     // Для отладки
  20.     this.lastResponse = null;
  21.     // Очередь запросов
  22.     this._queue = [];
  23.     this._stopped = false;
  24.     this._lastRequestTime = 0;
  25. }
  26.  
  27. Api.prototype = {
  28.   /**
  29.    * Добавляет запрос в очередь.
  30.    *
  31.    * method {string} Метод Api
  32.    * callback {function} Функция обработчик
  33.    * params {object} (optional) Параметры запроса
  34.    * options.delay {number} (optional) Задержка после предыдущего вызова в
  35.    *   миллисекундах
  36.    * options.context {object} (optional) Контекст в котором выполняется callback
  37.    */
  38.   call: function(method, callback, params, options) {
  39.     params = clone(params || {});
  40.     params.v = this.version;
  41.     if (this.accessToken) {
  42.       params.access_token = this.accessToken;
  43.     }
  44.     this._queue.push({
  45.       method: method,
  46.       callback: callback,
  47.       params: params,
  48.       options: clone(options || {})
  49.     });
  50.     console.log("Add request to queue");
  51.     this._handle();
  52.     // .call(...).call(...)
  53.     return this;
  54.   },
  55.   execute: function() {
  56.     console.log("Execute request");
  57.     this._stopped = false;
  58.     this._handle();
  59.   },
  60.   stop: function() {
  61.     console.log("Stop handle requests");
  62.     this._stopped = true;
  63.   },
  64.   current: function() {
  65.     return this._queue[0];
  66.   },
  67.   next: function() {
  68.     console.log("Next request");
  69.     this._queue.shift();
  70.     this.execute();
  71.   },
  72.   _handle: function() {
  73.     if (this._stopped) {
  74.       console.log("Stopped!");
  75.       return;
  76.     }
  77.     var cur = this.current();
  78.     if (cur === undefined) {
  79.       console.log("Queue empty");
  80.       return;
  81.     }
  82.     console.log("Calling method %s with parameters %s", cur.method,
  83.       JSON.stringify(cur.params).replace(
  84.         /("access_token":")[^"]+/, "$1*censored*"));
  85.     var endpoint = API_URL.replace(/(\/|)$/, '/') + cur.method;
  86.     var nextRequestTime = (cur.options.delay | this.delay) +
  87.       this._lastRequestTime;
  88.     var nowTime = Date.now();
  89.     var delay = nextRequestTime > nowTime ? nextRequestTime - nowTime : 0;  
  90.     console.log("Wait %s ms", delay);
  91.     var self = this;
  92.     setTimeout(function() {
  93.       post(endpoint, cur.params, function(response) {
  94.         self._lastRequestTime = Date.now();
  95.         if (response.error) {
  96.           var error = response.error;
  97.           if (error.error_code == ERRORS.CAPTCHA_NEEDED) {
  98.             cur.params.captcha_sid = error.captcha_sid;
  99.             console.log("Captcha required");
  100.             self.emit("captcha", error.captcha_img);
  101.             // Ожидаем ввода капчи
  102.             // self.next() не выполнится
  103.             return;
  104.           }
  105.         }
  106.         self.lastResponse = response;
  107.         cur.callback && cur.callback.call(cur.options.context, response.error,
  108.           response.response);
  109.         self.next();
  110.       });
  111.     }, delay);
  112.     // Stop handle requests
  113.     this.stop();
  114.   },
  115. };
  116.  
  117. EventEmitter.mixin(Api);
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement