Repository navigation
Expand file tree
/
Copy pathMaxBotBase.java
More file actions
260 lines (214 loc) · 8.57 KB
/
Copy pathMaxBotBase.java
File metadata and controls
260 lines (214 loc) · 8.57 KB
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
package ru.max.bot;
import java.lang.invoke.MethodHandle;
import java.lang.invoke.MethodHandles;
import java.lang.invoke.MethodType;
import java.lang.reflect.Method;
import java.lang.reflect.Parameter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import ru.max.bot.annotations.CommandHandler;
import ru.max.bot.annotations.UpdateHandler;
import ru.max.bot.commands.CommandLineParser;
import ru.max.bot.commands.RawCommandLine;
import ru.max.bot.updates.DefaultUpdateMapper;
import ru.max.botapi.client.MaxClient;
import ru.max.botapi.model.Message;
import ru.max.botapi.model.MessageCreatedUpdate;
import ru.max.botapi.model.Update;
import static java.lang.invoke.MethodHandles.filterReturnValue;
public class MaxBotBase implements MaxBot {
private static MethodHandle NO_RESPONSE;
static {
try {
NO_RESPONSE = MethodHandles.lookup().findStatic(MaxBotBase.class, "noResponse",
MethodType.methodType(Object.class));
} catch (NoSuchMethodException | IllegalAccessException e) {
// actually should never happens
throw new RuntimeException(e);
}
}
private final MaxClient client;
private final Map<Class<? extends Update>, MethodHandle> updateHandlers;
private final Map<String, CommandHandle> commandHandlers;
private final Update.Mapper<Object> rootHandler = new DefaultUpdateMapper<Object>() {
@Override
public Object map(MessageCreatedUpdate update) {
return tryHandleCommand(update);
}
@Override
public Object mapDefault(Update update) {
return handleUpdate(update);
}
};
public MaxBotBase(String accessToken, Object... handlers) {
this(MaxClient.create(accessToken), handlers);
}
public MaxBotBase(MaxClient client, Object... handlers) {
this.client = client;
this.updateHandlers = new HashMap<>();
this.commandHandlers = new HashMap<>();
addHandlers(this);
for (Object handler : handlers) {
addHandlers(handler);
}
}
@Override
public MaxClient getClient() {
return client;
}
@Nullable
@Override
public Object onUpdate(Update update) {
return update.map(rootHandler);
}
private static Object noResponse() {
return null;
}
private static MethodHandle unreflect(Method method) {
MethodHandle handle;
try {
handle = MethodHandles.lookup().unreflect(method);
} catch (IllegalAccessException e) {
// actually should never happens
throw new RuntimeException(e);
}
if (method.getReturnType().equals(void.class)) {
handle = filterReturnValue(handle, NO_RESPONSE);
}
return handle;
}
@NotNull
private static String prepareCommandKey(String cmdKey) {
if (cmdKey == null || cmdKey.isEmpty()) {
throw new IllegalArgumentException("Command key is empty");
}
if (cmdKey.charAt(0) == '/') {
return prepareCommandKey(cmdKey.substring(1));
}
return cmdKey.toLowerCase();
}
private Object handleUpdate(Update update) {
MethodHandle handler = updateHandlers.get(update.getClass());
if (handler == null) {
return null;
}
try {
return handler.invoke(update);
} catch (Throwable throwable) {
// should never happens
throw new RuntimeException(throwable);
}
}
private Object tryHandleCommand(MessageCreatedUpdate update) {
if (commandHandlers.isEmpty()) {
return handleUpdate(update);
}
Message message = update.getMessage();
String text = message.getBody().getText();
if (text == null || text.isEmpty()) {
return handleUpdate(update);
}
RawCommandLine commandLine = CommandLineParser.parseRaw(text);
if (commandLine == null) {
return handleUpdate(update);
}
String commandKey = commandLine.getKey();
CommandHandle commandHandler = commandHandlers.get(commandKey);
if (commandHandler == null) {
return handleUpdate(update);
}
String[] actualArgs;
if (commandHandler.shouldParseArgs) {
actualArgs = CommandLineParser.parseArgs(commandLine.getTail());
} else {
actualArgs = new String[]{commandLine.getTail()};
}
try {
Object[] invokeArgs = new Object[commandHandler.expectedArgs + 1];
invokeArgs[0] = message;
System.arraycopy(actualArgs, 0, invokeArgs, 1, Math.min(actualArgs.length, commandHandler.expectedArgs));
return commandHandler.handle.invokeWithArguments(invokeArgs);
} catch (Throwable throwable) {
throw new RuntimeException(throwable);
}
}
private void addHandlers(Object handler) {
List<Class> supers = new ArrayList<>(4);
for (Class<?> cls = handler.getClass(); cls != Object.class; cls = cls.getSuperclass()) {
supers.add(cls);
}
List<Method> updateHandlers = new ArrayList<>();
List<Method> commandHandlers = new ArrayList<>();
for (int i = supers.size(); --i >= 0; ) {
Class<?> cls = supers.get(i);
for (Method m : cls.getDeclaredMethods()) {
if (m.getAnnotation(UpdateHandler.class) != null) {
m.setAccessible(true);
updateHandlers.add(m);
}
if (m.getAnnotation(CommandHandler.class) != null) {
m.setAccessible(true);
commandHandlers.add(m);
}
}
}
for (Method updateHandler : updateHandlers) {
registerUpdateHandler(updateHandler, handler);
}
for (Method commandHandler : commandHandlers) {
registerCommandHandler(commandHandler, handler);
}
}
private void registerCommandHandler(Method method, Object target) {
Parameter[] parameters = method.getParameters();
if (parameters.length < 1) {
throw new IllegalArgumentException(
"Method " + method + " must match signature: (Message message, Object... args)");
}
Class<?> parameterType1 = method.getParameterTypes()[0];
if (!Message.class.isAssignableFrom(parameterType1)) {
throw new IllegalArgumentException(
"Method " + method + " must have only single parameter of type `Message`");
}
MethodHandle commandHandler = unreflect(method);
CommandHandler annotation = method.getAnnotation(CommandHandler.class);
commandHandler = commandHandler.bindTo(target);
String commandKey = prepareCommandKey(annotation.value());
boolean shouldParseArgs = annotation.parseArgs();
commandHandlers.put(commandKey, new CommandHandle(parameters.length - 1, shouldParseArgs, commandHandler));
}
private void registerUpdateHandler(Method method, Object target) {
Parameter[] parameters = method.getParameters();
if (parameters.length > 1) {
throw new IllegalArgumentException(
"Method " + method + " must only have single parameter of type `Update`");
}
Class<?> parameterType = method.getParameterTypes()[0];
if (!Update.class.isAssignableFrom(parameterType)) {
throw new IllegalArgumentException(
"Method " + method + " must have only single parameter of type `Update`");
}
MethodHandle mh = unreflect(method);
@SuppressWarnings("unchecked")
Class<? extends Update> updateClass = (Class<? extends Update>) parameterType;
MethodHandle prev = updateHandlers.put(updateClass, mh.bindTo(target));
if (prev != null) {
throw new IllegalStateException(
"Method " + method + " overrides already existing handler for update type " + updateClass);
}
}
private static class CommandHandle {
private final int expectedArgs;
private final boolean shouldParseArgs;
private final MethodHandle handle;
private CommandHandle(int expectedArgs, boolean shouldParseArgs, MethodHandle handle) {
this.expectedArgs = expectedArgs;
this.shouldParseArgs = shouldParseArgs;
this.handle = handle;
}
}
}