-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathpush-notification.service.ts
More file actions
238 lines (209 loc) · 6.79 KB
/
Copy pathpush-notification.service.ts
File metadata and controls
238 lines (209 loc) · 6.79 KB
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
import type {
Device,
DeviceIdentity,
IdentitiesOnDevice,
} from "@prisma/client";
import { createJwtToken } from "@/utils/jwt";
import logger from "@/utils/logger";
import { prisma } from "@/utils/prisma";
import { createApnsService, type ApnsPushService } from "./apns-push.service";
import type {
NotificationPayload,
NotificationPayloadWithJWTToken,
} from "./notifications-types";
type IdentityOnDeviceWithRelations = IdentitiesOnDevice & {
device: Device;
identity: DeviceIdentity;
};
type SendNotificationResult = {
success: boolean;
shouldCleanup?: boolean;
};
export class PushNotificationService {
private apnsService: ApnsPushService | null;
constructor() {
this.apnsService = createApnsService();
}
async sendPushNotificationToXmtpId(args: {
xmtpId: string;
notification: NotificationPayload;
}): Promise<SendNotificationResult> {
const { xmtpId, notification } = args;
// Right now one xmtp id = one device, we can adapt in the future
const device = await prisma.device.findFirst({
where: {
identities: {
some: {
identity: { xmtpId: xmtpId },
},
},
},
include: {
identities: {
include: {
identity: true,
},
},
},
});
if (!device) {
return { success: false, shouldCleanup: false };
}
// Find the identity that matches the notification's inboxId to get the xmtpInstallationId
const targetIdentityOnDevice = device.identities.find(
(identityOnDevice) =>
identityOnDevice.identity.xmtpId === notification.inboxId,
);
if (!targetIdentityOnDevice) {
logger.error(
{ deviceId: device.id, inboxId: notification.inboxId },
"No matching identity found on device for notification",
);
return { success: false };
}
if (!targetIdentityOnDevice.xmtpInstallationId) {
logger.error(
{ deviceId: device.id, inboxId: notification.inboxId },
"No XMTP installation ID found for identity",
);
return { success: false };
}
// Create the IdentityOnDeviceWithRelations object
const identityOnDevice: IdentityOnDeviceWithRelations = {
...targetIdentityOnDevice,
device,
};
return this.sendPushNotification({
identityOnDevice,
notification,
});
}
async _sendPushNotification(args: {
identityOnDevice: IdentityOnDeviceWithRelations;
notification: NotificationPayload;
}): Promise<SendNotificationResult> {
const { identityOnDevice, notification } = args;
const device = identityOnDevice.device;
if (!identityOnDevice.xmtpInstallationId) {
logger.error(
{ deviceId: device.id, identityId: identityOnDevice.identityId },
"No XMTP installation ID found for identity on device",
);
return { success: false };
}
const xmtpInstallationId = identityOnDevice.xmtpInstallationId;
// V1 notifications always have inboxId
if (!notification.inboxId) {
logger.error(
{ deviceId: device.id },
"Missing inboxId for v1 notification",
);
return { success: false };
}
// We add an JWT token to the notification payload to be used by the client
// So the notification extension is able to communicate with our backend (App Attest not supported in extensions so we can't call authenticate)
const apiJWT = await createJwtToken({
inboxId: notification.inboxId,
xmtpInstallationId,
expirationTime: "72h",
metadata: {
notificationExtensionOnly: true,
},
});
const notificationWithJWTToken = {
...notification,
apiJWT,
} as NotificationPayloadWithJWTToken;
// Check if device has too many push failures
if (device.pushFailures > 10) {
logger.warn(
`Device ${device.id} has too many push failures (${device.pushFailures}). Skipping notification.`,
);
return { success: false };
}
// Determine which push service to use
const pushTokenType = device.pushTokenType;
let result: { success: boolean; error?: string };
switch (pushTokenType) {
case "apns":
if (!this.apnsService) {
logger.error("APNS service not configured");
return { success: false };
}
result = await this.apnsService.sendPushNotification({
device,
notification: notificationWithJWTToken,
});
break;
case "fcm":
logger.error(
`FCM push notifications are not supported. Only APNS is supported for device ${device.id}`,
);
return { success: false };
default:
logger.warn(`Invalid push token type for device ${device.id}`);
return { success: false };
}
// Handle the result
if (result.success) {
await this.updateLastPushSuccess(device.id);
return { success: true };
} else {
await this.incrementPushFailures(device.id);
// Check if we should cleanup the device
const shouldCleanup =
result.error === "DeviceNotRegistered" ||
result.error === "BadDeviceToken";
return { success: false, shouldCleanup };
}
}
async sendPushNotification(args: {
identityOnDevice: IdentityOnDeviceWithRelations;
notification: NotificationPayload;
}): Promise<SendNotificationResult> {
try {
const notificationResult = await this._sendPushNotification(args);
return notificationResult;
} catch (error) {
logger.error(
{ error, deviceId: args.identityOnDevice.device.id },
"Unexpected error sending push",
);
await this.incrementPushFailures(args.identityOnDevice.device.id);
return { success: false };
}
}
private async incrementPushFailures(deviceId: string) {
try {
await prisma.device.update({
where: { id: deviceId },
data: { pushFailures: { increment: 1 } },
});
logger.info(`Incremented push failures for device ${deviceId}`);
} catch (error) {
logger.error({ error, deviceId }, "Failed to increment push failures");
}
}
private async updateLastPushSuccess(deviceId: string) {
try {
await prisma.device.update({
where: { id: deviceId },
data: {
lastPushSuccessAt: new Date(),
pushFailures: 0, // Reset failures on successful push
},
});
logger.info(`Updated last push success for device ${deviceId}`);
} catch (error) {
logger.error({ error, deviceId }, "Failed to update last push success");
}
}
}
// Singleton instance
let pushNotificationService: PushNotificationService | null = null;
export function getPushNotificationService(): PushNotificationService {
if (!pushNotificationService) {
pushNotificationService = new PushNotificationService();
}
return pushNotificationService;
}