@raucheacho/phono-web 0.0.0-stage → 0.1.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/LICENSE +21 -0
- package/README.md +41 -2
- package/assets/goul-audio.wasm +0 -0
- package/assets/goul-ptt-worklets.js +256 -0
- package/dist/announcements.d.ts +23 -0
- package/dist/audio.d.ts +79 -0
- package/dist/client.d.ts +265 -0
- package/dist/index.d.ts +8 -0
- package/dist/index.js +1204 -0
- package/dist/phone.d.ts +110 -0
- package/dist/react.d.ts +13 -0
- package/dist/react.js +18 -0
- package/dist/realtime.d.ts +39 -0
- package/dist/talkie.d.ts +85 -0
- package/dist/tones.d.ts +14 -0
- package/dist/types.d.ts +284 -0
- package/dist/types.js +0 -0
- package/package.json +53 -4
- package/src/announcements.ts +57 -0
- package/src/audio.ts +313 -0
- package/src/client.ts +433 -0
- package/src/index.ts +13 -0
- package/src/phone.ts +340 -0
- package/src/react.ts +34 -0
- package/src/realtime.ts +174 -0
- package/src/talkie.ts +342 -0
- package/src/tones.ts +58 -0
- package/src/types.ts +339 -0
package/src/phone.ts
ADDED
|
@@ -0,0 +1,340 @@
|
|
|
1
|
+
import { announcementForEnd, playAnnouncement, type AnnouncementFiles } from "./announcements";
|
|
2
|
+
import { CallAudio, type CallAudioSnapshot, type TalkMode } from "./audio";
|
|
3
|
+
import { PhonoError, type Phono } from "./client";
|
|
4
|
+
import { ringback, ringtone, titleAlert } from "./tones";
|
|
5
|
+
import type { AnnouncementCode, Call, CallEnvelope, PhonoEvent, PublicHandle } from "./types";
|
|
6
|
+
|
|
7
|
+
export interface PhoneCall {
|
|
8
|
+
call: Call;
|
|
9
|
+
direction: "incoming" | "outgoing";
|
|
10
|
+
/** Qui est en face, prêt à afficher. */
|
|
11
|
+
peer: string;
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
export interface PhoneState {
|
|
15
|
+
/** L'identité de ce téléphone, une fois `start()` fait. */
|
|
16
|
+
identity: PublicHandle | null;
|
|
17
|
+
ready: boolean;
|
|
18
|
+
/** Les appels qui sonnent ici et attendent qu'on décroche. */
|
|
19
|
+
ringing: PhoneCall[];
|
|
20
|
+
/** L'appel en cours : il sonne chez l'autre, ou on parle. */
|
|
21
|
+
current: PhoneCall | null;
|
|
22
|
+
/** Le dernier appel terminé, pour afficher « Appel terminé ». */
|
|
23
|
+
ended: PhoneCall | null;
|
|
24
|
+
audio: CallAudioSnapshot | null;
|
|
25
|
+
mode: TalkMode;
|
|
26
|
+
error: string | null;
|
|
27
|
+
/**
|
|
28
|
+
* L'appel n'a pas abouti : l'annonce d'opérateur en cours (`busy`,
|
|
29
|
+
* `unavailable`, `not_assigned`), le temps qu'elle se joue. Votre écran
|
|
30
|
+
* peut l'afficher (« Occupé »), même avec `announcements: false`.
|
|
31
|
+
*/
|
|
32
|
+
announcement: AnnouncementCode | null;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
export interface PhoneOptions {
|
|
36
|
+
/** « open » : micro ouvert, comme un téléphone (défaut). « ptt » : appuyer pour parler. */
|
|
37
|
+
mode?: TalkMode;
|
|
38
|
+
/** Jouer la sonnerie et la tonalité de retour. Vrai par défaut. */
|
|
39
|
+
tones?: boolean;
|
|
40
|
+
/** Faire clignoter le titre de l'onglet pendant qu'un appel sonne. Vrai par défaut. */
|
|
41
|
+
titleAlert?: boolean;
|
|
42
|
+
/**
|
|
43
|
+
* Les annonces d'opérateur quand un appel n'aboutit pas. Vrai par défaut :
|
|
44
|
+
* celles de votre organisation, sinon celles de Phono. Vos propres fichiers
|
|
45
|
+
* par code (`{ busy: "/sons/occupe.mp3" }`) ; `false` pour n'en jouer aucune.
|
|
46
|
+
*/
|
|
47
|
+
announcements?: boolean | AnnouncementFiles;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
type Listener = (state: PhoneState) => void;
|
|
51
|
+
|
|
52
|
+
/**
|
|
53
|
+
* Un téléphone dans le navigateur, au nom d'une identité : il sonne, appelle,
|
|
54
|
+
* décroche, parle.
|
|
55
|
+
*
|
|
56
|
+
* ```ts
|
|
57
|
+
* const phone = phono.phone();
|
|
58
|
+
* phone.subscribe((s) => render(s));
|
|
59
|
+
* await phone.start();
|
|
60
|
+
* button.onclick = () => phone.dial("jean.acme");
|
|
61
|
+
* ```
|
|
62
|
+
*
|
|
63
|
+
* `dial()` et `answer()` doivent venir d'un geste (un clic) : c'est ce qui
|
|
64
|
+
* autorise le navigateur à jouer du son et à demander le micro.
|
|
65
|
+
*/
|
|
66
|
+
export class Phone {
|
|
67
|
+
private state: PhoneState;
|
|
68
|
+
private listeners = new Set<Listener>();
|
|
69
|
+
private audio: CallAudio | null = null;
|
|
70
|
+
private unsubscribers: Array<() => void> = [];
|
|
71
|
+
private stopTone: (() => void) | null = null;
|
|
72
|
+
private toneKind: "ring" | "ringback" | null = null;
|
|
73
|
+
private stopTitle: (() => void) | null = null;
|
|
74
|
+
private starting: Promise<void> | null = null;
|
|
75
|
+
private announcementUrls: AnnouncementFiles = {};
|
|
76
|
+
private stopAnnouncement: (() => void) | null = null;
|
|
77
|
+
|
|
78
|
+
constructor(
|
|
79
|
+
readonly phono: Phono,
|
|
80
|
+
private readonly options: PhoneOptions = {}
|
|
81
|
+
) {
|
|
82
|
+
this.state = {
|
|
83
|
+
identity: null,
|
|
84
|
+
ready: false,
|
|
85
|
+
ringing: [],
|
|
86
|
+
current: null,
|
|
87
|
+
ended: null,
|
|
88
|
+
audio: null,
|
|
89
|
+
mode: options.mode ?? "open",
|
|
90
|
+
error: null,
|
|
91
|
+
announcement: null,
|
|
92
|
+
};
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
getState(): PhoneState {
|
|
96
|
+
return this.state;
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
subscribe(listener: Listener): () => void {
|
|
100
|
+
this.listeners.add(listener);
|
|
101
|
+
listener(this.state);
|
|
102
|
+
return () => this.listeners.delete(listener);
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
/** Charge l'identité, écoute les sonneries, et reprend un appel qui sonnait déjà. */
|
|
106
|
+
start(): Promise<void> {
|
|
107
|
+
this.starting ??= (async () => {
|
|
108
|
+
const { handle: identity } = await this.phono.me();
|
|
109
|
+
this.set({ identity });
|
|
110
|
+
if (this.options.announcements !== false) {
|
|
111
|
+
const lang = typeof navigator === "undefined" ? undefined : navigator.language;
|
|
112
|
+
const list = await this.phono.announcements(lang).catch(() => null);
|
|
113
|
+
for (const a of Object.values(list?.announcements ?? {})) this.announcementUrls[a.code] = a.url;
|
|
114
|
+
}
|
|
115
|
+
const rt = this.phono.realtime();
|
|
116
|
+
for (const type of ["call.ringing", "call.updated", "call.answered", "call.ended"] as const) {
|
|
117
|
+
this.unsubscribers.push(rt.on<Call>(type, (ev) => this.onEvent(ev)));
|
|
118
|
+
}
|
|
119
|
+
await rt.ready();
|
|
120
|
+
// Un appel qui sonnait avant que la page s'ouvre.
|
|
121
|
+
const recent = await this.phono.calls.list({ limit: 10 }).catch(() => [] as Call[]);
|
|
122
|
+
for (const call of recent) {
|
|
123
|
+
if (call.status === "ringing" && this.mine(call)?.state === "invited") this.addRinging(call);
|
|
124
|
+
}
|
|
125
|
+
this.set({ ready: true });
|
|
126
|
+
})().catch((err) => {
|
|
127
|
+
this.starting = null;
|
|
128
|
+
this.fail(err);
|
|
129
|
+
throw err;
|
|
130
|
+
});
|
|
131
|
+
return this.starting;
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
/** Appeler une identité (`jean.acme`). */
|
|
135
|
+
async dial(to: string): Promise<void> {
|
|
136
|
+
if (this.state.current) return;
|
|
137
|
+
this.endAnnouncement();
|
|
138
|
+
await this.start();
|
|
139
|
+
try {
|
|
140
|
+
const res = await this.phono.calls.create({ to: to.replace(/^@/, "") });
|
|
141
|
+
this.set({ current: this.describe(res.call, "outgoing"), ended: null, error: null });
|
|
142
|
+
await this.joinAudio(res);
|
|
143
|
+
} catch (err) {
|
|
144
|
+
this.fail(err);
|
|
145
|
+
if (err instanceof PhonoError && err.announcement) this.announce(err.announcement.code, err.announcement.url);
|
|
146
|
+
}
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
/** Décrocher. Sans argument : le premier appel qui sonne. */
|
|
150
|
+
async answer(callId?: string): Promise<void> {
|
|
151
|
+
if (this.state.current) return;
|
|
152
|
+
const r = callId ? this.state.ringing.find((x) => x.call.id === callId) : this.state.ringing[0];
|
|
153
|
+
if (!r) return;
|
|
154
|
+
try {
|
|
155
|
+
const res = await this.phono.calls.answer(r.call.id);
|
|
156
|
+
this.removeRinging(r.call.id);
|
|
157
|
+
this.set({ current: { ...r, call: res.call }, ended: null, error: null });
|
|
158
|
+
await this.joinAudio(res);
|
|
159
|
+
} catch (err) {
|
|
160
|
+
this.removeRinging(r.call.id);
|
|
161
|
+
// Le plus souvent : quelqu'un d'autre a décroché la même ligne avant.
|
|
162
|
+
if (err instanceof PhonoError && err.code === "invalid_state") {
|
|
163
|
+
this.set({ error: "Cet appel a déjà été pris." });
|
|
164
|
+
} else {
|
|
165
|
+
this.fail(err);
|
|
166
|
+
}
|
|
167
|
+
}
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
/** Refuser. Sans argument : le premier appel qui sonne. */
|
|
171
|
+
async reject(callId?: string): Promise<void> {
|
|
172
|
+
const r = callId ? this.state.ringing.find((x) => x.call.id === callId) : this.state.ringing[0];
|
|
173
|
+
if (!r) return;
|
|
174
|
+
this.removeRinging(r.call.id);
|
|
175
|
+
await this.phono.calls.reject(r.call.id).catch(() => {});
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
/** Raccrocher — ou annuler un appel qui sonne encore chez l'autre. */
|
|
179
|
+
async hangup(): Promise<void> {
|
|
180
|
+
this.endAnnouncement();
|
|
181
|
+
const cur = this.state.current;
|
|
182
|
+
if (!cur) return;
|
|
183
|
+
this.endAudio(cur);
|
|
184
|
+
await this.phono.calls.hangup(cur.call.id).catch(() => {});
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
setMuted(muted: boolean): void {
|
|
188
|
+
this.audio?.setMuted(muted);
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
setMode(mode: TalkMode): void {
|
|
192
|
+
this.set({ mode });
|
|
193
|
+
this.audio?.setMode(mode);
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
/** Appuyer pour parler (mode « ptt »). */
|
|
197
|
+
press(): void {
|
|
198
|
+
this.audio?.press();
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
release(): void {
|
|
202
|
+
this.audio?.release();
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
clearError(): void {
|
|
206
|
+
this.set({ error: null });
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
/** Couper l'annonce d'opérateur en cours. */
|
|
210
|
+
endAnnouncement(): void {
|
|
211
|
+
this.stopAnnouncement?.();
|
|
212
|
+
this.stopAnnouncement = null;
|
|
213
|
+
if (this.state.announcement) this.set({ announcement: null });
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
/** Coupe tout : l'appel en cours, l'écoute, les sonneries. */
|
|
217
|
+
destroy(): void {
|
|
218
|
+
this.audio?.stop();
|
|
219
|
+
this.audio = null;
|
|
220
|
+
this.endAnnouncement();
|
|
221
|
+
this.unsubscribers.forEach((u) => u());
|
|
222
|
+
this.unsubscribers = [];
|
|
223
|
+
this.syncAlerts(true);
|
|
224
|
+
this.listeners.clear();
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
// --- l'intérieur ---------------------------------------------------------------
|
|
228
|
+
|
|
229
|
+
private onEvent(ev: PhonoEvent<Call>): void {
|
|
230
|
+
const call = ev.data;
|
|
231
|
+
const mine = this.mine(call);
|
|
232
|
+
if (ev.type === "call.ringing" || ev.type === "call.updated") {
|
|
233
|
+
if (mine?.state === "invited" && call.status === "ringing") this.addRinging(call);
|
|
234
|
+
else this.removeRinging(call.id);
|
|
235
|
+
}
|
|
236
|
+
if (ev.type === "call.answered" || ev.type === "call.ended") this.removeRinging(call.id);
|
|
237
|
+
|
|
238
|
+
const cur = this.state.current;
|
|
239
|
+
if (cur && cur.call.id === call.id) {
|
|
240
|
+
if (ev.type === "call.ended") {
|
|
241
|
+
this.endAudio({ ...cur, call });
|
|
242
|
+
// Pas de réponse, ou refusé : l'appelant l'entend comme au téléphone.
|
|
243
|
+
const code = cur.direction === "outgoing" ? announcementForEnd(call) : null;
|
|
244
|
+
if (code) this.announce(code);
|
|
245
|
+
} else this.set({ current: { ...cur, call } });
|
|
246
|
+
}
|
|
247
|
+
}
|
|
248
|
+
|
|
249
|
+
/** Joue l'annonce : votre fichier, sinon celle de l'organisation. */
|
|
250
|
+
private announce(code: AnnouncementCode, fallbackUrl?: string): void {
|
|
251
|
+
this.endAnnouncement();
|
|
252
|
+
this.set({ announcement: code });
|
|
253
|
+
const own = typeof this.options.announcements === "object" ? this.options.announcements[code] : undefined;
|
|
254
|
+
const url = own ?? this.announcementUrls[code] ?? fallbackUrl;
|
|
255
|
+
if (this.options.announcements === false || !url) {
|
|
256
|
+
// Rien à jouer : l'état reste le temps qu'une annonce durerait.
|
|
257
|
+
const t = setTimeout(() => this.state.announcement === code && this.set({ announcement: null }), 5000);
|
|
258
|
+
this.stopAnnouncement = () => clearTimeout(t);
|
|
259
|
+
return;
|
|
260
|
+
}
|
|
261
|
+
const playing = playAnnouncement(url);
|
|
262
|
+
this.stopAnnouncement = playing.stop;
|
|
263
|
+
void playing.done.then(() => {
|
|
264
|
+
if (this.stopAnnouncement !== playing.stop) return;
|
|
265
|
+
this.stopAnnouncement = null;
|
|
266
|
+
this.set({ announcement: null });
|
|
267
|
+
});
|
|
268
|
+
}
|
|
269
|
+
|
|
270
|
+
private async joinAudio(res: CallEnvelope): Promise<void> {
|
|
271
|
+
if (!res.audio) return;
|
|
272
|
+
const audio = new CallAudio(res.audio, this.state.mode, this.phono.options.audio);
|
|
273
|
+
this.audio = audio;
|
|
274
|
+
audio.subscribe((a) => this.set({ audio: a }));
|
|
275
|
+
await audio.start();
|
|
276
|
+
}
|
|
277
|
+
|
|
278
|
+
private endAudio(ended: PhoneCall): void {
|
|
279
|
+
this.audio?.stop();
|
|
280
|
+
this.audio = null;
|
|
281
|
+
this.set({ audio: null, current: null, ended });
|
|
282
|
+
}
|
|
283
|
+
|
|
284
|
+
private mine(call: Call) {
|
|
285
|
+
const id = this.state.identity?.id;
|
|
286
|
+
return call.participants.find((p) => p.handle.id === id);
|
|
287
|
+
}
|
|
288
|
+
|
|
289
|
+
private describe(call: Call, direction: PhoneCall["direction"]): PhoneCall {
|
|
290
|
+
const id = this.state.identity?.id;
|
|
291
|
+
const others = call.participants.filter((p) => p.handle.id !== id);
|
|
292
|
+
const peer = others.map((p) => p.handle.display_name || `@${p.handle.handle}`).join(", ") || "—";
|
|
293
|
+
return { call, direction, peer };
|
|
294
|
+
}
|
|
295
|
+
|
|
296
|
+
private addRinging(call: Call): void {
|
|
297
|
+
if (this.state.ringing.some((r) => r.call.id === call.id)) return;
|
|
298
|
+
this.set({ ringing: [...this.state.ringing, this.describe(call, "incoming")] });
|
|
299
|
+
}
|
|
300
|
+
|
|
301
|
+
private removeRinging(callId: string): void {
|
|
302
|
+
if (!this.state.ringing.some((r) => r.call.id === callId)) return;
|
|
303
|
+
this.set({ ringing: this.state.ringing.filter((r) => r.call.id !== callId) });
|
|
304
|
+
}
|
|
305
|
+
|
|
306
|
+
private fail(err: unknown): void {
|
|
307
|
+
this.set({ error: (err as { message?: string })?.message ?? "Une erreur est survenue" });
|
|
308
|
+
}
|
|
309
|
+
|
|
310
|
+
private set(patch: Partial<PhoneState>): void {
|
|
311
|
+
this.state = { ...this.state, ...patch };
|
|
312
|
+
this.syncAlerts(false);
|
|
313
|
+
this.listeners.forEach((l) => l(this.state));
|
|
314
|
+
}
|
|
315
|
+
|
|
316
|
+
/** Sonnerie, tonalité de retour et titre suivent l'état. */
|
|
317
|
+
private syncAlerts(off: boolean): void {
|
|
318
|
+
const { ringing, current } = this.state;
|
|
319
|
+
const want: typeof this.toneKind = off
|
|
320
|
+
? null
|
|
321
|
+
: ringing.length > 0 && !current
|
|
322
|
+
? "ring"
|
|
323
|
+
: current?.direction === "outgoing" && current.call.status === "ringing"
|
|
324
|
+
? "ringback"
|
|
325
|
+
: null;
|
|
326
|
+
if (this.options.tones !== false && want !== this.toneKind) {
|
|
327
|
+
this.stopTone?.();
|
|
328
|
+
this.stopTone = want === "ring" ? ringtone() : want === "ringback" ? ringback() : null;
|
|
329
|
+
}
|
|
330
|
+
this.toneKind = want;
|
|
331
|
+
|
|
332
|
+
const title = want === "ring" && this.options.titleAlert !== false ? `📞 ${ringing[0]?.peer}` : null;
|
|
333
|
+
if (!title) {
|
|
334
|
+
this.stopTitle?.();
|
|
335
|
+
this.stopTitle = null;
|
|
336
|
+
} else if (!this.stopTitle) {
|
|
337
|
+
this.stopTitle = titleAlert(title);
|
|
338
|
+
}
|
|
339
|
+
}
|
|
340
|
+
}
|
package/src/react.ts
ADDED
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
import { useEffect, useRef, useSyncExternalStore } from "react";
|
|
2
|
+
|
|
3
|
+
import type { Phono } from "./client";
|
|
4
|
+
import type { Phone, PhoneState } from "./phone";
|
|
5
|
+
import type { EventType, PhonoEvent } from "./types";
|
|
6
|
+
|
|
7
|
+
/**
|
|
8
|
+
* L'état d'un téléphone, qui se met à jour tout seul.
|
|
9
|
+
*
|
|
10
|
+
* ```tsx
|
|
11
|
+
* const { ringing, current } = usePhone(phone);
|
|
12
|
+
* ```
|
|
13
|
+
*/
|
|
14
|
+
export function usePhone(phone: Phone): PhoneState {
|
|
15
|
+
return useSyncExternalStore(
|
|
16
|
+
(cb) => phone.subscribe(cb),
|
|
17
|
+
() => phone.getState(),
|
|
18
|
+
() => phone.getState()
|
|
19
|
+
);
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
/** Un événement temps réel, tant que le composant est monté. */
|
|
23
|
+
export function usePhonoEvent<T = unknown>(
|
|
24
|
+
phono: Phono | null,
|
|
25
|
+
type: EventType | "*",
|
|
26
|
+
handler: (event: PhonoEvent<T>) => void
|
|
27
|
+
): void {
|
|
28
|
+
const ref = useRef(handler);
|
|
29
|
+
ref.current = handler;
|
|
30
|
+
useEffect(() => {
|
|
31
|
+
if (!phono) return;
|
|
32
|
+
return phono.realtime().on<T>(type, (ev) => ref.current(ev));
|
|
33
|
+
}, [phono, type]);
|
|
34
|
+
}
|
package/src/realtime.ts
ADDED
|
@@ -0,0 +1,174 @@
|
|
|
1
|
+
import { KonetClient } from "@raucheacho/konet-js";
|
|
2
|
+
|
|
3
|
+
import type { Phono } from "./client";
|
|
4
|
+
import type { EventType, PhonoEvent } from "./types";
|
|
5
|
+
|
|
6
|
+
type Handler = (event: PhonoEvent) => void;
|
|
7
|
+
|
|
8
|
+
export type RealtimeStatus = "connecting" | "connected" | "reconnecting" | "closed";
|
|
9
|
+
|
|
10
|
+
/** Tous les événements qu'une identité reçoit. */
|
|
11
|
+
const EVENTS: EventType[] = [
|
|
12
|
+
"message.created",
|
|
13
|
+
"message.transcribed",
|
|
14
|
+
"message.read",
|
|
15
|
+
"message.reacted",
|
|
16
|
+
"conversation.activity",
|
|
17
|
+
"message.updated",
|
|
18
|
+
"message.deleted",
|
|
19
|
+
"message.delivered",
|
|
20
|
+
"conversation.transferred",
|
|
21
|
+
"group.updated",
|
|
22
|
+
"call.ringing",
|
|
23
|
+
"call.updated",
|
|
24
|
+
"call.answered",
|
|
25
|
+
"call.ended",
|
|
26
|
+
"call.transcribed",
|
|
27
|
+
"contact.requested",
|
|
28
|
+
"contact.accepted",
|
|
29
|
+
"channel.updated",
|
|
30
|
+
"channel.deleted",
|
|
31
|
+
"channel.floor",
|
|
32
|
+
"channel.invited",
|
|
33
|
+
"transmission.created",
|
|
34
|
+
"transmission.transcribed",
|
|
35
|
+
];
|
|
36
|
+
|
|
37
|
+
/**
|
|
38
|
+
* Les événements d'une identité, en direct : sa boîte de réception Konet.
|
|
39
|
+
*
|
|
40
|
+
* ```ts
|
|
41
|
+
* phono.realtime().on("message.created", (ev) => console.log(ev.data));
|
|
42
|
+
* ```
|
|
43
|
+
*
|
|
44
|
+
* La connexion s'ouvre au premier `on()`. Son jeton est renouvelé avant
|
|
45
|
+
* d'expirer ; si elle est perdue pour de bon (réseau coupé longtemps), un
|
|
46
|
+
* nouveau jeton est demandé et elle repart.
|
|
47
|
+
*/
|
|
48
|
+
export class Realtime {
|
|
49
|
+
private handlers = new Map<string, Set<Handler>>();
|
|
50
|
+
private statusHandlers = new Set<(s: RealtimeStatus) => void>();
|
|
51
|
+
private client: KonetClient | null = null;
|
|
52
|
+
private opening: Promise<void> | null = null;
|
|
53
|
+
private closed = false;
|
|
54
|
+
private retryTimer: ReturnType<typeof setTimeout> | null = null;
|
|
55
|
+
private renewTimer: ReturnType<typeof setTimeout> | null = null;
|
|
56
|
+
status: RealtimeStatus = "connecting";
|
|
57
|
+
|
|
58
|
+
constructor(private readonly phono: Phono) {}
|
|
59
|
+
|
|
60
|
+
/** `type` : un type d'événement, ou `*` pour tous. Rend de quoi se désabonner. */
|
|
61
|
+
on<T = unknown>(type: EventType | "*", handler: (event: PhonoEvent<T>) => void): () => void {
|
|
62
|
+
let set = this.handlers.get(type);
|
|
63
|
+
if (!set) this.handlers.set(type, (set = new Set()));
|
|
64
|
+
set.add(handler as Handler);
|
|
65
|
+
void this.open();
|
|
66
|
+
return () => set.delete(handler as Handler);
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
onStatus(handler: (s: RealtimeStatus) => void): () => void {
|
|
70
|
+
this.statusHandlers.add(handler);
|
|
71
|
+
handler(this.status);
|
|
72
|
+
return () => this.statusHandlers.delete(handler);
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
/** Attend que la boîte soit rejointe. */
|
|
76
|
+
ready(): Promise<void> {
|
|
77
|
+
return this.open();
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
/** À appeler quand l'onglet revient au premier plan : vérifie la connexion. */
|
|
81
|
+
check(): void {
|
|
82
|
+
this.client?.checkConnection();
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
close(): void {
|
|
86
|
+
this.closed = true;
|
|
87
|
+
if (this.retryTimer) clearTimeout(this.retryTimer);
|
|
88
|
+
if (this.renewTimer) clearTimeout(this.renewTimer);
|
|
89
|
+
this.client?.disconnect();
|
|
90
|
+
this.client = null;
|
|
91
|
+
this.setStatus("closed");
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
private open(): Promise<void> {
|
|
95
|
+
if (this.closed) return Promise.resolve();
|
|
96
|
+
this.opening ??= this.connect().catch((err) => {
|
|
97
|
+
this.opening = null;
|
|
98
|
+
this.scheduleRetry();
|
|
99
|
+
throw err;
|
|
100
|
+
});
|
|
101
|
+
return this.opening;
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
private async connect(): Promise<void> {
|
|
105
|
+
this.setStatus("connecting");
|
|
106
|
+
const rt = await this.phono.request<{ url: string; token: string; topic: string; expires_at?: string }>(
|
|
107
|
+
"/v1/realtime"
|
|
108
|
+
);
|
|
109
|
+
if (this.closed) return;
|
|
110
|
+
|
|
111
|
+
// Le jeton vit dans le constructeur du client : le renouveler, c'est
|
|
112
|
+
// remplacer le client, un peu avant qu'il n'expire.
|
|
113
|
+
const previous = this.client;
|
|
114
|
+
const client = new KonetClient(rt.url, { token: rt.token }).connect();
|
|
115
|
+
this.client = client;
|
|
116
|
+
previous?.disconnect();
|
|
117
|
+
if (rt.expires_at) {
|
|
118
|
+
const lifetime = new Date(rt.expires_at).getTime() - Date.now();
|
|
119
|
+
if (this.renewTimer) clearTimeout(this.renewTimer);
|
|
120
|
+
this.renewTimer = setTimeout(
|
|
121
|
+
() => {
|
|
122
|
+
this.opening = this.connect().catch(() => this.scheduleRetry());
|
|
123
|
+
},
|
|
124
|
+
Math.max(30_000, lifetime - 5 * 60_000)
|
|
125
|
+
);
|
|
126
|
+
}
|
|
127
|
+
client.onStatus((s) => {
|
|
128
|
+
if (client !== this.client) return;
|
|
129
|
+
if (s.state === "connected") this.setStatus("connected");
|
|
130
|
+
else if (s.state === "reconnecting") this.setStatus("reconnecting");
|
|
131
|
+
else if (s.state === "failed" && !this.closed) {
|
|
132
|
+
// Le jeton a peut-être expiré : on repart de zéro, avec un neuf.
|
|
133
|
+
client.disconnect();
|
|
134
|
+
this.client = null;
|
|
135
|
+
this.opening = null;
|
|
136
|
+
this.scheduleRetry();
|
|
137
|
+
}
|
|
138
|
+
});
|
|
139
|
+
|
|
140
|
+
const channel = client.channel(rt.topic);
|
|
141
|
+
for (const type of EVENTS) {
|
|
142
|
+
channel.on(type, (payload) => this.dispatch(payload as PhonoEvent));
|
|
143
|
+
}
|
|
144
|
+
await channel.subscribe();
|
|
145
|
+
this.setStatus("connected");
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
private scheduleRetry(): void {
|
|
149
|
+
if (this.closed || this.retryTimer) return;
|
|
150
|
+
this.setStatus("reconnecting");
|
|
151
|
+
this.retryTimer = setTimeout(() => {
|
|
152
|
+
this.retryTimer = null;
|
|
153
|
+
void this.open().catch(() => {});
|
|
154
|
+
}, 3_000);
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
private dispatch(event: PhonoEvent): void {
|
|
158
|
+
for (const key of [event.type, "*"]) {
|
|
159
|
+
this.handlers.get(key)?.forEach((h) => {
|
|
160
|
+
try {
|
|
161
|
+
h(event);
|
|
162
|
+
} catch (err) {
|
|
163
|
+
console.error("phono: handler failed", err);
|
|
164
|
+
}
|
|
165
|
+
});
|
|
166
|
+
}
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
private setStatus(s: RealtimeStatus): void {
|
|
170
|
+
if (this.status === s) return;
|
|
171
|
+
this.status = s;
|
|
172
|
+
this.statusHandlers.forEach((h) => h(s));
|
|
173
|
+
}
|
|
174
|
+
}
|