Closer/functions/dist/questions/onMessageWritten.js

111 lines
5.5 KiB
JavaScript

"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || (function () {
var ownKeys = function(o) {
ownKeys = Object.getOwnPropertyNames || function (o) {
var ar = [];
for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
return ar;
};
return ownKeys(o);
};
return function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
__setModuleDefault(result, mod);
return result;
};
})();
Object.defineProperty(exports, "__esModule", { value: true });
exports.onMessageWritten = void 0;
const admin = __importStar(require("firebase-admin"));
const firestore_1 = require("firebase-functions/v2/firestore");
const quietHours_1 = require("../notifications/quietHours");
const push_1 = require("../notifications/push");
const idempotency_1 = require("../notifications/idempotency");
const log_1 = require("../log");
/**
* Firestore trigger that notifies the other partner when a chat message is
* sent in a conversation (the couple chat or a per-question discussion).
*
* Path: couples/{coupleId}/conversations/{conversationId}/messages/{messageId}
*
* Respects the recipient's `notifChatMessage` preference (default: enabled).
*/
exports.onMessageWritten = (0, firestore_1.onDocumentCreated)('couples/{coupleId}/conversations/{conversationId}/messages/{messageId}', async (event) => {
var _a, _b, _c, _d;
const { coupleId, conversationId, messageId } = event.params;
const snap = event.data;
if (!snap)
return;
const db = admin.firestore();
const messageData = snap.data();
const authorId = typeof messageData.authorUserId === 'string' ? messageData.authorUserId : null;
if (!authorId) {
log_1.logger.warn(`[onMessageWritten] no authorUserId on message ${messageId}`);
return;
}
const coupleDoc = await db.collection('couples').doc(coupleId).get();
if (!coupleDoc.exists) {
log_1.logger.warn(`[onMessageWritten] couple ${coupleId} not found`);
return;
}
const userIds = ((_b = (_a = coupleDoc.data()) === null || _a === void 0 ? void 0 : _a.userIds) !== null && _b !== void 0 ? _b : []);
const partnerId = userIds.find((uid) => uid !== authorId);
if (!partnerId) {
log_1.logger.warn(`[onMessageWritten] no partner found for couple ${coupleId}`);
return;
}
const partnerUserDoc = await db.collection('users').doc(partnerId).get();
const partnerData = partnerUserDoc.data();
// Respect the partner's notification preference (opt-out; default is enabled).
if ((partnerData === null || partnerData === void 0 ? void 0 : partnerData.notifChatMessage) === false) {
log_1.logger.log(`[onMessageWritten] partner ${partnerId} has chat notifications off`);
return;
}
// M-001: honor the recipient's quiet-hours window ("no notifications" promise). Fail-open.
if ((0, quietHours_1.recipientInQuietHours)(partnerData)) {
log_1.logger.log(`[onMessageWritten] partner ${partnerId} is in quiet hours — suppressing`);
return;
}
// Dedupe redelivery of this message create (at-least-once). messageId is unique per message.
if (!(await (0, idempotency_1.claimOnce)((0, idempotency_1.notifMark)(db, coupleId, `msg-${messageId}`)))) {
log_1.logger.log(`[onMessageWritten] already notified for message ${messageId}; skipping`);
return;
}
// displayName is E2EE in users/{uid}, so the server can't read it for the OS-rendered push (the
// app shows the real name in-app). photoUrl stays plaintext, so the avatar is still sent.
const authorDoc = await db.collection('users').doc(authorId).get();
const authorPhotoUrl = (_d = (_c = authorDoc.data()) === null || _c === void 0 ? void 0 : _c.photoUrl) !== null && _d !== void 0 ? _d : '';
const res = await (0, push_1.sendPushToUser)(db, admin.messaging(), partnerId, {
notification: {
title: 'Your partner sent a message',
body: 'Tap to read and reply.',
},
data: Object.assign({ type: 'chat_message', couple_id: coupleId, conversation_id: conversationId }, (authorPhotoUrl ? { sender_avatar_url: authorPhotoUrl } : {})),
// E-OBS: backgrounded delivery on the Chat/partner channel, not the FCM fallback channel.
android: { notification: { channelId: 'partner_activity' } },
}, partnerData);
if (res.sent === 0 && res.failed === 0) {
log_1.logger.log(`[onMessageWritten] no FCM tokens for partner ${partnerId}`);
return;
}
log_1.logger.log(`[onMessageWritten] notified partner ${partnerId} for conversation ${conversationId} in couple ${coupleId}`);
});
//# sourceMappingURL=onMessageWritten.js.map