diff options
| author | Sin-MacBook <[email protected]> | 2020-08-10 23:44:20 +0200 |
|---|---|---|
| committer | Sin-MacBook <[email protected]> | 2020-08-10 23:44:20 +0200 |
| commit | 2a53887abba882bf7b63aeda8dfa55fdb3ab8792 (patch) | |
| tree | ad7a95eb41faa6ff13c3142285cdc0eb3ca92183 /src/data/blocked.js | |
| download | modmail-2a53887abba882bf7b63aeda8dfa55fdb3ab8792.tar.xz modmail-2a53887abba882bf7b63aeda8dfa55fdb3ab8792.zip | |
clean this up when home
Diffstat (limited to 'src/data/blocked.js')
| -rw-r--r-- | src/data/blocked.js | 94 |
1 files changed, 94 insertions, 0 deletions
diff --git a/src/data/blocked.js b/src/data/blocked.js new file mode 100644 index 0000000..81c1214 --- /dev/null +++ b/src/data/blocked.js @@ -0,0 +1,94 @@ +const moment = require('moment'); +const knex = require('../knex'); + +/** + * @param {String} userId + * @returns {Promise<{ isBlocked: boolean, expiresAt: string }>} + */ +async function getBlockStatus(userId) { + const row = await knex('blocked_users') + .where('user_id', userId) + .first(); + + return { + isBlocked: !! row, + expiresAt: row && row.expires_at + }; +} + +/** + * Checks whether userId is blocked + * @param {String} userId + * @returns {Promise<Boolean>} + */ +async function isBlocked(userId) { + return (await getBlockStatus(userId)).isBlocked; +} + +/** + * Blocks the given userId + * @param {String} userId + * @param {String} userName + * @param {String} blockedBy + * @returns {Promise} + */ +async function block(userId, userName = '', blockedBy = null, expiresAt = null) { + if (await isBlocked(userId)) return; + + return knex('blocked_users') + .insert({ + user_id: userId, + user_name: userName, + blocked_by: blockedBy, + blocked_at: moment.utc().format('YYYY-MM-DD HH:mm:ss'), + expires_at: expiresAt + }); +} + +/** + * Unblocks the given userId + * @param {String} userId + * @returns {Promise} + */ +async function unblock(userId) { + return knex('blocked_users') + .where('user_id', userId) + .delete(); +} + +/** + * Updates the expiry time of the block for the given userId + * @param {String} userId + * @param {String} expiresAt + * @returns {Promise<void>} + */ +async function updateExpiryTime(userId, expiresAt) { + return knex('blocked_users') + .where('user_id', userId) + .update({ + expires_at: expiresAt + }); +} + +/** + * @returns {String[]} + */ +async function getExpiredBlocks() { + const now = moment.utc().format('YYYY-MM-DD HH:mm:ss'); + + const blocks = await knex('blocked_users') + .whereNotNull('expires_at') + .where('expires_at', '<=', now) + .select(); + + return blocks.map(block => block.user_id); +} + +module.exports = { + getBlockStatus, + isBlocked, + block, + unblock, + updateExpiryTime, + getExpiredBlocks, +}; |