Skip to content

Commit

Permalink
State handler refactoring (#18)
Browse files Browse the repository at this point in the history
* Global shelf

* Minor Refactoring
  • Loading branch information
Serwios authored Aug 10, 2024
1 parent 345d496 commit a2f68f5
Show file tree
Hide file tree
Showing 21 changed files with 86 additions and 99 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
@Slf4j
public class CallbackTelegramEventHandler implements TelegramEventHandler<CallbackQuery> {
private final MessageSender messageSender;

public void handle(CallbackQuery callbackQuery) {
if (callbackQuery.getData().contains("hello_btn")) {
messageSender.sendMessage(SendMessage.builder()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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);
}
}
}
3 changes: 2 additions & 1 deletion src/main/java/com/archivision/community/model/Reply.java
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,8 @@ public enum Reply {
DISLIKE("-"),
SETTINGS("Налаштування"),
STATS("Статистика"),
BACK("Завершити");
BACK("Завершити"),
SEARCH("Пошук");

private final String replyOption;
Reply(String replyOption) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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());
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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);
}
Expand All @@ -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, "У вас вподобання!");
Expand Down
32 changes: 17 additions & 15 deletions src/main/java/com/archivision/community/service/ProfileSender.java
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand All @@ -51,23 +53,23 @@ public void sendNextProfile(Long chatId) {
@SneakyThrows
private Optional<User> giveUserPersonList(Long chatId) {
List<User> 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) {
showUserProfileTo(selfChatId, 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<Topic> topics) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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<Subscription> subscriptionTypes = subscriptionService.getAvailableSubscriptionTypes();
messageSender.sendTextMessage(chatId, formMessage(subscriptionTypes));
if (commands.contains(message.getText())) {
final List<Subscription> subscriptionTypes = subscriptionService.getAvailableSubscriptionTypes();
messageSender.sendTextMessage(message.getChatId(), formMessage(subscriptionTypes));
}
return FilterResult.builder().processNext(true).message("Success").build();
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ public class StateManagerService {
private final Map<UserFlowState, StateHandler> 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);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ public class SubscriptionService {
private final PayPalService payPalService;
private final RedisTemplate<String, String> 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<Subscription> getAvailableSubscriptionTypes() {
List<Subscription> subscriptions = new ArrayList<>();

Expand Down Expand Up @@ -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;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -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);
}
Expand All @@ -29,7 +28,6 @@ public UserDto remove(Long chatId) {
return redisTemplate.opsForValue().getAndDelete(chatId);
}

// use this
public void processUser(Long chatId, Consumer<UserDto> dtoConsumer){
UserDto userDto = get(chatId);
if (userDto != null) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand All @@ -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
}
}

Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand All @@ -45,12 +44,12 @@ public Optional<User> 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<User> findAllUsers(){
Expand Down Expand Up @@ -88,7 +87,7 @@ public User saveUser(UserDto userDto) {

@Transactional
public void changeSubscription(String chatId, User.Subscription subscription) {
Optional<User> byId = userRepository.findByTelegramUserId(Long.valueOf(chatId));
final Optional<User> byId = userRepository.findByTelegramUserId(Long.valueOf(chatId));
byId.ifPresentOrElse(user -> {
user.setSubscription(subscription);
}, () -> log.info("User with id={} not found", chatId));
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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);
}
}

Original file line number Diff line number Diff line change
Expand Up @@ -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<String, Consumer<Long>> 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
Expand All @@ -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<String> 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);
}
}
Loading

0 comments on commit a2f68f5

Please sign in to comment.