All files / src/routes conversations.js

97.79% Statements 133/136
95.2% Branches 119/125
87.5% Functions 14/16
98.26% Lines 113/115

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 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338              4x 4x 4x 4x 4x   4x 4x 4x 4x 4x 4x           37x                                                   9x 3x 3x 3x 3x   3x 1x   2x         37x 10x 9x 6x 5x 4x                                 35x 35x   50x 35x 50x     35x         28x 28x 18x   28x 28x 18x     28x 37x 37x 37x   37x   4x 4x                   4x 4x 1x       7x                 35x 35x         1x               4x 7x   7x 6x 5x 5x 1x     4x         4x           4x     4x   1x       1x         4x 44x 44x 44x 44x   43x 43x 43x 43x 43x 43x 43x     43x 2x       41x       41x     41x 41x 38x 37x     41x 39x 38x 38x   37x 37x 2x   85x 35x 35x   35x                                           35x 35x   35x 35x                   35x 50x                 35x     35x   50x         1x             50x 35x                               35x             35x       2x         2x       4x  
/**
 * Conversation routes - private messaging.
 *
 * GET  /api/conversations/:id/messages -> Get conversation messages
 * POST /api/conversations/:id/messages -> Send message (with FCM push + RTDB broadcast)
 */
 
const router = require('express').Router();
const { db, rtdb, FieldValue } = require('../utils/firebase');
const { generateId, now } = require('../utils/helpers');
const { sendFcmToTokens, cleanupInvalidTokens } = require('../utils/fcm');
const log = require('../utils/log');
 
const DEFAULT_MESSAGE_LIMIT = 50;
const MAX_MESSAGE_LIMIT = 200;
const MAX_TEXT_LENGTH = 2000;
const MAX_IMAGES_PER_MESSAGE = 10;
const MAX_SENDER_NAME_LENGTH = 50;
const VALID_MESSAGE_TYPES = ['TEXT', 'IMAGE', 'STICKER', 'ROOM_INVITE', 'MOD_ACTION'];
 
/**
 * Build a plain message object from a Firestore message doc.
 */
function buildMessage(doc) {
  return {
    id: doc.id,
    messageId: doc.id,
    senderId: doc.senderId || '',
    senderName: doc.senderName || '',
    text: doc.text || '',
    imageUrls: doc.imageUrls || [],
    type: doc.type || 'TEXT',
    createdAt: doc.createdAt || 0,
    editedAt: doc.editedAt || null,
    editCount: doc.editCount || 0,
    replyToMessageId: doc.replyToId || doc.replyToMessageId || null,
    replyToText: doc.replyToText || null,
    replyToSenderName: doc.replyToSenderName || null,
    stickerUrl: doc.stickerUrl || null,
    roomInviteId: doc.roomInviteId || null,
    roomInviteName: doc.roomInviteName || null,
    reactions: doc.reactions || {},
    isRecalled: !!doc.isRecalled,
    isHidden: !!doc.isHidden,
    hiddenBy: doc.hiddenBy || null,
  };
}
 
/** Check if the current time falls within a user's DND schedule. */
function isInDndPeriod(user) {
  if (!user.dndEnabled) return false;
  const utcNow = new Date();
  const currentMinutes = utcNow.getUTCHours() * 60 + utcNow.getUTCMinutes();
  const dndStart = (user.dndStartHour || 0) * 60 + (user.dndStartMinute || 0);
  const dndEnd = (user.dndEndHour || 0) * 60 + (user.dndEndMinute || 0);
 
  if (dndStart <= dndEnd) {
    return currentMinutes >= dndStart && currentMinutes < dndEnd;
  }
  return currentMinutes >= dndStart || currentMinutes < dndEnd;
}
 
/** Determine if a recipient should receive a notification. */
function shouldNotifyRecipient(user, settings) {
  if (!user) return false;
  if (user.pmNotificationsEnabled === false) return false;
  if (isInDndPeriod(user)) return false;
  if (settings?.isMuted) return false;
  if (!user.fcmTokens || user.fcmTokens.length === 0) return false;
  return true;
}
 
/**
 * Send FCM push notifications to conversation participants (except sender).
 * Uses batch Firestore reads to minimize read cost.
 */
async function sendMessageNotifications(
  conversationId,
  senderId,
  senderName,
  previewText,
  type,
  recipients,
  isGroup,
  groupName,
) {
  try {
    Iif (recipients.length === 0) return;
 
    const userRefs = recipients.map((p) => db.doc(`users/${p.userId}`));
    const settingsRefs = recipients.map((p) =>
      db.doc(`conversations/${conversationId}/userSettings/${p.userId}`),
    );
 
    const [userSnaps, settingsSnaps] = await Promise.all([
      db.getAll(...userRefs),
      db.getAll(...settingsRefs),
    ]);
 
    const usersById = {};
    for (const snap of userSnaps) {
      if (snap.exists) usersById[snap.id] = snap.data();
    }
    const settingsById = {};
    for (const snap of settingsSnaps) {
      if (snap.exists) settingsById[snap.id] = snap.data();
    }
 
    for (const p of recipients) {
      const recipientId = p.userId;
      const user = usersById[recipientId];
      const settings = settingsById[recipientId];
 
      if (!shouldNotifyRecipient(user, settings)) continue;
 
      const showPreview = user.pmNotificationPreview !== false;
      const data = {
        type: 'PM',
        senderId,
        senderName: isGroup ? `${senderName} (${groupName || 'Group'})` : senderName,
        messageText: showPreview ? previewText : 'New message',
        conversationId,
        isGroup: String(isGroup),
        showPreview: String(showPreview),
      };
 
      const invalidTokens = await sendFcmToTokens(user.fcmTokens, data);
      if (invalidTokens.length > 0) {
        await cleanupInvalidTokens(invalidTokens, recipientId);
      }
    }
  } catch (err) {
    log.error('conversations', 'Failed to send message notifications', {
      conversationId,
      error: err.message,
    });
  }
}
 
/** Broadcast a conversation event via RTDB. */
async function broadcastToConversation(conversationId, data) {
  try {
    await rtdb.ref(`conversations/${conversationId}/events/lastEvent`).set({
      type: data.type,
      ts: Date.now(),
    });
  } catch (err) {
    log.error('conversations', 'Failed to write RTDB event', {
      conversationId,
      error: err.message,
    });
  }
}
 
// -- Get messages --
router.get('/conversations/:id/messages', async (req, res) => {
  try {
    // Verify the requester is a participant
    const convSnap = await db.doc(`conversations/${req.params.id}`).get();
    if (!convSnap.exists) return res.status(404).json({ error: 'Conversation not found' });
    const participantIds = convSnap.data().participantIds || [];
    if (!participantIds.includes(req.auth.uniqueId)) {
      return res.status(403).json({ error: 'Not a participant of this conversation' });
    }
 
    const limit = Math.min(
      Number.parseInt(req.query.limit, 10) || DEFAULT_MESSAGE_LIMIT,
      MAX_MESSAGE_LIMIT,
    );
 
    const snap = await db
      .collection(`conversations/${req.params.id}/messages`)
      .orderBy('createdAt', 'desc')
      .limit(limit)
      .get();
 
    const messages = snap.docs.map((d) => ({ id: d.id, ...d.data() }));
 
    // Return in chronological order (oldest first)
    return res.json(messages.toReversed().map(buildMessage));
  } catch (err) {
    log.error('conversations', 'Failed to fetch messages', {
      conversationId: req.params.id,
      error: err.message,
    });
    return res.status(500).json({ error: 'Internal server error' });
  }
});
 
// -- Send message --
router.post('/conversations/:id/messages', async (req, res) => {
  try {
    const uniqueId = req.auth.uniqueId;
    const body = req.body;
    if (!body) return res.status(400).json({ error: 'Invalid body' });
 
    const conversationId = req.params.id;
    const messageId = generateId();
    const timestamp = now();
    const type = body.type || 'TEXT';
    const senderId = uniqueId;
    const senderName = (body.senderName || '').slice(0, MAX_SENDER_NAME_LENGTH);
    const text = (body.text || '').slice(0, MAX_TEXT_LENGTH);
 
    // Validate message type
    if (!VALID_MESSAGE_TYPES.includes(type)) {
      return res.status(400).json({ error: 'Invalid message type' });
    }
 
    // Validate imageUrls count
    const imageUrls = Array.isArray(body.imageUrls)
      ? body.imageUrls.slice(0, MAX_IMAGES_PER_MESSAGE)
      : [];
 
    log.info('conversations', 'Sending message', { conversationId, senderId, type });
 
    // Build preview text for lastMessage
    let previewText = text;
    if (type === 'IMAGE') previewText = '[Image]';
    else if (type === 'STICKER') previewText = '[Sticker]';
    else if (type === 'ROOM_INVITE') previewText = '[Room Invite]';
 
    // Read conversation to get participant list and group info
    const convSnap = await db.doc(`conversations/${conversationId}`).get();
    if (!convSnap.exists) return res.status(404).json({ error: 'Conversation not found' });
    const convDoc = convSnap.data();
    if (!convDoc) return res.status(500).json({ error: 'Corrupted conversation data' });
 
    const participantIds = convDoc.participantIds || [];
    if (!participantIds.includes(senderId)) {
      return res.status(403).json({ error: 'Not a participant of this conversation' });
    }
    const recipientIds = participantIds.filter((pid) => pid !== senderId);
    const isGroup = !!convDoc.isGroup;
    const groupName = convDoc.groupName || null;
 
    const msgData = {
      senderId,
      senderName,
      text,
      type,
      imageUrls,
      stickerUrl: body.stickerUrl || null,
      roomInviteId: body.roomInviteId || null,
      roomInviteName: body.roomInviteName || null,
      replyToId: body.replyToMessageId || null,
      replyToText: body.replyToText || null,
      replyToSenderName: body.replyToSenderName || null,
      reactions: {},
      isRecalled: false,
      isHidden: false,
      hiddenBy: null,
      editCount: 0,
      editedAt: null,
      createdAt: timestamp,
    };
 
    // Batch: write message + update conversation lastMessage + increment unread counts
    const lastMessage = { text: previewText, senderId, senderName, type, createdAt: timestamp };
    const batch = db.batch();
 
    batch.set(db.doc(`conversations/${conversationId}/messages/${messageId}`), msgData);
    batch.set(
      db.doc(`conversations/${conversationId}`),
      {
        lastMessage,
        lastMessageAt: timestamp,
      },
      { merge: true },
    );
 
    // Increment unread counts for all recipients (set+merge in case doc doesn't exist yet)
    for (const pid of recipientIds) {
      batch.set(
        db.doc(`conversations/${conversationId}/userSettings/${pid}`),
        {
          unreadCount: FieldValue.increment(1),
        },
        { merge: true },
      );
    }
 
    await batch.commit();
 
    // Un-hide conversation for all recipients (fire-and-forget)
    Promise.all(
      recipientIds.map((pid) =>
        db
          .doc(`conversations/${conversationId}/userSettings/${pid}`)
          .set({ isHidden: false }, { merge: true }),
      ),
    ).catch((err) =>
      log.error('conversations', 'Failed to un-hide for recipients', {
        conversationId,
        error: err.message,
      }),
    );
 
    // FCM notifications + RTDB broadcast (fire-and-forget)
    const recipients = recipientIds.map((id) => ({ userId: id }));
    sendMessageNotifications(
      conversationId,
      senderId,
      senderName,
      previewText,
      type,
      recipients,
      isGroup,
      groupName,
    ).catch((err) =>
      log.error('conversations', 'Failed to send notifications', {
        conversationId,
        error: err.message,
      }),
    );
 
    broadcastToConversation(conversationId, { type: 'new_message' }).catch((err) =>
      log.error('conversations', 'Failed to broadcast event', {
        conversationId,
        error: err.message,
      }),
    );
 
    return res.json(
      buildMessage({ id: messageId, ...msgData, replyToMessageId: msgData.replyToId }),
    );
  } catch (err) {
    log.error('conversations', 'Failed to send message', {
      conversationId: req.params.id,
      senderId: req.auth?.uniqueId,
      error: err.message,
    });
    return res.status(500).json({ error: 'Internal server error' });
  }
});
 
module.exports = router;