FreelanceBot
92 строки · 3.0 Кб
1package telegramBot.service;
2
3import org.springframework.beans.factory.annotation.Autowired;
4import org.springframework.boot.CommandLineRunner;
5import org.springframework.context.annotation.Lazy;
6import org.springframework.stereotype.Service;
7import telegramBot.dto.OrderDto;
8import telegramBot.entity.Order;
9import telegramBot.entity.Subscription;
10import telegramBot.entity.User;
11import telegramBot.enums.Language;
12import telegramBot.enums.SubscriptionStatus;
13import telegramBot.util.BotUtil;
14import telegramBot.util.OrderUtil;
15
16import java.util.*;
17import java.util.stream.Collectors;
18import static telegramBot.util.OrderUtil.distinctByKey;
19
20@Service
21public class BotService implements CommandLineRunner {
22
23@Autowired
24private @Lazy ExchangeService exchangeService;
25
26@Autowired
27private MessageService messageService;
28
29@Autowired
30private UserService userService;
31
32@Autowired
33private OrderService orderService;
34
35@Autowired
36private SubscriptionService subscriptionService;
37
38@Override
39public void run(String... args) throws Exception {
40new Thread(() -> {
41while (true) {
42for(Subscription subscription : subscriptionService.getAllByStatus(SubscriptionStatus.INIT)){
43Language language = Language.ignoreCaseValueOf(subscription.getLanguage());
44List<Order> newOrders = this.exchangeService.findNewOrders(language);
45newOrders.forEach(order -> this.orderService.save(order));
46Map<String, List<OrderDto>> orders = getFilteredOrders(newOrders);
47executeNotices(orders);
48}
49pause();
50}
51}).start();
52
53}
54
55public void executeNotices(Map<String, List<OrderDto>> orders) {
56for(User user : this.userService.getAllActive()){
57List<OrderDto> usersOrders = orders.get(user.getChatId());
58if(usersOrders != null) this.messageService.
59sendNotice(user.getChatId(), usersOrders);
60}
61}
62
63private Map<String, List<OrderDto>> getFilteredOrders(List<Order> newOrders){
64Map<String, List<OrderDto>> orders = new HashMap<>();
65if(newOrders.isEmpty()) return new HashMap<>();
66List<User> users = this.userService.getAllActive();
67users.forEach(user -> {
68List<OrderDto> filteredOrders = newOrders.stream()
69.filter(order -> {
70Subscription sub = order.getSubscription();
71return user.getSubscriptions().contains(sub);
72})
73.filter(distinctByKey(Order::getLink))
74.filter(distinctByKey(Order::getTitle))
75.map(OrderUtil::toDto)
76.collect(Collectors.toList());
77if(!filteredOrders.isEmpty()) orders.put(user.getChatId(), filteredOrders);
78});
79
80return orders;
81}
82
83private void pause() {
84try {
85Thread.sleep(BotUtil.EXECUTE_NOTICE_TIMEOUT);
86} catch (InterruptedException e) {
87e.getCause();
88}
89}
90
91
92}
93