aboutsummaryrefslogtreecommitdiff
path: root/src/data/blocked.js
blob: 81c121476b0a5007011c8e674cf74b810dc724b2 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
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,
};