/
RestActionImpl.java
322 lines (276 loc) · 9.87 KB
/
RestActionImpl.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
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
/*
* Copyright 2015-2020 Austin Keener, Michael Ritter, Florian Spieß, and the JDA contributors
*
* 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.internal.requests;
import net.dv8tion.jda.api.JDA;
import net.dv8tion.jda.api.exceptions.ErrorResponseException;
import net.dv8tion.jda.api.exceptions.RateLimitedException;
import net.dv8tion.jda.api.requests.Request;
import net.dv8tion.jda.api.requests.Response;
import net.dv8tion.jda.api.requests.RestAction;
import net.dv8tion.jda.api.requests.RestFuture;
import net.dv8tion.jda.api.utils.data.DataArray;
import net.dv8tion.jda.api.utils.data.DataObject;
import net.dv8tion.jda.internal.JDAImpl;
import net.dv8tion.jda.internal.utils.Checks;
import net.dv8tion.jda.internal.utils.JDALogger;
import okhttp3.RequestBody;
import org.apache.commons.collections4.map.CaseInsensitiveMap;
import org.slf4j.Logger;
import javax.annotation.Nonnull;
import java.util.concurrent.*;
import java.util.function.BiFunction;
import java.util.function.BooleanSupplier;
import java.util.function.Consumer;
public class RestActionImpl<T> implements RestAction<T>
{
public static final Logger LOG = JDALogger.getLog(RestAction.class);
private static Consumer<Object> DEFAULT_SUCCESS = o -> {};
private static Consumer<? super Throwable> DEFAULT_FAILURE = t ->
{
if (t instanceof CancellationException || t instanceof TimeoutException)
LOG.debug(t.getMessage());
else if (LOG.isDebugEnabled() || !(t instanceof ErrorResponseException))
LOG.error("RestAction queue returned failure", t);
else if (t.getCause() != null)
LOG.error("RestAction queue returned failure: [{}] {}", t.getClass().getSimpleName(), t.getMessage(), t.getCause());
else
LOG.error("RestAction queue returned failure: [{}] {}", t.getClass().getSimpleName(), t.getMessage());
};
protected static boolean passContext = true;
protected static long defaultTimeout = 0;
protected final JDAImpl api;
private final Route.CompiledRoute route;
private final RequestBody data;
private final BiFunction<Response, Request<T>, T> handler;
private boolean priority = false;
private long deadline = 0;
private Object rawData;
private BooleanSupplier checks;
public static void setPassContext(boolean enable)
{
passContext = enable;
}
public static boolean isPassContext()
{
return passContext;
}
public static void setDefaultFailure(final Consumer<? super Throwable> callback)
{
DEFAULT_FAILURE = callback == null ? t -> {} : callback;
}
public static void setDefaultSuccess(final Consumer<Object> callback)
{
DEFAULT_SUCCESS = callback == null ? t -> {} : callback;
}
public static void setDefaultTimeout(long timeout, @Nonnull TimeUnit unit)
{
Checks.notNull(unit, "TimeUnit");
defaultTimeout = unit.toMillis(timeout);
}
public static long getDefaultTimeout()
{
return defaultTimeout;
}
public static Consumer<? super Throwable> getDefaultFailure()
{
return DEFAULT_FAILURE;
}
public static Consumer<Object> getDefaultSuccess()
{
return DEFAULT_SUCCESS;
}
public RestActionImpl(JDA api, Route.CompiledRoute route)
{
this(api, route, (RequestBody) null, null);
}
public RestActionImpl(JDA api, Route.CompiledRoute route, DataObject data)
{
this(api, route, data, null);
}
public RestActionImpl(JDA api, Route.CompiledRoute route, RequestBody data)
{
this(api, route, data, null);
}
public RestActionImpl(JDA api, Route.CompiledRoute route, BiFunction<Response, Request<T>, T> handler)
{
this(api, route, (RequestBody) null, handler);
}
public RestActionImpl(JDA api, Route.CompiledRoute route, DataObject data, BiFunction<Response, Request<T>, T> handler)
{
this(api, route, data == null ? null : RequestBody.create(Requester.MEDIA_TYPE_JSON, data.toJson()), handler);
this.rawData = data;
}
public RestActionImpl(JDA api, Route.CompiledRoute route, RequestBody data, BiFunction<Response, Request<T>, T> handler)
{
Checks.notNull(api, "api");
this.api = (JDAImpl) api;
this.route = route;
this.data = data;
this.handler = handler;
}
public RestActionImpl<T> priority()
{
priority = true;
return this;
}
@Nonnull
@Override
public JDA getJDA()
{
return api;
}
@Nonnull
@Override
public RestAction<T> setCheck(BooleanSupplier checks)
{
this.checks = checks;
return this;
}
@Nonnull
@Override
public RestAction<T> deadline(long timestamp)
{
this.deadline = timestamp;
return this;
}
@Override
public void queue(Consumer<? super T> success, Consumer<? super Throwable> failure)
{
Route.CompiledRoute route = finalizeRoute();
Checks.notNull(route, "Route");
RequestBody data = finalizeData();
CaseInsensitiveMap<String, String> headers = finalizeHeaders();
BooleanSupplier finisher = getFinisher();
if (success == null)
success = DEFAULT_SUCCESS;
if (failure == null)
failure = DEFAULT_FAILURE;
api.getRequester().request(new Request<>(this, success, failure, finisher, true, data, rawData, getDeadline(), priority, route, headers));
}
@Nonnull
@Override
public CompletableFuture<T> submit(boolean shouldQueue)
{
Route.CompiledRoute route = finalizeRoute();
Checks.notNull(route, "Route");
RequestBody data = finalizeData();
CaseInsensitiveMap<String, String> headers = finalizeHeaders();
BooleanSupplier finisher = getFinisher();
return new RestFuture<>(this, shouldQueue, finisher, data, rawData, getDeadline(), priority, route, headers);
}
@Override
public T complete(boolean shouldQueue) throws RateLimitedException
{
if (CallbackContext.isCallbackContext())
throw new IllegalStateException("Preventing use of complete() in callback threads! This operation can be a deadlock cause");
try
{
return submit(shouldQueue).join();
}
catch (CompletionException e)
{
if (e.getCause() != null)
{
Throwable cause = e.getCause();
if (cause instanceof RuntimeException)
throw (RuntimeException) cause;
else if (cause instanceof Error)
throw (Error) cause;
else if (cause instanceof RateLimitedException)
throw (RateLimitedException) cause;
}
throw e;
}
}
protected RequestBody finalizeData() { return data; }
protected Route.CompiledRoute finalizeRoute() { return route; }
protected CaseInsensitiveMap<String, String> finalizeHeaders() { return null; }
protected BooleanSupplier finalizeChecks() { return null; }
protected RequestBody getRequestBody(DataObject object)
{
this.rawData = object;
return object == null ? null : RequestBody.create(Requester.MEDIA_TYPE_JSON, object.toJson());
}
protected RequestBody getRequestBody(DataArray array)
{
this.rawData = array;
return array == null ? null : RequestBody.create(Requester.MEDIA_TYPE_JSON, array.toJson());
}
private CheckWrapper getFinisher()
{
BooleanSupplier pre = finalizeChecks();
BooleanSupplier wrapped = this.checks;
return (pre != null || wrapped != null) ? new CheckWrapper(wrapped, pre) : CheckWrapper.EMPTY;
}
public void handleResponse(Response response, Request<T> request)
{
if (response.isOk())
handleSuccess(response, request);
else
request.onFailure(response);
}
protected void handleSuccess(Response response, Request<T> request)
{
if (handler == null)
request.onSuccess(null);
else
request.onSuccess(handler.apply(response, request));
}
private long getDeadline()
{
return deadline > 0
? deadline
: defaultTimeout > 0
? System.currentTimeMillis() + defaultTimeout
: 0;
}
/*
useful for final permission checks:
@Override
protected BooleanSupplier finalizeChecks()
{
// throw exception, if missing perms
return () -> hasPermission(Permission.MESSAGE_WRITE);
}
*/
protected static class CheckWrapper implements BooleanSupplier
{
public static final CheckWrapper EMPTY = new CheckWrapper(null, null)
{
public boolean getAsBoolean() { return true; }
};
protected final BooleanSupplier pre;
protected final BooleanSupplier wrapped;
public CheckWrapper(BooleanSupplier wrapped, BooleanSupplier pre)
{
this.pre = pre;
this.wrapped = wrapped;
}
public boolean pre()
{
return pre == null || pre.getAsBoolean();
}
public boolean test()
{
return wrapped == null || wrapped.getAsBoolean();
}
@Override
public boolean getAsBoolean()
{
return pre() && test();
}
}
}