Spaces:
Running
Running
Download apps/api/dist/queue/notification.processor.js from Benaah/MicProtocol: direct link, hf CLI and curl.
- Browser
- Download file 11.6 kB
-
https://huggingface.co/spaces/Benaah/MicProtocol/resolve/main/apps/api/dist/queue/notification.processor.js
- Command line
-
hf download hf://spaces/Benaah/MicProtocol/apps/api/dist/queue/notification.processor.js
-
curl -L -o notification.processor.js https://huggingface.co/spaces/Benaah/MicProtocol/resolve/main/apps/api/dist/queue/notification.processor.js
11.6 kB
| ; | |
| 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 |