@pyai/sdk 0.9.2 → 0.11.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/CLI.schema.json +11 -0
- package/README.md +131 -3
- package/dist/cli-omni-template.d.ts +2 -2
- package/dist/cli-omni-template.js +2 -2
- package/dist/cli.js +39 -4
- package/dist/dialer/appServer.d.ts +21 -0
- package/dist/dialer/appServer.js +195 -0
- package/dist/dialer/dialerElement.d.ts +23 -0
- package/dist/dialer/dialerElement.js +108 -0
- package/dist/dialer/dialingQueue.d.ts +31 -0
- package/dist/dialer/dialingQueue.js +78 -0
- package/dist/dialer/index.d.ts +6 -0
- package/dist/dialer/index.js +6 -0
- package/dist/dialer/indexedDbJournal.d.ts +11 -0
- package/dist/dialer/indexedDbJournal.js +62 -0
- package/dist/dialer/managedDialer.d.ts +65 -0
- package/dist/dialer/managedDialer.js +217 -0
- package/dist/dialer/meetingRecorder.d.ts +83 -0
- package/dist/dialer/meetingRecorder.js +261 -0
- package/dist/dialer/meetingRecorderElement.d.ts +20 -0
- package/dist/dialer/meetingRecorderElement.js +138 -0
- package/dist/dialer/meetingRecordingStore.d.ts +17 -0
- package/dist/dialer/meetingRecordingStore.js +129 -0
- package/dist/dialer/serverBroker.d.ts +3 -0
- package/dist/dialer/serverBroker.js +23 -0
- package/dist/dialer/voiceSdkAudio.d.ts +33 -0
- package/dist/dialer/voiceSdkAudio.js +66 -0
- package/dist/index.d.ts +238 -6
- package/dist/index.js +67 -3
- package/package.json +24 -1
- package/src/cli-omni-template.ts +2 -2
- package/src/cli.ts +25 -4
- package/src/dialer/app/app.css +1 -0
- package/src/dialer/app/app.html +7 -0
- package/src/dialer/app/app.js +88 -0
- package/src/dialer/app/icon.svg +1 -0
- package/src/dialer/app/manifest.webmanifest +1 -0
- package/src/dialer/appServer.ts +151 -0
- package/src/dialer/dialerElement.ts +80 -0
- package/src/dialer/dialingQueue.ts +65 -0
- package/src/dialer/index.ts +6 -0
- package/src/dialer/indexedDbJournal.ts +56 -0
- package/src/dialer/managedDialer.ts +187 -0
- package/src/dialer/meetingRecorder.ts +220 -0
- package/src/dialer/meetingRecorderElement.ts +99 -0
- package/src/dialer/meetingRecordingStore.ts +99 -0
- package/src/dialer/serverBroker.ts +23 -0
- package/src/dialer/voiceSdkAudio.ts +61 -0
- package/src/index.ts +174 -5
|
@@ -0,0 +1,187 @@
|
|
|
1
|
+
import type { TelephonyBrowserSession, TelephonyBrowserSessionCreate, TelephonyCall } from "../index.ts";
|
|
2
|
+
|
|
3
|
+
/** Implement on your server using PyAI's telephony client. The browser receives
|
|
4
|
+
* a single-call capability, never an organization key or carrier credential. */
|
|
5
|
+
export interface DialerBroker {
|
|
6
|
+
create(input: TelephonyBrowserSessionCreate, idempotencyKey: string): Promise<TelephonyBrowserSession>;
|
|
7
|
+
get(callId: string): Promise<TelephonyCall>;
|
|
8
|
+
hangup(callId: string): Promise<TelephonyCall>;
|
|
9
|
+
}
|
|
10
|
+
export interface DialerIntent {
|
|
11
|
+
scope: string;
|
|
12
|
+
key: string;
|
|
13
|
+
input: TelephonyBrowserSessionCreate;
|
|
14
|
+
callId?: string;
|
|
15
|
+
stopping: boolean;
|
|
16
|
+
}
|
|
17
|
+
export interface DialerJournal {
|
|
18
|
+
read(scope: string): Promise<DialerIntent | null>;
|
|
19
|
+
write(intent: DialerIntent): Promise<void>;
|
|
20
|
+
clear(scope: string, key: string): Promise<void>;
|
|
21
|
+
}
|
|
22
|
+
export interface DialerAudio {
|
|
23
|
+
connect(session: TelephonyBrowserSession, event: (state: "ringing" | "active" | "disconnected") => void): Promise<void>;
|
|
24
|
+
disconnect(): void;
|
|
25
|
+
mute(value: boolean): void;
|
|
26
|
+
sendDigits(digits: string): void;
|
|
27
|
+
}
|
|
28
|
+
export interface DialerSnapshot {
|
|
29
|
+
state: "idle" | "preparing" | "ringing" | "active" | "stopping" | "unconfirmed" | "wrapup";
|
|
30
|
+
callId: string | null;
|
|
31
|
+
call: TelephonyCall | null;
|
|
32
|
+
muted: boolean;
|
|
33
|
+
error: string | null;
|
|
34
|
+
}
|
|
35
|
+
const terminal = (call: TelephonyCall) => ["completed", "failed", "canceled"].includes(call.status);
|
|
36
|
+
|
|
37
|
+
/** One immutable workspace/user scope per instance. Setup and stop retain the
|
|
38
|
+
* original intent through lost acknowledgments, reloads and audio failures. */
|
|
39
|
+
export class ManagedDialer {
|
|
40
|
+
private intent: DialerIntent | null = null;
|
|
41
|
+
private snapshot: DialerSnapshot = { state: "idle", callId: null, call: null, muted: false, error: null };
|
|
42
|
+
private readonly listeners = new Set<(snapshot: DialerSnapshot) => void>();
|
|
43
|
+
private operation: Promise<void> | null = null;
|
|
44
|
+
private initialized = false;
|
|
45
|
+
private readonly scope: string;
|
|
46
|
+
private readonly broker: DialerBroker;
|
|
47
|
+
private readonly journal: DialerJournal;
|
|
48
|
+
private readonly audio: DialerAudio;
|
|
49
|
+
private readonly newKey: () => string;
|
|
50
|
+
private readonly now: () => number;
|
|
51
|
+
constructor(
|
|
52
|
+
scope: string, broker: DialerBroker, journal: DialerJournal, audio: DialerAudio,
|
|
53
|
+
newKey: () => string = () => crypto.randomUUID(), now: () => number = Date.now,
|
|
54
|
+
) {
|
|
55
|
+
if (!scope.trim()) throw new Error("An authenticated workspace/user scope is required.");
|
|
56
|
+
this.scope = scope; this.broker = broker; this.journal = journal; this.audio = audio; this.newKey = newKey; this.now = now;
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
get current(): DialerSnapshot { return structuredClone(this.snapshot); }
|
|
60
|
+
subscribe(listener: (snapshot: DialerSnapshot) => void): () => void {
|
|
61
|
+
this.listeners.add(listener); listener(this.current);
|
|
62
|
+
return () => { this.listeners.delete(listener); };
|
|
63
|
+
}
|
|
64
|
+
private update(patch: Partial<DialerSnapshot>) {
|
|
65
|
+
this.snapshot = { ...this.snapshot, ...patch };
|
|
66
|
+
for (const listener of this.listeners) { try { listener(this.current); } catch { /* UI observers cannot interrupt cleanup. */ } }
|
|
67
|
+
}
|
|
68
|
+
private async exclusive(action: () => Promise<void>) {
|
|
69
|
+
if (this.operation) throw new Error("Calling operation is already in progress.");
|
|
70
|
+
const operation = action(); this.operation = operation;
|
|
71
|
+
try { await operation; } finally { if (this.operation === operation) this.operation = null; }
|
|
72
|
+
}
|
|
73
|
+
async restore(): Promise<void> {
|
|
74
|
+
return this.exclusive(async () => {
|
|
75
|
+
if (this.initialized) return;
|
|
76
|
+
const saved = await this.journal.read(this.scope);
|
|
77
|
+
if (saved && saved.scope !== this.scope) throw new Error("Saved call belongs to another workspace.");
|
|
78
|
+
this.intent = saved ? structuredClone(saved) : null;
|
|
79
|
+
this.initialized = true;
|
|
80
|
+
if (saved) {
|
|
81
|
+
this.update({ state: "unconfirmed", callId: saved.callId ?? null, error: "Recover the previous call before starting another." });
|
|
82
|
+
// Reload never consumes a new browser capability automatically.
|
|
83
|
+
if (saved.callId) await this.readStatus();
|
|
84
|
+
}
|
|
85
|
+
});
|
|
86
|
+
}
|
|
87
|
+
async start(input: TelephonyBrowserSessionCreate): Promise<void> {
|
|
88
|
+
if (!this.initialized) throw new Error("Restore the calling journal before dialing.");
|
|
89
|
+
if (this.intent) throw new Error("The previous call must finish and be wrapped up first.");
|
|
90
|
+
if (!/^\+[1-9]\d{6,14}$/.test(input.to)) throw new Error("Enter the full destination with its country code.");
|
|
91
|
+
return this.exclusive(async () => {
|
|
92
|
+
const intent: DialerIntent = { scope: this.scope, key: this.newKey(), input: structuredClone(input), stopping: false };
|
|
93
|
+
// Persist before the first network request. A storage failure cannot dial.
|
|
94
|
+
await this.journal.write(structuredClone(intent)); this.intent = intent;
|
|
95
|
+
await this.setup();
|
|
96
|
+
});
|
|
97
|
+
}
|
|
98
|
+
async retrySetup(): Promise<void> {
|
|
99
|
+
if (!this.intent) throw new Error("No call to recover.");
|
|
100
|
+
return this.exclusive(async () => {
|
|
101
|
+
if (this.intent!.callId) { await this.readStatus(); return; }
|
|
102
|
+
await this.setup();
|
|
103
|
+
});
|
|
104
|
+
}
|
|
105
|
+
private async setup() {
|
|
106
|
+
const intent = this.intent!;
|
|
107
|
+
this.update({ state: intent.stopping ? "stopping" : "preparing", error: null });
|
|
108
|
+
try {
|
|
109
|
+
const session = await this.broker.create(structuredClone(intent.input), intent.key);
|
|
110
|
+
if (session.id !== session.call_id || session.call.id !== session.call_id || session.connect_params.session_id !== session.call_id ||
|
|
111
|
+
session.transport !== "voice-sdk" || (intent.callId && intent.callId !== session.call_id)) throw new Error("Calling session identity changed.");
|
|
112
|
+
intent.callId = session.call_id;
|
|
113
|
+
await this.journal.write(structuredClone(intent));
|
|
114
|
+
const saved = await this.journal.read(this.scope);
|
|
115
|
+
if (!saved || saved.key !== intent.key || saved.callId !== intent.callId) throw new Error("Calling recovery intent changed.");
|
|
116
|
+
if (saved.stopping) intent.stopping = true;
|
|
117
|
+
this.update({ callId: session.call_id, call: session.call });
|
|
118
|
+
if (terminal(session.call)) { await this.acceptStatus(session.call); return; }
|
|
119
|
+
if (intent.stopping) { await this.stopKnown(); return; }
|
|
120
|
+
if (!session.access_token || session.expires_at <= this.now() || session.call.stop_requested) {
|
|
121
|
+
this.update({ state: "unconfirmed", error: "This session was consumed, stopped or expired. End or recover the original call." }); return;
|
|
122
|
+
}
|
|
123
|
+
await this.audio.connect(session, state => {
|
|
124
|
+
if (this.intent !== intent || intent.stopping || this.snapshot.state === "wrapup") return;
|
|
125
|
+
if (state === "disconnected") {
|
|
126
|
+
this.audio.disconnect();
|
|
127
|
+
this.update({ state: "unconfirmed", error: "Audio disconnected. Check the original call before dialing again." });
|
|
128
|
+
} else this.update({ state, error: null });
|
|
129
|
+
});
|
|
130
|
+
} catch {
|
|
131
|
+
this.audio.disconnect();
|
|
132
|
+
this.update({ state: "unconfirmed", error: "Call setup is unconfirmed. Recover or end this same attempt." });
|
|
133
|
+
}
|
|
134
|
+
}
|
|
135
|
+
async refresh(): Promise<void> {
|
|
136
|
+
if (this.operation) await this.operation;
|
|
137
|
+
return this.exclusive(() => this.readStatus());
|
|
138
|
+
}
|
|
139
|
+
private async readStatus() {
|
|
140
|
+
if (!this.intent?.callId) return;
|
|
141
|
+
try { await this.acceptStatus(await this.broker.get(this.intent.callId)); }
|
|
142
|
+
catch { this.update({ error: "Call status is unavailable. The original call is still retained." }); }
|
|
143
|
+
}
|
|
144
|
+
private async acceptStatus(call: TelephonyCall) {
|
|
145
|
+
if (!this.intent || call.id !== this.intent.callId) throw new Error("Calling status identity changed.");
|
|
146
|
+
if (this.snapshot.call && call.version < this.snapshot.call.version) return;
|
|
147
|
+
if (terminal(call)) {
|
|
148
|
+
this.audio.disconnect();
|
|
149
|
+
this.update({ call, state: "wrapup", muted: false, error: null });
|
|
150
|
+
} else this.update({ call });
|
|
151
|
+
}
|
|
152
|
+
async stop(): Promise<void> {
|
|
153
|
+
if (!this.intent) return;
|
|
154
|
+
// Mark immediately so a late create acknowledgment cannot connect audio.
|
|
155
|
+
this.intent.stopping = true; this.audio.disconnect();
|
|
156
|
+
this.update({ state: "stopping", muted: false });
|
|
157
|
+
// Await in-flight setup; never issue an independent replacement create.
|
|
158
|
+
if (this.operation) await this.operation;
|
|
159
|
+
return this.exclusive(async () => {
|
|
160
|
+
await this.journal.write(structuredClone(this.intent!));
|
|
161
|
+
if (!this.intent!.callId) await this.setup();
|
|
162
|
+
else await this.stopKnown();
|
|
163
|
+
});
|
|
164
|
+
}
|
|
165
|
+
private async stopKnown() {
|
|
166
|
+
try {
|
|
167
|
+
const call = await this.broker.hangup(this.intent!.callId!);
|
|
168
|
+
await this.acceptStatus(call);
|
|
169
|
+
if (!terminal(call)) this.update({ state: "stopping", error: null });
|
|
170
|
+
} catch { this.update({ state: "unconfirmed", error: "Stop is unconfirmed. Retry ending the same call." }); }
|
|
171
|
+
}
|
|
172
|
+
async finishWrapup(): Promise<void> {
|
|
173
|
+
return this.exclusive(async () => {
|
|
174
|
+
if (!this.intent || this.snapshot.state !== "wrapup" || !this.snapshot.call || !terminal(this.snapshot.call)) throw new Error("Confirmed call completion is required.");
|
|
175
|
+
await this.journal.clear(this.scope, this.intent.key); this.intent = null;
|
|
176
|
+
this.update({ state: "idle", callId: null, call: null, muted: false, error: null });
|
|
177
|
+
});
|
|
178
|
+
}
|
|
179
|
+
mute(value: boolean) {
|
|
180
|
+
if (this.snapshot.state !== "active") throw new Error("No active audio call.");
|
|
181
|
+
this.audio.mute(value); this.update({ muted: value });
|
|
182
|
+
}
|
|
183
|
+
sendDigits(digits: string) {
|
|
184
|
+
if (this.snapshot.state !== "active" || !/^[0-9*#w]{1,32}$/.test(digits)) throw new Error("Enter up to 32 keypad digits on an active call.");
|
|
185
|
+
this.audio.sendDigits(digits);
|
|
186
|
+
}
|
|
187
|
+
}
|
|
@@ -0,0 +1,220 @@
|
|
|
1
|
+
/** Permission-based, audio-only meeting capture. The user selects a source on
|
|
2
|
+
* every start; video is requested for the browser picker but is never recorded. */
|
|
3
|
+
export interface MeetingRecording {
|
|
4
|
+
id: string;
|
|
5
|
+
scope: string;
|
|
6
|
+
state: "recording" | "ready" | "incomplete";
|
|
7
|
+
mimeType: string;
|
|
8
|
+
sources: Array<"shared_audio" | "microphone">;
|
|
9
|
+
createdAt: number;
|
|
10
|
+
endedAt: number | null;
|
|
11
|
+
bytes: number;
|
|
12
|
+
chunks: number;
|
|
13
|
+
maxBytes: number;
|
|
14
|
+
signalObserved: { shared_audio: boolean; microphone: boolean };
|
|
15
|
+
error: string | null;
|
|
16
|
+
}
|
|
17
|
+
export interface MeetingRecordingStore {
|
|
18
|
+
/** Held for the entire capture; recovery must use the same exclusive lease. */
|
|
19
|
+
acquire(scope: string, id: string): Promise<() => void>;
|
|
20
|
+
create(recording: MeetingRecording): Promise<void>;
|
|
21
|
+
append(scope: string, id: string, sequence: number, bytes: Blob): Promise<void>;
|
|
22
|
+
finish(scope: string, id: string, state: "ready" | "incomplete", endedAt: number, error: string | null, signalObserved?: MeetingRecording["signalObserved"]): Promise<MeetingRecording>;
|
|
23
|
+
get(scope: string, id: string): Promise<MeetingRecording | null>;
|
|
24
|
+
list(scope: string): Promise<MeetingRecording[]>;
|
|
25
|
+
recover(scope: string, id: string): Promise<MeetingRecording>;
|
|
26
|
+
audio(scope: string, id: string): Promise<Blob>;
|
|
27
|
+
}
|
|
28
|
+
export interface MeetingCaptureOptions {
|
|
29
|
+
/** The host must display a recording notice before this foreground action. */
|
|
30
|
+
noticeAccepted: boolean;
|
|
31
|
+
microphone: boolean;
|
|
32
|
+
maxDurationSeconds?: number;
|
|
33
|
+
maxBytes?: number;
|
|
34
|
+
}
|
|
35
|
+
export interface MeetingCaptureEnvironment {
|
|
36
|
+
sharedAudio(): Promise<MediaStream>;
|
|
37
|
+
microphone(): Promise<MediaStream>;
|
|
38
|
+
audioContext(): AudioContext;
|
|
39
|
+
recorder(stream: MediaStream): MediaRecorder;
|
|
40
|
+
newId(): string;
|
|
41
|
+
now(): number;
|
|
42
|
+
}
|
|
43
|
+
const defaultEnvironment: MeetingCaptureEnvironment = {
|
|
44
|
+
// Do not narrow the source picker to an app selected by the host. Audio can
|
|
45
|
+
// cover a wider surface than video; the browser/OS must obtain real consent.
|
|
46
|
+
sharedAudio: () => navigator.mediaDevices.getDisplayMedia({ video: true, audio: true }),
|
|
47
|
+
microphone: () => navigator.mediaDevices.getUserMedia({ audio: { echoCancellation: true, noiseSuppression: true }, video: false }),
|
|
48
|
+
audioContext: () => new AudioContext(),
|
|
49
|
+
recorder: stream => {
|
|
50
|
+
const mimeType = ["audio/webm;codecs=opus", "audio/mp4"].find(type => MediaRecorder.isTypeSupported(type));
|
|
51
|
+
return new MediaRecorder(stream, { ...(mimeType ? { mimeType } : {}), audioBitsPerSecond: 64000 });
|
|
52
|
+
},
|
|
53
|
+
newId: () => crypto.randomUUID(), now: Date.now,
|
|
54
|
+
};
|
|
55
|
+
export interface MeetingCaptureSnapshot {
|
|
56
|
+
state: "idle" | "starting" | "recording" | "paused" | "stopping" | "ready" | "error";
|
|
57
|
+
recording: MeetingRecording | null;
|
|
58
|
+
error: string | null;
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
export class MeetingRecorder {
|
|
62
|
+
private readonly scope: string;
|
|
63
|
+
private readonly store: MeetingRecordingStore;
|
|
64
|
+
private readonly environment: MeetingCaptureEnvironment;
|
|
65
|
+
private streams: MediaStream[] = [];
|
|
66
|
+
private context: AudioContext | null = null;
|
|
67
|
+
private recorder: MediaRecorder | null = null;
|
|
68
|
+
private listeners = new Set<(snapshot: MeetingCaptureSnapshot) => void>();
|
|
69
|
+
private snapshot: MeetingCaptureSnapshot = { state: "idle", recording: null, error: null };
|
|
70
|
+
private pendingWrites: Promise<void> = Promise.resolve();
|
|
71
|
+
private writeError: Error | null = null;
|
|
72
|
+
private sequence = 0;
|
|
73
|
+
private generation = 0;
|
|
74
|
+
private starting: Promise<void> | null = null;
|
|
75
|
+
private stopping: Promise<void> | null = null;
|
|
76
|
+
private timer: ReturnType<typeof setTimeout> | null = null;
|
|
77
|
+
private watchdog: ReturnType<typeof setInterval> | null = null;
|
|
78
|
+
private analysers: Array<{ source: "shared_audio" | "microphone"; node: AnalyserNode; samples: Float32Array<ArrayBuffer> }> = [];
|
|
79
|
+
private signalObserved = { shared_audio: false, microphone: false };
|
|
80
|
+
private releaseStorage: (() => void) | null = null;
|
|
81
|
+
constructor(scope: string, store: MeetingRecordingStore, environment: MeetingCaptureEnvironment = defaultEnvironment) {
|
|
82
|
+
if (!scope.trim()) throw new Error("A workspace/user recording scope is required.");
|
|
83
|
+
this.scope = scope; this.store = store; this.environment = environment;
|
|
84
|
+
}
|
|
85
|
+
get current(): MeetingCaptureSnapshot { return structuredClone(this.snapshot); }
|
|
86
|
+
get recordingScope(): string { return this.scope; }
|
|
87
|
+
subscribe(listener: (snapshot: MeetingCaptureSnapshot) => void) {
|
|
88
|
+
this.listeners.add(listener); listener(this.current);
|
|
89
|
+
return () => { this.listeners.delete(listener); };
|
|
90
|
+
}
|
|
91
|
+
private update(patch: Partial<MeetingCaptureSnapshot>) {
|
|
92
|
+
this.snapshot = { ...this.snapshot, ...patch };
|
|
93
|
+
for (const listener of this.listeners) { try { listener(this.current); } catch { /* UI cannot prevent capture cleanup. */ } }
|
|
94
|
+
}
|
|
95
|
+
async start(options: MeetingCaptureOptions): Promise<void> {
|
|
96
|
+
if (this.starting || this.stopping || ["recording", "paused", "starting", "stopping"].includes(this.snapshot.state)) throw new Error("Finish the current recording first.");
|
|
97
|
+
if (!options.noticeAccepted) throw new Error("Confirm the recording notice before starting.");
|
|
98
|
+
const duration = options.maxDurationSeconds ?? 7200, maxBytes = options.maxBytes ?? 128 * 1024 * 1024;
|
|
99
|
+
if (!Number.isInteger(duration) || duration < 1 || duration > 7200 || !Number.isSafeInteger(maxBytes) || maxBytes < 65536 || maxBytes > 256 * 1024 * 1024) throw new Error("Recording limits must be 1–7200 seconds and 64 KiB–256 MiB.");
|
|
100
|
+
const generation = ++this.generation;
|
|
101
|
+
this.pendingWrites = Promise.resolve(); this.writeError = null; this.sequence = 0;
|
|
102
|
+
this.signalObserved = { shared_audio: false, microphone: false };
|
|
103
|
+
this.update({ state: "starting", recording: null, error: null });
|
|
104
|
+
const prepare = this.prepare(options, generation, duration, maxBytes); this.starting = prepare;
|
|
105
|
+
try { await prepare; } finally { if (this.starting === prepare) this.starting = null; }
|
|
106
|
+
}
|
|
107
|
+
private async prepare(options: MeetingCaptureOptions, generation: number, duration: number, maxBytes: number) {
|
|
108
|
+
try {
|
|
109
|
+
const shared = await this.environment.sharedAudio(); this.streams.push(shared);
|
|
110
|
+
if (generation !== this.generation) { await this.release(); return; }
|
|
111
|
+
if (!shared.getAudioTracks().some(track => track.readyState === "live" && track.enabled)) throw new Error("The selected source has no shared audio. Enable sharing audio or choose a supported tab or system source.");
|
|
112
|
+
const sources: MeetingRecording["sources"] = ["shared_audio"];
|
|
113
|
+
if (options.microphone) {
|
|
114
|
+
const mic = await this.environment.microphone(); this.streams.push(mic);
|
|
115
|
+
if (generation !== this.generation) { await this.release(); return; }
|
|
116
|
+
if (!mic.getAudioTracks().some(track => track.readyState === "live" && track.enabled)) throw new Error("The microphone is unavailable.");
|
|
117
|
+
sources.push("microphone");
|
|
118
|
+
}
|
|
119
|
+
const context = this.environment.audioContext(); this.context = context;
|
|
120
|
+
await context.resume();
|
|
121
|
+
if (generation !== this.generation) { await this.release(); return; }
|
|
122
|
+
const destination = context.createMediaStreamDestination();
|
|
123
|
+
for (const [index, stream] of this.streams.entries()) {
|
|
124
|
+
const audio = new MediaStream(stream.getAudioTracks());
|
|
125
|
+
const gain = context.createGain(); gain.gain.value = this.streams.length > 1 ? 0.5 : 1;
|
|
126
|
+
const analyser = context.createAnalyser(); analyser.fftSize = 512;
|
|
127
|
+
context.createMediaStreamSource(audio).connect(analyser).connect(gain).connect(destination);
|
|
128
|
+
this.analysers.push({ source: index === 0 ? "shared_audio" : "microphone", node: analyser, samples: new Float32Array(512) });
|
|
129
|
+
}
|
|
130
|
+
const recorder = this.environment.recorder(destination.stream); this.recorder = recorder;
|
|
131
|
+
const recording: MeetingRecording = { id: this.environment.newId(), scope: this.scope, state: "recording", mimeType: recorder.mimeType,
|
|
132
|
+
sources, createdAt: this.environment.now(), endedAt: null, bytes: 0, chunks: 0, maxBytes, signalObserved: { ...this.signalObserved }, error: null };
|
|
133
|
+
this.releaseStorage = await this.store.acquire(this.scope, recording.id);
|
|
134
|
+
await this.store.create(recording);
|
|
135
|
+
if (generation !== this.generation) {
|
|
136
|
+
await this.store.finish(this.scope, recording.id, "incomplete", this.environment.now(), "Capture was cancelled before audio started.");
|
|
137
|
+
await this.release(); return;
|
|
138
|
+
}
|
|
139
|
+
this.update({ recording, state: "recording" });
|
|
140
|
+
recorder.ondataavailable = event => {
|
|
141
|
+
if (!event.data.size) return;
|
|
142
|
+
const sequence = this.sequence++;
|
|
143
|
+
this.pendingWrites = this.pendingWrites.then(async () => {
|
|
144
|
+
if (this.writeError) return;
|
|
145
|
+
await this.store.append(this.scope, recording.id, sequence, event.data);
|
|
146
|
+
const stored = await this.store.get(this.scope, recording.id);
|
|
147
|
+
if (stored) this.update({ recording: stored });
|
|
148
|
+
}).catch(error => {
|
|
149
|
+
this.writeError = error instanceof Error ? error : new Error("Recording storage failed.");
|
|
150
|
+
void this.stop();
|
|
151
|
+
});
|
|
152
|
+
};
|
|
153
|
+
recorder.onerror = () => { this.writeError = new Error("Audio capture failed; the saved recording may be incomplete."); void this.stop(); };
|
|
154
|
+
// A stop from the browser/OS source chooser must also release the mic.
|
|
155
|
+
for (const stream of this.streams) for (const track of stream.getTracks()) track.addEventListener("ended", () => void this.stop(), { once: true });
|
|
156
|
+
recorder.start(1000);
|
|
157
|
+
this.timer = setTimeout(() => void this.stop(), duration * 1000);
|
|
158
|
+
this.watchdog = setInterval(() => {
|
|
159
|
+
if (this.snapshot.state === "recording") for (const analyser of this.analysers) {
|
|
160
|
+
analyser.node.getFloatTimeDomainData(analyser.samples);
|
|
161
|
+
if (analyser.samples.some(sample => Math.abs(sample) > 0.00001)) this.signalObserved[analyser.source] = true;
|
|
162
|
+
}
|
|
163
|
+
if (this.streams.some(stream => stream.getAudioTracks().some(track => track.readyState !== "live" || !track.enabled))) {
|
|
164
|
+
this.writeError = new Error("An audio source stopped; the saved recording may be incomplete."); void this.stop();
|
|
165
|
+
}
|
|
166
|
+
}, 250);
|
|
167
|
+
} catch (error) {
|
|
168
|
+
await this.release();
|
|
169
|
+
if (generation === this.generation) this.update({ state: "error", error: error instanceof Error ? error.message : "Meeting capture could not start." });
|
|
170
|
+
throw error;
|
|
171
|
+
}
|
|
172
|
+
}
|
|
173
|
+
pause() {
|
|
174
|
+
if (this.snapshot.state !== "recording" || !this.recorder) throw new Error("No recording to pause.");
|
|
175
|
+
this.recorder.pause(); this.update({ state: "paused" });
|
|
176
|
+
}
|
|
177
|
+
resume() {
|
|
178
|
+
if (this.snapshot.state !== "paused" || !this.recorder) throw new Error("No paused recording.");
|
|
179
|
+
this.recorder.resume(); this.update({ state: "recording" });
|
|
180
|
+
}
|
|
181
|
+
async stop(): Promise<void> {
|
|
182
|
+
if (this.stopping) return this.stopping;
|
|
183
|
+
++this.generation;
|
|
184
|
+
const finish = this.finish(); this.stopping = finish;
|
|
185
|
+
try { await finish; } finally { if (this.stopping === finish) this.stopping = null; }
|
|
186
|
+
}
|
|
187
|
+
private async finish() {
|
|
188
|
+
this.update({ state: "stopping" });
|
|
189
|
+
if (this.starting) await this.starting.catch(() => {});
|
|
190
|
+
const recorder = this.recorder, recording = this.snapshot.recording;
|
|
191
|
+
try {
|
|
192
|
+
if (recorder && recorder.state !== "inactive") {
|
|
193
|
+
await new Promise<void>(resolve => {
|
|
194
|
+
const timeout = setTimeout(() => { this.writeError = new Error("Audio finalization was not acknowledged."); resolve(); }, 5000);
|
|
195
|
+
recorder.addEventListener("stop", () => { clearTimeout(timeout); resolve(); }, { once: true });
|
|
196
|
+
try { recorder.stop(); } catch { clearTimeout(timeout); this.writeError = new Error("Audio finalization failed."); resolve(); }
|
|
197
|
+
});
|
|
198
|
+
}
|
|
199
|
+
await this.pendingWrites;
|
|
200
|
+
if (recording) {
|
|
201
|
+
const stored = await this.store.get(this.scope, recording.id);
|
|
202
|
+
const error = this.writeError?.message ?? (!stored?.bytes ? "No audio was saved." : !this.signalObserved.shared_audio ? "No sound was detected from the shared source. Check this recording before using it." : null);
|
|
203
|
+
const final = await this.store.finish(this.scope, recording.id, error ? "incomplete" : "ready", this.environment.now(), error, { ...this.signalObserved });
|
|
204
|
+
this.update({ state: error ? "error" : "ready", recording: final, error });
|
|
205
|
+
} else this.update({ state: "idle", error: null });
|
|
206
|
+
} catch (error) {
|
|
207
|
+
this.update({ state: "error", error: error instanceof Error ? error.message : "Recording finalization failed; saved chunks remain recoverable." });
|
|
208
|
+
} finally { await this.release(); }
|
|
209
|
+
}
|
|
210
|
+
private async release() {
|
|
211
|
+
if (this.timer) clearTimeout(this.timer); if (this.watchdog) clearInterval(this.watchdog);
|
|
212
|
+
this.timer = null; this.watchdog = null;
|
|
213
|
+
for (const stream of this.streams) for (const track of stream.getTracks()) { try { track.stop(); } catch { /* Release the remaining sources. */ } }
|
|
214
|
+
this.streams = []; this.recorder = null;
|
|
215
|
+
this.releaseStorage?.(); this.releaseStorage = null;
|
|
216
|
+
this.analysers = [];
|
|
217
|
+
const context = this.context; this.context = null;
|
|
218
|
+
if (context && context.state !== "closed") await context.close().catch(() => {});
|
|
219
|
+
}
|
|
220
|
+
}
|
|
@@ -0,0 +1,99 @@
|
|
|
1
|
+
import type { MeetingRecorder, MeetingCaptureSnapshot } from "./meetingRecorder.ts";
|
|
2
|
+
import type { MeetingRecordingStore } from "./meetingRecorder.ts";
|
|
3
|
+
|
|
4
|
+
/** Foreground capture controls. The native browser/OS picker is always shown;
|
|
5
|
+
* the application never silently chooses a user's window or microphone. */
|
|
6
|
+
export class PyaiMeetingRecorderElement extends HTMLElement {
|
|
7
|
+
private root: ShadowRoot;
|
|
8
|
+
private recorder: MeetingRecorder | null = null;
|
|
9
|
+
private store: MeetingRecordingStore | null = null;
|
|
10
|
+
private unsubscribe: (() => void) | null = null;
|
|
11
|
+
private historyGeneration = 0;
|
|
12
|
+
constructor() {
|
|
13
|
+
super(); this.root = this.attachShadow({ mode: "open" });
|
|
14
|
+
this.root.innerHTML = `<style>
|
|
15
|
+
:host{display:block;max-width:440px;color:#202332;font:14px/1.5 system-ui,sans-serif;--recorder-accent:#5b55e7}*{box-sizing:border-box}section{background:#fff;border:1px solid #e7e8ef;border-radius:24px;padding:26px;box-shadow:0 16px 56px #25284c12}h2{margin:0 0 8px;font-size:19px}.description,.hint{color:#737b8e;font-size:13px;margin:0 0 20px}.status{background:#f5f5fc;border-radius:14px;padding:16px;margin-bottom:20px;display:flex;gap:10px;align-items:center}.dot{width:9px;height:9px;border-radius:50%;background:#a6abba}.dot.active{background:#e33f56;box-shadow:0 0 0 5px #e33f5612}label{display:flex;gap:10px;margin:14px 0;align-items:flex-start}input{accent-color:var(--recorder-accent);margin-top:4px}.actions{display:flex;gap:8px;margin-top:22px}button{font:600 13px system-ui;cursor:pointer;border:0;border-radius:13px;padding:14px 18px;min-height:46px;background:#f1f2f7;color:#535b70}button.primary{flex:1;background:var(--recorder-accent);color:white}button.end{background:#da4055}button:disabled{opacity:.45;cursor:default}button:focus-visible{outline:3px solid #bdb8ff;outline-offset:2px}.error{color:#b42338;font-size:12px;min-height:18px}.saved{font-size:12px;color:#667085;overflow-wrap:anywhere}.hint{font-size:11px;margin:16px 0 0}
|
|
16
|
+
</style><section><h2>Record a meeting</h2><p class="description">Record shared audio and your microphone. Choose a meeting tab or a supported system audio source.</p>
|
|
17
|
+
<div class="status" role="status" aria-live="polite"><span class="dot"></span><span data-status>Ready when you are</span></div>
|
|
18
|
+
<label><input type="checkbox" data-notice><span>Everyone has been informed and I’m ready to record.</span></label>
|
|
19
|
+
<label><input type="checkbox" data-microphone checked><span>Include my microphone</span></label>
|
|
20
|
+
<div class="actions"><button class="primary" data-start disabled>Choose audio & record</button><button data-pause disabled>Pause</button><button data-download hidden>Save audio</button></div>
|
|
21
|
+
<p class="error" role="alert"></p><p class="saved"></p><p class="hint">Saved privately in this browser. Nothing is uploaded until your app explicitly submits it. Video is never saved.</p>
|
|
22
|
+
<details><summary>Saved recordings</summary><button data-refresh>Refresh recordings</button><ul data-history></ul></details></section>`;
|
|
23
|
+
this.root.querySelector("[data-notice]")!.addEventListener("change", () => { if (this.recorder) this.render(this.recorder.current); });
|
|
24
|
+
this.root.querySelector("[data-start]")!.addEventListener("click", () => void this.run(async () => {
|
|
25
|
+
if (!this.recorder) return;
|
|
26
|
+
if (["starting", "recording", "paused", "stopping"].includes(this.recorder.current.state)) await this.recorder.stop();
|
|
27
|
+
else await this.recorder.start({ noticeAccepted: this.root.querySelector<HTMLInputElement>("[data-notice]")!.checked,
|
|
28
|
+
microphone: this.root.querySelector<HTMLInputElement>("[data-microphone]")!.checked });
|
|
29
|
+
}));
|
|
30
|
+
this.root.querySelector("[data-pause]")!.addEventListener("click", () => {
|
|
31
|
+
if (!this.recorder) return;
|
|
32
|
+
try { this.recorder.current.state === "paused" ? this.recorder.resume() : this.recorder.pause(); }
|
|
33
|
+
catch (error) { this.showError(error); }
|
|
34
|
+
});
|
|
35
|
+
this.root.querySelector("[data-download]")!.addEventListener("click", () => void this.download());
|
|
36
|
+
this.root.querySelector("[data-refresh]")!.addEventListener("click", () => void this.run(() => this.refreshHistory()));
|
|
37
|
+
}
|
|
38
|
+
bind(recorder: MeetingRecorder, store: MeetingRecordingStore) {
|
|
39
|
+
if (this.recorder && this.recorder !== recorder && ["starting", "recording", "paused", "stopping"].includes(this.recorder.current.state)) throw new Error("Stop the current recording before switching workspaces.");
|
|
40
|
+
this.unsubscribe?.(); this.recorder = recorder; this.store = store; this.unsubscribe = recorder.subscribe(snapshot => this.render(snapshot));
|
|
41
|
+
void this.run(() => this.refreshHistory());
|
|
42
|
+
}
|
|
43
|
+
connectedCallback() { if (this.recorder && !this.unsubscribe) this.unsubscribe = this.recorder.subscribe(snapshot => this.render(snapshot)); }
|
|
44
|
+
disconnectedCallback() {
|
|
45
|
+
this.unsubscribe?.(); this.unsubscribe = null;
|
|
46
|
+
++this.historyGeneration;
|
|
47
|
+
// Removing the only visible controls cannot leave a hidden capture running.
|
|
48
|
+
if (this.recorder && ["starting", "recording", "paused"].includes(this.recorder.current.state)) void this.recorder.stop();
|
|
49
|
+
}
|
|
50
|
+
private render(snapshot: MeetingCaptureSnapshot) {
|
|
51
|
+
const labels = { idle: "Ready when you are", starting: "Waiting for your audio selection…", recording: "Recording your selected audio", paused: "Recording paused", stopping: "Saving your audio…", ready: "Recording saved", error: "Recording needs attention" };
|
|
52
|
+
this.root.querySelector("[data-status]")!.textContent = labels[snapshot.state];
|
|
53
|
+
this.root.querySelector(".dot")!.classList.toggle("active", snapshot.state === "recording");
|
|
54
|
+
const active = ["starting", "recording", "paused", "stopping"].includes(snapshot.state);
|
|
55
|
+
const start = this.root.querySelector<HTMLButtonElement>("[data-start]")!;
|
|
56
|
+
start.textContent = active ? "Stop recording" : "Choose audio & record";
|
|
57
|
+
start.disabled = snapshot.state === "stopping" || !this.recorder || !active && !this.root.querySelector<HTMLInputElement>("[data-notice]")!.checked;
|
|
58
|
+
start.classList.toggle("end", active);
|
|
59
|
+
const pause = this.root.querySelector<HTMLButtonElement>("[data-pause]")!;
|
|
60
|
+
pause.disabled = !["recording", "paused"].includes(snapshot.state); pause.textContent = snapshot.state === "paused" ? "Resume" : "Pause";
|
|
61
|
+
this.root.querySelector<HTMLInputElement>("[data-notice]")!.disabled = active;
|
|
62
|
+
this.root.querySelector<HTMLInputElement>("[data-microphone]")!.disabled = active;
|
|
63
|
+
this.root.querySelector<HTMLButtonElement>("[data-download]")!.hidden = !snapshot.recording?.bytes || active;
|
|
64
|
+
this.root.querySelector(".error")!.textContent = snapshot.error ?? "";
|
|
65
|
+
this.root.querySelector(".saved")!.textContent = snapshot.recording?.bytes ? `${Math.ceil(snapshot.recording.bytes / 1024)} KB saved · ${snapshot.recording.state === "incomplete" ? "Review incomplete recording" : "Audio only"}` : "";
|
|
66
|
+
}
|
|
67
|
+
private async refreshHistory() {
|
|
68
|
+
const recorder = this.recorder, store = this.store, generation = ++this.historyGeneration;
|
|
69
|
+
if (!recorder || !store) return;
|
|
70
|
+
const records = await store.list(recorder.recordingScope);
|
|
71
|
+
if (generation !== this.historyGeneration || recorder !== this.recorder) return;
|
|
72
|
+
const list = this.root.querySelector("[data-history]")!; list.replaceChildren();
|
|
73
|
+
for (const recording of records.slice(0, 40)) {
|
|
74
|
+
const item = document.createElement("li"), label = document.createElement("p"), action = document.createElement("button");
|
|
75
|
+
label.textContent = `${new Date(recording.createdAt).toLocaleString()} · ${Math.ceil(recording.bytes / 1024)} KB · ${recording.state === "ready" ? "Saved" : recording.state === "incomplete" ? "Incomplete — review audio" : "Active or interrupted"}`;
|
|
76
|
+
action.textContent = recording.state === "recording" ? "Recover interrupted recording" : "Save recording";
|
|
77
|
+
action.addEventListener("click", () => void this.run(async () => {
|
|
78
|
+
if (recorder !== this.recorder) return;
|
|
79
|
+
if (recording.state === "recording") { await store.recover(recording.scope, recording.id); await this.refreshHistory(); }
|
|
80
|
+
else await this.download(recording);
|
|
81
|
+
}));
|
|
82
|
+
item.append(label, action); list.append(item);
|
|
83
|
+
}
|
|
84
|
+
if (!records.length) { const item = document.createElement("li"); item.textContent = "No saved recordings in this workspace."; list.append(item); }
|
|
85
|
+
}
|
|
86
|
+
private async download(selected?: MeetingCaptureSnapshot["recording"]) {
|
|
87
|
+
await this.run(async () => {
|
|
88
|
+
const recording = selected ?? this.recorder?.current.recording;
|
|
89
|
+
if (!recording || !this.store) throw new Error("No saved recording.");
|
|
90
|
+
if (recording.scope !== this.recorder?.recordingScope) throw new Error("No recording in this workspace.");
|
|
91
|
+
const blob = await this.store.audio(recording.scope, recording.id), url = URL.createObjectURL(blob);
|
|
92
|
+
const link = document.createElement("a"); link.href = url; link.download = `Meeting-${new Date(recording.createdAt).toISOString().replace(/[:.]/g, "-")}.${recording.mimeType.includes("mp4") ? "m4a" : "webm"}`;
|
|
93
|
+
link.click(); setTimeout(() => URL.revokeObjectURL(url), 60000);
|
|
94
|
+
});
|
|
95
|
+
}
|
|
96
|
+
private showError(error: unknown) { this.root.querySelector(".error")!.textContent = error instanceof Error ? error.message : "Recording action failed."; }
|
|
97
|
+
private async run(action: () => Promise<void>) { try { await action(); } catch (error) { this.showError(error); } }
|
|
98
|
+
}
|
|
99
|
+
if (!customElements.get("pyai-meeting-recorder")) customElements.define("pyai-meeting-recorder", PyaiMeetingRecorderElement);
|
|
@@ -0,0 +1,99 @@
|
|
|
1
|
+
import type { MeetingRecording, MeetingRecordingStore } from "./meetingRecorder.ts";
|
|
2
|
+
|
|
3
|
+
/** Private, scoped chunk storage. Completed and interrupted captures survive
|
|
4
|
+
* reload; storage errors never cause a silent fallback to public uploads. */
|
|
5
|
+
export class IndexedDbMeetingRecordingStore implements MeetingRecordingStore {
|
|
6
|
+
private readonly database: Promise<IDBDatabase>;
|
|
7
|
+
constructor(name = "pyai-meeting-recordings") {
|
|
8
|
+
this.database = new Promise((resolve, reject) => {
|
|
9
|
+
const request = indexedDB.open(name, 1);
|
|
10
|
+
request.onupgradeneeded = () => {
|
|
11
|
+
request.result.createObjectStore("recordings", { keyPath: ["scope", "id"] });
|
|
12
|
+
const chunks = request.result.createObjectStore("chunks", { keyPath: ["scope", "id", "sequence"] });
|
|
13
|
+
chunks.createIndex("recording", ["scope", "id"]);
|
|
14
|
+
};
|
|
15
|
+
request.onsuccess = () => { request.result.onversionchange = () => request.result.close(); resolve(request.result); };
|
|
16
|
+
request.onerror = () => reject(new Error("Private recording storage is unavailable."));
|
|
17
|
+
request.onblocked = () => reject(new Error("Close the older recorder tab to upgrade storage."));
|
|
18
|
+
});
|
|
19
|
+
}
|
|
20
|
+
private lockName(scope: string, id: string) { return `pyai-meeting:${JSON.stringify([scope, id])}`; }
|
|
21
|
+
async acquire(scope: string, id: string): Promise<() => void> {
|
|
22
|
+
if (!navigator.locks) throw new Error("This browser cannot safely recover meeting recordings. Use a current supported browser.");
|
|
23
|
+
return new Promise((resolve, reject) => {
|
|
24
|
+
void navigator.locks.request(this.lockName(scope, id), { ifAvailable: true }, async lock => {
|
|
25
|
+
if (!lock) throw new Error("This recording is active in another tab.");
|
|
26
|
+
await new Promise<void>(release => resolve(release));
|
|
27
|
+
}).catch(reject);
|
|
28
|
+
});
|
|
29
|
+
}
|
|
30
|
+
async recover(scope: string, id: string): Promise<MeetingRecording> {
|
|
31
|
+
const release = await this.acquire(scope, id);
|
|
32
|
+
try {
|
|
33
|
+
return await this.finish(scope, id, "incomplete", Date.now(), "Recording was interrupted. Saved audio was recovered; review it before use.");
|
|
34
|
+
} finally { release(); }
|
|
35
|
+
}
|
|
36
|
+
private async transact<T>(stores: string[], mode: IDBTransactionMode, action: (tx: IDBTransaction, done: (value: T) => void, fail: (message: string) => void) => void): Promise<T> {
|
|
37
|
+
const database = await this.database;
|
|
38
|
+
return new Promise((resolve, reject) => {
|
|
39
|
+
const tx = database.transaction(stores, mode); let value: T, error: string | null = null;
|
|
40
|
+
tx.oncomplete = () => resolve(value);
|
|
41
|
+
tx.onerror = tx.onabort = () => reject(new Error(error ?? "Recording storage failed; earlier audio remains saved."));
|
|
42
|
+
action(tx, next => { value = next; }, message => { error = message; tx.abort(); });
|
|
43
|
+
});
|
|
44
|
+
}
|
|
45
|
+
create(recording: MeetingRecording): Promise<void> {
|
|
46
|
+
return this.transact(["recordings"], "readwrite", (tx, done) => { tx.objectStore("recordings").add(structuredClone(recording)); done(undefined); });
|
|
47
|
+
}
|
|
48
|
+
append(scope: string, id: string, sequence: number, bytes: Blob): Promise<void> {
|
|
49
|
+
return this.transact(["recordings", "chunks"], "readwrite", (tx, done, fail) => {
|
|
50
|
+
const records = tx.objectStore("recordings"), request = records.get([scope, id]);
|
|
51
|
+
request.onsuccess = () => {
|
|
52
|
+
const current = request.result as MeetingRecording | undefined;
|
|
53
|
+
if (!current || current.state !== "recording" || current.chunks !== sequence) { fail("Recording chunk sequence changed."); return; }
|
|
54
|
+
if (current.bytes + bytes.size > current.maxBytes) { fail("Recording storage limit reached; earlier audio remains saved."); return; }
|
|
55
|
+
tx.objectStore("chunks").add({ scope, id, sequence, bytes });
|
|
56
|
+
records.put({ ...current, bytes: current.bytes + bytes.size, chunks: sequence + 1 }); done(undefined);
|
|
57
|
+
};
|
|
58
|
+
});
|
|
59
|
+
}
|
|
60
|
+
get(scope: string, id: string): Promise<MeetingRecording | null> {
|
|
61
|
+
return this.transact(["recordings"], "readonly", (tx, done) => {
|
|
62
|
+
const request = tx.objectStore("recordings").get([scope, id]); request.onsuccess = () => done(request.result ?? null);
|
|
63
|
+
});
|
|
64
|
+
}
|
|
65
|
+
finish(scope: string, id: string, state: "ready" | "incomplete", endedAt: number, error: string | null, signalObserved?: MeetingRecording["signalObserved"]): Promise<MeetingRecording> {
|
|
66
|
+
return this.transact(["recordings"], "readwrite", (tx, done, fail) => {
|
|
67
|
+
const records = tx.objectStore("recordings"), request = records.get([scope, id]);
|
|
68
|
+
request.onsuccess = () => {
|
|
69
|
+
const current = request.result as MeetingRecording | undefined;
|
|
70
|
+
if (!current) { fail("No recording in this workspace."); return; }
|
|
71
|
+
if (current.state !== "recording") { done(current); return; }
|
|
72
|
+
const final = { ...current, state, endedAt, error, ...(signalObserved ? { signalObserved } : {}) }; records.put(final); done(final);
|
|
73
|
+
};
|
|
74
|
+
});
|
|
75
|
+
}
|
|
76
|
+
list(scope: string): Promise<MeetingRecording[]> {
|
|
77
|
+
return this.transact(["recordings"], "readonly", (tx, done) => {
|
|
78
|
+
const request = tx.objectStore("recordings").getAll(IDBKeyRange.bound([scope, ""], [scope, "\uffff"]));
|
|
79
|
+
request.onsuccess = () => done((request.result as MeetingRecording[]).sort((a, b) => b.createdAt - a.createdAt));
|
|
80
|
+
});
|
|
81
|
+
}
|
|
82
|
+
async audio(scope: string, id: string): Promise<Blob> {
|
|
83
|
+
return this.transact(["recordings", "chunks"], "readonly", (tx, done, fail) => {
|
|
84
|
+
const record = tx.objectStore("recordings").get([scope, id]);
|
|
85
|
+
record.onsuccess = () => {
|
|
86
|
+
const current = record.result as MeetingRecording | undefined;
|
|
87
|
+
if (!current || current.state === "recording" || !current.bytes) { fail("Stop or recover this recording before downloading it."); return; }
|
|
88
|
+
const chunks = tx.objectStore("chunks").index("recording").getAll(IDBKeyRange.only([scope, id]));
|
|
89
|
+
chunks.onsuccess = () => {
|
|
90
|
+
const rows = chunks.result as Array<{ sequence: number; bytes: Blob }>;
|
|
91
|
+
rows.sort((a, b) => a.sequence - b.sequence);
|
|
92
|
+
if (rows.length !== current.chunks || rows.some((row, i) => row.sequence !== i)) { fail("Saved audio is incomplete; preserve its chunks for recovery."); return; }
|
|
93
|
+
const blob = new Blob(rows.map(row => row.bytes), { type: current.mimeType });
|
|
94
|
+
if (blob.size !== current.bytes) { fail("Saved recording size changed."); return; } done(blob);
|
|
95
|
+
};
|
|
96
|
+
};
|
|
97
|
+
});
|
|
98
|
+
}
|
|
99
|
+
}
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
/** Server-only broker. Never import this module into a browser bundle. */
|
|
2
|
+
import { createHash } from "node:crypto";
|
|
3
|
+
import type { PyAI, TelephonyBrowserSessionCreate } from "../index.ts";
|
|
4
|
+
import type { DialerBroker } from "./managedDialer.ts";
|
|
5
|
+
|
|
6
|
+
export function createServerDialerBroker(sdk: PyAI, authenticatedUserId: string): DialerBroker {
|
|
7
|
+
if (!authenticatedUserId.trim()) throw new Error("An authenticated user is required.");
|
|
8
|
+
const ownedCall = async (id: string) => {
|
|
9
|
+
const call = await sdk.telephony.calls.get(id);
|
|
10
|
+
if (call.call_type !== "human" || call.user_id !== authenticatedUserId) throw new Error("No such call.");
|
|
11
|
+
return call;
|
|
12
|
+
};
|
|
13
|
+
return {
|
|
14
|
+
async create(input: TelephonyBrowserSessionCreate, key: string) {
|
|
15
|
+
if (!key || key.length > 255 || /[\r\n]/.test(key)) throw new Error("A valid Idempotency-Key is required.");
|
|
16
|
+
// Separate users cannot collide on an organization-wide caller-chosen key.
|
|
17
|
+
const scopedKey = "dialer:" + createHash("sha256").update(authenticatedUserId).update("\0").update(key).digest("hex");
|
|
18
|
+
return sdk.telephony.browserSessions.create({ ...input, user_id: authenticatedUserId }, { idempotencyKey: scopedKey });
|
|
19
|
+
},
|
|
20
|
+
get: ownedCall,
|
|
21
|
+
async hangup(id: string) { await ownedCall(id); return sdk.telephony.calls.hangup(id); },
|
|
22
|
+
};
|
|
23
|
+
}
|