|
| 1 | +package org.togetherjava.tjbot.features.basic; |
| 2 | + |
| 3 | +import net.dv8tion.jda.api.JDA; |
| 4 | +import net.dv8tion.jda.api.entities.Guild; |
| 5 | +import net.dv8tion.jda.api.entities.Member; |
| 6 | +import org.jooq.Query; |
| 7 | +import org.jooq.impl.DSL; |
| 8 | +import org.slf4j.Logger; |
| 9 | +import org.slf4j.LoggerFactory; |
| 10 | + |
| 11 | +import org.togetherjava.tjbot.config.CakeDayConfig; |
| 12 | +import org.togetherjava.tjbot.config.Config; |
| 13 | +import org.togetherjava.tjbot.db.Database; |
| 14 | +import org.togetherjava.tjbot.db.generated.tables.records.CakeDaysRecord; |
| 15 | +import org.togetherjava.tjbot.features.Routine; |
| 16 | + |
| 17 | +import java.time.OffsetDateTime; |
| 18 | +import java.time.format.DateTimeFormatter; |
| 19 | +import java.util.ArrayList; |
| 20 | +import java.util.List; |
| 21 | +import java.util.Optional; |
| 22 | +import java.util.concurrent.CompletableFuture; |
| 23 | +import java.util.concurrent.TimeUnit; |
| 24 | +import java.util.stream.Collectors; |
| 25 | + |
| 26 | +import static org.togetherjava.tjbot.db.generated.tables.CakeDays.CAKE_DAYS; |
| 27 | + |
| 28 | +public class CakeDayRoutine implements Routine { |
| 29 | + |
| 30 | + private static final Logger logger = LoggerFactory.getLogger(CakeDayRoutine.class); |
| 31 | + private static final DateTimeFormatter MONTH_DAY_FORMATTER = |
| 32 | + DateTimeFormatter.ofPattern("MM-dd"); |
| 33 | + private static final int BULK_INSERT_SIZE = 500; |
| 34 | + private final CakeDayConfig config; |
| 35 | + private final Database database; |
| 36 | + |
| 37 | + public CakeDayRoutine(Config config, Database database) { |
| 38 | + this.config = config.getCakeDayConfig(); |
| 39 | + this.database = database; |
| 40 | + } |
| 41 | + |
| 42 | + /** |
| 43 | + * Retrieves the schedule of this routine. Called by the core system once during the startup in |
| 44 | + * order to execute the routine accordingly. |
| 45 | + * <p> |
| 46 | + * Changes on the schedule returned by this method afterwards will not be picked up. |
| 47 | + * |
| 48 | + * @return the schedule of this routine |
| 49 | + */ |
| 50 | + @Override |
| 51 | + public Schedule createSchedule() { |
| 52 | + return new Schedule(ScheduleMode.FIXED_RATE, 0, 1, TimeUnit.DAYS); |
| 53 | + } |
| 54 | + |
| 55 | + /** |
| 56 | + * Triggered by the core system on the schedule defined by {@link #createSchedule()}. |
| 57 | + * |
| 58 | + * @param jda the JDA instance the bot is operating with |
| 59 | + */ |
| 60 | + @Override |
| 61 | + public void runRoutine(JDA jda) { |
| 62 | + if (getCakeDayCount(this.database) == 0) { |
| 63 | + int guildsCount = jda.getGuilds().size(); |
| 64 | + |
| 65 | + logger.info("Found empty cake_days table. Populating from guild count: {}", |
| 66 | + guildsCount); |
| 67 | + CompletableFuture.runAsync(() -> populateAllGuildCakeDays(jda)) |
| 68 | + .handle((result, exception) -> { |
| 69 | + if (exception != null) { |
| 70 | + logger.error("populateAllGuildCakeDays failed. Message: {}", |
| 71 | + exception.getMessage()); |
| 72 | + } else { |
| 73 | + logger.info("populateAllGuildCakeDays completed."); |
| 74 | + } |
| 75 | + |
| 76 | + return result; |
| 77 | + }); |
| 78 | + } |
| 79 | + } |
| 80 | + |
| 81 | + private int getCakeDayCount(Database database) { |
| 82 | + return database.read(context -> context.fetchCount(CAKE_DAYS)); |
| 83 | + } |
| 84 | + |
| 85 | + private void populateAllGuildCakeDays(JDA jda) { |
| 86 | + jda.getGuilds().forEach(this::batchPopulateGuildCakeDays); |
| 87 | + } |
| 88 | + |
| 89 | + private void batchPopulateGuildCakeDays(Guild guild) { |
| 90 | + final List<Query> queriesBuffer = new ArrayList<>(); |
| 91 | + |
| 92 | + guild.getMembers().stream().filter(Member::hasTimeJoined).forEach(member -> { |
| 93 | + if (queriesBuffer.size() == BULK_INSERT_SIZE) { |
| 94 | + database.write(context -> context.batch(queriesBuffer).execute()); |
| 95 | + queriesBuffer.clear(); |
| 96 | + return; |
| 97 | + } |
| 98 | + |
| 99 | + Optional<Query> query = createMemberCakeDayQuery(member, guild.getIdLong()); |
| 100 | + query.ifPresent(queriesBuffer::add); |
| 101 | + }); |
| 102 | + |
| 103 | + // Flush the queries buffer so that the remaining ones get written |
| 104 | + if (!queriesBuffer.isEmpty()) { |
| 105 | + database.write(context -> context.batch(queriesBuffer).execute()); |
| 106 | + } |
| 107 | + } |
| 108 | + |
| 109 | + private Optional<Query> createMemberCakeDayQuery(Member member, long guildId) { |
| 110 | + if (!member.hasTimeJoined()) { |
| 111 | + return Optional.empty(); |
| 112 | + } |
| 113 | + |
| 114 | + OffsetDateTime cakeDay = member.getTimeJoined(); |
| 115 | + String joinedMonthDay = cakeDay.format(MONTH_DAY_FORMATTER); |
| 116 | + |
| 117 | + return Optional.of(DSL.insertInto(CAKE_DAYS) |
| 118 | + .set(CAKE_DAYS.JOINED_MONTH_DAY, joinedMonthDay) |
| 119 | + .set(CAKE_DAYS.JOINED_YEAR, cakeDay.getYear()) |
| 120 | + .set(CAKE_DAYS.GUILD_ID, guildId) |
| 121 | + .set(CAKE_DAYS.USER_ID, member.getIdLong())); |
| 122 | + } |
| 123 | + |
| 124 | + private List<CakeDaysRecord> findCakeDaysTodayFromDatabase() { |
| 125 | + String todayMonthDay = OffsetDateTime.now().format(MONTH_DAY_FORMATTER); |
| 126 | + |
| 127 | + return database |
| 128 | + .read(context -> context.selectFrom(CAKE_DAYS) |
| 129 | + .where(CAKE_DAYS.JOINED_MONTH_DAY.eq(todayMonthDay)) |
| 130 | + .fetch()) |
| 131 | + .collect(Collectors.toList()); |
| 132 | + } |
| 133 | +} |
0 commit comments