Preserve accumulated client implementation since v0.1.4, including local identities, multi-server state, chat, administration, audio and streaming controls. Refine official-source layout, original artwork, responsive composer overflow, settings navigation and chat scroll anchoring. Current verification: Node suite passes; isolated packaged chat and responsive control smokes pass without device capture. Native core is reused, not rebuilt in this pass. Strict whole-screen visual parity remains incomplete; no 1:1 or cross-platform acceptance claim. Local checkpoint only; no release or push.
234 lines
8.6 KiB
JavaScript
234 lines
8.6 KiB
JavaScript
'use strict';
|
|
|
|
const path = require('node:path');
|
|
const { EventEmitter } = require('node:events');
|
|
const { CoreProcess } = require('./core-process');
|
|
|
|
/** Official TS6 keeps one server connection handler per tab; this bounds the number of core processes. */
|
|
const MAX_CONNECTIONS = 8;
|
|
const ID_PATTERN = /^c[1-9][0-9]{0,8}$/;
|
|
|
|
const closedError = (id) => ({ ok: false, error: { code: 'connection_closed', message: `Server connection ${id} no longer exists` } });
|
|
|
|
/**
|
|
* Simultaneous server connections: one `teamspeach-core` process per connection, all sharing the
|
|
* profile (identity + nickname) in `dataDir`. Each core locks the profile shared and its own
|
|
* `<dataDir>/connections/<slot>` exclusively; the private key is never copied (core/src/main.rs,
|
|
* core/src/profile.rs serialize identity writes across cores).
|
|
*
|
|
* Connection ids (`c1`, `c2`, …) are never reused within a run, so a request, answer or event for a
|
|
* closed connection can never be attributed to a newer one. Slots (directories, log files) are reused.
|
|
*
|
|
* Captured microphone audio goes only to the input connection chosen by the renderer (official
|
|
* `FindAudioInputServerConnectionHandler`: the connection whose own client has the input hardware);
|
|
* changing it ends any talk spurt on the previous core first.
|
|
*
|
|
* Emits 'event' (id, coreEvent), 'status' (id, status), 'changed' (list).
|
|
*/
|
|
class ConnectionManager extends EventEmitter {
|
|
constructor({ resolveBinary, dataDir, logsDir, createCore = (options) => new CoreProcess(options), maxConnections = MAX_CONNECTIONS }) {
|
|
super();
|
|
this.resolveBinary = resolveBinary;
|
|
this.dataDir = dataDir;
|
|
this.logsDir = logsDir;
|
|
this.createCore = createCore;
|
|
this.maxConnections = maxConnections;
|
|
this.entries = new Map();
|
|
this.nextId = 1;
|
|
this.stoppingSlots = new Set();
|
|
this.inputId = null;
|
|
}
|
|
|
|
static validId(id) {
|
|
return typeof id === 'string' && ID_PATTERN.test(id);
|
|
}
|
|
|
|
_freeSlot() {
|
|
const used = new Set(Array.from(this.entries.values(), (e) => e.slot));
|
|
for (let slot = 1; ; slot += 1) if (!used.has(slot) && !this.stoppingSlots.has(slot)) return slot;
|
|
}
|
|
|
|
_info(entry) {
|
|
return {
|
|
id: entry.id,
|
|
slot: entry.slot,
|
|
core: { ...entry.status },
|
|
state: entry.state,
|
|
address: entry.address,
|
|
identityId: entry.identityId,
|
|
session: entry.session,
|
|
input: this.inputId === entry.id,
|
|
};
|
|
}
|
|
|
|
list() {
|
|
return Array.from(this.entries.values(), (e) => this._info(e));
|
|
}
|
|
|
|
get(id) {
|
|
return this.entries.get(id) ?? null;
|
|
}
|
|
|
|
/** True while any connection is connecting, connected or disconnecting. */
|
|
anyActive() {
|
|
for (const e of this.entries.values()) if (e.state !== 'disconnected') return true;
|
|
return false;
|
|
}
|
|
|
|
/** Opens a new server connection (a new core process). */
|
|
create() {
|
|
if (this.entries.size >= this.maxConnections) {
|
|
return { ok: false, error: { code: 'too_many_connections', message: `At most ${this.maxConnections} server connections can be open` } };
|
|
}
|
|
const id = `c${this.nextId++}`;
|
|
const entry = { id, slot: this._freeSlot(), core: null, status: { status: 'starting' }, state: 'disconnected', address: '', identityId: null, session: 0, stopping: null, restarting: null };
|
|
this.entries.set(id, entry);
|
|
// Announce first: the core's 'starting' status must never reach the renderer before the connection does.
|
|
this.emit('changed', this.list());
|
|
this._spawn(entry);
|
|
return { ok: true, connection: this._info(entry) };
|
|
}
|
|
|
|
_spawn(entry) {
|
|
const binary = this.resolveBinary();
|
|
if (!binary.path) {
|
|
entry.core = null;
|
|
entry.status = { status: 'missing', candidates: binary.candidates };
|
|
this.emit('status', entry.id, entry.status);
|
|
return;
|
|
}
|
|
const core = this.createCore({
|
|
binary: binary.path,
|
|
dataDir: this.dataDir,
|
|
connectionDir: path.join(this.dataDir, 'connections', String(entry.slot)),
|
|
// Slot 1 keeps the historical file name, so single-server diagnostics stay where they were.
|
|
logFile: path.join(this.logsDir, entry.slot === 1 ? 'core.log' : `core-${entry.slot}.log`),
|
|
});
|
|
entry.core = core;
|
|
// Listeners check identity: a replaced or closed core can never write into a live connection.
|
|
const current = () => this.entries.get(entry.id) === entry && entry.core === core;
|
|
core.on('status', (status) => {
|
|
if (!current()) return;
|
|
entry.status = { ...status, binary: binary.path };
|
|
if (status.status !== 'ready') {
|
|
if (entry.state !== 'disconnected') entry.session += 1;
|
|
entry.state = 'disconnected';
|
|
if (this.inputId === entry.id) this.setInput(null);
|
|
}
|
|
this.emit('status', entry.id, entry.status);
|
|
});
|
|
core.on('event', (evt) => {
|
|
if (!current()) return;
|
|
if (evt.event === 'state' && typeof evt.state === 'string') {
|
|
if ((evt.state === 'disconnected' && entry.state !== 'disconnected') || (entry.state === 'connected' && evt.state === 'connecting')) entry.session += 1;
|
|
if (typeof evt.identity_id === 'string') entry.identityId = evt.identity_id;
|
|
entry.state = evt.state;
|
|
if (typeof evt.address === 'string') entry.address = evt.address;
|
|
}
|
|
this.emit('event', entry.id, evt);
|
|
});
|
|
core.start();
|
|
}
|
|
|
|
async _stopCore(entry) {
|
|
if (entry.stopping) return entry.stopping;
|
|
const core = entry.core;
|
|
entry.core = null;
|
|
entry.state = 'disconnected';
|
|
entry.session += 1;
|
|
if (this.inputId === entry.id) this.setInput(null);
|
|
if (!core) return;
|
|
this.stoppingSlots.add(entry.slot);
|
|
entry.stopping = (async () => {
|
|
try { await core.stop(); }
|
|
finally {
|
|
core.removeAllListeners();
|
|
this.stoppingSlots.delete(entry.slot);
|
|
if (this.entries.get(entry.id) === entry && !entry.core) {
|
|
entry.status = { status: 'stopped' };
|
|
this.emit('status', entry.id, entry.status);
|
|
}
|
|
}
|
|
})();
|
|
try { await entry.stopping; }
|
|
finally { entry.stopping = null; }
|
|
}
|
|
|
|
request(id, cmd, args) {
|
|
const entry = this.entries.get(id);
|
|
if (!entry) return Promise.resolve(closedError(id));
|
|
if (!entry.core) return Promise.resolve({ ok: false, error: { code: 'core_unavailable', message: 'The core is not running' } });
|
|
return entry.core.request(cmd, args);
|
|
}
|
|
|
|
/** Selects the connection that receives captured microphone audio (`null`: none). */
|
|
setInput(id) {
|
|
if (id !== null && !this.entries.has(id)) return { ok: false, error: closedError(id).error };
|
|
if (this.inputId !== id) {
|
|
this.entries.get(this.inputId)?.core?.sendAudio('audio_end');
|
|
this.inputId = id;
|
|
this.emit('changed', this.list());
|
|
}
|
|
return { ok: true, input: this.inputId };
|
|
}
|
|
|
|
sendAudioFrame(pcmBase64, whisper) {
|
|
const entry = this.entries.get(this.inputId);
|
|
return entry?.state === 'connected' && entry.status.status === 'ready' ? entry.core?.sendAudio('audio_frame', whisper === undefined ? { pcm: pcmBase64 } : { pcm: pcmBase64, whisper }) ?? false : false;
|
|
}
|
|
|
|
endAudio() {
|
|
this.entries.get(this.inputId)?.core?.sendAudio('audio_end');
|
|
}
|
|
|
|
/** Disconnects (best effort) and stops the connection's core; its id becomes invalid. */
|
|
async close(id) {
|
|
const entry = this.entries.get(id);
|
|
if (!entry) return { ok: false, error: closedError(id).error };
|
|
if (entry.core || entry.stopping) this.stoppingSlots.add(entry.slot);
|
|
this.entries.delete(id);
|
|
if (this.inputId === id) {
|
|
entry.core?.sendAudio('audio_end');
|
|
this.inputId = null;
|
|
}
|
|
this.emit('changed', this.list());
|
|
await this._stopCore(entry);
|
|
return { ok: true };
|
|
}
|
|
|
|
async restart(id) {
|
|
const entry = this.entries.get(id);
|
|
if (!entry) return { ok: false, error: closedError(id).error };
|
|
if (entry.restarting) return entry.restarting;
|
|
entry.restarting = (async () => {
|
|
await this._stopCore(entry);
|
|
if (this.entries.get(id) !== entry) return { ok: false, error: closedError(id).error };
|
|
entry.status = { status: 'starting' };
|
|
this._spawn(entry);
|
|
return { ok: true };
|
|
})();
|
|
try { return await entry.restarting; }
|
|
finally { entry.restarting = null; }
|
|
}
|
|
|
|
/** Stops every core but keeps the connections (identity import); `startAll` respawns them. */
|
|
async stopAll() {
|
|
await Promise.all(Array.from(this.entries.values(), (e) => this._stopCore(e)));
|
|
}
|
|
|
|
startAll() {
|
|
for (const entry of this.entries.values()) {
|
|
if (entry.core) continue;
|
|
entry.status = { status: 'starting' };
|
|
this._spawn(entry);
|
|
}
|
|
}
|
|
|
|
get running() {
|
|
for (const e of this.entries.values()) if (e.core?.running) return true;
|
|
return false;
|
|
}
|
|
}
|
|
|
|
module.exports = { ConnectionManager, MAX_CONNECTIONS };
|