-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathBtDefault.java
225 lines (212 loc) · 7.01 KB
/
BtDefault.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
/*
* The MIT License (MIT)
*
* Copyright (c) 2022-2023 Ivanchuck Ivan.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included
* in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
/*
* @todo #60 Design/ Testing.
* Write tests for DefaultBot class after closing other issues in DefaultBot class.
* */
/*
* @todo #106 Fix #handleUpdates.
* This method work unpredictable,
* need to fix work with incoming updates.
* */
package com.l3r8yj.elegramapi.bot;
import com.jcabi.http.response.JsonResponse;
import com.jcabi.log.Logger;
import com.l3r8yj.elegramapi.command.Command;
import com.l3r8yj.elegramapi.request.TRqGetUpdates;
import com.l3r8yj.elegramapi.request.TRqPost;
import com.l3r8yj.elegramapi.request.TRqSendMessage;
import com.l3r8yj.elegramapi.request.TRqWithChatId;
import com.l3r8yj.elegramapi.request.TRqWithText;
import com.l3r8yj.elegramapi.update.UpdDefault;
import java.io.IOException;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.atomic.AtomicInteger;
import org.cactoos.list.ListOf;
import org.cactoos.text.Concatenated;
import org.json.JSONArray;
import org.json.JSONObject;
/**
* The default implementation of {@link Bot}.
*
* @since 0.0.0
*/
public class BtDefault implements Bot {
/**
* All commands.
*/
private final List<Command> commands;
/**
* The token.
*/
private final String token;
/**
* The processed updates.
*/
private final Set<Long> processed;
/**
* Ctor.
*
* @param token The token
* @param commands All custom commands
*/
public BtDefault(final String token, final Command... commands) {
this.token = token;
this.commands = new ListOf<>(commands);
this.processed = Collections.synchronizedSet(new HashSet<>());
}
@Override
public final void start() {
try {
this.handleUpdates();
} catch (final InterruptedException | IOException ex) {
Logger.error(
this,
new Concatenated(
"An error occurred while handling updates:\n",
ex.getMessage()
).toString()
);
throw new IllegalStateException(ex);
}
}
@Override
public final JsonResponse sendMessage(final long chat, final String text) {
try {
return new TRqPost(
new TRqWithChatId(
new TRqWithText(
new TRqSendMessage(this.token),
text
),
chat
)
).response();
} catch (final IOException ex) {
Logger.error(
this,
new Concatenated(
"An error occurred while sending message:\n",
ex.getMessage()
).toString()
);
throw new IllegalStateException("Can't send a message to user!", ex);
}
}
/**
* Handles the updates.
*
* @throws InterruptedException Thread interrupted
* @throws IOException When getting updates went wrong
*/
private void handleUpdates() throws InterruptedException, IOException {
final BlockingQueue<JSONObject> updates = new LinkedBlockingQueue<>();
this.updatingThread(updates).start();
this.processUpdates(updates);
}
/**
* Processing updates.
*
* @param updates The queue with updates
* @throws InterruptedException When thread interrupted
*/
private void processUpdates(final BlockingQueue<JSONObject> updates)
throws InterruptedException {
while (true) {
final JSONObject upd = updates.take();
if (!this.processed.contains(upd.getLong("update_id"))) {
for (final Command command : this.commands) {
this.processed.add(upd.getLong("update_id"));
command.act(new UpdDefault(upd), this);
}
}
Thread.sleep(500L);
}
}
/**
* Creates thread for handling updates.
*
* @param updates Queue with updates
* @return The thread
*/
private Thread updatingThread(final BlockingQueue<JSONObject> updates) {
return new Thread(
() -> {
while (!Thread.currentThread().isInterrupted()) {
this.fillUpdates(updates);
}
}
);
}
/**
* Check new updates.
*
* @param accum Queue with updates
*/
private void fillUpdates(final BlockingQueue<JSONObject> accum) {
final AtomicInteger offset = new AtomicInteger();
try {
BtDefault.putUpdatesWithOffset(
accum,
offset,
new JSONObject(
new TRqGetUpdates(this.token).response().body()
).getJSONArray("result")
);
} catch (final IOException | InterruptedException ex) {
Logger.error(
this,
new Concatenated(
"Error occurred while filling updates:\n",
ex.getMessage()
).toString()
);
throw new IllegalStateException(ex);
}
}
/**
* Iterating through updates with offset calculation.
*
* @param updates The updates queue
* @param offset The offset for each update
* @param server The data from server as JSON
* @throws InterruptedException When interrupted
*/
private static void putUpdatesWithOffset(
final BlockingQueue<JSONObject> updates,
final AtomicInteger offset,
final JSONArray server
) throws InterruptedException {
for (final Object upd : server) {
final int id = new JSONObject(upd.toString()).getInt("update_id");
offset.set(id + 1);
updates.put(new JSONObject(upd.toString()));
}
}
}