FreelanceBot

Форк
0
92 строки · 3.0 Кб
1
package telegramBot.service;
2

3
import org.springframework.beans.factory.annotation.Autowired;
4
import org.springframework.boot.CommandLineRunner;
5
import org.springframework.context.annotation.Lazy;
6
import org.springframework.stereotype.Service;
7
import telegramBot.dto.OrderDto;
8
import telegramBot.entity.Order;
9
import telegramBot.entity.Subscription;
10
import telegramBot.entity.User;
11
import telegramBot.enums.Language;
12
import telegramBot.enums.SubscriptionStatus;
13
import telegramBot.util.BotUtil;
14
import telegramBot.util.OrderUtil;
15

16
import java.util.*;
17
import java.util.stream.Collectors;
18
import static telegramBot.util.OrderUtil.distinctByKey;
19

20
@Service
21
public class BotService implements CommandLineRunner {
22

23
    @Autowired
24
    private @Lazy ExchangeService exchangeService;
25

26
    @Autowired
27
    private MessageService messageService;
28

29
    @Autowired
30
    private UserService userService;
31

32
    @Autowired
33
    private OrderService orderService;
34

35
    @Autowired
36
    private SubscriptionService subscriptionService;
37

38
    @Override
39
    public void run(String... args) throws Exception {
40
        new Thread(() -> {
41
            while (true) {
42
                for(Subscription subscription : subscriptionService.getAllByStatus(SubscriptionStatus.INIT)){
43
                    Language language = Language.ignoreCaseValueOf(subscription.getLanguage());
44
                    List<Order> newOrders = this.exchangeService.findNewOrders(language);
45
                    newOrders.forEach(order -> this.orderService.save(order));
46
                    Map<String, List<OrderDto>> orders = getFilteredOrders(newOrders);
47
                    executeNotices(orders);
48
                }
49
                pause();
50
            }
51
        }).start();
52

53
    }
54

55
    public void executeNotices(Map<String, List<OrderDto>> orders) {
56
        for(User user : this.userService.getAllActive()){
57
            List<OrderDto> usersOrders = orders.get(user.getChatId());
58
            if(usersOrders != null) this.messageService.
59
                    sendNotice(user.getChatId(), usersOrders);
60
        }
61
    }
62

63
    private Map<String, List<OrderDto>> getFilteredOrders(List<Order> newOrders){
64
        Map<String, List<OrderDto>> orders = new HashMap<>();
65
        if(newOrders.isEmpty()) return new HashMap<>();
66
        List<User> users = this.userService.getAllActive();
67
        users.forEach(user -> {
68
            List<OrderDto> filteredOrders = newOrders.stream()
69
                    .filter(order -> {
70
                Subscription sub = order.getSubscription();
71
                return user.getSubscriptions().contains(sub);
72
            })
73
                    .filter(distinctByKey(Order::getLink))
74
                    .filter(distinctByKey(Order::getTitle))
75
                    .map(OrderUtil::toDto)
76
                    .collect(Collectors.toList());
77
            if(!filteredOrders.isEmpty()) orders.put(user.getChatId(), filteredOrders);
78
        });
79

80
    return orders;
81
    }
82

83
    private void pause() {
84
        try {
85
            Thread.sleep(BotUtil.EXECUTE_NOTICE_TIMEOUT);
86
        } catch (InterruptedException e) {
87
            e.getCause();
88
        }
89
    }
90

91

92
}
93

Использование cookies

Мы используем файлы cookie в соответствии с Политикой конфиденциальности и Политикой использования cookies.

Нажимая кнопку «Принимаю», Вы даете АО «СберТех» согласие на обработку Ваших персональных данных в целях совершенствования нашего веб-сайта и Сервиса GitVerse, а также повышения удобства их использования.

Запретить использование cookies Вы можете самостоятельно в настройках Вашего браузера.