-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCommandService.java
More file actions
398 lines (364 loc) · 18.4 KB
/
CommandService.java
File metadata and controls
398 lines (364 loc) · 18.4 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
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
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
package tnews.subscription.service;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.telegram.telegrambots.meta.api.methods.BotApiMethod;
import org.telegram.telegrambots.meta.api.methods.updatingmessages.DeleteMessage;
import org.telegram.telegrambots.meta.api.objects.CallbackQuery;
import org.telegram.telegrambots.meta.api.objects.Message;
import org.telegram.telegrambots.meta.api.objects.Update;
import tnews.aggregator.client.dto.NewsDto;
import tnews.subscription.bot.Command;
import tnews.subscription.bot.KeyboardFactory;
import tnews.subscription.bot.Management;
import tnews.subscription.bot.MessageFactory;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import tnews.subscription.entity.Category;
import tnews.subscription.entity.KeyWord;
import tnews.subscription.entity.Subscription;
import tnews.subscription.entity.TimeInterval;
import tnews.subscription.entity.User;
import tnews.subscription.entity.UserAction;
@Slf4j
@Component
@AllArgsConstructor
public class CommandService {
private final UserService userService;
private final KeyWordsService keyWordsService;
private final SubscriptionService subscriptionService;
private final CategoryService categoryService;
public List<BotApiMethod<?>> get(Update update) {
Message message = update.getMessage();
Long chatId = message.getChatId();
String text = message.getText();
if(message.isCommand()) {
if (Command.START.getCom().equals(text)) { //TODO: стоит заменить на switch, если добавим меню. Так как там только "команды" (начитаются со /). Просто дублирование методов из handleCallbackQuery
return start(chatId, message.getFrom().getFirstName(), message.getMessageId());
}
}
User user = userService.findById(chatId);
Management management = null;
try {
management = Management.fromString(text);
} catch (IllegalArgumentException e) {
System.out.println(e.getMessage());
}
if (management != null) {
switch (management) {
case ADD -> {
return addSubscription(chatId, user, message.getMessageId());
}
case UPDATE -> {
return updateSubscription(chatId, user);
}
case DELETE -> {
return exactlyDeleteSubscription(chatId, message.getMessageId());
}
}
}
if(UserAction.WAITING_FOR_KEYWORD.equals(user.getCurrentAction())) {
return createKeyword(chatId, text);
}
return List.of(MessageFactory.createMessage(chatId, "Неизвестная команда",
KeyboardFactory.keyboardMarkup(user.getSubscription())));
}
public List<BotApiMethod<?>> handleCallbackQuery (Update update) {
CallbackQuery callbackQuery = update.getCallbackQuery();
String callbackData = callbackQuery.getData();
Long chatId = callbackQuery.getMessage().getChatId();
Integer messageId = callbackQuery.getMessage().getMessageId();
Command command = null;
try {
command = Command.fromString(callbackData.split(" ")[0]);
log.info(command.getCom());
} catch (IllegalArgumentException e) {
log.info(callbackData);
}
if (command != null) {
switch (command) {
case CATEGORY,
ADD_CATEGORY -> {
List<Category> categories = categoryService.findAll();
return choosingCategories(chatId, messageId, categories);
}
case KEYWORD -> {
return addKeyWord(chatId, messageId);
}
case UPDATE_KEYWORD -> {
return updateKeyWord(chatId, messageId);
}
case DELETE_KEYWORD -> {
return deleteKeyWord(chatId, messageId);
}
case UPDATE_CATEGORY -> {
return updateCategory(chatId, messageId);
}
case DELETE_CATEGORY -> {
return deleteCategory(chatId, messageId);
}
case DELETE_CATEGORY_ACTION -> {
String categoryName = Arrays.stream(callbackData.split(" "))
.skip(1)
.collect(Collectors.joining(" "));
return deleteCategoryAction(chatId, categoryName, messageId);
}
case TIME_INTERVAL,
UPDATE_TIME_INTERVAL -> {
return chooseTimeInterval(chatId, messageId);
}
case EXIT -> {
return exit(chatId);
}
case DELETE -> {
return deleteSubscription(chatId, messageId);
}
case UPDATE -> {
return updateSubscription(chatId, messageId);
}
case START -> {
return start(chatId, callbackQuery.getFrom().getFirstName(), messageId);
}
case CANCELLATION -> {
return cancellation(chatId, messageId);
}
case MORE -> {
return moreNews(chatId, messageId);
}
}
}
if (TimeInterval.isEmun(callbackData)) {
log.info("Update time interval is emun");
log.info(callbackData);
return addTimeInterval(chatId, callbackData, messageId);
}
if (categoryService.findByCategoryName(callbackData) != null) {
return addCategory(chatId, callbackData, messageId);
}
return List.of(MessageFactory.createMessage(chatId, "Неизвестная команда"));
}
private List<BotApiMethod<?>> addSubscription (Long chatId, User user, Integer messageId) {
if (user.getSubscription() != null) {
return List.of(
MessageFactory.createMessage(chatId, "Подписка уже создана",
KeyboardFactory.keyboardMarkup(user.getSubscription())),
MessageFactory.createMessage(chatId, "Желаете обновить подписку?",
KeyboardFactory.chooseUpdateSubscription())
);
}
return start(chatId, user.getUsername(), messageId);
}
private List<BotApiMethod<?>> updateSubscription (Long chatId, User user) {
if (user.getSubscription() == null) {
return List.of(
MessageFactory.createMessage(chatId, "Для начала необходимо создать подписку",
KeyboardFactory.createSubscription()));
}
userService.updateCurrentAction(chatId, UserAction.UPDATE.name());
return List.of(
MessageFactory.createMessage(chatId, "Что обновить?",
KeyboardFactory.updateButtonsCategoryAndKeyword())
);
}
private List<BotApiMethod<?>> updateSubscription (Long chatId, Integer messageId) {
User user = userService.findById(chatId);
if (user.getSubscription() == null) {
return MessageFactory.createMessage(chatId, "Для начала необходимо создать подписку",
KeyboardFactory.createSubscription(), messageId);
}
userService.updateCurrentAction(chatId, UserAction.UPDATE.name());
return MessageFactory.createMessage(chatId, "Что обновить?",
KeyboardFactory.updateButtonsCategoryAndKeyword(), messageId);
}
private List<BotApiMethod<?>> exactlyDeleteSubscription(Long chatId, Integer messageId) {
return MessageFactory.createMessage(chatId, "Вы точно хотите удалить подписку?",
KeyboardFactory.deleteSubscription(), messageId);
}
private List<BotApiMethod<?>> deleteSubscription (Long chatId, Integer messageId) {
User user = userService.findById(chatId);
if (user.getSubscription() == null) {
return MessageFactory.createMessage(chatId, "Подписка еще не создана",
KeyboardFactory.keyboardMarkup(null), messageId);
}
subscriptionService.deleteById(chatId);
return List.of(
MessageFactory.createMessage(chatId, "Подписка удалена"),
MessageFactory.createMessage(chatId, "\uD83D\uDE22",
KeyboardFactory.keyboardMarkup(null)),
DeleteMessage.builder()
.chatId(chatId)
.messageId(messageId)
.build()
);
}
private List<BotApiMethod<?>> cancellation (Long chatId, Integer messageId) {
log.info("Delete message {}", messageId);
return List.of(
DeleteMessage.builder()
.chatId(chatId)
.messageId(messageId)
.build()
);
}
private List<BotApiMethod<?>> start (Long chatId, String firstName, Integer messageId) {
User user = new User();
user.setId(chatId);
user.setUsername(firstName);
user.setCurrentAction(UserAction.START);
userService.create(user);
return List.of(
MessageFactory.createMessage(chatId, "Привет, " + firstName + "! Я новостной бот. Рад тебя видеть!"),
MessageFactory.createMessage(chatId, "Как будем искать новости? (можно выбрать и категории и ключевые слова)",
KeyboardFactory.startButtons()),
DeleteMessage.builder()
.chatId(chatId)
.messageId(messageId)
.build()
);
}
private List<BotApiMethod<?>> createKeyword (Long chatId, String keyword) {
User updateUser = userService.addKeyword(chatId, keyword);
if (updateUser == null) {
return List.of(MessageFactory.createMessage(chatId, "Пользователь не найден :("));
}
userService.updateCurrentAction(chatId, UserAction.READY.name());
return List.of(MessageFactory.createMessage(chatId, "Ключевое слово: " + keyword + " добавлено!",
KeyboardFactory.settingMenu()));
}
private List<BotApiMethod<?>> addKeyWord (Long chatId, Integer messageId) {
userService.updateCurrentAction(chatId, UserAction.WAITING_FOR_KEYWORD.name());
return MessageFactory.createMessage(chatId, "Введите одно ключевое слово: ", messageId);
}
private List<BotApiMethod<?>> updateKeyWord (Long chatId, Integer messageId) {
Subscription subscription = subscriptionService.findById(chatId);
Set<KeyWord> keyWords = subscription.getKeyWords();
List<String> keyWordsList = new ArrayList<>();
for (KeyWord keyWord : keyWords) {
keyWordsList.add(keyWord.getKeyword());
}
return List.of(
MessageFactory.createMessage(chatId, "Ваши ключевые слова:"),
MessageFactory.createMessage(chatId, keyWordsList.toString()),
MessageFactory.createMessage(chatId, "С чего начнем?",
KeyboardFactory.updateKeyWord()),
DeleteMessage.builder()
.chatId(chatId)
.messageId(messageId)
.build()
);
}
private List<BotApiMethod<?>> deleteKeyWord (Long chatId, Integer messageId) {
Subscription subscription = subscriptionService.findById(chatId);
Set<KeyWord> keyWords = subscription.getKeyWords();
return MessageFactory.createMessage(chatId, "Выбирете ключевое слово для удаления",
KeyboardFactory.deleteButtonKeyWord(keyWords), messageId);
}
private List<BotApiMethod<?>> choosingCategories (Long chatId, Integer messageId, List<Category> categories) {
return MessageFactory.createMessage(chatId, "Выберите нужную категорию: ",
KeyboardFactory.categoriesButtons(categories), messageId);
}
private List<BotApiMethod<?>> addCategory (Long chatId, String callbackData, Integer messageId) {
User updateUser = userService.addCategory(chatId, callbackData);
if (updateUser == null) {
return MessageFactory.createMessage(chatId, "Пользователь не найден :(", messageId);
}
return MessageFactory.createMessage(chatId, "Категория добавлена",
KeyboardFactory.settingMenu(), messageId);
}
private List<BotApiMethod<?>> updateCategory (Long chatId, Integer messageId) {
Subscription subscription = subscriptionService.findById(chatId);
Set<Category> categories = subscription.getCategories();
return List.of(
MessageFactory.createMessage(chatId, "Ваши категории: "),
MessageFactory.createMessage(chatId, categories.stream()
.map(Category::getCategoryName)
.collect(Collectors.joining(", "))),
MessageFactory.createMessage(chatId, "С чего начнем?", KeyboardFactory.updateCategory()),
DeleteMessage.builder()
.chatId(chatId)
.messageId(messageId)
.build()
);
}
private List<BotApiMethod<?>> deleteCategory (Long chatId, Integer messageId) {
Subscription subscription = subscriptionService.findById(chatId);
Set<Category> categories = subscription.getCategories();
return MessageFactory.createMessage(chatId, "Выбирете категорию для удаления",
KeyboardFactory.deleteButtonsCategory(categories), messageId);
}
private List<BotApiMethod<?>> deleteCategoryAction (Long chatId, String categoryName, Integer messageId) {
Subscription subscription = subscriptionService.findById(chatId);
Set<Category> categories = subscription.getCategories();
categories.remove(categoryService.findByCategoryName(categoryName));
subscription.setCategories(categories);
subscriptionService.save(subscription);
return MessageFactory.createMessage(chatId, "Категория удалена " + categoryName,
KeyboardFactory.deleteButtonsCategory(categories), messageId);
}
private List<BotApiMethod<?>> addTimeInterval (Long chatId, String callbackData, Integer messageId) {
User user = userService.findById(chatId);
Subscription subscription = subscriptionService.findById(chatId);
subscription.setTimeInterval(TimeInterval.valueOf(callbackData));
subscriptionService.save(subscription);
switch (user.getCurrentAction()) {
case READY,
START -> {
return MessageFactory.createMessage(chatId, "Временной интервал успешно добавлен",
KeyboardFactory.settingMenu(), messageId);
}
case UPDATE -> {
return MessageFactory.createMessage(chatId, "Временной интервал обнавлен",
KeyboardFactory.updateMenu(), messageId);
}
default -> {
return List.of(MessageFactory.createMessage(chatId, "Неизвестная команда"));
}
}
}
private List<BotApiMethod<?>> chooseTimeInterval (Long chatId, Integer messageId) {
return MessageFactory.createMessage(chatId, "Как часто хотите получать новости?",
KeyboardFactory.setTimeInterval(), messageId);
}
private List<BotApiMethod<?>> exit (Long chatId) {
Subscription subscription = subscriptionService.findById(chatId);
if (subscription.getTimeInterval() == null) {
return List.of(
MessageFactory.createMessage(chatId, "Настройка не закончена"),
MessageFactory.createMessage(chatId, "Установите частоту обновления новостей",
KeyboardFactory.setTimeInterval()));
}
Set<String> sendNews = new HashSet<>();
List<NewsDto> newNews = subscriptionService.getActualNews(chatId, 3);
if (newNews.isEmpty()) {
return List.of();
}
return Stream.concat(
Stream.concat(
Stream.of(MessageFactory.createMessage(chatId, "Свежие новости")),
newNews.stream()
.map(news -> MessageFactory.createMessage(chatId, news.toString()))),
Stream.of(MessageFactory.createMessage(chatId, "Делее", KeyboardFactory.moreNews()))
).collect(Collectors.toList());
}
private List<BotApiMethod<?>> moreNews(Long chatId, Integer messageId) {
Subscription subscription = subscriptionService.findById(chatId);
if (subscription == null) {
return List.of(
MessageFactory.createMessage(chatId, "Пользователь не найден"),
MessageFactory.createMessage(chatId, "Создать подписку?",
KeyboardFactory.createSubscription())
);
}
List<NewsDto> newNews = subscriptionService.getActualNews(chatId, 3);
if (newNews.isEmpty()) {
return MessageFactory.createMessage(chatId,
"Свежих новостей пока нет :( Как появятся что-то новое - уведомим вас", messageId);
}
return Stream.concat(
newNews.stream()
.map(news -> MessageFactory.createMessage(chatId, news.toString())),
MessageFactory.createMessage(chatId,"Далее", KeyboardFactory.moreNews(), messageId).stream()
).collect(Collectors.toList());
}
}