-
-
Notifications
You must be signed in to change notification settings - Fork 97
Expand file tree
/
Copy pathsendspin-connection.ts
More file actions
531 lines (468 loc) · 14.7 KB
/
Copy pathsendspin-connection.ts
File metadata and controls
531 lines (468 loc) · 14.7 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
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
/**
* Sendspin Connection
*
* Provides Sendspin connections with automatic fallback:
* 1. If in remote mode, uses the sendspin DataChannel through existing WebRTC
* 2. Falls back to authenticated proxy WebSocket through the webserver
*/
import api from "@/plugins/api";
import { authManager } from "@/plugins/auth";
import { store } from "@/plugins/store";
const OriginalWebSocket = window.WebSocket;
/**
* Build the WebSocket URL for the sendspin proxy endpoint.
*/
function getSendspinProxyUrl(): string {
const baseUrl = api.baseUrl;
if (!baseUrl) return "";
const wsScheme = baseUrl.startsWith("https") ? "wss" : "ws";
const urlWithoutScheme = baseUrl.replace(/^https?:\/\//, "");
return `${wsScheme}://${urlWithoutScheme}/sendspin`;
}
/**
* Create a proxy WebSocket connection.
* In ingress mode, no auth message is needed (HA handles auth via headers).
* Otherwise, sends auth message with token and client_id.
*/
function createProxyWebSocket(): Promise<WebSocket | null> {
const url = getSendspinProxyUrl();
const isIngress = store.isIngressSession;
return new Promise((resolve) => {
if (!url) {
resolve(null);
return;
}
// In non-ingress mode, we need a token
const token = authManager.getToken();
if (!isIngress && !token) {
console.error("[Sendspin] No auth token available for proxy connection");
resolve(null);
return;
}
console.debug("[Sendspin] Connecting to proxy WebSocket:", url);
let ws: WebSocket;
try {
ws = new OriginalWebSocket(url);
} catch (error) {
console.error("[Sendspin] Failed to create proxy WebSocket:", error);
resolve(null);
return;
}
let ready = false;
ws.onopen = () => {
if (isIngress) {
// In ingress mode, no auth message needed - connection is ready immediately
console.debug("[Sendspin] Proxy WebSocket connected (ingress mode)");
ready = true;
resolve(ws);
} else {
// Send auth message with token
const clientId =
window.localStorage.getItem("sendspin_webplayer_id") || "";
console.debug("[Sendspin] Sending auth to proxy");
ws.send(JSON.stringify({ type: "auth", token, client_id: clientId }));
}
};
ws.onmessage = () => {
if (!ready && !isIngress) {
ready = true;
console.debug("[Sendspin] Proxy WebSocket authenticated and ready");
resolve(ws);
}
};
ws.onerror = (error) => {
if (!ready) {
console.error("[Sendspin] Proxy WebSocket error:", error);
resolve(null);
}
};
ws.onclose = (event) => {
if (!ready) {
console.debug(
"[Sendspin] Proxy WebSocket closed before ready:",
event.code,
event.reason,
);
resolve(null);
}
};
setTimeout(() => {
if (!ready) {
console.debug("[Sendspin] Proxy WebSocket connection timed out");
ws.close();
resolve(null);
}
}, 10000);
});
}
/**
* WebSocket-like interface for sendspin-js compatibility.
*/
export interface SendspinWebSocketBridge {
send: (data: string | ArrayBuffer) => void;
close: (code?: number, reason?: string) => void;
readonly readyState: number;
onopen: ((event: Event) => void) | null;
onmessage: ((event: MessageEvent) => void) | null;
onerror: ((event: Event) => void) | null;
onclose: ((event: CloseEvent) => void) | null;
readonly CONNECTING: 0;
readonly OPEN: 1;
readonly CLOSING: 2;
readonly CLOSED: 3;
}
function wrapWebSocket(ws: WebSocket): SendspinWebSocketBridge {
const bridge: SendspinWebSocketBridge = {
send: (data: string | ArrayBuffer) => {
if (ws.readyState === WebSocket.OPEN) {
ws.send(data);
}
},
close: (code?: number, reason?: string) => {
ws.close(code, reason);
},
get readyState() {
return ws.readyState;
},
onopen: null,
onmessage: null,
onerror: null,
onclose: null,
CONNECTING: 0,
OPEN: 1,
CLOSING: 2,
CLOSED: 3,
};
ws.onopen = (event) => {
if (bridge.onopen) bridge.onopen(event);
};
ws.onmessage = (event) => {
if (bridge.onmessage) bridge.onmessage(event);
};
ws.onerror = (event) => {
if (bridge.onerror) bridge.onerror(event);
};
ws.onclose = (event) => {
if (bridge.onclose) bridge.onclose(event);
};
return bridge;
}
/**
* Wraps an RTCDataChannel to match the SendspinWebSocketBridge interface.
*/
function wrapDataChannel(channel: RTCDataChannel): SendspinWebSocketBridge {
const bridge: SendspinWebSocketBridge = {
send: (data: string | ArrayBuffer) => {
if (channel.readyState === "open") {
if (typeof data === "string") {
channel.send(data);
} else {
channel.send(data);
}
}
},
close: (_code?: number, _reason?: string) => {
channel.close();
},
get readyState() {
switch (channel.readyState) {
case "connecting":
return 0;
case "open":
return 1;
case "closing":
return 2;
case "closed":
default:
return 3;
}
},
onopen: null,
onmessage: null,
onerror: null,
onclose: null,
CONNECTING: 0,
OPEN: 1,
CLOSING: 2,
CLOSED: 3,
};
channel.onopen = () => {
if (bridge.onopen) bridge.onopen(new Event("open"));
};
channel.onmessage = (event) => {
if (bridge.onmessage) bridge.onmessage(event);
};
channel.onerror = () => {
if (bridge.onerror) bridge.onerror(new Event("error"));
};
channel.onclose = () => {
if (bridge.onclose) bridge.onclose(new CloseEvent("close"));
};
return bridge;
}
let pendingBridge: SendspinWebSocketBridge | null = null;
let _isDirectConnection = false;
/**
* Returns true if the current sendspin connection is direct (proxy WebSocket),
* false if it's through remote access (DataChannel).
*/
export function isDirectConnection(): boolean {
return _isDirectConnection;
}
/**
* Reset the connection state when API connection is lost.
*/
export function resetSendspinConnection(): void {
console.debug("[SendspinConnection] Resetting connection state");
if (pendingBridge) {
try {
pendingBridge.close();
} catch {
// Ignore
}
pendingBridge = null;
}
_isDirectConnection = false;
}
/**
* Creates a Sendspin connection.
* Priority: 1) DataChannel (remote mode), 2) Proxy WebSocket
*/
export async function createSendspinConnection(): Promise<SendspinWebSocketBridge> {
console.debug("[Sendspin] Creating connection...");
if (api.isRemoteConnection.value) {
console.debug("[Sendspin] In remote mode, trying DataChannel...");
const channel = await api.createSendspinDataChannel();
if (channel) {
console.info("[Sendspin] Using remote access DataChannel");
_isDirectConnection = false;
return wrapDataChannel(channel);
}
}
console.debug("[Sendspin] Trying proxy WebSocket...");
const proxyWs = await createProxyWebSocket();
if (proxyWs) {
console.info("[Sendspin] Using proxy WebSocket connection");
_isDirectConnection = true;
return wrapWebSocket(proxyWs);
}
throw new Error("Failed to establish Sendspin connection");
}
/**
* WebSocket-like object that sendspin-js talks to.
*
* sendspin-js opens its socket with `new WebSocket(baseUrl + "/sendspin")`, which
* the interceptor routes here. On the initial connect a bridge is pre-staged by
* prepareSendspinSession(); on the library's own auto-reconnect no bridge is
* staged, so this wrapper builds a fresh one on demand. Either way the bridge is
* attached on a later microtask — after sendspin-js has wired its handlers and
* armed its reconnect bookkeeping — and a failed build is surfaced as a close so
* the library's exponential-backoff reconnect keeps running instead of stalling.
*/
class SendspinWebSocketWrapper {
binaryType: BinaryType = "arraybuffer";
private bridge: SendspinWebSocketBridge | null = null;
private closed = false;
private openFired = false;
private closeFired = false;
private sendQueue: (string | ArrayBuffer)[] = [];
private _onopen: ((event: Event) => void) | null = null;
private _onmessage: ((event: MessageEvent) => void) | null = null;
private _onerror: ((event: Event) => void) | null = null;
private _onclose: ((event: CloseEvent) => void) | null = null;
constructor(_url: string | URL, _protocols?: string | string[]) {
const staged = pendingBridge;
pendingBridge = null;
if (staged) {
console.debug("[Sendspin] Interceptor: using pre-staged connection");
} else {
console.debug(
"[Sendspin] Interceptor: no staged connection, building one for reconnect",
);
}
// Defer attach so sendspin-js finishes wiring its on* handlers (and sets
// shouldReconnect) before any event fires; otherwise the open/close would be
// delivered to handlers that are not registered yet and the library's
// reconnect loop would never re-arm.
const bridgePromise = staged
? Promise.resolve(staged)
: createSendspinConnection();
bridgePromise
.then((bridge) => this.attachBridge(bridge))
.catch((error) => {
console.error(
"[Sendspin] Interceptor: failed to build connection:",
error,
);
// Surface as a close so sendspin-js reschedules its next reconnect attempt.
this.fireClose();
});
}
send(data: string | ArrayBuffer | Blob): void {
if (data instanceof Blob) {
data.arrayBuffer().then((buffer) => this.sendRaw(buffer));
} else {
this.sendRaw(data);
}
}
close(code?: number, reason?: string): void {
this.closed = true;
if (this.bridge) {
this.bridge.close(code, reason);
}
// If a bridge is still being built, attachBridge() closes it on arrival.
}
get readyState(): number {
if (this.bridge) return this.bridge.readyState;
return this.closed ? 3 /* CLOSED */ : 0 /* CONNECTING */;
}
get bufferedAmount(): number {
return 0;
}
get extensions(): string {
return "";
}
get protocol(): string {
return "";
}
get url(): string {
return "";
}
set onopen(handler: ((event: Event) => void) | null) {
this._onopen = handler;
}
get onopen(): ((event: Event) => void) | null {
return this._onopen;
}
set onmessage(handler: ((event: MessageEvent) => void) | null) {
this._onmessage = handler;
}
get onmessage(): ((event: MessageEvent) => void) | null {
return this._onmessage;
}
set onerror(handler: ((event: Event) => void) | null) {
this._onerror = handler;
}
get onerror(): ((event: Event) => void) | null {
return this._onerror;
}
set onclose(handler: ((event: CloseEvent) => void) | null) {
this._onclose = handler;
}
get onclose(): ((event: CloseEvent) => void) | null {
return this._onclose;
}
addEventListener(
type: string,
listener: EventListenerOrEventListenerObject,
): void {
if (typeof listener !== "function") return;
if (type === "open") this._onopen = listener as (event: Event) => void;
else if (type === "message")
this._onmessage = listener as (event: MessageEvent) => void;
else if (type === "error")
this._onerror = listener as (event: Event) => void;
else if (type === "close")
this._onclose = listener as (event: CloseEvent) => void;
}
removeEventListener(
_type: string,
_listener: EventListenerOrEventListenerObject,
): void {
// No-op
}
dispatchEvent(_event: Event): boolean {
return false;
}
static readonly CONNECTING = 0;
static readonly OPEN = 1;
static readonly CLOSING = 2;
static readonly CLOSED = 3;
private sendRaw(data: string | ArrayBuffer): void {
if (this.closed) return;
if (this.bridge) {
this.bridge.send(data);
} else {
this.sendQueue.push(data);
}
}
private attachBridge(bridge: SendspinWebSocketBridge): void {
if (this.closed) {
// close() was called while the bridge was still being built; discard it.
console.debug(
"[Sendspin] Interceptor: connection ready after close(), discarding",
);
try {
bridge.close();
} catch {
// Ignore
}
return;
}
this.bridge = bridge;
bridge.onopen = () => this.fireOpen();
bridge.onmessage = (event) => this._onmessage?.(event);
bridge.onerror = (event) => this._onerror?.(event);
bridge.onclose = (event) => this.fireClose(event);
// readyState now delegates to the live bridge, so queued sends go through.
for (const data of this.sendQueue) {
bridge.send(data);
}
this.sendQueue = [];
// createSendspinConnection() only resolves once the transport is open; if it
// closed in the gap before attach, surface that as a close rather than a
// (false) open so the handshake is not attempted on a dead socket.
if (bridge.readyState === bridge.OPEN) {
this.fireOpen();
} else {
console.debug("[Sendspin] Interceptor: connection closed before attach");
this.fireClose();
}
}
private fireOpen(): void {
if (this.openFired || this.closeFired || this.closed) return;
this.openFired = true;
this._onopen?.(new Event("open"));
}
private fireClose(event?: CloseEvent): void {
if (this.closeFired) return;
this.closeFired = true;
this._onclose?.(event ?? new CloseEvent("close"));
}
}
let interceptorInstalled = false;
/**
* Install WebSocket interceptor for /sendspin URLs. Call once at app startup.
*/
export function installSendspinInterceptor(): void {
if (interceptorInstalled) return;
(window as unknown as { WebSocket: unknown }).WebSocket = function (
url: string | URL,
protocols?: string | string[],
) {
const urlStr = url.toString();
if (urlStr.includes("/sendspin")) {
console.debug("[SendspinInterceptor] Intercepting WebSocket to:", urlStr);
return new SendspinWebSocketWrapper(url, protocols);
}
return new OriginalWebSocket(url, protocols);
} as unknown as typeof WebSocket;
(window.WebSocket as unknown as { CONNECTING: number }).CONNECTING =
OriginalWebSocket.CONNECTING;
(window.WebSocket as unknown as { OPEN: number }).OPEN =
OriginalWebSocket.OPEN;
(window.WebSocket as unknown as { CLOSING: number }).CLOSING =
OriginalWebSocket.CLOSING;
(window.WebSocket as unknown as { CLOSED: number }).CLOSED =
OriginalWebSocket.CLOSED;
interceptorInstalled = true;
console.info("[SendspinInterceptor] Installed");
}
/**
* Prepare a session before creating a SendspinPlayer.
*/
export async function prepareSendspinSession(): Promise<void> {
console.debug("[SendspinConnection] Creating session...");
pendingBridge = await createSendspinConnection();
console.debug("[SendspinConnection] Session ready");
}