@zygout/eris 0.19.0 → 0.19.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +20 -20
- package/README.md +109 -80
- package/esm.mjs +72 -72
- package/index.d.ts +4407 -4397
- package/index.js +75 -75
- package/lib/Client.js +4708 -4683
- package/lib/Constants.d.ts +990 -988
- package/lib/Constants.js +1163 -1161
- package/lib/command/Command.js +552 -552
- package/lib/command/CommandClient.js +460 -460
- package/lib/errors/DiscordHTTPError.js +63 -63
- package/lib/errors/DiscordRESTError.js +77 -77
- package/lib/gateway/Shard.js +3029 -3029
- package/lib/gateway/ShardManager.js +164 -164
- package/lib/rest/Endpoints.js +172 -172
- package/lib/rest/RequestHandler.js +459 -459
- package/lib/structures/ApplicationCommand.js +125 -125
- package/lib/structures/AutoModerationRule.js +143 -143
- package/lib/structures/AutocompleteInteraction.js +80 -80
- package/lib/structures/Base.js +81 -81
- package/lib/structures/CategoryChannel.js +77 -77
- package/lib/structures/Channel.js +98 -98
- package/lib/structures/CommandInteraction.js +473 -473
- package/lib/structures/ComponentInteraction.js +538 -538
- package/lib/structures/DMChannel.js +278 -278
- package/lib/structures/Entitlement.js +77 -77
- package/lib/structures/ExtendedUser.js +46 -46
- package/lib/structures/ForumChannel.js +24 -24
- package/lib/structures/GroupChannel.js +106 -106
- package/lib/structures/Guild.js +1677 -1677
- package/lib/structures/GuildAuditLogEntry.js +190 -190
- package/lib/structures/GuildChannel.js +128 -128
- package/lib/structures/GuildIntegration.js +99 -99
- package/lib/structures/GuildPreview.js +97 -97
- package/lib/structures/GuildScheduledEvent.js +176 -176
- package/lib/structures/GuildTemplate.js +76 -76
- package/lib/structures/GuildTextableChannel.js +260 -260
- package/lib/structures/Interaction.js +133 -133
- package/lib/structures/Invite.js +143 -143
- package/lib/structures/Lobby.js +108 -108
- package/lib/structures/LobbyMember.js +59 -59
- package/lib/structures/MediaChannel.js +216 -216
- package/lib/structures/Member.js +371 -371
- package/lib/structures/Message.js +708 -708
- package/lib/structures/ModalSubmitInteraction.js +478 -478
- package/lib/structures/NewsChannel.js +34 -34
- package/lib/structures/NewsThreadChannel.js +12 -12
- package/lib/structures/Permission.js +80 -80
- package/lib/structures/PermissionOverwrite.js +32 -32
- package/lib/structures/PingInteraction.js +39 -39
- package/lib/structures/PrivateThreadChannel.js +25 -25
- package/lib/structures/PublicThreadChannel.js +26 -26
- package/lib/structures/Role.js +163 -163
- package/lib/structures/SKU.js +80 -80
- package/lib/structures/SoundboardSound.js +79 -79
- package/lib/structures/StageChannel.js +59 -59
- package/lib/structures/StageInstance.js +55 -55
- package/lib/structures/Subscription.js +69 -69
- package/lib/structures/TextChannel.js +202 -202
- package/lib/structures/ThreadChannel.js +143 -143
- package/lib/structures/ThreadMember.js +59 -59
- package/lib/structures/UnavailableGuild.js +26 -26
- package/lib/structures/UnknownInteraction.js +502 -502
- package/lib/structures/User.js +296 -296
- package/lib/structures/VoiceChannel.js +166 -166
- package/lib/structures/VoiceState.js +84 -84
- package/lib/util/BrowserWebSocket.js +76 -76
- package/lib/util/Bucket.js +89 -89
- package/lib/util/Collection.js +202 -202
- package/lib/util/MultipartData.js +70 -70
- package/lib/util/Opus.js +33 -33
- package/lib/util/SequentialBucket.js +83 -83
- package/lib/util/emitDeprecation.js +26 -26
- package/lib/voice/Piper.js +300 -300
- package/lib/voice/SharedStream.js +238 -238
- package/lib/voice/VoiceConnection.js +1440 -1440
- package/lib/voice/VoiceConnectionManager.js +151 -151
- package/lib/voice/VoiceDataStream.js +22 -22
- package/lib/voice/streams/BaseTransformer.js +40 -40
- package/lib/voice/streams/DCAOpusTransformer.js +78 -78
- package/lib/voice/streams/FFmpegDuplex.js +192 -192
- package/lib/voice/streams/FFmpegOggTransformer.js +35 -35
- package/lib/voice/streams/FFmpegPCMTransformer.js +26 -26
- package/lib/voice/streams/OggOpusTransformer.js +108 -108
- package/lib/voice/streams/PCMOpusTransformer.js +61 -61
- package/lib/voice/streams/VolumeTransformer.js +50 -50
- package/lib/voice/streams/WebmOpusTransformer.js +258 -258
- package/package.json +83 -82
|
@@ -1,459 +1,459 @@
|
|
|
1
|
-
"use strict";
|
|
2
|
-
|
|
3
|
-
const util = require("util");
|
|
4
|
-
const Base = require("../structures/Base");
|
|
5
|
-
const DiscordHTTPError = require("../errors/DiscordHTTPError");
|
|
6
|
-
const DiscordRESTError = require("../errors/DiscordRESTError");
|
|
7
|
-
const Endpoints = require("./Endpoints");
|
|
8
|
-
const HTTPS = require("https");
|
|
9
|
-
const MultipartData = require("../util/MultipartData");
|
|
10
|
-
const SequentialBucket = require("../util/SequentialBucket");
|
|
11
|
-
const Zlib = require("zlib");
|
|
12
|
-
|
|
13
|
-
/**
|
|
14
|
-
* Handles API requests
|
|
15
|
-
*/
|
|
16
|
-
class RequestHandler {
|
|
17
|
-
constructor(client, options) {
|
|
18
|
-
// [DEPRECATED] Previously forceQueueing
|
|
19
|
-
if (typeof options === "boolean") {
|
|
20
|
-
options = {
|
|
21
|
-
forceQueueing: options,
|
|
22
|
-
};
|
|
23
|
-
}
|
|
24
|
-
this.options = options = Object.assign({
|
|
25
|
-
agent: client.options.agent || null,
|
|
26
|
-
baseURL: Endpoints.BASE_URL,
|
|
27
|
-
decodeReasons: true,
|
|
28
|
-
disableLatencyCompensation: false,
|
|
29
|
-
domain: "discord.com",
|
|
30
|
-
latencyThreshold: client.options.latencyThreshold || 30000,
|
|
31
|
-
ratelimiterOffset: client.options.ratelimiterOffset || 0,
|
|
32
|
-
requestTimeout: client.options.requestTimeout || 15000,
|
|
33
|
-
}, options);
|
|
34
|
-
|
|
35
|
-
this._client = client;
|
|
36
|
-
this.userAgent = `DiscordBot (https://github.com/abalabahaha/eris, ${require("../../package.json").version})`;
|
|
37
|
-
this.ratelimits = {};
|
|
38
|
-
this.latencyRef = {
|
|
39
|
-
latency: this.options.ratelimiterOffset,
|
|
40
|
-
raw: new Array(10).fill(this.options.ratelimiterOffset),
|
|
41
|
-
timeOffset: 0,
|
|
42
|
-
timeOffsets: new Array(10).fill(0),
|
|
43
|
-
lastTimeOffsetCheck: 0,
|
|
44
|
-
};
|
|
45
|
-
this.globalBlock = false;
|
|
46
|
-
this.readyQueue = [];
|
|
47
|
-
if (this.options.forceQueueing) {
|
|
48
|
-
this.globalBlock = true;
|
|
49
|
-
this._client.once("shardPreReady", () => this.globalUnblock());
|
|
50
|
-
}
|
|
51
|
-
}
|
|
52
|
-
|
|
53
|
-
globalUnblock() {
|
|
54
|
-
this.globalBlock = false;
|
|
55
|
-
while (this.readyQueue.length > 0) {
|
|
56
|
-
this.readyQueue.shift()();
|
|
57
|
-
}
|
|
58
|
-
}
|
|
59
|
-
|
|
60
|
-
/**
|
|
61
|
-
* Make an API request
|
|
62
|
-
* @arg {String} method Uppercase HTTP method
|
|
63
|
-
* @arg {String} url URL of the endpoint
|
|
64
|
-
* @arg {Boolean} [auth] Whether to add the Authorization header and token or not
|
|
65
|
-
* @arg {Object} [body] Request payload
|
|
66
|
-
* @arg {Object} [file] File object
|
|
67
|
-
* @arg {Buffer} file.file A buffer containing file data
|
|
68
|
-
* @arg {String} file.name What to name the file
|
|
69
|
-
* @arg {String} [_route] The ratelimiting route of the request, computed from the URL by default
|
|
70
|
-
* @arg {Boolean} [short] Whether to prioritize the request in its ratelimiting queue
|
|
71
|
-
* @arg {Object} [options] Additional request options
|
|
72
|
-
* @arg {Object<String, String>} [options.headers] Additional headers to send
|
|
73
|
-
* @arg {Boolean} [options.rawBody] Whether to send the body as is. By default, a `reason` in the body is sent as the audit log reason instead
|
|
74
|
-
* @returns {Promise<Object>} Resolves with the returned JSON data
|
|
75
|
-
*/
|
|
76
|
-
request(method, url, auth, body, file, _route, short, options = {}) {
|
|
77
|
-
const route = _route || this.routefy(url, method);
|
|
78
|
-
|
|
79
|
-
const _stackHolder = {}; // Preserve async stack
|
|
80
|
-
Error.captureStackTrace(_stackHolder);
|
|
81
|
-
|
|
82
|
-
return new Promise((resolve, reject) => {
|
|
83
|
-
let attempts = 0;
|
|
84
|
-
|
|
85
|
-
const actualCall = (cb) => {
|
|
86
|
-
const headers = Object.assign({
|
|
87
|
-
"User-Agent": this.userAgent,
|
|
88
|
-
"Accept-Encoding": "gzip,deflate",
|
|
89
|
-
}, options.headers);
|
|
90
|
-
let data;
|
|
91
|
-
let finalURL = url;
|
|
92
|
-
|
|
93
|
-
try {
|
|
94
|
-
if (auth) {
|
|
95
|
-
headers.Authorization = this._client._token;
|
|
96
|
-
}
|
|
97
|
-
if (body && body.reason && !options.rawBody) { // Audit log reason sniping
|
|
98
|
-
let unencodedReason = body.reason;
|
|
99
|
-
if (this.options.decodeReasons) {
|
|
100
|
-
try {
|
|
101
|
-
if (unencodedReason.includes("%") && !unencodedReason.includes(" ")) {
|
|
102
|
-
unencodedReason = decodeURIComponent(unencodedReason);
|
|
103
|
-
}
|
|
104
|
-
} catch (err) {
|
|
105
|
-
this._client.emit("error", err);
|
|
106
|
-
}
|
|
107
|
-
}
|
|
108
|
-
headers["X-Audit-Log-Reason"] = encodeURIComponent(unencodedReason);
|
|
109
|
-
// The reason is removed from the body, so retries of this request get it from the options
|
|
110
|
-
options = Object.assign({}, options, {
|
|
111
|
-
headers: Object.assign({}, options.headers, { "X-Audit-Log-Reason": headers["X-Audit-Log-Reason"] }),
|
|
112
|
-
});
|
|
113
|
-
delete body.reason;
|
|
114
|
-
}
|
|
115
|
-
if (file) {
|
|
116
|
-
data = new MultipartData();
|
|
117
|
-
headers["Content-Type"] = "multipart/form-data; boundary=" + data.boundary;
|
|
118
|
-
|
|
119
|
-
if (Array.isArray(file)) {
|
|
120
|
-
file.forEach(function (f, i) {
|
|
121
|
-
if (!f.file) {
|
|
122
|
-
return;
|
|
123
|
-
}
|
|
124
|
-
data.attach(`files[${i}]`, f.file, f.name);
|
|
125
|
-
});
|
|
126
|
-
} else if (file.file) {
|
|
127
|
-
if (file.fieldName) {
|
|
128
|
-
data.attach(file.fieldName, file.file, file.name);
|
|
129
|
-
} else if (method === "POST" && url.endsWith("/stickers")) {
|
|
130
|
-
data.attach("file", file.file, file.name);
|
|
131
|
-
} else {
|
|
132
|
-
data.attach("files[0]", file.file, file.name);
|
|
133
|
-
}
|
|
134
|
-
} else {
|
|
135
|
-
throw new Error("Invalid file object");
|
|
136
|
-
}
|
|
137
|
-
|
|
138
|
-
if (body) {
|
|
139
|
-
for (const key in body) {
|
|
140
|
-
data.attach(key, body[key]);
|
|
141
|
-
}
|
|
142
|
-
}
|
|
143
|
-
|
|
144
|
-
data = data.finish();
|
|
145
|
-
} else if (body) {
|
|
146
|
-
if (method === "GET" || method === "DELETE") {
|
|
147
|
-
let qs = "";
|
|
148
|
-
Object.keys(body).forEach(function (key) {
|
|
149
|
-
if (body[key] != undefined) {
|
|
150
|
-
if (Array.isArray(body[key])) {
|
|
151
|
-
body[key].forEach(function (val) {
|
|
152
|
-
qs += `&${encodeURIComponent(key)}=${encodeURIComponent(val)}`;
|
|
153
|
-
});
|
|
154
|
-
} else if (body[key] instanceof Date) {
|
|
155
|
-
qs += `&${encodeURIComponent(key)}=${body[key].toISOString()}`;
|
|
156
|
-
} else {
|
|
157
|
-
qs += `&${encodeURIComponent(key)}=${encodeURIComponent(body[key])}`;
|
|
158
|
-
}
|
|
159
|
-
}
|
|
160
|
-
});
|
|
161
|
-
finalURL += "?" + qs.substring(1);
|
|
162
|
-
} else {
|
|
163
|
-
// Replacer function serializes bigints to strings, the format Discord uses
|
|
164
|
-
data = JSON.stringify(body, (k, v) => typeof v === "bigint" ? v.toString() : v);
|
|
165
|
-
headers["Content-Type"] = "application/json";
|
|
166
|
-
}
|
|
167
|
-
}
|
|
168
|
-
} catch (err) {
|
|
169
|
-
cb();
|
|
170
|
-
reject(err);
|
|
171
|
-
return;
|
|
172
|
-
}
|
|
173
|
-
|
|
174
|
-
let req;
|
|
175
|
-
try {
|
|
176
|
-
req = HTTPS.request({
|
|
177
|
-
method: method,
|
|
178
|
-
host: this.options.domain,
|
|
179
|
-
path: this.options.baseURL + finalURL,
|
|
180
|
-
headers: headers,
|
|
181
|
-
agent: this.options.agent,
|
|
182
|
-
});
|
|
183
|
-
} catch (err) {
|
|
184
|
-
cb();
|
|
185
|
-
reject(err);
|
|
186
|
-
return;
|
|
187
|
-
}
|
|
188
|
-
|
|
189
|
-
let reqError;
|
|
190
|
-
|
|
191
|
-
req.once("abort", () => {
|
|
192
|
-
cb();
|
|
193
|
-
reqError = reqError || new Error(`Request aborted by client on ${method} ${url}`);
|
|
194
|
-
reqError.req = req;
|
|
195
|
-
reject(reqError);
|
|
196
|
-
}).once("error", (err) => {
|
|
197
|
-
reqError = err;
|
|
198
|
-
req.abort();
|
|
199
|
-
});
|
|
200
|
-
|
|
201
|
-
let latency = Date.now();
|
|
202
|
-
|
|
203
|
-
req.once("response", (resp) => {
|
|
204
|
-
latency = Date.now() - latency;
|
|
205
|
-
if (!this.options.disableLatencyCompensation) {
|
|
206
|
-
this.latencyRef.raw.push(latency);
|
|
207
|
-
this.latencyRef.latency = this.latencyRef.latency - ~~(this.latencyRef.raw.shift() / 10) + ~~(latency / 10);
|
|
208
|
-
}
|
|
209
|
-
|
|
210
|
-
if (this._client.listeners("rawREST").length) {
|
|
211
|
-
/**
|
|
212
|
-
* Fired when the Client's RequestHandler receives a response
|
|
213
|
-
* @event Client#rawREST
|
|
214
|
-
* @prop {Object} [request] The data for the request.
|
|
215
|
-
* @prop {Boolean} request.auth True if the request required an authorization token
|
|
216
|
-
* @prop {Object} [request.body] The request payload
|
|
217
|
-
* @prop {Object} [request.file] The file object sent in the request
|
|
218
|
-
* @prop {Buffer} request.file.file A buffer containing file data
|
|
219
|
-
* @prop {String} request.file.name The name of the file
|
|
220
|
-
* @prop {Number} request.latency The HTTP response latency
|
|
221
|
-
* @prop {String} request.method Uppercase HTTP method
|
|
222
|
-
* @prop {IncomingMessage} request.resp The HTTP response to the request
|
|
223
|
-
* @prop {String} request.route The calculated ratelimiting route for the request
|
|
224
|
-
* @prop {Boolean} request.short Whether or not the request was prioritized in its ratelimiting queue
|
|
225
|
-
* @prop {String} request.url URL of the endpoint
|
|
226
|
-
*/
|
|
227
|
-
this._client.emit("rawREST", { method, url, auth, body, file, route, short, resp, latency });
|
|
228
|
-
}
|
|
229
|
-
|
|
230
|
-
const headerNow = Date.parse(resp.headers["date"]);
|
|
231
|
-
if (this.latencyRef.lastTimeOffsetCheck < Date.now() - 5000) {
|
|
232
|
-
const timeOffset = headerNow + 500 - (this.latencyRef.lastTimeOffsetCheck = Date.now());
|
|
233
|
-
if (this.latencyRef.timeOffset - this.latencyRef.latency >= this.options.latencyThreshold && timeOffset - this.latencyRef.latency >= this.options.latencyThreshold) {
|
|
234
|
-
this._client.emit("warn", new Error(`Your clock is ${this.latencyRef.timeOffset}ms behind Discord's server clock. Please check your connection and system time.`));
|
|
235
|
-
}
|
|
236
|
-
this.latencyRef.timeOffset = this.latencyRef.timeOffset - ~~(this.latencyRef.timeOffsets.shift() / 10) + ~~(timeOffset / 10);
|
|
237
|
-
this.latencyRef.timeOffsets.push(timeOffset);
|
|
238
|
-
}
|
|
239
|
-
|
|
240
|
-
resp.once("aborted", () => {
|
|
241
|
-
cb();
|
|
242
|
-
reqError = reqError || new Error(`Request aborted by server on ${method} ${url}`);
|
|
243
|
-
reqError.req = req;
|
|
244
|
-
reject(reqError);
|
|
245
|
-
});
|
|
246
|
-
|
|
247
|
-
let response = "";
|
|
248
|
-
|
|
249
|
-
let _respStream = resp;
|
|
250
|
-
if (resp.headers["content-encoding"]) {
|
|
251
|
-
if (resp.headers["content-encoding"].includes("gzip")) {
|
|
252
|
-
_respStream = resp.pipe(Zlib.createGunzip());
|
|
253
|
-
} else if (resp.headers["content-encoding"].includes("deflate")) {
|
|
254
|
-
_respStream = resp.pipe(Zlib.createInflate());
|
|
255
|
-
}
|
|
256
|
-
}
|
|
257
|
-
|
|
258
|
-
_respStream.on("data", (str) => {
|
|
259
|
-
response += str;
|
|
260
|
-
}).on("error", (err) => {
|
|
261
|
-
reqError = err;
|
|
262
|
-
req.abort();
|
|
263
|
-
}).once("end", () => {
|
|
264
|
-
const now = Date.now();
|
|
265
|
-
|
|
266
|
-
if (resp.headers["x-ratelimit-limit"]) {
|
|
267
|
-
this.ratelimits[route].limit = +resp.headers["x-ratelimit-limit"];
|
|
268
|
-
}
|
|
269
|
-
|
|
270
|
-
if (method !== "GET" && (resp.headers["x-ratelimit-remaining"] == undefined || resp.headers["x-ratelimit-limit"] == undefined) && this.ratelimits[route].limit !== 1) {
|
|
271
|
-
this._client.emit("debug", `Missing ratelimit headers for SequentialBucket(${this.ratelimits[route].remaining}/${this.ratelimits[route].limit}) with non-default limit\n`
|
|
272
|
-
+ `${resp.statusCode} ${resp.headers["content-type"]}: ${method} ${route} | ${resp.headers["cf-ray"]}\n`
|
|
273
|
-
+ "x-ratelimit-remaining = " + resp.headers["x-ratelimit-remaining"] + "\n"
|
|
274
|
-
+ "x-ratelimit-limit = " + resp.headers["x-ratelimit-limit"] + "\n"
|
|
275
|
-
+ "x-ratelimit-reset = " + resp.headers["x-ratelimit-reset"] + "\n"
|
|
276
|
-
+ "x-ratelimit-global = " + resp.headers["x-ratelimit-global"]);
|
|
277
|
-
}
|
|
278
|
-
|
|
279
|
-
this.ratelimits[route].remaining = resp.headers["x-ratelimit-remaining"] === undefined ? 1 : +resp.headers["x-ratelimit-remaining"] || 0;
|
|
280
|
-
|
|
281
|
-
const retryAfter = Number(resp.headers["x-ratelimit-reset-after"] || resp.headers["retry-after"]) * 1000;
|
|
282
|
-
if (retryAfter >= 0) {
|
|
283
|
-
if (resp.headers["x-ratelimit-global"]) {
|
|
284
|
-
this.globalBlock = true;
|
|
285
|
-
setTimeout(() => this.globalUnblock(), retryAfter || 1);
|
|
286
|
-
} else {
|
|
287
|
-
this.ratelimits[route].reset = (retryAfter || 1) + now;
|
|
288
|
-
}
|
|
289
|
-
} else if (resp.headers["x-ratelimit-reset"]) {
|
|
290
|
-
let resetTime = +resp.headers["x-ratelimit-reset"] * 1000;
|
|
291
|
-
if (route.endsWith("/reactions/:id") && (+resp.headers["x-ratelimit-reset"] * 1000 - headerNow) === 1000) {
|
|
292
|
-
resetTime = now + 250;
|
|
293
|
-
}
|
|
294
|
-
this.ratelimits[route].reset = Math.max(resetTime - this.latencyRef.latency, now);
|
|
295
|
-
} else {
|
|
296
|
-
this.ratelimits[route].reset = now;
|
|
297
|
-
}
|
|
298
|
-
|
|
299
|
-
if (resp.statusCode !== 429) {
|
|
300
|
-
const content = typeof body === "object" ? `${body.content} ` : "";
|
|
301
|
-
this._client.emit("debug", `${content}${now} ${route} ${resp.statusCode}: ${latency}ms (${this.latencyRef.latency}ms avg) | ${this.ratelimits[route].remaining}/${this.ratelimits[route].limit} left | Reset ${this.ratelimits[route].reset} (${this.ratelimits[route].reset - now}ms left)`);
|
|
302
|
-
}
|
|
303
|
-
|
|
304
|
-
if (resp.statusCode >= 300) {
|
|
305
|
-
if (resp.statusCode === 429) {
|
|
306
|
-
const content = typeof body === "object" ? `${body.content} ` : "";
|
|
307
|
-
let delay = retryAfter;
|
|
308
|
-
if (resp.headers["x-ratelimit-scope"] === "shared") {
|
|
309
|
-
try {
|
|
310
|
-
delay = JSON.parse(response).retry_after * 1000;
|
|
311
|
-
} catch (err) {
|
|
312
|
-
reject(err);
|
|
313
|
-
return;
|
|
314
|
-
}
|
|
315
|
-
}
|
|
316
|
-
this._client.emit("debug", `${resp.headers["x-ratelimit-global"] ? "Global" : "Unexpected"} 429 (╯°□°)╯︵ ┻━┻: ${response}\n${content} ${now} ${route} ${resp.statusCode}: ${latency}ms (${this.latencyRef.latency}ms avg) | ${this.ratelimits[route].remaining}/${this.ratelimits[route].limit} left | Reset ${delay} (${this.ratelimits[route].reset - now}ms left) | Scope ${resp.headers["x-ratelimit-scope"]}`);
|
|
317
|
-
if (delay) {
|
|
318
|
-
setTimeout(() => {
|
|
319
|
-
cb();
|
|
320
|
-
this.request(method, url, auth, body, file, route, true, options).then(resolve).catch(reject);
|
|
321
|
-
}, delay);
|
|
322
|
-
return;
|
|
323
|
-
} else {
|
|
324
|
-
cb();
|
|
325
|
-
this.request(method, url, auth, body, file, route, true, options).then(resolve).catch(reject);
|
|
326
|
-
return;
|
|
327
|
-
}
|
|
328
|
-
} else if (resp.statusCode === 502 && ++attempts < 4) {
|
|
329
|
-
this._client.emit("debug", `A wild 502 appeared! Thanks CloudFlare! Retry ${attempts}/3`);
|
|
330
|
-
// Queued again in this same call, so the attempts keep counting
|
|
331
|
-
setTimeout(() => queueCall(true), Math.floor(Math.random() * 1900 + 100));
|
|
332
|
-
return cb();
|
|
333
|
-
}
|
|
334
|
-
cb();
|
|
335
|
-
|
|
336
|
-
if (response.length > 0) {
|
|
337
|
-
if (resp.headers["content-type"] === "application/json") {
|
|
338
|
-
try {
|
|
339
|
-
response = JSON.parse(response);
|
|
340
|
-
} catch (err) {
|
|
341
|
-
reject(err);
|
|
342
|
-
return;
|
|
343
|
-
}
|
|
344
|
-
}
|
|
345
|
-
}
|
|
346
|
-
|
|
347
|
-
let { stack } = _stackHolder;
|
|
348
|
-
if (stack.startsWith("Error\n")) {
|
|
349
|
-
stack = stack.substring(6);
|
|
350
|
-
}
|
|
351
|
-
let err;
|
|
352
|
-
if (response.code) {
|
|
353
|
-
err = new DiscordRESTError(req, resp, response, stack);
|
|
354
|
-
} else {
|
|
355
|
-
err = new DiscordHTTPError(req, resp, response, stack);
|
|
356
|
-
}
|
|
357
|
-
reject(err);
|
|
358
|
-
return;
|
|
359
|
-
}
|
|
360
|
-
|
|
361
|
-
if (response.length > 0) {
|
|
362
|
-
if (resp.headers["content-type"] === "application/json") {
|
|
363
|
-
try {
|
|
364
|
-
response = JSON.parse(response);
|
|
365
|
-
} catch (err) {
|
|
366
|
-
cb();
|
|
367
|
-
reject(err);
|
|
368
|
-
return;
|
|
369
|
-
}
|
|
370
|
-
}
|
|
371
|
-
}
|
|
372
|
-
|
|
373
|
-
cb();
|
|
374
|
-
resolve(response || undefined);
|
|
375
|
-
});
|
|
376
|
-
});
|
|
377
|
-
|
|
378
|
-
req.setTimeout(this.options.requestTimeout, () => {
|
|
379
|
-
reqError = new Error(`Request timed out (>${this.options.requestTimeout}ms) on ${method} ${url}`);
|
|
380
|
-
req.abort();
|
|
381
|
-
});
|
|
382
|
-
|
|
383
|
-
if (Array.isArray(data)) {
|
|
384
|
-
for (const chunk of data) {
|
|
385
|
-
req.write(chunk);
|
|
386
|
-
}
|
|
387
|
-
req.end();
|
|
388
|
-
} else {
|
|
389
|
-
req.end(data);
|
|
390
|
-
}
|
|
391
|
-
};
|
|
392
|
-
|
|
393
|
-
const queueCall = (short) => {
|
|
394
|
-
if (this.globalBlock && auth) {
|
|
395
|
-
this.readyQueue.push(() => {
|
|
396
|
-
if (!this.ratelimits[route]) {
|
|
397
|
-
this.ratelimits[route] = new SequentialBucket(1, this.latencyRef);
|
|
398
|
-
}
|
|
399
|
-
this.ratelimits[route].queue(actualCall, short);
|
|
400
|
-
});
|
|
401
|
-
} else {
|
|
402
|
-
if (!this.ratelimits[route]) {
|
|
403
|
-
this.ratelimits[route] = new SequentialBucket(1, this.latencyRef);
|
|
404
|
-
}
|
|
405
|
-
this.ratelimits[route].queue(actualCall, short);
|
|
406
|
-
}
|
|
407
|
-
};
|
|
408
|
-
|
|
409
|
-
queueCall(short);
|
|
410
|
-
});
|
|
411
|
-
}
|
|
412
|
-
|
|
413
|
-
routefy(url, method) {
|
|
414
|
-
let route = url.replace(/\/([a-z-]+)\/(?:[0-9]{17,19})/g, function (match, p) {
|
|
415
|
-
return p === "channels" || p === "guilds" || p === "webhooks" ? match : `/${p}/:id`;
|
|
416
|
-
}).replace(/\/reactions\/[^/]+/g, "/reactions/:id").replace(/\/reactions\/:id\/[^/]+/g, "/reactions/:id/:userID").replace(/^\/webhooks\/(\d+)\/[A-Za-z0-9-_]{64,}/, "/webhooks/$1/:token");
|
|
417
|
-
if (method === "DELETE" && route.endsWith("/messages/:id")) {
|
|
418
|
-
const messageID = url.slice(url.lastIndexOf("/") + 1);
|
|
419
|
-
const createdAt = Base.getCreatedAt(messageID);
|
|
420
|
-
if (Date.now() - this.latencyRef.latency - createdAt >= 1000 * 60 * 60 * 24 * 14) {
|
|
421
|
-
method += "_OLD";
|
|
422
|
-
} else if (Date.now() - this.latencyRef.latency - createdAt <= 1000 * 10) {
|
|
423
|
-
method += "_NEW";
|
|
424
|
-
}
|
|
425
|
-
route = method + route;
|
|
426
|
-
} else if (method === "GET" && /\/guilds\/[0-9]+\/channels$/.test(route)) {
|
|
427
|
-
route = "/guilds/:id/channels";
|
|
428
|
-
}
|
|
429
|
-
if (method === "PUT" || method === "DELETE") {
|
|
430
|
-
const index = route.indexOf("/reactions");
|
|
431
|
-
if (index !== -1) {
|
|
432
|
-
route = "MODIFY" + route.slice(0, index + 10);
|
|
433
|
-
}
|
|
434
|
-
}
|
|
435
|
-
return route;
|
|
436
|
-
}
|
|
437
|
-
|
|
438
|
-
[util.inspect.custom]() {
|
|
439
|
-
return Base.prototype[util.inspect.custom].call(this);
|
|
440
|
-
}
|
|
441
|
-
|
|
442
|
-
toString() {
|
|
443
|
-
return "[RequestHandler]";
|
|
444
|
-
}
|
|
445
|
-
|
|
446
|
-
toJSON(props = []) {
|
|
447
|
-
return Base.prototype.toJSON.call(this, [
|
|
448
|
-
"globalBlock",
|
|
449
|
-
"latencyRef",
|
|
450
|
-
"options",
|
|
451
|
-
"ratelimits",
|
|
452
|
-
"readyQueue",
|
|
453
|
-
"userAgent",
|
|
454
|
-
...props,
|
|
455
|
-
]);
|
|
456
|
-
}
|
|
457
|
-
}
|
|
458
|
-
|
|
459
|
-
module.exports = RequestHandler;
|
|
1
|
+
"use strict";
|
|
2
|
+
|
|
3
|
+
const util = require("util");
|
|
4
|
+
const Base = require("../structures/Base");
|
|
5
|
+
const DiscordHTTPError = require("../errors/DiscordHTTPError");
|
|
6
|
+
const DiscordRESTError = require("../errors/DiscordRESTError");
|
|
7
|
+
const Endpoints = require("./Endpoints");
|
|
8
|
+
const HTTPS = require("https");
|
|
9
|
+
const MultipartData = require("../util/MultipartData");
|
|
10
|
+
const SequentialBucket = require("../util/SequentialBucket");
|
|
11
|
+
const Zlib = require("zlib");
|
|
12
|
+
|
|
13
|
+
/**
|
|
14
|
+
* Handles API requests
|
|
15
|
+
*/
|
|
16
|
+
class RequestHandler {
|
|
17
|
+
constructor(client, options) {
|
|
18
|
+
// [DEPRECATED] Previously forceQueueing
|
|
19
|
+
if (typeof options === "boolean") {
|
|
20
|
+
options = {
|
|
21
|
+
forceQueueing: options,
|
|
22
|
+
};
|
|
23
|
+
}
|
|
24
|
+
this.options = options = Object.assign({
|
|
25
|
+
agent: client.options.agent || null,
|
|
26
|
+
baseURL: Endpoints.BASE_URL,
|
|
27
|
+
decodeReasons: true,
|
|
28
|
+
disableLatencyCompensation: false,
|
|
29
|
+
domain: "discord.com",
|
|
30
|
+
latencyThreshold: client.options.latencyThreshold || 30000,
|
|
31
|
+
ratelimiterOffset: client.options.ratelimiterOffset || 0,
|
|
32
|
+
requestTimeout: client.options.requestTimeout || 15000,
|
|
33
|
+
}, options);
|
|
34
|
+
|
|
35
|
+
this._client = client;
|
|
36
|
+
this.userAgent = `DiscordBot (https://github.com/abalabahaha/eris, ${require("../../package.json").version})`;
|
|
37
|
+
this.ratelimits = {};
|
|
38
|
+
this.latencyRef = {
|
|
39
|
+
latency: this.options.ratelimiterOffset,
|
|
40
|
+
raw: new Array(10).fill(this.options.ratelimiterOffset),
|
|
41
|
+
timeOffset: 0,
|
|
42
|
+
timeOffsets: new Array(10).fill(0),
|
|
43
|
+
lastTimeOffsetCheck: 0,
|
|
44
|
+
};
|
|
45
|
+
this.globalBlock = false;
|
|
46
|
+
this.readyQueue = [];
|
|
47
|
+
if (this.options.forceQueueing) {
|
|
48
|
+
this.globalBlock = true;
|
|
49
|
+
this._client.once("shardPreReady", () => this.globalUnblock());
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
globalUnblock() {
|
|
54
|
+
this.globalBlock = false;
|
|
55
|
+
while (this.readyQueue.length > 0) {
|
|
56
|
+
this.readyQueue.shift()();
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
/**
|
|
61
|
+
* Make an API request
|
|
62
|
+
* @arg {String} method Uppercase HTTP method
|
|
63
|
+
* @arg {String} url URL of the endpoint
|
|
64
|
+
* @arg {Boolean} [auth] Whether to add the Authorization header and token or not
|
|
65
|
+
* @arg {Object} [body] Request payload
|
|
66
|
+
* @arg {Object} [file] File object
|
|
67
|
+
* @arg {Buffer} file.file A buffer containing file data
|
|
68
|
+
* @arg {String} file.name What to name the file
|
|
69
|
+
* @arg {String} [_route] The ratelimiting route of the request, computed from the URL by default
|
|
70
|
+
* @arg {Boolean} [short] Whether to prioritize the request in its ratelimiting queue
|
|
71
|
+
* @arg {Object} [options] Additional request options
|
|
72
|
+
* @arg {Object<String, String>} [options.headers] Additional headers to send
|
|
73
|
+
* @arg {Boolean} [options.rawBody] Whether to send the body as is. By default, a `reason` in the body is sent as the audit log reason instead
|
|
74
|
+
* @returns {Promise<Object>} Resolves with the returned JSON data
|
|
75
|
+
*/
|
|
76
|
+
request(method, url, auth, body, file, _route, short, options = {}) {
|
|
77
|
+
const route = _route || this.routefy(url, method);
|
|
78
|
+
|
|
79
|
+
const _stackHolder = {}; // Preserve async stack
|
|
80
|
+
Error.captureStackTrace(_stackHolder);
|
|
81
|
+
|
|
82
|
+
return new Promise((resolve, reject) => {
|
|
83
|
+
let attempts = 0;
|
|
84
|
+
|
|
85
|
+
const actualCall = (cb) => {
|
|
86
|
+
const headers = Object.assign({
|
|
87
|
+
"User-Agent": this.userAgent,
|
|
88
|
+
"Accept-Encoding": "gzip,deflate",
|
|
89
|
+
}, options.headers);
|
|
90
|
+
let data;
|
|
91
|
+
let finalURL = url;
|
|
92
|
+
|
|
93
|
+
try {
|
|
94
|
+
if (auth) {
|
|
95
|
+
headers.Authorization = this._client._token;
|
|
96
|
+
}
|
|
97
|
+
if (body && body.reason && !options.rawBody) { // Audit log reason sniping
|
|
98
|
+
let unencodedReason = body.reason;
|
|
99
|
+
if (this.options.decodeReasons) {
|
|
100
|
+
try {
|
|
101
|
+
if (unencodedReason.includes("%") && !unencodedReason.includes(" ")) {
|
|
102
|
+
unencodedReason = decodeURIComponent(unencodedReason);
|
|
103
|
+
}
|
|
104
|
+
} catch (err) {
|
|
105
|
+
this._client.emit("error", err);
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
headers["X-Audit-Log-Reason"] = encodeURIComponent(unencodedReason);
|
|
109
|
+
// The reason is removed from the body, so retries of this request get it from the options
|
|
110
|
+
options = Object.assign({}, options, {
|
|
111
|
+
headers: Object.assign({}, options.headers, { "X-Audit-Log-Reason": headers["X-Audit-Log-Reason"] }),
|
|
112
|
+
});
|
|
113
|
+
delete body.reason;
|
|
114
|
+
}
|
|
115
|
+
if (file) {
|
|
116
|
+
data = new MultipartData();
|
|
117
|
+
headers["Content-Type"] = "multipart/form-data; boundary=" + data.boundary;
|
|
118
|
+
|
|
119
|
+
if (Array.isArray(file)) {
|
|
120
|
+
file.forEach(function (f, i) {
|
|
121
|
+
if (!f.file) {
|
|
122
|
+
return;
|
|
123
|
+
}
|
|
124
|
+
data.attach(`files[${i}]`, f.file, f.name);
|
|
125
|
+
});
|
|
126
|
+
} else if (file.file) {
|
|
127
|
+
if (file.fieldName) {
|
|
128
|
+
data.attach(file.fieldName, file.file, file.name);
|
|
129
|
+
} else if (method === "POST" && url.endsWith("/stickers")) {
|
|
130
|
+
data.attach("file", file.file, file.name);
|
|
131
|
+
} else {
|
|
132
|
+
data.attach("files[0]", file.file, file.name);
|
|
133
|
+
}
|
|
134
|
+
} else {
|
|
135
|
+
throw new Error("Invalid file object");
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
if (body) {
|
|
139
|
+
for (const key in body) {
|
|
140
|
+
data.attach(key, body[key]);
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
data = data.finish();
|
|
145
|
+
} else if (body) {
|
|
146
|
+
if (method === "GET" || method === "DELETE") {
|
|
147
|
+
let qs = "";
|
|
148
|
+
Object.keys(body).forEach(function (key) {
|
|
149
|
+
if (body[key] != undefined) {
|
|
150
|
+
if (Array.isArray(body[key])) {
|
|
151
|
+
body[key].forEach(function (val) {
|
|
152
|
+
qs += `&${encodeURIComponent(key)}=${encodeURIComponent(val)}`;
|
|
153
|
+
});
|
|
154
|
+
} else if (body[key] instanceof Date) {
|
|
155
|
+
qs += `&${encodeURIComponent(key)}=${body[key].toISOString()}`;
|
|
156
|
+
} else {
|
|
157
|
+
qs += `&${encodeURIComponent(key)}=${encodeURIComponent(body[key])}`;
|
|
158
|
+
}
|
|
159
|
+
}
|
|
160
|
+
});
|
|
161
|
+
finalURL += "?" + qs.substring(1);
|
|
162
|
+
} else {
|
|
163
|
+
// Replacer function serializes bigints to strings, the format Discord uses
|
|
164
|
+
data = JSON.stringify(body, (k, v) => typeof v === "bigint" ? v.toString() : v);
|
|
165
|
+
headers["Content-Type"] = "application/json";
|
|
166
|
+
}
|
|
167
|
+
}
|
|
168
|
+
} catch (err) {
|
|
169
|
+
cb();
|
|
170
|
+
reject(err);
|
|
171
|
+
return;
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
let req;
|
|
175
|
+
try {
|
|
176
|
+
req = HTTPS.request({
|
|
177
|
+
method: method,
|
|
178
|
+
host: this.options.domain,
|
|
179
|
+
path: this.options.baseURL + finalURL,
|
|
180
|
+
headers: headers,
|
|
181
|
+
agent: this.options.agent,
|
|
182
|
+
});
|
|
183
|
+
} catch (err) {
|
|
184
|
+
cb();
|
|
185
|
+
reject(err);
|
|
186
|
+
return;
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
let reqError;
|
|
190
|
+
|
|
191
|
+
req.once("abort", () => {
|
|
192
|
+
cb();
|
|
193
|
+
reqError = reqError || new Error(`Request aborted by client on ${method} ${url}`);
|
|
194
|
+
reqError.req = req;
|
|
195
|
+
reject(reqError);
|
|
196
|
+
}).once("error", (err) => {
|
|
197
|
+
reqError = err;
|
|
198
|
+
req.abort();
|
|
199
|
+
});
|
|
200
|
+
|
|
201
|
+
let latency = Date.now();
|
|
202
|
+
|
|
203
|
+
req.once("response", (resp) => {
|
|
204
|
+
latency = Date.now() - latency;
|
|
205
|
+
if (!this.options.disableLatencyCompensation) {
|
|
206
|
+
this.latencyRef.raw.push(latency);
|
|
207
|
+
this.latencyRef.latency = this.latencyRef.latency - ~~(this.latencyRef.raw.shift() / 10) + ~~(latency / 10);
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
if (this._client.listeners("rawREST").length) {
|
|
211
|
+
/**
|
|
212
|
+
* Fired when the Client's RequestHandler receives a response
|
|
213
|
+
* @event Client#rawREST
|
|
214
|
+
* @prop {Object} [request] The data for the request.
|
|
215
|
+
* @prop {Boolean} request.auth True if the request required an authorization token
|
|
216
|
+
* @prop {Object} [request.body] The request payload
|
|
217
|
+
* @prop {Object} [request.file] The file object sent in the request
|
|
218
|
+
* @prop {Buffer} request.file.file A buffer containing file data
|
|
219
|
+
* @prop {String} request.file.name The name of the file
|
|
220
|
+
* @prop {Number} request.latency The HTTP response latency
|
|
221
|
+
* @prop {String} request.method Uppercase HTTP method
|
|
222
|
+
* @prop {IncomingMessage} request.resp The HTTP response to the request
|
|
223
|
+
* @prop {String} request.route The calculated ratelimiting route for the request
|
|
224
|
+
* @prop {Boolean} request.short Whether or not the request was prioritized in its ratelimiting queue
|
|
225
|
+
* @prop {String} request.url URL of the endpoint
|
|
226
|
+
*/
|
|
227
|
+
this._client.emit("rawREST", { method, url, auth, body, file, route, short, resp, latency });
|
|
228
|
+
}
|
|
229
|
+
|
|
230
|
+
const headerNow = Date.parse(resp.headers["date"]);
|
|
231
|
+
if (this.latencyRef.lastTimeOffsetCheck < Date.now() - 5000) {
|
|
232
|
+
const timeOffset = headerNow + 500 - (this.latencyRef.lastTimeOffsetCheck = Date.now());
|
|
233
|
+
if (this.latencyRef.timeOffset - this.latencyRef.latency >= this.options.latencyThreshold && timeOffset - this.latencyRef.latency >= this.options.latencyThreshold) {
|
|
234
|
+
this._client.emit("warn", new Error(`Your clock is ${this.latencyRef.timeOffset}ms behind Discord's server clock. Please check your connection and system time.`));
|
|
235
|
+
}
|
|
236
|
+
this.latencyRef.timeOffset = this.latencyRef.timeOffset - ~~(this.latencyRef.timeOffsets.shift() / 10) + ~~(timeOffset / 10);
|
|
237
|
+
this.latencyRef.timeOffsets.push(timeOffset);
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
resp.once("aborted", () => {
|
|
241
|
+
cb();
|
|
242
|
+
reqError = reqError || new Error(`Request aborted by server on ${method} ${url}`);
|
|
243
|
+
reqError.req = req;
|
|
244
|
+
reject(reqError);
|
|
245
|
+
});
|
|
246
|
+
|
|
247
|
+
let response = "";
|
|
248
|
+
|
|
249
|
+
let _respStream = resp;
|
|
250
|
+
if (resp.headers["content-encoding"]) {
|
|
251
|
+
if (resp.headers["content-encoding"].includes("gzip")) {
|
|
252
|
+
_respStream = resp.pipe(Zlib.createGunzip());
|
|
253
|
+
} else if (resp.headers["content-encoding"].includes("deflate")) {
|
|
254
|
+
_respStream = resp.pipe(Zlib.createInflate());
|
|
255
|
+
}
|
|
256
|
+
}
|
|
257
|
+
|
|
258
|
+
_respStream.on("data", (str) => {
|
|
259
|
+
response += str;
|
|
260
|
+
}).on("error", (err) => {
|
|
261
|
+
reqError = err;
|
|
262
|
+
req.abort();
|
|
263
|
+
}).once("end", () => {
|
|
264
|
+
const now = Date.now();
|
|
265
|
+
|
|
266
|
+
if (resp.headers["x-ratelimit-limit"]) {
|
|
267
|
+
this.ratelimits[route].limit = +resp.headers["x-ratelimit-limit"];
|
|
268
|
+
}
|
|
269
|
+
|
|
270
|
+
if (method !== "GET" && (resp.headers["x-ratelimit-remaining"] == undefined || resp.headers["x-ratelimit-limit"] == undefined) && this.ratelimits[route].limit !== 1) {
|
|
271
|
+
this._client.emit("debug", `Missing ratelimit headers for SequentialBucket(${this.ratelimits[route].remaining}/${this.ratelimits[route].limit}) with non-default limit\n`
|
|
272
|
+
+ `${resp.statusCode} ${resp.headers["content-type"]}: ${method} ${route} | ${resp.headers["cf-ray"]}\n`
|
|
273
|
+
+ "x-ratelimit-remaining = " + resp.headers["x-ratelimit-remaining"] + "\n"
|
|
274
|
+
+ "x-ratelimit-limit = " + resp.headers["x-ratelimit-limit"] + "\n"
|
|
275
|
+
+ "x-ratelimit-reset = " + resp.headers["x-ratelimit-reset"] + "\n"
|
|
276
|
+
+ "x-ratelimit-global = " + resp.headers["x-ratelimit-global"]);
|
|
277
|
+
}
|
|
278
|
+
|
|
279
|
+
this.ratelimits[route].remaining = resp.headers["x-ratelimit-remaining"] === undefined ? 1 : +resp.headers["x-ratelimit-remaining"] || 0;
|
|
280
|
+
|
|
281
|
+
const retryAfter = Number(resp.headers["x-ratelimit-reset-after"] || resp.headers["retry-after"]) * 1000;
|
|
282
|
+
if (retryAfter >= 0) {
|
|
283
|
+
if (resp.headers["x-ratelimit-global"]) {
|
|
284
|
+
this.globalBlock = true;
|
|
285
|
+
setTimeout(() => this.globalUnblock(), retryAfter || 1);
|
|
286
|
+
} else {
|
|
287
|
+
this.ratelimits[route].reset = (retryAfter || 1) + now;
|
|
288
|
+
}
|
|
289
|
+
} else if (resp.headers["x-ratelimit-reset"]) {
|
|
290
|
+
let resetTime = +resp.headers["x-ratelimit-reset"] * 1000;
|
|
291
|
+
if (route.endsWith("/reactions/:id") && (+resp.headers["x-ratelimit-reset"] * 1000 - headerNow) === 1000) {
|
|
292
|
+
resetTime = now + 250;
|
|
293
|
+
}
|
|
294
|
+
this.ratelimits[route].reset = Math.max(resetTime - this.latencyRef.latency, now);
|
|
295
|
+
} else {
|
|
296
|
+
this.ratelimits[route].reset = now;
|
|
297
|
+
}
|
|
298
|
+
|
|
299
|
+
if (resp.statusCode !== 429) {
|
|
300
|
+
const content = typeof body === "object" ? `${body.content} ` : "";
|
|
301
|
+
this._client.emit("debug", `${content}${now} ${route} ${resp.statusCode}: ${latency}ms (${this.latencyRef.latency}ms avg) | ${this.ratelimits[route].remaining}/${this.ratelimits[route].limit} left | Reset ${this.ratelimits[route].reset} (${this.ratelimits[route].reset - now}ms left)`);
|
|
302
|
+
}
|
|
303
|
+
|
|
304
|
+
if (resp.statusCode >= 300) {
|
|
305
|
+
if (resp.statusCode === 429) {
|
|
306
|
+
const content = typeof body === "object" ? `${body.content} ` : "";
|
|
307
|
+
let delay = retryAfter;
|
|
308
|
+
if (resp.headers["x-ratelimit-scope"] === "shared") {
|
|
309
|
+
try {
|
|
310
|
+
delay = JSON.parse(response).retry_after * 1000;
|
|
311
|
+
} catch (err) {
|
|
312
|
+
reject(err);
|
|
313
|
+
return;
|
|
314
|
+
}
|
|
315
|
+
}
|
|
316
|
+
this._client.emit("debug", `${resp.headers["x-ratelimit-global"] ? "Global" : "Unexpected"} 429 (╯°□°)╯︵ ┻━┻: ${response}\n${content} ${now} ${route} ${resp.statusCode}: ${latency}ms (${this.latencyRef.latency}ms avg) | ${this.ratelimits[route].remaining}/${this.ratelimits[route].limit} left | Reset ${delay} (${this.ratelimits[route].reset - now}ms left) | Scope ${resp.headers["x-ratelimit-scope"]}`);
|
|
317
|
+
if (delay) {
|
|
318
|
+
setTimeout(() => {
|
|
319
|
+
cb();
|
|
320
|
+
this.request(method, url, auth, body, file, route, true, options).then(resolve).catch(reject);
|
|
321
|
+
}, delay);
|
|
322
|
+
return;
|
|
323
|
+
} else {
|
|
324
|
+
cb();
|
|
325
|
+
this.request(method, url, auth, body, file, route, true, options).then(resolve).catch(reject);
|
|
326
|
+
return;
|
|
327
|
+
}
|
|
328
|
+
} else if (resp.statusCode === 502 && ++attempts < 4) {
|
|
329
|
+
this._client.emit("debug", `A wild 502 appeared! Thanks CloudFlare! Retry ${attempts}/3`);
|
|
330
|
+
// Queued again in this same call, so the attempts keep counting
|
|
331
|
+
setTimeout(() => queueCall(true), Math.floor(Math.random() * 1900 + 100));
|
|
332
|
+
return cb();
|
|
333
|
+
}
|
|
334
|
+
cb();
|
|
335
|
+
|
|
336
|
+
if (response.length > 0) {
|
|
337
|
+
if (resp.headers["content-type"] === "application/json") {
|
|
338
|
+
try {
|
|
339
|
+
response = JSON.parse(response);
|
|
340
|
+
} catch (err) {
|
|
341
|
+
reject(err);
|
|
342
|
+
return;
|
|
343
|
+
}
|
|
344
|
+
}
|
|
345
|
+
}
|
|
346
|
+
|
|
347
|
+
let { stack } = _stackHolder;
|
|
348
|
+
if (stack.startsWith("Error\n")) {
|
|
349
|
+
stack = stack.substring(6);
|
|
350
|
+
}
|
|
351
|
+
let err;
|
|
352
|
+
if (response.code) {
|
|
353
|
+
err = new DiscordRESTError(req, resp, response, stack);
|
|
354
|
+
} else {
|
|
355
|
+
err = new DiscordHTTPError(req, resp, response, stack);
|
|
356
|
+
}
|
|
357
|
+
reject(err);
|
|
358
|
+
return;
|
|
359
|
+
}
|
|
360
|
+
|
|
361
|
+
if (response.length > 0) {
|
|
362
|
+
if (resp.headers["content-type"] === "application/json") {
|
|
363
|
+
try {
|
|
364
|
+
response = JSON.parse(response);
|
|
365
|
+
} catch (err) {
|
|
366
|
+
cb();
|
|
367
|
+
reject(err);
|
|
368
|
+
return;
|
|
369
|
+
}
|
|
370
|
+
}
|
|
371
|
+
}
|
|
372
|
+
|
|
373
|
+
cb();
|
|
374
|
+
resolve(response || undefined);
|
|
375
|
+
});
|
|
376
|
+
});
|
|
377
|
+
|
|
378
|
+
req.setTimeout(this.options.requestTimeout, () => {
|
|
379
|
+
reqError = new Error(`Request timed out (>${this.options.requestTimeout}ms) on ${method} ${url}`);
|
|
380
|
+
req.abort();
|
|
381
|
+
});
|
|
382
|
+
|
|
383
|
+
if (Array.isArray(data)) {
|
|
384
|
+
for (const chunk of data) {
|
|
385
|
+
req.write(chunk);
|
|
386
|
+
}
|
|
387
|
+
req.end();
|
|
388
|
+
} else {
|
|
389
|
+
req.end(data);
|
|
390
|
+
}
|
|
391
|
+
};
|
|
392
|
+
|
|
393
|
+
const queueCall = (short) => {
|
|
394
|
+
if (this.globalBlock && auth) {
|
|
395
|
+
this.readyQueue.push(() => {
|
|
396
|
+
if (!this.ratelimits[route]) {
|
|
397
|
+
this.ratelimits[route] = new SequentialBucket(1, this.latencyRef);
|
|
398
|
+
}
|
|
399
|
+
this.ratelimits[route].queue(actualCall, short);
|
|
400
|
+
});
|
|
401
|
+
} else {
|
|
402
|
+
if (!this.ratelimits[route]) {
|
|
403
|
+
this.ratelimits[route] = new SequentialBucket(1, this.latencyRef);
|
|
404
|
+
}
|
|
405
|
+
this.ratelimits[route].queue(actualCall, short);
|
|
406
|
+
}
|
|
407
|
+
};
|
|
408
|
+
|
|
409
|
+
queueCall(short);
|
|
410
|
+
});
|
|
411
|
+
}
|
|
412
|
+
|
|
413
|
+
routefy(url, method) {
|
|
414
|
+
let route = url.replace(/\/([a-z-]+)\/(?:[0-9]{17,19})/g, function (match, p) {
|
|
415
|
+
return p === "channels" || p === "guilds" || p === "webhooks" ? match : `/${p}/:id`;
|
|
416
|
+
}).replace(/\/reactions\/[^/]+/g, "/reactions/:id").replace(/\/reactions\/:id\/[^/]+/g, "/reactions/:id/:userID").replace(/^\/webhooks\/(\d+)\/[A-Za-z0-9-_]{64,}/, "/webhooks/$1/:token");
|
|
417
|
+
if (method === "DELETE" && route.endsWith("/messages/:id")) {
|
|
418
|
+
const messageID = url.slice(url.lastIndexOf("/") + 1);
|
|
419
|
+
const createdAt = Base.getCreatedAt(messageID);
|
|
420
|
+
if (Date.now() - this.latencyRef.latency - createdAt >= 1000 * 60 * 60 * 24 * 14) {
|
|
421
|
+
method += "_OLD";
|
|
422
|
+
} else if (Date.now() - this.latencyRef.latency - createdAt <= 1000 * 10) {
|
|
423
|
+
method += "_NEW";
|
|
424
|
+
}
|
|
425
|
+
route = method + route;
|
|
426
|
+
} else if (method === "GET" && /\/guilds\/[0-9]+\/channels$/.test(route)) {
|
|
427
|
+
route = "/guilds/:id/channels";
|
|
428
|
+
}
|
|
429
|
+
if (method === "PUT" || method === "DELETE") {
|
|
430
|
+
const index = route.indexOf("/reactions");
|
|
431
|
+
if (index !== -1) {
|
|
432
|
+
route = "MODIFY" + route.slice(0, index + 10);
|
|
433
|
+
}
|
|
434
|
+
}
|
|
435
|
+
return route;
|
|
436
|
+
}
|
|
437
|
+
|
|
438
|
+
[util.inspect.custom]() {
|
|
439
|
+
return Base.prototype[util.inspect.custom].call(this);
|
|
440
|
+
}
|
|
441
|
+
|
|
442
|
+
toString() {
|
|
443
|
+
return "[RequestHandler]";
|
|
444
|
+
}
|
|
445
|
+
|
|
446
|
+
toJSON(props = []) {
|
|
447
|
+
return Base.prototype.toJSON.call(this, [
|
|
448
|
+
"globalBlock",
|
|
449
|
+
"latencyRef",
|
|
450
|
+
"options",
|
|
451
|
+
"ratelimits",
|
|
452
|
+
"readyQueue",
|
|
453
|
+
"userAgent",
|
|
454
|
+
...props,
|
|
455
|
+
]);
|
|
456
|
+
}
|
|
457
|
+
}
|
|
458
|
+
|
|
459
|
+
module.exports = RequestHandler;
|