-
-
Notifications
You must be signed in to change notification settings - Fork 724
/
Requester.java
192 lines (174 loc) · 6.69 KB
/
Requester.java
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
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
/*
* Copyright 2015-2016 Austin Keener & Michael Ritter
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.dv8tion.jda.core.requests;
import com.mashape.unirest.http.HttpResponse;
import com.mashape.unirest.http.Unirest;
import com.mashape.unirest.http.exceptions.UnirestException;
import com.mashape.unirest.request.BaseRequest;
import com.mashape.unirest.request.GetRequest;
import com.mashape.unirest.request.HttpRequest;
import net.dv8tion.jda.core.AccountType;
import net.dv8tion.jda.core.JDA;
import net.dv8tion.jda.core.JDAInfo;
import net.dv8tion.jda.core.requests.Route.CompiledRoute;
import net.dv8tion.jda.core.requests.ratelimit.BotRateLimiter;
import net.dv8tion.jda.core.requests.ratelimit.ClientRateLimiter;
import net.dv8tion.jda.core.requests.ratelimit.IBucket;
import net.dv8tion.jda.core.utils.SimpleLog;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class Requester
{
public static final SimpleLog LOG = SimpleLog.getLog("JDARequester");
public static String USER_AGENT = "JDA DiscordBot (" + JDAInfo.GITHUB + ", " + JDAInfo.VERSION + ")";
public static final String DISCORD_API_PREFIX = "https://discordapp.com/api/";
private final JDA api;
private final RateLimiter rateLimiter;
public Requester(JDA api)
{
this(api, api.getAccountType());
}
public Requester(JDA api, AccountType accountType)
{
this.api = api;
if (accountType == AccountType.BOT)
rateLimiter = new BotRateLimiter(this, 5);
else
rateLimiter = new ClientRateLimiter(this, 5);
}
public void request(Request apiRequest)
{
if (rateLimiter.isShutdown)
throw new IllegalStateException("The Requester has been shutdown! No new requests can be requested!");
if (apiRequest.shouldQueue())
{
rateLimiter.queueRequest(apiRequest);
}
else
{
Long retryAfter = execute(apiRequest);
if (retryAfter != null)
apiRequest.getRestAction().handleResponse(new Response(429, null, retryAfter), apiRequest);
}
}
/**
* Used to execute an Request. Processes request related to provided bucket.
*
* @param apiRequest The API request that needs to be sent
* @return Returns non-null if the request was ratelimited. Returns a Long containing retry_after milliseconds until
* the request can be made again. This could either be for the Per-Route ratelimit or the Global ratelimit.
* Check if globalCooldown is null to determine if it was Per-Route or Global.
*/
public Long execute(Request apiRequest)
{
CompiledRoute route = apiRequest.getRoute();
Long retryAfter = rateLimiter.getRateLimit(route);
if (retryAfter != null)
return retryAfter;
Object body = apiRequest.getData();
String bodyData = body != null ? body.toString() : null;
BaseRequest request = createRequest(route, bodyData);
try
{
HttpResponse<String> response = request.asString();
int attempt = 1;
while (attempt < 4 && response.getStatus() != 429 && response.getBody() != null && response.getBody().startsWith("<"))
{
LOG.debug(String.format("Requesting %s -> %s returned HTML... retrying (attempt %d)",
request.getHttpRequest().getHttpMethod().name(),
request.getHttpRequest().getUrl(),
attempt));
try
{
Thread.sleep(50 * attempt);
}
catch (InterruptedException ignored)
{
}
response = request.asString();
attempt++;
}
if (response.getBody() != null && response.getBody().startsWith("<"))
{
//Epic failure due to cloudfare. Attempted 4 times.
return null;
}
retryAfter = rateLimiter.handleResponse(route, response);
if (retryAfter == null)
apiRequest.getRestAction().handleResponse(new Response(response.getStatus(), response.getBody(), -1), apiRequest);
return retryAfter;
}
catch (UnirestException e)
{
LOG.log(e); //This originally only printed on DEBUG in 2.x
apiRequest.getRestAction().handleResponse(new Response(e), apiRequest);
return null;
}
}
public RateLimiter getRateLimiter()
{
return rateLimiter;
}
public void shutdown()
{
rateLimiter.shutdown();
}
public List<IBucket> shutdownNow()
{
return rateLimiter.shutdownNow();
}
private BaseRequest createRequest(Route.CompiledRoute route, String body)
{
String url = DISCORD_API_PREFIX + route.getCompiledRoute();
BaseRequest request = null;
switch (route.getMethod())
{
case GET:
request = addHeaders(Unirest.get(url));
break;
case POST:
request = addHeaders(Unirest.post(url)).body(body);
break;
case PUT:
request = addHeaders(Unirest.put(url)).body(body);
break;
case DELETE:
request = addHeaders(Unirest.delete(url));
break;
case PATCH:
request = addHeaders(Unirest.patch(url)).body(body);
break;
}
return request;
}
protected <T extends HttpRequest> T addHeaders(T request)
{
//adding token to all requests to the discord api or cdn pages
//can't check for startsWith(DISCORD_API_PREFIX) due to cdn endpoints
if (api.getToken() != null && request.getUrl().contains("discordapp.com"))
{
request.header("authorization", api.getToken());
}
if (!(request instanceof GetRequest))
{
request.header("Content-Type", "application/json");
}
request.header("user-agent", USER_AGENT);
request.header("Accept-Encoding", "gzip");
return request;
}
}