File size: 4,703 Bytes
e7c953d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
'use strict';

var https = require('https');

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

var got = require('got').extend({
    agent: {https: new https.Agent({keepAlive: true})},
    decompress: true,
    followRedirect: false,
    headers: {'user-agent': 'DubAPI/' + pkg.version},
    prefixUrl: 'https://api.queup.net/',
    responseType: 'json',
    retry: 0,
    throwHttpErrors: false
});

var CookieJar = require('tough-cookie').CookieJar;

var DubAPIError = require('./errors/error.js'),
    DubAPIRequestError = require('./errors/requestError.js');

var utils = require('./utils.js');

function RequestHandler(dubAPI) {
    this._ = {};
    this._.dubAPI = dubAPI;

    this._.cookieJar = new CookieJar();

    this._.ticking = false;
    this._.limit = 10;
    this._.queue = [];
    this._.sent = 0;

    //Bind functions once instead of every time we need them
    this._tick = utils.bind(this._tick, this);
    this._decrementSent = utils.bind(this._decrementSent, this);
}

RequestHandler.prototype.queue = function(options, callback) {
    if (typeof options !== 'object') throw new TypeError('options must be an object');
    if (typeof options.url !== 'string') throw new TypeError('options.url must be a string');

    var isChat = options.isChat;
    delete options.isChat;

    options.url = this.endpoint(options.url);

    this._.queue.push({options: options, callback: callback, isChat: isChat});

    if (!this._.ticking) this._tick();

    return true;
};

RequestHandler.prototype.clear = function() {
    this._.queue.splice(0, this._.queue.length);
};

RequestHandler.prototype.send = function(options, callback) {
    if (typeof options !== 'object') throw new TypeError('options must be an object');
    if (typeof options.url !== 'string') throw new TypeError('options.url must be a string');

    delete options.isChat;

    options.url = this.endpoint(options.url);

    this._sendRequest({options: options, callback: callback});

    return true;
};

RequestHandler.prototype._tick = function() {
    if (this._.queue.length === 0) {
        this._.ticking = false;
        return;
    }

    this._.ticking = true;

    if (this._.sent >= this._.limit) {
        setTimeout(this._tick, 5000);
        return;
    }

    var queueItem = this._.queue.shift();

    if (queueItem) {
        if (queueItem.isChat) queueItem.options.timeout = 2500;

        this._.sent++;

        setTimeout(this._decrementSent, queueItem.isChat ? 5000 : 30000);

        this._sendRequest(queueItem);
    }

    if (!queueItem || !queueItem.isChat) setImmediate(this._tick);
};

RequestHandler.prototype._sendRequest = function(queueItem) {
    queueItem.options.cookieJar = this._.cookieJar;

    var that = this;

    got(queueItem.options).then(function(res) {
        if (!queueItem.isRetry && res.statusCode === 302 && res.headers.location === '/auth/login') {
            that._.dubAPI._.actHandler.doLogin(function(err) {
                if (err) that._.dubAPI.emit('error', err);

                queueItem.isRetry = true;
                that._.queue.unshift(queueItem);
                if (!that._.ticking || queueItem.isChat) that._tick();
            });
            return;
        }

        if (queueItem.isChat) that._tick();

        if (typeof queueItem.callback === 'function') queueItem.callback(res.statusCode, res.body);
        else if (res.statusCode !== 200) that._.dubAPI.emit('error', new DubAPIRequestError(res.statusCode, queueItem.options.url));
    }).catch(function(err) {
        if (queueItem.isChat && err.code === 'ETIMEDOUT') err = new DubAPIError('Chat request timed out');

        that._.dubAPI.emit('error', err);

        //Will not work for chat request timeouts
        if (!queueItem.isRetry && ['ETIMEDOUT', 'ECONNRESET', 'ESOCKETTIMEDOUT'].indexOf(err.code) !== -1) {
            queueItem.isRetry = true;
            that._.queue.unshift(queueItem);
            if (!that._.ticking || queueItem.isChat) that._tick();
            return;
        }

        if (queueItem.isChat) that._tick();
    });
};

RequestHandler.prototype._decrementSent = function() {
    this._.sent--;
};

RequestHandler.prototype.endpoint = function(endpoint) {
    if (endpoint.indexOf('%SLUG%') !== -1 && this._.dubAPI._.slug) {
        endpoint = endpoint.replace('%SLUG%', this._.dubAPI._.slug);
    }

    if (endpoint.indexOf('%RID%') !== -1 && this._.dubAPI._.room) {
        endpoint = endpoint.replace('%RID%', this._.dubAPI._.room.id);
    }

    return endpoint;
};

module.exports = RequestHandler;