diff --git a/README.md b/README.md index bc3d2b6..a8677c8 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,20 @@ # Release Notes +## 0.8.0 + +*JRTB-10: extended bot statistics for admins. + +## 0.7.0 + +* JRTB-4: added ability to send notifications about new articles +* JRTB-8: added ability to set inactive telegram user +* JRTB-9: added ability to set active user and/or start using it. + +## 0.6.0 + +* JRTB-7 added the ability to delete group subscription + ## 0.5.0 * JRTB-5: added ability to subscribe on group diff --git a/pom.xml b/pom.xml index 6242859..f45525f 100644 --- a/pom.xml +++ b/pom.xml @@ -28,7 +28,7 @@ com.githab.javarushcommunity javarush-telegrambot - 0.5.0-SNAPSHOT + 0.8.0-SNAPSHOT Javarush-Telegrambot Telegram bot for Javarush from community to community diff --git a/src/main/java/com/githab/javarushcommunity/javarush_telegrambot/JavarushTelegrambotApplication.java b/src/main/java/com/githab/javarushcommunity/javarush_telegrambot/JavarushTelegrambotApplication.java index beaadc5..e7a1bc0 100644 --- a/src/main/java/com/githab/javarushcommunity/javarush_telegrambot/JavarushTelegrambotApplication.java +++ b/src/main/java/com/githab/javarushcommunity/javarush_telegrambot/JavarushTelegrambotApplication.java @@ -6,10 +6,11 @@ import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.scheduling.annotation.EnableScheduling; import org.telegram.telegrambots.meta.TelegramBotsApi; import org.telegram.telegrambots.meta.exceptions.TelegramApiException; import org.telegram.telegrambots.updatesreceivers.DefaultBotSession; - +@EnableScheduling @SpringBootApplication @AutoConfigurationPackage diff --git a/src/main/java/com/githab/javarushcommunity/javarush_telegrambot/bot/JavaRushTelegramBot.java b/src/main/java/com/githab/javarushcommunity/javarush_telegrambot/bot/JavaRushTelegramBot.java index 844b424..1380c69 100644 --- a/src/main/java/com/githab/javarushcommunity/javarush_telegrambot/bot/JavaRushTelegramBot.java +++ b/src/main/java/com/githab/javarushcommunity/javarush_telegrambot/bot/JavaRushTelegramBot.java @@ -4,14 +4,14 @@ import com.githab.javarushcommunity.javarush_telegrambot.command.CommandContainer; import com.githab.javarushcommunity.javarush_telegrambot.javarushclient.JavaRushGroupClient; import com.githab.javarushcommunity.javarush_telegrambot.javarushclient.JavaRushGroupClientIml; -import com.githab.javarushcommunity.javarush_telegrambot.service.GroupSubService; -import com.githab.javarushcommunity.javarush_telegrambot.service.GroupSubServiceIml; -import com.githab.javarushcommunity.javarush_telegrambot.service.SendBotMessageImpl; -import com.githab.javarushcommunity.javarush_telegrambot.service.TelegramUserServiceIml; +import com.githab.javarushcommunity.javarush_telegrambot.service.*; +import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Component; import org.telegram.telegrambots.bots.TelegramLongPollingBot; import org.telegram.telegrambots.meta.api.objects.Update; +import java.util.List; + import static com.githab.javarushcommunity.javarush_telegrambot.command.CommandName.NO; @@ -26,8 +26,10 @@ public class JavaRushTelegramBot extends TelegramLongPollingBot { public final String COMMAND_PREFIX="/"; - public JavaRushTelegramBot(TelegramUserServiceIml telegramUserServiceIml, GroupSubService groupSubServiceIml, JavaRushGroupClientIml javaRushGroupClient){ - this.commandContainer=new CommandContainer(new SendBotMessageImpl(this),telegramUserServiceIml,javaRushGroupClient,groupSubServiceIml); + public JavaRushTelegramBot(TelegramUserServiceIml telegramUserServiceIml, GroupSubService groupSubServiceIml, + JavaRushGroupClientIml javaRushGroupClient, @Value("#{'${bot.admins}'.split('.')}") List admins, StatisticsService statisticsService){ + this.commandContainer=new CommandContainer(new SendBotMessageImpl(this),telegramUserServiceIml, + javaRushGroupClient,groupSubServiceIml,admins,statisticsService); } @@ -40,9 +42,9 @@ public void onUpdateReceived(Update update){ if (message.startsWith(COMMAND_PREFIX)) { String commandIdentifier = message.split(" ")[0].toLowerCase(); - commandContainer.retrieveCommand(commandIdentifier).execute(update); + commandContainer.retrieveCommand(commandIdentifier,update.getMessage().getFrom().getUserName()).execute(update); } else { - commandContainer.retrieveCommand(NO.getCommandName()).execute(update); + commandContainer.retrieveCommand(NO.getCommandName(),update.getMessage().getFrom().getUserName()).execute(update); } } } diff --git a/src/main/java/com/githab/javarushcommunity/javarush_telegrambot/command/AdminHelpCommand.java b/src/main/java/com/githab/javarushcommunity/javarush_telegrambot/command/AdminHelpCommand.java new file mode 100644 index 0000000..9b542b5 --- /dev/null +++ b/src/main/java/com/githab/javarushcommunity/javarush_telegrambot/command/AdminHelpCommand.java @@ -0,0 +1,24 @@ +package com.githab.javarushcommunity.javarush_telegrambot.command; + +import com.githab.javarushcommunity.javarush_telegrambot.service.SendBotMessageService; +import org.telegram.telegrambots.meta.api.objects.Update; + +import static com.githab.javarushcommunity.javarush_telegrambot.command.CommandName.STAT; + +public class AdminHelpCommand implements Command { + + public static final String ADMIN_HELP_MESSAGE=String.format(" Доступные команды администратора" + +"Получить статистику\n" + +"%s-статистика бота\n",STAT.getCommandName()); + + private final SendBotMessageService sendBotMessageService; + + public AdminHelpCommand (SendBotMessageService sendBotMessageService){ + this.sendBotMessageService=sendBotMessageService; + } + @Override + public void execute(Update update){ + sendBotMessageService.sendMessage(update.getMessage().getChatId().toString(),ADMIN_HELP_MESSAGE); + } + +} diff --git a/src/main/java/com/githab/javarushcommunity/javarush_telegrambot/command/CommandContainer.java b/src/main/java/com/githab/javarushcommunity/javarush_telegrambot/command/CommandContainer.java index b77fc7a..01a581a 100644 --- a/src/main/java/com/githab/javarushcommunity/javarush_telegrambot/command/CommandContainer.java +++ b/src/main/java/com/githab/javarushcommunity/javarush_telegrambot/command/CommandContainer.java @@ -1,30 +1,54 @@ package com.githab.javarushcommunity.javarush_telegrambot.command; +import com.githab.javarushcommunity.javarush_telegrambot.command.annotation.AdminCommand; import com.githab.javarushcommunity.javarush_telegrambot.javarushclient.JavaRushGroupClient; import com.githab.javarushcommunity.javarush_telegrambot.service.GroupSubService; import com.githab.javarushcommunity.javarush_telegrambot.service.SendBotMessageService; +import com.githab.javarushcommunity.javarush_telegrambot.service.StatisticsService; import com.githab.javarushcommunity.javarush_telegrambot.service.TelegramUserService; import com.google.common.collect.ImmutableMap; import org.apache.http.conn.params.ConnConnectionParamBean; +import org.glassfish.grizzly.Connection; import org.springframework.beans.factory.annotation.Autowired; +import java.util.List; + import static com.githab.javarushcommunity.javarush_telegrambot.command.CommandName.*; +import static java.util.Objects.nonNull; public class CommandContainer { public final ImmutableMap commandMap ; public final Command unknownCommand; - public CommandContainer(SendBotMessageService sendBotMessageService, TelegramUserService telegramUserService, JavaRushGroupClient javaRushGroupClient, GroupSubService groupSubService) { + private final List admins; + public CommandContainer(SendBotMessageService sendBotMessageService, TelegramUserService telegramUserService, + JavaRushGroupClient javaRushGroupClient, GroupSubService groupSubService, List admins, StatisticsService statisticsService) { commandMap= ImmutableMap.builder().put(START.getCommandName(),new StartCommand(sendBotMessageService,telegramUserService)) .put(HELP.getCommandName(),new HelpCommand(sendBotMessageService)) .put(NO.getCommandName(),new NoCommand(sendBotMessageService)) .put(STOP.getCommandName(),new StopCommand(sendBotMessageService,telegramUserService)) - .put(STAT.getCommandName(),new StatCommand(sendBotMessageService,telegramUserService)) + .put(STAT.getCommandName(),new StatCommand(sendBotMessageService,statisticsService)) .put(ADD_GROUP_SUB.getCommandName(), new AddGroupSubCommand(sendBotMessageService,javaRushGroupClient,groupSubService)) - .put(LIST_GROUP_SUB.getCommandName(),new ListGroupSubCommand(sendBotMessageService,telegramUserService)).build(); + .put(LIST_GROUP_SUB.getCommandName(),new ListGroupSubCommand(sendBotMessageService,telegramUserService)) + .put(DELETE_GROUP_SUB.getCommandName(),new DeleteGroupSubCommand(sendBotMessageService,telegramUserService,groupSubService)) + .put(ADMIN_HELP.getCommandName(),new AdminHelpCommand(sendBotMessageService)).build(); unknownCommand=new UnknownCommand(sendBotMessageService); +this.admins=admins; + } + public Command retrieveCommand(String commandIdentifier,String username) { + Command orDefault = commandMap.getOrDefault(commandIdentifier, unknownCommand); + if (isAdminCommand(orDefault)) { + if (admins.contains(username)) { + return orDefault; + } else { + return unknownCommand; + } + + } + return orDefault; } - public Command retrieveCommand(String commandIdentifier){ - return commandMap.getOrDefault(commandIdentifier,unknownCommand); + private boolean isAdminCommand (Command command){ + return nonNull(command.getClass().getAnnotation(AdminCommand.class)); } } + diff --git a/src/main/java/com/githab/javarushcommunity/javarush_telegrambot/command/CommandName.java b/src/main/java/com/githab/javarushcommunity/javarush_telegrambot/command/CommandName.java index 424aa5f..a00fe58 100644 --- a/src/main/java/com/githab/javarushcommunity/javarush_telegrambot/command/CommandName.java +++ b/src/main/java/com/githab/javarushcommunity/javarush_telegrambot/command/CommandName.java @@ -7,7 +7,9 @@ public enum CommandName { NO(""), STAT("/stat"), ADD_GROUP_SUB("/addgroupsub"), - LIST_GROUP_SUB("/listgroupsub"); + LIST_GROUP_SUB("/listgroupsub"), + DELETE_GROUP_SUB("/deletegroupsub"), + ADMIN_HELP("/ahelp"); private final String commandName; CommandName (String commandName){ this.commandName=commandName; diff --git a/src/main/java/com/githab/javarushcommunity/javarush_telegrambot/command/DeleteGroupSubCommand.java b/src/main/java/com/githab/javarushcommunity/javarush_telegrambot/command/DeleteGroupSubCommand.java new file mode 100644 index 0000000..2033b02 --- /dev/null +++ b/src/main/java/com/githab/javarushcommunity/javarush_telegrambot/command/DeleteGroupSubCommand.java @@ -0,0 +1,80 @@ +package com.githab.javarushcommunity.javarush_telegrambot.command; + +import com.githab.javarushcommunity.javarush_telegrambot.repository.entity.GroupSub; +import com.githab.javarushcommunity.javarush_telegrambot.repository.entity.TelegramUser; +import com.githab.javarushcommunity.javarush_telegrambot.service.GroupSubService; +import com.githab.javarushcommunity.javarush_telegrambot.service.SendBotMessageService; +import com.githab.javarushcommunity.javarush_telegrambot.service.TelegramUserService; +import jakarta.ws.rs.NotFoundException; +import org.springframework.util.CollectionUtils; +import org.telegram.telegrambots.meta.api.objects.Update; + +import java.util.List; +import java.util.Optional; +import java.util.stream.Collectors; + + +import static com.githab.javarushcommunity.javarush_telegrambot.command.CommandName.DELETE_GROUP_SUB; +import static org.apache.commons.lang3.StringUtils.SPACE; +import static org.apache.commons.lang3.StringUtils.isNumeric; + +public class DeleteGroupSubCommand implements Command{ + + private final SendBotMessageService sendBotMessageService; + private final TelegramUserService telegramUserService; + private final GroupSubService groupSubService; + + public DeleteGroupSubCommand(SendBotMessageService sendBotMessageService, + TelegramUserService telegramUserService, GroupSubService groupSubService) { + this.sendBotMessageService = sendBotMessageService; + this.telegramUserService = telegramUserService; + this.groupSubService = groupSubService; + } + + + + @Override + public void execute(Update update) { + if (update.getMessage().getText().equalsIgnoreCase(DELETE_GROUP_SUB.getCommandName())) { + sendGroupIdList(String.valueOf(update.getMessage().getChatId())); + return; + } + String groupId = update.getMessage().getText().split(SPACE)[1]; + String chatId = String.valueOf(update.getMessage().getChatId()); + + if (isNumeric(groupId)) { + Optional optionalGroupSub = groupSubService.findById(Integer.valueOf(groupId)); + if (optionalGroupSub.isPresent()) { + GroupSub groupSub = optionalGroupSub.get(); + TelegramUser telegramUser = telegramUserService.findByChatId(chatId).orElseThrow(NotFoundException::new); + groupSub.getUsers().remove(telegramUser); + groupSubService.save(groupSub); + sendBotMessageService.sendMessage(chatId, String.format("Удалил подписку на группу: %s", groupSub.getTitle())); + + } else { + sendBotMessageService.sendMessage(chatId, "Не нашел такой группы =/"); + } + + } else { + sendBotMessageService.sendMessage(chatId, "неправильный формат ID группы"); + + } + } + private void sendGroupIdList (String chatId){ + String message; + List groupSubs=telegramUserService.findByChatId(chatId).orElseThrow(NotFoundException::new) + .getGroupSubs(); + if (CollectionUtils.isEmpty(groupSubs)){ + message="Пока нет подписки на группы"; + + }else { + message="Чтобы удалить подписку передай - команду вместе с ID \n\n"+ + "имя группы - ID группы \n\n"+ + "%s"; + + } + String userGroupSubData=groupSubs.stream().map(group->String.format("%s - %s",group.getTitle(),group.getId())) + .collect(Collectors.joining()); + sendBotMessageService.sendMessage(chatId,String.format(message,userGroupSubData)); + } +} diff --git a/src/main/java/com/githab/javarushcommunity/javarush_telegrambot/command/StatCommand.java b/src/main/java/com/githab/javarushcommunity/javarush_telegrambot/command/StatCommand.java index bf7945b..8ac445f 100644 --- a/src/main/java/com/githab/javarushcommunity/javarush_telegrambot/command/StatCommand.java +++ b/src/main/java/com/githab/javarushcommunity/javarush_telegrambot/command/StatCommand.java @@ -1,23 +1,46 @@ package com.githab.javarushcommunity.javarush_telegrambot.command; +import com.githab.javarushcommunity.javarush_telegrambot.command.annotation.AdminCommand; +import com.githab.javarushcommunity.javarush_telegrambot.javarushclient.dto.StatisticDTO; import com.githab.javarushcommunity.javarush_telegrambot.service.SendBotMessageService; -import com.githab.javarushcommunity.javarush_telegrambot.service.TelegramUserService; +import com.githab.javarushcommunity.javarush_telegrambot.service.StatisticsService; + import org.springframework.beans.factory.annotation.Autowired; import org.telegram.telegrambots.meta.api.objects.Update; + +import java.util.stream.Collectors; + + + +@AdminCommand public class StatCommand implements Command{ private final SendBotMessageService sendBotMessageService; -private final TelegramUserService telegramUserService; +private final StatisticsService statisticsService; + +public final static String STAT_MESSAGE="✨Подготовил статистику✨\n" + + "- Количество активных пользователей: %s\n" + + "- Количество неактивных пользователей: %s\n" + + "- Среднее количество групп на одного пользователя: %s\n\n" + + "Информация по активным группам:\n" + + "%s"; -public final static String STAT_MESSAGE="JavaRush Telegram Bot використовує %s людей."; @Autowired -public StatCommand(SendBotMessageService sendBotMessageService,TelegramUserService telegramUserService){ +public StatCommand(SendBotMessageService sendBotMessageService,StatisticsService statisticsService){ this.sendBotMessageService=sendBotMessageService; - this.telegramUserService=telegramUserService; + this.statisticsService=statisticsService; } @Override public void execute(Update update) { -int activeUserCount=telegramUserService.retrieveAllActiveUser().size(); -sendBotMessageService.sendMessage(update.getMessage().getChatId().toString(),String.format(STAT_MESSAGE,activeUserCount)); + StatisticDTO statisticDTO=statisticsService.countBotStatistic(); + String collectedGroups=statisticDTO.getGroupStatDTOs().stream() + .map(it->String.format("%s (id=%s)-%s подписчиков",it.getTitle(),it.getId(),it.getActiveUserCount())) + .collect(Collectors.joining("\n")); + +sendBotMessageService.sendMessage(update.getMessage().getChatId().toString(),String.format(STAT_MESSAGE, + statisticDTO.getActiveUserCount(), + statisticDTO.getInactiveUserCount(), + statisticDTO.getAverageGroupCountByUser(), + collectedGroups)); } } diff --git a/src/main/java/com/githab/javarushcommunity/javarush_telegrambot/command/annotation/AdminCommand.java b/src/main/java/com/githab/javarushcommunity/javarush_telegrambot/command/annotation/AdminCommand.java new file mode 100644 index 0000000..a2236ed --- /dev/null +++ b/src/main/java/com/githab/javarushcommunity/javarush_telegrambot/command/annotation/AdminCommand.java @@ -0,0 +1,10 @@ +package com.githab.javarushcommunity.javarush_telegrambot.command.annotation; + +import java.lang.annotation.Retention; + +import static java.lang.annotation.RetentionPolicy.RUNTIME; + +@Retention(RUNTIME) + +public @interface AdminCommand { +} diff --git a/src/main/java/com/githab/javarushcommunity/javarush_telegrambot/javarushclient/JavaRushGroupClient.java b/src/main/java/com/githab/javarushcommunity/javarush_telegrambot/javarushclient/JavaRushGroupClient.java index 2cf70f9..b6fc56a 100644 --- a/src/main/java/com/githab/javarushcommunity/javarush_telegrambot/javarushclient/JavaRushGroupClient.java +++ b/src/main/java/com/githab/javarushcommunity/javarush_telegrambot/javarushclient/JavaRushGroupClient.java @@ -15,6 +15,7 @@ public interface JavaRushGroupClient { Integer getGroupCount(GroupCountRequestArgs countRequestArgs); GroupDiscussionInfo getGroupById(Integer id); + Integer findLastArticle(Integer groupSub); } diff --git a/src/main/java/com/githab/javarushcommunity/javarush_telegrambot/javarushclient/JavaRushGroupClientIml.java b/src/main/java/com/githab/javarushcommunity/javarush_telegrambot/javarushclient/JavaRushGroupClientIml.java index 3fe2721..00accd9 100644 --- a/src/main/java/com/githab/javarushcommunity/javarush_telegrambot/javarushclient/JavaRushGroupClientIml.java +++ b/src/main/java/com/githab/javarushcommunity/javarush_telegrambot/javarushclient/JavaRushGroupClientIml.java @@ -1,9 +1,6 @@ package com.githab.javarushcommunity.javarush_telegrambot.javarushclient; -import com.githab.javarushcommunity.javarush_telegrambot.javarushclient.dto.GroupCountRequestArgs; -import com.githab.javarushcommunity.javarush_telegrambot.javarushclient.dto.GroupDiscussionInfo; -import com.githab.javarushcommunity.javarush_telegrambot.javarushclient.dto.GroupInfo; -import com.githab.javarushcommunity.javarush_telegrambot.javarushclient.dto.GroupRequestArgs; +import com.githab.javarushcommunity.javarush_telegrambot.javarushclient.dto.*; import kong.unirest.GenericType; import kong.unirest.Unirest; import org.springframework.beans.factory.annotation.Autowired; @@ -11,13 +8,19 @@ import org.springframework.stereotype.Component; import java.util.List; +import java.util.Optional; + +import static org.springframework.util.CollectionUtils.isEmpty; + @Component public class JavaRushGroupClientIml implements JavaRushGroupClient { private String javarushApiGroupPath; + private String getJavarushApiPostPath; - public JavaRushGroupClientIml(@Value("${javarush.api.path}") String javarushApi){ - this.javarushApiGroupPath=javarushApi+"/groups"; + public JavaRushGroupClientIml(@Value("${javarush.api.path}") String javarushApi) { + this.javarushApiGroupPath = javarushApi + "/groups"; + this.getJavarushApiPostPath = javarushApi + "/posts"; } @Override public List getGroupList(GroupRequestArgs requestArgs) { @@ -45,4 +48,17 @@ public GroupDiscussionInfo getGroupById(Integer id) { return Unirest.get(String.format("%s/group%s",javarushApiGroupPath,id.toString())). asObject(GroupDiscussionInfo.class).getBody(); } + + + @Override + public Integer findLastArticle(Integer groupSubId) { + List posts = Unirest.get(getJavarushApiPostPath) + .queryString("order", "NEW") + .queryString("groupKid", groupSubId.toString()) + .queryString("limit", "1") + .asObject(new GenericType>() { + }) + .getBody(); + return isEmpty(posts) ? 0 : Optional.ofNullable(posts.get(0)).map(PostInfo::getId).orElse(0); + } } diff --git a/src/main/java/com/githab/javarushcommunity/javarush_telegrambot/javarushclient/JavaRushPostClient.java b/src/main/java/com/githab/javarushcommunity/javarush_telegrambot/javarushclient/JavaRushPostClient.java new file mode 100644 index 0000000..a1678f7 --- /dev/null +++ b/src/main/java/com/githab/javarushcommunity/javarush_telegrambot/javarushclient/JavaRushPostClient.java @@ -0,0 +1,10 @@ +package com.githab.javarushcommunity.javarush_telegrambot.javarushclient; + +import com.githab.javarushcommunity.javarush_telegrambot.javarushclient.dto.PostInfo; + +import java.util.List; + +public interface JavaRushPostClient { + + List findNewPosts(Integer groupId, Integer lastPostId); +} diff --git a/src/main/java/com/githab/javarushcommunity/javarush_telegrambot/javarushclient/JavaRushPostClientIml.java b/src/main/java/com/githab/javarushcommunity/javarush_telegrambot/javarushclient/JavaRushPostClientIml.java new file mode 100644 index 0000000..bee1889 --- /dev/null +++ b/src/main/java/com/githab/javarushcommunity/javarush_telegrambot/javarushclient/JavaRushPostClientIml.java @@ -0,0 +1,37 @@ +package com.githab.javarushcommunity.javarush_telegrambot.javarushclient; + +import com.githab.javarushcommunity.javarush_telegrambot.javarushclient.dto.PostInfo; +import kong.unirest.GenericType; +import kong.unirest.Unirest; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.stereotype.Component; + +import java.util.ArrayList; +import java.util.List; +@Component +public class JavaRushPostClientIml implements JavaRushPostClient{ + + private final String javarushApiPostPath; + + public JavaRushPostClientIml(@Value("${javarush.api.path}") String javarushApi){ + this.javarushApiPostPath=javarushApi+"/posts"; + } + @Override + public List findNewPosts(Integer groupId, Integer lastArticleId) { + List lastPostsByGroup= Unirest.get(javarushApiPostPath) + .queryString("order","NEW") + .queryString("groupKid",groupId) + .queryString("limit",15) + .asObject(new GenericType>() { + }).getBody(); + List newPosts=new ArrayList<>(); + for (PostInfo post:lastPostsByGroup){ + if(lastArticleId.equals(post.getId())){ + return newPosts; + } + newPosts.add(post); + } + + return newPosts; + } +} diff --git a/src/main/java/com/githab/javarushcommunity/javarush_telegrambot/javarushclient/dto/GroupStatDTO.java b/src/main/java/com/githab/javarushcommunity/javarush_telegrambot/javarushclient/dto/GroupStatDTO.java new file mode 100644 index 0000000..4e596e3 --- /dev/null +++ b/src/main/java/com/githab/javarushcommunity/javarush_telegrambot/javarushclient/dto/GroupStatDTO.java @@ -0,0 +1,13 @@ +package com.githab.javarushcommunity.javarush_telegrambot.javarushclient.dto; + +import lombok.Data; +import lombok.EqualsAndHashCode; + +@Data +@EqualsAndHashCode(exclude = {"title","activeUserCount"}) + +public class GroupStatDTO { + private final Integer id; + private final String title; + private final Integer activeUserCount; +} diff --git a/src/main/java/com/githab/javarushcommunity/javarush_telegrambot/javarushclient/dto/PostInfo.java b/src/main/java/com/githab/javarushcommunity/javarush_telegrambot/javarushclient/dto/PostInfo.java new file mode 100644 index 0000000..8b45e08 --- /dev/null +++ b/src/main/java/com/githab/javarushcommunity/javarush_telegrambot/javarushclient/dto/PostInfo.java @@ -0,0 +1,12 @@ +package com.githab.javarushcommunity.javarush_telegrambot.javarushclient.dto; + +import lombok.Data; + +@Data +public class PostInfo { + private Integer id; + private String title; + private String description; + private String key; + +} diff --git a/src/main/java/com/githab/javarushcommunity/javarush_telegrambot/javarushclient/dto/StatisticDTO.java b/src/main/java/com/githab/javarushcommunity/javarush_telegrambot/javarushclient/dto/StatisticDTO.java new file mode 100644 index 0000000..f8de65a --- /dev/null +++ b/src/main/java/com/githab/javarushcommunity/javarush_telegrambot/javarushclient/dto/StatisticDTO.java @@ -0,0 +1,15 @@ +package com.githab.javarushcommunity.javarush_telegrambot.javarushclient.dto; + +import lombok.Data; +import lombok.EqualsAndHashCode; + +import java.util.List; +@Data +@EqualsAndHashCode +public class StatisticDTO { + private final int activeUserCount; + private final int inactiveUserCount; + private final List groupStatDTOs; + private final double averageGroupCountByUser; + +} diff --git a/src/main/java/com/githab/javarushcommunity/javarush_telegrambot/job/FindNewArticleJob.java b/src/main/java/com/githab/javarushcommunity/javarush_telegrambot/job/FindNewArticleJob.java new file mode 100644 index 0000000..257f9b8 --- /dev/null +++ b/src/main/java/com/githab/javarushcommunity/javarush_telegrambot/job/FindNewArticleJob.java @@ -0,0 +1,33 @@ +package com.githab.javarushcommunity.javarush_telegrambot.job; + + +import com.githab.javarushcommunity.javarush_telegrambot.service.FindNewArticleService; +import com.githab.javarushcommunity.javarush_telegrambot.service.FindNewArticleServiceIml; +import lombok.extern.slf4j.Slf4j; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.scheduling.annotation.Scheduled; +import org.springframework.stereotype.Component; + +import java.time.LocalDateTime; +import java.time.ZoneOffset; + +@Slf4j +@Component +public class FindNewArticleJob { + + private final FindNewArticleService findNewArticleService; +@Autowired + public FindNewArticleJob(FindNewArticleServiceIml findNewArticleService) { + this.findNewArticleService = findNewArticleService; + } + @Scheduled(fixedRateString = "${bot.recountNewArticleFixedRate}") + public void findNewArticles(){ + LocalDateTime start=LocalDateTime.now(); + log.info("Find new article job started."); + findNewArticleService.findNewArticles(); + LocalDateTime end=LocalDateTime.now(); + log.info("find new article job finished. Took seconds:{}" + ,end.toEpochSecond(ZoneOffset.UTC)-start.toEpochSecond(ZoneOffset.UTC)); + } + +} diff --git a/src/main/java/com/githab/javarushcommunity/javarush_telegrambot/repository/TelegramuserRepository.java b/src/main/java/com/githab/javarushcommunity/javarush_telegrambot/repository/TelegramuserRepository.java index 29c3879..3f4627c 100644 --- a/src/main/java/com/githab/javarushcommunity/javarush_telegrambot/repository/TelegramuserRepository.java +++ b/src/main/java/com/githab/javarushcommunity/javarush_telegrambot/repository/TelegramuserRepository.java @@ -9,4 +9,5 @@ @Repository public interface TelegramuserRepository extends CrudRepository { List findAllByActiveTrue(); +List findAllByActiveFalse(); } diff --git a/src/main/java/com/githab/javarushcommunity/javarush_telegrambot/repository/entity/TelegramUser.java b/src/main/java/com/githab/javarushcommunity/javarush_telegrambot/repository/entity/TelegramUser.java index 774d94b..d3dee79 100644 --- a/src/main/java/com/githab/javarushcommunity/javarush_telegrambot/repository/entity/TelegramUser.java +++ b/src/main/java/com/githab/javarushcommunity/javarush_telegrambot/repository/entity/TelegramUser.java @@ -2,12 +2,14 @@ import jakarta.persistence.*; import lombok.Data; +import lombok.EqualsAndHashCode; import java.util.List; @Data @Entity @Table(name = "tg_user") +@EqualsAndHashCode(exclude = "groupSubs") public class TelegramUser { @Id @Column(name = "chat_id") diff --git a/src/main/java/com/githab/javarushcommunity/javarush_telegrambot/service/FindNewArticleService.java b/src/main/java/com/githab/javarushcommunity/javarush_telegrambot/service/FindNewArticleService.java new file mode 100644 index 0000000..7cf4c8e --- /dev/null +++ b/src/main/java/com/githab/javarushcommunity/javarush_telegrambot/service/FindNewArticleService.java @@ -0,0 +1,5 @@ +package com.githab.javarushcommunity.javarush_telegrambot.service; + +public interface FindNewArticleService { + void findNewArticles(); +} diff --git a/src/main/java/com/githab/javarushcommunity/javarush_telegrambot/service/FindNewArticleServiceIml.java b/src/main/java/com/githab/javarushcommunity/javarush_telegrambot/service/FindNewArticleServiceIml.java new file mode 100644 index 0000000..7d77d91 --- /dev/null +++ b/src/main/java/com/githab/javarushcommunity/javarush_telegrambot/service/FindNewArticleServiceIml.java @@ -0,0 +1,56 @@ +package com.githab.javarushcommunity.javarush_telegrambot.service; + +import com.githab.javarushcommunity.javarush_telegrambot.javarushclient.JavaRushPostClient; +import com.githab.javarushcommunity.javarush_telegrambot.javarushclient.dto.PostInfo; +import com.githab.javarushcommunity.javarush_telegrambot.repository.entity.GroupSub; +import com.githab.javarushcommunity.javarush_telegrambot.repository.entity.TelegramUser; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +import java.util.Collections; +import java.util.List; +import java.util.stream.Collectors; + +@Service +public class FindNewArticleServiceIml implements FindNewArticleService{ + + public static final String JAVARUSH_WEB_POST_FORMAT="https://javarush.com/groups/posts/%s"; + private final GroupSubService groupSubService; + private final JavaRushPostClient javaRushPostClient; + private final SendBotMessageService sendBotMessageService; +@Autowired + public FindNewArticleServiceIml(GroupSubService groupSubService, JavaRushPostClient javaRushPostClient, + SendBotMessageService sendBotMessageService) { + this.groupSubService = groupSubService; + this.javaRushPostClient = javaRushPostClient; + this.sendBotMessageService = sendBotMessageService; + } + + + @Override + public void findNewArticles() { +groupSubService.findAll().forEach(gSub->{ + List newPosts=javaRushPostClient.findNewPosts(gSub.getId(),gSub.getLastArticleId()); + setNewLastArticleId(gSub,newPosts); + notifySubscribersAboutNewArticles(gSub,newPosts); +}); + } + public void notifySubscribersAboutNewArticles(GroupSub groupSub,List newPosts){ + Collections.reverse(newPosts); + List messageWithNewArticles=newPosts.stream().map(post->String.format("Вышла новая статья %s в группе %s.\n\n\\" + + "Описание: %s \n\n" + + "Ссылка: %s \n",post.getTitle(),groupSub.getTitle(),post.getDescription(),getPostUrl(post.getKey()))) + .collect(Collectors.toList()); +groupSub.getUsers().stream().filter(TelegramUser::isActive).forEach(it->sendBotMessageService.sendMessage(it.getChat_id(), messageWithNewArticles)); + } + + private String getPostUrl(String key){ + return String.format(JAVARUSH_WEB_POST_FORMAT,key); + } + private void setNewLastArticleId(GroupSub groupSub,List newPosts){ + newPosts.stream().mapToInt(PostInfo::getId).max().ifPresent( + id->{groupSub.setLastArticleId(id); + groupSubService.save(groupSub);} + ); + } +} diff --git a/src/main/java/com/githab/javarushcommunity/javarush_telegrambot/service/GroupSubService.java b/src/main/java/com/githab/javarushcommunity/javarush_telegrambot/service/GroupSubService.java index 7a32c4d..ba398d8 100644 --- a/src/main/java/com/githab/javarushcommunity/javarush_telegrambot/service/GroupSubService.java +++ b/src/main/java/com/githab/javarushcommunity/javarush_telegrambot/service/GroupSubService.java @@ -3,6 +3,12 @@ import com.githab.javarushcommunity.javarush_telegrambot.javarushclient.dto.GroupDiscussionInfo; import com.githab.javarushcommunity.javarush_telegrambot.repository.entity.GroupSub; +import java.util.List; +import java.util.Optional; + public interface GroupSubService { GroupSub save (String chatId, GroupDiscussionInfo groupDiscussionInfo); + Optional findById(Integer id); + GroupSub save (GroupSub groupSub); + List findAll(); } diff --git a/src/main/java/com/githab/javarushcommunity/javarush_telegrambot/service/GroupSubServiceIml.java b/src/main/java/com/githab/javarushcommunity/javarush_telegrambot/service/GroupSubServiceIml.java index 3fcd3f3..17fb1d6 100644 --- a/src/main/java/com/githab/javarushcommunity/javarush_telegrambot/service/GroupSubServiceIml.java +++ b/src/main/java/com/githab/javarushcommunity/javarush_telegrambot/service/GroupSubServiceIml.java @@ -1,5 +1,8 @@ package com.githab.javarushcommunity.javarush_telegrambot.service; +import com.githab.javarushcommunity.javarush_telegrambot.javarushclient.JavaRushGroupClient; +import com.githab.javarushcommunity.javarush_telegrambot.javarushclient.JavaRushPostClient; +import com.githab.javarushcommunity.javarush_telegrambot.javarushclient.JavaRushPostClientIml; import com.githab.javarushcommunity.javarush_telegrambot.javarushclient.dto.GroupDiscussionInfo; import com.githab.javarushcommunity.javarush_telegrambot.repository.GroupSubRepository; import com.githab.javarushcommunity.javarush_telegrambot.repository.entity.GroupSub; @@ -8,17 +11,21 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; +import java.util.List; import java.util.Optional; @Service public class GroupSubServiceIml implements GroupSubService{ private final GroupSubRepository groupSubRepository; private final TelegramUserService telegramUserService; + private final JavaRushGroupClient javaRushGroupClient; @Autowired - public GroupSubServiceIml(GroupSubRepository groupSubRepository,TelegramUserService telegramUserService) { + public GroupSubServiceIml(GroupSubRepository groupSubRepository, TelegramUserService telegramUserService, + JavaRushGroupClient javaRushGroupClient) { this.groupSubRepository=groupSubRepository; this.telegramUserService=telegramUserService; + this.javaRushGroupClient=javaRushGroupClient; } @@ -38,10 +45,26 @@ public GroupSub save(String chatId, GroupDiscussionInfo groupDiscussionInfo) { }else { groupSub=new GroupSub(); groupSub.addUser(telegramUser); + groupSub.setLastArticleId(javaRushGroupClient.findLastArticle(groupDiscussionInfo.getId())); groupSub.setId(groupDiscussionInfo.getId()); groupSub.setTitle(groupDiscussionInfo.getTitle()); } return groupSubRepository.save(groupSub); } + + @Override + public GroupSub save(GroupSub groupSub) { + return groupSubRepository.save(groupSub); + } + + @Override + public List findAll() { + return groupSubRepository.findAll(); + } + + @Override + public Optional findById(Integer id) { + return groupSubRepository.findById(id); } +} diff --git a/src/main/java/com/githab/javarushcommunity/javarush_telegrambot/service/SendBotMessageImpl.java b/src/main/java/com/githab/javarushcommunity/javarush_telegrambot/service/SendBotMessageImpl.java index 9100b67..45a0e55 100644 --- a/src/main/java/com/githab/javarushcommunity/javarush_telegrambot/service/SendBotMessageImpl.java +++ b/src/main/java/com/githab/javarushcommunity/javarush_telegrambot/service/SendBotMessageImpl.java @@ -6,6 +6,12 @@ import org.telegram.telegrambots.meta.TelegramBotsApi; import org.telegram.telegrambots.meta.api.methods.send.SendMessage; import org.telegram.telegrambots.meta.exceptions.TelegramApiException; + +import java.util.List; + +import static org.springframework.util.CollectionUtils.isEmpty; + + @Service public class SendBotMessageImpl implements SendBotMessageService{ private final JavaRushTelegramBot javaRushBot; @@ -28,4 +34,11 @@ public void sendMessage(String chatId, String message) { e.printStackTrace(); } } + + @Override + public void sendMessage(String chaId, List messages) { + if(isEmpty(messages)) + return; + messages.forEach(m->sendMessage(String.valueOf(chaId),m)); + } } diff --git a/src/main/java/com/githab/javarushcommunity/javarush_telegrambot/service/SendBotMessageService.java b/src/main/java/com/githab/javarushcommunity/javarush_telegrambot/service/SendBotMessageService.java index 1726db8..040adfd 100644 --- a/src/main/java/com/githab/javarushcommunity/javarush_telegrambot/service/SendBotMessageService.java +++ b/src/main/java/com/githab/javarushcommunity/javarush_telegrambot/service/SendBotMessageService.java @@ -1,7 +1,9 @@ package com.githab.javarushcommunity.javarush_telegrambot.service; +import java.util.List; + public interface SendBotMessageService { void sendMessage(String chatId,String message); - +void sendMessage(String chaId, List messages); } diff --git a/src/main/java/com/githab/javarushcommunity/javarush_telegrambot/service/StatisticsService.java b/src/main/java/com/githab/javarushcommunity/javarush_telegrambot/service/StatisticsService.java new file mode 100644 index 0000000..ce64365 --- /dev/null +++ b/src/main/java/com/githab/javarushcommunity/javarush_telegrambot/service/StatisticsService.java @@ -0,0 +1,7 @@ +package com.githab.javarushcommunity.javarush_telegrambot.service; + +import com.githab.javarushcommunity.javarush_telegrambot.javarushclient.dto.StatisticDTO; + +public interface StatisticsService { + StatisticDTO countBotStatistic(); +} diff --git a/src/main/java/com/githab/javarushcommunity/javarush_telegrambot/service/StatisticsServiceIml.java b/src/main/java/com/githab/javarushcommunity/javarush_telegrambot/service/StatisticsServiceIml.java new file mode 100644 index 0000000..943b7bc --- /dev/null +++ b/src/main/java/com/githab/javarushcommunity/javarush_telegrambot/service/StatisticsServiceIml.java @@ -0,0 +1,41 @@ +package com.githab.javarushcommunity.javarush_telegrambot.service; + +import com.githab.javarushcommunity.javarush_telegrambot.javarushclient.dto.GroupStatDTO; +import com.githab.javarushcommunity.javarush_telegrambot.javarushclient.dto.StatisticDTO; +import com.githab.javarushcommunity.javarush_telegrambot.repository.entity.TelegramUser; +import org.springframework.stereotype.Service; + +import java.util.List; +import java.util.stream.Collectors; + +import static org.springframework.util.CollectionUtils.isEmpty; + +@Service +public class StatisticsServiceIml implements StatisticsService{ + + private final GroupSubService groupSubService; + private final TelegramUserService telegramUserService; + + public StatisticsServiceIml(GroupSubService groupSubService, TelegramUserService telegramUserService) { + this.groupSubService = groupSubService; + this.telegramUserService = telegramUserService; + } + + @Override + public StatisticDTO countBotStatistic() { + List groupStatDTOS=groupSubService.findAll().stream() + .filter(it->!isEmpty(it.getUsers())) + .map(groupSub -> new GroupStatDTO(groupSub.getId(),groupSub.getTitle(),groupSub.getUsers().size())) + .toList(); + List allInActiveUsers=telegramUserService.findAllInActiveUsers(); + List allActiveUsers=telegramUserService.findAllActiveUser(); + + double groupsPerUser=getGroupPerUser(allActiveUsers); + + return new StatisticDTO(allActiveUsers.size(),allInActiveUsers.size(),groupStatDTOS,groupsPerUser); + } + private double getGroupPerUser(List allActiveUsers){ + return (double) allActiveUsers.stream().mapToInt(it->it.getGroupSubs().size()).sum()/allActiveUsers.size(); + + } +} diff --git a/src/main/java/com/githab/javarushcommunity/javarush_telegrambot/service/TelegramUserService.java b/src/main/java/com/githab/javarushcommunity/javarush_telegrambot/service/TelegramUserService.java index 6151a2b..e4d8be9 100644 --- a/src/main/java/com/githab/javarushcommunity/javarush_telegrambot/service/TelegramUserService.java +++ b/src/main/java/com/githab/javarushcommunity/javarush_telegrambot/service/TelegramUserService.java @@ -7,8 +7,9 @@ public interface TelegramUserService { void save(TelegramUser telegramUser); - List retrieveAllActiveUser(); + List findAllActiveUser(); Optional findByChatId(String chatId); + List findAllInActiveUsers(); } diff --git a/src/main/java/com/githab/javarushcommunity/javarush_telegrambot/service/TelegramUserServiceIml.java b/src/main/java/com/githab/javarushcommunity/javarush_telegrambot/service/TelegramUserServiceIml.java index 69b4586..c7e36fa 100644 --- a/src/main/java/com/githab/javarushcommunity/javarush_telegrambot/service/TelegramUserServiceIml.java +++ b/src/main/java/com/githab/javarushcommunity/javarush_telegrambot/service/TelegramUserServiceIml.java @@ -29,7 +29,7 @@ public void save(TelegramUser telegramUser) { @Override - public List retrieveAllActiveUser() { + public List findAllActiveUser() { return telegramuserRepository.findAllByActiveTrue(); } @@ -38,4 +38,9 @@ public List retrieveAllActiveUser() { public Optional findByChatId(String chatId) { return telegramuserRepository.findById(chatId); } + + @Override + public List findAllInActiveUsers() { + return telegramuserRepository.findAllByActiveFalse(); + } } diff --git a/src/main/resources/application-test.properties b/src/main/resources/application-test.properties index c5021c2..f0685b3 100644 --- a/src/main/resources/application-test.properties +++ b/src/main/resources/application-test.properties @@ -5,4 +5,7 @@ spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver #server.port=0 # TelegramBot configurations: #username=@test_javarush1_community_bot -#token=7168425753:AAEluuiQNbM_UAqhvItXQdIB68rN2QlaO9U \ No newline at end of file +#token=7168425753:AAEluuiQNbM_UAqhvItXQdIB68rN2QlaO9U + +javarush.api.path=https://javarush.com/api/1.0/rest +bot.recountNewArticleFixedRate=900000 \ No newline at end of file diff --git a/src/main/resources/application.properties b/src/main/resources/application.properties index ef7ae13..196bec9 100644 --- a/src/main/resources/application.properties +++ b/src/main/resources/application.properties @@ -6,4 +6,6 @@ spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver username=@test_javarush1_community_bot token=7168425753:AAEluuiQNbM_UAqhvItXQdIB68rN2QlaO9U -javarush.api.path=https://javarush.com/api/1.0/rest \ No newline at end of file +javarush.api.path=https://javarush.com/api/1.0/rest +bot.recountNewArticleFixedRate=900000 +bot.admins: evgen \ No newline at end of file diff --git a/src/test/java/AbstractCommandTest.java b/src/test/java/AbstractCommandTest.java index b4d0b8f..3401b3f 100644 --- a/src/test/java/AbstractCommandTest.java +++ b/src/test/java/AbstractCommandTest.java @@ -1,19 +1,24 @@ import com.githab.javarushcommunity.javarush_telegrambot.bot.JavaRushTelegramBot; import com.githab.javarushcommunity.javarush_telegrambot.command.Command; +import com.githab.javarushcommunity.javarush_telegrambot.command.CommandName; import com.githab.javarushcommunity.javarush_telegrambot.service.SendBotMessageImpl; import com.githab.javarushcommunity.javarush_telegrambot.service.SendBotMessageService; +import com.githab.javarushcommunity.javarush_telegrambot.service.StatisticsService; import com.githab.javarushcommunity.javarush_telegrambot.service.TelegramUserService; import org.junit.jupiter.api.Test; import org.mockito.Mockito; import org.telegram.telegrambots.meta.api.methods.send.SendMessage; +import org.telegram.telegrambots.meta.api.objects.Chat; import org.telegram.telegrambots.meta.api.objects.Message; import org.telegram.telegrambots.meta.api.objects.Update; +import org.telegram.telegrambots.meta.api.objects.User; import org.telegram.telegrambots.meta.exceptions.TelegramApiException; public abstract class AbstractCommandTest { protected TelegramUserService telegramUserService=Mockito.mock(TelegramUserService.class); protected JavaRushTelegramBot javaRushBot= Mockito.mock(JavaRushTelegramBot.class); protected SendBotMessageService sendBotMessageService=new SendBotMessageImpl(javaRushBot); + protected StatisticsService statisticsService=Mockito.mock(StatisticsService.class); abstract String getCommandName(); abstract String getCommandMessage(); @@ -38,5 +43,16 @@ public void shouldProperlyExecuteCommand() throws TelegramApiException{ Mockito.verify(javaRushBot).execute(sendMessage); } + public static Update prepareUpdate(Long chatId, String name){ + Update update=new Update(); + + Message message=Mockito.mock(Message.class); + Mockito.when(message.getChatId()).thenReturn(chatId); + Mockito.when(message.getText()).thenReturn(name); + update.setMessage(message); + + return update; + + } } diff --git a/src/test/java/CommandContainerTest.java b/src/test/java/CommandContainerTest.java index 8d86989..3d6f941 100644 --- a/src/test/java/CommandContainerTest.java +++ b/src/test/java/CommandContainerTest.java @@ -13,6 +13,9 @@ import org.mockito.Mockito; import java.util.Arrays; +import java.util.Collections; + +import static java.util.Collections.singletonList; @DisplayName("Unit-level testing for CommandContainer") public class CommandContainerTest { @@ -24,19 +27,19 @@ public void init(){ TelegramUserService telegramUserService=Mockito.mock(TelegramUserService.class); JavaRushGroupClient javaRushGroupClient=Mockito.mock(JavaRushGroupClient.class); GroupSubService groupSubService=Mockito.mock(GroupSubService.class); - commandContainer=new CommandContainer(sendBotMessageService,telegramUserService,javaRushGroupClient,groupSubService); + commandContainer=new CommandContainer(sendBotMessageService,telegramUserService,javaRushGroupClient,groupSubService, singletonList("username")); } @Test public void shouldGetAllTheExistingCommands(){ Arrays.stream(CommandName.values()).forEach(commandName -> { - Command command=commandContainer.retrieveCommand(commandName.getCommandName()); + Command command=commandContainer.retrieveCommand(commandName.getCommandName(),"username"); Assertions.assertNotEquals(UnknownCommand.class,command.getClass()); }); } @Test public void shouldReturnUnknownCommand(){ String unknownCommand="/wggbvsr"; - Command command=commandContainer.retrieveCommand(unknownCommand); + Command command=commandContainer.retrieveCommand(unknownCommand,"username"); Assertions.assertEquals(UnknownCommand.class,command.getClass()); } } diff --git a/src/test/java/DeleteGroupSubCommandTest.java b/src/test/java/DeleteGroupSubCommandTest.java new file mode 100644 index 0000000..7fd576f --- /dev/null +++ b/src/test/java/DeleteGroupSubCommandTest.java @@ -0,0 +1,152 @@ +import com.githab.javarushcommunity.javarush_telegrambot.command.Command; +import com.githab.javarushcommunity.javarush_telegrambot.command.DeleteGroupSubCommand; +import com.githab.javarushcommunity.javarush_telegrambot.repository.entity.GroupSub; +import com.githab.javarushcommunity.javarush_telegrambot.repository.entity.TelegramUser; +import com.githab.javarushcommunity.javarush_telegrambot.service.GroupSubService; +import com.githab.javarushcommunity.javarush_telegrambot.service.SendBotMessageService; +import com.githab.javarushcommunity.javarush_telegrambot.service.TelegramUserService; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; +import org.mockito.Mockito; +import org.telegram.telegrambots.meta.api.objects.Update; + +import java.util.AbstractList; +import java.util.ArrayList; +import java.util.List; +import java.util.Optional; + +import static com.githab.javarushcommunity.javarush_telegrambot.command.CommandName.DELETE_GROUP_SUB; +import static java.util.Collections.singletonList; + +@DisplayName("Unit-level testing for DeleteGroupSubCommandTest" ) +public class DeleteGroupSubCommandTest { + + private Command command; + private SendBotMessageService sendBotMessageService; + GroupSubService groupSubService; + TelegramUserService telegramUserService; + + @BeforeEach + public void init(){ + sendBotMessageService= Mockito.mock(SendBotMessageService.class); + groupSubService=Mockito.mock(GroupSubService.class); + telegramUserService=Mockito.mock(TelegramUserService.class); + + command=new DeleteGroupSubCommand(sendBotMessageService,telegramUserService,groupSubService); + + } + @Test + public void shouldProperlyReturnEmptySubscriptionList(){ + Long chatId=23456L; + + Update update = AbstractCommandTest.prepareUpdate(chatId,DELETE_GROUP_SUB.getCommandName()); + Mockito.when(telegramUserService.findByChatId(String.valueOf(chatId))).thenReturn(Optional.of(new TelegramUser())); + + String expectedMessage="Пока нет подписки на группу"; + command.execute(update); + Mockito.verify(sendBotMessageService).sendMessage(chatId.toString(),expectedMessage); + + } + @Test + public void shouldProperlyReturnSubscriptionLit() { + + Long chatId = 23456L; + Update update = AbstractCommandTest.prepareUpdate(chatId, DELETE_GROUP_SUB.getCommandName()); + TelegramUser telegramUser = new TelegramUser(); + GroupSub gs1 = new GroupSub(); + gs1.setId(123); + gs1.setTitle("GS1 Title"); + telegramUser.setGroupSubs(singletonList(gs1)); + Mockito.when(telegramUserService.findByChatId(String.valueOf(chatId))) + .thenReturn(Optional.of(telegramUser)); + + String expectedMessage = "Чтобы удалить подписку передай - команду вместе с ID \n\n"+ + "имя группы - ID группы \n\n"+ + "GS1 Title - 123"; + + + command.execute(update); + + + Mockito.verify(sendBotMessageService).sendMessage(chatId.toString(), expectedMessage); + } + + @Test + public void shouldRejectByInvalidGroupId() { + + Long chatId = 23456L; + Update update = AbstractCommandTest.prepareUpdate(chatId, String.format("%s %s", DELETE_GROUP_SUB.getCommandName(), "groupSubId")); + TelegramUser telegramUser = new TelegramUser(); + GroupSub gs1 = new GroupSub(); + gs1.setId(123); + gs1.setTitle("GS1 Title"); + telegramUser.setGroupSubs(singletonList(gs1)); + Mockito.when(telegramUserService.findByChatId(String.valueOf(chatId))) + .thenReturn(Optional.of(telegramUser)); + + String expectedMessage = "неправильный формат ID группы"; + + + + command.execute(update); + + + Mockito.verify(sendBotMessageService).sendMessage(chatId.toString(), expectedMessage); + } + + @Test + public void shouldProperlyDeleteByGroupId() { + + + + Long chatId = 23456L; + Integer groupId = 1234; + Update update = AbstractCommandTest.prepareUpdate(chatId, String.format("%s %s", DELETE_GROUP_SUB.getCommandName(), groupId)); + + + GroupSub gs1 = new GroupSub(); + gs1.setId(123); + gs1.setTitle("GS1 Title"); + TelegramUser telegramUser = new TelegramUser(); + telegramUser.setChat_id(chatId.toString()); + telegramUser.setGroupSubs(singletonList(gs1)); + ArrayList users = new ArrayList<>(); + users.add(telegramUser); + gs1.setUsers(users); + Mockito.when(groupSubService.findById(groupId)).thenReturn(Optional.of(gs1)); + Mockito.when(telegramUserService.findByChatId(String.valueOf(chatId))) + .thenReturn(Optional.of(telegramUser)); + + String expectedMessage = "Удалил подписку на группу: GS1 Title"; + + + command.execute(update); + + + users.remove(telegramUser); + Mockito.verify(groupSubService).save(gs1); + Mockito.verify(sendBotMessageService).sendMessage(chatId.toString(), expectedMessage); + } + + @Test + public void shouldDoesNotExistByGroupId() { + + Long chatId = 23456L; + Integer groupId = 1234; + Update update = AbstractCommandTest.prepareUpdate(chatId, String.format("%s %s", DELETE_GROUP_SUB.getCommandName(), groupId)); + + + Mockito.when(groupSubService.findById(groupId)).thenReturn(Optional.empty()); + + String expectedMessage = "Не нашел такой группы =/"; + + + command.execute(update); + + + Mockito.verify(groupSubService).findById(groupId); + Mockito.verify(sendBotMessageService).sendMessage(chatId.toString(), expectedMessage); + } +} + diff --git a/src/test/java/GroupSubServiceTest.java b/src/test/java/GroupSubServiceTest.java index 55b44f4..c57ac91 100644 --- a/src/test/java/GroupSubServiceTest.java +++ b/src/test/java/GroupSubServiceTest.java @@ -1,3 +1,4 @@ +import com.githab.javarushcommunity.javarush_telegrambot.javarushclient.JavaRushGroupClient; import com.githab.javarushcommunity.javarush_telegrambot.javarushclient.dto.GroupDiscussionInfo; import com.githab.javarushcommunity.javarush_telegrambot.repository.GroupSubRepository; import com.githab.javarushcommunity.javarush_telegrambot.repository.entity.GroupSub; @@ -18,6 +19,7 @@ public class GroupSubServiceTest { private GroupSubService groupSubService; private GroupSubRepository groupSubRepository; private TelegramUser newUser; + private JavaRushGroupClient javaRushGroupClient; private final static String CHAT_ID = "1"; @@ -25,7 +27,7 @@ public class GroupSubServiceTest { public void init() { TelegramUserService telegramUserService = Mockito.mock(TelegramUserService.class); groupSubRepository = Mockito.mock(GroupSubRepository.class); - groupSubService = new GroupSubServiceIml(groupSubRepository, telegramUserService); + groupSubService = new GroupSubServiceIml(groupSubRepository, telegramUserService,javaRushGroupClient); newUser = new TelegramUser(); newUser.setActive(true); diff --git a/src/test/java/JavaRushPostClientTest.java b/src/test/java/JavaRushPostClientTest.java new file mode 100644 index 0000000..cc45e88 --- /dev/null +++ b/src/test/java/JavaRushPostClientTest.java @@ -0,0 +1,22 @@ +import com.githab.javarushcommunity.javarush_telegrambot.javarushclient.JavaRushPostClient; +import com.githab.javarushcommunity.javarush_telegrambot.javarushclient.JavaRushPostClientIml; +import com.githab.javarushcommunity.javarush_telegrambot.javarushclient.dto.PostInfo; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; + +import java.util.List; + +public class JavaRushPostClientTest { + + private final JavaRushPostClient postClient=new JavaRushPostClientIml("https://javarush.com/api/1.0/rest"); + + @Test + public void shouldProperlyGetNew15Posts(){ + List newPosts=postClient.findNewPosts(30,2935); + Assertions.assertEquals(15,newPosts.size()); + + } + + + +} diff --git a/src/test/java/com/githab/javarushcommunity/javarush_telegrambot/ListGroupSubCommandTest.java b/src/test/java/ListGroupSubCommandTest.java similarity index 97% rename from src/test/java/com/githab/javarushcommunity/javarush_telegrambot/ListGroupSubCommandTest.java rename to src/test/java/ListGroupSubCommandTest.java index 1bfe1a2..cd2b504 100644 --- a/src/test/java/com/githab/javarushcommunity/javarush_telegrambot/ListGroupSubCommandTest.java +++ b/src/test/java/ListGroupSubCommandTest.java @@ -1,5 +1,3 @@ -package com.githab.javarushcommunity.javarush_telegrambot; - import com.githab.javarushcommunity.javarush_telegrambot.command.ListGroupSubCommand; import com.githab.javarushcommunity.javarush_telegrambot.repository.entity.GroupSub; import com.githab.javarushcommunity.javarush_telegrambot.repository.entity.TelegramUser; diff --git a/src/test/java/StatCommandTest.java b/src/test/java/StatCommandTest.java index c0a9d44..2e0c897 100644 --- a/src/test/java/StatCommandTest.java +++ b/src/test/java/StatCommandTest.java @@ -16,6 +16,6 @@ String getCommandMessage(){ @Override Command getCommand() { - return new StatCommand(sendBotMessageService,telegramUserService); + return new StatCommand(sendBotMessageService,statisticsService); } } diff --git a/src/test/java/StatisticsServiceTest.java b/src/test/java/StatisticsServiceTest.java new file mode 100644 index 0000000..3614253 --- /dev/null +++ b/src/test/java/StatisticsServiceTest.java @@ -0,0 +1,49 @@ +import com.githab.javarushcommunity.javarush_telegrambot.javarushclient.dto.GroupStatDTO; +import com.githab.javarushcommunity.javarush_telegrambot.javarushclient.dto.StatisticDTO; +import com.githab.javarushcommunity.javarush_telegrambot.repository.entity.GroupSub; +import com.githab.javarushcommunity.javarush_telegrambot.repository.entity.TelegramUser; +import com.githab.javarushcommunity.javarush_telegrambot.service.GroupSubService; +import com.githab.javarushcommunity.javarush_telegrambot.service.StatisticsService; +import com.githab.javarushcommunity.javarush_telegrambot.service.TelegramUserService; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.BeforeEach; +import org.mockito.Mockito; + +import java.util.Collections; + +import static java.util.Collections.singletonList; + +public class StatisticsServiceTest { + private GroupSubService groupSubService; + private TelegramUserService telegramUserService; + + private StatisticsService statisticsService; + + @BeforeEach + public void init(){ + groupSubService= Mockito.mock(GroupSubService.class); + telegramUserService=Mockito.mock(TelegramUserService.class); + statisticsService=Mockito.mock(StatisticsService.class); + + } + public void shouldProperlySendStatDTO(){ + Mockito.when(telegramUserService.findAllInActiveUsers()).thenReturn(singletonList(new TelegramUser())); + TelegramUser activeUser=new TelegramUser(); + activeUser.setGroupSubs(singletonList(new GroupSub())); + Mockito.when(telegramUserService.findAllActiveUser()).thenReturn(singletonList(activeUser)); + GroupSub groupSub=new GroupSub(); + groupSub.setTitle("group"); + groupSub.setId(1); + groupSub.setUsers(singletonList(new TelegramUser())); + Mockito.when(groupSubService.findAll()).thenReturn(singletonList(groupSub)); + + StatisticDTO statisticDTO=statisticsService.countBotStatistic(); + + Assertions.assertNotNull(statisticDTO); + Assertions.assertEquals(1,statisticDTO.getActiveUserCount()); + Assertions.assertEquals(1,statisticDTO.getInactiveUserCount()); + Assertions.assertEquals(1.0,statisticDTO.getAverageGroupCountByUser()); + Assertions.assertEquals(singletonList(new GroupStatDTO(groupSub.getId(),groupSub.getTitle(),groupSub.getUsers().size())), + statisticDTO.getGroupStatDTOs()); + } +} diff --git a/src/test/resources/sql/clearDbs.sql b/src/test/resources/sql/clearDbs.sql index 4d5594a..43c01bc 100644 --- a/src/test/resources/sql/clearDbs.sql +++ b/src/test/resources/sql/clearDbs.sql @@ -1 +1,3 @@ -delete from tg_user; \ No newline at end of file +delete from tg_user; +delete from group_x_user; +delete from group_sub; \ No newline at end of file