Spaces:
Running
Running
File size: 11,578 Bytes
9f29339 | 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 | "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 __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
return c > 3 && r && Object.defineProperty(target, key, r), r;
};
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;
};
})();
var __metadata = (this && this.__metadata) || function (k, v) {
if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
var NotificationProcessor_1;
Object.defineProperty(exports, "__esModule", { value: true });
exports.NotificationProcessor = void 0;
const bullmq_1 = require("@nestjs/bullmq");
const common_1 = require("@nestjs/common");
const config_1 = require("@nestjs/config");
const webpush = __importStar(require("web-push"));
const shared_types_1 = require("@micprotocol/shared-types");
const prisma_service_1 = require("../prisma/prisma.service");
const events_gateway_1 = require("../websocket/events.gateway");
const fcm_service_1 = require("../notifications/fcm.service");
const channel_dispatcher_service_1 = require("../notifications/channels/channel-dispatcher.service");
const TYPE_TO_PREF_COLUMN = {
[shared_types_1.NotificationType.BOOKING]: "bookingReminders",
[shared_types_1.NotificationType.EPISODE]: "bookingReminders",
[shared_types_1.NotificationType.ASSET]: "assetReminders",
[shared_types_1.NotificationType.OUTREACH]: "outreachReplies",
[shared_types_1.NotificationType.MESSAGE]: "outreachReplies",
[shared_types_1.NotificationType.NETWORK_BOOKING]: "networkRequests",
[shared_types_1.NotificationType.VERIFICATION]: "networkRequests",
[shared_types_1.NotificationType.BADGE]: "networkRequests",
[shared_types_1.NotificationType.TRUST_SCORE]: "networkRequests",
[shared_types_1.NotificationType.RECORDING]: "recordingAlerts",
[shared_types_1.NotificationType.CLIP]: "recordingAlerts",
[shared_types_1.NotificationType.EXPORT]: "recordingAlerts",
[shared_types_1.NotificationType.BILLING]: "billingAlerts",
[shared_types_1.NotificationType.SYSTEM]: null,
[shared_types_1.NotificationType.ALERT]: null,
[shared_types_1.NotificationType.DIGEST]: null,
};
let NotificationProcessor = NotificationProcessor_1 = class NotificationProcessor extends bullmq_1.WorkerHost {
prisma;
eventsGateway;
fcmService;
configService;
channelDispatcher;
logger = new common_1.Logger(NotificationProcessor_1.name);
constructor(prisma, eventsGateway, fcmService, configService, channelDispatcher) {
super();
this.prisma = prisma;
this.eventsGateway = eventsGateway;
this.fcmService = fcmService;
this.configService = configService;
this.channelDispatcher = channelDispatcher;
this.initializeVapid();
}
initializeVapid() {
const vapidPublicKey = this.configService.get("VAPID_PUBLIC_KEY");
const vapidPrivateKey = this.configService.get("VAPID_PRIVATE_KEY");
const vapidSubject = this.configService.get("VAPID_SUBJECT") || "mailto:admin@localhost";
if (vapidPublicKey && vapidPrivateKey) {
webpush.setVapidDetails(vapidSubject, vapidPublicKey, vapidPrivateKey);
this.logger.log("Web push VAPID details configured");
}
else {
this.logger.warn("Web push VAPID keys not configured. Web push notifications will be disabled. " +
"Set VAPID_PUBLIC_KEY, VAPID_PRIVATE_KEY, and VAPID_SUBJECT to enable.");
}
}
async process(job) {
const { userId, type, title, message, link, metadata, podcastId, skipPreferenceCheck } = job.data;
this.logger.log(`Processing notification job ${job.id}: type=${type} user=${userId}`);
if (!skipPreferenceCheck) {
const prefColumn = TYPE_TO_PREF_COLUMN[type];
if (prefColumn) {
const prefs = await this.prisma.userNotificationPreferences.findUnique({
where: { userId },
select: { [prefColumn]: true, pushEnabled: true },
});
if (prefs) {
const categoryEnabled = prefs[prefColumn];
if (!categoryEnabled) {
this.logger.debug(`User ${userId} has disabled ${prefColumn}; skipping notification type=${type}`);
return { delivered: false, reason: `preference_${prefColumn}_disabled` };
}
}
}
}
const notification = await this.prisma.notification.create({
data: {
userId,
type: type,
title,
message,
link: link || null,
metadata: (metadata || {}),
},
});
this.logger.debug(`Notification persisted: id=${notification.id} type=${type} user=${userId}`);
const wsPayload = {
id: notification.id,
type,
title,
message,
link: link || null,
metadata: metadata || {},
createdAt: notification.createdAt.toISOString(),
};
this.eventsGateway.emitToUser(userId, "notification:created", wsPayload);
if (podcastId) {
this.eventsGateway.notifyInAppNotification(podcastId, {
...wsPayload,
userId,
});
}
try {
const prefs = await this.prisma.userNotificationPreferences.findUnique({
where: { userId },
select: { pushEnabled: true, pushToken: true, pushProvider: true },
});
const data = {
type,
...(link && { link }),
};
if (metadata) {
for (const [key, value] of Object.entries(metadata)) {
data[key] = String(value);
}
}
if (prefs?.pushEnabled && prefs?.pushToken) {
if (prefs.pushProvider === "firebase" && this.fcmService.isConfigured()) {
await this.fcmService.sendPushNotification(prefs.pushToken, {
title,
body: message,
data,
});
}
else if (prefs.pushProvider === "expo") {
await this.sendExpoPush(prefs.pushToken, title, message, data);
}
}
if (prefs?.pushEnabled) {
await this.sendWebPush(userId, title, message, data, link);
}
}
catch (err) {
this.logger.warn(`Failed to send push to user ${userId}:`, err);
}
try {
await this.channelDispatcher.dispatch(userId, {
userId,
type,
title,
message,
link: link || null,
metadata: metadata || {},
});
}
catch (err) {
this.logger.warn(`Channel dispatch failed for user ${userId}:`, err);
}
return { delivered: true, notificationId: notification.id };
}
async sendExpoPush(token, title, body, data) {
try {
const response = await fetch("https://exp.host/--/api/v2/push/send", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
to: token,
title,
body,
data,
}),
});
if (!response.ok) {
this.logger.warn(`Expo push failed: ${response.status} ${response.statusText}`);
return;
}
const result = (await response.json());
if (result.data && result.data.status === "error") {
this.logger.warn(`Expo push error: ${result.data.message}`);
}
else {
this.logger.debug(`Expo push sent to token ${token.slice(0, 12)}...`);
}
}
catch (err) {
this.logger.warn("Failed to send Expo push", err);
}
}
async sendWebPush(userId, title, body, data, link) {
const subscriptions = await this.prisma.webPushSubscription.findMany({
where: { userId },
select: { endpoint: true, p256dhKey: true, authKey: true },
});
if (subscriptions.length === 0) {
return;
}
const payload = JSON.stringify({
title,
body,
data,
...(link && { link }),
timestamp: Date.now(),
});
for (const sub of subscriptions) {
try {
await webpush.sendNotification({
endpoint: sub.endpoint,
keys: {
p256dh: sub.p256dhKey,
auth: sub.authKey,
},
}, payload);
this.logger.debug(`Web push sent to subscription ${sub.endpoint.slice(0, 30)}...`);
}
catch (err) {
this.logger.warn(`Web push failed for subscription ${sub.endpoint.slice(0, 30)}...`, err);
}
}
}
};
exports.NotificationProcessor = NotificationProcessor;
exports.NotificationProcessor = NotificationProcessor = NotificationProcessor_1 = __decorate([
(0, bullmq_1.Processor)("notifications", {
concurrency: 5,
}),
__metadata("design:paramtypes", [prisma_service_1.PrismaService,
events_gateway_1.EventsGateway,
fcm_service_1.FcmService,
config_1.ConfigService,
channel_dispatcher_service_1.ChannelDispatcherService])
], NotificationProcessor);
//# sourceMappingURL=notification.processor.js.map |