diff --git a/src/data/Thread.js b/src/data/Thread.js index 23e9e4a..fad9c36 100644 --- a/src/data/Thread.js +++ b/src/data/Thread.js @@ -169,8 +169,8 @@ class Thread { } if (this.alert_id) { - await this.setAlert(null); - await this.postSystemMessage(`<@!${this.alert_id}> New message from ${this.user_name}`); + await this.deleteAlerts(); + await this.postSystemMessage(`${this.alert_id} New message from ${this.user_name}`); } } @@ -449,14 +449,65 @@ class Thread { * @param {String} userId * @returns {Promise} */ - async setAlert(userId) { + async addAlert(userId) { + let alerts = await knex('threads') + .where('id', this.id) + .select('alert_id') + .first(); + alerts = alerts.alert_id; + + if (alerts == null) { + alerts = `<@!${userId}>`; + } else { + if (! alerts.includes(`<@!${userId}>`)) { + alerts += ` <@!${userId}>`; + } + } + await knex('threads') .where('id', this.id) .update({ - alert_id: userId + alert_id: alerts }); } + /** + * @param {String} userId + * @returns {Promise} + */ + async removeAlert(userId) { + let alerts = await knex('threads') + .where('id', this.id) + .select('alert_id') + .first(); + alerts = alerts.alert_id; + + if (! (alerts == null)) { + if (alerts.startsWith(`<@!${userId}>`)) { // we do this to properly handle the spacing between @s + alerts = alerts.replace(`<@!${userId}> `, ""); + } else { + alerts = alerts.replace(` <@!${userId}>`, ""); + } + } + + await knex('threads') + .where('id', this.id) + .update({ + alert_id: alerts + }); + } + + /** + * @returns {Promise} + */ + async deleteAlerts() { + await knex('threads') + .where('id', this.id) + .update({ + alert_id: null + }) + } + /** * @returns {Promise} */ @@ -465,4 +516,4 @@ class Thread { } } -module.exports = Thread; +module.exports = Thread; \ No newline at end of file diff --git a/src/modules/alert.js b/src/modules/alert.js index a844230..65d6576 100644 --- a/src/modules/alert.js +++ b/src/modules/alert.js @@ -1,10 +1,10 @@ module.exports = ({ bot, knex, config, commands }) => { commands.addInboxThreadCommand('alert', '[opt:string]', async (msg, args, thread) => { if (args.opt && args.opt.startsWith('c')) { - await thread.setAlert(null); - await thread.postSystemMessage(`Cancelled new message alert`); + await thread.removeAlert(msg.author.id) + await thread.postSystemMessage(`Cancelled your new message alert`); } else { - await thread.setAlert(msg.author.id); + await thread.addAlert(msg.author.id); await thread.postSystemMessage(`Pinging ${msg.author.username}#${msg.author.discriminator} when this thread gets a new reply`); } });