Skip to content

Commit

Permalink
Move reminders to their own separate module
Browse files Browse the repository at this point in the history
  • Loading branch information
Matyrobbrt committed Aug 28, 2024
1 parent 2ce941a commit 4c053a4
Show file tree
Hide file tree
Showing 12 changed files with 72 additions and 30 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
import net.neoforged.camelot.db.impl.PostCallbackDecorator;
import net.neoforged.camelot.module.BuiltInModule;
import net.neoforged.camelot.module.api.CamelotModule;
import net.neoforged.camelot.module.custompings.db.PingsCallbacks;
import net.neoforged.camelot.module.custompings.db.PingsDAO;

import java.util.Objects;
Expand All @@ -33,14 +34,14 @@ public CustomPingsModule() {
});

logger.info("Moving custom pings from pings.db to custom-pings.db");
isMigrating = true;
PingsCallbacks.migrating = true;
var pings = stmt.executeQuery("select * from pings");
db().useExtension(PingsDAO.class, db -> {
while (pings.next()) {
db.insert(pings.getLong(2), pings.getLong(3), pings.getString(4), pings.getString(5));
}
});
isMigrating = false;
PingsCallbacks.migrating = false;

CustomPingListener.requestRefresh();
}));
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,13 @@

import net.neoforged.camelot.db.api.ExecutionCallback;
import net.neoforged.camelot.module.custompings.CustomPingListener;
import net.neoforged.camelot.module.custompings.CustomPingsModule;

public class PingsCallbacks {
public static volatile boolean migrating;

@ExecutionCallback(methodName = "insert")
public static void onInsert(PingsDAO dao, long guild, long user, String regex, String message) {
if (!CustomPingsModule.isMigrating) {
if (!migrating) {
CustomPingListener.requestRefresh();
}
}
Expand Down
11 changes: 11 additions & 0 deletions modules/reminders/build.gradle
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
plugins {
id 'camelot-module'
}

camelotModule {
id = 'reminders'
}

dependencies {
library(libs.bundles.database)
}
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
package net.neoforged.camelot.commands.utility;
package net.neoforged.camelot.module.reminders;

import com.jagrosh.jdautilities.command.CooldownScope;
import com.jagrosh.jdautilities.command.SlashCommand;
Expand All @@ -13,11 +13,10 @@
import net.dv8tion.jda.api.utils.messages.MessageEditBuilder;
import net.dv8tion.jda.api.utils.messages.MessageEditData;
import net.neoforged.camelot.BotMain;
import net.neoforged.camelot.Database;
import net.neoforged.camelot.commands.PaginatableCommand;
import net.neoforged.camelot.db.schemas.Reminder;
import net.neoforged.camelot.db.transactionals.RemindersDAO;
import net.neoforged.camelot.listener.DismissListener;
import net.neoforged.camelot.module.reminders.db.Reminder;
import net.neoforged.camelot.module.reminders.db.RemindersDAO;
import net.neoforged.camelot.util.DateUtils;

import java.time.Instant;
Expand Down Expand Up @@ -58,7 +57,7 @@ protected void execute(final SlashCommandEvent event) {
try {
final var time = DateUtils.getDurationFromInput(event.getOption("time", "", OptionMapping::getAsString));
final var remTime = Instant.now().plus(time);
Database.main().useExtension(RemindersDAO.class, db -> db.insertReminder(
BotMain.getModule(RemindersModule.class).db().useExtension(RemindersDAO.class, db -> db.insertReminder(
userId, event.isFromType(ChannelType.PRIVATE) ? 0 : event.getChannel().getIdLong(), remTime.getEpochSecond(), event.getOption("content", OptionMapping::getAsString)
));
event.deferReply().setContent("Successfully scheduled reminder on %s (%s)!".formatted(TimeFormat.DATE_TIME_LONG.format(remTime), TimeFormat.RELATIVE.format(remTime)))
Expand All @@ -84,7 +83,7 @@ public Delete() {

@Override
protected void execute(SlashCommandEvent event) {
final Reminder reminder = Database.main().withExtension(RemindersDAO.class, db -> db.getReminderById(event.getOption("reminder", 0, OptionMapping::getAsInt)));
final Reminder reminder = BotMain.getModule(RemindersModule.class).db().withExtension(RemindersDAO.class, db -> db.getReminderById(event.getOption("reminder", 0, OptionMapping::getAsInt)));
if (reminder == null) {
event.reply("Unknown reminder!").setEphemeral(true).queue();
return;
Expand All @@ -94,7 +93,7 @@ protected void execute(SlashCommandEvent event) {
return;
}

Database.main().useExtension(RemindersDAO.class, db -> db.deleteReminder(reminder.id()));
BotMain.getModule(RemindersModule.class).db().useExtension(RemindersDAO.class, db -> db.deleteReminder(reminder.id()));
event.reply("Reminder deleted!").setEphemeral(true).queue();
}
}
Expand All @@ -113,7 +112,7 @@ public ListCmd() {

@Override
public ListCmd.Data collectData(SlashCommandEvent event) {
return new ListCmd.Data(Database.main().withExtension(RemindersDAO.class, db -> db.getAllRemindersOf(
return new ListCmd.Data(BotMain.getModule(RemindersModule.class).db().withExtension(RemindersDAO.class, db -> db.getAllRemindersOf(
event.getUser().getIdLong()
)));
}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
package net.neoforged.camelot.module;
package net.neoforged.camelot.module.reminders;

import com.github.benmanes.caffeine.cache.Cache;
import com.github.benmanes.caffeine.cache.Caffeine;
Expand Down Expand Up @@ -30,14 +30,14 @@
import net.dv8tion.jda.api.utils.messages.MessageCreateBuilder;
import net.dv8tion.jda.api.utils.messages.MessageCreateData;
import net.neoforged.camelot.BotMain;
import net.neoforged.camelot.Database;
import net.neoforged.camelot.commands.utility.RemindCommand;
import net.neoforged.camelot.config.module.Reminders;
import net.neoforged.camelot.db.schemas.Reminder;
import net.neoforged.camelot.db.transactionals.RemindersDAO;
import net.neoforged.camelot.listener.DismissListener;
import net.neoforged.camelot.listener.ReferencingListener;
import net.neoforged.camelot.module.BuiltInModule;
import net.neoforged.camelot.module.api.CamelotModule;
import net.neoforged.camelot.module.reminders.db.Reminder;
import net.neoforged.camelot.module.reminders.db.RemindersCallbacks;
import net.neoforged.camelot.module.reminders.db.RemindersDAO;
import net.neoforged.camelot.util.DateUtils;
import net.neoforged.camelot.util.Emojis;
import net.neoforged.camelot.util.Utils;
Expand All @@ -55,12 +55,30 @@
import java.util.function.Supplier;

@AutoService(CamelotModule.class)
public class RemindersModule extends CamelotModule.Base<Reminders> {
public class RemindersModule extends CamelotModule.WithDatabase<Reminders> {
public static final Supplier<ScheduledExecutorService> EXECUTOR = Suppliers.memoize(() ->
Executors.newScheduledThreadPool(1, Utils.daemonGroup("Reminders")));

public RemindersModule() {
super(Reminders.class);

accept(BuiltInModule.DB_MIGRATION_CALLBACKS, builder -> builder
.add(BuiltInModule.DatabaseSource.MAIN, 17, statement -> {
logger.info("Moving reminders from main.db to reminders.db");
RemindersCallbacks.migrating = true;
var rs = statement.executeQuery("select * from reminders");
db().useExtension(RemindersDAO.class, db -> {
while (rs.next()) {
db.insertReminder(
rs.getLong(2),
rs.getLong(3),
rs.getLong(4),
rs.getString(5)
);
}
});
RemindersCallbacks.migrating = false;
}));
}

private static final String SNOOZE_BUTTON_ID = "snooze_reminder";
Expand Down Expand Up @@ -120,7 +138,7 @@ public void setup(JDA jda) {
var url = "https://discord.com/channels/" + event.getGuild().getId() + "/" + event.getChannel().getId() + "/" + msgId;
final var time = DateUtils.getDurationFromInput(event.getValue("time").getAsString());
final var remTime = Instant.now().plus(time);
Database.main().useExtension(RemindersDAO.class, db -> db.insertReminder(
db().useExtension(RemindersDAO.class, db -> db.insertReminder(
event.getUser().getIdLong(), event.getChannel().getIdLong(), remTime.getEpochSecond(),
(url + " " + Optional.ofNullable(event.getValue("text")).map(ModalMapping::getAsString).orElse("")).trim()
));
Expand All @@ -134,7 +152,7 @@ public void setup(JDA jda) {
snoozeButtons = ActionRow.partitionOf(config().getSnoozeDurations().stream().map(duration -> Button.of(ButtonStyle.SECONDARY, SNOOZE_BUTTON_ID + "-" + duration.getSeconds(), DateUtils.formatDuration(duration), SNOOZE_EMOJI))
.toArray(ItemComponent[]::new));

Database.main().useExtension(RemindersDAO.class, db -> db.getAllReminders()
db().useExtension(RemindersDAO.class, db -> db.getAllReminders()
.forEach(reminder -> {
final Instant now = Instant.now();
if (reminder.time().isBefore(now)) {
Expand Down Expand Up @@ -165,7 +183,7 @@ public void registerListeners(JDABuilder builder) {

final Instant offset = Instant.now().plusSeconds(snoozeSecs);
snoozable.invalidate(event.getMessage().getIdLong());
Database.main().useExtension(RemindersDAO.class, db -> db.insertReminder(
db().useExtension(RemindersDAO.class, db -> db.insertReminder(
reminder.user(), reminder.channel(), offset.getEpochSecond(), reminder.reminder()
));
event.reply("Successfully snoozed reminder until %s (%s)!".formatted(TimeFormat.DATE_TIME_LONG.format(offset), TimeFormat.RELATIVE.format(offset)))
Expand All @@ -174,7 +192,7 @@ public void registerListeners(JDABuilder builder) {
}

public void run(int reminderId) {
final var reminder = Database.main().withExtension(RemindersDAO.class, db -> db.getReminderById(reminderId));
final var reminder = db().withExtension(RemindersDAO.class, db -> db.getReminderById(reminderId));
if (reminder == null) return;

BotMain.get().retrieveUserById(reminder.user())
Expand Down Expand Up @@ -207,7 +225,7 @@ public void run(int reminderId) {
BotMain.LOGGER.error("Failed to send reminder to '{}' in channel with ID '{}': ", reminder.user(), reminder.channel(), err);
return null;
})
.whenComplete((a, b) -> Database.main().useExtension(RemindersDAO.class, db -> db.deleteReminder(reminderId)));
.whenComplete((a, b) -> db().useExtension(RemindersDAO.class, db -> db.deleteReminder(reminderId)));
}

private RestAction<Message> sendMessage(User user, Reminder reminder, MessageChannel channel) {
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
package net.neoforged.camelot.db.schemas;
package net.neoforged.camelot.module.reminders.db;

import org.jdbi.v3.core.mapper.RowMapper;
import org.jdbi.v3.core.statement.StatementContext;
Expand Down
Original file line number Diff line number Diff line change
@@ -1,9 +1,8 @@
package net.neoforged.camelot.db.callback;
package net.neoforged.camelot.module.reminders.db;

import net.neoforged.camelot.BotMain;
import net.neoforged.camelot.db.api.ExecutionCallback;
import net.neoforged.camelot.db.transactionals.RemindersDAO;
import net.neoforged.camelot.module.RemindersModule;
import net.neoforged.camelot.module.reminders.RemindersModule;

import java.time.Instant;
import java.util.concurrent.TimeUnit;
Expand All @@ -12,12 +11,16 @@
* Callbacks for {@link RemindersDAO}.
*/
public class RemindersCallbacks {
public static volatile boolean migrating;

/**
* A callback that is called when a new reminder is added to the database.
* This callback will schedule the reminder to the {@link RemindersModule#EXECUTOR}.
*/
@ExecutionCallback(methodName = "insertReminder", phase = ExecutionCallback.Phase.POST)
public static void onReminderAdded(RemindersDAO dao, long user, long channel, long time, String reminder) {
if (migrating) return;

final int id = dao.getHandle().createQuery("select max(id) from reminders").execute((statement, ctx) -> statement.get().getResultSet().getInt(1));
BotMain.EXECUTOR.schedule(() -> BotMain.getModule(RemindersModule.class).run(id), time - Instant.now().getEpochSecond(), TimeUnit.SECONDS);
}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,8 +1,6 @@
package net.neoforged.camelot.db.transactionals;
package net.neoforged.camelot.module.reminders.db;

import net.neoforged.camelot.db.api.RegisterExecutionCallbacks;
import net.neoforged.camelot.db.callback.RemindersCallbacks;
import net.neoforged.camelot.db.schemas.Reminder;
import org.jdbi.v3.sqlobject.config.RegisterRowMapper;
import org.jdbi.v3.sqlobject.statement.SqlQuery;
import org.jdbi.v3.sqlobject.statement.SqlUpdate;
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
create table reminders
(
-- alias for rowid --
id integer primary key,
user big int not null,
channel big int,
"time" big int not null,
reminder text not null
)
1 change: 1 addition & 0 deletions settings.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -36,3 +36,4 @@ include ':modules:file-preview'
include ':modules:thread-pings'
include ':modules:quotes'
include ':modules:custom-pings'
include ':modules:reminders'
1 change: 1 addition & 0 deletions src/main/resources/db/main/V17__move_reminders.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
drop table reminders;

0 comments on commit 4c053a4

Please sign in to comment.