-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathsafari-client.ts
More file actions
334 lines (282 loc) · 8.92 KB
/
safari-client.ts
File metadata and controls
334 lines (282 loc) · 8.92 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
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
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
import Client from './client';
import {randomUUID} from '../helpers';
import {asperaSdk} from '../../index';
/**
* Enum defining different types of Safari extension events.
*/
enum SafariExtensionEventType {
Monitor = 'Monitor',
Ping = 'Ping',
Request = 'Request'
}
/**
* Interface representing a JSON-RPC request object.
*/
interface JSONRPCRequest {
id: string;
jsonrpc: string;
method: string;
params: any;
}
/**
* Interface representing a JSON-RPC response object.
*/
interface JSONRPCResponse {
id: string;
jsonrpc: string;
result?: any;
error?: any;
}
/**
* Interface representing a promise executor used in a promise.
*/
export interface PromiseExecutor {
resolve: (value: any) => void;
reject: (error: any) => void;
}
/**
* Global keep alive timeout to prevent recursion.
*/
let keepAliveTimeout: ReturnType<typeof setTimeout>;
/**
* Handles communication with the Safari extension using JSON-RPC over custom events.
*/
export class SafariClient implements Client {
private keepAliveInterval = 1000;
private promiseExecutors: Map<string, PromiseExecutor>;
private lastPing: number|null = null;
private lastPong: number|null = null;
private safariExtensionEnabled = false;
private subscribedTransferActivity = false;
/**
* Initializes the SafariExtensionHandler instance.
* Sets up the promise executor map and starts listening to extension events.
*/
constructor() {
this.promiseExecutors = new Map();
this.listenResponseEvents();
this.listenTransferActivityEvents();
this.listenStatusEvents();
this.listenClientStatusEvents();
this.listenPongEvents();
if (keepAliveTimeout) {
clearTimeout(keepAliveTimeout);
}
this.keepAlive();
}
/**
* Sends a JSON-RPC request to the Safari extension.
* @param method The method name to invoke on the extension.
* @param payload Optional payload for the request.
* @returns A Promise that resolves with the response from the extension.
*/
request = (method: string, payload: any = {}): Promise<any> => {
return this.dispatchPromiseEvent(
SafariExtensionEventType.Request,
method,
payload
);
};
/**
* Monitors transfer activity.
* @returns A Promise that resolves with the response from the extension.
*/
public monitorTransferActivity(): Promise<unknown> {
const dispatchMonitorEvent = (): Promise<unknown> => {
const promise = this.dispatchPromiseEvent(
SafariExtensionEventType.Monitor,
'subscribe_transfer_activity',
[asperaSdk.globals.appId]
);
return promise.then(() => {
this.subscribedTransferActivity = true;
});
};
if (this.safariExtensionEnabled) {
return dispatchMonitorEvent();
}
return new Promise((resolve, reject) => {
const extensionInterval = setInterval(() => {
if (!this.safariExtensionEnabled) {
return;
}
dispatchMonitorEvent()
.then(resolve)
.catch(reject);
clearInterval(extensionInterval);
}, 1000);
});
}
/**
* Builds a JSON-RPC request object with a unique identifier.
* @param method The method name to invoke on the extension.
* @param payload Optional parameters for the method.
* @returns The constructed JSON-RPC request object.
*/
private buildRPCRequest(method: string, payload?: unknown): JSONRPCRequest {
return {
jsonrpc: '2.0',
method,
params: payload,
id: randomUUID()
};
}
/**
* Dispatches a custom event to the document to communicate with the Safari extension.
* @param type The type of Safari extension event to dispatch.
* @param request Optional JSON-RPC request payload to send with the event.
*/
private dispatchEvent(type: SafariExtensionEventType, request?: JSONRPCRequest) {
const payload = {
detail: request ?? {}
};
document.dispatchEvent(new CustomEvent(`AsperaDesktop.${type}`, payload));
}
/**
* Dispatches a custom event to the document to communicate with the Safari extension.
* @param type The type of Safari extension event to dispatch.
* @param method The method name to invoke on the extension.
* @param payload Optional parameters for the method.
*/
private dispatchPromiseEvent(type: SafariExtensionEventType, method: string, payload?: unknown): Promise<any> {
const request = this.buildRPCRequest(method, payload);
return new Promise<any>((resolve, reject) => {
if (this.safariExtensionEnabled) {
this.promiseExecutors.set(request.id, {resolve, reject});
this.dispatchEvent(type, request);
} else {
console.warn('The Safari extension is disabled or unresponsive (dispatch event)');
console.warn(`Failed event: ${JSON.stringify(request)}`);
reject('The Safari extension is disabled or unresponsive (dispatch event)');
}
});
}
/**
* Handles incoming JSON-RPC responses from the Safari extension.
* Resolves or rejects promises based on the response.
* @param response The JSON-RPC response object received from the extension.
*/
private handleResponse(response: JSONRPCResponse) {
const requestId = response.id;
const executor = this.promiseExecutors.get(requestId);
if (!executor) {
console.warn(`Unable to find a promise executor for ${requestId}`);
console.warn(`Response: ${response}`);
return;
}
this.promiseExecutors.delete(requestId);
if (response.error) {
executor.reject(response.error);
return;
}
executor.resolve(response.result);
}
/**
* Listens for 'AsperaDesktop.Response' events.
*/
private listenResponseEvents() {
document.addEventListener('AsperaDesktop.Response', (event: CustomEvent<JSONRPCResponse>) => {
if (!event.detail) {
return;
}
this.handleResponse(event.detail);
});
}
/**
* Listens for 'AsperaDesktop.TransferActivity' events.
*/
private listenTransferActivityEvents() {
document.addEventListener('AsperaDesktop.TransferActivity', (event: any) => {
if (!event.detail) {
return;
}
asperaSdk.activityTracking.handleTransferActivity(event.detail);
});
}
/**
* Listens for 'AsperaDesktop.Status' events.
*/
private listenStatusEvents() {
document.addEventListener('AsperaDesktop.Status', (event: any) => {
if (!event.detail) {
return;
}
asperaSdk.activityTracking.handleWebSocketEvents(event.detail);
});
}
/**
* Listens for 'isAppAlive' events. This was introduced in version 1.0.9.
*/
private listenClientStatusEvents() {
document.addEventListener('isAppAlive', (event: any) => {
if (!event.detail?.running) {
return;
}
asperaSdk.activityTracking.handleClientEvents(event.detail.running);
});
}
/**
* Listens for 'AsperaDesktop.Pong' events.
*/
private listenPongEvents() {
document.addEventListener('AsperaDesktop.Pong', () => {
this.lastPong = Date.now();
this.safariExtensionStatusChanged(true);
});
}
/**
* Sends a keep alive ping according to the defined interval.
*/
private keepAlive() {
this.lastPing = Date.now();
this.dispatchEvent(SafariExtensionEventType.Ping);
keepAliveTimeout = setTimeout(() => {
this.keepAlive();
}, this.keepAliveInterval);
}
/**
* Listens for Safari extension status changes.
* If the extension was disabled and enabled again after initializing the SDK, it
* will call 'monitorTransferActivity' to resume transfer activities.
*/
private safariExtensionStatusChanged(isEnabled: boolean) {
if (isEnabled === this.safariExtensionEnabled) {
return;
}
this.safariExtensionEnabled = isEnabled;
if (isEnabled) {
if (this.subscribedTransferActivity) {
const resumeTransferActivity = () => {
this.monitorTransferActivity()
.catch(() => {
console.error('Failed to resume transfer activity, will try again in 1s');
setTimeout(() => {
resumeTransferActivity();
}, 1000);
});
};
resumeTransferActivity();
}
} else {
asperaSdk.activityTracking.handleWebSocketEvents('CLOSED');
this.promiseExecutors.forEach((promiseExecutor) => {
promiseExecutor.reject('The Safari extension is disabled or unresponsive (extension status)');
});
this.promiseExecutors.clear();
}
asperaSdk.activityTracking.handleSafariExtensionEvents(this.safariExtensionEnabled ? 'ENABLED' : 'DISABLED');
}
/**
* Checks if the last pong received was longer than the max interval.
*/
private checkSafariExtensionStatus() {
const pingPongDiff = this.lastPong - this.lastPing;
if (this.lastPong == null || pingPongDiff < 0 || pingPongDiff > 500) {
this.safariExtensionStatusChanged(false);
}
}
}
export const safariClient = new SafariClient();
export default {
safariClient
};