-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathPushNotificationModule.ts
More file actions
178 lines (138 loc) · 6.85 KB
/
PushNotificationModule.ts
File metadata and controls
178 lines (138 loc) · 6.85 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
import { sleep } from "@js-soft/ts-utils";
import { RuntimeServices, SyncEverythingResponse } from "@nmshd/runtime";
import { AppRuntimeErrors } from "../AppRuntimeErrors.js";
import { AccountSelectedEvent, ExternalEventReceivedEvent, RemoteNotificationEvent, RemoteNotificationRegistrationEvent } from "../events/index.js";
import { AppRuntimeModule, AppRuntimeModuleConfiguration } from "./AppRuntimeModule.js";
enum BackboneEventName {
DatawalletModificationsCreated = "DatawalletModificationsCreated",
ExternalEventCreated = "ExternalEventCreated"
}
interface IBackboneEventContent {
devicePushIdentifier: string;
eventName: BackboneEventName;
sentAt: string;
payload: any;
}
export interface PushNotificationModuleConfig extends AppRuntimeModuleConfiguration {}
export class PushNotificationModule extends AppRuntimeModule<PushNotificationModuleConfig> {
public async init(): Promise<void> {
// Nothing to do here
}
public start(): void {
this.subscribeToEvent(RemoteNotificationEvent, this.handleRemoteNotification.bind(this));
this.subscribeToEvent(RemoteNotificationRegistrationEvent, this.handleTokenRegistration.bind(this));
this.subscribeToEvent(AccountSelectedEvent, this.handleAccountSelected.bind(this));
}
private async handleRemoteNotification(event: RemoteNotificationEvent) {
this.logger.trace("PushNotificationModule.handleRemoteNotification", event);
const notification = event.notification;
const content = notification.content as IBackboneEventContent;
const accRef = await this.runtime.multiAccountController.getAccountReferenceForDevicePushIdentifier(content.devicePushIdentifier);
try {
const services = await this.runtime.getServices(accRef);
switch (content.eventName) {
case BackboneEventName.DatawalletModificationsCreated:
const walletResult = await services.transportServices.account.syncDatawallet();
if (walletResult.isError) {
this.logger.error(walletResult);
return;
}
break;
case BackboneEventName.ExternalEventCreated:
const result = await this.syncEverythingUntilHasChanges(services);
if (result) this.runtime.eventBus.publish(new ExternalEventReceivedEvent(accRef, result));
break;
default:
break;
}
} catch (e) {
this.logger.error(e);
}
}
private async syncEverythingUntilHasChanges(services: RuntimeServices): Promise<SyncEverythingResponse | undefined> {
const hasChanges = (value: SyncEverythingResponse): boolean =>
Object.values(value)
.filter((v) => Array.isArray(v))
.some((array) => array.length > 0);
const syncResult = await services.transportServices.account.syncEverything();
if (syncResult.isError) {
this.logger.error(syncResult.error);
} else if (hasChanges(syncResult.value)) {
return syncResult.value;
}
let currentAttempt = 1;
const maxAttempts = 6;
while (currentAttempt <= maxAttempts) {
this.logger.info(`No changes found in sync attempt ${currentAttempt}. Retrying...`);
currentAttempt++;
await sleep(250 * Math.ceil(currentAttempt / 2));
const syncResult = await services.transportServices.account.syncEverything();
if (syncResult.isError) {
this.logger.error(syncResult.error);
continue;
}
if (hasChanges(syncResult.value)) return syncResult.value;
}
return;
}
private async handleTokenRegistration(event: RemoteNotificationRegistrationEvent) {
try {
this.logger.trace("PushNotificationModule.handleTokenRegistration", event);
for (const session of this.runtime.getSessions()) {
await this.registerPushTokenForLocalAccount(session.account.address!, event.token);
}
} catch (e) {
this.logger.error(e);
}
}
private async handleAccountSelected(event: AccountSelectedEvent) {
this.logger.trace("PushNotificationModule.handleAccountSelected", event);
const tokenResult = await this.runtime.notificationAccess.getPushToken();
if (tokenResult.isError) {
this.logger.error(tokenResult.error);
return;
}
await this.registerPushTokenForLocalAccount(event.data.address, tokenResult.value);
}
private async registerPushTokenForLocalAccount(address: string, token: string): Promise<void> {
if (!token) {
this.logger.info("The registered token was empty. This might be the case if you did not allow push notifications.");
return;
}
const services = await this.runtime.getServices(address);
const deviceResult = await services.transportServices.account.getDeviceInfo();
if (deviceResult.isError) {
this.logger.error(deviceResult.error);
const error = AppRuntimeErrors.modules.pushNotificationModule.tokenRegistrationNotPossible("No device for this account found", deviceResult.error);
this.logger.error(error);
throw error;
}
const appId = this.runtime.config.applicationId;
const handle = token;
const platform = this.runtime.config.pushService;
const environment = this.runtime.config.applePushEnvironment;
if (platform === "none") return;
const result = await services.transportServices.account.registerPushNotificationToken({
platform,
handle,
appId,
environment: environment
});
if (result.isError) {
this.logger.error(result.error);
const error = AppRuntimeErrors.modules.pushNotificationModule.tokenRegistrationNotPossible(result.error.message, result.error);
this.logger.error(error);
throw error;
}
this.logger.info(
`PushNotificationModule.registerPushTokenForLocalAccount: Token ${handle} registered for account ${address} on platform ${platform}${
environment ? ` (${environment})` : ""
} and appId ${appId}`
);
await this.registerPushIdentifierForAccount(address, result.value.devicePushIdentifier);
}
private async registerPushIdentifierForAccount(address: string, devicePushIdentifier: string): Promise<void> {
this.logger.trace("PushNotificationModule.registerPushIdentifierForAccount", { address, pushIdentifier: devicePushIdentifier });
await this.runtime.multiAccountController.updatePushIdentifierForAccount(address, devicePushIdentifier);
}
}