diff --git a/src/main/java/com/archivision/community/handler/CallbackTelegramEventHandler.java b/src/main/java/com/archivision/community/handler/CallbackTelegramEventHandler.java index 76ddead..599717c 100644 --- a/src/main/java/com/archivision/community/handler/CallbackTelegramEventHandler.java +++ b/src/main/java/com/archivision/community/handler/CallbackTelegramEventHandler.java @@ -12,6 +12,7 @@ @Slf4j public class CallbackTelegramEventHandler implements TelegramEventHandler { private final MessageSender messageSender; + public void handle(CallbackQuery callbackQuery) { if (callbackQuery.getData().contains("hello_btn")) { messageSender.sendMessage(SendMessage.builder() diff --git a/src/main/java/com/archivision/community/listener/LikesEventListener.java b/src/main/java/com/archivision/community/listener/LikesEventListener.java index f67a540..0be5fea 100644 --- a/src/main/java/com/archivision/community/listener/LikesEventListener.java +++ b/src/main/java/com/archivision/community/listener/LikesEventListener.java @@ -18,7 +18,7 @@ public void handleLike(LikeEvent likeEvent) { if (userLikeService.isReverseLikeExists(likeEvent.liker(), likeEvent.liked())) { notificationService.notifyUsersAboutMatch(likeEvent.liker(), likeEvent.liked()); } else { - notificationService.notifyPersonAboutLine(likeEvent); + notificationService.notifyPersonAboutLike(likeEvent); } } } diff --git a/src/main/java/com/archivision/community/model/Reply.java b/src/main/java/com/archivision/community/model/Reply.java index ac278f9..ced7fc7 100644 --- a/src/main/java/com/archivision/community/model/Reply.java +++ b/src/main/java/com/archivision/community/model/Reply.java @@ -12,7 +12,8 @@ public enum Reply { DISLIKE("-"), SETTINGS("Налаштування"), STATS("Статистика"), - BACK("Завершити"); + BACK("Завершити"), + SEARCH("Пошук"); private final String replyOption; Reply(String replyOption) { diff --git a/src/main/java/com/archivision/community/processor/TelegramUpdateProcessor.java b/src/main/java/com/archivision/community/processor/TelegramUpdateProcessor.java index 28b7523..d8c3f27 100644 --- a/src/main/java/com/archivision/community/processor/TelegramUpdateProcessor.java +++ b/src/main/java/com/archivision/community/processor/TelegramUpdateProcessor.java @@ -40,7 +40,7 @@ public void processUpdate(Update update) { private void checkForSpecialUpdates(Update update) { if (update.hasMyChatMember()) { - ChatMemberUpdated chatMember = update.getMyChatMember(); + final ChatMemberUpdated chatMember = update.getMyChatMember(); if (chatMember.getNewChatMember().getStatus().equals("kicked")) { userService.deleteByTgId(chatMember.getFrom().getId()); } diff --git a/src/main/java/com/archivision/community/service/NotificationService.java b/src/main/java/com/archivision/community/service/NotificationService.java index 3efbf5a..2d485bb 100644 --- a/src/main/java/com/archivision/community/service/NotificationService.java +++ b/src/main/java/com/archivision/community/service/NotificationService.java @@ -15,12 +15,14 @@ public class NotificationService { private final UserService userService; private final ProfileSender profileSender; + private final static String SYMPATHY = "У вас симпатія! @"; + public void notifyUsersAboutMatch(Long likerId, Long likedId) { - messageSender.sendTextMessage(likedId, "У вас симпатія! @" + + messageSender.sendTextMessage(likedId, SYMPATHY + userService.getUserByTgId(likerId).getUsername()); profileSender.showUserProfileTo(likerId, likedId); - messageSender.sendTextMessage(likerId, "У вас симпатія! @" + + messageSender.sendTextMessage(likerId, SYMPATHY + userService.getUserByTgId(likedId).getUsername()); profileSender.showUserProfileTo(likedId, likerId); } @@ -29,7 +31,7 @@ public void notifyUserAboutSuccessfulPayment(String chatId, String message) { messageSender.sendTextMessage(Long.valueOf(chatId), message); } - public void notifyPersonAboutLine(LikeEvent likeEvent) { + public void notifyPersonAboutLike(LikeEvent likeEvent) { final Long whoIsLiked = likeEvent.liked(); messageSender.sendTextMessage(whoIsLiked, "У вас вподобання!"); diff --git a/src/main/java/com/archivision/community/service/ProfileSender.java b/src/main/java/com/archivision/community/service/ProfileSender.java index 5563d1b..6183739 100644 --- a/src/main/java/com/archivision/community/service/ProfileSender.java +++ b/src/main/java/com/archivision/community/service/ProfileSender.java @@ -28,14 +28,16 @@ public class ProfileSender { private final UserRepository userRepository; public void showUserProfileTo(Long chatId, Long userTo) { - User user = userService.getUserByTgIdWithTopics(chatId); - String formattedProfileText = getFormattedProfileText(user); + final User user = userService.getUserByTgIdWithTopics(chatId); + if (Objects.equals(chatId, userTo)) { messageSender.sendTextMessage(userTo, "Твоя анкета:"); } - boolean hasPhoto = user.getPhotoId() != null; - telegramImageS3Service.sendImageOfUserToUser(chatId, userTo, hasPhoto, formattedProfileText); - log.info("showing profile"); + + final boolean hasPhoto = user.getPhotoId() != null; + telegramImageS3Service.sendImageOfUserToUser(chatId, userTo, hasPhoto, getFormattedProfileText(user)); + + log.info("Showing profile"); } public void sendNextProfile(Long chatId) { @@ -51,7 +53,7 @@ public void sendNextProfile(Long chatId) { @SneakyThrows private Optional giveUserPersonList(Long chatId) { List allUsers = userService.findAllExceptId(chatId); - return allUsers.size() > 0 ? Optional.of(allUsers.get(0)) : Optional.empty(); + return !allUsers.isEmpty() ? Optional.of(allUsers.get(0)) : Optional.empty(); } public void showProfile(Long selfChatId) { @@ -59,15 +61,15 @@ public void showProfile(Long selfChatId) { } private String getFormattedProfileText(User user) { - String formattedProfileText; - formattedProfileText = """ - %s, %s, %s - - Теми: %s - - Опис: %s - """.formatted(user.getName(), user.getAge(), user.getCity(), formatTopics(user.getTopics()), user.getDescription() == null ? "*пусто*" : user.getDescription()); - return formattedProfileText; + return """ + %s, %s, %s + + Теми: %s + + Опис: %s + """.formatted(user.getName(), user.getAge(), user.getCity(), + formatTopics(user.getTopics()), user.getDescription() == null ? "*пусто*" : user.getDescription() + ); } private String formatTopics(Set topics) { diff --git a/src/main/java/com/archivision/community/service/ServiceCommandChecker.java b/src/main/java/com/archivision/community/service/ServiceCommandChecker.java index a0bf021..022337f 100644 --- a/src/main/java/com/archivision/community/service/ServiceCommandChecker.java +++ b/src/main/java/com/archivision/community/service/ServiceCommandChecker.java @@ -26,11 +26,9 @@ public void init() { } public FilterResult filter(Message message) { - Long chatId = message.getChatId(); - String text = message.getText(); - if (commands.contains(text)) { - List subscriptionTypes = subscriptionService.getAvailableSubscriptionTypes(); - messageSender.sendTextMessage(chatId, formMessage(subscriptionTypes)); + if (commands.contains(message.getText())) { + final List subscriptionTypes = subscriptionService.getAvailableSubscriptionTypes(); + messageSender.sendTextMessage(message.getChatId(), formMessage(subscriptionTypes)); } return FilterResult.builder().processNext(true).message("Success").build(); } diff --git a/src/main/java/com/archivision/community/service/StateManagerService.java b/src/main/java/com/archivision/community/service/StateManagerService.java index 120bbcb..7c7484d 100644 --- a/src/main/java/com/archivision/community/service/StateManagerService.java +++ b/src/main/java/com/archivision/community/service/StateManagerService.java @@ -16,7 +16,7 @@ public class StateManagerService { private final Map statesHandlers; public void manageOtherStates(UserFlowState userFlowState, Message message) { - StateHandler stateHandler = statesHandlers.get(userFlowState); + final StateHandler stateHandler = statesHandlers.get(userFlowState); if (stateHandler != null) { stateHandler.handle(message); } diff --git a/src/main/java/com/archivision/community/service/SubscriptionService.java b/src/main/java/com/archivision/community/service/SubscriptionService.java index e2159f2..135cc39 100644 --- a/src/main/java/com/archivision/community/service/SubscriptionService.java +++ b/src/main/java/com/archivision/community/service/SubscriptionService.java @@ -20,7 +20,7 @@ public class SubscriptionService { private final PayPalService payPalService; private final RedisTemplate redisTemplate; - // TODO: 26.01.2024 store in DB + // TODO: 26.01.2024 https://github.com/orgs/ArchiVision/projects/3/views/1?pane=issue&itemId=74322041 public List getAvailableSubscriptionTypes() { List subscriptions = new ArrayList<>(); @@ -52,7 +52,7 @@ public String getPaymentUrl(Long chatId, String subscriptionType) { return link.getHref(); } } - // TODO: 26.01.2024 better handling + // TODO: 26.01.2024 https://github.com/orgs/ArchiVision/projects/3/views/1?pane=issue&itemId=74322057 return null; } } diff --git a/src/main/java/com/archivision/community/service/UserRegistrationCache.java b/src/main/java/com/archivision/community/service/UserRegistrationCache.java index bed3f1e..2c7f2f2 100644 --- a/src/main/java/com/archivision/community/service/UserRegistrationCache.java +++ b/src/main/java/com/archivision/community/service/UserRegistrationCache.java @@ -20,7 +20,6 @@ public void add(Long chatId, UserDto userDto) { redisTemplate.opsForValue().set(chatId, userDto); } - // only read-only ops public UserDto get(Long chatId) { return redisTemplate.opsForValue().get(chatId); } @@ -29,7 +28,6 @@ public UserDto remove(Long chatId) { return redisTemplate.opsForValue().getAndDelete(chatId); } - // use this public void processUser(Long chatId, Consumer dtoConsumer){ UserDto userDto = get(chatId); if (userDto != null) { diff --git a/src/main/java/com/archivision/community/service/user/UserInteractionService.java b/src/main/java/com/archivision/community/service/user/UserInteractionService.java index 2c2ef07..a50e6a9 100644 --- a/src/main/java/com/archivision/community/service/user/UserInteractionService.java +++ b/src/main/java/com/archivision/community/service/user/UserInteractionService.java @@ -19,8 +19,6 @@ public class UserInteractionService { private final ProfileSender profileSender; public void handleLikeAction(Long chatId) { - log.info("Like"); - activeViewingData.get(chatId).ifPresent(checkingThisUser -> { activeViewingData.remove(chatId); userLikeService.like(chatId, checkingThisUser); @@ -30,8 +28,7 @@ public void handleLikeAction(Long chatId) { } public void handleDislikeAction(Long chatId) { - log.info("Dislike"); - // TODO: logic for dislike action + // TODO: https://github.com/orgs/ArchiVision/projects/3?pane=issue&itemId=74320337 } } diff --git a/src/main/java/com/archivision/community/service/user/UserLikeService.java b/src/main/java/com/archivision/community/service/user/UserLikeService.java index 55c6bed..b1f7927 100644 --- a/src/main/java/com/archivision/community/service/user/UserLikeService.java +++ b/src/main/java/com/archivision/community/service/user/UserLikeService.java @@ -22,14 +22,13 @@ public class UserLikeService { private String likesEventQueue; public void like(Long userId, Long userLikeId) { - log.info("test!"); UserLike userLike = new UserLike(); userLike.setUserId(userId); userLike.setLikedUserId(userLikeId); userLike.setDateTime(LocalDateTime.now()); userLikeRepo.save(userLike); - LikeEvent likeEvent = new LikeEvent(userId, userLikeId); - rabbitTemplate.convertAndSend(likesEventQueue, likeEvent); + + rabbitTemplate.convertAndSend(likesEventQueue, new LikeEvent(userId, userLikeId)); } public boolean isReverseLikeExists(Long likerId, Long likedId) { diff --git a/src/main/java/com/archivision/community/service/user/UserService.java b/src/main/java/com/archivision/community/service/user/UserService.java index d2aebb7..ed211b6 100644 --- a/src/main/java/com/archivision/community/service/user/UserService.java +++ b/src/main/java/com/archivision/community/service/user/UserService.java @@ -32,7 +32,6 @@ public void changeState(Long userId, UserFlowState userUserFlowState) { .ifPresentOrElse(user -> user.setUserFlowState(userUserFlowState), () -> userCache.processUser(userId, userDto -> userDto.setUserFlowState(userUserFlowState))); - // log.info("User with id={} not found", userId) stateManagerService .getStateHandler(userUserFlowState) @@ -45,12 +44,12 @@ public Optional getUserByTelegramId(Long chatId) { public User getUserByTgId(Long chatId) { return userRepository.findByTelegramUserId(chatId).orElseThrow(); - // TODO: 03.09.2023 custom exception + // TODO: 03.09.2023 https://github.com/orgs/ArchiVision/projects/3/views/1?pane=issue&itemId=74320387 } public User getUserByTgIdWithTopics(Long chatId) { return userRepository.findByIdWithTopics(chatId).orElseThrow(); - // TODO: 03.09.2023 custom exception + // TODO: 03.09.2023 https://github.com/orgs/ArchiVision/projects/3/views/1?pane=issue&itemId=74320387 } public List findAllUsers(){ @@ -88,7 +87,7 @@ public User saveUser(UserDto userDto) { @Transactional public void changeSubscription(String chatId, User.Subscription subscription) { - Optional byId = userRepository.findByTelegramUserId(Long.valueOf(chatId)); + final Optional byId = userRepository.findByTelegramUserId(Long.valueOf(chatId)); byId.ifPresentOrElse(user -> { user.setSubscription(subscription); }, () -> log.info("User with id={} not found", chatId)); diff --git a/src/main/java/com/archivision/community/service/user/UserStatsService.java b/src/main/java/com/archivision/community/service/user/UserStatsService.java index f891b49..fa2e26b 100644 --- a/src/main/java/com/archivision/community/service/user/UserStatsService.java +++ b/src/main/java/com/archivision/community/service/user/UserStatsService.java @@ -18,8 +18,8 @@ public double resolveUserPopularityIndex(Long chatId) { final User user = userRepository.findByTelegramUserId(chatId) .orElseThrow(() -> new IllegalArgumentException("User not found")); - long numberOfLikes = userLikeRepo.countNumberOfLikesForUser(user.getTelegramUserId()); - long numberOfViews = user.getNumberOfViews(); + final long numberOfLikes = userLikeRepo.countNumberOfLikesForUser(user.getTelegramUserId()); + final long numberOfViews = user.getNumberOfViews(); log.info("Likes: {}, views: {}", numberOfLikes, numberOfViews); if (numberOfViews == 0) { diff --git a/src/main/java/com/archivision/community/service/user/UserTopicService.java b/src/main/java/com/archivision/community/service/user/UserTopicService.java index 35ef795..3161af0 100644 --- a/src/main/java/com/archivision/community/service/user/UserTopicService.java +++ b/src/main/java/com/archivision/community/service/user/UserTopicService.java @@ -54,15 +54,14 @@ public void createTopic(String topicName) { @Transactional public void removeTopic(Long topicId) { - Topic topic = topicRepository.findById(topicId).orElse(null); + topicRepository.findById(topicId).ifPresent(this::removeTopicFromAllUsers); + } - if (topic != null) { - // Remove the topic from all users - for (User user : topic.getUsers()) { - user.getTopics().remove(topic); - } - topicRepository.delete(topic); + private void removeTopicFromAllUsers(Topic topic) { + for (User user : topic.getUsers()) { + user.getTopics().remove(topic); } + topicRepository.delete(topic); } } diff --git a/src/main/java/com/archivision/community/state/impl/MatchStateHandler.java b/src/main/java/com/archivision/community/state/impl/MatchStateHandler.java index 5d64bc0..54b568b 100644 --- a/src/main/java/com/archivision/community/state/impl/MatchStateHandler.java +++ b/src/main/java/com/archivision/community/state/impl/MatchStateHandler.java @@ -15,43 +15,45 @@ import org.springframework.stereotype.Component; import org.telegram.telegrambots.meta.api.objects.Message; +import java.util.Map; import java.util.Set; +import java.util.function.Consumer; import java.util.stream.Stream; +import static com.archivision.community.model.Reply.*; import static java.util.stream.Collectors.toSet; @Component @Slf4j public class MatchStateHandler extends AbstractStateHandler implements WithReplyOptions { - private final UserInteractionService userInteractionService; private final ProfileSender profileSender; + private final Map> messageHandlerStrategy; public MatchStateHandler(InputValidator inputValidator, UserService userService, MessageSender messageSender, KeyboardBuilderService keyboardBuilder, UserCache userCache, UserInteractionService userLikeService, ProfileSender profileSender) { super(inputValidator, userService, messageSender, keyboardBuilder, userCache); - this.userInteractionService = userLikeService; this.profileSender = profileSender; + + this.messageHandlerStrategy = Map.of( + LIKE.toString(), userLikeService::handleLikeAction, + DISLIKE.toString(), userLikeService::handleDislikeAction, + SETTINGS.toString(), chatId -> { + messageSender.sendMsgWithMarkup(chatId, SETTINGS.toString(), keyboardBuilder.subscriptions()); + userService.changeState(chatId, UserFlowState.SETTINGS); + }, + STATS.toString(), chatId -> { + messageSender.sendMsgWithMarkup(chatId, STATS.toString(), keyboardBuilder.backButton()); + userService.changeState(chatId, UserFlowState.STATS); + } + ); } @Override public void doHandle(Message message) { - Long chatId = message.getChatId(); - String messageText = message.getText(); - if (isLiked(messageText)) { - userInteractionService.handleLikeAction(chatId); - } - if (isDisliked(messageText)) { - userInteractionService.handleDislikeAction(chatId); - } - if (messageText.equals(Reply.SETTINGS.toString())) { - messageSender.sendMsgWithMarkup(chatId, "Налаштування", keyboardBuilder.subscriptions()); - userService.changeState(chatId, UserFlowState.SETTINGS); - } - if (messageText.equals(Reply.STATS.toString())) { - messageSender.sendMsgWithMarkup(chatId, "Статистика", keyboardBuilder.backButton()); - userService.changeState(chatId, UserFlowState.STATS); - } + messageHandlerStrategy + .get(message.getText()) + .accept(message.getChatId()); } @Override @@ -74,25 +76,21 @@ public boolean shouldValidateInput() { return true; } - private boolean isLiked(String msg) { - return "+".equals(msg); - } - - private boolean isDisliked(String msg) { - return "-".equals(msg); - } - @Override public Set getOptions() { - return Stream.of(Reply.LIKE, Reply.DISLIKE, Reply.SETTINGS, Reply.STATS) + return Stream.of(LIKE, DISLIKE, SETTINGS, STATS) .map(Reply::toString) .collect(toSet()); } @Override public void onStateChanged(Long chatId) { + processBrowsing(chatId); + } + + private void processBrowsing(Long chatId) { profileSender.showProfile(chatId); - messageSender.sendMsgWithMarkup(chatId, "Пошук", keyboardBuilder.matchButtons()); + messageSender.sendMsgWithMarkup(chatId, SEARCH.toString(), keyboardBuilder.matchButtons()); profileSender.sendNextProfile(chatId); } } diff --git a/src/main/java/com/archivision/community/state/impl/SettingsStateHandler.java b/src/main/java/com/archivision/community/state/impl/SettingsStateHandler.java index 1658558..0064df9 100644 --- a/src/main/java/com/archivision/community/state/impl/SettingsStateHandler.java +++ b/src/main/java/com/archivision/community/state/impl/SettingsStateHandler.java @@ -17,6 +17,8 @@ @Slf4j @Component public class SettingsStateHandler extends AbstractStateHandler implements Validatable { + private final SubscriptionService subscriptionService; + public SettingsStateHandler(InputValidator inputValidator, UserService userService, MessageSender messageSender, @@ -27,18 +29,13 @@ public SettingsStateHandler(InputValidator inputValidator, this.subscriptionService = subscriptionService; } - private final SubscriptionService subscriptionService; - @Override public void doHandle(Message message) { - String text = message.getText(); - Long chatId = message.getChatId(); - log.info("message on settings state"); - formMarkupBasedOnDonationType(text, chatId); + formMarkupBasedOnDonationType(message.getText(), message.getChatId()); } private void formMarkupBasedOnDonationType(String subscriptionType, Long chatId) { - InlineKeyboardMarkup markup = keyboardBuilder.inlineBtn(subscriptionType, getPaymentUrl(chatId, subscriptionType)); + final InlineKeyboardMarkup markup = keyboardBuilder.inlineBtn(subscriptionType, getPaymentUrl(chatId, subscriptionType)); messageSender.sendMsgWithInline(chatId, markup); } @@ -64,6 +61,6 @@ public boolean isInputValid(Message message) { @Override public void onValidationError(Message message) { - + log.error("Validation error in state: {}. Message={}", getState(), message.getText()); } } diff --git a/src/main/java/com/archivision/community/state/impl/StatsStateHandler.java b/src/main/java/com/archivision/community/state/impl/StatsStateHandler.java index ad99a79..b2af8be 100644 --- a/src/main/java/com/archivision/community/state/impl/StatsStateHandler.java +++ b/src/main/java/com/archivision/community/state/impl/StatsStateHandler.java @@ -24,7 +24,7 @@ public class StatsStateHandler extends AbstractStateHandler implements Validatab Popularity index: %s """; - private UserStatsService userStatsService; + private final UserStatsService userStatsService; public StatsStateHandler(InputValidator inputValidator, UserService userService, MessageSender messageSender, KeyboardBuilderService keyboardBuilder, UserCache userCache, UserStatsService userStatsService) { diff --git a/src/main/java/com/archivision/community/strategy/message/impl/PhotoMessageStrategy.java b/src/main/java/com/archivision/community/strategy/message/impl/PhotoMessageStrategy.java index 585b8aa..d2624d0 100644 --- a/src/main/java/com/archivision/community/strategy/message/impl/PhotoMessageStrategy.java +++ b/src/main/java/com/archivision/community/strategy/message/impl/PhotoMessageStrategy.java @@ -18,8 +18,7 @@ public class PhotoMessageStrategy implements MessageStrategy { private final UserCache userCache; @Override public void handleMessage(Message message) { - Long chatId = message.getChatId(); - UserDto userDto = userCache.get(chatId); + final UserDto userDto = userCache.get(message.getChatId()); if (ifNotInPhotoState(userDto)) { return; } diff --git a/src/main/java/com/archivision/community/strategy/message/impl/TextMessageStrategy.java b/src/main/java/com/archivision/community/strategy/message/impl/TextMessageStrategy.java index 3b03334..b4b0123 100644 --- a/src/main/java/com/archivision/community/strategy/message/impl/TextMessageStrategy.java +++ b/src/main/java/com/archivision/community/strategy/message/impl/TextMessageStrategy.java @@ -31,21 +31,18 @@ public class TextMessageStrategy implements MessageStrategy { @Override public void handleMessage(Message message) { - log.info("public void handleMessage(Message message) , TextMessageStrategy"); - FilterResult filterResult = filterService.filter(message); - if (!filterResult.isProcessNext()) { + if (!filterService.filter(message).isProcessNext()) { return; } - Long chatId = message.getChatId(); - Optional optionalDbUser = userService.getUserByTelegramId(chatId); + final Long chatId = message.getChatId(); + final Optional optionalDbUser = userService.getUserByTelegramId(chatId); if (optionalDbUser.isPresent()) { - User dbUser = optionalDbUser.get(); - stateManagerService.manageOtherStates(dbUser.getUserFlowState(), message); + stateManagerService.manageOtherStates(optionalDbUser.get().getUserFlowState(), message); return; } - UserDto userDto = userCache.get(chatId); + final UserDto userDto = userCache.get(chatId); if (userDto == null) { registerIfNeeded(chatId, message); } else { diff --git a/src/main/java/com/archivision/community/util/InputValidator.java b/src/main/java/com/archivision/community/util/InputValidator.java index f95a84f..ac2fdf6 100644 --- a/src/main/java/com/archivision/community/util/InputValidator.java +++ b/src/main/java/com/archivision/community/util/InputValidator.java @@ -8,7 +8,7 @@ public boolean isNameValid(String name) { return !name.isBlank() && !name.isEmpty() && (name.length() <= 20 && name.length() > 2); } - // TODO: 18.07.2023 use city repository to check the city is present in DB + // TODO: 18.07.2023 https://github.com/orgs/ArchiVision/projects/3/views/1?pane=issue&itemId=74322188 public boolean isCityValid(String city) { return !city.isBlank() && !city.isEmpty() && (city.length() <= 25 && city.length() >= 4); }