|
1 | | -import { Injectable, Logger } from '@nestjs/common'; |
2 | | -import { DatabaseService } from '../common/database/database.service'; |
3 | | -import webpush, { WebPushError } from 'web-push'; |
4 | | -import admin from 'firebase-admin'; |
5 | | -import { Subscription } from '@prisma/client'; |
6 | | -import { Prisma } from '@prisma/client'; |
7 | | - |
8 | | -// VAPID keys should be set via environment variables |
9 | | -if (process.env.NEXT_PUBLIC_VAPID_PUBLIC_KEY && process.env.VAPID_PRIVATE_KEY && process.env.VAPID_EMAIL) { |
10 | | - webpush.setVapidDetails( |
11 | | - `mailto:${process.env.VAPID_EMAIL}`, |
12 | | - process.env.NEXT_PUBLIC_VAPID_PUBLIC_KEY, |
13 | | - process.env.VAPID_PRIVATE_KEY |
14 | | - ); |
15 | | -} |
16 | | - |
17 | | -// Initialize Firebase Admin if not already initialized |
18 | | -if (!admin.apps.length && process.env.FIREBASE_SERVICE_ACCOUNT_KEY) { |
19 | | - try { |
20 | | - admin.initializeApp({ |
21 | | - credential: admin.credential.cert(JSON.parse(process.env.FIREBASE_SERVICE_ACCOUNT_KEY)), |
22 | | - }); |
23 | | - } catch (error) { |
24 | | - console.error('Failed to initialize Firebase Admin:', error); |
25 | | - } |
26 | | -} |
27 | | - |
28 | | -export interface NotificationPayload { |
29 | | - title: string; |
30 | | - body: string; |
31 | | - url: string; |
32 | | - icon?: string; |
33 | | - badge?: string; |
34 | | -} |
35 | | - |
36 | | -export interface WebSubscription extends Subscription { |
37 | | - type: 'web'; |
38 | | - keys: Prisma.JsonValue; |
39 | | -} |
40 | | - |
41 | | -export interface FcmSubscription extends Subscription { |
42 | | - type: 'fcm'; |
43 | | - keys: Prisma.JsonValue; |
44 | | -} |
45 | | - |
46 | | -export type SubscriptionRecord = WebSubscription | FcmSubscription; |
47 | | - |
48 | | -@Injectable() |
49 | | -export class NotificationsService { |
50 | | - private readonly logger = new Logger(NotificationsService.name); |
51 | | - |
52 | | - constructor(private readonly db: DatabaseService) {} |
53 | | - |
54 | | - async sendNotification(subscription: SubscriptionRecord, notificationPayload: NotificationPayload): Promise<void> { |
55 | | - try { |
56 | | - this.logger.log('Sending notification to subscription:', subscription); |
57 | | - |
58 | | - if (subscription.type === 'web') { |
59 | | - if (!isWebKeys(subscription.keys)) { |
60 | | - throw new Error(`Invalid keys for web subscription: ${JSON.stringify(subscription.keys)}`); |
61 | | - } |
62 | | - await webpush.sendNotification( |
63 | | - { |
64 | | - endpoint: subscription.endpoint, |
65 | | - keys: { |
66 | | - auth: (subscription.keys as any).auth, |
67 | | - p256dh: (subscription.keys as any).p256dh, |
68 | | - }, |
69 | | - }, |
70 | | - JSON.stringify({ |
71 | | - title: notificationPayload.title, |
72 | | - body: notificationPayload.body, |
73 | | - icon: notificationPayload.icon, |
74 | | - badge: notificationPayload.badge, |
75 | | - url: notificationPayload.url, |
76 | | - }) |
77 | | - ); |
78 | | - } else if (subscription.type === 'fcm') { |
79 | | - if (!isFcmKeys(subscription.keys)) { |
80 | | - throw new Error(`Invalid keys for FCM subscription: ${JSON.stringify(subscription.keys)}`); |
81 | | - } |
82 | | - const fcmMessage = { |
83 | | - notification: { |
84 | | - title: notificationPayload.title, |
85 | | - body: notificationPayload.body, |
86 | | - }, |
87 | | - data: { |
88 | | - url: notificationPayload.url, |
89 | | - }, |
90 | | - token: (subscription.keys as any).token, |
91 | | - android: { |
92 | | - notification: { |
93 | | - sound: 'notification', |
94 | | - }, |
95 | | - }, |
96 | | - apns: { |
97 | | - payload: { |
98 | | - aps: { |
99 | | - sound: 'notification', |
100 | | - }, |
101 | | - }, |
102 | | - }, |
103 | | - }; |
104 | | - const response = await admin.messaging().send(fcmMessage); |
105 | | - this.logger.log('FCM response:', response); |
106 | | - } |
107 | | - } catch (error: any) { |
108 | | - if (subscription.type === 'web' && error instanceof WebPushError) { |
109 | | - if (error.statusCode === 410) { |
110 | | - await this.db.subscription.delete({ where: { id: subscription.id } }); |
111 | | - this.logger.log(`Subscription with id ${subscription.id} removed due to expiration.`); |
112 | | - } else { |
113 | | - this.logger.log( |
114 | | - `Failed to send notification to subscription id ${subscription.id}:`, |
115 | | - error.statusCode, |
116 | | - error.body |
117 | | - ); |
118 | | - } |
119 | | - } else if (subscription.type === 'fcm') { |
120 | | - if ( |
121 | | - error.code === 'messaging/invalid-registration-token' || |
122 | | - error.code === 'messaging/registration-token-not-registered' |
123 | | - ) { |
124 | | - await this.db.subscription.delete({ where: { id: subscription.id } }); |
125 | | - this.logger.log(`Removed invalid FCM token for subscription id ${subscription.id}.`); |
126 | | - } else { |
127 | | - this.logger.log(`Failed to send FCM notification to subscription id ${subscription.id}:`, error); |
128 | | - } |
129 | | - } else { |
130 | | - this.logger.log(`An error occurred while sending notification to subscription id ${subscription.id}:`, error); |
131 | | - } |
132 | | - } |
133 | | - } |
134 | | -} |
135 | | - |
136 | | -export function isWebKeys(keys: Prisma.JsonValue): keys is { auth: string; p256dh: string } { |
137 | | - return ( |
138 | | - typeof keys === 'object' && |
139 | | - keys !== null && |
140 | | - 'auth' in keys && |
141 | | - 'p256dh' in keys && |
142 | | - typeof (keys as any).auth === 'string' && |
143 | | - typeof (keys as any).p256dh === 'string' |
144 | | - ); |
145 | | -} |
146 | | - |
147 | | -export function isFcmKeys(keys: Prisma.JsonValue): keys is { token: string } { |
148 | | - return typeof keys === 'object' && keys !== null && 'token' in keys && typeof (keys as any).token === 'string'; |
149 | | -} |
| 1 | +// DEPRECATED: Use NotificationsService from 'src/notifications/notifications.service' |
| 2 | +// This file remains temporarily to avoid breaking existing imports. Update imports to: |
| 3 | +// import { NotificationsService } from '../notifications/notifications.service'; |
| 4 | +// Then delete this file. |
| 5 | + |
| 6 | +export * from '../notifications/notifications.service'; |
| 7 | +export * from '../notifications/interfaces/notification-payload.interface'; |
| 8 | +export * from '../notifications/interfaces/subscription-record.interface'; |
0 commit comments