Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
@Getter
@AllArgsConstructor
public enum TimeInterval {
// при внесении изменений придется менять SubscriptionRepository, так как там используется ORDINAL
Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Чтобы не забыть надо писать тесты, тогда они начнут падать если забудешь поменять. Все эти комментарии - бесполезны практически, ставь жесткие ограничения.

ONE_HOUR("ONE_HOUR"),
ONE_DAY("ONE_DAY"),
ONE_WEEK("ONE_WEEK"),
Expand Down
Original file line number Diff line number Diff line change
@@ -1,9 +1,31 @@
package tnews.subscription.repository;

import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.stereotype.Repository;
import tnews.subscription.entity.Subscription;

import java.util.List;

@Repository
public interface SubscriptionRepository extends JpaRepository<Subscription, Long>, CustomizedSave<Subscription> {

@Query(value = """
SELECT *
FROM subscription s
WHERE
(s.time_interval = 0 AND
(s.last_send IS NULL OR s.last_send <= now() - INTERVAL '1 minute'))
OR
(s.time_interval = 1 AND
(s.last_send IS NULL OR s.last_send <= now() - INTERVAL '1 day'))
OR
(s.time_interval = 2 AND
(s.last_send IS NULL OR s.last_send <= now() - INTERVAL '1 week'))
OR
(s.time_interval = 3 AND
(s.last_send IS NULL OR s.last_send <= now() - INTERVAL '1 month'))
""", nativeQuery = true)
List<Subscription> findValidSubscriptions();

}
Original file line number Diff line number Diff line change
Expand Up @@ -11,13 +11,10 @@
import tnews.subscription.bot.Command;
import tnews.subscription.controllers.BotController;
import tnews.subscription.entity.Subscription;
import tnews.subscription.entity.UserAction;
import tnews.subscription.service.CategoryService;
import tnews.subscription.service.SubscriptionService;
import tnews.subscription.service.UserService;

import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;
import java.util.List;

@Component
Expand All @@ -37,41 +34,16 @@ public void scheduleCategoryUpdate() {
log.info("Updated categories: " + categories.size());
}

@Scheduled(fixedRate = 600000) // проверка рассылок новостей раз в минуту для теста оптимально мин время рассылки
@Scheduled(fixedRate = 600000) // проверка рассылок новостей раз в 10 минут
// нужно резать LocalDateTime, так как из-за милисекунд будут пропуски
public void sendNewsDigest() {
log.info("Sending news digest");
List<Subscription> subscriptionList = subscriptionService.findAll();
List<Subscription> subscriptionList = subscriptionService.findNewsToValidSubscriptions();
Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Стало на порядок лучше.


for (Subscription subscription : subscriptionList) {
if (shouldSend(subscription)) {
Update update = createFakeCallbackUpdate(subscription.getId());
botController.onUpdateReceived(update);
}
}

}

private boolean shouldSend(Subscription subscription) {
if (userService.findById(subscription.getId()).getCurrentAction().equals(UserAction.UPDATE)) // не очень читабельно, но используется только тут. Стоит ли переписать?
return false;
LocalDateTime lastSent = subscription.getLastSend() != null
? subscription.getLastSend().truncatedTo(ChronoUnit.MINUTES)
: null; // скорее всего округление не обязательно, так как отправка раз в час. Но тесты с ним удут более четко
LocalDateTime now = LocalDateTime.now();
log.info("Checking if last sent is: {}", lastSent);

boolean tmp = switch (subscription.getTimeInterval()) {
case ONE_HOUR -> lastSent == null || lastSent.plusHours(1).isBefore(now); //TODO: пока раз минуту, должно быть раз в час
case ONE_DAY -> lastSent == null || lastSent.plusDays(1).isBefore(now);
case ONE_WEEK -> lastSent == null || lastSent.plusWeeks(1).isBefore(now);
case ONE_MONTH -> lastSent == null || lastSent.plusMonths(1).isBefore(now);
};
subscription.setLastSend(now);
subscriptionService.save(subscription);
if (lastSent != null)
log.info(lastSent.toString());
else log.info("Last sent is null");
return tmp;
}

/**
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -360,15 +360,10 @@ private List<BotApiMethod<?>> exit (Long chatId) {
}
Set<String> sendNews = new HashSet<>();

List<NewsDto> newNews = subscriptionService.getActualNews(chatId, 3); // userService.findActualNews(chatId);
List<NewsDto> newNews = subscriptionService.getActualNews(chatId, 3);
Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Это мы лимит хардкодим? Вынеси тогда в константу, чтобы читалось нормально.

if (newNews.isEmpty()) {
return List.of();
}
sendNews.addAll(newNews.stream()
.map(NewsDto::getId)
.toList());
subscription.setSentNewsIds(sendNews);
subscriptionService.save(subscription);

return Stream.concat(
Stream.concat(
Expand All @@ -388,7 +383,7 @@ private List<BotApiMethod<?>> moreNews(Long chatId, Integer messageId) {
KeyboardFactory.createSubscription())
);
}
List<NewsDto> newNews = subscriptionService.getActualNews(chatId, 3); // userService.findActualNews(chatId);
List<NewsDto> newNews = subscriptionService.getActualNews(chatId, 3);
if (newNews.isEmpty()) {
return MessageFactory.createMessage(chatId,
"Свежих новостей пока нет :( Как появятся что-то новое - уведомим вас", messageId);
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package tnews.subscription.service;

import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import tnews.aggregator.client.AggregatorClient;
import tnews.aggregator.client.dto.NewsDto;
Expand All @@ -10,16 +11,16 @@
import tnews.subscription.entity.Subscription;
import tnews.subscription.repository.SubscriptionRepository;

import java.util.ArrayList;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

@Service
@Slf4j
@AllArgsConstructor
public class SubscriptionService {
private SubscriptionRepository subscriptionRepository;
private CategoryService categoryService;
private AggregatorClient aggregatorClient;

public List<Subscription> findAll() {
Expand Down Expand Up @@ -67,18 +68,6 @@ public void deleteById(Long id) {
subscriptionRepository.deleteById(id);
}

public List<NewsDto> getNewsByCategory(String category) { // скорее всего лишнее
return aggregatorClient.getNewsByCategory(category);
}

public List<List<NewsDto>> getNewsByCategories(Set<String> categories) {
List<List<NewsDto>> news = new ArrayList<>();
for (String category : categories) {
news.add(aggregatorClient.getNewsByCategory(category));
}
return news;
}

public List<NewsDto> getActualNews(Long id, int limit) {
Subscription subscription = findById(id);
Set<String> categories = subscription.getCategories().stream()
Expand All @@ -97,5 +86,15 @@ public List<NewsDto> getActualNews(Long id, int limit) {
return actualNews;
}


public List<Subscription> findNewsToValidSubscriptions() {
List<Subscription> subscriptionList = subscriptionRepository.findValidSubscriptions();
if (subscriptionList.isEmpty()) {
log.info("Нет подписок для обновления времени отправки.");
return List.of();
}
subscriptionList.forEach(subscription -> {subscription.setLastSend(LocalDateTime.now());});
subscriptionRepository.saveAll(subscriptionList);
log.info("Обновлено {} подписок, время отправки установлено на {}", subscriptionList.size(), LocalDateTime.now());
return subscriptionList;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,9 @@

import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;
import tnews.aggregator.client.dto.NewsDto;
import tnews.subscription.repository.UserRepository;

import java.util.Collection;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

import tnews.subscription.entity.Category;
import tnews.subscription.entity.KeyWord;
Expand Down Expand Up @@ -79,27 +75,4 @@ public User updateCurrentAction(Long id, String action) {
return userRepository.save(user);
}

// public List<NewsDto> findActualNews(Long id) {
// updateCurrentAction(id, UserAction.READY.name());
// Subscription subscription = subscriptionService.findById(id);
// Set<String> categories = subscription.getCategories().stream()
// .map(Category::getCategoryName)
// .collect(Collectors.toSet());
// List<List<NewsDto>> allNews = subscriptionService.getNewsByCategories(categories);
// Set<String> sendNews = subscription.getSentNewsIds();
//
//
// List<NewsDto> newNews = allNews.stream()
// .flatMap(Collection::stream)
// .filter(news -> !sendNews.contains(news.getId()))
// .limit(3)
// .toList();
// sendNews.addAll(newNews.stream()
// .map(NewsDto::getId)
// .toList());
// subscription.setSentNewsIds(sendNews);
// subscriptionService.save(subscription);
// return newNews;
// }

}
Loading