@caisual/kit 0.1.0 → 0.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/kit.d.ts +67 -0
- package/dist/kit.js +1374 -31
- package/dist/node.d.ts +75 -0
- package/dist/node.js +1930 -0
- package/dist/runtime.d.ts +106 -0
- package/dist/runtime.js +1458 -0
- package/dist/server.d.ts +57 -0
- package/dist/server.js +38 -0
- package/package.json +33 -6
package/dist/kit.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
// Caisual game kit v0.
|
|
1
|
+
// Caisual game kit v0.3.0
|
|
2
2
|
|
|
3
3
|
// src/errors.ts
|
|
4
4
|
function creaErrore(code, message) {
|
|
@@ -11,25 +11,19 @@ function codiceErrore(valore) {
|
|
|
11
11
|
return typeof valore === "object" && valore !== null && "code" in valore ? valore.code : null;
|
|
12
12
|
}
|
|
13
13
|
|
|
14
|
-
// src/
|
|
15
|
-
async function leggiJson(response) {
|
|
16
|
-
try {
|
|
17
|
-
return await response.json();
|
|
18
|
-
} catch {
|
|
19
|
-
throw creaErrore("internal_error", "The service returned an invalid response.");
|
|
20
|
-
}
|
|
21
|
-
}
|
|
14
|
+
// src/http.ts
|
|
22
15
|
async function leggiErrore(response) {
|
|
23
16
|
let corpo = {};
|
|
24
17
|
try {
|
|
25
18
|
corpo = await response.json();
|
|
26
19
|
} catch {
|
|
27
20
|
}
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
21
|
+
return creaErrore(
|
|
22
|
+
typeof corpo.error?.code === "string" ? corpo.error.code : response.status === 401 ? "invalid_ticket" : "internal_error",
|
|
23
|
+
typeof corpo.error?.message === "string" ? corpo.error.message : `The request failed with status ${response.status}.`
|
|
24
|
+
);
|
|
31
25
|
}
|
|
32
|
-
function
|
|
26
|
+
function creaRichiedente(origin, prefix, fetcher, biglietto) {
|
|
33
27
|
async function manda(path, metodo, ticket, corpo) {
|
|
34
28
|
const headers = new Headers({ Authorization: `Bearer ${ticket}` });
|
|
35
29
|
let body;
|
|
@@ -42,7 +36,7 @@ function creaClienteApi(appOrigin, fetcher, biglietto) {
|
|
|
42
36
|
}
|
|
43
37
|
}
|
|
44
38
|
try {
|
|
45
|
-
return await fetcher(new URL(
|
|
39
|
+
return await fetcher(new URL(prefix + path, origin), {
|
|
46
40
|
method: metodo,
|
|
47
41
|
headers,
|
|
48
42
|
body,
|
|
@@ -52,10 +46,10 @@ function creaClienteApi(appOrigin, fetcher, biglietto) {
|
|
|
52
46
|
throw erroreOffline();
|
|
53
47
|
}
|
|
54
48
|
}
|
|
55
|
-
async function richiesta(path, metodo, corpo) {
|
|
49
|
+
return async function richiesta(path, metodo, corpo, forzaRinnovo = false) {
|
|
56
50
|
let ticket;
|
|
57
51
|
try {
|
|
58
|
-
ticket = await biglietto.ottieni();
|
|
52
|
+
ticket = forzaRinnovo ? await biglietto.rinnova() : await biglietto.ottieni();
|
|
59
53
|
} catch {
|
|
60
54
|
throw erroreOffline();
|
|
61
55
|
}
|
|
@@ -69,8 +63,17 @@ function creaClienteApi(appOrigin, fetcher, biglietto) {
|
|
|
69
63
|
response = await manda(path, metodo, ticket, corpo);
|
|
70
64
|
}
|
|
71
65
|
if (!response.ok) throw await leggiErrore(response);
|
|
72
|
-
|
|
73
|
-
|
|
66
|
+
try {
|
|
67
|
+
return await response.json();
|
|
68
|
+
} catch {
|
|
69
|
+
throw creaErrore("internal_error", "The service returned an invalid response.");
|
|
70
|
+
}
|
|
71
|
+
};
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
// src/api.ts
|
|
75
|
+
function creaClienteApi(appOrigin, fetcher, biglietto) {
|
|
76
|
+
const richiesta = creaRichiedente(appOrigin, "/api/kit", fetcher, biglietto);
|
|
74
77
|
return {
|
|
75
78
|
me: () => richiesta("/me", "GET"),
|
|
76
79
|
saveSet: (key, value) => richiesta(`/saves/${encodeURIComponent(key)}`, "PUT", { value }),
|
|
@@ -135,6 +138,15 @@ function record(valore) {
|
|
|
135
138
|
function eTipo(valore, tipo) {
|
|
136
139
|
return record(valore)?.type === tipo;
|
|
137
140
|
}
|
|
141
|
+
function leggiOrigine(valore) {
|
|
142
|
+
if (typeof valore !== "string") return null;
|
|
143
|
+
try {
|
|
144
|
+
const url = new URL(valore);
|
|
145
|
+
return url.origin === valore && (url.protocol === "https:" || url.protocol === "http:") ? valore : null;
|
|
146
|
+
} catch {
|
|
147
|
+
return null;
|
|
148
|
+
}
|
|
149
|
+
}
|
|
138
150
|
function attendiHandshake(finestra, appOrigin, timeoutMs = 3e3) {
|
|
139
151
|
return new Promise((resolve) => {
|
|
140
152
|
let concluso = false;
|
|
@@ -159,7 +171,12 @@ function attendiHandshake(finestra, appOrigin, timeoutMs = 3e3) {
|
|
|
159
171
|
const porta = evento.ports[0];
|
|
160
172
|
if (typeof dati?.ticket !== "string" || porta === void 0) return;
|
|
161
173
|
porta.start();
|
|
162
|
-
termina({
|
|
174
|
+
termina({
|
|
175
|
+
ticket: dati.ticket,
|
|
176
|
+
live: leggiOrigine(dati.live),
|
|
177
|
+
invite: typeof dati.invite === "string" ? dati.invite : null,
|
|
178
|
+
porta
|
|
179
|
+
});
|
|
163
180
|
};
|
|
164
181
|
finestra.addEventListener("message", ascolta);
|
|
165
182
|
const scadenza = finestra.setTimeout(() => termina(null), timeoutMs);
|
|
@@ -180,7 +197,7 @@ function scadenzaJwt(ticket) {
|
|
|
180
197
|
return null;
|
|
181
198
|
}
|
|
182
199
|
}
|
|
183
|
-
function chiediBiglietto(porta, finestra, timeoutMs) {
|
|
200
|
+
function chiediBiglietto(porta, finestra, timeoutMs, aud) {
|
|
184
201
|
return new Promise((resolve, reject) => {
|
|
185
202
|
let concluso = false;
|
|
186
203
|
const termina = (ticket) => {
|
|
@@ -193,25 +210,26 @@ function chiediBiglietto(porta, finestra, timeoutMs) {
|
|
|
193
210
|
};
|
|
194
211
|
const ascolta = (evento) => {
|
|
195
212
|
const dati = record(evento.data);
|
|
196
|
-
|
|
213
|
+
const destinatario = dati?.aud === void 0 ? "portal" : dati.aud;
|
|
214
|
+
if (dati?.type === "caisual:ticket" && destinatario === aud && typeof dati.ticket === "string") {
|
|
197
215
|
termina(dati.ticket);
|
|
198
216
|
}
|
|
199
217
|
};
|
|
200
218
|
porta.addEventListener("message", ascolta);
|
|
201
219
|
const scadenza = finestra.setTimeout(() => termina(null), timeoutMs);
|
|
202
220
|
try {
|
|
203
|
-
porta.postMessage({ type: "caisual:ticket" });
|
|
221
|
+
porta.postMessage(aud === "live" ? { type: "caisual:ticket", aud: "live" } : { type: "caisual:ticket" });
|
|
204
222
|
} catch {
|
|
205
223
|
termina(null);
|
|
206
224
|
}
|
|
207
225
|
});
|
|
208
226
|
}
|
|
209
|
-
function creaGestoreBiglietto(ticketIniziale, porta, finestra, ora, timeoutMs = 3e3) {
|
|
227
|
+
function creaGestoreBiglietto(ticketIniziale, porta, finestra, ora, timeoutMs = 3e3, aud = "portal") {
|
|
210
228
|
let ticket = ticketIniziale;
|
|
211
229
|
let rinnovo = null;
|
|
212
230
|
const rinnova = () => {
|
|
213
231
|
if (rinnovo !== null) return rinnovo;
|
|
214
|
-
const richiesta = chiediBiglietto(porta, finestra, timeoutMs).then((nuovo) => {
|
|
232
|
+
const richiesta = chiediBiglietto(porta, finestra, timeoutMs, aud).then((nuovo) => {
|
|
215
233
|
ticket = nuovo;
|
|
216
234
|
return nuovo;
|
|
217
235
|
});
|
|
@@ -223,6 +241,7 @@ function creaGestoreBiglietto(ticketIniziale, porta, finestra, ora, timeoutMs =
|
|
|
223
241
|
};
|
|
224
242
|
return {
|
|
225
243
|
async ottieni() {
|
|
244
|
+
if (ticket === null) return rinnova();
|
|
226
245
|
const scadenza = scadenzaJwt(ticket);
|
|
227
246
|
return scadenza !== null && scadenza - ora() < 3e4 ? rinnova() : ticket;
|
|
228
247
|
},
|
|
@@ -230,6 +249,1303 @@ function creaGestoreBiglietto(ticketIniziale, porta, finestra, ora, timeoutMs =
|
|
|
230
249
|
};
|
|
231
250
|
}
|
|
232
251
|
|
|
252
|
+
// src/voce/index.ts
|
|
253
|
+
var SOGLIA_AUDIO = 0.02;
|
|
254
|
+
var DURATA_PARLANTE = 300;
|
|
255
|
+
var INTERVALLO_AUDIO = 200;
|
|
256
|
+
var DURATA_ZERO = 3e3;
|
|
257
|
+
var TIMEOUT_CONNESSIONE = 1e4;
|
|
258
|
+
var RITARDI_RICONNESSIONE = [1e3, 2e3, 4e3];
|
|
259
|
+
function limita(value) {
|
|
260
|
+
return Number.isNaN(value) ? 1 : Math.min(1, Math.max(0, value));
|
|
261
|
+
}
|
|
262
|
+
function dipendenzeReali(input) {
|
|
263
|
+
const globali = globalThis;
|
|
264
|
+
const AudioContextClass = globali.AudioContext ?? globali.webkitAudioContext;
|
|
265
|
+
if (typeof RTCPeerConnection === "undefined" || typeof MediaStream === "undefined" || AudioContextClass === void 0 || typeof navigator === "undefined" || navigator.mediaDevices?.getUserMedia === void 0 || typeof document === "undefined") return null;
|
|
266
|
+
return {
|
|
267
|
+
...input,
|
|
268
|
+
creaPeerConnection: (configuration) => new RTCPeerConnection(configuration),
|
|
269
|
+
getUserMedia: (constraints) => navigator.mediaDevices.getUserMedia(constraints),
|
|
270
|
+
creaAudioContext: () => new AudioContextClass(),
|
|
271
|
+
creaAudioElement: () => document.createElement("audio"),
|
|
272
|
+
creaMediaStream: (tracks) => new MediaStream(tracks)
|
|
273
|
+
};
|
|
274
|
+
}
|
|
275
|
+
var VoceClient = class {
|
|
276
|
+
constructor(contesto, timer, dipendenze) {
|
|
277
|
+
this.contesto = contesto;
|
|
278
|
+
this.modeCorrente = "none";
|
|
279
|
+
this.stateCorrente = "off";
|
|
280
|
+
this.mutedCorrente = false;
|
|
281
|
+
this.speakingCorrente = false;
|
|
282
|
+
this.roster = [];
|
|
283
|
+
this.gains = /* @__PURE__ */ new Map();
|
|
284
|
+
this.volumi = /* @__PURE__ */ new Map();
|
|
285
|
+
this.speakingPeers = /* @__PURE__ */ new Map();
|
|
286
|
+
this.ultimoAudio = /* @__PURE__ */ new Map();
|
|
287
|
+
this.zeroDa = /* @__PURE__ */ new Map();
|
|
288
|
+
this.timerZero = /* @__PURE__ */ new Map();
|
|
289
|
+
this.ascoltatoriPeers = /* @__PURE__ */ new Set();
|
|
290
|
+
this.ascoltatoriState = /* @__PURE__ */ new Set();
|
|
291
|
+
this.richieste = /* @__PURE__ */ new Map();
|
|
292
|
+
this.riproduzioni = /* @__PURE__ */ new Map();
|
|
293
|
+
this.sfuAttive = /* @__PURE__ */ new Map();
|
|
294
|
+
this.midGiocatori = /* @__PURE__ */ new Map();
|
|
295
|
+
this.mesh = /* @__PURE__ */ new Map();
|
|
296
|
+
this.stream = null;
|
|
297
|
+
this.mic = null;
|
|
298
|
+
this.audioContext = null;
|
|
299
|
+
this.analyser = null;
|
|
300
|
+
this.peerSfu = null;
|
|
301
|
+
this.sessioneSfu = null;
|
|
302
|
+
this.trasporto = null;
|
|
303
|
+
this.intervalloAudio = null;
|
|
304
|
+
this.timerConnessione = null;
|
|
305
|
+
this.cancellaAttesaConnessione = null;
|
|
306
|
+
this.timerRiconnessione = null;
|
|
307
|
+
this.ultimoAudioMic = Number.NEGATIVE_INFINITY;
|
|
308
|
+
this.sequenzaRichieste = 0;
|
|
309
|
+
this.generazione = 0;
|
|
310
|
+
this.tentativoRiconnessione = 0;
|
|
311
|
+
this.desiderata = false;
|
|
312
|
+
this.promessaIngresso = null;
|
|
313
|
+
this.negoziazione = Promise.resolve();
|
|
314
|
+
this.dipendenze = dipendenze ?? dipendenzeReali(timer);
|
|
315
|
+
}
|
|
316
|
+
get mode() {
|
|
317
|
+
return this.modeCorrente;
|
|
318
|
+
}
|
|
319
|
+
get state() {
|
|
320
|
+
return this.stateCorrente;
|
|
321
|
+
}
|
|
322
|
+
get muted() {
|
|
323
|
+
return this.mutedCorrente;
|
|
324
|
+
}
|
|
325
|
+
get speaking() {
|
|
326
|
+
return this.speakingCorrente;
|
|
327
|
+
}
|
|
328
|
+
get peers() {
|
|
329
|
+
return this.copiaPeers();
|
|
330
|
+
}
|
|
331
|
+
async join() {
|
|
332
|
+
if (this.stateCorrente === "on") return;
|
|
333
|
+
if (this.stateCorrente === "joining") {
|
|
334
|
+
if (this.promessaIngresso !== null) await this.promessaIngresso;
|
|
335
|
+
return;
|
|
336
|
+
}
|
|
337
|
+
if (this.stateCorrente === "reconnecting" && this.desiderata) return;
|
|
338
|
+
this.verificaIngresso();
|
|
339
|
+
this.desiderata = true;
|
|
340
|
+
this.tentativoRiconnessione = 0;
|
|
341
|
+
this.aggiornaState("joining");
|
|
342
|
+
const generazione = ++this.generazione;
|
|
343
|
+
const promessa = this.completaIngresso(generazione);
|
|
344
|
+
this.promessaIngresso = promessa;
|
|
345
|
+
try {
|
|
346
|
+
await promessa;
|
|
347
|
+
} finally {
|
|
348
|
+
if (this.promessaIngresso === promessa) this.promessaIngresso = null;
|
|
349
|
+
}
|
|
350
|
+
}
|
|
351
|
+
async completaIngresso(generazione) {
|
|
352
|
+
try {
|
|
353
|
+
await this.entra(generazione);
|
|
354
|
+
} catch (cause) {
|
|
355
|
+
if (generazione !== this.generazione) return;
|
|
356
|
+
this.desiderata = false;
|
|
357
|
+
this.chiudiRisorse();
|
|
358
|
+
this.aggiornaState("off");
|
|
359
|
+
throw this.mappaErrore(cause);
|
|
360
|
+
}
|
|
361
|
+
}
|
|
362
|
+
leave() {
|
|
363
|
+
const deveFermare = this.desiderata || this.stateCorrente !== "off";
|
|
364
|
+
this.desiderata = false;
|
|
365
|
+
this.generazione++;
|
|
366
|
+
this.fermaRiconnessione();
|
|
367
|
+
if (deveFermare && this.contesto.connessa()) {
|
|
368
|
+
void this.richiedi({ t: "voice", op: "stop" }).catch(() => void 0);
|
|
369
|
+
}
|
|
370
|
+
this.rifiutaRichieste(creaErrore("offline", "Voice has stopped."));
|
|
371
|
+
this.chiudiRisorse();
|
|
372
|
+
this.aggiornaState("off");
|
|
373
|
+
}
|
|
374
|
+
mute(muted = true) {
|
|
375
|
+
if (this.stateCorrente !== "on" || this.mic === null) {
|
|
376
|
+
throw creaErrore("not_publishing", "Join voice before changing mute.");
|
|
377
|
+
}
|
|
378
|
+
this.mutedCorrente = muted;
|
|
379
|
+
this.mic.enabled = !muted;
|
|
380
|
+
void this.richiedi({ t: "voice", op: "mute", muted }).catch(() => void 0);
|
|
381
|
+
}
|
|
382
|
+
setVolume(playerId, volume) {
|
|
383
|
+
const valore = limita(volume);
|
|
384
|
+
this.volumi.set(playerId, valore);
|
|
385
|
+
this.aggiornaGuadagno(playerId);
|
|
386
|
+
this.notificaPeers();
|
|
387
|
+
}
|
|
388
|
+
onPeers(listener) {
|
|
389
|
+
this.ascoltatoriPeers.add(listener);
|
|
390
|
+
return () => {
|
|
391
|
+
this.ascoltatoriPeers.delete(listener);
|
|
392
|
+
};
|
|
393
|
+
}
|
|
394
|
+
onState(listener) {
|
|
395
|
+
this.ascoltatoriState.add(listener);
|
|
396
|
+
return () => {
|
|
397
|
+
this.ascoltatoriState.delete(listener);
|
|
398
|
+
};
|
|
399
|
+
}
|
|
400
|
+
ricevi(message) {
|
|
401
|
+
if ("r" in message) {
|
|
402
|
+
const pending = this.richieste.get(message.r);
|
|
403
|
+
if (pending !== void 0) {
|
|
404
|
+
this.richieste.delete(message.r);
|
|
405
|
+
if ("error" in message) {
|
|
406
|
+
pending.reject(creaErrore(message.error.code, message.error.message));
|
|
407
|
+
} else pending.resolve(message);
|
|
408
|
+
}
|
|
409
|
+
return;
|
|
410
|
+
}
|
|
411
|
+
if (message.op === "roster") {
|
|
412
|
+
this.modeCorrente = message.mode;
|
|
413
|
+
this.roster = message.peers.map((peer) => ({ ...peer }));
|
|
414
|
+
for (const peer of this.roster) {
|
|
415
|
+
if (peer.muted) this.speakingPeers.set(peer.id, false);
|
|
416
|
+
}
|
|
417
|
+
this.pulisciPeerAssenti();
|
|
418
|
+
this.contesto.rosterPronto();
|
|
419
|
+
this.notificaPeers();
|
|
420
|
+
this.accodaRiconciliazione();
|
|
421
|
+
return;
|
|
422
|
+
}
|
|
423
|
+
if (message.op === "gain") {
|
|
424
|
+
for (const [playerId, gain] of Object.entries(message.gains)) {
|
|
425
|
+
this.gains.set(playerId, limita(gain));
|
|
426
|
+
this.aggiornaZero(playerId);
|
|
427
|
+
this.aggiornaGuadagno(playerId);
|
|
428
|
+
}
|
|
429
|
+
this.notificaPeers();
|
|
430
|
+
this.accodaRiconciliazione();
|
|
431
|
+
return;
|
|
432
|
+
}
|
|
433
|
+
if (message.op === "signal") void this.riceviSegnale(message.from, message.data);
|
|
434
|
+
}
|
|
435
|
+
giocatoriCambiati() {
|
|
436
|
+
const presenti = new Set(this.contesto.giocatori().map((player) => player.id));
|
|
437
|
+
for (const playerId of this.gains.keys()) {
|
|
438
|
+
if (presenti.has(playerId)) continue;
|
|
439
|
+
this.gains.delete(playerId);
|
|
440
|
+
this.zeroDa.delete(playerId);
|
|
441
|
+
const timer = this.timerZero.get(playerId);
|
|
442
|
+
if (timer !== void 0) this.dipendenze?.clearTimeout(timer);
|
|
443
|
+
this.timerZero.delete(playerId);
|
|
444
|
+
this.aggiornaGuadagno(playerId);
|
|
445
|
+
}
|
|
446
|
+
this.notificaPeers();
|
|
447
|
+
this.accodaRiconciliazione();
|
|
448
|
+
}
|
|
449
|
+
socketDisconnesso() {
|
|
450
|
+
this.sequenzaRichieste = 0;
|
|
451
|
+
this.rifiutaRichieste(creaErrore("offline", "The room is reconnecting."));
|
|
452
|
+
if (!this.desiderata) return;
|
|
453
|
+
this.generazione++;
|
|
454
|
+
this.chiudiRisorse();
|
|
455
|
+
this.tentativoRiconnessione = 0;
|
|
456
|
+
this.aggiornaState("reconnecting");
|
|
457
|
+
}
|
|
458
|
+
socketRiconnesso() {
|
|
459
|
+
this.sequenzaRichieste = 0;
|
|
460
|
+
if (this.desiderata && this.stateCorrente === "reconnecting") this.programmaRiconnessione();
|
|
461
|
+
}
|
|
462
|
+
termina() {
|
|
463
|
+
this.desiderata = false;
|
|
464
|
+
this.generazione++;
|
|
465
|
+
this.fermaRiconnessione();
|
|
466
|
+
this.rifiutaRichieste(creaErrore("offline", "The room connection ended."));
|
|
467
|
+
this.chiudiRisorse();
|
|
468
|
+
this.aggiornaState("off");
|
|
469
|
+
}
|
|
470
|
+
verificaIngresso() {
|
|
471
|
+
if (!this.contesto.connessa()) throw creaErrore("offline", "The room is not connected.");
|
|
472
|
+
if (this.modeCorrente === "none") {
|
|
473
|
+
throw creaErrore("voice_disabled", "Voice is disabled for this room.");
|
|
474
|
+
}
|
|
475
|
+
const you = this.contesto.giocatori().find((player) => player.id === this.contesto.you());
|
|
476
|
+
if (you?.role === "spectator") {
|
|
477
|
+
throw creaErrore("spectator", "Spectators cannot join voice.");
|
|
478
|
+
}
|
|
479
|
+
if (this.dipendenze === null) {
|
|
480
|
+
throw creaErrore("unsupported", "Voice is not supported in this browser.");
|
|
481
|
+
}
|
|
482
|
+
}
|
|
483
|
+
async entra(generazione) {
|
|
484
|
+
this.verificaIngresso();
|
|
485
|
+
const dipendenze = this.richiediDipendenze();
|
|
486
|
+
const audioContext = dipendenze.creaAudioContext();
|
|
487
|
+
this.audioContext = audioContext;
|
|
488
|
+
try {
|
|
489
|
+
await audioContext.resume();
|
|
490
|
+
} catch {
|
|
491
|
+
}
|
|
492
|
+
let stream;
|
|
493
|
+
try {
|
|
494
|
+
stream = await dipendenze.getUserMedia({ audio: true });
|
|
495
|
+
} catch (cause) {
|
|
496
|
+
if (this.permessoNegato(cause)) {
|
|
497
|
+
throw creaErrore("permission_denied", "Microphone permission was denied.");
|
|
498
|
+
}
|
|
499
|
+
throw creaErrore("voice_error", "The microphone could not be opened.");
|
|
500
|
+
}
|
|
501
|
+
try {
|
|
502
|
+
this.controllaGenerazione(generazione);
|
|
503
|
+
} catch (cause) {
|
|
504
|
+
for (const track of stream.getTracks()) track.stop();
|
|
505
|
+
throw cause;
|
|
506
|
+
}
|
|
507
|
+
const mic = stream.getAudioTracks()[0];
|
|
508
|
+
if (mic === void 0) throw creaErrore("voice_error", "The microphone has no audio track.");
|
|
509
|
+
this.stream = stream;
|
|
510
|
+
this.mic = mic;
|
|
511
|
+
mic.enabled = !this.mutedCorrente;
|
|
512
|
+
this.preparaAnalizzatore(stream);
|
|
513
|
+
const risposta = await this.richiedi({ t: "voice", op: "ice" });
|
|
514
|
+
this.controllaGenerazione(generazione);
|
|
515
|
+
if (risposta.op !== "ice") throw creaErrore("voice_error", "The voice service returned an invalid response.");
|
|
516
|
+
this.modeCorrente = risposta.mode;
|
|
517
|
+
if (risposta.mode === "none") throw creaErrore("voice_disabled", "Voice is disabled for this room.");
|
|
518
|
+
this.trasporto = risposta.transport;
|
|
519
|
+
if (risposta.transport === "sfu") {
|
|
520
|
+
await this.entraSfu(risposta.iceServers, generazione);
|
|
521
|
+
} else {
|
|
522
|
+
await this.richiedi({ t: "voice", op: "publish" });
|
|
523
|
+
}
|
|
524
|
+
if (this.mutedCorrente) await this.richiedi({ t: "voice", op: "mute", muted: true });
|
|
525
|
+
this.controllaGenerazione(generazione);
|
|
526
|
+
this.tentativoRiconnessione = 0;
|
|
527
|
+
this.aggiornaState("on");
|
|
528
|
+
this.avviaMisuraAudio();
|
|
529
|
+
for (const playerId of this.gains.keys()) this.aggiornaZero(playerId);
|
|
530
|
+
this.accodaRiconciliazione();
|
|
531
|
+
}
|
|
532
|
+
async entraSfu(iceServers, generazione) {
|
|
533
|
+
const pc = this.richiediDipendenze().creaPeerConnection({
|
|
534
|
+
iceServers,
|
|
535
|
+
bundlePolicy: "max-bundle"
|
|
536
|
+
});
|
|
537
|
+
this.peerSfu = pc;
|
|
538
|
+
pc.ontrack = (event) => {
|
|
539
|
+
const mid2 = event.transceiver.mid;
|
|
540
|
+
const playerId = mid2 === null ? void 0 : this.midGiocatori.get(mid2);
|
|
541
|
+
if (playerId !== void 0) this.collegaTraccia(playerId, event.track, event.receiver);
|
|
542
|
+
};
|
|
543
|
+
this.osservaCaduta(pc);
|
|
544
|
+
const transceiver = pc.addTransceiver(this.richiediMic(), { direction: "sendonly" });
|
|
545
|
+
const offer = await pc.createOffer();
|
|
546
|
+
await pc.setLocalDescription(offer);
|
|
547
|
+
this.controllaGenerazione(generazione);
|
|
548
|
+
const mid = transceiver.mid;
|
|
549
|
+
const sdp = pc.localDescription?.sdp;
|
|
550
|
+
if (mid === null || sdp === void 0) {
|
|
551
|
+
throw creaErrore("voice_error", "The voice connection could not create an offer.");
|
|
552
|
+
}
|
|
553
|
+
const risposta = await this.richiedi({ t: "voice", op: "session", sdp, mid });
|
|
554
|
+
if (risposta.op !== "session") {
|
|
555
|
+
throw creaErrore("voice_error", "The voice service returned an invalid response.");
|
|
556
|
+
}
|
|
557
|
+
this.sessioneSfu = risposta.session;
|
|
558
|
+
await pc.setRemoteDescription({ type: "answer", sdp: risposta.sdp });
|
|
559
|
+
await this.attendiConnessione(pc, generazione);
|
|
560
|
+
}
|
|
561
|
+
attendiConnessione(pc, generazione) {
|
|
562
|
+
if (pc.connectionState === "connected") return Promise.resolve();
|
|
563
|
+
const dipendenze = this.richiediDipendenze();
|
|
564
|
+
return new Promise((resolve, reject) => {
|
|
565
|
+
const pulisci = () => {
|
|
566
|
+
pc.removeEventListener("connectionstatechange", cambiata);
|
|
567
|
+
if (this.timerConnessione !== null) dipendenze.clearTimeout(this.timerConnessione);
|
|
568
|
+
this.timerConnessione = null;
|
|
569
|
+
this.cancellaAttesaConnessione = null;
|
|
570
|
+
};
|
|
571
|
+
const cambiata = () => {
|
|
572
|
+
if (generazione !== this.generazione) {
|
|
573
|
+
pulisci();
|
|
574
|
+
reject(creaErrore("offline", "Voice was stopped."));
|
|
575
|
+
} else if (pc.connectionState === "connected") {
|
|
576
|
+
pulisci();
|
|
577
|
+
resolve();
|
|
578
|
+
} else if (pc.connectionState === "failed" || pc.connectionState === "closed") {
|
|
579
|
+
pulisci();
|
|
580
|
+
reject(creaErrore("voice_error", "The voice connection failed."));
|
|
581
|
+
}
|
|
582
|
+
};
|
|
583
|
+
pc.addEventListener("connectionstatechange", cambiata);
|
|
584
|
+
this.cancellaAttesaConnessione = () => {
|
|
585
|
+
pulisci();
|
|
586
|
+
reject(creaErrore("offline", "Voice was stopped."));
|
|
587
|
+
};
|
|
588
|
+
this.timerConnessione = dipendenze.setTimeout(() => {
|
|
589
|
+
pulisci();
|
|
590
|
+
reject(creaErrore("voice_error", "The voice connection timed out."));
|
|
591
|
+
}, TIMEOUT_CONNESSIONE);
|
|
592
|
+
});
|
|
593
|
+
}
|
|
594
|
+
accodaRiconciliazione() {
|
|
595
|
+
if (this.stateCorrente !== "on") return;
|
|
596
|
+
this.negoziazione = this.negoziazione.then(async () => {
|
|
597
|
+
if (this.stateCorrente !== "on") return;
|
|
598
|
+
if (this.trasporto === "sfu") await this.riconciliaSfu();
|
|
599
|
+
else if (this.trasporto === "mesh") this.riconciliaMesh();
|
|
600
|
+
}).catch(() => this.avviaRiconnessione());
|
|
601
|
+
}
|
|
602
|
+
async riconciliaSfu() {
|
|
603
|
+
const sessione = this.sessioneSfu;
|
|
604
|
+
const pc = this.peerSfu;
|
|
605
|
+
if (sessione === null || pc === null) return;
|
|
606
|
+
const desiderati = new Map(this.peerDesiderati().map((peer) => [peer.id, peer]));
|
|
607
|
+
const daChiudere = [];
|
|
608
|
+
for (const [playerId, attiva] of this.sfuAttive) {
|
|
609
|
+
const peer = desiderati.get(playerId);
|
|
610
|
+
if (peer !== void 0 && peer.session === attiva.session && peer.track === attiva.track) continue;
|
|
611
|
+
daChiudere.push(attiva);
|
|
612
|
+
if (!this.riproduzioni.has(playerId)) attiva.receiver?.track.stop();
|
|
613
|
+
this.sfuAttive.delete(playerId);
|
|
614
|
+
this.midGiocatori.delete(attiva.mid);
|
|
615
|
+
this.scollegaTraccia(playerId);
|
|
616
|
+
}
|
|
617
|
+
if (daChiudere.length > 0) {
|
|
618
|
+
await this.richiedi({
|
|
619
|
+
t: "voice",
|
|
620
|
+
op: "close",
|
|
621
|
+
session: sessione,
|
|
622
|
+
mids: daChiudere.map((item) => item.mid)
|
|
623
|
+
});
|
|
624
|
+
}
|
|
625
|
+
const nuove = [...desiderati.values()].filter((peer) => !this.sfuAttive.has(peer.id));
|
|
626
|
+
if (nuove.length === 0) return;
|
|
627
|
+
const risposta = await this.richiedi({
|
|
628
|
+
t: "voice",
|
|
629
|
+
op: "subscribe",
|
|
630
|
+
session: sessione,
|
|
631
|
+
tracks: nuove.map((peer) => ({ session: peer.session, track: peer.track }))
|
|
632
|
+
});
|
|
633
|
+
if (risposta.op !== "subscribe") {
|
|
634
|
+
throw creaErrore("voice_error", "The voice service returned an invalid response.");
|
|
635
|
+
}
|
|
636
|
+
for (const risultato of risposta.tracks) {
|
|
637
|
+
const peer = nuove.find(
|
|
638
|
+
(item) => item.session === risultato.session && item.track === risultato.track
|
|
639
|
+
);
|
|
640
|
+
if (risultato?.mid === null || risultato?.mid === void 0 || risultato.error !== null || peer === void 0) continue;
|
|
641
|
+
this.midGiocatori.set(risultato.mid, peer.id);
|
|
642
|
+
this.sfuAttive.set(peer.id, {
|
|
643
|
+
session: peer.session,
|
|
644
|
+
track: peer.track,
|
|
645
|
+
mid: risultato.mid,
|
|
646
|
+
receiver: null
|
|
647
|
+
});
|
|
648
|
+
}
|
|
649
|
+
await pc.setRemoteDescription({ type: "offer", sdp: risposta.sdp });
|
|
650
|
+
const answer = await pc.createAnswer();
|
|
651
|
+
await pc.setLocalDescription(answer);
|
|
652
|
+
const sdp = pc.localDescription?.sdp;
|
|
653
|
+
if (sdp === void 0) throw creaErrore("voice_error", "The voice answer is missing.");
|
|
654
|
+
await this.richiedi({ t: "voice", op: "answer", session: sessione, sdp });
|
|
655
|
+
}
|
|
656
|
+
riconciliaMesh() {
|
|
657
|
+
const desiderati = new Map(this.peerDesiderati().map((peer) => [peer.id, peer]));
|
|
658
|
+
for (const [playerId, item] of this.mesh) {
|
|
659
|
+
if (desiderati.has(playerId)) continue;
|
|
660
|
+
item.pc.close();
|
|
661
|
+
this.mesh.delete(playerId);
|
|
662
|
+
this.scollegaTraccia(playerId);
|
|
663
|
+
}
|
|
664
|
+
for (const peer of desiderati.values()) {
|
|
665
|
+
if (!this.mesh.has(peer.id)) this.creaMesh(peer.id);
|
|
666
|
+
}
|
|
667
|
+
}
|
|
668
|
+
creaMesh(playerId) {
|
|
669
|
+
const pc = this.richiediDipendenze().creaPeerConnection();
|
|
670
|
+
const item = {
|
|
671
|
+
pc,
|
|
672
|
+
makingOffer: false,
|
|
673
|
+
ignoreOffer: false,
|
|
674
|
+
settingRemoteAnswer: false,
|
|
675
|
+
polite: this.contesto.you() > playerId,
|
|
676
|
+
receiver: null
|
|
677
|
+
};
|
|
678
|
+
this.mesh.set(playerId, item);
|
|
679
|
+
pc.onicecandidate = (event) => {
|
|
680
|
+
if (event.candidate === null) return;
|
|
681
|
+
void this.inviaSegnale(playerId, { kind: "candidate", candidate: event.candidate.toJSON() });
|
|
682
|
+
};
|
|
683
|
+
if (!item.polite) pc.onnegotiationneeded = () => {
|
|
684
|
+
void this.offriMesh(playerId, item);
|
|
685
|
+
};
|
|
686
|
+
pc.ontrack = (event) => {
|
|
687
|
+
item.receiver = event.receiver;
|
|
688
|
+
this.collegaTraccia(playerId, event.track, event.receiver);
|
|
689
|
+
};
|
|
690
|
+
this.osservaCaduta(pc);
|
|
691
|
+
pc.addTrack(this.richiediMic(), this.richiediStream());
|
|
692
|
+
}
|
|
693
|
+
async offriMesh(playerId, item) {
|
|
694
|
+
try {
|
|
695
|
+
item.makingOffer = true;
|
|
696
|
+
const offer = await item.pc.createOffer();
|
|
697
|
+
await item.pc.setLocalDescription(offer);
|
|
698
|
+
const sdp = item.pc.localDescription?.sdp;
|
|
699
|
+
if (sdp !== void 0) await this.inviaSegnale(playerId, { kind: "offer", sdp });
|
|
700
|
+
} finally {
|
|
701
|
+
item.makingOffer = false;
|
|
702
|
+
}
|
|
703
|
+
}
|
|
704
|
+
async riceviSegnale(from, data) {
|
|
705
|
+
if (this.trasporto !== "mesh" || this.stateCorrente !== "on") return;
|
|
706
|
+
if (!this.peerDesiderati().some((peer) => peer.id === from)) return;
|
|
707
|
+
if (!this.mesh.has(from)) this.creaMesh(from);
|
|
708
|
+
const item = this.mesh.get(from);
|
|
709
|
+
if (item === void 0 || typeof data !== "object" || data === null || Array.isArray(data)) return;
|
|
710
|
+
const segnale = data;
|
|
711
|
+
try {
|
|
712
|
+
if (segnale.kind === "candidate") {
|
|
713
|
+
if (!item.ignoreOffer) await item.pc.addIceCandidate(segnale.candidate);
|
|
714
|
+
return;
|
|
715
|
+
}
|
|
716
|
+
if (segnale.kind !== "offer" && segnale.kind !== "answer" || typeof segnale.sdp !== "string") return;
|
|
717
|
+
const pronta = !item.makingOffer && (item.pc.signalingState === "stable" || item.settingRemoteAnswer);
|
|
718
|
+
const collisione = segnale.kind === "offer" && !pronta;
|
|
719
|
+
item.ignoreOffer = !item.polite && collisione;
|
|
720
|
+
if (item.ignoreOffer) return;
|
|
721
|
+
item.settingRemoteAnswer = segnale.kind === "answer";
|
|
722
|
+
await item.pc.setRemoteDescription({ type: segnale.kind, sdp: segnale.sdp });
|
|
723
|
+
item.settingRemoteAnswer = false;
|
|
724
|
+
if (segnale.kind === "offer") {
|
|
725
|
+
const answer = await item.pc.createAnswer();
|
|
726
|
+
await item.pc.setLocalDescription(answer);
|
|
727
|
+
const sdp = item.pc.localDescription?.sdp;
|
|
728
|
+
if (sdp !== void 0) await this.inviaSegnale(from, { kind: "answer", sdp });
|
|
729
|
+
}
|
|
730
|
+
} catch {
|
|
731
|
+
this.avviaRiconnessione();
|
|
732
|
+
}
|
|
733
|
+
}
|
|
734
|
+
inviaSegnale(to, data) {
|
|
735
|
+
return this.richiedi({ t: "voice", op: "signal", to, data });
|
|
736
|
+
}
|
|
737
|
+
peerDesiderati() {
|
|
738
|
+
const you = this.contesto.you();
|
|
739
|
+
const giocatori = this.contesto.giocatori();
|
|
740
|
+
const player = giocatori.find((item) => item.id === you);
|
|
741
|
+
return this.roster.filter((peer) => {
|
|
742
|
+
if (peer.id === you) return false;
|
|
743
|
+
if (this.modeCorrente === "team") {
|
|
744
|
+
const altro = giocatori.find((item) => item.id === peer.id);
|
|
745
|
+
if (player?.role !== "spectator" && altro?.team !== player?.team) return false;
|
|
746
|
+
}
|
|
747
|
+
const zeroAt = this.zeroDa.get(peer.id);
|
|
748
|
+
return zeroAt === void 0 || this.richiediDipendenze().ora() - zeroAt < DURATA_ZERO;
|
|
749
|
+
});
|
|
750
|
+
}
|
|
751
|
+
aggiornaZero(playerId) {
|
|
752
|
+
const dipendenze = this.dipendenze;
|
|
753
|
+
if (dipendenze === null) return;
|
|
754
|
+
const precedente = this.timerZero.get(playerId);
|
|
755
|
+
if (precedente !== void 0) dipendenze.clearTimeout(precedente);
|
|
756
|
+
this.timerZero.delete(playerId);
|
|
757
|
+
if ((this.gains.get(playerId) ?? 1) > 0) {
|
|
758
|
+
this.zeroDa.delete(playerId);
|
|
759
|
+
return;
|
|
760
|
+
}
|
|
761
|
+
if (!this.zeroDa.has(playerId)) this.zeroDa.set(playerId, dipendenze.ora());
|
|
762
|
+
const trascorso = dipendenze.ora() - (this.zeroDa.get(playerId) ?? dipendenze.ora());
|
|
763
|
+
const timer = dipendenze.setTimeout(() => {
|
|
764
|
+
this.timerZero.delete(playerId);
|
|
765
|
+
this.accodaRiconciliazione();
|
|
766
|
+
}, Math.max(0, DURATA_ZERO - trascorso));
|
|
767
|
+
this.timerZero.set(playerId, timer);
|
|
768
|
+
}
|
|
769
|
+
collegaTraccia(playerId, track, receiver) {
|
|
770
|
+
this.scollegaTraccia(playerId);
|
|
771
|
+
const dipendenze = this.richiediDipendenze();
|
|
772
|
+
const media = dipendenze.creaMediaStream([track]);
|
|
773
|
+
const source = this.richiediAudioContext().createMediaStreamSource(media);
|
|
774
|
+
const gain = this.richiediAudioContext().createGain();
|
|
775
|
+
source.connect(gain);
|
|
776
|
+
gain.connect(this.richiediAudioContext().destination);
|
|
777
|
+
let analyser = null;
|
|
778
|
+
try {
|
|
779
|
+
analyser = this.richiediAudioContext().createAnalyser();
|
|
780
|
+
analyser.fftSize = 256;
|
|
781
|
+
source.connect(analyser);
|
|
782
|
+
} catch {
|
|
783
|
+
analyser = null;
|
|
784
|
+
}
|
|
785
|
+
const audio = dipendenze.creaAudioElement();
|
|
786
|
+
audio.srcObject = media;
|
|
787
|
+
audio.muted = true;
|
|
788
|
+
audio.playsInline = true;
|
|
789
|
+
void audio.play().catch(() => void 0);
|
|
790
|
+
this.riproduzioni.set(playerId, { source, gain, analyser, audio, track, receiver });
|
|
791
|
+
const attiva = this.sfuAttive.get(playerId);
|
|
792
|
+
if (attiva !== void 0) attiva.receiver = receiver;
|
|
793
|
+
this.aggiornaGuadagno(playerId);
|
|
794
|
+
}
|
|
795
|
+
scollegaTraccia(playerId) {
|
|
796
|
+
const riproduzione = this.riproduzioni.get(playerId);
|
|
797
|
+
if (riproduzione === void 0) return;
|
|
798
|
+
riproduzione.source.disconnect();
|
|
799
|
+
riproduzione.gain.disconnect();
|
|
800
|
+
riproduzione.analyser?.disconnect();
|
|
801
|
+
riproduzione.track.stop();
|
|
802
|
+
riproduzione.audio.pause();
|
|
803
|
+
riproduzione.audio.srcObject = null;
|
|
804
|
+
this.riproduzioni.delete(playerId);
|
|
805
|
+
this.speakingPeers.delete(playerId);
|
|
806
|
+
this.ultimoAudio.delete(playerId);
|
|
807
|
+
}
|
|
808
|
+
aggiornaGuadagno(playerId) {
|
|
809
|
+
const riproduzione = this.riproduzioni.get(playerId);
|
|
810
|
+
if (riproduzione !== void 0) {
|
|
811
|
+
riproduzione.gain.gain.value = (this.volumi.get(playerId) ?? 1) * (this.gains.get(playerId) ?? 1);
|
|
812
|
+
}
|
|
813
|
+
}
|
|
814
|
+
preparaAnalizzatore(stream) {
|
|
815
|
+
const context = this.richiediAudioContext();
|
|
816
|
+
const analyser = context.createAnalyser();
|
|
817
|
+
analyser.fftSize = 256;
|
|
818
|
+
context.createMediaStreamSource(stream).connect(analyser);
|
|
819
|
+
this.analyser = analyser;
|
|
820
|
+
}
|
|
821
|
+
avviaMisuraAudio() {
|
|
822
|
+
const dipendenze = this.richiediDipendenze();
|
|
823
|
+
if (this.intervalloAudio !== null) dipendenze.clearInterval(this.intervalloAudio);
|
|
824
|
+
this.intervalloAudio = dipendenze.setInterval(() => this.misuraAudio(), INTERVALLO_AUDIO);
|
|
825
|
+
}
|
|
826
|
+
misuraAudio() {
|
|
827
|
+
const dipendenze = this.dipendenze;
|
|
828
|
+
if (dipendenze === null) return;
|
|
829
|
+
let sopraSoglia = false;
|
|
830
|
+
if (this.analyser !== null) sopraSoglia = this.livelloAnalizzatore(this.analyser) > SOGLIA_AUDIO;
|
|
831
|
+
if (sopraSoglia) this.ultimoAudioMic = dipendenze.ora();
|
|
832
|
+
const parlando = !this.mutedCorrente && dipendenze.ora() - this.ultimoAudioMic <= DURATA_PARLANTE;
|
|
833
|
+
if (parlando !== this.speakingCorrente) {
|
|
834
|
+
this.speakingCorrente = parlando;
|
|
835
|
+
this.notificaPeers();
|
|
836
|
+
}
|
|
837
|
+
let cambiato = false;
|
|
838
|
+
for (const peer of this.copiaPeers()) {
|
|
839
|
+
const riproduzione = this.riproduzioni.get(peer.id);
|
|
840
|
+
if (this.livelloAnalizzatore(riproduzione?.analyser ?? null) > SOGLIA_AUDIO) {
|
|
841
|
+
this.ultimoAudio.set(peer.id, dipendenze.ora());
|
|
842
|
+
} else if (riproduzione?.analyser === null || riproduzione?.analyser === void 0) {
|
|
843
|
+
const sources = riproduzione?.receiver?.getSynchronizationSources?.() ?? [];
|
|
844
|
+
if (sources.some((source) => (source.audioLevel ?? 0) > SOGLIA_AUDIO)) {
|
|
845
|
+
this.ultimoAudio.set(peer.id, dipendenze.ora());
|
|
846
|
+
}
|
|
847
|
+
}
|
|
848
|
+
const speaking = !peer.muted && dipendenze.ora() - (this.ultimoAudio.get(peer.id) ?? 0) <= DURATA_PARLANTE;
|
|
849
|
+
if ((this.speakingPeers.get(peer.id) ?? false) !== speaking) {
|
|
850
|
+
this.speakingPeers.set(peer.id, speaking);
|
|
851
|
+
cambiato = true;
|
|
852
|
+
}
|
|
853
|
+
}
|
|
854
|
+
if (cambiato) this.notificaPeers();
|
|
855
|
+
}
|
|
856
|
+
livelloAnalizzatore(analyser) {
|
|
857
|
+
const nodo = analyser;
|
|
858
|
+
if (nodo?.getFloatTimeDomainData === void 0) return 0;
|
|
859
|
+
const campioni = new Float32Array(nodo.fftSize);
|
|
860
|
+
nodo.getFloatTimeDomainData(campioni);
|
|
861
|
+
return Math.sqrt(campioni.reduce((somma, valore) => somma + valore * valore, 0) / Math.max(1, campioni.length));
|
|
862
|
+
}
|
|
863
|
+
copiaPeers() {
|
|
864
|
+
const you = this.contesto.you();
|
|
865
|
+
const giocatori = this.contesto.giocatori();
|
|
866
|
+
const player = giocatori.find((item) => item.id === you);
|
|
867
|
+
return this.roster.flatMap((peer) => {
|
|
868
|
+
if (peer.id === you) return [];
|
|
869
|
+
if (this.modeCorrente === "team") {
|
|
870
|
+
const altro = giocatori.find((item) => item.id === peer.id);
|
|
871
|
+
if (player?.role !== "spectator" && altro?.team !== player?.team) return [];
|
|
872
|
+
}
|
|
873
|
+
return [{
|
|
874
|
+
id: peer.id,
|
|
875
|
+
muted: peer.muted,
|
|
876
|
+
speaking: !peer.muted && (this.speakingPeers.get(peer.id) ?? false),
|
|
877
|
+
volume: this.volumi.get(peer.id) ?? 1,
|
|
878
|
+
gain: this.gains.get(peer.id) ?? 1
|
|
879
|
+
}];
|
|
880
|
+
});
|
|
881
|
+
}
|
|
882
|
+
pulisciPeerAssenti() {
|
|
883
|
+
const presenti = new Set(this.roster.map((peer) => peer.id));
|
|
884
|
+
for (const playerId of this.speakingPeers.keys()) {
|
|
885
|
+
if (!presenti.has(playerId)) this.speakingPeers.delete(playerId);
|
|
886
|
+
}
|
|
887
|
+
for (const playerId of this.zeroDa.keys()) {
|
|
888
|
+
if (presenti.has(playerId)) continue;
|
|
889
|
+
this.zeroDa.delete(playerId);
|
|
890
|
+
const timer = this.timerZero.get(playerId);
|
|
891
|
+
if (timer !== void 0) this.dipendenze?.clearTimeout(timer);
|
|
892
|
+
this.timerZero.delete(playerId);
|
|
893
|
+
}
|
|
894
|
+
}
|
|
895
|
+
osservaCaduta(pc) {
|
|
896
|
+
pc.addEventListener("connectionstatechange", () => {
|
|
897
|
+
if (this.stateCorrente === "on" && (pc.connectionState === "failed" || pc.connectionState === "disconnected")) this.avviaRiconnessione();
|
|
898
|
+
});
|
|
899
|
+
}
|
|
900
|
+
avviaRiconnessione() {
|
|
901
|
+
if (!this.desiderata || this.stateCorrente === "reconnecting") return;
|
|
902
|
+
this.generazione++;
|
|
903
|
+
this.rifiutaRichieste(creaErrore("voice_error", "The voice connection was restarted."));
|
|
904
|
+
this.chiudiRisorse();
|
|
905
|
+
this.tentativoRiconnessione = 0;
|
|
906
|
+
this.aggiornaState("reconnecting");
|
|
907
|
+
this.programmaRiconnessione();
|
|
908
|
+
}
|
|
909
|
+
programmaRiconnessione() {
|
|
910
|
+
if (!this.desiderata || !this.contesto.connessa() || this.timerRiconnessione !== null || this.stateCorrente !== "reconnecting") return;
|
|
911
|
+
const ritardo = RITARDI_RICONNESSIONE[this.tentativoRiconnessione];
|
|
912
|
+
if (ritardo === void 0) {
|
|
913
|
+
this.desiderata = false;
|
|
914
|
+
this.aggiornaState("off");
|
|
915
|
+
return;
|
|
916
|
+
}
|
|
917
|
+
this.tentativoRiconnessione++;
|
|
918
|
+
this.timerRiconnessione = this.richiediDipendenze().setTimeout(() => {
|
|
919
|
+
this.timerRiconnessione = null;
|
|
920
|
+
const generazione = ++this.generazione;
|
|
921
|
+
void this.entra(generazione).catch(() => {
|
|
922
|
+
if (generazione !== this.generazione || !this.desiderata) return;
|
|
923
|
+
this.chiudiRisorse();
|
|
924
|
+
this.aggiornaState("reconnecting");
|
|
925
|
+
this.programmaRiconnessione();
|
|
926
|
+
});
|
|
927
|
+
}, ritardo);
|
|
928
|
+
}
|
|
929
|
+
fermaRiconnessione() {
|
|
930
|
+
if (this.timerRiconnessione === null || this.dipendenze === null) return;
|
|
931
|
+
this.dipendenze.clearTimeout(this.timerRiconnessione);
|
|
932
|
+
this.timerRiconnessione = null;
|
|
933
|
+
}
|
|
934
|
+
chiudiRisorse() {
|
|
935
|
+
const dipendenze = this.dipendenze;
|
|
936
|
+
this.cancellaAttesaConnessione?.();
|
|
937
|
+
this.cancellaAttesaConnessione = null;
|
|
938
|
+
if (dipendenze !== null) {
|
|
939
|
+
if (this.intervalloAudio !== null) dipendenze.clearInterval(this.intervalloAudio);
|
|
940
|
+
if (this.timerConnessione !== null) dipendenze.clearTimeout(this.timerConnessione);
|
|
941
|
+
for (const timer of this.timerZero.values()) dipendenze.clearTimeout(timer);
|
|
942
|
+
}
|
|
943
|
+
this.intervalloAudio = null;
|
|
944
|
+
this.timerConnessione = null;
|
|
945
|
+
this.timerZero.clear();
|
|
946
|
+
for (const playerId of [...this.riproduzioni.keys()]) this.scollegaTraccia(playerId);
|
|
947
|
+
this.peerSfu?.close();
|
|
948
|
+
this.peerSfu = null;
|
|
949
|
+
for (const item of this.mesh.values()) item.pc.close();
|
|
950
|
+
this.mesh.clear();
|
|
951
|
+
this.sfuAttive.clear();
|
|
952
|
+
this.midGiocatori.clear();
|
|
953
|
+
for (const track of this.stream?.getTracks() ?? []) track.stop();
|
|
954
|
+
this.stream = null;
|
|
955
|
+
this.mic = null;
|
|
956
|
+
this.analyser = null;
|
|
957
|
+
void this.audioContext?.close().catch(() => void 0);
|
|
958
|
+
this.audioContext = null;
|
|
959
|
+
this.sessioneSfu = null;
|
|
960
|
+
this.trasporto = null;
|
|
961
|
+
this.speakingCorrente = false;
|
|
962
|
+
this.ultimoAudioMic = Number.NEGATIVE_INFINITY;
|
|
963
|
+
this.speakingPeers.clear();
|
|
964
|
+
this.ultimoAudio.clear();
|
|
965
|
+
this.negoziazione = Promise.resolve();
|
|
966
|
+
}
|
|
967
|
+
richiedi(message) {
|
|
968
|
+
if (!this.contesto.connessa()) return Promise.reject(creaErrore("offline", "The room is reconnecting."));
|
|
969
|
+
const r = ++this.sequenzaRichieste;
|
|
970
|
+
return new Promise((resolve, reject) => {
|
|
971
|
+
this.richieste.set(r, { resolve, reject });
|
|
972
|
+
try {
|
|
973
|
+
this.contesto.invia({ ...message, r });
|
|
974
|
+
} catch (cause) {
|
|
975
|
+
this.richieste.delete(r);
|
|
976
|
+
reject(cause);
|
|
977
|
+
}
|
|
978
|
+
});
|
|
979
|
+
}
|
|
980
|
+
rifiutaRichieste(reason) {
|
|
981
|
+
for (const richiesta of this.richieste.values()) richiesta.reject(reason);
|
|
982
|
+
this.richieste.clear();
|
|
983
|
+
}
|
|
984
|
+
aggiornaState(state) {
|
|
985
|
+
if (state === this.stateCorrente) return;
|
|
986
|
+
this.stateCorrente = state;
|
|
987
|
+
for (const listener of this.ascoltatoriState) {
|
|
988
|
+
try {
|
|
989
|
+
listener(state);
|
|
990
|
+
} catch {
|
|
991
|
+
}
|
|
992
|
+
}
|
|
993
|
+
}
|
|
994
|
+
notificaPeers() {
|
|
995
|
+
const peers = this.copiaPeers();
|
|
996
|
+
for (const listener of this.ascoltatoriPeers) {
|
|
997
|
+
try {
|
|
998
|
+
listener(peers);
|
|
999
|
+
} catch {
|
|
1000
|
+
}
|
|
1001
|
+
}
|
|
1002
|
+
}
|
|
1003
|
+
controllaGenerazione(generazione) {
|
|
1004
|
+
if (generazione !== this.generazione || !this.desiderata) {
|
|
1005
|
+
throw creaErrore("offline", "Voice was stopped.");
|
|
1006
|
+
}
|
|
1007
|
+
}
|
|
1008
|
+
richiediDipendenze() {
|
|
1009
|
+
if (this.dipendenze === null) throw creaErrore("unsupported", "Voice is not supported.");
|
|
1010
|
+
return this.dipendenze;
|
|
1011
|
+
}
|
|
1012
|
+
richiediMic() {
|
|
1013
|
+
if (this.mic === null) throw creaErrore("voice_error", "The microphone is not ready.");
|
|
1014
|
+
return this.mic;
|
|
1015
|
+
}
|
|
1016
|
+
richiediStream() {
|
|
1017
|
+
if (this.stream === null) throw creaErrore("voice_error", "The microphone is not ready.");
|
|
1018
|
+
return this.stream;
|
|
1019
|
+
}
|
|
1020
|
+
richiediAudioContext() {
|
|
1021
|
+
if (this.audioContext === null) throw creaErrore("voice_error", "Audio is not ready.");
|
|
1022
|
+
return this.audioContext;
|
|
1023
|
+
}
|
|
1024
|
+
permessoNegato(cause) {
|
|
1025
|
+
return typeof cause === "object" && cause !== null && "name" in cause && (cause.name === "NotAllowedError" || cause.name === "SecurityError");
|
|
1026
|
+
}
|
|
1027
|
+
mappaErrore(cause) {
|
|
1028
|
+
if (typeof cause === "object" && cause !== null && "code" in cause) {
|
|
1029
|
+
const code = cause.code;
|
|
1030
|
+
if (code === "voice_disabled" || code === "permission_denied" || code === "unsupported" || code === "spectator" || code === "offline" || code === "voice_error") return cause;
|
|
1031
|
+
return creaErrore("voice_error", "Voice could not be started.");
|
|
1032
|
+
}
|
|
1033
|
+
return creaErrore("voice_error", "Voice could not be started.");
|
|
1034
|
+
}
|
|
1035
|
+
};
|
|
1036
|
+
|
|
1037
|
+
// src/stanza-client/index.ts
|
|
1038
|
+
var APERTO = 1;
|
|
1039
|
+
var RITARDI_RICONNESSIONE2 = [1e3, 2e3, 4e3, 8e3];
|
|
1040
|
+
var GRAZIA_RICONNESSIONE = 6e4;
|
|
1041
|
+
var INTERVALLO_PING = 5e3;
|
|
1042
|
+
var RITARDO_FLUSH = 500;
|
|
1043
|
+
var ATTESA_ROSTER = 2e3;
|
|
1044
|
+
var CHIUSURE_DEFINITIVE = /* @__PURE__ */ new Set([4003, 4004, 4005, 4006]);
|
|
1045
|
+
function record2(value) {
|
|
1046
|
+
return typeof value === "object" && value !== null && !Array.isArray(value) ? value : null;
|
|
1047
|
+
}
|
|
1048
|
+
function copiaJson(value) {
|
|
1049
|
+
return JSON.parse(JSON.stringify(value));
|
|
1050
|
+
}
|
|
1051
|
+
function applicaPatch(state, value) {
|
|
1052
|
+
let risultato = copiaJson(state);
|
|
1053
|
+
for (const operazione of value) {
|
|
1054
|
+
if (operazione.path.length === 0) {
|
|
1055
|
+
if (operazione.op !== "set") return { ok: false };
|
|
1056
|
+
risultato = copiaJson(operazione.value);
|
|
1057
|
+
continue;
|
|
1058
|
+
}
|
|
1059
|
+
let contenitore = risultato;
|
|
1060
|
+
const percorso = operazione.path;
|
|
1061
|
+
for (let indice = 0; indice < percorso.length - 1; indice++) {
|
|
1062
|
+
const parte = percorso[indice];
|
|
1063
|
+
if (Array.isArray(contenitore)) {
|
|
1064
|
+
if (typeof parte !== "number" || parte >= contenitore.length) return { ok: false };
|
|
1065
|
+
contenitore = contenitore[parte];
|
|
1066
|
+
} else {
|
|
1067
|
+
const oggetto = record2(contenitore);
|
|
1068
|
+
if (oggetto === null || typeof parte !== "string" || !Object.hasOwn(oggetto, parte)) {
|
|
1069
|
+
return { ok: false };
|
|
1070
|
+
}
|
|
1071
|
+
contenitore = oggetto[parte];
|
|
1072
|
+
}
|
|
1073
|
+
}
|
|
1074
|
+
const ultima = percorso.at(-1);
|
|
1075
|
+
if (Array.isArray(contenitore)) {
|
|
1076
|
+
if (operazione.op !== "set" || typeof ultima !== "number" || ultima >= contenitore.length) return { ok: false };
|
|
1077
|
+
contenitore[ultima] = copiaJson(operazione.value);
|
|
1078
|
+
} else {
|
|
1079
|
+
const oggetto = record2(contenitore);
|
|
1080
|
+
if (oggetto === null || typeof ultima !== "string") return { ok: false };
|
|
1081
|
+
if (operazione.op === "del") {
|
|
1082
|
+
if (!Object.hasOwn(oggetto, ultima)) return { ok: false };
|
|
1083
|
+
delete oggetto[ultima];
|
|
1084
|
+
} else {
|
|
1085
|
+
Object.defineProperty(oggetto, ultima, {
|
|
1086
|
+
configurable: true,
|
|
1087
|
+
enumerable: true,
|
|
1088
|
+
value: copiaJson(operazione.value),
|
|
1089
|
+
writable: true
|
|
1090
|
+
});
|
|
1091
|
+
}
|
|
1092
|
+
}
|
|
1093
|
+
}
|
|
1094
|
+
return { ok: true, state: risultato };
|
|
1095
|
+
}
|
|
1096
|
+
function creaApiLive(input) {
|
|
1097
|
+
const richiesta = creaRichiedente(input.liveOrigin, "", input.fetcher, input.biglietto);
|
|
1098
|
+
function ingressoValido(value) {
|
|
1099
|
+
const dati = record2(value);
|
|
1100
|
+
return dati !== null && typeof dati.roomId === "string" && typeof dati.code === "string" && typeof dati.join === "string" && typeof dati.url === "string";
|
|
1101
|
+
}
|
|
1102
|
+
async function ingresso(path, body, rinnova = false) {
|
|
1103
|
+
const value = await richiesta(path, "POST", body, rinnova);
|
|
1104
|
+
if (!ingressoValido(value)) {
|
|
1105
|
+
throw creaErrore("internal_error", "The room service returned an invalid response.");
|
|
1106
|
+
}
|
|
1107
|
+
return value;
|
|
1108
|
+
}
|
|
1109
|
+
return {
|
|
1110
|
+
create: (mode) => ingresso("/rooms", { mode }),
|
|
1111
|
+
joinCode: (code) => ingresso("/rooms/join", { code }),
|
|
1112
|
+
joinRoom: (roomId) => ingresso("/rooms/join", { roomId }, true),
|
|
1113
|
+
flush: (roomId) => richiesta(
|
|
1114
|
+
`/rooms/${encodeURIComponent(roomId)}/flush`,
|
|
1115
|
+
"POST"
|
|
1116
|
+
)
|
|
1117
|
+
};
|
|
1118
|
+
}
|
|
1119
|
+
var StanzaClient = class {
|
|
1120
|
+
constructor(roomId, codice, url, input, api) {
|
|
1121
|
+
this.roomId = roomId;
|
|
1122
|
+
this.codice = codice;
|
|
1123
|
+
this.input = input;
|
|
1124
|
+
this.api = api;
|
|
1125
|
+
this.statoPubblico = null;
|
|
1126
|
+
this.statoSincronizzato = null;
|
|
1127
|
+
this.tickCorrente = 0;
|
|
1128
|
+
this.statusCorrente = "lobby";
|
|
1129
|
+
this.giocatoriCorrenti = [];
|
|
1130
|
+
this.youCorrente = "";
|
|
1131
|
+
this.hostCorrente = null;
|
|
1132
|
+
this.resultCorrente = null;
|
|
1133
|
+
this.socket = null;
|
|
1134
|
+
this.seq = 0;
|
|
1135
|
+
this.scartoOrario = 0;
|
|
1136
|
+
this.timerPing = null;
|
|
1137
|
+
this.timerRiconnessione = null;
|
|
1138
|
+
this.timerFlush = null;
|
|
1139
|
+
this.flushInCorso = false;
|
|
1140
|
+
this.flushRichiesto = false;
|
|
1141
|
+
this.ritardoIndice = 0;
|
|
1142
|
+
this.tempoRiconnessione = 0;
|
|
1143
|
+
this.resyncRichiesto = false;
|
|
1144
|
+
this.terminata = false;
|
|
1145
|
+
this.lasciata = false;
|
|
1146
|
+
this.prontaRisolta = false;
|
|
1147
|
+
this.welcomeRicevuto = false;
|
|
1148
|
+
this.rosterRicevuto = false;
|
|
1149
|
+
this.timerRoster = null;
|
|
1150
|
+
this.risolviPronta = () => void 0;
|
|
1151
|
+
this.rifiutaPronta = () => void 0;
|
|
1152
|
+
this.ascoltatoriStato = /* @__PURE__ */ new Set();
|
|
1153
|
+
this.ascoltatoriGiocatori = /* @__PURE__ */ new Set();
|
|
1154
|
+
this.ascoltatoriStatus = /* @__PURE__ */ new Set();
|
|
1155
|
+
this.ascoltatoriMessaggi = /* @__PURE__ */ new Set();
|
|
1156
|
+
this.promessaPronta = new Promise((resolve, reject) => {
|
|
1157
|
+
this.risolviPronta = resolve;
|
|
1158
|
+
this.rifiutaPronta = reject;
|
|
1159
|
+
});
|
|
1160
|
+
this.voice = new VoceClient({
|
|
1161
|
+
invia: (message) => this.invia(message),
|
|
1162
|
+
connessa: () => this.socket?.readyState === APERTO && this.welcomeRicevuto && !this.terminata && !this.lasciata,
|
|
1163
|
+
you: () => this.youCorrente,
|
|
1164
|
+
giocatori: () => this.copiaGiocatori(),
|
|
1165
|
+
rosterPronto: () => {
|
|
1166
|
+
this.rosterRicevuto = true;
|
|
1167
|
+
this.risolviProntaSePossibile();
|
|
1168
|
+
}
|
|
1169
|
+
}, input, input.voce);
|
|
1170
|
+
this.apri(url);
|
|
1171
|
+
}
|
|
1172
|
+
get state() {
|
|
1173
|
+
return this.statoPubblico;
|
|
1174
|
+
}
|
|
1175
|
+
get tick() {
|
|
1176
|
+
return this.tickCorrente;
|
|
1177
|
+
}
|
|
1178
|
+
get status() {
|
|
1179
|
+
return this.statusCorrente;
|
|
1180
|
+
}
|
|
1181
|
+
get players() {
|
|
1182
|
+
return this.copiaGiocatori();
|
|
1183
|
+
}
|
|
1184
|
+
get you() {
|
|
1185
|
+
return this.youCorrente;
|
|
1186
|
+
}
|
|
1187
|
+
get host() {
|
|
1188
|
+
return this.hostCorrente;
|
|
1189
|
+
}
|
|
1190
|
+
get code() {
|
|
1191
|
+
return this.codice;
|
|
1192
|
+
}
|
|
1193
|
+
get result() {
|
|
1194
|
+
return this.resultCorrente;
|
|
1195
|
+
}
|
|
1196
|
+
pronta() {
|
|
1197
|
+
return this.promessaPronta;
|
|
1198
|
+
}
|
|
1199
|
+
invite() {
|
|
1200
|
+
return { code: this.codice, url: new URL(`/r/${this.codice}`, this.input.appOrigin).href };
|
|
1201
|
+
}
|
|
1202
|
+
onState(listener) {
|
|
1203
|
+
this.ascoltatoriStato.add(listener);
|
|
1204
|
+
return () => {
|
|
1205
|
+
this.ascoltatoriStato.delete(listener);
|
|
1206
|
+
};
|
|
1207
|
+
}
|
|
1208
|
+
onPlayers(listener) {
|
|
1209
|
+
this.ascoltatoriGiocatori.add(listener);
|
|
1210
|
+
return () => {
|
|
1211
|
+
this.ascoltatoriGiocatori.delete(listener);
|
|
1212
|
+
};
|
|
1213
|
+
}
|
|
1214
|
+
onStatus(listener) {
|
|
1215
|
+
this.ascoltatoriStatus.add(listener);
|
|
1216
|
+
return () => {
|
|
1217
|
+
this.ascoltatoriStatus.delete(listener);
|
|
1218
|
+
};
|
|
1219
|
+
}
|
|
1220
|
+
onMessage(listener) {
|
|
1221
|
+
this.ascoltatoriMessaggi.add(listener);
|
|
1222
|
+
return () => {
|
|
1223
|
+
this.ascoltatoriMessaggi.delete(listener);
|
|
1224
|
+
};
|
|
1225
|
+
}
|
|
1226
|
+
send(message) {
|
|
1227
|
+
const prossimo = this.seq + 1;
|
|
1228
|
+
this.invia({ t: "msg", seq: prossimo, m: message });
|
|
1229
|
+
this.seq = prossimo;
|
|
1230
|
+
}
|
|
1231
|
+
ready(ready) {
|
|
1232
|
+
this.invia({ t: "ready", ready });
|
|
1233
|
+
}
|
|
1234
|
+
setRole(role) {
|
|
1235
|
+
this.invia({ t: "role", role });
|
|
1236
|
+
}
|
|
1237
|
+
setTeam(team) {
|
|
1238
|
+
this.invia({ t: "team", team });
|
|
1239
|
+
}
|
|
1240
|
+
start() {
|
|
1241
|
+
this.invia({ t: "start" });
|
|
1242
|
+
}
|
|
1243
|
+
leave() {
|
|
1244
|
+
if (this.lasciata) return;
|
|
1245
|
+
this.voice.leave();
|
|
1246
|
+
this.lasciata = true;
|
|
1247
|
+
if (this.socket?.readyState === APERTO) this.invia({ t: "leave" });
|
|
1248
|
+
this.termina(1e3);
|
|
1249
|
+
}
|
|
1250
|
+
serverTime() {
|
|
1251
|
+
return this.input.ora() + this.scartoOrario;
|
|
1252
|
+
}
|
|
1253
|
+
copiaGiocatori() {
|
|
1254
|
+
return this.giocatoriCorrenti.map((player) => ({ ...player }));
|
|
1255
|
+
}
|
|
1256
|
+
notifica(listeners, ...args) {
|
|
1257
|
+
for (const listener of listeners) {
|
|
1258
|
+
try {
|
|
1259
|
+
listener(...args);
|
|
1260
|
+
} catch {
|
|
1261
|
+
}
|
|
1262
|
+
}
|
|
1263
|
+
}
|
|
1264
|
+
invia(message) {
|
|
1265
|
+
if (this.socket?.readyState !== APERTO) {
|
|
1266
|
+
throw creaErrore("offline", "The room is reconnecting.");
|
|
1267
|
+
}
|
|
1268
|
+
let frame;
|
|
1269
|
+
try {
|
|
1270
|
+
frame = JSON.stringify(message);
|
|
1271
|
+
} catch {
|
|
1272
|
+
throw creaErrore("invalid_request", "Room messages must be valid JSON.");
|
|
1273
|
+
}
|
|
1274
|
+
this.socket.send(frame);
|
|
1275
|
+
}
|
|
1276
|
+
apri(url) {
|
|
1277
|
+
let socket;
|
|
1278
|
+
try {
|
|
1279
|
+
socket = this.input.apriSocket(url);
|
|
1280
|
+
} catch {
|
|
1281
|
+
this.programmaRiconnessione();
|
|
1282
|
+
return;
|
|
1283
|
+
}
|
|
1284
|
+
this.socket = socket;
|
|
1285
|
+
socket.addEventListener("open", () => {
|
|
1286
|
+
if (this.socket === socket) this.avviaPing();
|
|
1287
|
+
});
|
|
1288
|
+
socket.addEventListener("message", (evento) => {
|
|
1289
|
+
if (this.socket === socket && typeof evento.data === "string") this.ricevi(evento.data);
|
|
1290
|
+
});
|
|
1291
|
+
socket.addEventListener("close", (evento) => {
|
|
1292
|
+
if (this.socket === socket) this.chiuso(evento.code);
|
|
1293
|
+
});
|
|
1294
|
+
}
|
|
1295
|
+
avviaPing() {
|
|
1296
|
+
if (this.timerPing !== null) this.input.clearInterval(this.timerPing);
|
|
1297
|
+
this.timerPing = this.input.setInterval(() => {
|
|
1298
|
+
if (this.socket?.readyState !== APERTO) return;
|
|
1299
|
+
try {
|
|
1300
|
+
this.invia({ t: "ping", c: this.input.ora() });
|
|
1301
|
+
} catch {
|
|
1302
|
+
}
|
|
1303
|
+
}, INTERVALLO_PING);
|
|
1304
|
+
}
|
|
1305
|
+
fermaPing() {
|
|
1306
|
+
if (this.timerPing === null) return;
|
|
1307
|
+
this.input.clearInterval(this.timerPing);
|
|
1308
|
+
this.timerPing = null;
|
|
1309
|
+
}
|
|
1310
|
+
ricevi(frame) {
|
|
1311
|
+
let dati;
|
|
1312
|
+
try {
|
|
1313
|
+
const value = JSON.parse(frame);
|
|
1314
|
+
const oggetto = record2(value);
|
|
1315
|
+
if (oggetto === null || typeof oggetto.t !== "string") return;
|
|
1316
|
+
dati = oggetto;
|
|
1317
|
+
} catch {
|
|
1318
|
+
return;
|
|
1319
|
+
}
|
|
1320
|
+
try {
|
|
1321
|
+
if (dati.t === "welcome") this.riceviWelcome(dati);
|
|
1322
|
+
else if (dati.t === "players") this.riceviGiocatori(dati.players);
|
|
1323
|
+
else if (dati.t === "status") this.riceviStatus(dati);
|
|
1324
|
+
else if (dati.t === "state") this.riceviDiff(dati);
|
|
1325
|
+
else if (dati.t === "snapshot") this.riceviSnapshot(dati);
|
|
1326
|
+
else if (dati.t === "msg") this.notifica(this.ascoltatoriMessaggi, copiaJson(dati.m));
|
|
1327
|
+
else if (dati.t === "pong") this.riceviPong(dati);
|
|
1328
|
+
else if (dati.t === "flush") this.richiediFlush();
|
|
1329
|
+
else if (dati.t === "voice") this.voice.ricevi(dati);
|
|
1330
|
+
} catch {
|
|
1331
|
+
if (dati.t === "state" || dati.t === "snapshot") this.chiediResync();
|
|
1332
|
+
}
|
|
1333
|
+
}
|
|
1334
|
+
riceviWelcome(dati) {
|
|
1335
|
+
const room = dati.room;
|
|
1336
|
+
if (room.id !== this.roomId) return;
|
|
1337
|
+
this.youCorrente = dati.you;
|
|
1338
|
+
this.hostCorrente = room.host;
|
|
1339
|
+
this.statusCorrente = room.status;
|
|
1340
|
+
this.giocatoriCorrenti = dati.players.map((player) => ({ ...player }));
|
|
1341
|
+
this.aggiornaStato(dati.state, room.tick, room.serverTime);
|
|
1342
|
+
this.scartoOrario = room.serverTime - this.input.ora();
|
|
1343
|
+
this.resyncRichiesto = false;
|
|
1344
|
+
this.welcomeRicevuto = true;
|
|
1345
|
+
if (!this.rosterRicevuto && this.timerRoster === null) {
|
|
1346
|
+
this.timerRoster = this.input.setTimeout(() => {
|
|
1347
|
+
this.timerRoster = null;
|
|
1348
|
+
this.rosterRicevuto = true;
|
|
1349
|
+
this.risolviProntaSePossibile();
|
|
1350
|
+
}, ATTESA_ROSTER);
|
|
1351
|
+
}
|
|
1352
|
+
this.ritardoIndice = 0;
|
|
1353
|
+
this.tempoRiconnessione = 0;
|
|
1354
|
+
this.notifica(this.ascoltatoriGiocatori, this.copiaGiocatori());
|
|
1355
|
+
this.voice.giocatoriCambiati();
|
|
1356
|
+
this.voice.socketRiconnesso();
|
|
1357
|
+
this.notifica(
|
|
1358
|
+
this.ascoltatoriStatus,
|
|
1359
|
+
this.statusCorrente,
|
|
1360
|
+
this.resultCorrente,
|
|
1361
|
+
room.serverTime
|
|
1362
|
+
);
|
|
1363
|
+
this.risolviProntaSePossibile();
|
|
1364
|
+
}
|
|
1365
|
+
riceviGiocatori(value) {
|
|
1366
|
+
this.giocatoriCorrenti = value.map((player) => ({ ...player }));
|
|
1367
|
+
if (!this.giocatoriCorrenti.some(
|
|
1368
|
+
(player) => player.id === this.hostCorrente && player.connected
|
|
1369
|
+
)) {
|
|
1370
|
+
this.hostCorrente = this.giocatoriCorrenti.find((player) => player.connected)?.id ?? null;
|
|
1371
|
+
}
|
|
1372
|
+
this.notifica(this.ascoltatoriGiocatori, this.copiaGiocatori());
|
|
1373
|
+
this.voice.giocatoriCambiati();
|
|
1374
|
+
}
|
|
1375
|
+
riceviStatus(dati) {
|
|
1376
|
+
this.statusCorrente = dati.status;
|
|
1377
|
+
this.resultCorrente = copiaJson(dati.result);
|
|
1378
|
+
if (dati.status === "ended") {
|
|
1379
|
+
this.terminata = true;
|
|
1380
|
+
this.voice.termina();
|
|
1381
|
+
this.fermaPing();
|
|
1382
|
+
this.fermaRiconnessione();
|
|
1383
|
+
}
|
|
1384
|
+
this.notifica(this.ascoltatoriStatus, this.statusCorrente, this.resultCorrente, dati.at);
|
|
1385
|
+
}
|
|
1386
|
+
riceviDiff(dati) {
|
|
1387
|
+
if (dati.base !== this.tickCorrente) {
|
|
1388
|
+
this.chiediResync();
|
|
1389
|
+
return;
|
|
1390
|
+
}
|
|
1391
|
+
const risultato = applicaPatch(this.statoSincronizzato, dati.patch);
|
|
1392
|
+
if (!risultato.ok) {
|
|
1393
|
+
this.chiediResync();
|
|
1394
|
+
return;
|
|
1395
|
+
}
|
|
1396
|
+
this.resyncRichiesto = false;
|
|
1397
|
+
this.aggiornaStato(risultato.state, dati.tick, dati.serverTime);
|
|
1398
|
+
}
|
|
1399
|
+
riceviSnapshot(dati) {
|
|
1400
|
+
if (dati.tick < this.tickCorrente) return;
|
|
1401
|
+
this.resyncRichiesto = false;
|
|
1402
|
+
this.aggiornaStato(dati.state, dati.tick, dati.serverTime);
|
|
1403
|
+
}
|
|
1404
|
+
aggiornaStato(state, tick, serverTime) {
|
|
1405
|
+
this.statoSincronizzato = copiaJson(state);
|
|
1406
|
+
this.statoPubblico = copiaJson(state);
|
|
1407
|
+
this.tickCorrente = tick;
|
|
1408
|
+
this.notifica(this.ascoltatoriStato, this.statoPubblico, tick, serverTime);
|
|
1409
|
+
}
|
|
1410
|
+
chiediResync() {
|
|
1411
|
+
if (this.resyncRichiesto || this.socket?.readyState !== APERTO) return;
|
|
1412
|
+
this.resyncRichiesto = true;
|
|
1413
|
+
try {
|
|
1414
|
+
this.invia({ t: "resync" });
|
|
1415
|
+
} catch {
|
|
1416
|
+
this.resyncRichiesto = false;
|
|
1417
|
+
}
|
|
1418
|
+
}
|
|
1419
|
+
riceviPong(dati) {
|
|
1420
|
+
this.scartoOrario = dati.s - (dati.c + this.input.ora()) / 2;
|
|
1421
|
+
}
|
|
1422
|
+
chiuso(code) {
|
|
1423
|
+
this.socket = null;
|
|
1424
|
+
this.welcomeRicevuto = false;
|
|
1425
|
+
this.fermaPing();
|
|
1426
|
+
if (CHIUSURE_DEFINITIVE.has(code)) {
|
|
1427
|
+
this.termina(code);
|
|
1428
|
+
return;
|
|
1429
|
+
}
|
|
1430
|
+
if (this.lasciata || this.terminata) return;
|
|
1431
|
+
this.voice.socketDisconnesso();
|
|
1432
|
+
this.programmaRiconnessione();
|
|
1433
|
+
}
|
|
1434
|
+
programmaRiconnessione() {
|
|
1435
|
+
if (this.terminata || this.lasciata || this.timerRiconnessione !== null) return;
|
|
1436
|
+
const indice = Math.min(this.ritardoIndice, RITARDI_RICONNESSIONE2.length - 1);
|
|
1437
|
+
const ritardo = RITARDI_RICONNESSIONE2[indice];
|
|
1438
|
+
if (this.tempoRiconnessione + ritardo > GRAZIA_RICONNESSIONE) {
|
|
1439
|
+
this.termina("timeout");
|
|
1440
|
+
return;
|
|
1441
|
+
}
|
|
1442
|
+
this.ritardoIndice++;
|
|
1443
|
+
this.tempoRiconnessione += ritardo;
|
|
1444
|
+
this.timerRiconnessione = this.input.setTimeout(() => {
|
|
1445
|
+
this.timerRiconnessione = null;
|
|
1446
|
+
void this.riconnetti();
|
|
1447
|
+
}, ritardo);
|
|
1448
|
+
}
|
|
1449
|
+
async riconnetti() {
|
|
1450
|
+
if (this.terminata || this.lasciata) return;
|
|
1451
|
+
try {
|
|
1452
|
+
const ingresso = await this.api.joinRoom(this.roomId);
|
|
1453
|
+
this.codice = ingresso.code;
|
|
1454
|
+
this.apri(ingresso.url);
|
|
1455
|
+
} catch {
|
|
1456
|
+
this.programmaRiconnessione();
|
|
1457
|
+
}
|
|
1458
|
+
}
|
|
1459
|
+
fermaRiconnessione() {
|
|
1460
|
+
if (this.timerRiconnessione === null) return;
|
|
1461
|
+
this.input.clearTimeout(this.timerRiconnessione);
|
|
1462
|
+
this.timerRiconnessione = null;
|
|
1463
|
+
}
|
|
1464
|
+
termina(code) {
|
|
1465
|
+
const risultato = { closed: code };
|
|
1466
|
+
const cambiato = this.statusCorrente !== "ended" || JSON.stringify(this.resultCorrente) !== JSON.stringify(risultato);
|
|
1467
|
+
this.terminata = true;
|
|
1468
|
+
this.statusCorrente = "ended";
|
|
1469
|
+
this.resultCorrente = risultato;
|
|
1470
|
+
this.voice.termina();
|
|
1471
|
+
this.fermaPing();
|
|
1472
|
+
this.fermaRiconnessione();
|
|
1473
|
+
if (cambiato) this.notifica(this.ascoltatoriStatus, "ended", risultato, this.serverTime());
|
|
1474
|
+
if (!this.prontaRisolta) {
|
|
1475
|
+
this.prontaRisolta = true;
|
|
1476
|
+
const codici = {
|
|
1477
|
+
4003: "kicked",
|
|
1478
|
+
4004: "room_ended",
|
|
1479
|
+
4005: "version_closed",
|
|
1480
|
+
4006: "replaced"
|
|
1481
|
+
};
|
|
1482
|
+
const erroreCode = typeof code === "number" ? codici[code] ?? "offline" : "offline";
|
|
1483
|
+
this.rifiutaPronta(creaErrore(erroreCode, "The room connection ended."));
|
|
1484
|
+
}
|
|
1485
|
+
}
|
|
1486
|
+
risolviProntaSePossibile() {
|
|
1487
|
+
if (this.prontaRisolta || !this.welcomeRicevuto || !this.rosterRicevuto) return;
|
|
1488
|
+
if (this.timerRoster !== null) {
|
|
1489
|
+
this.input.clearTimeout(this.timerRoster);
|
|
1490
|
+
this.timerRoster = null;
|
|
1491
|
+
}
|
|
1492
|
+
this.prontaRisolta = true;
|
|
1493
|
+
this.risolviPronta();
|
|
1494
|
+
}
|
|
1495
|
+
richiediFlush() {
|
|
1496
|
+
this.flushRichiesto = true;
|
|
1497
|
+
if (this.flushInCorso || this.timerFlush !== null) return;
|
|
1498
|
+
this.timerFlush = this.input.setTimeout(() => {
|
|
1499
|
+
this.timerFlush = null;
|
|
1500
|
+
void this.eseguiFlush();
|
|
1501
|
+
}, RITARDO_FLUSH);
|
|
1502
|
+
}
|
|
1503
|
+
async eseguiFlush() {
|
|
1504
|
+
if (this.flushInCorso || !this.flushRichiesto) return;
|
|
1505
|
+
this.flushInCorso = true;
|
|
1506
|
+
this.flushRichiesto = false;
|
|
1507
|
+
try {
|
|
1508
|
+
await this.api.flush(this.roomId);
|
|
1509
|
+
} catch {
|
|
1510
|
+
} finally {
|
|
1511
|
+
this.flushInCorso = false;
|
|
1512
|
+
if (this.flushRichiesto) this.richiediFlush();
|
|
1513
|
+
}
|
|
1514
|
+
}
|
|
1515
|
+
};
|
|
1516
|
+
function creaStanzeOffline(invited = null) {
|
|
1517
|
+
return {
|
|
1518
|
+
invited,
|
|
1519
|
+
async create() {
|
|
1520
|
+
throw erroreOffline();
|
|
1521
|
+
},
|
|
1522
|
+
async join() {
|
|
1523
|
+
throw erroreOffline();
|
|
1524
|
+
}
|
|
1525
|
+
};
|
|
1526
|
+
}
|
|
1527
|
+
function creaGestoreStanze(input, invited) {
|
|
1528
|
+
const api = creaApiLive(input);
|
|
1529
|
+
const collega = async (ingresso) => {
|
|
1530
|
+
const stanza = new StanzaClient(ingresso.roomId, ingresso.code, ingresso.url, input, api);
|
|
1531
|
+
await stanza.pronta();
|
|
1532
|
+
return stanza;
|
|
1533
|
+
};
|
|
1534
|
+
return {
|
|
1535
|
+
invited,
|
|
1536
|
+
async create(options) {
|
|
1537
|
+
return collega(await api.create(options.mode));
|
|
1538
|
+
},
|
|
1539
|
+
async join(code) {
|
|
1540
|
+
const scelto = code ?? invited;
|
|
1541
|
+
if (scelto === null || scelto === void 0 || scelto.length === 0) {
|
|
1542
|
+
throw creaErrore("invalid_request", "A room invitation code is required.");
|
|
1543
|
+
}
|
|
1544
|
+
return collega(await api.joinCode(scelto));
|
|
1545
|
+
}
|
|
1546
|
+
};
|
|
1547
|
+
}
|
|
1548
|
+
|
|
233
1549
|
// src/standalone.ts
|
|
234
1550
|
var PREFISSO = "caisual:save:";
|
|
235
1551
|
var CHIAVE_VALIDA = /^[a-z0-9][a-z0-9_-]{0,31}$/;
|
|
@@ -292,7 +1608,7 @@ function creaSave(archivio, ora) {
|
|
|
292
1608
|
}
|
|
293
1609
|
};
|
|
294
1610
|
}
|
|
295
|
-
async function creaStandalone(input) {
|
|
1611
|
+
async function creaStandalone(input, invited = null) {
|
|
296
1612
|
const day = giornoUtc(input.ora());
|
|
297
1613
|
const seed = await calcolaSeed(input.hostname, day, input.subtle);
|
|
298
1614
|
return {
|
|
@@ -308,7 +1624,8 @@ async function creaStandalone(input) {
|
|
|
308
1624
|
async top(_board, opzioni = {}) {
|
|
309
1625
|
return { day: opzioni.daily ? day : null, entries: [], me: null };
|
|
310
1626
|
}
|
|
311
|
-
}
|
|
1627
|
+
},
|
|
1628
|
+
room: creaStanzeOffline(invited)
|
|
312
1629
|
};
|
|
313
1630
|
}
|
|
314
1631
|
|
|
@@ -330,7 +1647,7 @@ function archivioReale() {
|
|
|
330
1647
|
return null;
|
|
331
1648
|
}
|
|
332
1649
|
}
|
|
333
|
-
function
|
|
1650
|
+
function dipendenzeReali2() {
|
|
334
1651
|
return {
|
|
335
1652
|
finestra: typeof window === "undefined" ? null : window,
|
|
336
1653
|
documento: typeof document === "undefined" ? null : document,
|
|
@@ -358,7 +1675,8 @@ async function connetti(input) {
|
|
|
358
1675
|
handshake.porta,
|
|
359
1676
|
input.finestra,
|
|
360
1677
|
input.ora,
|
|
361
|
-
input.timeoutRinnovo
|
|
1678
|
+
input.timeoutRinnovo,
|
|
1679
|
+
"portal"
|
|
362
1680
|
);
|
|
363
1681
|
const api = creaClienteApi(appOrigin, input.fetcher, biglietto);
|
|
364
1682
|
const prima = input.ora();
|
|
@@ -366,10 +1684,34 @@ async function connetti(input) {
|
|
|
366
1684
|
try {
|
|
367
1685
|
me = await api.me();
|
|
368
1686
|
} catch {
|
|
369
|
-
return creaStandalone(input);
|
|
1687
|
+
return creaStandalone(input, handshake.invite);
|
|
370
1688
|
}
|
|
371
1689
|
const dopo = input.ora();
|
|
372
1690
|
const scartoOrario = me.serverTime - (prima + dopo) / 2;
|
|
1691
|
+
const room = handshake.live === null ? creaStanzeOffline(handshake.invite) : creaGestoreStanze({
|
|
1692
|
+
appOrigin,
|
|
1693
|
+
liveOrigin: handshake.live,
|
|
1694
|
+
fetcher: input.fetcher,
|
|
1695
|
+
biglietto: creaGestoreBiglietto(
|
|
1696
|
+
null,
|
|
1697
|
+
handshake.porta,
|
|
1698
|
+
input.finestra,
|
|
1699
|
+
input.ora,
|
|
1700
|
+
input.timeoutRinnovo,
|
|
1701
|
+
"live"
|
|
1702
|
+
),
|
|
1703
|
+
apriSocket(url) {
|
|
1704
|
+
if (input.apriSocket !== void 0) return input.apriSocket(url);
|
|
1705
|
+
if (typeof WebSocket === "undefined") throw erroreOffline();
|
|
1706
|
+
return new WebSocket(url);
|
|
1707
|
+
},
|
|
1708
|
+
ora: input.ora,
|
|
1709
|
+
setTimeout: (handler, timeout) => globalThis.setTimeout(handler, timeout),
|
|
1710
|
+
clearTimeout: (id) => globalThis.clearTimeout(id),
|
|
1711
|
+
setInterval: (handler, timeout) => globalThis.setInterval(handler, timeout),
|
|
1712
|
+
clearInterval: (id) => globalThis.clearInterval(id),
|
|
1713
|
+
voce: input.voce
|
|
1714
|
+
}, handshake.invite);
|
|
373
1715
|
return {
|
|
374
1716
|
connected: true,
|
|
375
1717
|
player: me.player,
|
|
@@ -391,10 +1733,11 @@ async function connetti(input) {
|
|
|
391
1733
|
}
|
|
392
1734
|
},
|
|
393
1735
|
top: (board, opzioni = {}) => api.boardTop(board, opzioni)
|
|
394
|
-
}
|
|
1736
|
+
},
|
|
1737
|
+
room
|
|
395
1738
|
};
|
|
396
1739
|
}
|
|
397
|
-
function creaKit(input =
|
|
1740
|
+
function creaKit(input = dipendenzeReali2()) {
|
|
398
1741
|
let promessa = null;
|
|
399
1742
|
return {
|
|
400
1743
|
connect() {
|