All files / message message.service.ts

100% Statements 68/68
100% Branches 24/24
100% Functions 14/14
100% Lines 66/66

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284          18x 18x 18x 18x 18x   18x         18x           18x   34x 34x 34x 34x 34x 34x 34x 34x                                 11x       11x 11x   11x 9x 9x   9x 7x 6x               6x 6x   1x         2x     2x                     2x       2x                   12x         12x 9x   3x                     7x   7x 6x                                   6x 6x   1x                             5x 5x   5x 3x             2x                     3x   2x                       2x           2x   2x                   2x   1x                       1x           1x   1x                 6x                   9x       9x 9x   9x 7x                   7x 7x   2x        
/**
 * Message service.
 * @packageDocumentation
 */
 
import { Injectable, Inject, forwardRef } from '@nestjs/common';
import { DBService } from '../db/db.service';
import { ResourceService } from '../resource/resource.service';
import { UserService } from '../user/user.service';
import { BlockService } from '../block/block.service';
import { NBMessage } from './message.interface';
import { ServiceException } from '../service.exception';
 
/**
 * Message table name.
 */
export const messageTableName = 'NB_MESSAGE';
 
/**
 * Message table service.
 */
@Injectable()
export class MessageService {
  constructor(
    @Inject(forwardRef(() => DBService))
    private readonly dbService: DBService,
    @Inject(forwardRef(() => ResourceService))
    private readonly resourceService: ResourceService,
    @Inject(forwardRef(() => UserService))
    private readonly userService: UserService,
    @Inject(forwardRef(() => BlockService))
    private readonly blockService: BlockService,
  ) {}
 
  /**
   * Send a message.
   *
   * @param fromUserID The ID of the user sending the message.
   * @param toUserID The ID of the user receiving the message.
   * @param content The message content.
   * @returns The new message record.
   */
  public async sendMessage(
    fromUserID: string,
    toUserID: string,
    content: string,
  ): Promise<NBMessage> {
    const messageContentMaxLength =
      await this.resourceService.getResource<number>(
        'MESSAGE_CONTENT_MAX_LENGTH',
      );
 
    const fromUserExists = await this.userService.userExists(fromUserID);
    const toUserExists = await this.userService.userExists(toUserID);
 
    if (fromUserExists && toUserExists) {
      const blocked1 = await this.blockService.isBlocked(fromUserID, toUserID);
      const blocked2 = await this.blockService.isBlocked(toUserID, fromUserID);
 
      if (!blocked1 && !blocked2) {
        if (content.length >= 1 && content.length <= messageContentMaxLength) {
          const message = await this.dbService.create<NBMessage>(
            messageTableName,
            {
              fromUserID,
              toUserID,
              content,
            },
          );
          await this.deleteOldMessages(fromUserID, toUserID);
          return message;
        } else {
          throw new ServiceException(
            `Message content must be between 1 and ${messageContentMaxLength} characters`,
          );
        }
      } else {
        throw new ServiceException('User is blocked');
      }
    } else {
      throw new ServiceException('User does not exist');
    }
  }
 
  /**
   * Determine whether or not a message exists.
   *
   * @param messageID The message's ID.
   * @returns Whether or not the message exists.
   */
  public async messageExists(messageID: string): Promise<boolean> {
    const message = await this.dbService.getByID<NBMessage>(
      messageTableName,
      messageID,
    );
    return !!message;
  }
 
  /**
   * Get a message.
   *
   * @param messageID The message's ID.
   * @returns The message record.
   */
  public async getMessage(messageID: string): Promise<NBMessage> {
    const message = await this.dbService.getByID<NBMessage>(
      messageTableName,
      messageID,
    );
 
    if (message) {
      return message;
    } else {
      throw new ServiceException('Message does not exist');
    }
  }
 
  /**
   * Get a user's message threads.
   *
   * @param userID The user's ID.
   * @returns
   */
  public async getMessageThreads(userID: string): Promise<NBMessage[]> {
    const userExists = await this.userService.userExists(userID);
 
    if (userExists) {
      const sql = `
        WITH x AS (
          SELECT
              MAX("sendTime") "sendTime",
              least("fromUserID", "toUserID") "userID1",
              greatest("fromUserID", "toUserID") "userID2"
            FROM "${messageTableName}"
            GROUP BY
              least("fromUserID", "toUserID"),
              greatest("fromUserID", "toUserID")
        )
        SELECT "${messageTableName}".*
          FROM "${messageTableName}"
          JOIN x
            ON "${messageTableName}"."sendTime" = x."sendTime"
          WHERE "fromUserID" = ? OR "toUserID" = ?
          ORDER BY "sendTime" DESC;
      `;
      const params = [userID, userID];
      return this.dbService.execute<NBMessage>(sql, params);
    } else {
      throw new ServiceException('User does not exist');
    }
  }
 
  /**
   * Get message history for two users.
   *
   * @param userID1 One user's ID.
   * @param userID2 Another user's ID.
   * @returns Messages exchanged between two users.
   */
  public async getMessages(
    userID1: string,
    userID2: string,
  ): Promise<NBMessage[]> {
    const user1Exists = await this.userService.userExists(userID1);
    const user2Exists = await this.userService.userExists(userID2);
 
    if (user1Exists && user2Exists) {
      return this.dbService.listCustom<NBMessage>(
        messageTableName,
        '("fromUserID" = ? AND "toUserID" = ?) OR ("fromUserID" = ? AND "toUserID" = ?)',
        { fieldName: 'sendTime', sortOrder: 'ASC' },
        [userID1, userID2, userID2, userID1],
      );
    } else {
      throw new ServiceException('User does not exist');
    }
  }
 
  /**
   * Mark a message as read.
   *
   * @param messageID The message's ID.
   * @returns The updated message record.
   */
  public async markRead(messageID: string): Promise<NBMessage> {
    const message = await this.getMessage(messageID);
 
    const sql = `
      WITH updated AS (
        UPDATE "${messageTableName}"
          SET
            "read" = TRUE
          WHERE
            "fromUserID" = ? AND "toUserID" = ? AND EXTRACT(EPOCH FROM "sendTime") <= ?
        RETURNING *
      )
      SELECT *
        FROM updated
        WHERE id = ?;`;
    const params = [
      message.fromUserID,
      message.toUserID,
      message.sendTime / 1000 + 0.000999,
      messageID,
    ];
    const messages = await this.dbService.execute<NBMessage>(sql, params);
 
    return messages[0];
  }
 
  /**
   * Mark a message as unread.
   *
   * @param messageID The message's ID.
   * @returns The updated message record.
   */
  public async markUnread(messageID: string): Promise<NBMessage> {
    const message = await this.getMessage(messageID);
 
    const sql = `
      WITH updated AS (
        UPDATE "${messageTableName}"
          SET
            "read" = FALSE
          WHERE
            "fromUserID" = ? AND "toUserID" = ? AND EXTRACT(EPOCH FROM "sendTime") >= ?
        RETURNING *
      )
      SELECT *
        FROM updated
        WHERE id = ?;`;
    const params = [
      message.fromUserID,
      message.toUserID,
      message.sendTime / 1000,
      messageID,
    ];
    const messages = await this.dbService.execute<NBMessage>(sql, params);
 
    return messages[0];
  }
 
  /**
   * Delete a message.
   *
   * @param messageID The message's ID.
   */
  public async deleteMessage(messageID: string): Promise<void> {
    await this.dbService.deleteByID(messageTableName, messageID);
  }
 
  /**
   * Delete old messages.
   */
  public async deleteOldMessages(
    fromUserID: string,
    toUserID: string,
  ): Promise<void> {
    const maxMessages = await this.resourceService.getResource<number>(
      'MAX_MESSAGES',
    );
 
    const fromUserExists = await this.userService.userExists(fromUserID);
    const toUserExists = await this.userService.userExists(toUserID);
 
    if (fromUserExists && toUserExists) {
      const sql = `
        DELETE FROM "${messageTableName}"
          WHERE "fromUserID" = ? AND "toUserID" = ?
          AND "id" NOT IN (
            SELECT "id" FROM "${messageTableName}"
              WHERE "fromUserID" = ? AND "toUserID" = ?
              ORDER BY "sendTime" DESC
              LIMIT ?
          );
      `;
      const params = [fromUserID, toUserID, fromUserID, toUserID, maxMessages];
      await this.dbService.execute(sql, params);
    } else {
      throw new ServiceException('User does not exist');
    }
  }
}