@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/dist/index.js
ADDED
|
@@ -0,0 +1,1204 @@
|
|
|
1
|
+
// src/announcements.ts
|
|
2
|
+
function announcementForEnd(call) {
|
|
3
|
+
if (call.answered_at)
|
|
4
|
+
return null;
|
|
5
|
+
return call.end_reason === "missed" || call.end_reason === "declined" ? "unavailable" : null;
|
|
6
|
+
}
|
|
7
|
+
function announcementForError(code) {
|
|
8
|
+
switch (code) {
|
|
9
|
+
case "busy":
|
|
10
|
+
return "busy";
|
|
11
|
+
case "handle_not_found":
|
|
12
|
+
return "not_assigned";
|
|
13
|
+
case "contact_required":
|
|
14
|
+
case "unavailable":
|
|
15
|
+
return "unavailable";
|
|
16
|
+
}
|
|
17
|
+
return null;
|
|
18
|
+
}
|
|
19
|
+
function playAnnouncement(url) {
|
|
20
|
+
if (typeof Audio === "undefined")
|
|
21
|
+
return { done: Promise.resolve(), stop: () => {} };
|
|
22
|
+
const audio = new Audio(url);
|
|
23
|
+
let finish = () => {};
|
|
24
|
+
const done = new Promise((resolve) => {
|
|
25
|
+
finish = resolve;
|
|
26
|
+
audio.onended = () => resolve();
|
|
27
|
+
audio.onerror = () => resolve();
|
|
28
|
+
});
|
|
29
|
+
audio.play().catch(() => finish());
|
|
30
|
+
return {
|
|
31
|
+
done,
|
|
32
|
+
stop: () => {
|
|
33
|
+
audio.pause();
|
|
34
|
+
audio.removeAttribute("src");
|
|
35
|
+
finish();
|
|
36
|
+
}
|
|
37
|
+
};
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
// src/audio.ts
|
|
41
|
+
import { KonetClient } from "@raucheacho/konet-js";
|
|
42
|
+
var AUDIO_EVENT = "a";
|
|
43
|
+
var TARGET_MS = 120;
|
|
44
|
+
var MAX_MS = 400;
|
|
45
|
+
var JOIN_TIMEOUT_MS = 8000;
|
|
46
|
+
var SPEAKING_HOLD_MS = 300;
|
|
47
|
+
var VOICE_MIN_BYTES = 16;
|
|
48
|
+
function withTimeout(promise, ms, message) {
|
|
49
|
+
return Promise.race([
|
|
50
|
+
promise,
|
|
51
|
+
new Promise((_, reject) => setTimeout(() => reject(new Error(message)), ms))
|
|
52
|
+
]);
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
class CallAudio {
|
|
56
|
+
creds;
|
|
57
|
+
assets;
|
|
58
|
+
listeners = new Set;
|
|
59
|
+
snapshot;
|
|
60
|
+
client = null;
|
|
61
|
+
channel = null;
|
|
62
|
+
context = null;
|
|
63
|
+
micStream = null;
|
|
64
|
+
capture = null;
|
|
65
|
+
playback = null;
|
|
66
|
+
wasmBytes = null;
|
|
67
|
+
speakingTimer = null;
|
|
68
|
+
stopped = false;
|
|
69
|
+
constructor(creds, mode = "open", assets = {}) {
|
|
70
|
+
this.creds = creds;
|
|
71
|
+
this.assets = assets;
|
|
72
|
+
this.snapshot = {
|
|
73
|
+
state: "idle",
|
|
74
|
+
mode,
|
|
75
|
+
talking: false,
|
|
76
|
+
muted: false,
|
|
77
|
+
remoteSpeaking: false,
|
|
78
|
+
micReady: false,
|
|
79
|
+
error: null
|
|
80
|
+
};
|
|
81
|
+
}
|
|
82
|
+
subscribe(listener) {
|
|
83
|
+
this.listeners.add(listener);
|
|
84
|
+
listener(this.snapshot);
|
|
85
|
+
return () => this.listeners.delete(listener);
|
|
86
|
+
}
|
|
87
|
+
get state() {
|
|
88
|
+
return this.snapshot;
|
|
89
|
+
}
|
|
90
|
+
async start() {
|
|
91
|
+
if (this.stopped)
|
|
92
|
+
return;
|
|
93
|
+
this.emit({ state: "connecting", error: null });
|
|
94
|
+
try {
|
|
95
|
+
await this.buildPlayback();
|
|
96
|
+
const client = new KonetClient(this.creds.url, { token: this.creds.token }).connect();
|
|
97
|
+
this.client = client;
|
|
98
|
+
const channel = client.channel(this.creds.topic, { binaryMode: "multiplex" });
|
|
99
|
+
this.channel = channel;
|
|
100
|
+
channel.on(this.creds.event || AUDIO_EVENT, (data) => {
|
|
101
|
+
const frame = data;
|
|
102
|
+
this.playback?.port.postMessage({ type: "frame", frame });
|
|
103
|
+
if (frame.length > VOICE_MIN_BYTES)
|
|
104
|
+
this.markRemoteSpeaking();
|
|
105
|
+
});
|
|
106
|
+
await withTimeout(channel.subscribe(), JOIN_TIMEOUT_MS, "L'appel n'a pas répondu. Vérifiez que le temps réel est joignable.");
|
|
107
|
+
await this.context?.resume();
|
|
108
|
+
await this.ensureCapture();
|
|
109
|
+
this.emit({ state: "connected" });
|
|
110
|
+
if (this.snapshot.mode === "open")
|
|
111
|
+
this.startTalking();
|
|
112
|
+
} catch (error) {
|
|
113
|
+
this.emit({
|
|
114
|
+
state: this.isPermissionDenied(error) ? "denied" : "error",
|
|
115
|
+
error: this.describe(error)
|
|
116
|
+
});
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
press() {
|
|
120
|
+
if (this.snapshot.mode !== "ptt" || this.snapshot.state !== "connected")
|
|
121
|
+
return;
|
|
122
|
+
this.startTalking();
|
|
123
|
+
}
|
|
124
|
+
release() {
|
|
125
|
+
if (this.snapshot.mode !== "ptt")
|
|
126
|
+
return;
|
|
127
|
+
this.stopTalking();
|
|
128
|
+
}
|
|
129
|
+
setMode(mode) {
|
|
130
|
+
this.stopTalking();
|
|
131
|
+
this.emit({ mode, muted: false });
|
|
132
|
+
if (mode === "open" && this.snapshot.state === "connected")
|
|
133
|
+
this.startTalking();
|
|
134
|
+
}
|
|
135
|
+
setMuted(muted) {
|
|
136
|
+
if (this.snapshot.mode !== "open")
|
|
137
|
+
return;
|
|
138
|
+
this.emit({ muted });
|
|
139
|
+
if (muted)
|
|
140
|
+
this.stopTalking();
|
|
141
|
+
else
|
|
142
|
+
this.startTalking();
|
|
143
|
+
}
|
|
144
|
+
stop() {
|
|
145
|
+
this.stopped = true;
|
|
146
|
+
if (this.speakingTimer)
|
|
147
|
+
clearTimeout(this.speakingTimer);
|
|
148
|
+
this.capture?.port.postMessage({ type: "stop" });
|
|
149
|
+
this.playback?.port.postMessage({ type: "close" });
|
|
150
|
+
this.capture?.disconnect();
|
|
151
|
+
this.playback?.disconnect();
|
|
152
|
+
this.micStream?.getTracks().forEach((t) => t.stop());
|
|
153
|
+
this.context?.close();
|
|
154
|
+
this.client?.disconnect();
|
|
155
|
+
this.client = null;
|
|
156
|
+
this.channel = null;
|
|
157
|
+
this.context = null;
|
|
158
|
+
this.micStream = null;
|
|
159
|
+
this.capture = null;
|
|
160
|
+
this.playback = null;
|
|
161
|
+
this.listeners.clear();
|
|
162
|
+
}
|
|
163
|
+
startTalking() {
|
|
164
|
+
if (!this.capture || this.snapshot.talking)
|
|
165
|
+
return;
|
|
166
|
+
const streamId = Math.random() * 4294967295 >>> 0;
|
|
167
|
+
this.capture.port.postMessage({ type: "start", streamId, bitrate: 24000 });
|
|
168
|
+
this.emit({ talking: true });
|
|
169
|
+
}
|
|
170
|
+
stopTalking() {
|
|
171
|
+
if (!this.snapshot.talking)
|
|
172
|
+
return;
|
|
173
|
+
this.capture?.port.postMessage({ type: "stop" });
|
|
174
|
+
this.emit({ talking: false });
|
|
175
|
+
}
|
|
176
|
+
markRemoteSpeaking() {
|
|
177
|
+
if (!this.snapshot.remoteSpeaking)
|
|
178
|
+
this.emit({ remoteSpeaking: true });
|
|
179
|
+
if (this.speakingTimer)
|
|
180
|
+
clearTimeout(this.speakingTimer);
|
|
181
|
+
this.speakingTimer = setTimeout(() => this.emit({ remoteSpeaking: false }), SPEAKING_HOLD_MS);
|
|
182
|
+
}
|
|
183
|
+
async buildPlayback() {
|
|
184
|
+
if (typeof window !== "undefined" && !window.isSecureContext) {
|
|
185
|
+
throw new Error("Le navigateur n'autorise l'audio que sur une page sécurisée : ouvrez cette page en https:// ou sur localhost.");
|
|
186
|
+
}
|
|
187
|
+
const context = new AudioContext({ sampleRate: 48000 });
|
|
188
|
+
if (!context.audioWorklet) {
|
|
189
|
+
context.close();
|
|
190
|
+
throw new Error("Ce navigateur ne permet pas l'audio temps réel (AudioWorklet).");
|
|
191
|
+
}
|
|
192
|
+
this.context = context;
|
|
193
|
+
await context.audioWorklet.addModule(this.assets.workletUrl ?? "/goul-ptt-worklets.js");
|
|
194
|
+
const res = await fetch(this.assets.wasmUrl ?? "/goul-audio.wasm");
|
|
195
|
+
if (!res.ok)
|
|
196
|
+
throw new Error("goul-audio.wasm introuvable : voir « Le cœur audio » dans le README de @raucheacho/phono-web.");
|
|
197
|
+
const bytes = await res.arrayBuffer();
|
|
198
|
+
this.wasmBytes = bytes;
|
|
199
|
+
const playback = new AudioWorkletNode(context, "goul-playback", {
|
|
200
|
+
numberOfInputs: 0,
|
|
201
|
+
numberOfOutputs: 1,
|
|
202
|
+
outputChannelCount: [1]
|
|
203
|
+
});
|
|
204
|
+
await this.initWorklet(playback, bytes.slice(0));
|
|
205
|
+
playback.connect(context.destination);
|
|
206
|
+
playback.port.postMessage({ type: "open", targetMs: TARGET_MS, maxMs: MAX_MS });
|
|
207
|
+
this.playback = playback;
|
|
208
|
+
}
|
|
209
|
+
async ensureCapture() {
|
|
210
|
+
const context = this.context;
|
|
211
|
+
const bytes = this.wasmBytes;
|
|
212
|
+
if (this.capture || !context || !bytes)
|
|
213
|
+
return;
|
|
214
|
+
this.micStream = await navigator.mediaDevices.getUserMedia({
|
|
215
|
+
audio: {
|
|
216
|
+
echoCancellation: true,
|
|
217
|
+
noiseSuppression: true,
|
|
218
|
+
autoGainControl: true,
|
|
219
|
+
channelCount: 1
|
|
220
|
+
}
|
|
221
|
+
});
|
|
222
|
+
const capture = new AudioWorkletNode(context, "goul-capture", {
|
|
223
|
+
numberOfInputs: 1,
|
|
224
|
+
numberOfOutputs: 0,
|
|
225
|
+
channelCount: 1
|
|
226
|
+
});
|
|
227
|
+
await this.initWorklet(capture, bytes.slice(0));
|
|
228
|
+
capture.port.onmessage = ({ data }) => {
|
|
229
|
+
if (data.type === "frame") {
|
|
230
|
+
try {
|
|
231
|
+
this.channel?.sendBinary(this.creds.event || AUDIO_EVENT, data.frame);
|
|
232
|
+
} catch {}
|
|
233
|
+
}
|
|
234
|
+
};
|
|
235
|
+
context.createMediaStreamSource(this.micStream).connect(capture);
|
|
236
|
+
this.capture = capture;
|
|
237
|
+
this.emit({ micReady: true });
|
|
238
|
+
}
|
|
239
|
+
initWorklet(node, bytes) {
|
|
240
|
+
return new Promise((resolve, reject) => {
|
|
241
|
+
const timer = setTimeout(() => reject(new Error("Le cœur audio n'a pas démarré.")), 5000);
|
|
242
|
+
node.port.onmessage = ({ data }) => {
|
|
243
|
+
if (data.type === "ready") {
|
|
244
|
+
clearTimeout(timer);
|
|
245
|
+
resolve();
|
|
246
|
+
} else if (data.type === "error") {
|
|
247
|
+
clearTimeout(timer);
|
|
248
|
+
reject(new Error(data.message ?? "Le cœur audio a refusé de démarrer."));
|
|
249
|
+
}
|
|
250
|
+
};
|
|
251
|
+
node.port.postMessage({ type: "init", bytes }, [bytes]);
|
|
252
|
+
});
|
|
253
|
+
}
|
|
254
|
+
isPermissionDenied(error) {
|
|
255
|
+
return error instanceof DOMException && error.name === "NotAllowedError";
|
|
256
|
+
}
|
|
257
|
+
describe(error) {
|
|
258
|
+
if (this.isPermissionDenied(error))
|
|
259
|
+
return "Micro refusé par le navigateur.";
|
|
260
|
+
return error instanceof Error ? error.message : "Erreur inconnue.";
|
|
261
|
+
}
|
|
262
|
+
emit(patch) {
|
|
263
|
+
if (this.stopped && patch.state === undefined)
|
|
264
|
+
return;
|
|
265
|
+
this.snapshot = { ...this.snapshot, ...patch };
|
|
266
|
+
this.listeners.forEach((l) => l(this.snapshot));
|
|
267
|
+
}
|
|
268
|
+
}
|
|
269
|
+
|
|
270
|
+
// src/tones.ts
|
|
271
|
+
function ringtone() {
|
|
272
|
+
return loop(2000, (ctx) => {
|
|
273
|
+
beep(ctx, 0, 0.35, 0.08);
|
|
274
|
+
beep(ctx, 0.5, 0.35, 0.08);
|
|
275
|
+
});
|
|
276
|
+
}
|
|
277
|
+
function ringback() {
|
|
278
|
+
return loop(5000, (ctx) => beep(ctx, 0, 1.5, 0.06));
|
|
279
|
+
}
|
|
280
|
+
function titleAlert(text) {
|
|
281
|
+
if (typeof document === "undefined")
|
|
282
|
+
return () => {};
|
|
283
|
+
const original = document.title;
|
|
284
|
+
let on = false;
|
|
285
|
+
const t = setInterval(() => {
|
|
286
|
+
on = !on;
|
|
287
|
+
document.title = on ? text : original;
|
|
288
|
+
}, 1000);
|
|
289
|
+
return () => {
|
|
290
|
+
clearInterval(t);
|
|
291
|
+
document.title = original;
|
|
292
|
+
};
|
|
293
|
+
}
|
|
294
|
+
function loop(everyMs, play) {
|
|
295
|
+
if (typeof AudioContext === "undefined")
|
|
296
|
+
return () => {};
|
|
297
|
+
const ctx = new AudioContext;
|
|
298
|
+
play(ctx);
|
|
299
|
+
const t = setInterval(() => play(ctx), everyMs);
|
|
300
|
+
return () => {
|
|
301
|
+
clearInterval(t);
|
|
302
|
+
ctx.close();
|
|
303
|
+
};
|
|
304
|
+
}
|
|
305
|
+
function beep(ctx, at, length, volume) {
|
|
306
|
+
const osc = ctx.createOscillator();
|
|
307
|
+
const gain = ctx.createGain();
|
|
308
|
+
osc.frequency.value = 440;
|
|
309
|
+
gain.gain.setValueAtTime(volume, ctx.currentTime + at);
|
|
310
|
+
gain.gain.setValueAtTime(0, ctx.currentTime + at + length);
|
|
311
|
+
osc.connect(gain).connect(ctx.destination);
|
|
312
|
+
osc.start(ctx.currentTime + at);
|
|
313
|
+
osc.stop(ctx.currentTime + at + length + 0.05);
|
|
314
|
+
}
|
|
315
|
+
|
|
316
|
+
// src/phone.ts
|
|
317
|
+
class Phone {
|
|
318
|
+
phono;
|
|
319
|
+
options;
|
|
320
|
+
state;
|
|
321
|
+
listeners = new Set;
|
|
322
|
+
audio = null;
|
|
323
|
+
unsubscribers = [];
|
|
324
|
+
stopTone = null;
|
|
325
|
+
toneKind = null;
|
|
326
|
+
stopTitle = null;
|
|
327
|
+
starting = null;
|
|
328
|
+
announcementUrls = {};
|
|
329
|
+
stopAnnouncement = null;
|
|
330
|
+
constructor(phono, options = {}) {
|
|
331
|
+
this.phono = phono;
|
|
332
|
+
this.options = options;
|
|
333
|
+
this.state = {
|
|
334
|
+
identity: null,
|
|
335
|
+
ready: false,
|
|
336
|
+
ringing: [],
|
|
337
|
+
current: null,
|
|
338
|
+
ended: null,
|
|
339
|
+
audio: null,
|
|
340
|
+
mode: options.mode ?? "open",
|
|
341
|
+
error: null,
|
|
342
|
+
announcement: null
|
|
343
|
+
};
|
|
344
|
+
}
|
|
345
|
+
getState() {
|
|
346
|
+
return this.state;
|
|
347
|
+
}
|
|
348
|
+
subscribe(listener) {
|
|
349
|
+
this.listeners.add(listener);
|
|
350
|
+
listener(this.state);
|
|
351
|
+
return () => this.listeners.delete(listener);
|
|
352
|
+
}
|
|
353
|
+
start() {
|
|
354
|
+
this.starting ??= (async () => {
|
|
355
|
+
const { handle: identity } = await this.phono.me();
|
|
356
|
+
this.set({ identity });
|
|
357
|
+
if (this.options.announcements !== false) {
|
|
358
|
+
const lang = typeof navigator === "undefined" ? undefined : navigator.language;
|
|
359
|
+
const list = await this.phono.announcements(lang).catch(() => null);
|
|
360
|
+
for (const a of Object.values(list?.announcements ?? {}))
|
|
361
|
+
this.announcementUrls[a.code] = a.url;
|
|
362
|
+
}
|
|
363
|
+
const rt = this.phono.realtime();
|
|
364
|
+
for (const type of ["call.ringing", "call.updated", "call.answered", "call.ended"]) {
|
|
365
|
+
this.unsubscribers.push(rt.on(type, (ev) => this.onEvent(ev)));
|
|
366
|
+
}
|
|
367
|
+
await rt.ready();
|
|
368
|
+
const recent = await this.phono.calls.list({ limit: 10 }).catch(() => []);
|
|
369
|
+
for (const call of recent) {
|
|
370
|
+
if (call.status === "ringing" && this.mine(call)?.state === "invited")
|
|
371
|
+
this.addRinging(call);
|
|
372
|
+
}
|
|
373
|
+
this.set({ ready: true });
|
|
374
|
+
})().catch((err) => {
|
|
375
|
+
this.starting = null;
|
|
376
|
+
this.fail(err);
|
|
377
|
+
throw err;
|
|
378
|
+
});
|
|
379
|
+
return this.starting;
|
|
380
|
+
}
|
|
381
|
+
async dial(to) {
|
|
382
|
+
if (this.state.current)
|
|
383
|
+
return;
|
|
384
|
+
this.endAnnouncement();
|
|
385
|
+
await this.start();
|
|
386
|
+
try {
|
|
387
|
+
const res = await this.phono.calls.create({ to: to.replace(/^@/, "") });
|
|
388
|
+
this.set({ current: this.describe(res.call, "outgoing"), ended: null, error: null });
|
|
389
|
+
await this.joinAudio(res);
|
|
390
|
+
} catch (err) {
|
|
391
|
+
this.fail(err);
|
|
392
|
+
if (err instanceof PhonoError && err.announcement)
|
|
393
|
+
this.announce(err.announcement.code, err.announcement.url);
|
|
394
|
+
}
|
|
395
|
+
}
|
|
396
|
+
async answer(callId) {
|
|
397
|
+
if (this.state.current)
|
|
398
|
+
return;
|
|
399
|
+
const r = callId ? this.state.ringing.find((x) => x.call.id === callId) : this.state.ringing[0];
|
|
400
|
+
if (!r)
|
|
401
|
+
return;
|
|
402
|
+
try {
|
|
403
|
+
const res = await this.phono.calls.answer(r.call.id);
|
|
404
|
+
this.removeRinging(r.call.id);
|
|
405
|
+
this.set({ current: { ...r, call: res.call }, ended: null, error: null });
|
|
406
|
+
await this.joinAudio(res);
|
|
407
|
+
} catch (err) {
|
|
408
|
+
this.removeRinging(r.call.id);
|
|
409
|
+
if (err instanceof PhonoError && err.code === "invalid_state") {
|
|
410
|
+
this.set({ error: "Cet appel a déjà été pris." });
|
|
411
|
+
} else {
|
|
412
|
+
this.fail(err);
|
|
413
|
+
}
|
|
414
|
+
}
|
|
415
|
+
}
|
|
416
|
+
async reject(callId) {
|
|
417
|
+
const r = callId ? this.state.ringing.find((x) => x.call.id === callId) : this.state.ringing[0];
|
|
418
|
+
if (!r)
|
|
419
|
+
return;
|
|
420
|
+
this.removeRinging(r.call.id);
|
|
421
|
+
await this.phono.calls.reject(r.call.id).catch(() => {});
|
|
422
|
+
}
|
|
423
|
+
async hangup() {
|
|
424
|
+
this.endAnnouncement();
|
|
425
|
+
const cur = this.state.current;
|
|
426
|
+
if (!cur)
|
|
427
|
+
return;
|
|
428
|
+
this.endAudio(cur);
|
|
429
|
+
await this.phono.calls.hangup(cur.call.id).catch(() => {});
|
|
430
|
+
}
|
|
431
|
+
setMuted(muted) {
|
|
432
|
+
this.audio?.setMuted(muted);
|
|
433
|
+
}
|
|
434
|
+
setMode(mode) {
|
|
435
|
+
this.set({ mode });
|
|
436
|
+
this.audio?.setMode(mode);
|
|
437
|
+
}
|
|
438
|
+
press() {
|
|
439
|
+
this.audio?.press();
|
|
440
|
+
}
|
|
441
|
+
release() {
|
|
442
|
+
this.audio?.release();
|
|
443
|
+
}
|
|
444
|
+
clearError() {
|
|
445
|
+
this.set({ error: null });
|
|
446
|
+
}
|
|
447
|
+
endAnnouncement() {
|
|
448
|
+
this.stopAnnouncement?.();
|
|
449
|
+
this.stopAnnouncement = null;
|
|
450
|
+
if (this.state.announcement)
|
|
451
|
+
this.set({ announcement: null });
|
|
452
|
+
}
|
|
453
|
+
destroy() {
|
|
454
|
+
this.audio?.stop();
|
|
455
|
+
this.audio = null;
|
|
456
|
+
this.endAnnouncement();
|
|
457
|
+
this.unsubscribers.forEach((u) => u());
|
|
458
|
+
this.unsubscribers = [];
|
|
459
|
+
this.syncAlerts(true);
|
|
460
|
+
this.listeners.clear();
|
|
461
|
+
}
|
|
462
|
+
onEvent(ev) {
|
|
463
|
+
const call = ev.data;
|
|
464
|
+
const mine = this.mine(call);
|
|
465
|
+
if (ev.type === "call.ringing" || ev.type === "call.updated") {
|
|
466
|
+
if (mine?.state === "invited" && call.status === "ringing")
|
|
467
|
+
this.addRinging(call);
|
|
468
|
+
else
|
|
469
|
+
this.removeRinging(call.id);
|
|
470
|
+
}
|
|
471
|
+
if (ev.type === "call.answered" || ev.type === "call.ended")
|
|
472
|
+
this.removeRinging(call.id);
|
|
473
|
+
const cur = this.state.current;
|
|
474
|
+
if (cur && cur.call.id === call.id) {
|
|
475
|
+
if (ev.type === "call.ended") {
|
|
476
|
+
this.endAudio({ ...cur, call });
|
|
477
|
+
const code = cur.direction === "outgoing" ? announcementForEnd(call) : null;
|
|
478
|
+
if (code)
|
|
479
|
+
this.announce(code);
|
|
480
|
+
} else
|
|
481
|
+
this.set({ current: { ...cur, call } });
|
|
482
|
+
}
|
|
483
|
+
}
|
|
484
|
+
announce(code, fallbackUrl) {
|
|
485
|
+
this.endAnnouncement();
|
|
486
|
+
this.set({ announcement: code });
|
|
487
|
+
const own = typeof this.options.announcements === "object" ? this.options.announcements[code] : undefined;
|
|
488
|
+
const url = own ?? this.announcementUrls[code] ?? fallbackUrl;
|
|
489
|
+
if (this.options.announcements === false || !url) {
|
|
490
|
+
const t = setTimeout(() => this.state.announcement === code && this.set({ announcement: null }), 5000);
|
|
491
|
+
this.stopAnnouncement = () => clearTimeout(t);
|
|
492
|
+
return;
|
|
493
|
+
}
|
|
494
|
+
const playing = playAnnouncement(url);
|
|
495
|
+
this.stopAnnouncement = playing.stop;
|
|
496
|
+
playing.done.then(() => {
|
|
497
|
+
if (this.stopAnnouncement !== playing.stop)
|
|
498
|
+
return;
|
|
499
|
+
this.stopAnnouncement = null;
|
|
500
|
+
this.set({ announcement: null });
|
|
501
|
+
});
|
|
502
|
+
}
|
|
503
|
+
async joinAudio(res) {
|
|
504
|
+
if (!res.audio)
|
|
505
|
+
return;
|
|
506
|
+
const audio = new CallAudio(res.audio, this.state.mode, this.phono.options.audio);
|
|
507
|
+
this.audio = audio;
|
|
508
|
+
audio.subscribe((a) => this.set({ audio: a }));
|
|
509
|
+
await audio.start();
|
|
510
|
+
}
|
|
511
|
+
endAudio(ended) {
|
|
512
|
+
this.audio?.stop();
|
|
513
|
+
this.audio = null;
|
|
514
|
+
this.set({ audio: null, current: null, ended });
|
|
515
|
+
}
|
|
516
|
+
mine(call) {
|
|
517
|
+
const id = this.state.identity?.id;
|
|
518
|
+
return call.participants.find((p) => p.handle.id === id);
|
|
519
|
+
}
|
|
520
|
+
describe(call, direction) {
|
|
521
|
+
const id = this.state.identity?.id;
|
|
522
|
+
const others = call.participants.filter((p) => p.handle.id !== id);
|
|
523
|
+
const peer = others.map((p) => p.handle.display_name || `@${p.handle.handle}`).join(", ") || "—";
|
|
524
|
+
return { call, direction, peer };
|
|
525
|
+
}
|
|
526
|
+
addRinging(call) {
|
|
527
|
+
if (this.state.ringing.some((r) => r.call.id === call.id))
|
|
528
|
+
return;
|
|
529
|
+
this.set({ ringing: [...this.state.ringing, this.describe(call, "incoming")] });
|
|
530
|
+
}
|
|
531
|
+
removeRinging(callId) {
|
|
532
|
+
if (!this.state.ringing.some((r) => r.call.id === callId))
|
|
533
|
+
return;
|
|
534
|
+
this.set({ ringing: this.state.ringing.filter((r) => r.call.id !== callId) });
|
|
535
|
+
}
|
|
536
|
+
fail(err) {
|
|
537
|
+
this.set({ error: err?.message ?? "Une erreur est survenue" });
|
|
538
|
+
}
|
|
539
|
+
set(patch) {
|
|
540
|
+
this.state = { ...this.state, ...patch };
|
|
541
|
+
this.syncAlerts(false);
|
|
542
|
+
this.listeners.forEach((l) => l(this.state));
|
|
543
|
+
}
|
|
544
|
+
syncAlerts(off) {
|
|
545
|
+
const { ringing, current } = this.state;
|
|
546
|
+
const want = off ? null : ringing.length > 0 && !current ? "ring" : current?.direction === "outgoing" && current.call.status === "ringing" ? "ringback" : null;
|
|
547
|
+
if (this.options.tones !== false && want !== this.toneKind) {
|
|
548
|
+
this.stopTone?.();
|
|
549
|
+
this.stopTone = want === "ring" ? ringtone() : want === "ringback" ? ringback() : null;
|
|
550
|
+
}
|
|
551
|
+
this.toneKind = want;
|
|
552
|
+
const title = want === "ring" && this.options.titleAlert !== false ? `\uD83D\uDCDE ${ringing[0]?.peer}` : null;
|
|
553
|
+
if (!title) {
|
|
554
|
+
this.stopTitle?.();
|
|
555
|
+
this.stopTitle = null;
|
|
556
|
+
} else if (!this.stopTitle) {
|
|
557
|
+
this.stopTitle = titleAlert(title);
|
|
558
|
+
}
|
|
559
|
+
}
|
|
560
|
+
}
|
|
561
|
+
|
|
562
|
+
// src/realtime.ts
|
|
563
|
+
import { KonetClient as KonetClient2 } from "@raucheacho/konet-js";
|
|
564
|
+
var EVENTS = [
|
|
565
|
+
"message.created",
|
|
566
|
+
"message.transcribed",
|
|
567
|
+
"message.read",
|
|
568
|
+
"message.reacted",
|
|
569
|
+
"conversation.activity",
|
|
570
|
+
"message.updated",
|
|
571
|
+
"message.deleted",
|
|
572
|
+
"message.delivered",
|
|
573
|
+
"conversation.transferred",
|
|
574
|
+
"group.updated",
|
|
575
|
+
"call.ringing",
|
|
576
|
+
"call.updated",
|
|
577
|
+
"call.answered",
|
|
578
|
+
"call.ended",
|
|
579
|
+
"call.transcribed",
|
|
580
|
+
"contact.requested",
|
|
581
|
+
"contact.accepted",
|
|
582
|
+
"channel.updated",
|
|
583
|
+
"channel.deleted",
|
|
584
|
+
"channel.floor",
|
|
585
|
+
"channel.invited",
|
|
586
|
+
"transmission.created",
|
|
587
|
+
"transmission.transcribed"
|
|
588
|
+
];
|
|
589
|
+
|
|
590
|
+
class Realtime {
|
|
591
|
+
phono;
|
|
592
|
+
handlers = new Map;
|
|
593
|
+
statusHandlers = new Set;
|
|
594
|
+
client = null;
|
|
595
|
+
opening = null;
|
|
596
|
+
closed = false;
|
|
597
|
+
retryTimer = null;
|
|
598
|
+
renewTimer = null;
|
|
599
|
+
status = "connecting";
|
|
600
|
+
constructor(phono) {
|
|
601
|
+
this.phono = phono;
|
|
602
|
+
}
|
|
603
|
+
on(type, handler) {
|
|
604
|
+
let set = this.handlers.get(type);
|
|
605
|
+
if (!set)
|
|
606
|
+
this.handlers.set(type, set = new Set);
|
|
607
|
+
set.add(handler);
|
|
608
|
+
this.open();
|
|
609
|
+
return () => set.delete(handler);
|
|
610
|
+
}
|
|
611
|
+
onStatus(handler) {
|
|
612
|
+
this.statusHandlers.add(handler);
|
|
613
|
+
handler(this.status);
|
|
614
|
+
return () => this.statusHandlers.delete(handler);
|
|
615
|
+
}
|
|
616
|
+
ready() {
|
|
617
|
+
return this.open();
|
|
618
|
+
}
|
|
619
|
+
check() {
|
|
620
|
+
this.client?.checkConnection();
|
|
621
|
+
}
|
|
622
|
+
close() {
|
|
623
|
+
this.closed = true;
|
|
624
|
+
if (this.retryTimer)
|
|
625
|
+
clearTimeout(this.retryTimer);
|
|
626
|
+
if (this.renewTimer)
|
|
627
|
+
clearTimeout(this.renewTimer);
|
|
628
|
+
this.client?.disconnect();
|
|
629
|
+
this.client = null;
|
|
630
|
+
this.setStatus("closed");
|
|
631
|
+
}
|
|
632
|
+
open() {
|
|
633
|
+
if (this.closed)
|
|
634
|
+
return Promise.resolve();
|
|
635
|
+
this.opening ??= this.connect().catch((err) => {
|
|
636
|
+
this.opening = null;
|
|
637
|
+
this.scheduleRetry();
|
|
638
|
+
throw err;
|
|
639
|
+
});
|
|
640
|
+
return this.opening;
|
|
641
|
+
}
|
|
642
|
+
async connect() {
|
|
643
|
+
this.setStatus("connecting");
|
|
644
|
+
const rt = await this.phono.request("/v1/realtime");
|
|
645
|
+
if (this.closed)
|
|
646
|
+
return;
|
|
647
|
+
const previous = this.client;
|
|
648
|
+
const client = new KonetClient2(rt.url, { token: rt.token }).connect();
|
|
649
|
+
this.client = client;
|
|
650
|
+
previous?.disconnect();
|
|
651
|
+
if (rt.expires_at) {
|
|
652
|
+
const lifetime = new Date(rt.expires_at).getTime() - Date.now();
|
|
653
|
+
if (this.renewTimer)
|
|
654
|
+
clearTimeout(this.renewTimer);
|
|
655
|
+
this.renewTimer = setTimeout(() => {
|
|
656
|
+
this.opening = this.connect().catch(() => this.scheduleRetry());
|
|
657
|
+
}, Math.max(30000, lifetime - 5 * 60000));
|
|
658
|
+
}
|
|
659
|
+
client.onStatus((s) => {
|
|
660
|
+
if (client !== this.client)
|
|
661
|
+
return;
|
|
662
|
+
if (s.state === "connected")
|
|
663
|
+
this.setStatus("connected");
|
|
664
|
+
else if (s.state === "reconnecting")
|
|
665
|
+
this.setStatus("reconnecting");
|
|
666
|
+
else if (s.state === "failed" && !this.closed) {
|
|
667
|
+
client.disconnect();
|
|
668
|
+
this.client = null;
|
|
669
|
+
this.opening = null;
|
|
670
|
+
this.scheduleRetry();
|
|
671
|
+
}
|
|
672
|
+
});
|
|
673
|
+
const channel = client.channel(rt.topic);
|
|
674
|
+
for (const type of EVENTS) {
|
|
675
|
+
channel.on(type, (payload) => this.dispatch(payload));
|
|
676
|
+
}
|
|
677
|
+
await channel.subscribe();
|
|
678
|
+
this.setStatus("connected");
|
|
679
|
+
}
|
|
680
|
+
scheduleRetry() {
|
|
681
|
+
if (this.closed || this.retryTimer)
|
|
682
|
+
return;
|
|
683
|
+
this.setStatus("reconnecting");
|
|
684
|
+
this.retryTimer = setTimeout(() => {
|
|
685
|
+
this.retryTimer = null;
|
|
686
|
+
this.open().catch(() => {});
|
|
687
|
+
}, 3000);
|
|
688
|
+
}
|
|
689
|
+
dispatch(event) {
|
|
690
|
+
for (const key of [event.type, "*"]) {
|
|
691
|
+
this.handlers.get(key)?.forEach((h) => {
|
|
692
|
+
try {
|
|
693
|
+
h(event);
|
|
694
|
+
} catch (err) {
|
|
695
|
+
console.error("phono: handler failed", err);
|
|
696
|
+
}
|
|
697
|
+
});
|
|
698
|
+
}
|
|
699
|
+
}
|
|
700
|
+
setStatus(s) {
|
|
701
|
+
if (this.status === s)
|
|
702
|
+
return;
|
|
703
|
+
this.status = s;
|
|
704
|
+
this.statusHandlers.forEach((h) => h(s));
|
|
705
|
+
}
|
|
706
|
+
}
|
|
707
|
+
|
|
708
|
+
// src/talkie.ts
|
|
709
|
+
import { KonetClient as KonetClient3 } from "@raucheacho/konet-js";
|
|
710
|
+
var AUDIO_EVENT2 = "a";
|
|
711
|
+
var TARGET_MS2 = 120;
|
|
712
|
+
var MAX_MS2 = 400;
|
|
713
|
+
var JOIN_TIMEOUT_MS2 = 8000;
|
|
714
|
+
var VOICE_MIN_BYTES2 = 12;
|
|
715
|
+
function withTimeout2(promise, ms, message) {
|
|
716
|
+
return Promise.race([promise, new Promise((_, reject) => setTimeout(() => reject(new Error(message)), ms))]);
|
|
717
|
+
}
|
|
718
|
+
|
|
719
|
+
class Talkie {
|
|
720
|
+
phono;
|
|
721
|
+
channelId;
|
|
722
|
+
assets;
|
|
723
|
+
listeners = new Set;
|
|
724
|
+
snapshot = {
|
|
725
|
+
state: "idle",
|
|
726
|
+
holder: null,
|
|
727
|
+
remoteSpeaking: false,
|
|
728
|
+
micReady: false,
|
|
729
|
+
online: [],
|
|
730
|
+
error: null
|
|
731
|
+
};
|
|
732
|
+
client = null;
|
|
733
|
+
channel = null;
|
|
734
|
+
context = null;
|
|
735
|
+
micStream = null;
|
|
736
|
+
capture = null;
|
|
737
|
+
playback = null;
|
|
738
|
+
wasmBytes = null;
|
|
739
|
+
speakingTimer = null;
|
|
740
|
+
renewTimer = null;
|
|
741
|
+
stopped = false;
|
|
742
|
+
constructor(phono, channelId, assets = {}) {
|
|
743
|
+
this.phono = phono;
|
|
744
|
+
this.channelId = channelId;
|
|
745
|
+
this.assets = assets;
|
|
746
|
+
}
|
|
747
|
+
subscribe(listener) {
|
|
748
|
+
this.listeners.add(listener);
|
|
749
|
+
listener(this.snapshot);
|
|
750
|
+
return () => this.listeners.delete(listener);
|
|
751
|
+
}
|
|
752
|
+
get state() {
|
|
753
|
+
return this.snapshot;
|
|
754
|
+
}
|
|
755
|
+
async start() {
|
|
756
|
+
if (this.stopped)
|
|
757
|
+
return;
|
|
758
|
+
this.emit({ state: "connecting", error: null });
|
|
759
|
+
try {
|
|
760
|
+
const creds = await this.phono.request(`/v1/channels/${encodeURIComponent(this.channelId)}/audio`, { method: "POST" });
|
|
761
|
+
await this.buildPlayback();
|
|
762
|
+
const client = new KonetClient3(creds.url, { token: creds.token }).connect();
|
|
763
|
+
this.client = client;
|
|
764
|
+
const channel = client.channel(creds.topic);
|
|
765
|
+
this.channel = channel;
|
|
766
|
+
channel.on("konet:floor", (payload) => {
|
|
767
|
+
this.onFloorChanged(payload.holder);
|
|
768
|
+
});
|
|
769
|
+
channel.on("presence", (payload) => {
|
|
770
|
+
const list = Array.isArray(payload) ? payload : [];
|
|
771
|
+
this.emit({ online: list.map((e) => e.id).filter((id) => id && id !== "talkie-listener") });
|
|
772
|
+
});
|
|
773
|
+
channel.on(creds.event || AUDIO_EVENT2, (data) => {
|
|
774
|
+
const frame = data;
|
|
775
|
+
this.playback?.port.postMessage({ type: "frame", frame });
|
|
776
|
+
if (frame.length > VOICE_MIN_BYTES2)
|
|
777
|
+
this.markRemoteSpeaking();
|
|
778
|
+
});
|
|
779
|
+
await withTimeout2(channel.subscribe(), JOIN_TIMEOUT_MS2, "Le canal n'a pas répondu. Vérifiez que le temps réel est joignable.");
|
|
780
|
+
this.emit({ state: "ready", error: null });
|
|
781
|
+
this.context?.resume();
|
|
782
|
+
const ttl = new Date(creds.expires_at).getTime() - Date.now();
|
|
783
|
+
if (ttl > 60000)
|
|
784
|
+
this.renewTimer = setTimeout(() => void this.reconnect(), ttl - 60000);
|
|
785
|
+
this.prepareMicIfAlreadyGranted();
|
|
786
|
+
} catch (error) {
|
|
787
|
+
this.emit({ state: "error", error: this.describe(error) });
|
|
788
|
+
}
|
|
789
|
+
}
|
|
790
|
+
async reconnect() {
|
|
791
|
+
if (this.stopped)
|
|
792
|
+
return;
|
|
793
|
+
this.client?.disconnect();
|
|
794
|
+
this.client = null;
|
|
795
|
+
this.channel = null;
|
|
796
|
+
this.playback?.port.postMessage({ type: "close" });
|
|
797
|
+
this.playback?.disconnect();
|
|
798
|
+
this.capture?.disconnect();
|
|
799
|
+
this.capture = null;
|
|
800
|
+
this.playback = null;
|
|
801
|
+
this.context?.close();
|
|
802
|
+
this.context = null;
|
|
803
|
+
this.emit({ micReady: false });
|
|
804
|
+
await this.start();
|
|
805
|
+
}
|
|
806
|
+
async prepareMicIfAlreadyGranted() {
|
|
807
|
+
try {
|
|
808
|
+
const status = await navigator.permissions.query({ name: "microphone" });
|
|
809
|
+
if (status.state === "granted")
|
|
810
|
+
await this.ensureCapture();
|
|
811
|
+
} catch {}
|
|
812
|
+
}
|
|
813
|
+
async press() {
|
|
814
|
+
if (!this.channel || this.snapshot.state === "transmitting")
|
|
815
|
+
return;
|
|
816
|
+
try {
|
|
817
|
+
await this.ensureCapture();
|
|
818
|
+
} catch (error) {
|
|
819
|
+
this.emit({ state: this.isPermissionDenied(error) ? "denied" : "error", error: this.describe(error) });
|
|
820
|
+
return;
|
|
821
|
+
}
|
|
822
|
+
try {
|
|
823
|
+
await this.channel.acquireFloor();
|
|
824
|
+
} catch {
|
|
825
|
+
this.emit({ error: "Quelqu'un parle déjà." });
|
|
826
|
+
return;
|
|
827
|
+
}
|
|
828
|
+
await this.context?.resume();
|
|
829
|
+
const streamId = Math.random() * 4294967295 >>> 0;
|
|
830
|
+
this.capture?.port.postMessage({ type: "start", streamId, bitrate: 24000 });
|
|
831
|
+
this.emit({ state: "transmitting", error: null });
|
|
832
|
+
}
|
|
833
|
+
async release() {
|
|
834
|
+
if (this.snapshot.state !== "transmitting")
|
|
835
|
+
return;
|
|
836
|
+
this.capture?.port.postMessage({ type: "stop" });
|
|
837
|
+
try {
|
|
838
|
+
await this.channel?.releaseFloor();
|
|
839
|
+
} catch {}
|
|
840
|
+
this.emit({ state: "ready" });
|
|
841
|
+
}
|
|
842
|
+
stop() {
|
|
843
|
+
this.stopped = true;
|
|
844
|
+
if (this.speakingTimer)
|
|
845
|
+
clearTimeout(this.speakingTimer);
|
|
846
|
+
if (this.renewTimer)
|
|
847
|
+
clearTimeout(this.renewTimer);
|
|
848
|
+
this.capture?.port.postMessage({ type: "stop" });
|
|
849
|
+
this.playback?.port.postMessage({ type: "close" });
|
|
850
|
+
this.capture?.disconnect();
|
|
851
|
+
this.playback?.disconnect();
|
|
852
|
+
this.micStream?.getTracks().forEach((t) => t.stop());
|
|
853
|
+
this.context?.close();
|
|
854
|
+
this.client?.disconnect();
|
|
855
|
+
this.client = null;
|
|
856
|
+
this.channel = null;
|
|
857
|
+
this.context = null;
|
|
858
|
+
this.micStream = null;
|
|
859
|
+
this.capture = null;
|
|
860
|
+
this.playback = null;
|
|
861
|
+
this.emit({ state: "idle", holder: null, remoteSpeaking: false, online: [] });
|
|
862
|
+
this.listeners.clear();
|
|
863
|
+
}
|
|
864
|
+
async buildPlayback() {
|
|
865
|
+
if (!window.isSecureContext) {
|
|
866
|
+
throw new Error("Le talkie demande une page sécurisée : https://, ou localhost en développement.");
|
|
867
|
+
}
|
|
868
|
+
const context = new AudioContext({ sampleRate: 48000 });
|
|
869
|
+
if (!context.audioWorklet) {
|
|
870
|
+
context.close();
|
|
871
|
+
throw new Error("Ce navigateur ne permet pas l'audio temps réel (AudioWorklet).");
|
|
872
|
+
}
|
|
873
|
+
this.context = context;
|
|
874
|
+
await context.audioWorklet.addModule(this.assets.workletUrl ?? "/goul-ptt-worklets.js");
|
|
875
|
+
const res = await fetch(this.assets.wasmUrl ?? "/goul-audio.wasm");
|
|
876
|
+
if (!res.ok)
|
|
877
|
+
throw new Error("goul-audio.wasm introuvable : voir « Le cœur audio » dans le README de @raucheacho/phono-web.");
|
|
878
|
+
const bytes = await res.arrayBuffer();
|
|
879
|
+
this.wasmBytes = bytes;
|
|
880
|
+
const playback = new AudioWorkletNode(context, "goul-playback", {
|
|
881
|
+
numberOfInputs: 0,
|
|
882
|
+
numberOfOutputs: 1,
|
|
883
|
+
outputChannelCount: [1]
|
|
884
|
+
});
|
|
885
|
+
await this.initWorklet(playback, bytes.slice(0));
|
|
886
|
+
playback.connect(context.destination);
|
|
887
|
+
playback.port.postMessage({ type: "open", targetMs: TARGET_MS2, maxMs: MAX_MS2 });
|
|
888
|
+
this.playback = playback;
|
|
889
|
+
}
|
|
890
|
+
async ensureCapture() {
|
|
891
|
+
const context = this.context;
|
|
892
|
+
const bytes = this.wasmBytes;
|
|
893
|
+
if (this.capture || !context || !bytes)
|
|
894
|
+
return;
|
|
895
|
+
this.micStream = await navigator.mediaDevices.getUserMedia({
|
|
896
|
+
audio: { echoCancellation: true, noiseSuppression: true, autoGainControl: true, channelCount: 1 }
|
|
897
|
+
});
|
|
898
|
+
const capture = new AudioWorkletNode(context, "goul-capture", {
|
|
899
|
+
numberOfInputs: 1,
|
|
900
|
+
numberOfOutputs: 0,
|
|
901
|
+
channelCount: 1
|
|
902
|
+
});
|
|
903
|
+
await this.initWorklet(capture, bytes.slice(0));
|
|
904
|
+
capture.port.onmessage = ({ data }) => {
|
|
905
|
+
if (data.type === "frame")
|
|
906
|
+
this.sendFrame(data.frame);
|
|
907
|
+
};
|
|
908
|
+
context.createMediaStreamSource(this.micStream).connect(capture);
|
|
909
|
+
this.capture = capture;
|
|
910
|
+
this.emit({ micReady: true });
|
|
911
|
+
}
|
|
912
|
+
initWorklet(node, bytes) {
|
|
913
|
+
return new Promise((resolve, reject) => {
|
|
914
|
+
const timer = setTimeout(() => reject(new Error("Le cœur audio n'a pas démarré.")), 5000);
|
|
915
|
+
node.port.onmessage = ({ data }) => {
|
|
916
|
+
if (data.type === "ready") {
|
|
917
|
+
clearTimeout(timer);
|
|
918
|
+
resolve();
|
|
919
|
+
} else if (data.type === "error") {
|
|
920
|
+
clearTimeout(timer);
|
|
921
|
+
reject(new Error(data.message ?? "Le cœur audio a refusé de démarrer."));
|
|
922
|
+
}
|
|
923
|
+
};
|
|
924
|
+
node.port.postMessage({ type: "init", bytes }, [bytes]);
|
|
925
|
+
});
|
|
926
|
+
}
|
|
927
|
+
sendFrame(frame) {
|
|
928
|
+
try {
|
|
929
|
+
this.channel?.sendBinary(AUDIO_EVENT2, frame);
|
|
930
|
+
} catch {}
|
|
931
|
+
}
|
|
932
|
+
markRemoteSpeaking() {
|
|
933
|
+
if (!this.snapshot.remoteSpeaking)
|
|
934
|
+
this.emit({ remoteSpeaking: true });
|
|
935
|
+
if (this.speakingTimer)
|
|
936
|
+
clearTimeout(this.speakingTimer);
|
|
937
|
+
this.speakingTimer = setTimeout(() => this.emit({ remoteSpeaking: false }), 300);
|
|
938
|
+
}
|
|
939
|
+
onFloorChanged(holder) {
|
|
940
|
+
if (holder === null) {
|
|
941
|
+
this.playback?.port.postMessage({ type: "end" });
|
|
942
|
+
if (this.snapshot.state !== "transmitting")
|
|
943
|
+
this.emit({ state: "ready", holder: null });
|
|
944
|
+
else
|
|
945
|
+
this.emit({ holder: null });
|
|
946
|
+
return;
|
|
947
|
+
}
|
|
948
|
+
this.emit({ holder, state: this.snapshot.state === "transmitting" ? "transmitting" : "listening" });
|
|
949
|
+
}
|
|
950
|
+
isPermissionDenied(error) {
|
|
951
|
+
return error instanceof DOMException && error.name === "NotAllowedError";
|
|
952
|
+
}
|
|
953
|
+
describe(error) {
|
|
954
|
+
if (this.isPermissionDenied(error))
|
|
955
|
+
return "Micro refusé par le navigateur.";
|
|
956
|
+
return error instanceof Error ? error.message : "Erreur inconnue.";
|
|
957
|
+
}
|
|
958
|
+
emit(patch) {
|
|
959
|
+
this.snapshot = { ...this.snapshot, ...patch };
|
|
960
|
+
this.listeners.forEach((l) => l(this.snapshot));
|
|
961
|
+
}
|
|
962
|
+
}
|
|
963
|
+
|
|
964
|
+
// src/client.ts
|
|
965
|
+
class PhonoError extends Error {
|
|
966
|
+
status;
|
|
967
|
+
code;
|
|
968
|
+
announcement;
|
|
969
|
+
constructor(status, code, message, announcement) {
|
|
970
|
+
super(message);
|
|
971
|
+
this.status = status;
|
|
972
|
+
this.code = code;
|
|
973
|
+
this.announcement = announcement;
|
|
974
|
+
this.name = "PhonoError";
|
|
975
|
+
}
|
|
976
|
+
}
|
|
977
|
+
var REFRESH_MARGIN_MS = 60000;
|
|
978
|
+
function expiryOf(token) {
|
|
979
|
+
const jwt = token.startsWith("pht_") ? token.slice(4) : null;
|
|
980
|
+
const payload = jwt?.split(".")[1];
|
|
981
|
+
if (!payload)
|
|
982
|
+
return null;
|
|
983
|
+
try {
|
|
984
|
+
const json = JSON.parse(atob(payload.replace(/-/g, "+").replace(/_/g, "/")));
|
|
985
|
+
return typeof json.exp === "number" ? json.exp * 1000 : null;
|
|
986
|
+
} catch {
|
|
987
|
+
return null;
|
|
988
|
+
}
|
|
989
|
+
}
|
|
990
|
+
|
|
991
|
+
class Phono {
|
|
992
|
+
options;
|
|
993
|
+
token = null;
|
|
994
|
+
tokenExpiry = null;
|
|
995
|
+
pendingToken = null;
|
|
996
|
+
realtimeInstance = null;
|
|
997
|
+
constructor(options) {
|
|
998
|
+
this.options = { ...options, baseUrl: options.baseUrl.replace(/\/+$/, "") };
|
|
999
|
+
}
|
|
1000
|
+
async request(path, init = {}) {
|
|
1001
|
+
const res = await this.send(path, init, false);
|
|
1002
|
+
if (res.status === 204)
|
|
1003
|
+
return;
|
|
1004
|
+
return res.json();
|
|
1005
|
+
}
|
|
1006
|
+
async send(path, init, retried) {
|
|
1007
|
+
const headers = new Headers(this.options.headers);
|
|
1008
|
+
new Headers(init.headers).forEach((v, k) => headers.set(k, v));
|
|
1009
|
+
if (init.body && !(init.body instanceof FormData) && !headers.has("Content-Type")) {
|
|
1010
|
+
headers.set("Content-Type", "application/json");
|
|
1011
|
+
}
|
|
1012
|
+
const token = await this.currentToken(false);
|
|
1013
|
+
if (token)
|
|
1014
|
+
headers.set("Authorization", `Bearer ${token}`);
|
|
1015
|
+
const doFetch = this.options.fetch ?? fetch;
|
|
1016
|
+
const res = await doFetch(`${this.options.baseUrl}${path}`, {
|
|
1017
|
+
...init,
|
|
1018
|
+
headers,
|
|
1019
|
+
credentials: this.options.credentials ?? init.credentials
|
|
1020
|
+
});
|
|
1021
|
+
if (res.status === 401 && !retried && typeof this.options.token === "function") {
|
|
1022
|
+
await this.currentToken(true);
|
|
1023
|
+
return this.send(path, init, true);
|
|
1024
|
+
}
|
|
1025
|
+
if (!res.ok) {
|
|
1026
|
+
const body = await res.json().catch(() => null);
|
|
1027
|
+
throw new PhonoError(res.status, body?.error ?? "unknown", body?.message ?? `HTTP ${res.status}`, body?.announcement);
|
|
1028
|
+
}
|
|
1029
|
+
return res;
|
|
1030
|
+
}
|
|
1031
|
+
async currentToken(force) {
|
|
1032
|
+
const source = this.options.token;
|
|
1033
|
+
if (source === undefined)
|
|
1034
|
+
return null;
|
|
1035
|
+
if (typeof source === "string")
|
|
1036
|
+
return source;
|
|
1037
|
+
const fresh = this.token && (this.tokenExpiry === null || this.tokenExpiry - Date.now() > REFRESH_MARGIN_MS);
|
|
1038
|
+
if (fresh && !force)
|
|
1039
|
+
return this.token;
|
|
1040
|
+
this.pendingToken ??= Promise.resolve(source()).then((t) => {
|
|
1041
|
+
this.token = t.trim();
|
|
1042
|
+
this.tokenExpiry = expiryOf(this.token);
|
|
1043
|
+
return this.token;
|
|
1044
|
+
}).finally(() => {
|
|
1045
|
+
this.pendingToken = null;
|
|
1046
|
+
});
|
|
1047
|
+
return this.pendingToken;
|
|
1048
|
+
}
|
|
1049
|
+
me() {
|
|
1050
|
+
return this.request("/v1/me");
|
|
1051
|
+
}
|
|
1052
|
+
announcements(lang) {
|
|
1053
|
+
return this.request(`/v1/announcements${lang ? `?lang=${encodeURIComponent(lang)}` : ""}`);
|
|
1054
|
+
}
|
|
1055
|
+
lookup(handle) {
|
|
1056
|
+
return this.request(`/v1/handles/${encodeURIComponent(handle.replace(/^@/, ""))}`);
|
|
1057
|
+
}
|
|
1058
|
+
contacts() {
|
|
1059
|
+
return this.request("/v1/contacts");
|
|
1060
|
+
}
|
|
1061
|
+
contactRequests = {
|
|
1062
|
+
list: () => this.request("/v1/contact-requests"),
|
|
1063
|
+
send: (input) => this.request("/v1/contact-requests", { method: "POST", body: JSON.stringify(input) }),
|
|
1064
|
+
accept: (handle) => this.request(`/v1/contact-requests/${encodeURIComponent(bare(handle))}/accept`, { method: "POST" }),
|
|
1065
|
+
decline: (handle) => this.request(`/v1/contact-requests/${encodeURIComponent(bare(handle))}/decline`, { method: "POST" })
|
|
1066
|
+
};
|
|
1067
|
+
removeContact(handle) {
|
|
1068
|
+
return this.request(`/v1/contacts/${encodeURIComponent(bare(handle))}`, { method: "DELETE" });
|
|
1069
|
+
}
|
|
1070
|
+
blocks = {
|
|
1071
|
+
list: () => this.request("/v1/blocks"),
|
|
1072
|
+
add: (handle) => this.request(`/v1/blocks/${encodeURIComponent(bare(handle))}`, { method: "PUT" }),
|
|
1073
|
+
remove: (handle) => this.request(`/v1/blocks/${encodeURIComponent(bare(handle))}`, { method: "DELETE" })
|
|
1074
|
+
};
|
|
1075
|
+
messages = {
|
|
1076
|
+
send: (input) => this.request("/v1/messages", { method: "POST", body: JSON.stringify(input) }),
|
|
1077
|
+
sendVoice: (input) => {
|
|
1078
|
+
const form = new FormData;
|
|
1079
|
+
if (input.group)
|
|
1080
|
+
form.set("group", input.group);
|
|
1081
|
+
else if (input.to)
|
|
1082
|
+
form.set("to", input.to);
|
|
1083
|
+
if (input.reply_to)
|
|
1084
|
+
form.set("reply_to", input.reply_to);
|
|
1085
|
+
const ext = input.audio.type.includes("mp4") ? "m4a" : input.audio.type.includes("webm") ? "webm" : "ogg";
|
|
1086
|
+
form.set("audio", input.audio, `voice.${ext}`);
|
|
1087
|
+
return this.request("/v1/messages/voice", { method: "POST", body: form });
|
|
1088
|
+
},
|
|
1089
|
+
sendFile: (input) => {
|
|
1090
|
+
const form = new FormData;
|
|
1091
|
+
if (input.group)
|
|
1092
|
+
form.set("group", input.group);
|
|
1093
|
+
else if (input.to)
|
|
1094
|
+
form.set("to", input.to);
|
|
1095
|
+
if (input.caption)
|
|
1096
|
+
form.set("caption", input.caption);
|
|
1097
|
+
if (input.reply_to)
|
|
1098
|
+
form.set("reply_to", input.reply_to);
|
|
1099
|
+
if (input.width)
|
|
1100
|
+
form.set("width", String(Math.round(input.width)));
|
|
1101
|
+
if (input.height)
|
|
1102
|
+
form.set("height", String(Math.round(input.height)));
|
|
1103
|
+
form.set("file", input.file, input.filename);
|
|
1104
|
+
return this.request("/v1/messages/attachment", { method: "POST", body: form });
|
|
1105
|
+
},
|
|
1106
|
+
sendLocation: (input) => this.request("/v1/messages/location", { method: "POST", body: JSON.stringify(input) }),
|
|
1107
|
+
edit: (messageId, text) => this.request(`/v1/messages/${messageId}`, { method: "PATCH", body: JSON.stringify({ text }) }),
|
|
1108
|
+
remove: (messageId) => this.request(`/v1/messages/${messageId}`, { method: "DELETE" }),
|
|
1109
|
+
search: (q, limit = 30) => this.request(`/v1/messages/search?${query({ q, limit })}`),
|
|
1110
|
+
group: (groupId, input = {}) => this.request(`/v1/messages?${query({ group: groupId, ...input })}`),
|
|
1111
|
+
list: (input) => this.request(`/v1/messages?${query(input)}`),
|
|
1112
|
+
react: (messageId, emoji) => this.request(`/v1/messages/${messageId}/reaction`, { method: "PUT", body: JSON.stringify({ emoji }) }),
|
|
1113
|
+
unreact: (messageId) => this.request(`/v1/messages/${messageId}/reaction`, { method: "DELETE" }),
|
|
1114
|
+
activity: (input) => this.request("/v1/activity", { method: "POST", body: JSON.stringify(input) })
|
|
1115
|
+
};
|
|
1116
|
+
conversations = {
|
|
1117
|
+
list: (input = {}) => this.request(`/v1/conversations?${query(input)}`),
|
|
1118
|
+
markRead: (conversationId) => this.request(`/v1/conversations/${conversationId}/read`, { method: "POST" }),
|
|
1119
|
+
delivered: (conversationId) => this.request(`/v1/conversations/${conversationId}/delivered`, { method: "POST" }),
|
|
1120
|
+
mute: (conversationId, until) => this.request(`/v1/conversations/${conversationId}/mute`, { method: "PUT", body: JSON.stringify(until ? { until } : {}) }),
|
|
1121
|
+
unmute: (conversationId) => this.request(`/v1/conversations/${conversationId}/mute`, { method: "DELETE" }),
|
|
1122
|
+
archive: (conversationId, archived = true) => this.request(`/v1/conversations/${conversationId}/archive`, { method: archived ? "PUT" : "DELETE" }),
|
|
1123
|
+
transfer: (input) => this.request("/v1/transfers", { method: "POST", body: JSON.stringify(input) }),
|
|
1124
|
+
transfers: (withHandle) => this.request(`/v1/transfers?${query({ with: withHandle })}`),
|
|
1125
|
+
transferHistory: (id) => this.request(`/v1/transfers/${id}/messages`)
|
|
1126
|
+
};
|
|
1127
|
+
groups = {
|
|
1128
|
+
create: (input) => this.request("/v1/groups", { method: "POST", body: JSON.stringify(input) }),
|
|
1129
|
+
get: (groupId) => this.request(`/v1/groups/${groupId}`),
|
|
1130
|
+
rename: (groupId, title) => this.request(`/v1/groups/${groupId}`, { method: "PATCH", body: JSON.stringify({ title }) }),
|
|
1131
|
+
add: (groupId, handle) => this.request(`/v1/groups/${groupId}/members`, { method: "POST", body: JSON.stringify({ handle }) }),
|
|
1132
|
+
remove: (groupId, handle) => this.request(`/v1/groups/${groupId}/members/${encodeURIComponent(bare(handle))}`, { method: "DELETE" })
|
|
1133
|
+
};
|
|
1134
|
+
calls = {
|
|
1135
|
+
create: (input) => this.request("/v1/calls", { method: "POST", body: JSON.stringify(input) }),
|
|
1136
|
+
get: (callId) => this.request(`/v1/calls/${callId}`),
|
|
1137
|
+
list: (input = {}) => this.request(`/v1/calls?${query(input)}`),
|
|
1138
|
+
answer: (callId) => this.request(`/v1/calls/${callId}/answer`, { method: "POST" }),
|
|
1139
|
+
reject: (callId) => this.request(`/v1/calls/${callId}/reject`, { method: "POST" }),
|
|
1140
|
+
hangup: (callId) => this.request(`/v1/calls/${callId}/hangup`, { method: "POST" }),
|
|
1141
|
+
audio: (callId) => this.request(`/v1/calls/${callId}/audio`, { method: "POST" })
|
|
1142
|
+
};
|
|
1143
|
+
async mediaUrl(mediaId, speed) {
|
|
1144
|
+
const res = await this.send(`/v1/media/${mediaId}${speed ? `?speed=${speed}` : ""}`, {}, false);
|
|
1145
|
+
return URL.createObjectURL(await res.blob());
|
|
1146
|
+
}
|
|
1147
|
+
realtime() {
|
|
1148
|
+
this.realtimeInstance ??= new Realtime(this);
|
|
1149
|
+
return this.realtimeInstance;
|
|
1150
|
+
}
|
|
1151
|
+
phone(options) {
|
|
1152
|
+
return new Phone(this, options);
|
|
1153
|
+
}
|
|
1154
|
+
talkie(channelId) {
|
|
1155
|
+
return new Talkie(this, channelId, this.options.audio);
|
|
1156
|
+
}
|
|
1157
|
+
channels = {
|
|
1158
|
+
list: () => this.request("/v1/channels"),
|
|
1159
|
+
get: (id) => this.request(`/v1/channels/${encodeURIComponent(id)}`),
|
|
1160
|
+
create: (input) => this.request("/v1/channels", { method: "POST", body: JSON.stringify(input) }),
|
|
1161
|
+
update: (id, input) => this.request(`/v1/channels/${encodeURIComponent(id)}`, { method: "PATCH", body: JSON.stringify(input) }),
|
|
1162
|
+
add: (id, handle) => this.request(`/v1/channels/${encodeURIComponent(id)}/members`, { method: "POST", body: JSON.stringify({ handle }) }),
|
|
1163
|
+
remove: (id, handle) => this.request(`/v1/channels/${encodeURIComponent(id)}/members/${encodeURIComponent(handle.replace(/^@/, ""))}`, {
|
|
1164
|
+
method: "DELETE"
|
|
1165
|
+
}),
|
|
1166
|
+
delete: (id) => this.request(`/v1/channels/${encodeURIComponent(id)}`, { method: "DELETE" }),
|
|
1167
|
+
accept: (id) => this.request(`/v1/channels/${encodeURIComponent(id)}/accept`, { method: "POST" }),
|
|
1168
|
+
decline: (id) => this.request(`/v1/channels/${encodeURIComponent(id)}/decline`, { method: "POST" }),
|
|
1169
|
+
transmissions: (id, options = {}) => {
|
|
1170
|
+
const q = new URLSearchParams({ limit: String(options.limit ?? 50) });
|
|
1171
|
+
if (options.before)
|
|
1172
|
+
q.set("before", options.before);
|
|
1173
|
+
return this.request(`/v1/channels/${encodeURIComponent(id)}/transmissions?${q}`);
|
|
1174
|
+
}
|
|
1175
|
+
};
|
|
1176
|
+
close() {
|
|
1177
|
+
this.realtimeInstance?.close();
|
|
1178
|
+
this.realtimeInstance = null;
|
|
1179
|
+
}
|
|
1180
|
+
}
|
|
1181
|
+
function query(input) {
|
|
1182
|
+
const params = new URLSearchParams;
|
|
1183
|
+
for (const [k, v] of Object.entries(input)) {
|
|
1184
|
+
if (v !== undefined && v !== null)
|
|
1185
|
+
params.set(k, String(v));
|
|
1186
|
+
}
|
|
1187
|
+
return params.toString();
|
|
1188
|
+
}
|
|
1189
|
+
function bare(handle) {
|
|
1190
|
+
return handle.replace(/^@/, "");
|
|
1191
|
+
}
|
|
1192
|
+
export {
|
|
1193
|
+
ringtone,
|
|
1194
|
+
ringback,
|
|
1195
|
+
playAnnouncement,
|
|
1196
|
+
announcementForError,
|
|
1197
|
+
announcementForEnd,
|
|
1198
|
+
Talkie,
|
|
1199
|
+
Realtime,
|
|
1200
|
+
PhonoError,
|
|
1201
|
+
Phono,
|
|
1202
|
+
Phone,
|
|
1203
|
+
CallAudio
|
|
1204
|
+
};
|