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 | 3x 3x 3x 3x 3x 3x 3x 27x 27x 15x 3x 16x 16x 16x 2x 14x 1x 13x 13x 13x 13x 12x 11x 11x 11x 11x 11x 11x 11x 11x 11x 6x 6x 6x 6x 5x 1x 1x 11x 11x 1x 1x 3x 26x 26x 26x 26x 26x 26x 8x 18x 18x 18x 16x 2x 2x 2x 2x 2x 14x 14x 14x 14x 14x 14x 14x 11x 11x 11x 11x 5x 4x 1x 1x 14x 14x 2x 2x 3x | /**
* Room routes — invite sending and seat request creation (FCM push required).
*
* POST /api/rooms/:roomId/invites/send -> Send invite (FCM push to invitee)
* POST /api/rooms/:roomId/seat-requests -> Create seat request (FCM push to room owner)
*/
const router = require('express').Router();
const { db, rtdb } = require('../utils/firebase');
const { generateId, now } = require('../utils/helpers');
const { sendFcmToTokens, cleanupInvalidTokens } = require('../utils/fcm');
const log = require('../utils/log');
const MAX_USER_NAME_LENGTH = 50;
const MAX_SEAT_INDEX = 20;
// --- Helpers ---
/** Broadcast a room event via RTDB. */
async function broadcastToRoom(roomId, data) {
try {
await rtdb.ref(`rooms/${roomId}/events/lastEvent`).set({
type: data.type,
ts: Date.now(),
...(data.userId ? { userId: data.userId } : {}),
});
} catch (err) {
log.error('rooms', 'Failed to write RTDB event', { roomId, error: err.message });
}
}
// --- Route registration ---
// -- Send invite --
router.post('/rooms/:roomId/invites/send', async (req, res) => {
try {
const body = req.body;
if (!body?.userId || !body?.invitedBy) {
return res.status(400).json({ error: 'userId and invitedBy required' });
}
if (req.auth.uniqueId !== body.invitedBy) {
return res.status(403).json({ error: 'Cannot send invite on behalf of another user' });
}
const roomId = req.params.roomId;
const inviteeId = body.userId;
log.info('rooms', 'Sending room invite', { roomId, inviteeId, invitedBy: body.invitedBy });
const roomSnap = await db.doc(`rooms/${roomId}`).get();
if (!roomSnap.exists) return res.status(404).json({ error: 'Room not found' });
const room = roomSnap.data();
// Update pendingInvites on the room doc (matches Android client field name)
const pendingInvites = room.pendingInvites || {};
pendingInvites[inviteeId] = {
invitedBy: body.invitedBy,
invitedAt: now(),
};
await db.doc(`rooms/${roomId}`).update({ pendingInvites });
// Send FCM push to invitee
try {
const inviteeSnap = await db.doc(`users/${inviteeId}`).get();
const inviteeDoc = inviteeSnap.exists ? inviteeSnap.data() : null;
const tokens = inviteeDoc?.fcmTokens || [];
if (tokens.length > 0) {
const roomName = room.name || 'a room';
// Look up inviter's display name
const inviterSnap = await db.doc(`users/${body.invitedBy}`).get();
const inviterName = inviterSnap.exists
? inviterSnap.data().displayName || 'Someone'
: 'Someone';
const invalidTokens = await sendFcmToTokens(tokens, {
type: 'ROOM_INVITE',
roomId,
roomName,
invitedBy: body.invitedBy,
inviterName,
});
if (invalidTokens.length > 0) {
await cleanupInvalidTokens(invalidTokens, inviteeId);
}
}
} catch (err) {
log.error('rooms', 'Failed to send invite FCM', { roomId, inviteeId, error: err.message });
}
await broadcastToRoom(roomId, { type: 'room_updated' });
return res.json({ success: true });
} catch (err) {
log.error('rooms', 'Send invite failed', { roomId: req.params.roomId, error: err.message });
return res.status(500).json({ error: 'Internal server error' });
}
});
// -- Create seat request --
router.post('/rooms/:roomId/seat-requests', async (req, res) => {
try {
const uniqueId = req.auth.uniqueId;
const body = req.body;
const seatIndex = body?.seatIndex;
const userName = (body?.userName || '').slice(0, MAX_USER_NAME_LENGTH);
if (
seatIndex === null ||
seatIndex === undefined ||
typeof seatIndex !== 'number' ||
!Number.isInteger(seatIndex) ||
seatIndex < 0 ||
seatIndex > MAX_SEAT_INDEX
) {
return res.status(400).json({ error: 'Valid seatIndex required (0-20)' });
}
const roomId = req.params.roomId;
log.info('rooms', 'Creating seat request', { roomId, userId: uniqueId, seatIndex });
// Check for existing pending request
const existingSnap = await db
.collection(`rooms/${roomId}/seatRequests`)
.where('userId', '==', uniqueId)
.where('status', '==', 'PENDING')
.limit(1)
.get();
if (!existingSnap.empty) {
const existingDoc = existingSnap.docs[0];
const reqId = existingDoc.id;
await db.doc(`rooms/${roomId}/seatRequests/${reqId}`).update({
seatIndex,
createdAt: now(),
});
await broadcastToRoom(roomId, { type: 'seat_request_updated' });
return res.json({ requestId: reqId });
}
const reqId = generateId();
const timestamp = now();
await db.doc(`rooms/${roomId}/seatRequests/${reqId}`).set({
requestId: reqId,
userId: uniqueId,
userName: userName || '',
seatIndex,
status: 'PENDING',
resolvedBy: null,
createdAt: timestamp,
resolvedAt: null,
});
// Send FCM push to room owner
try {
const roomSnap = await db.doc(`rooms/${roomId}`).get();
const room = roomSnap.exists ? roomSnap.data() : null;
if (room?.ownerId) {
const ownerSnap = await db.doc(`users/${room.ownerId}`).get();
const ownerDoc = ownerSnap.exists ? ownerSnap.data() : null;
const tokens = ownerDoc?.fcmTokens || [];
if (tokens.length > 0) {
const invalidTokens = await sendFcmToTokens(tokens, {
type: 'SEAT_REQUEST',
roomId,
roomName: room.name || 'a room',
requesterId: uniqueId,
requesterName: userName || '',
seatIndex: String(seatIndex),
});
if (invalidTokens.length > 0) {
await cleanupInvalidTokens(invalidTokens, room.ownerId);
}
}
}
} catch (err) {
log.error('rooms', 'Failed to send seat request FCM', {
roomId,
userId: uniqueId,
error: err.message,
});
}
await broadcastToRoom(roomId, { type: 'seat_request_updated' });
return res.json({ requestId: reqId });
} catch (err) {
log.error('rooms', 'Create seat request failed', {
roomId: req.params.roomId,
userId: req.auth?.uniqueId,
error: err.message,
});
return res.status(500).json({ error: 'Internal server error' });
}
});
module.exports = router;
|