Compare commits
31
Commits
macos
..
a351116f58
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
a351116f58 | ||
|
|
bb31b142c9 | ||
|
|
0cbad12e49 | ||
|
|
b0f7d294d8 | ||
|
|
06cb6a7dd1 | ||
|
|
bf960f49bb | ||
|
|
9a2bec6d2f | ||
|
|
87a1370ad4 | ||
|
|
51245db256 | ||
|
|
b3fbe31a2d | ||
|
|
955bfdfe07 | ||
|
|
a7a488403f | ||
|
|
22bb66b680 | ||
|
|
144caac183 | ||
|
|
b7911badb2 | ||
|
|
dfe5db979a | ||
|
|
d3558388ad | ||
|
|
8d2b83be0a | ||
|
|
861448f565 | ||
|
|
32158079c6 | ||
|
|
c21433b9eb | ||
|
|
865d40b7db | ||
|
|
bc2d5a0940 | ||
|
|
ad214f644b | ||
|
|
f0cf363408 | ||
|
|
8a7e98ae47 | ||
|
|
17afd6e5f1 | ||
|
|
b65e6cc791 | ||
|
|
1c5bdeddb5 | ||
|
|
530c3a10b2 | ||
|
|
312d47d677 |
@@ -9,6 +9,7 @@ pnpm-lock.yaml
|
||||
.env.local
|
||||
.env.*.local
|
||||
server/.env
|
||||
server/config/config.yaml
|
||||
client/.env
|
||||
|
||||
# Keep .env.example files (templates)
|
||||
@@ -55,3 +56,6 @@ server.log
|
||||
|
||||
# Runtime files
|
||||
/tmp/ptt-live.pid
|
||||
|
||||
# Certificats SSL locaux (mkcert) - contiennent des clés privées
|
||||
certs/
|
||||
|
||||
@@ -208,6 +208,11 @@ PTT Live/
|
||||
./install.sh # Détecte OS, configure tout automatiquement
|
||||
|
||||
# Démarrage rapide
|
||||
|
||||
# Option 1 : Application Desktop (Interface graphique)
|
||||
./start-desktop.sh # Lance l'app Electron avec dashboard
|
||||
|
||||
# Option 2 : Mode CLI (deux terminaux)
|
||||
./start.sh --dev # Mode développement
|
||||
./start.sh # Mode production
|
||||
|
||||
@@ -223,6 +228,44 @@ npm install
|
||||
npm run dev
|
||||
```
|
||||
|
||||
## Application Desktop (v0.3.0)
|
||||
|
||||
### Interface Electron
|
||||
- **Main Process** : spawn serveur Node.js, IPC handlers
|
||||
- **Renderer Process** : dashboard HTML/CSS/JS
|
||||
- **Communication** : IPC sécurisé (contextBridge) + HTTP vers API admin
|
||||
|
||||
### Fonctionnalités
|
||||
- ✅ **Dashboard** : stats temps réel, utilisateurs, QR Code
|
||||
- ✅ **Configuration** : devices audio, sample rate, bitrate, jitter
|
||||
- ✅ **Groupes** : CRUD complet via API admin
|
||||
- ✅ **Monitoring** : logs filtrables (error/warn/info/debug)
|
||||
- ✅ **Notifications** : toast visuelles avec auto-dismiss
|
||||
- 🚧 **VU-mètres** : WebSocket audio levels (prévu)
|
||||
|
||||
### Structure
|
||||
```
|
||||
electron/
|
||||
├── main.js # Main Process (spawn serveur)
|
||||
├── preload.js # IPC bridge sécurisé
|
||||
├── package.json # Config Electron + electron-builder
|
||||
└── ui/
|
||||
├── index.html # Interface dashboard
|
||||
├── styles.css # Dark theme
|
||||
└── app.js # Logic + API calls
|
||||
```
|
||||
|
||||
### Build & Distribution
|
||||
```bash
|
||||
cd electron
|
||||
npm run build:mac # → dist/PTT Live Server.dmg
|
||||
npm run build:linux # → dist/PTT Live Server.AppImage
|
||||
```
|
||||
|
||||
Voir [DESKTOP-APP.md](DESKTOP-APP.md) pour la doc complète.
|
||||
|
||||
---
|
||||
|
||||
## Fonctionnalités de portabilité (v0.2.1)
|
||||
|
||||
### Installation zéro-config
|
||||
|
||||
+438
@@ -0,0 +1,438 @@
|
||||
# PTT Live - Application Desktop Server
|
||||
|
||||
Application Electron pour gérer le serveur PTT Live avec interface graphique complète.
|
||||
|
||||
## 📸 Aperçu
|
||||
|
||||
L'application desktop intègre :
|
||||
- ✅ **Dashboard temps réel** : stats, utilisateurs, QR Code (généré côté Main Process, sans dépendance CDN)
|
||||
- ✅ **HTTPS automatique** : certificats locaux mkcert installés au premier lancement
|
||||
- ✅ **Configuration audio** : sélection devices, sample rate, bitrate
|
||||
- ✅ **Gestion groupes** : CRUD complet avec API
|
||||
- ✅ **Monitoring** : VU-mètres temps réel via WebSocket, logs filtrables
|
||||
- ✅ **Contrôle serveur** : démarrage manuel/arrêt avec feedback visuel
|
||||
|
||||
---
|
||||
|
||||
## 🚀 Démarrage Rapide
|
||||
|
||||
```bash
|
||||
# Depuis la racine du projet
|
||||
./start-desktop.sh
|
||||
|
||||
# OU manuellement
|
||||
cd electron
|
||||
npm start
|
||||
```
|
||||
|
||||
Au premier lancement, l'app configure automatiquement les certificats HTTPS locaux (mkcert) — voir [HTTPS et certificats](#-https-et-certificats). Le serveur PTT Live **ne démarre pas automatiquement** : cliquez sur "Démarrer" dans le dashboard pour le lancer.
|
||||
|
||||
---
|
||||
|
||||
## 📦 Installation
|
||||
|
||||
Les dépendances sont déjà installées. Si nécessaire :
|
||||
|
||||
```bash
|
||||
cd electron
|
||||
npm install
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 🎯 Utilisation
|
||||
|
||||
### 1. Dashboard
|
||||
|
||||
**Stats temps réel** :
|
||||
- Uptime serveur
|
||||
- Nombre d'utilisateurs connectés
|
||||
- Groupes actifs
|
||||
- Total connexions
|
||||
|
||||
**QR Code** :
|
||||
- Généré côté Main Process (lib `qrcode`, pas de CDN externe — fonctionne sans accès Internet sur le WiFi d'un événement)
|
||||
- IP réseau détectée par le Main Process (même logique que pour les certificats mkcert)
|
||||
- URL construite à partir du protocole/port réels du serveur (HTTPS par défaut)
|
||||
- Scanner depuis smartphone pour connexion rapide
|
||||
- Bouton copier URL
|
||||
- Placeholder visuel tant que le serveur est arrêté ou qu'aucun QR code n'a été généré
|
||||
|
||||
**Utilisateurs** :
|
||||
- Liste en temps réel
|
||||
- Groupe de chaque utilisateur
|
||||
- Heure de connexion
|
||||
|
||||
### 2. Configuration Audio
|
||||
|
||||
**Périphériques** :
|
||||
- Sélection input/output depuis dropdown auto-détecté
|
||||
- Support macOS (CoreAudio), Linux (JACK/PipeWire)
|
||||
- Appliquer instantanément (bridge audio rechargé)
|
||||
|
||||
**Paramètres** :
|
||||
- Sample Rate : 44.1 / 48 / 96 kHz
|
||||
- Bitrate par défaut : 32-320 kbps
|
||||
- Jitter Buffer : 20-100 ms
|
||||
|
||||
### 3. Gestion Groupes
|
||||
|
||||
- **Créer** : bouton "➕ Nouveau groupe"
|
||||
- **Modifier** : depuis la liste (nom, bitrate)
|
||||
- **Supprimer** : confirmation requise
|
||||
- Sauvegardé automatiquement dans `config.yaml`
|
||||
|
||||
### 4. Monitoring
|
||||
|
||||
**VU-Mètres** :
|
||||
- Niveaux audio par canal (input/output) et par groupe
|
||||
- Temps réel via WebSocket (`/audio-levels`, même port que l'API)
|
||||
- Reconnexion automatique si la connexion WebSocket tombe
|
||||
|
||||
### 5. Logs
|
||||
|
||||
- Logs serveur en temps réel
|
||||
- Filtrage par niveau (error/warn/info/debug)
|
||||
- Bouton "Effacer"
|
||||
- Format timestamp + niveau + message
|
||||
|
||||
---
|
||||
|
||||
## 🏗️ Architecture Technique
|
||||
|
||||
```
|
||||
┌─────────────────────────────────────────────────┐
|
||||
│ ELECTRON APP (Desktop) │
|
||||
│ │
|
||||
│ ┌───────────────────────────────────────────┐ │
|
||||
│ │ MAIN PROCESS (Node.js) │ │
|
||||
│ │ │ │
|
||||
│ │ • spawn server/index.js │ │
|
||||
│ │ • IPC handlers (start/stop/status) │ │
|
||||
│ │ • Tray icon (macOS/Linux) │ │
|
||||
│ │ • Logs forwarding → Renderer │ │
|
||||
│ └───────────────────────────────────────────┘ │
|
||||
│ ↕ IPC │
|
||||
│ ┌───────────────────────────────────────────┐ │
|
||||
│ │ RENDERER PROCESS (Frontend) │ │
|
||||
│ │ │ │
|
||||
│ │ • HTML/CSS/JS (pas de framework) │ │
|
||||
│ │ • Fetch API REST :3000/admin/* │ │
|
||||
│ │ • WebSocket audio levels (live) │ │
|
||||
│ │ • QR Code (data URL via IPC) │ │
|
||||
│ └───────────────────────────────────────────┘ │
|
||||
└─────────────────────────────────────────────────┘
|
||||
↕ HTTPS (127.0.0.1, certs mkcert)
|
||||
┌─────────────────────────────────────────────────┐
|
||||
│ SERVEUR PTT LIVE (spawned) │
|
||||
│ │
|
||||
│ • LiveKit Server (binaire Go) :7880 │
|
||||
│ • Audio Bridge Manager │
|
||||
│ • API REST Express :3000 (HTTPS) │
|
||||
│ • Proxy HTTP + WS → LiveKit (/livekit/*) │
|
||||
│ • WebSocket Audio Levels (/audio-levels) │
|
||||
└─────────────────────────────────────────────────┘
|
||||
```
|
||||
|
||||
Le proxy `/livekit/*` (http-proxy natif) permet aux clients de joindre LiveKit via le même port/certificat HTTPS que l'API, sans exposer le port 7880 séparément. Le serveur Express dispatch lui-même les événements `upgrade` (un seul listener) entre le proxy LiveKit et le WebSocket audio-levels, qui partagent le même port.
|
||||
|
||||
---
|
||||
|
||||
## 🔌 API Consommées
|
||||
|
||||
L'interface desktop utilise toutes les routes admin existantes :
|
||||
|
||||
| Endpoint | Méthode | Usage |
|
||||
|----------|---------|-------|
|
||||
| `/admin/stats` | GET | Dashboard metrics |
|
||||
| `/admin/users` | GET | Liste utilisateurs |
|
||||
| `/admin/groups` | GET | Liste groupes |
|
||||
| `/admin/groups` | POST | Créer groupe |
|
||||
| `/admin/groups/:id` | PUT | Modifier groupe |
|
||||
| `/admin/groups/:id` | DELETE | Supprimer groupe |
|
||||
| `/admin/config` | GET | Config complète |
|
||||
| `/admin/config/audio` | PUT | Mettre à jour audio |
|
||||
| `/admin/audio/devices` | GET | Énumérer devices |
|
||||
| `/admin/audio/device` | POST | Sélectionner device |
|
||||
| `/admin/devices/list` | GET | Auto-détection (macOS/Linux) |
|
||||
| `/admin/logs` | GET | Logs serveur |
|
||||
| `/health` | GET | Health check |
|
||||
| `/livekit/*` | ALL | Proxy HTTP vers LiveKit Server (port 7880) |
|
||||
|
||||
WebSocket :
|
||||
- `wss://127.0.0.1:3000/audio-levels` → VU-mètres temps réel
|
||||
- `wss://127.0.0.1:3000/livekit/*` → Proxy WebSocket signaling LiveKit (clients PWA)
|
||||
|
||||
---
|
||||
|
||||
## 🔒 HTTPS et certificats
|
||||
|
||||
L'app est en HTTPS par défaut (`ENABLE_HTTPS=false` pour revenir en HTTP explicitement).
|
||||
|
||||
### Setup automatique (premier lancement)
|
||||
|
||||
Au premier démarrage, si `certs/localhost.pem` et `certs/localhost-key.pem` sont absents, `electron/setup-helper.js` :
|
||||
1. Installe `mkcert` automatiquement (Homebrew sur macOS, téléchargement direct sur Linux)
|
||||
2. Installe la CA locale (`mkcert -install`) dans le trousseau système
|
||||
3. Détecte l'IP réseau et génère les certificats pour `localhost`, `127.0.0.1` et cette IP
|
||||
4. Affiche des dialogs de progression/erreur (avec fallback manuel `./setup-certificates.sh`)
|
||||
|
||||
### Points d'attention
|
||||
|
||||
- **127.0.0.1, pas localhost** : le serveur écoute en IPv4 (`host: 0.0.0.0`), mais le Node embarqué par Electron peut résoudre `localhost` en IPv6 (`::1`) en priorité. `main.js` et `preload.js` utilisent donc `127.0.0.1` pour tous les appels internes (ping, health check) afin d'éviter des échecs silencieux.
|
||||
- **Ping interne et `rejectUnauthorized`** : le module `https` de Node ne lit pas le trousseau système où mkcert installe sa CA (contrairement à Safari/Chrome/Electron renderer) ; `pingServer()` passe donc `rejectUnauthorized: false` pour son propre ping local.
|
||||
- **Proxy LiveKit en HTTPS** : LiveKit Server local tourne en HTTP brut (port 7880) ; le proxy Express (`http-proxy`) fait le pont HTTPS ↔ HTTP côté clients.
|
||||
|
||||
---
|
||||
|
||||
## 📦 Build pour Distribution
|
||||
|
||||
### macOS
|
||||
|
||||
```bash
|
||||
cd electron
|
||||
npm run build:mac
|
||||
```
|
||||
|
||||
Génère :
|
||||
- `dist/mac/PTT Live Server.app`
|
||||
- `dist/PTT Live Server-0.3.0.dmg`
|
||||
|
||||
### Linux
|
||||
|
||||
```bash
|
||||
cd electron
|
||||
npm run build:linux
|
||||
```
|
||||
|
||||
Génère :
|
||||
- `dist/PTT Live Server-0.3.0.deb`
|
||||
- `dist/PTT Live Server-0.3.0.AppImage`
|
||||
|
||||
### Tester le build
|
||||
|
||||
```bash
|
||||
# macOS
|
||||
open dist/mac/PTT\ Live\ Server.app
|
||||
|
||||
# Linux
|
||||
./dist/PTT\ Live\ Server-0.3.0.AppImage
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 🎨 Personnalisation
|
||||
|
||||
### Icônes
|
||||
|
||||
Placer les icônes dans `electron/assets/` :
|
||||
|
||||
```
|
||||
electron/assets/
|
||||
├── icon.icns # macOS (512x512 minimum)
|
||||
├── icon.png # Linux (512x512)
|
||||
└── tray-icon.png # Tray 22x22 ou 44x44 (retina)
|
||||
```
|
||||
|
||||
Générer icônes depuis PNG :
|
||||
|
||||
```bash
|
||||
# macOS .icns
|
||||
iconutil -c icns assets/icon.iconset
|
||||
|
||||
# Linux .png
|
||||
convert icon.png -resize 512x512 assets/icon.png
|
||||
```
|
||||
|
||||
### Thème
|
||||
|
||||
Modifier `electron/ui/styles.css` :
|
||||
|
||||
```css
|
||||
:root {
|
||||
--bg-primary: #1a1a1a;
|
||||
--accent-primary: #4a9eff;
|
||||
/* ... */
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 🐛 Debug
|
||||
|
||||
### DevTools
|
||||
|
||||
Ouvrir automatiquement en mode dev :
|
||||
|
||||
```bash
|
||||
cd electron
|
||||
npm run dev
|
||||
```
|
||||
|
||||
Ou manuellement dans `main.js` :
|
||||
|
||||
```javascript
|
||||
mainWindow.webContents.openDevTools();
|
||||
```
|
||||
|
||||
### Logs Console
|
||||
|
||||
**Main Process** :
|
||||
```javascript
|
||||
console.log('[Main]', ...); // Terminal qui a lancé npm start
|
||||
```
|
||||
|
||||
**Renderer Process** :
|
||||
```javascript
|
||||
console.log('[Renderer]', ...); // DevTools → Console
|
||||
```
|
||||
|
||||
**Serveur PTT Live** :
|
||||
```javascript
|
||||
// Transmis au Renderer via IPC
|
||||
window.electronAPI.server.onLog((log) => {
|
||||
console.log('[Serveur]', log);
|
||||
});
|
||||
```
|
||||
|
||||
### Erreurs courantes
|
||||
|
||||
**Port 3000 déjà utilisé** :
|
||||
```bash
|
||||
# Tuer le process
|
||||
lsof -i :3000
|
||||
kill -9 <PID>
|
||||
|
||||
# OU changer de port
|
||||
PORT=3001 npm start
|
||||
```
|
||||
|
||||
**Serveur ne démarre pas** :
|
||||
- Vérifier que `server/index.js` existe
|
||||
- Vérifier permissions LiveKit binaire
|
||||
- Voir logs dans DevTools console
|
||||
|
||||
**Certificats SSL manquants / setup mkcert échoue** :
|
||||
- Exécuter manuellement : `./setup-certificates.sh`
|
||||
- Ou installer mkcert : https://github.com/FiloSottile/mkcert puis `mkcert -install`
|
||||
- Vérifier la présence de `certs/localhost.pem` et `certs/localhost-key.pem`
|
||||
|
||||
**Statut serveur affiché à tort comme "arrêté"** :
|
||||
- Vérifier que le ping utilise bien `127.0.0.1` (pas `localhost`, qui peut résoudre en IPv6 alors que le serveur n'écoute qu'en IPv4)
|
||||
- En HTTPS, le ping interne ignore volontairement les erreurs de certificat (`rejectUnauthorized: false`) puisque Node ne lit pas le trousseau système où mkcert installe sa CA
|
||||
|
||||
**QR Code ne s'affiche pas** :
|
||||
- Vérifier que le serveur tourne (le QR code est réinitialisé tant qu'il est arrêté)
|
||||
- Le QR code est généré côté Main Process (IPC `qrcode:generate`), pas de dépendance réseau/CDN
|
||||
|
||||
---
|
||||
|
||||
## 🚧 TODO / Améliorations
|
||||
|
||||
### Priorité haute
|
||||
- [x] **WebSocket VU-mètres** : implémenter connexion `/audio-levels`
|
||||
- [ ] **Vraies icônes** : icns/png pour macOS/Linux
|
||||
- [ ] **Tray icon** : avec menu contextuel fonctionnel
|
||||
|
||||
### Priorité moyenne
|
||||
- [ ] **Graphiques monitoring** : Chart.js pour latence/bande passante
|
||||
- [x] **Export logs** : bouton télécharger JSON (filtre niveau appliqué)
|
||||
- [ ] **Matrice routing** : interface graphique drag & drop
|
||||
- [x] **Export & import config** : bouton télécharger YAML et charger config (backup auto .bak)
|
||||
|
||||
### Priorité basse
|
||||
- [ ] **Thème toggle** : dark/light mode
|
||||
- [ ] **Auto-update** : electron-updater pour mises à jour
|
||||
|
||||
### Technique
|
||||
- [ ] **Tests** : Spectron ou Playwright pour Electron
|
||||
- [ ] **CI/CD** : GitHub Actions pour builds automatiques
|
||||
- [ ] **Signature code** : macOS notarization + Linux AppImage signature
|
||||
|
||||
---
|
||||
|
||||
## 📝 Notes de Développement
|
||||
|
||||
### Structure Fichiers
|
||||
|
||||
```
|
||||
electron/
|
||||
├── main.js # Main Process
|
||||
│ # - Spawn serveur
|
||||
│ # - IPC handlers
|
||||
│ # - Window management
|
||||
│ # - Setup SSL au premier lancement
|
||||
│
|
||||
├── preload.js # IPC Bridge sécurisé
|
||||
│ # - contextBridge
|
||||
│ # - Expose electronAPI
|
||||
│
|
||||
├── setup-helper.js # Installation auto mkcert + génération certificats
|
||||
│ # - Détection IP réseau
|
||||
│
|
||||
├── package.json # Config Electron + electron-builder
|
||||
│
|
||||
└── ui/ # Renderer Process (Frontend)
|
||||
├── index.html # Structure UI
|
||||
├── styles.css # Styles (dark theme)
|
||||
└── app.js # Logic frontend (QR code reçu via IPC en data URL)
|
||||
```
|
||||
|
||||
### Communication IPC
|
||||
|
||||
**Renderer → Main** :
|
||||
|
||||
```javascript
|
||||
// Depuis ui/app.js
|
||||
const result = await window.electronAPI.server.start();
|
||||
```
|
||||
|
||||
**Main → Renderer** :
|
||||
|
||||
```javascript
|
||||
// Depuis main.js
|
||||
mainWindow.webContents.send('server:status', { running: true });
|
||||
|
||||
// Écouté dans ui/app.js
|
||||
window.electronAPI.server.onStatus((data) => {
|
||||
console.log('Status:', data);
|
||||
});
|
||||
```
|
||||
|
||||
### Sécurité
|
||||
|
||||
- ✅ **contextIsolation: true** : isole Node.js du renderer
|
||||
- ✅ **nodeIntegration: false** : pas d'accès Node direct
|
||||
- ✅ **preload.js** : whitelist API exposées via contextBridge
|
||||
- ⚠️ **CSP manquant** : ajouter Content-Security-Policy en prod
|
||||
|
||||
---
|
||||
|
||||
## 🤝 Contribution
|
||||
|
||||
L'app desktop est modulaire et extensible :
|
||||
|
||||
1. **Ajouter une vue** : créer `<div id="view-xxx">` dans `index.html`
|
||||
2. **Ajouter un handler IPC** : `ipcMain.handle()` dans `main.js`
|
||||
3. **Exposer au renderer** : `contextBridge.exposeInMainWorld()` dans `preload.js`
|
||||
4. **Appeler l'API** : fetch dans `ui/app.js`
|
||||
|
||||
---
|
||||
|
||||
## 📚 Ressources
|
||||
|
||||
- **Electron Docs** : https://www.electronjs.org/docs
|
||||
- **electron-builder** : https://www.electron.build
|
||||
- **LiveKit Server API** : https://docs.livekit.io
|
||||
- **QR Code.js** : https://github.com/soldair/node-qrcode
|
||||
|
||||
---
|
||||
|
||||
## 📄 Licence
|
||||
|
||||
Même licence que PTT Live (MIT)
|
||||
|
||||
---
|
||||
|
||||
**Version** : 0.3.0
|
||||
**Dernière mise à jour** : 2026-06-30
|
||||
@@ -8,18 +8,43 @@ Communiquez via smartphone (PWA) en WiFi, le serveur fait le pont avec l'install
|
||||
|
||||
## 🚀 Démarrage rapide
|
||||
|
||||
### 🖥️ Application Desktop (Nouveau !)
|
||||
|
||||
**Interface graphique complète pour gérer le serveur** :
|
||||
|
||||
```bash
|
||||
# Lancer l'application desktop
|
||||
./start-desktop.sh
|
||||
```
|
||||
|
||||
✨ **Fonctionnalités** :
|
||||
- Dashboard temps réel (stats, utilisateurs)
|
||||
- Configuration audio (devices, bitrate)
|
||||
- Gestion groupes (CRUD)
|
||||
- QR Code pour connexion clients
|
||||
- Logs serveur filtrables
|
||||
|
||||
📖 **Documentation complète** : [DESKTOP-APP.md](DESKTOP-APP.md)
|
||||
|
||||
---
|
||||
|
||||
### Installation Automatique (Recommandé)
|
||||
|
||||
**Un seul script pour tout installer** (détection automatique macOS/Linux) :
|
||||
|
||||
```bash
|
||||
# Lancer l'installation portable
|
||||
# 1. Installer dépendances + LiveKit
|
||||
./install.sh
|
||||
|
||||
# Démarrer le système
|
||||
# 2. Configurer certificats SSL locaux (NOUVEAU - requis pour HTTPS)
|
||||
./setup-certificates.sh
|
||||
|
||||
# 3. Démarrer le système (mode CLI)
|
||||
./start.sh --dev
|
||||
```
|
||||
|
||||
🔐 **Certificats SSL** : Le script `setup-certificates.sh` génère des certificats **automatiquement approuvés** (pas de warnings navigateur). Voir [SSL-SETUP.md](SSL-SETUP.md)
|
||||
|
||||
✨ **L'installeur configure automatiquement** :
|
||||
- LiveKit Server local (pas besoin de compte cloud)
|
||||
- Détection et configuration IP réseau
|
||||
|
||||
+375
@@ -0,0 +1,375 @@
|
||||
# 🔐 Configuration SSL 100% Locale - PTT Live
|
||||
|
||||
## Problème Résolu
|
||||
|
||||
❌ **Avant** : Certificats self-signed bloqués par navigateurs
|
||||
✅ **Après** : Certificats locaux **automatiquement approuvés**
|
||||
|
||||
---
|
||||
|
||||
## Solution : mkcert
|
||||
|
||||
**mkcert** génère des certificats SSL locaux **de confiance** :
|
||||
- ✅ Approuvés automatiquement par Chrome/Safari/Edge/Firefox
|
||||
- ✅ Approuvés par le système (macOS/Linux)
|
||||
- ✅ Pas besoin de clics "Accepter le risque"
|
||||
- ✅ 100% local, pas de cloud, pas de domaine
|
||||
|
||||
---
|
||||
|
||||
## 🚀 Installation Automatique (Recommandée)
|
||||
|
||||
### Un seul script fait tout
|
||||
|
||||
```bash
|
||||
# Depuis la racine du projet
|
||||
./setup-certificates.sh
|
||||
```
|
||||
|
||||
Ce script :
|
||||
1. ✅ Installe `mkcert` (si pas déjà installé)
|
||||
2. ✅ Installe la CA locale (Certificate Authority)
|
||||
3. ✅ Génère certificats pour localhost + IP réseau
|
||||
4. ✅ Configure automatiquement serveur et client
|
||||
5. ✅ Crée les `.env` avec chemins certificats
|
||||
|
||||
**Temps : ~2 minutes**
|
||||
|
||||
---
|
||||
|
||||
## 📋 Ce qui est Créé
|
||||
|
||||
### Structure
|
||||
|
||||
```
|
||||
PTT Live/
|
||||
├── certs/ # Nouveau dossier
|
||||
│ ├── localhost.pem # Certificat public
|
||||
│ └── localhost-key.pem # Clé privée
|
||||
│
|
||||
├── server/.env # Mis à jour automatiquement
|
||||
│ ├── SSL_CERT=/path/to/localhost.pem
|
||||
│ └── SSL_KEY=/path/to/localhost-key.pem
|
||||
│
|
||||
└── client/
|
||||
├── .env # Créé automatiquement
|
||||
└── vite.config.js # Mis à jour avec HTTPS
|
||||
```
|
||||
|
||||
### Certificats Générés Pour
|
||||
|
||||
- `localhost`
|
||||
- `127.0.0.1`
|
||||
- Votre **IP réseau** (ex: `192.168.1.10`)
|
||||
- `*.local` (wildcard)
|
||||
- `$(hostname).local`
|
||||
|
||||
---
|
||||
|
||||
## 🌐 URLs d'Accès
|
||||
|
||||
Après installation, accès HTTPS sans warnings :
|
||||
|
||||
```
|
||||
Serveur : https://192.168.1.10:3000
|
||||
Client : https://192.168.1.10:5173
|
||||
|
||||
QR Code : généré automatiquement au démarrage
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 📱 Smartphones (iOS/Android)
|
||||
|
||||
### Première Connexion
|
||||
|
||||
1. **Scanner le QR Code** affiché au démarrage du serveur
|
||||
2. Le navigateur ouvre l'URL HTTPS
|
||||
3. **Accepter le certificat** (une seule fois par appareil)
|
||||
- iOS : Cliquer "Continuer" → "Visiter ce site web"
|
||||
- Android : Cliquer "Avancé" → "Continuer vers le site"
|
||||
4. La PWA se charge normalement
|
||||
5. **Installer sur l'écran d'accueil** (recommandé)
|
||||
|
||||
### Pourquoi Accepter Manuellement sur Mobile ?
|
||||
|
||||
La CA locale est installée sur l'**ordinateur serveur**, pas sur le smartphone.
|
||||
|
||||
**Options** :
|
||||
|
||||
**A) Accepter à chaque appareil** (simple, rapide)
|
||||
- Une seule fois par smartphone
|
||||
- 2 clics
|
||||
|
||||
**B) Installer la CA sur les mobiles** (optionnel, avancé)
|
||||
- iOS : Réglages → Général → VPN & Gestion → Profils
|
||||
- Android : Paramètres → Sécurité → Certificats
|
||||
|
||||
💡 **Recommandation** : Option A (accepter manuellement), plus simple.
|
||||
|
||||
---
|
||||
|
||||
## 🛠️ Fonctionnement Technique
|
||||
|
||||
### 1. mkcert
|
||||
|
||||
```bash
|
||||
# Installer CA locale (une fois par machine)
|
||||
mkcert -install
|
||||
|
||||
# Générer certificats
|
||||
mkcert localhost 192.168.1.10 *.local
|
||||
# → Crée localhost.pem + localhost-key.pem
|
||||
```
|
||||
|
||||
### 2. Serveur Express (HTTPS)
|
||||
|
||||
```javascript
|
||||
// server/index.js
|
||||
const https = require('https');
|
||||
const fs = require('fs');
|
||||
|
||||
const httpsOptions = {
|
||||
key: fs.readFileSync(process.env.SSL_KEY),
|
||||
cert: fs.readFileSync(process.env.SSL_CERT)
|
||||
};
|
||||
|
||||
https.createServer(httpsOptions, app).listen(3000);
|
||||
```
|
||||
|
||||
### 3. Vite Dev Server (HTTPS)
|
||||
|
||||
```javascript
|
||||
// client/vite.config.js
|
||||
export default defineConfig({
|
||||
server: {
|
||||
https: {
|
||||
key: fs.readFileSync('../certs/localhost-key.pem'),
|
||||
cert: fs.readFileSync('../certs/localhost.pem')
|
||||
}
|
||||
}
|
||||
});
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 🔧 Installation Manuelle (Si Script Échoue)
|
||||
|
||||
### macOS
|
||||
|
||||
```bash
|
||||
# 1. Installer mkcert
|
||||
brew install mkcert
|
||||
brew install nss # Pour Firefox
|
||||
|
||||
# 2. Installer CA locale
|
||||
mkcert -install
|
||||
|
||||
# 3. Créer dossier certificats
|
||||
mkdir certs
|
||||
cd certs
|
||||
|
||||
# 4. Générer certificats (remplacer IP)
|
||||
mkcert localhost 127.0.0.1 192.168.1.10 *.local
|
||||
|
||||
# 5. Renommer
|
||||
mv localhost+*.pem localhost.pem
|
||||
mv localhost+*-key.pem localhost-key.pem
|
||||
|
||||
# 6. Configurer .env (voir ci-dessous)
|
||||
```
|
||||
|
||||
### Linux
|
||||
|
||||
```bash
|
||||
# 1. Installer dépendances
|
||||
sudo apt-get install libnss3-tools # Debian/Ubuntu
|
||||
# OU
|
||||
sudo yum install nss-tools # RedHat/CentOS
|
||||
|
||||
# 2. Télécharger mkcert
|
||||
curl -JLO "https://dl.filippo.io/mkcert/latest?for=linux/amd64"
|
||||
chmod +x mkcert-v*-linux-amd64
|
||||
sudo mv mkcert-v*-linux-amd64 /usr/local/bin/mkcert
|
||||
|
||||
# 3-6. Mêmes étapes que macOS
|
||||
```
|
||||
|
||||
### Configuration Manuelle .env
|
||||
|
||||
**server/.env** :
|
||||
```bash
|
||||
USE_LOCAL_LIVEKIT=true
|
||||
LIVEKIT_API_KEY=devkey
|
||||
LIVEKIT_API_SECRET=secret
|
||||
LIVEKIT_URL=AUTO
|
||||
|
||||
PORT=3000
|
||||
ENABLE_HTTPS=true
|
||||
|
||||
# Chemins ABSOLUS
|
||||
SSL_CERT=/Users/vous/PTT Live/certs/localhost.pem
|
||||
SSL_KEY=/Users/vous/PTT Live/certs/localhost-key.pem
|
||||
|
||||
NETWORK_IP=192.168.1.10 # Votre IP
|
||||
```
|
||||
|
||||
**client/.env** :
|
||||
```bash
|
||||
VITE_SERVER_URL=https://192.168.1.10:3000
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## ✅ Vérification
|
||||
|
||||
### 1. Certificats Créés ?
|
||||
|
||||
```bash
|
||||
ls -lh certs/
|
||||
# Doit afficher :
|
||||
# localhost.pem
|
||||
# localhost-key.pem
|
||||
```
|
||||
|
||||
### 2. CA Installée ?
|
||||
|
||||
```bash
|
||||
mkcert -CAROOT
|
||||
# Affiche le chemin de la CA (ex: /Users/vous/Library/Application Support/mkcert)
|
||||
```
|
||||
|
||||
### 3. Serveur HTTPS Fonctionne ?
|
||||
|
||||
```bash
|
||||
# Démarrer
|
||||
./start.sh --dev
|
||||
|
||||
# Vérifier
|
||||
curl -k https://localhost:3000/health
|
||||
# Doit retourner JSON sans erreur
|
||||
```
|
||||
|
||||
### 4. Client HTTPS Fonctionne ?
|
||||
|
||||
Ouvrir dans navigateur :
|
||||
```
|
||||
https://localhost:5173
|
||||
```
|
||||
|
||||
✅ **Pas de warning SSL** = succès !
|
||||
|
||||
---
|
||||
|
||||
## 🐛 Dépannage
|
||||
|
||||
### Erreur "Certificats SSL introuvables"
|
||||
|
||||
**Symptôme** : Le serveur refuse de démarrer
|
||||
|
||||
**Solution** :
|
||||
```bash
|
||||
# 1. Vérifier que les certificats existent
|
||||
ls certs/
|
||||
|
||||
# 2. Relancer le script
|
||||
./setup-certificates.sh
|
||||
|
||||
# 3. Vérifier .env
|
||||
cat server/.env | grep SSL_
|
||||
```
|
||||
|
||||
### Warning SSL sur Smartphone
|
||||
|
||||
**Symptôme** : "Votre connexion n'est pas privée"
|
||||
|
||||
**Solution** : Normal ! Cliquer "Avancé" → "Continuer"
|
||||
- Une seule fois par appareil
|
||||
- La CA locale n'est pas sur le mobile
|
||||
|
||||
### Firefox : Certificat Non Approuvé
|
||||
|
||||
**Symptôme** : Firefox affiche warning (Chrome OK)
|
||||
|
||||
**Solution** :
|
||||
```bash
|
||||
# Installer NSS tools
|
||||
brew install nss # macOS
|
||||
sudo apt install libnss3-tools # Linux
|
||||
|
||||
# Réinstaller CA
|
||||
mkcert -install
|
||||
```
|
||||
|
||||
### Certificat Expiré
|
||||
|
||||
**Symptôme** : Après plusieurs mois
|
||||
|
||||
**Solution** :
|
||||
```bash
|
||||
# Régénérer certificats
|
||||
cd certs
|
||||
rm *.pem
|
||||
mkcert localhost $(ipconfig getifaddr en0) *.local
|
||||
|
||||
# Redémarrer serveur
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 🔄 Renouvellement
|
||||
|
||||
Les certificats mkcert sont valides **10 ans** (pas besoin de renouveler).
|
||||
|
||||
Pour regénérer (changement d'IP, etc.) :
|
||||
|
||||
```bash
|
||||
./setup-certificates.sh
|
||||
# Écrase les anciens certificats
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 🌍 Production (Déploiement Réel)
|
||||
|
||||
### Option 1 : mkcert (Réseau Local Privé)
|
||||
|
||||
✅ **Si PTT Live reste sur réseau local privé** (WiFi événement)
|
||||
- Garder mkcert
|
||||
- Les clients acceptent le certificat une fois
|
||||
- Pas besoin de domaine/DNS
|
||||
|
||||
### Option 2 : Let's Encrypt (Internet Public)
|
||||
|
||||
⚠️ **Si PTT Live doit être accessible depuis Internet**
|
||||
- Nécessite un domaine (ex: `ptt.votredomaine.com`)
|
||||
- Utiliser Caddy ou Certbot (Let's Encrypt)
|
||||
- Pas recommandé pour intercom événementiel
|
||||
|
||||
**Recommandation** : Rester sur **Option 1** (mkcert + réseau local)
|
||||
|
||||
---
|
||||
|
||||
## 📚 Ressources
|
||||
|
||||
- **mkcert** : https://github.com/FiloSottile/mkcert
|
||||
- **Vite HTTPS** : https://vitejs.dev/config/server-options.html#server-https
|
||||
- **Node.js HTTPS** : https://nodejs.org/api/https.html
|
||||
|
||||
---
|
||||
|
||||
## ✅ Récapitulatif
|
||||
|
||||
| Avant | Après |
|
||||
|-------|-------|
|
||||
| ❌ Certificats self-signed bloqués | ✅ Certificats approuvés automatiquement |
|
||||
| ❌ Warnings "Non sécurisé" | ✅ Cadenas vert 🔒 |
|
||||
| ❌ WebRTC refuse HTTPS invalide | ✅ WebRTC fonctionne |
|
||||
| ❌ Configuration manuelle complexe | ✅ Script automatique 2 min |
|
||||
| ❌ Dépendance cloud/domaine | ✅ 100% local |
|
||||
|
||||
---
|
||||
|
||||
**Solution : `./setup-certificates.sh` → 2 minutes → HTTPS fonctionnel**
|
||||
|
||||
🎉 Problème résolu définitivement !
|
||||
@@ -1,6 +1,5 @@
|
||||
import { useState, useEffect, useRef } from 'react';
|
||||
import './Admin.css';
|
||||
import AudioRoutingMatrix from './components/AudioRoutingMatrix';
|
||||
|
||||
const API_URL = import.meta.env.VITE_API_URL || '/api';
|
||||
|
||||
@@ -409,9 +408,6 @@ function Admin() {
|
||||
</label>
|
||||
</div>
|
||||
|
||||
<p style={{color: 'var(--color-text-secondary)', fontSize: '0.9rem', marginTop: 'var(--spacing-md)'}}>
|
||||
Le routing audio se configure dans l'onglet "Audio" via la matrice de routing.
|
||||
</p>
|
||||
|
||||
<div className="form-actions">
|
||||
<button type="submit" className="btn-primary">
|
||||
@@ -609,7 +605,6 @@ function Admin() {
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<AudioRoutingMatrix groups={groups} channelNames={channelNames} />
|
||||
|
||||
{currentDevice && currentDevice.inputDeviceId && (
|
||||
<div className="current-config">
|
||||
|
||||
+7
-7
@@ -100,17 +100,17 @@ function App() {
|
||||
|
||||
const data = await response.json();
|
||||
|
||||
// En mode dev (HTTPS via Vite), utiliser le proxy WebSocket
|
||||
// En mode prod (HTTP direct), utiliser l'URL LiveKit directement
|
||||
// Si HTTPS, utiliser le proxy WebSocket (résout mixed content)
|
||||
// Sinon utiliser l'URL LiveKit directement
|
||||
let livekitUrl = data.url;
|
||||
|
||||
if (import.meta.env.DEV && window.location.protocol === 'https:') {
|
||||
// Mode dev avec Vite : utiliser le proxy WSS
|
||||
livekitUrl = `${window.location.protocol}//${window.location.host}/livekit`;
|
||||
if (window.location.protocol === 'https:') {
|
||||
// HTTPS : utiliser le proxy WSS (wss://host:port/livekit)
|
||||
livekitUrl = `wss://${window.location.host}/livekit`;
|
||||
console.log('🔒 Mode HTTPS : utilisation proxy WebSocket');
|
||||
}
|
||||
|
||||
console.log('🔗 Connexion LiveKit:', livekitUrl);
|
||||
console.log('📝 Mode:', import.meta.env.DEV ? 'dev' : 'prod');
|
||||
|
||||
// Se connecter à LiveKit avec les canaux virtuels
|
||||
await connect(livekitUrl, data.token, data.virtualChannels || []);
|
||||
@@ -154,7 +154,7 @@ function App() {
|
||||
// Adapter l'URL LiveKit selon le protocole de la page
|
||||
let livekitUrl = data.url;
|
||||
if (window.location.protocol === 'https:') {
|
||||
livekitUrl = `${window.location.protocol}//${window.location.host}/livekit`;
|
||||
livekitUrl = `wss://${window.location.host}/livekit`;
|
||||
}
|
||||
|
||||
// Changer de room LiveKit avec les canaux virtuels du nouveau groupe
|
||||
|
||||
@@ -1,245 +0,0 @@
|
||||
.routing-matrix-container {
|
||||
background: var(--color-surface);
|
||||
border: 1px solid var(--color-border);
|
||||
border-radius: 12px;
|
||||
padding: var(--spacing-xl);
|
||||
margin-top: var(--spacing-lg);
|
||||
}
|
||||
|
||||
.routing-actions {
|
||||
margin-top: var(--spacing-xl);
|
||||
display: flex;
|
||||
justify-content: flex-start;
|
||||
gap: var(--spacing-sm);
|
||||
}
|
||||
|
||||
.routing-matrix-header {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: center;
|
||||
margin-bottom: var(--spacing-xl);
|
||||
}
|
||||
|
||||
.routing-matrix-header h3 {
|
||||
margin: 0;
|
||||
font-size: 1.25rem;
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.ws-status {
|
||||
font-size: 0.8rem;
|
||||
font-weight: 600;
|
||||
padding: 4px 10px;
|
||||
border-radius: 12px;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.ws-status.connected {
|
||||
color: #44ff44;
|
||||
background: rgba(68, 255, 68, 0.1);
|
||||
}
|
||||
|
||||
.ws-status.disconnected {
|
||||
color: #888;
|
||||
background: rgba(136, 136, 136, 0.1);
|
||||
}
|
||||
|
||||
.routing-section {
|
||||
margin-bottom: var(--spacing-xl);
|
||||
}
|
||||
|
||||
.routing-section:last-child {
|
||||
margin-bottom: 0;
|
||||
}
|
||||
|
||||
.routing-section h4 {
|
||||
margin: 0 0 var(--spacing-sm) 0;
|
||||
font-size: 1rem;
|
||||
font-weight: 600;
|
||||
color: var(--color-text);
|
||||
}
|
||||
|
||||
.routing-description {
|
||||
margin: 0 0 var(--spacing-lg) 0;
|
||||
color: var(--color-text-secondary);
|
||||
font-size: 0.9rem;
|
||||
}
|
||||
|
||||
.routing-matrix {
|
||||
display: inline-grid;
|
||||
gap: 2px;
|
||||
background: var(--color-border);
|
||||
border: 1px solid var(--color-border);
|
||||
border-radius: 8px;
|
||||
overflow-x: auto;
|
||||
max-width: 100%;
|
||||
}
|
||||
|
||||
.matrix-corner {
|
||||
background: var(--color-surface-hover);
|
||||
min-height: 50px;
|
||||
}
|
||||
|
||||
.matrix-header-cell {
|
||||
background: var(--color-surface-hover);
|
||||
padding: var(--spacing-sm);
|
||||
font-size: 0.85rem;
|
||||
font-weight: 600;
|
||||
color: var(--color-text-secondary);
|
||||
text-align: center;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
min-height: 50px;
|
||||
word-break: break-word;
|
||||
hyphens: auto;
|
||||
}
|
||||
|
||||
.matrix-label-cell {
|
||||
background: var(--color-surface-hover);
|
||||
padding: var(--spacing-sm);
|
||||
font-size: 0.85rem;
|
||||
font-weight: 600;
|
||||
color: var(--color-text-secondary);
|
||||
display: flex;
|
||||
align-items: center;
|
||||
min-width: 120px;
|
||||
word-break: break-word;
|
||||
}
|
||||
|
||||
.label-content {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 4px;
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
.label-text {
|
||||
flex: 1;
|
||||
}
|
||||
|
||||
.header-content {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 4px;
|
||||
width: 100%;
|
||||
align-items: center;
|
||||
}
|
||||
|
||||
.header-text {
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.matrix-cell {
|
||||
background: var(--color-bg);
|
||||
padding: var(--spacing-sm);
|
||||
min-height: 60px;
|
||||
min-width: 80px;
|
||||
transition: all 0.2s;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
gap: var(--spacing-xs);
|
||||
position: relative;
|
||||
}
|
||||
|
||||
.cell-checkbox {
|
||||
width: 100%;
|
||||
min-height: 30px;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.matrix-cell:hover {
|
||||
background: var(--color-surface-hover);
|
||||
border: 1px solid var(--color-primary);
|
||||
}
|
||||
|
||||
.matrix-cell.active {
|
||||
background: var(--color-primary);
|
||||
color: white;
|
||||
}
|
||||
|
||||
.matrix-cell.active:hover {
|
||||
background: var(--color-primary-hover);
|
||||
}
|
||||
|
||||
.checkmark {
|
||||
font-size: 1.2rem;
|
||||
font-weight: bold;
|
||||
}
|
||||
|
||||
.gain-select {
|
||||
width: 100%;
|
||||
padding: 4px 8px;
|
||||
font-size: 0.75rem;
|
||||
background: rgba(59, 130, 246, 0.2);
|
||||
color: #ffffff;
|
||||
border: 1px solid rgba(255, 255, 255, 1);
|
||||
border-radius: 4px;
|
||||
cursor: pointer;
|
||||
font-weight: 600;
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.gain-select:focus {
|
||||
outline: none;
|
||||
background: rgba(59, 130, 246, 0.3);
|
||||
border-color: rgba(255, 255, 255, 1);
|
||||
box-shadow: 0 0 0 2px rgba(59, 130, 246, 0.2);
|
||||
}
|
||||
|
||||
@media (max-width: 1024px) {
|
||||
.matrix-header-cell,
|
||||
.matrix-label-cell {
|
||||
font-size: 0.75rem;
|
||||
padding: var(--spacing-xs);
|
||||
min-width: 80px;
|
||||
}
|
||||
|
||||
.matrix-cell {
|
||||
min-width: 70px;
|
||||
min-height: 50px;
|
||||
padding: var(--spacing-sm);
|
||||
}
|
||||
|
||||
.gain-select {
|
||||
font-size: 0.7rem;
|
||||
padding: 3px 6px;
|
||||
}
|
||||
}
|
||||
|
||||
@media (max-width: 768px) {
|
||||
.routing-matrix-container {
|
||||
padding: var(--spacing-md);
|
||||
}
|
||||
|
||||
.routing-matrix-header {
|
||||
flex-direction: column;
|
||||
gap: var(--spacing-md);
|
||||
align-items: stretch;
|
||||
}
|
||||
|
||||
.matrix-header-cell,
|
||||
.matrix-label-cell {
|
||||
font-size: 0.7rem;
|
||||
min-width: 60px;
|
||||
}
|
||||
|
||||
.matrix-cell {
|
||||
min-width: 65px;
|
||||
min-height: 45px;
|
||||
}
|
||||
|
||||
.checkmark {
|
||||
font-size: 1rem;
|
||||
}
|
||||
|
||||
.gain-select {
|
||||
font-size: 0.65rem;
|
||||
padding: 2px 4px;
|
||||
}
|
||||
}
|
||||
@@ -1,349 +0,0 @@
|
||||
import React, { useState, useEffect } from 'react';
|
||||
import './AudioRoutingMatrix.css';
|
||||
import VUMeter from './VUMeter.jsx';
|
||||
import { useAudioLevels } from '../hooks/useAudioLevels.js';
|
||||
|
||||
const API_URL = import.meta.env.VITE_API_URL || 'http://localhost:3000';
|
||||
|
||||
function AudioRoutingMatrix({ groups, channelNames }) {
|
||||
const { levels, connected: wsConnected } = useAudioLevels();
|
||||
const [routing, setRouting] = useState({ inputToGroup: {}, groupToOutput: {}, gains: {} });
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [showOnlyNamedChannels, setShowOnlyNamedChannels] = useState(false);
|
||||
const [audioDevice, setAudioDevice] = useState({ inputChannels: 8, outputChannels: 8 });
|
||||
|
||||
useEffect(() => {
|
||||
loadRouting();
|
||||
loadAudioDevice();
|
||||
}, []);
|
||||
|
||||
const loadRouting = async () => {
|
||||
try {
|
||||
const res = await fetch(`${API_URL}/admin/audio/routing`);
|
||||
if (!res.ok) {
|
||||
throw new Error(`HTTP error! status: ${res.status}`);
|
||||
}
|
||||
const data = await res.json();
|
||||
setRouting(data.routing || { inputToGroup: {}, groupToOutput: {}, gains: {} });
|
||||
} catch (error) {
|
||||
console.error('Erreur chargement routing:', error);
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
const loadAudioDevice = async () => {
|
||||
try {
|
||||
const res = await fetch(`${API_URL}/admin/audio/device`);
|
||||
if (res.ok) {
|
||||
const data = await res.json();
|
||||
setAudioDevice({
|
||||
inputChannels: data.device?.inputChannels || 8,
|
||||
outputChannels: data.device?.outputChannels || 8
|
||||
});
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Erreur chargement audio device:', error);
|
||||
}
|
||||
};
|
||||
|
||||
const saveRouting = async () => {
|
||||
try {
|
||||
const res = await fetch(`${API_URL}/admin/audio/routing`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(routing)
|
||||
});
|
||||
|
||||
if (res.ok) {
|
||||
alert('Configuration de routing sauvegardée!');
|
||||
} else {
|
||||
const errorText = await res.text();
|
||||
console.error('Erreur serveur:', errorText);
|
||||
alert(`Erreur: ${res.status} - ${errorText}`);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Erreur sauvegarde routing:', error);
|
||||
alert('Erreur lors de la sauvegarde');
|
||||
}
|
||||
};
|
||||
|
||||
const toggleInputToGroup = (inputId, groupId) => {
|
||||
setRouting(prev => {
|
||||
const inputToGroup = { ...prev.inputToGroup };
|
||||
if (!inputToGroup[inputId]) {
|
||||
inputToGroup[inputId] = [];
|
||||
}
|
||||
|
||||
const groupArray = [...inputToGroup[inputId]];
|
||||
const index = groupArray.indexOf(groupId);
|
||||
|
||||
if (index > -1) {
|
||||
groupArray.splice(index, 1);
|
||||
} else {
|
||||
groupArray.push(groupId);
|
||||
}
|
||||
|
||||
inputToGroup[inputId] = groupArray;
|
||||
|
||||
return { ...prev, inputToGroup };
|
||||
});
|
||||
};
|
||||
|
||||
const toggleGroupToOutput = (groupId, outputId) => {
|
||||
setRouting(prev => {
|
||||
const groupToOutput = { ...prev.groupToOutput };
|
||||
if (!groupToOutput[groupId]) {
|
||||
groupToOutput[groupId] = [];
|
||||
}
|
||||
|
||||
const outputArray = [...groupToOutput[groupId]];
|
||||
const index = outputArray.indexOf(outputId);
|
||||
|
||||
if (index > -1) {
|
||||
outputArray.splice(index, 1);
|
||||
} else {
|
||||
outputArray.push(outputId);
|
||||
}
|
||||
|
||||
groupToOutput[groupId] = outputArray;
|
||||
|
||||
return { ...prev, groupToOutput };
|
||||
});
|
||||
};
|
||||
|
||||
const isInputRoutedToGroup = (inputId, groupId) => {
|
||||
return routing.inputToGroup[inputId]?.includes(groupId) || false;
|
||||
};
|
||||
|
||||
const isGroupRoutedToOutput = (groupId, outputId) => {
|
||||
return routing.groupToOutput[groupId]?.includes(outputId) || false;
|
||||
};
|
||||
|
||||
const getGainForInputToGroup = (inputId, groupId) => {
|
||||
const key = `in_${inputId}_${groupId}`;
|
||||
return routing.gains?.[key] || 0.0;
|
||||
};
|
||||
|
||||
const getGainForGroupToOutput = (groupId, outputId) => {
|
||||
const key = `${groupId}_out_${outputId}`;
|
||||
return routing.gains?.[key] || 0.0;
|
||||
};
|
||||
|
||||
const setGainForInputToGroup = (inputId, groupId, gainDb) => {
|
||||
setRouting(prev => {
|
||||
const gains = { ...prev.gains };
|
||||
const key = `in_${inputId}_${groupId}`;
|
||||
gains[key] = parseFloat(gainDb);
|
||||
return { ...prev, gains };
|
||||
});
|
||||
};
|
||||
|
||||
const setGainForGroupToOutput = (groupId, outputId, gainDb) => {
|
||||
setRouting(prev => {
|
||||
const gains = { ...prev.gains };
|
||||
const key = `${groupId}_out_${outputId}`;
|
||||
gains[key] = parseFloat(gainDb);
|
||||
return { ...prev, gains };
|
||||
});
|
||||
};
|
||||
|
||||
const formatGain = (gainDb) => {
|
||||
if (gainDb === 0) return '0dB';
|
||||
return gainDb > 0 ? `+${gainDb}dB` : `${gainDb}dB`;
|
||||
};
|
||||
|
||||
const getChannelName = (type, id) => {
|
||||
const name = channelNames?.[type]?.[id];
|
||||
return name || `${type === 'inputs' ? 'Input' : 'Output'} ${id}`;
|
||||
};
|
||||
|
||||
const hasCustomName = (type, id) => {
|
||||
return channelNames?.[type]?.[id] !== undefined;
|
||||
};
|
||||
|
||||
const getVisibleInputChannels = () => {
|
||||
const allInputs = Array.from({length: audioDevice.inputChannels}, (_, i) => i);
|
||||
if (showOnlyNamedChannels) {
|
||||
return allInputs.filter(i => hasCustomName('inputs', i));
|
||||
}
|
||||
return allInputs;
|
||||
};
|
||||
|
||||
const getVisibleOutputChannels = () => {
|
||||
const allOutputs = Array.from({length: audioDevice.outputChannels}, (_, i) => i);
|
||||
if (showOnlyNamedChannels) {
|
||||
return allOutputs.filter(i => hasCustomName('outputs', i));
|
||||
}
|
||||
return allOutputs;
|
||||
};
|
||||
|
||||
if (loading) {
|
||||
return <div style={{padding: 'var(--spacing-xl)', textAlign: 'center'}}>Chargement...</div>;
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="routing-matrix-container">
|
||||
<div className="routing-matrix-header">
|
||||
<div style={{ display: 'flex', alignItems: 'center', gap: '1rem' }}>
|
||||
<h3>Matrice de routing audio</h3>
|
||||
<span
|
||||
className={`ws-status ${wsConnected ? 'connected' : 'disconnected'}`}
|
||||
title={wsConnected ? 'Monitoring temps réel actif' : 'Monitoring temps réel déconnecté'}
|
||||
>
|
||||
{wsConnected ? '● Live' : '○ Offline'}
|
||||
</span>
|
||||
</div>
|
||||
<label style={{ display: 'flex', alignItems: 'center', gap: '0.5rem', cursor: 'pointer' }}>
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={showOnlyNamedChannels}
|
||||
onChange={(e) => setShowOnlyNamedChannels(e.target.checked)}
|
||||
/>
|
||||
<span>Afficher uniquement les canaux nommés</span>
|
||||
</label>
|
||||
</div>
|
||||
|
||||
<div className="routing-section">
|
||||
<h4>Inputs vers Groupes</h4>
|
||||
<p className="routing-description">
|
||||
Sélectionnez quels inputs audio alimentent chaque groupe
|
||||
</p>
|
||||
|
||||
<div className="routing-matrix" style={{gridTemplateColumns: `120px repeat(${groups.length}, minmax(60px, 1fr))`}}>
|
||||
<div className="matrix-corner"></div>
|
||||
|
||||
{groups.map(group => (
|
||||
<div key={group.id} className="matrix-header-cell">
|
||||
{group.name}
|
||||
</div>
|
||||
))}
|
||||
|
||||
{getVisibleInputChannels().map(i => (
|
||||
<React.Fragment key={`input-row-${i}`}>
|
||||
<div className="matrix-label-cell">
|
||||
<div className="label-content">
|
||||
<span className="label-text">{getChannelName('inputs', i)}</span>
|
||||
{wsConnected && levels.inputs[i] && (
|
||||
<VUMeter level={levels.inputs[i]} size="mini" />
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{groups.map(group => {
|
||||
const isRouted = isInputRoutedToGroup(String(i), group.id);
|
||||
const gain = getGainForInputToGroup(String(i), group.id);
|
||||
|
||||
return (
|
||||
<div
|
||||
key={`${i}-${group.id}`}
|
||||
className={`matrix-cell ${isRouted ? 'active' : ''}`}
|
||||
>
|
||||
<div
|
||||
className="cell-checkbox"
|
||||
onClick={() => toggleInputToGroup(String(i), group.id)}
|
||||
>
|
||||
{isRouted && <span className="checkmark">✓</span>}
|
||||
</div>
|
||||
{isRouted && (
|
||||
<select
|
||||
className="gain-select"
|
||||
value={gain}
|
||||
onChange={(e) => setGainForInputToGroup(String(i), group.id, e.target.value)}
|
||||
onClick={(e) => e.stopPropagation()}
|
||||
>
|
||||
<option value="-12">-12dB</option>
|
||||
<option value="-6">-6dB</option>
|
||||
<option value="-3">-3dB</option>
|
||||
<option value="0">0dB</option>
|
||||
<option value="3">+3dB</option>
|
||||
<option value="6">+6dB</option>
|
||||
</select>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</React.Fragment>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="routing-section">
|
||||
<h4>Groupes vers Outputs</h4>
|
||||
<p className="routing-description">
|
||||
Sélectionnez vers quels outputs chaque groupe envoie son audio
|
||||
</p>
|
||||
|
||||
<div className="routing-matrix" style={{gridTemplateColumns: `120px repeat(${getVisibleOutputChannels().length}, minmax(60px, 1fr))`}}>
|
||||
<div className="matrix-corner"></div>
|
||||
|
||||
{getVisibleOutputChannels().map(i => (
|
||||
<div key={`output-header-${i}`} className="matrix-header-cell">
|
||||
<div className="header-content">
|
||||
<span className="header-text">{getChannelName('outputs', i)}</span>
|
||||
{wsConnected && levels.outputs[i] && (
|
||||
<VUMeter level={levels.outputs[i]} size="mini" />
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
|
||||
{groups.map(group => (
|
||||
<React.Fragment key={`group-row-${group.id}`}>
|
||||
<div className="matrix-label-cell">
|
||||
<div className="label-content">
|
||||
<span className="label-text">{group.name}</span>
|
||||
{wsConnected && levels.groups[group.id] && (
|
||||
<VUMeter level={levels.groups[group.id]} size="mini" />
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{getVisibleOutputChannels().map(i => {
|
||||
const isRouted = isGroupRoutedToOutput(group.id, String(i));
|
||||
const gain = getGainForGroupToOutput(group.id, String(i));
|
||||
|
||||
return (
|
||||
<div
|
||||
key={`${group.id}-${i}`}
|
||||
className={`matrix-cell ${isRouted ? 'active' : ''}`}
|
||||
>
|
||||
<div
|
||||
className="cell-checkbox"
|
||||
onClick={() => toggleGroupToOutput(group.id, String(i))}
|
||||
>
|
||||
{isRouted && <span className="checkmark">✓</span>}
|
||||
</div>
|
||||
{isRouted && (
|
||||
<select
|
||||
className="gain-select"
|
||||
value={gain}
|
||||
onChange={(e) => setGainForGroupToOutput(group.id, String(i), e.target.value)}
|
||||
onClick={(e) => e.stopPropagation()}
|
||||
>
|
||||
<option value="-12">-12dB</option>
|
||||
<option value="-6">-6dB</option>
|
||||
<option value="-3">-3dB</option>
|
||||
<option value="0">0dB</option>
|
||||
<option value="3">+3dB</option>
|
||||
<option value="6">+6dB</option>
|
||||
</select>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</React.Fragment>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="routing-actions">
|
||||
<button onClick={saveRouting} className="btn-primary">
|
||||
Sauvegarder le routing audio
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export default AudioRoutingMatrix;
|
||||
@@ -283,8 +283,17 @@ export default function useLiveKit() {
|
||||
});
|
||||
});
|
||||
|
||||
// Participants distants (utilisateurs WebRTC)
|
||||
// Participants distants (utilisateurs WebRTC + server audio users)
|
||||
// Exclure les participants internes de routage (role: 'bridge')
|
||||
room.remoteParticipants.forEach((participant) => {
|
||||
let role = null;
|
||||
try {
|
||||
const meta = participant.metadata ? JSON.parse(participant.metadata) : {};
|
||||
role = meta.role || null;
|
||||
} catch (_) {}
|
||||
|
||||
if (role === 'bridge') return;
|
||||
|
||||
const audioTracks = participant.audioTracks ? Array.from(participant.audioTracks.values()) : [];
|
||||
const audioPublication = audioTracks[0];
|
||||
const isSpeaking = room.activeSpeakers.some(s => s.identity === participant.identity);
|
||||
|
||||
@@ -0,0 +1,19 @@
|
||||
# Node
|
||||
node_modules/
|
||||
npm-debug.log
|
||||
yarn-error.log
|
||||
|
||||
# Electron
|
||||
dist/
|
||||
out/
|
||||
|
||||
# OS
|
||||
.DS_Store
|
||||
Thumbs.db
|
||||
|
||||
# IDE
|
||||
.vscode/
|
||||
.idea/
|
||||
|
||||
# Logs
|
||||
*.log
|
||||
@@ -0,0 +1,153 @@
|
||||
# PTT Live Desktop - Changelog
|
||||
|
||||
## v0.3.0 - 2026-06-19
|
||||
|
||||
### 🎉 Première version de l'application desktop Electron
|
||||
|
||||
#### ✨ Nouvelles Fonctionnalités
|
||||
|
||||
**Interface Electron**
|
||||
- Application desktop native (macOS/Linux)
|
||||
- Main Process spawn serveur Node.js automatiquement
|
||||
- IPC sécurisé via contextBridge (preload.js)
|
||||
- Démarrage/arrêt serveur depuis l'interface
|
||||
- Tray icon placeholder (à compléter)
|
||||
|
||||
**Dashboard**
|
||||
- Stats temps réel (uptime, utilisateurs, connexions)
|
||||
- Liste utilisateurs connectés avec groupes
|
||||
- Génération QR Code automatique (détection IP réseau)
|
||||
- Bouton copier URL clients
|
||||
- Polling automatique toutes les 2 secondes
|
||||
|
||||
**Configuration Audio**
|
||||
- Sélection devices input/output (auto-détectés)
|
||||
- Configuration sample rate (44.1/48/96 kHz)
|
||||
- Bitrate par défaut (32-320 kbps)
|
||||
- Jitter buffer (20-100 ms)
|
||||
- Sauvegarde dans config.yaml
|
||||
|
||||
**Gestion Groupes**
|
||||
- Liste groupes existants
|
||||
- Création nouveau groupe (nom + bitrate)
|
||||
- Modification/suppression (via API admin)
|
||||
- Synchronisation config.yaml
|
||||
|
||||
**Monitoring**
|
||||
- Logs serveur en temps réel
|
||||
- Filtrage par niveau (error/warn/info/debug)
|
||||
- Bouton effacer logs
|
||||
- Format timestamp + niveau + message
|
||||
|
||||
**Notifications**
|
||||
- Toast visuelles (success/error/warning/info)
|
||||
- Auto-dismiss 5 secondes
|
||||
- Bouton fermeture manuelle
|
||||
- Animation slide-in
|
||||
|
||||
#### 🛠️ Technique
|
||||
|
||||
**Stack**
|
||||
- Electron 28.0.0
|
||||
- electron-builder 24.9.1
|
||||
- qrcode 1.5.3 (via CDN)
|
||||
- HTML/CSS/JS vanilla (pas de framework)
|
||||
|
||||
**Architecture**
|
||||
- Main Process : spawn serveur, IPC handlers
|
||||
- Renderer Process : dashboard, fetch API admin
|
||||
- Communication : IPC + HTTP vers localhost:3000
|
||||
|
||||
**API Utilisées**
|
||||
- `GET /admin/stats` : dashboard metrics
|
||||
- `GET /admin/users` : utilisateurs
|
||||
- `GET /admin/groups` : groupes
|
||||
- `POST /admin/groups` : créer groupe
|
||||
- `GET /admin/config` : config complète
|
||||
- `PUT /admin/config/audio` : config audio
|
||||
- `GET /admin/devices/list` : auto-détection devices
|
||||
- `POST /admin/audio/device` : sélectionner device
|
||||
- `GET /health` : health check
|
||||
|
||||
**Build**
|
||||
- electron-builder configuré
|
||||
- macOS : .dmg + .app
|
||||
- Linux : .deb + .AppImage
|
||||
- Scripts : `npm run build:mac` / `build:linux`
|
||||
|
||||
#### 📝 Documentation
|
||||
|
||||
- [DESKTOP-APP.md](DESKTOP-APP.md) : doc complète (architecture, API, debug)
|
||||
- [QUICKSTART.md](QUICKSTART.md) : guide démarrage rapide
|
||||
- [README.md](README.md) : intégration Electron dans README principal
|
||||
- [CLAUDE.md](../CLAUDE.md) : section Application Desktop ajoutée
|
||||
|
||||
#### 🚧 TODO / Limitations
|
||||
|
||||
**À implémenter** :
|
||||
- [ ] WebSocket audio levels (VU-mètres temps réel)
|
||||
- [ ] Vraies icônes (icon.icns / icon.png)
|
||||
- [ ] Tray icon fonctionnel avec menu
|
||||
- [ ] Graphiques monitoring (Chart.js)
|
||||
- [ ] Export logs (CSV/JSON)
|
||||
- [ ] Matrice routing audio (drag & drop)
|
||||
- [ ] Auth admin (mot de passe)
|
||||
- [ ] Thème dark/light toggle
|
||||
- [ ] Auto-update (electron-updater)
|
||||
- [ ] Tests (Spectron/Playwright)
|
||||
|
||||
**Limitations connues** :
|
||||
- QR Code utilise CDN (pas de lib locale)
|
||||
- Pas de CSP (Content-Security-Policy)
|
||||
- Pas de signature code (notarization macOS)
|
||||
- Tray icon pas implémenté (commenté dans main.js)
|
||||
|
||||
#### 🔧 Installation
|
||||
|
||||
```bash
|
||||
# Depuis la racine du projet
|
||||
./start-desktop.sh
|
||||
|
||||
# OU depuis electron/
|
||||
cd electron
|
||||
npm install
|
||||
npm start
|
||||
```
|
||||
|
||||
#### 🏗️ Structure Fichiers
|
||||
|
||||
```
|
||||
electron/
|
||||
├── package.json # Config Electron
|
||||
├── main.js # Main Process (585 lignes)
|
||||
├── preload.js # IPC bridge (40 lignes)
|
||||
├── README.md # Doc technique
|
||||
├── QUICKSTART.md # Guide démarrage
|
||||
├── CHANGELOG.md # Ce fichier
|
||||
└── ui/
|
||||
├── index.html # Interface (185 lignes)
|
||||
├── styles.css # Styles (557 lignes)
|
||||
└── app.js # Logic frontend (627 lignes)
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Prochaine version (v0.3.1)
|
||||
|
||||
### 🎯 Priorités
|
||||
|
||||
1. **VU-mètres WebSocket** : connexion `/audio-levels`
|
||||
2. **Icônes** : créer icon.icns + icon.png + tray-icon.png
|
||||
3. **Tray menu** : implémenter menu contextuel
|
||||
4. **Tests** : premiers tests Electron
|
||||
|
||||
### 💡 Idées
|
||||
|
||||
- Graphiques latence/bande passante (Chart.js)
|
||||
- Notifications desktop (Electron Notification API)
|
||||
- Matrice routing visuelle
|
||||
- Export config (JSON/YAML)
|
||||
|
||||
---
|
||||
|
||||
**Développé avec Claude Code**
|
||||
@@ -0,0 +1,139 @@
|
||||
# PTT Live Desktop - Quick Start Guide
|
||||
|
||||
## 🚀 Lancement en 30 secondes
|
||||
|
||||
```bash
|
||||
# Depuis la racine du projet
|
||||
./start-desktop.sh
|
||||
```
|
||||
|
||||
C'est tout ! L'application démarre automatiquement le serveur.
|
||||
|
||||
---
|
||||
|
||||
## 📋 Checklist Première Utilisation
|
||||
|
||||
### 1. Vérifier le serveur
|
||||
|
||||
✅ Statut : **🟢 Actif** (coin haut-droit)
|
||||
✅ Dashboard : stats doivent s'afficher sous 5s
|
||||
|
||||
### 2. Configurer l'audio
|
||||
|
||||
**Configuration → Périphériques Audio**
|
||||
|
||||
1. Sélectionner **Input Device** (carte son ou micro)
|
||||
2. Sélectionner **Output Device** (haut-parleurs)
|
||||
3. Cliquer **Appliquer**
|
||||
|
||||
💡 Les devices sont auto-détectés depuis votre système
|
||||
|
||||
### 3. Créer des groupes (optionnel)
|
||||
|
||||
**Groupes → ➕ Nouveau groupe**
|
||||
|
||||
1. Entrer un nom (ex: "Production")
|
||||
2. Bitrate par défaut : 96 kbps (voix standard)
|
||||
3. Sauvegarder
|
||||
|
||||
Les groupes sont enregistrés dans `server/config/config.yaml`
|
||||
|
||||
### 4. Connecter des clients
|
||||
|
||||
**Dashboard → QR Code**
|
||||
|
||||
1. Scanner le QR Code avec smartphone
|
||||
2. OU copier l'URL et ouvrir dans navigateur
|
||||
|
||||
URL type : `https://192.168.1.10:5173`
|
||||
|
||||
---
|
||||
|
||||
## 🎯 Fonctionnalités Principales
|
||||
|
||||
### Dashboard
|
||||
|
||||
- **Stats** : uptime, utilisateurs, connexions
|
||||
- **QR Code** : connexion rapide clients
|
||||
- **Utilisateurs** : liste en temps réel
|
||||
|
||||
### Configuration
|
||||
|
||||
- **Audio** : devices, sample rate, bitrate, jitter buffer
|
||||
- **Groupes** : créer/modifier/supprimer
|
||||
|
||||
### Monitoring
|
||||
|
||||
- **Logs** : serveur en temps réel, filtrables
|
||||
|
||||
---
|
||||
|
||||
## 🐛 Problèmes Courants
|
||||
|
||||
### Serveur ne démarre pas
|
||||
|
||||
**Symptôme** : statut reste "⚪ Arrêté"
|
||||
|
||||
**Solutions** :
|
||||
|
||||
1. Vérifier port 3000 libre :
|
||||
```bash
|
||||
lsof -i :3000
|
||||
```
|
||||
|
||||
2. Vérifier LiveKit installé :
|
||||
```bash
|
||||
livekit-server --version
|
||||
# OU
|
||||
ls ../server/bin/livekit-server
|
||||
```
|
||||
|
||||
3. Voir logs dans **Monitoring → Logs**
|
||||
|
||||
### QR Code ne s'affiche pas
|
||||
|
||||
**Symptôme** : zone blanche
|
||||
|
||||
**Solutions** :
|
||||
|
||||
1. Attendre 5-10s (génération après démarrage serveur)
|
||||
2. Vérifier serveur actif (🟢)
|
||||
3. Recharger : **Dashboard** → cliquer nav
|
||||
|
||||
### Pas d'audio
|
||||
|
||||
**Symptôme** : clients connectés mais pas de son
|
||||
|
||||
**Solutions** :
|
||||
|
||||
1. **Configuration** → vérifier devices sélectionnés
|
||||
2. Vérifier permissions micro (système)
|
||||
3. Tester avec devices différents
|
||||
|
||||
---
|
||||
|
||||
## ⌨️ Raccourcis
|
||||
|
||||
- `Cmd/Ctrl + R` : recharger interface
|
||||
- `Cmd/Ctrl + Q` : quitter app
|
||||
- `Cmd/Ctrl + Shift + I` : DevTools (debug)
|
||||
|
||||
---
|
||||
|
||||
## 📖 Documentation
|
||||
|
||||
- [DESKTOP-APP.md](DESKTOP-APP.md) : doc complète
|
||||
- [README.md](../README.md) : vue d'ensemble projet
|
||||
- [CLAUDE.md](../CLAUDE.md) : doc développement
|
||||
|
||||
---
|
||||
|
||||
## 🆘 Support
|
||||
|
||||
**Logs** : `Monitoring → Logs`
|
||||
**DevTools** : `npm run dev` (dans terminal)
|
||||
**Issues** : GitHub (si open source)
|
||||
|
||||
---
|
||||
|
||||
Bon intercom ! 🎙️
|
||||
@@ -0,0 +1,171 @@
|
||||
# PTT Live Desktop
|
||||
|
||||
Application desktop Electron pour gérer le serveur PTT Live.
|
||||
|
||||
## 🚀 Démarrage
|
||||
|
||||
```bash
|
||||
# Depuis la racine du projet
|
||||
./start-desktop.sh
|
||||
|
||||
# OU depuis electron/
|
||||
cd electron
|
||||
npm start
|
||||
```
|
||||
|
||||
## 📦 Build pour distribution
|
||||
|
||||
```bash
|
||||
cd electron
|
||||
|
||||
# macOS
|
||||
npm run build:mac
|
||||
|
||||
# Linux
|
||||
npm run build:linux
|
||||
|
||||
# Les deux
|
||||
npm run build
|
||||
```
|
||||
|
||||
Les builds seront dans `electron/dist/`.
|
||||
|
||||
## 🎨 Fonctionnalités
|
||||
|
||||
### Dashboard
|
||||
- ✅ Stats temps réel (uptime, utilisateurs, connexions)
|
||||
- ✅ Liste utilisateurs connectés
|
||||
- ✅ QR Code pour connexion rapide clients
|
||||
- ✅ Contrôles démarrage/arrêt serveur
|
||||
|
||||
### Configuration
|
||||
- ✅ Sélection périphériques audio (input/output)
|
||||
- ✅ Paramètres audio (sample rate, bitrate, jitter buffer)
|
||||
- ✅ Sauvegarde automatique dans config.yaml
|
||||
|
||||
### Groupes
|
||||
- ✅ Liste groupes configurés
|
||||
- ✅ Ajout/modification/suppression groupes
|
||||
- ✅ Configuration bitrate par groupe
|
||||
|
||||
### Monitoring
|
||||
- 🚧 VU-mètres temps réel (WebSocket)
|
||||
- 🚧 Graphiques latence
|
||||
- 🚧 Stats réseau par client
|
||||
|
||||
### Logs
|
||||
- ✅ Logs serveur en temps réel
|
||||
- ✅ Filtrage par niveau (error/warn/info/debug)
|
||||
- ✅ Export logs
|
||||
|
||||
## 🏗️ Architecture
|
||||
|
||||
```
|
||||
electron/
|
||||
├── main.js # Main Process (Node.js)
|
||||
│ # - Spawn serveur PTT Live
|
||||
│ # - IPC avec renderer
|
||||
│ # - Gestion tray icon
|
||||
│
|
||||
├── preload.js # Bridge sécurisé IPC
|
||||
│
|
||||
└── ui/ # Renderer Process (Frontend)
|
||||
├── index.html # Interface dashboard
|
||||
├── styles.css # Styles
|
||||
└── app.js # Logic frontend
|
||||
# - Consomme API admin (/admin/*)
|
||||
# - Met à jour UI
|
||||
```
|
||||
|
||||
## 🔌 Communication
|
||||
|
||||
```
|
||||
┌─────────────────────────────────────────┐
|
||||
│ MAIN PROCESS (Node.js) │
|
||||
│ ┌──────────────────────────────────┐ │
|
||||
│ │ Serveur PTT Live (spawn) │ │
|
||||
│ │ - LiveKit Server │ │
|
||||
│ │ - Audio Bridge │ │
|
||||
│ │ - API REST :3000 │ │
|
||||
│ └──────────────────────────────────┘ │
|
||||
│ ↕ IPC │
|
||||
│ ┌──────────────────────────────────┐ │
|
||||
│ │ Electron Window │ │
|
||||
│ └──────────────────────────────────┘ │
|
||||
└─────────────────────────────────────────┘
|
||||
↕ HTTP
|
||||
┌─────────────────────────────────────────┐
|
||||
│ RENDERER PROCESS (Frontend) │
|
||||
│ - Fetch API admin │
|
||||
│ - WebSocket audio levels │
|
||||
│ - Interface dashboard │
|
||||
└─────────────────────────────────────────┘
|
||||
```
|
||||
|
||||
## 🛠️ API Utilisées
|
||||
|
||||
Toutes les routes de l'API admin serveur :
|
||||
|
||||
```
|
||||
GET /admin/stats → Dashboard metrics
|
||||
GET /admin/users → Utilisateurs connectés
|
||||
GET /admin/groups → Liste groupes
|
||||
POST /admin/groups → Créer groupe
|
||||
PUT /admin/groups/:id → Modifier groupe
|
||||
DELETE /admin/groups/:id → Supprimer groupe
|
||||
GET /admin/config → Config complète
|
||||
PUT /admin/config/audio → Mettre à jour config audio
|
||||
GET /admin/audio/devices → Énumérer devices
|
||||
POST /admin/audio/device → Sélectionner device
|
||||
GET /admin/audio/routing → Config routing
|
||||
POST /admin/audio/routing → Mettre à jour routing
|
||||
GET /admin/devices/list → Auto-détection devices
|
||||
GET /admin/logs → Logs serveur
|
||||
WS /audio-levels → WebSocket VU-mètres
|
||||
```
|
||||
|
||||
## 🔧 TODO
|
||||
|
||||
- [ ] Implémenter QR Code canvas (bibliothèque qrcode.js)
|
||||
- [ ] WebSocket audio levels pour VU-mètres
|
||||
- [ ] Notifications desktop (toast)
|
||||
- [ ] Tray icon avec vraie icône
|
||||
- [ ] Graphiques monitoring (Chart.js)
|
||||
- [ ] Export logs (CSV/JSON)
|
||||
- [ ] Auth admin (optionnel)
|
||||
- [ ] Thème dark/light toggle
|
||||
- [ ] Auto-update (electron-updater)
|
||||
|
||||
## 📝 Notes de développement
|
||||
|
||||
- **Main Process** : Gère le cycle de vie de l'app et spawn le serveur
|
||||
- **Renderer Process** : Interface web, appelle l'API REST du serveur
|
||||
- **IPC** : Communication sécurisée via contextBridge
|
||||
- **Serveur** : Tourne dans un process child_process, logs transmis au renderer
|
||||
- **Port** : 3000 par défaut (configurable via PORT env)
|
||||
|
||||
## 🐛 Debug
|
||||
|
||||
Ouvrir DevTools : automatique en mode `--dev`
|
||||
|
||||
```bash
|
||||
npm run dev
|
||||
```
|
||||
|
||||
Logs dans la console :
|
||||
- `[Serveur]` : logs du serveur PTT Live
|
||||
- `[Serveur Error]` : erreurs serveur
|
||||
- `✅/❌` : statut démarrage/arrêt
|
||||
|
||||
## 📦 Packaging
|
||||
|
||||
electron-builder crée :
|
||||
- **macOS** : `.dmg` + `.app` dans `dist/mac/`
|
||||
- **Linux** : `.deb` + `.AppImage` dans `dist/`
|
||||
|
||||
Tester le build :
|
||||
|
||||
```bash
|
||||
npm run build:mac
|
||||
open dist/mac/PTT\ Live\ Server.app
|
||||
```
|
||||
@@ -0,0 +1,715 @@
|
||||
/**
|
||||
* PTT Live Desktop - Main Process
|
||||
* Intègre le serveur Node.js existant dans une application Electron
|
||||
*/
|
||||
|
||||
const { app, BrowserWindow, ipcMain, Menu, Tray, dialog } = require('electron');
|
||||
const path = require('path');
|
||||
const fs = require('fs');
|
||||
const { spawn } = require('child_process');
|
||||
const http = require('http');
|
||||
const https = require('https');
|
||||
const QRCode = require('qrcode');
|
||||
const yaml = require('yaml');
|
||||
const setupHelper = require('./setup-helper');
|
||||
|
||||
const CONFIG_PATH = path.join(__dirname, '..', 'server', 'config', 'config.yaml');
|
||||
|
||||
function readConfig() {
|
||||
return yaml.parse(fs.readFileSync(CONFIG_PATH, 'utf8'));
|
||||
}
|
||||
|
||||
function writeConfig(config) {
|
||||
fs.writeFileSync(CONFIG_PATH, yaml.stringify(config), 'utf8');
|
||||
}
|
||||
|
||||
function slugify(text) {
|
||||
return text.toString().normalize('NFD').replace(/[̀-ͯ]/g, '')
|
||||
.toLowerCase().trim().replace(/\s+/g, '-').replace(/[^\w-]+/g, '').replace(/--+/g, '-');
|
||||
}
|
||||
|
||||
// État de l'application
|
||||
let mainWindow = null;
|
||||
let tray = null;
|
||||
let serverProcess = null;
|
||||
let serverStarted = false;
|
||||
let rendererReady = false;
|
||||
|
||||
const SERVER_PORT = process.env.PORT || 3000;
|
||||
// HTTPS activé par défaut (cohérent avec le setup mkcert automatique au premier
|
||||
// lancement) ; ENABLE_HTTPS=false permet de revenir explicitement en HTTP
|
||||
const ENABLE_HTTPS = process.env.ENABLE_HTTPS !== 'false';
|
||||
const SERVER_PROTOCOL = ENABLE_HTTPS ? 'https' : 'http';
|
||||
// 127.0.0.1 plutôt que localhost : le serveur n'écoute qu'en IPv4 (host: 0.0.0.0
|
||||
// dans config.yaml), or le Node embarqué par Electron peut résoudre "localhost"
|
||||
// en IPv6 (::1) en priorité, ce qui ferait échouer silencieusement le ping
|
||||
const SERVER_URL = `${SERVER_PROTOCOL}://127.0.0.1:${SERVER_PORT}`;
|
||||
const isDev = process.argv.includes('--dev');
|
||||
|
||||
/**
|
||||
* Créer la fenêtre principale
|
||||
*/
|
||||
function createWindow() {
|
||||
mainWindow = new BrowserWindow({
|
||||
width: 1200,
|
||||
height: 800,
|
||||
minWidth: 900,
|
||||
minHeight: 600,
|
||||
webPreferences: {
|
||||
preload: path.join(__dirname, 'preload.js'),
|
||||
nodeIntegration: false,
|
||||
contextIsolation: true
|
||||
},
|
||||
title: 'PTT Live Server',
|
||||
backgroundColor: '#1a1a1a'
|
||||
});
|
||||
|
||||
// Charger l'interface dashboard
|
||||
mainWindow.loadFile(path.join(__dirname, 'ui', 'index.html'));
|
||||
|
||||
// Attendre que le renderer soit prêt
|
||||
mainWindow.webContents.on('did-finish-load', () => {
|
||||
rendererReady = true;
|
||||
console.log('✅ Interface chargée');
|
||||
|
||||
// Envoyer l'état initial du serveur
|
||||
if (mainWindow) {
|
||||
mainWindow.webContents.send('server:status', { running: serverStarted });
|
||||
}
|
||||
});
|
||||
|
||||
// DevTools en mode dev
|
||||
if (isDev) {
|
||||
mainWindow.webContents.openDevTools();
|
||||
}
|
||||
|
||||
// Cleanup à la fermeture
|
||||
mainWindow.on('closed', () => {
|
||||
mainWindow = null;
|
||||
rendererReady = false;
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Créer la tray icon (macOS/Linux)
|
||||
*/
|
||||
function createTray() {
|
||||
// TODO: créer une vraie icône
|
||||
// tray = new Tray(path.join(__dirname, 'assets', 'tray-icon.png'));
|
||||
|
||||
const contextMenu = Menu.buildFromTemplate([
|
||||
{
|
||||
label: 'Ouvrir Dashboard',
|
||||
click: () => {
|
||||
if (mainWindow) {
|
||||
mainWindow.show();
|
||||
} else {
|
||||
createWindow();
|
||||
}
|
||||
}
|
||||
},
|
||||
{ type: 'separator' },
|
||||
{
|
||||
label: serverStarted ? '🟢 Serveur actif' : '⚪ Serveur arrêté',
|
||||
enabled: false
|
||||
},
|
||||
{
|
||||
label: serverStarted ? 'Arrêter serveur' : 'Démarrer serveur',
|
||||
click: async () => {
|
||||
if (serverStarted) {
|
||||
await stopServer();
|
||||
} else {
|
||||
await startServer();
|
||||
}
|
||||
}
|
||||
},
|
||||
{ type: 'separator' },
|
||||
{
|
||||
label: 'Quitter',
|
||||
click: () => {
|
||||
app.quit();
|
||||
}
|
||||
}
|
||||
]);
|
||||
|
||||
if (tray) {
|
||||
tray.setContextMenu(contextMenu);
|
||||
tray.setToolTip('PTT Live Server');
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Démarrer le serveur Node.js
|
||||
*/
|
||||
async function startServer() {
|
||||
return new Promise((resolve, reject) => {
|
||||
if (serverProcess) {
|
||||
console.log('⚠️ Serveur déjà démarré');
|
||||
resolve({ success: false, message: 'Server already running' });
|
||||
return;
|
||||
}
|
||||
|
||||
console.log('🚀 Démarrage du serveur PTT Live...');
|
||||
|
||||
const serverPath = path.join(__dirname, '..', 'server', 'index.js');
|
||||
|
||||
serverProcess = spawn('node', [serverPath], {
|
||||
cwd: path.join(__dirname, '..', 'server'),
|
||||
env: {
|
||||
...process.env,
|
||||
PORT: SERVER_PORT,
|
||||
USE_LOCAL_LIVEKIT: 'true',
|
||||
ENABLE_HTTPS: ENABLE_HTTPS ? 'true' : 'false',
|
||||
NODE_ENV: isDev ? 'development' : 'production'
|
||||
}
|
||||
});
|
||||
|
||||
serverProcess.stdout.on('data', (data) => {
|
||||
const output = data.toString();
|
||||
console.log('[Serveur]', output);
|
||||
|
||||
// Transmettre les logs au renderer (seulement si prêt)
|
||||
if (mainWindow && rendererReady) {
|
||||
mainWindow.webContents.send('server:log', {
|
||||
level: 'info',
|
||||
message: output.trim()
|
||||
});
|
||||
}
|
||||
|
||||
// Détecter démarrage réussi
|
||||
if (output.includes('Serveur prêt') || output.includes('API REST démarrée')) {
|
||||
serverStarted = true;
|
||||
console.log('✅ Serveur démarré avec succès');
|
||||
|
||||
if (mainWindow && rendererReady) {
|
||||
mainWindow.webContents.send('server:status', { running: true });
|
||||
}
|
||||
|
||||
createTray(); // Mettre à jour tray
|
||||
resolve({ success: true, url: SERVER_URL });
|
||||
}
|
||||
});
|
||||
|
||||
serverProcess.stderr.on('data', (data) => {
|
||||
const output = data.toString();
|
||||
|
||||
// LiveKit envoie INFO/WARN dans stderr (comportement normal Go)
|
||||
// Ne les traiter comme erreurs que s'ils contiennent vraiment "ERROR"
|
||||
const isError = output.includes('ERROR') || output.includes('Error:');
|
||||
|
||||
console.log(isError ? '[Serveur Error]' : '[Serveur]', output);
|
||||
|
||||
if (mainWindow && rendererReady) {
|
||||
mainWindow.webContents.send('server:log', {
|
||||
level: isError ? 'error' : 'info',
|
||||
message: output.trim()
|
||||
});
|
||||
}
|
||||
|
||||
// Détecter démarrage LiveKit dans stderr
|
||||
if (output.includes('starting LiveKit server') || output.includes('Serveur prêt')) {
|
||||
if (!serverStarted) {
|
||||
serverStarted = true;
|
||||
console.log('✅ Serveur démarré (détecté via stderr)');
|
||||
|
||||
if (mainWindow && rendererReady) {
|
||||
mainWindow.webContents.send('server:status', { running: true });
|
||||
}
|
||||
|
||||
createTray();
|
||||
resolve({ success: true, url: SERVER_URL });
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
serverProcess.on('error', (error) => {
|
||||
console.error('❌ Erreur démarrage serveur:', error);
|
||||
serverStarted = false;
|
||||
|
||||
if (mainWindow && rendererReady) {
|
||||
mainWindow.webContents.send('server:status', { running: false, error: error.message });
|
||||
}
|
||||
|
||||
reject(error);
|
||||
});
|
||||
|
||||
serverProcess.on('exit', (code, signal) => {
|
||||
console.log(`⚠️ Serveur arrêté (code: ${code}, signal: ${signal})`);
|
||||
serverProcess = null;
|
||||
serverStarted = false;
|
||||
|
||||
if (mainWindow && rendererReady) {
|
||||
mainWindow.webContents.send('server:status', { running: false });
|
||||
}
|
||||
|
||||
createTray(); // Mettre à jour tray
|
||||
});
|
||||
|
||||
// Timeout de sécurité (15s)
|
||||
setTimeout(() => {
|
||||
if (!serverStarted && serverProcess) {
|
||||
console.log('⏱️ Timeout démarrage serveur (15s), vérification health...');
|
||||
|
||||
// Vérifier que le serveur répond vraiment
|
||||
pingServer().then((health) => {
|
||||
if (health.success) {
|
||||
serverStarted = true;
|
||||
console.log('✅ Serveur répond au health check');
|
||||
|
||||
if (mainWindow) {
|
||||
mainWindow.webContents.send('server:status', { running: true });
|
||||
}
|
||||
|
||||
createTray();
|
||||
resolve({ success: true, url: SERVER_URL });
|
||||
} else {
|
||||
console.error('❌ Serveur ne répond pas après 15s');
|
||||
reject(new Error('Server startup timeout'));
|
||||
}
|
||||
});
|
||||
}
|
||||
}, 15000);
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Arrêter le serveur Node.js
|
||||
*/
|
||||
async function stopServer() {
|
||||
return new Promise((resolve) => {
|
||||
if (!serverProcess) {
|
||||
console.log('⚠️ Aucun serveur à arrêter');
|
||||
resolve({ success: false, message: 'No server running' });
|
||||
return;
|
||||
}
|
||||
|
||||
console.log('🛑 Arrêt du serveur...');
|
||||
|
||||
serverProcess.on('exit', () => {
|
||||
serverProcess = null;
|
||||
serverStarted = false;
|
||||
console.log('✅ Serveur arrêté');
|
||||
|
||||
if (mainWindow) {
|
||||
mainWindow.webContents.send('server:status', { running: false });
|
||||
}
|
||||
|
||||
createTray();
|
||||
resolve({ success: true });
|
||||
});
|
||||
|
||||
// Envoyer SIGTERM (shutdown gracieux)
|
||||
serverProcess.kill('SIGTERM');
|
||||
|
||||
// Forcer après 5s si nécessaire
|
||||
setTimeout(() => {
|
||||
if (serverProcess) {
|
||||
console.log('⚠️ Force kill du serveur');
|
||||
serverProcess.kill('SIGKILL');
|
||||
}
|
||||
}, 5000);
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Tester si le serveur répond
|
||||
*/
|
||||
async function pingServer() {
|
||||
return new Promise((resolve) => {
|
||||
const client = ENABLE_HTTPS ? https : http;
|
||||
// rejectUnauthorized: false : le cert mkcert est approuvé par le Keychain
|
||||
// macOS (Safari/Chrome/Electron renderer), mais le module https de Node
|
||||
// ne lit pas ce trust store et rejetterait sinon ce ping vers notre
|
||||
// propre serveur local.
|
||||
const options = ENABLE_HTTPS ? { rejectUnauthorized: false } : {};
|
||||
client.get(`${SERVER_URL}/health`, options, (res) => {
|
||||
let data = '';
|
||||
res.on('data', (chunk) => { data += chunk; });
|
||||
res.on('end', () => {
|
||||
try {
|
||||
const json = JSON.parse(data);
|
||||
resolve({ success: true, data: json });
|
||||
} catch (e) {
|
||||
resolve({ success: false, error: 'Invalid response' });
|
||||
}
|
||||
});
|
||||
}).on('error', (err) => {
|
||||
resolve({ success: false, error: err.message });
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
// ========== App Lifecycle ==========
|
||||
|
||||
app.whenReady().then(async () => {
|
||||
// Setup IPC Handlers (doit être après app.whenReady)
|
||||
ipcMain.handle('server:start', async () => {
|
||||
return await startServer();
|
||||
});
|
||||
|
||||
ipcMain.handle('server:stop', async () => {
|
||||
return await stopServer();
|
||||
});
|
||||
|
||||
ipcMain.handle('server:status', async () => {
|
||||
if (!serverStarted) {
|
||||
return { running: false };
|
||||
}
|
||||
|
||||
const health = await pingServer();
|
||||
return {
|
||||
running: health.success,
|
||||
health: health.data,
|
||||
error: health.error,
|
||||
url: SERVER_URL
|
||||
};
|
||||
});
|
||||
|
||||
ipcMain.handle('server:ping', async () => {
|
||||
return await pingServer();
|
||||
});
|
||||
|
||||
ipcMain.handle('qrcode:generate', async (event, text) => {
|
||||
try {
|
||||
const dataUrl = await QRCode.toDataURL(text, { width: 256, margin: 2 });
|
||||
return { success: true, dataUrl };
|
||||
} catch (error) {
|
||||
return { success: false, error: error.message };
|
||||
}
|
||||
});
|
||||
|
||||
ipcMain.handle('network:ip', async () => {
|
||||
return setupHelper.getNetworkIP();
|
||||
});
|
||||
|
||||
// ========== Groupes (lecture/écriture YAML directe, sans serveur) ==========
|
||||
|
||||
ipcMain.handle('groups:list', () => {
|
||||
try {
|
||||
const config = readConfig();
|
||||
return { groups: config.groups || [] };
|
||||
} catch (error) {
|
||||
return { groups: [], error: error.message };
|
||||
}
|
||||
});
|
||||
|
||||
ipcMain.handle('groups:create', (event, { name, audioBitrate }) => {
|
||||
try {
|
||||
const config = readConfig();
|
||||
const id = slugify(name);
|
||||
if ((config.groups || []).find(g => slugify(g.name) === id)) {
|
||||
return { success: false, error: `Un groupe "${name}" existe déjà` };
|
||||
}
|
||||
const group = { name, ...(audioBitrate ? { audioBitrate } : {}) };
|
||||
config.groups = [...(config.groups || []), group];
|
||||
writeConfig(config);
|
||||
return { success: true, group };
|
||||
} catch (error) {
|
||||
return { success: false, error: error.message };
|
||||
}
|
||||
});
|
||||
|
||||
ipcMain.handle('groups:update', (event, { id, name, audioBitrate }) => {
|
||||
try {
|
||||
const config = readConfig();
|
||||
const idx = (config.groups || []).findIndex(g => slugify(g.name) === id);
|
||||
if (idx === -1) return { success: false, error: `Groupe ${id} introuvable` };
|
||||
if (name !== undefined) config.groups[idx].name = name;
|
||||
if (audioBitrate !== undefined) config.groups[idx].audioBitrate = audioBitrate;
|
||||
writeConfig(config);
|
||||
return { success: true, group: config.groups[idx] };
|
||||
} catch (error) {
|
||||
return { success: false, error: error.message };
|
||||
}
|
||||
});
|
||||
|
||||
ipcMain.handle('groups:delete', (event, { id }) => {
|
||||
try {
|
||||
const config = readConfig();
|
||||
const idx = (config.groups || []).findIndex(g => slugify(g.name) === id);
|
||||
if (idx === -1) return { success: false, error: `Groupe ${id} introuvable` };
|
||||
config.groups.splice(idx, 1);
|
||||
writeConfig(config);
|
||||
return { success: true };
|
||||
} catch (error) {
|
||||
return { success: false, error: error.message };
|
||||
}
|
||||
});
|
||||
|
||||
// ========== Server Audio Users (lecture/écriture YAML directe) ==========
|
||||
|
||||
ipcMain.handle('server-audio-users:list', () => {
|
||||
try {
|
||||
const config = readConfig();
|
||||
return { users: config.server_audio_users || [] };
|
||||
} catch (error) {
|
||||
return { users: [], error: error.message };
|
||||
}
|
||||
});
|
||||
|
||||
ipcMain.handle('server-audio-users:create', (event, { name, group, input_channel, output_channel }) => {
|
||||
try {
|
||||
const config = readConfig();
|
||||
const users = config.server_audio_users || [];
|
||||
if (users.find(u => u.name === name)) {
|
||||
return { success: false, error: `Un utilisateur "${name}" existe déjà` };
|
||||
}
|
||||
const parsedInput = input_channel !== null && input_channel !== undefined ? parseInt(input_channel) : null;
|
||||
const user = {
|
||||
name,
|
||||
group,
|
||||
input_channel: parsedInput,
|
||||
output_channel: output_channel !== null && output_channel !== '' ? parseInt(output_channel) : null
|
||||
};
|
||||
config.server_audio_users = [...users, user];
|
||||
writeConfig(config);
|
||||
return { success: true, user };
|
||||
} catch (error) {
|
||||
return { success: false, error: error.message };
|
||||
}
|
||||
});
|
||||
|
||||
ipcMain.handle('server-audio-users:update', (event, { name, group, input_channel, output_channel }) => {
|
||||
try {
|
||||
const config = readConfig();
|
||||
const users = config.server_audio_users || [];
|
||||
const idx = users.findIndex(u => u.name === name);
|
||||
if (idx === -1) return { success: false, error: `Utilisateur "${name}" introuvable` };
|
||||
const parsedInput = input_channel !== null && input_channel !== undefined ? parseInt(input_channel) : null;
|
||||
config.server_audio_users[idx] = {
|
||||
name,
|
||||
group,
|
||||
input_channel: parsedInput,
|
||||
output_channel: output_channel !== null && output_channel !== '' ? parseInt(output_channel) : null
|
||||
};
|
||||
writeConfig(config);
|
||||
return { success: true };
|
||||
} catch (error) {
|
||||
return { success: false, error: error.message };
|
||||
}
|
||||
});
|
||||
|
||||
ipcMain.handle('server-audio-users:delete', (event, { name }) => {
|
||||
try {
|
||||
const config = readConfig();
|
||||
const users = config.server_audio_users || [];
|
||||
const idx = users.findIndex(u => u.name === name);
|
||||
if (idx === -1) return { success: false, error: `Utilisateur "${name}" introuvable` };
|
||||
config.server_audio_users.splice(idx, 1);
|
||||
writeConfig(config);
|
||||
return { success: true };
|
||||
} catch (error) {
|
||||
return { success: false, error: error.message };
|
||||
}
|
||||
});
|
||||
|
||||
// ========== Routing (lecture/écriture YAML directe) ==========
|
||||
|
||||
ipcMain.handle('routing:get', () => {
|
||||
try {
|
||||
const config = readConfig();
|
||||
return {
|
||||
channelNames: config.audio?.channelNames || { inputs: {}, outputs: {} },
|
||||
groups: config.groups || [],
|
||||
serverAudioUsers: config.server_audio_users || []
|
||||
};
|
||||
} catch (error) {
|
||||
return { error: error.message };
|
||||
}
|
||||
});
|
||||
|
||||
// ========== Devices : découverte canaux physiques ==========
|
||||
|
||||
ipcMain.handle('devices:getChannels', () => {
|
||||
try {
|
||||
const config = readConfig();
|
||||
const inputDeviceName = config.audio?.device?.inputDeviceId;
|
||||
const outputDeviceName = config.audio?.device?.outputDeviceId;
|
||||
|
||||
let inputDevice = { name: inputDeviceName || 'Non configuré', channels: 0 };
|
||||
let outputDevice = { name: outputDeviceName || 'Non configuré', channels: 0 };
|
||||
|
||||
if (process.platform === 'darwin') {
|
||||
try {
|
||||
const { execSync } = require('child_process');
|
||||
const raw = execSync('system_profiler SPAudioDataType -json', { encoding: 'utf8', timeout: 5000 });
|
||||
const data = JSON.parse(raw);
|
||||
|
||||
if (data.SPAudioDataType) {
|
||||
data.SPAudioDataType.forEach(item => {
|
||||
(item._items || []).forEach(dev => {
|
||||
const name = dev._name || '';
|
||||
const inCh = parseInt(dev.coreaudio_device_input) || 0;
|
||||
const outCh = parseInt(dev.coreaudio_device_output) || 0;
|
||||
if (inputDeviceName && name === inputDeviceName && inCh > 0) {
|
||||
inputDevice = { name, channels: inCh };
|
||||
}
|
||||
if (outputDeviceName && name === outputDeviceName && outCh > 0) {
|
||||
outputDevice = { name, channels: outCh };
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
} catch (_) { /* detection failed, keep defaults */ }
|
||||
}
|
||||
|
||||
return { inputDevice, outputDevice };
|
||||
} catch (error) {
|
||||
return { error: error.message, inputDevice: { name: 'Inconnu', channels: 0 }, outputDevice: { name: 'Inconnu', channels: 0 } };
|
||||
}
|
||||
});
|
||||
|
||||
ipcMain.handle('routing:save', (event, { channelNames }) => {
|
||||
try {
|
||||
const config = readConfig();
|
||||
if (!config.audio) config.audio = {};
|
||||
config.audio.channelNames = channelNames;
|
||||
writeConfig(config);
|
||||
return { success: true };
|
||||
} catch (error) {
|
||||
return { success: false, error: error.message };
|
||||
}
|
||||
});
|
||||
|
||||
ipcMain.handle('config:export', async () => {
|
||||
const configPath = path.join(__dirname, '..', 'server', 'config', 'config.yaml');
|
||||
|
||||
try {
|
||||
const content = fs.readFileSync(configPath, 'utf8');
|
||||
|
||||
const { filePath } = await dialog.showSaveDialog(mainWindow, {
|
||||
title: 'Exporter la configuration',
|
||||
defaultPath: 'config.yaml',
|
||||
filters: [{ name: 'YAML', extensions: ['yaml', 'yml'] }]
|
||||
});
|
||||
|
||||
if (!filePath) return { success: false, cancelled: true };
|
||||
|
||||
fs.writeFileSync(filePath, content, 'utf8');
|
||||
return { success: true, filePath };
|
||||
} catch (error) {
|
||||
return { success: false, error: error.message };
|
||||
}
|
||||
});
|
||||
|
||||
ipcMain.handle('config:import', async () => {
|
||||
const { filePaths } = await dialog.showOpenDialog(mainWindow, {
|
||||
title: 'Importer une configuration',
|
||||
filters: [{ name: 'YAML', extensions: ['yaml', 'yml'] }],
|
||||
properties: ['openFile']
|
||||
});
|
||||
|
||||
if (!filePaths || filePaths.length === 0) return { success: false, cancelled: true };
|
||||
|
||||
try {
|
||||
const content = fs.readFileSync(filePaths[0], 'utf8');
|
||||
const configPath = path.join(__dirname, '..', 'server', 'config', 'config.yaml');
|
||||
|
||||
// Backup de l'ancienne config avant remplacement
|
||||
if (fs.existsSync(configPath)) {
|
||||
fs.copyFileSync(configPath, configPath + '.bak');
|
||||
}
|
||||
|
||||
fs.writeFileSync(configPath, content, 'utf8');
|
||||
return { success: true };
|
||||
} catch (error) {
|
||||
return { success: false, error: error.message };
|
||||
}
|
||||
});
|
||||
|
||||
// Créer fenêtre
|
||||
createWindow();
|
||||
createTray();
|
||||
|
||||
// Vérifier setup automatique (certificats)
|
||||
console.log('🔍 Vérification configuration...');
|
||||
const projectRoot = path.join(__dirname, '..');
|
||||
const certsDir = path.join(projectRoot, 'certs');
|
||||
|
||||
if (!setupHelper.certificatesExist(certsDir)) {
|
||||
console.log('⚠️ Certificats SSL manquants, configuration automatique...\n');
|
||||
|
||||
// Afficher dialog d'information
|
||||
const infoResult = await dialog.showMessageBox(mainWindow, {
|
||||
type: 'info',
|
||||
title: 'Configuration initiale',
|
||||
message: 'Première utilisation de PTT Live',
|
||||
detail: 'Configuration des certificats SSL en cours...\nCela peut prendre 1-2 minutes.\n\nmkcert sera installé automatiquement.',
|
||||
buttons: ['Continuer', 'Annuler']
|
||||
});
|
||||
|
||||
if (infoResult.response === 1) {
|
||||
console.log('⚠️ Configuration annulée par l\'utilisateur');
|
||||
return;
|
||||
}
|
||||
|
||||
// Lancer setup auto
|
||||
const setupResult = await setupHelper.autoSetup(projectRoot);
|
||||
|
||||
if (!setupResult.success) {
|
||||
// Échec du setup automatique
|
||||
await dialog.showMessageBox(mainWindow, {
|
||||
type: 'error',
|
||||
title: 'Configuration échouée',
|
||||
message: 'Impossible de configurer automatiquement les certificats SSL',
|
||||
detail: setupResult.manual
|
||||
? 'Veuillez exécuter manuellement :\n./setup-certificates.sh\n\nOu installer mkcert : https://github.com/FiloSottile/mkcert'
|
||||
: setupResult.error,
|
||||
buttons: ['OK']
|
||||
});
|
||||
|
||||
console.error('❌ Setup automatique échoué');
|
||||
return; // Ne pas démarrer le serveur
|
||||
}
|
||||
|
||||
// Setup réussi
|
||||
await dialog.showMessageBox(mainWindow, {
|
||||
type: 'info',
|
||||
title: 'Configuration terminée',
|
||||
message: 'Certificats SSL configurés avec succès !',
|
||||
detail: `Votre IP réseau : ${setupResult.networkIP}\n\nLe serveur va démarrer...`,
|
||||
buttons: ['OK']
|
||||
});
|
||||
|
||||
console.log('✅ Setup automatique terminé\n');
|
||||
} else {
|
||||
console.log('✅ Certificats présents\n');
|
||||
}
|
||||
|
||||
// NE PAS démarrer automatiquement
|
||||
// L'utilisateur cliquera sur "Démarrer" dans l'interface
|
||||
console.log('✅ Application prête');
|
||||
console.log('💡 Cliquez sur "Démarrer" pour lancer le serveur\n');
|
||||
});
|
||||
|
||||
app.on('window-all-closed', () => {
|
||||
// Ne pas quitter l'app sur macOS (comportement standard)
|
||||
if (process.platform !== 'darwin') {
|
||||
app.quit();
|
||||
}
|
||||
});
|
||||
|
||||
app.on('activate', () => {
|
||||
if (BrowserWindow.getAllWindows().length === 0) {
|
||||
createWindow();
|
||||
}
|
||||
});
|
||||
|
||||
// Cleanup au quit
|
||||
app.on('before-quit', async (event) => {
|
||||
if (serverProcess) {
|
||||
event.preventDefault();
|
||||
console.log('🧹 Cleanup avant fermeture...');
|
||||
await stopServer();
|
||||
app.quit();
|
||||
}
|
||||
});
|
||||
|
||||
// Gestion des erreurs non catchées
|
||||
process.on('uncaughtException', (error) => {
|
||||
console.error('❌ Erreur non catchée:', error);
|
||||
});
|
||||
|
||||
process.on('unhandledRejection', (reason, promise) => {
|
||||
console.error('❌ Promise rejection non gérée:', reason);
|
||||
});
|
||||
@@ -0,0 +1,61 @@
|
||||
{
|
||||
"name": "ptt-live-desktop",
|
||||
"version": "0.3.0",
|
||||
"description": "PTT Live - Desktop Server Application",
|
||||
"main": "main.js",
|
||||
"scripts": {
|
||||
"start": "electron .",
|
||||
"dev": "electron . --dev",
|
||||
"build": "electron-builder",
|
||||
"build:mac": "electron-builder --mac",
|
||||
"build:linux": "electron-builder --linux"
|
||||
},
|
||||
"build": {
|
||||
"appId": "com.pttlive.desktop",
|
||||
"productName": "PTT Live Server",
|
||||
"directories": {
|
||||
"output": "dist"
|
||||
},
|
||||
"files": [
|
||||
"main.js",
|
||||
"preload.js",
|
||||
"ui/**/*",
|
||||
"../server/**/*",
|
||||
"!../server/node_modules",
|
||||
"../server/node_modules/**/*"
|
||||
],
|
||||
"mac": {
|
||||
"category": "public.app-category.utilities",
|
||||
"icon": "assets/icon.icns",
|
||||
"target": [
|
||||
"dmg",
|
||||
"zip"
|
||||
]
|
||||
},
|
||||
"linux": {
|
||||
"category": "AudioVideo",
|
||||
"icon": "assets/icon.png",
|
||||
"target": [
|
||||
"deb",
|
||||
"AppImage"
|
||||
]
|
||||
}
|
||||
},
|
||||
"keywords": [
|
||||
"electron",
|
||||
"webrtc",
|
||||
"intercom",
|
||||
"audio"
|
||||
],
|
||||
"author": "",
|
||||
"license": "MIT",
|
||||
"devDependencies": {
|
||||
"electron": "^28.0.0",
|
||||
"electron-builder": "^24.9.1"
|
||||
},
|
||||
"dependencies": {
|
||||
"electron-store": "^8.1.0",
|
||||
"qrcode": "^1.5.4",
|
||||
"yaml": "^2.9.0"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,78 @@
|
||||
/**
|
||||
* PTT Live Desktop - Preload Script
|
||||
* Bridge sécurisé entre Main Process et Renderer Process
|
||||
*/
|
||||
|
||||
const { contextBridge, ipcRenderer } = require('electron');
|
||||
|
||||
// Même logique que dans main.js : doit rester synchronisé avec SERVER_URL
|
||||
// (127.0.0.1 : le serveur n'écoute qu'en IPv4, voir le commentaire dans main.js)
|
||||
const SERVER_PORT = process.env.PORT || 3000;
|
||||
const ENABLE_HTTPS = process.env.ENABLE_HTTPS !== 'false';
|
||||
const SERVER_URL = `${ENABLE_HTTPS ? 'https' : 'http'}://127.0.0.1:${SERVER_PORT}`;
|
||||
|
||||
// Exposer l'API au renderer de manière sécurisée
|
||||
contextBridge.exposeInMainWorld('electronAPI', {
|
||||
serverUrl: SERVER_URL,
|
||||
|
||||
// Contrôle serveur
|
||||
server: {
|
||||
start: () => ipcRenderer.invoke('server:start'),
|
||||
stop: () => ipcRenderer.invoke('server:stop'),
|
||||
status: () => ipcRenderer.invoke('server:status'),
|
||||
ping: () => ipcRenderer.invoke('server:ping'),
|
||||
|
||||
// Écouter les événements du serveur
|
||||
onStatus: (callback) => {
|
||||
ipcRenderer.on('server:status', (event, data) => callback(data));
|
||||
},
|
||||
onLog: (callback) => {
|
||||
ipcRenderer.on('server:log', (event, data) => callback(data));
|
||||
}
|
||||
},
|
||||
|
||||
// QR Code (généré côté Main Process, pas de dépendance CDN)
|
||||
generateQRCode: (text) => ipcRenderer.invoke('qrcode:generate', text),
|
||||
|
||||
// IP réseau locale (même détection que pour les certificats mkcert)
|
||||
getNetworkIP: () => ipcRenderer.invoke('network:ip'),
|
||||
|
||||
// Export/import configuration YAML via dialog système
|
||||
config: {
|
||||
export: () => ipcRenderer.invoke('config:export'),
|
||||
import: () => ipcRenderer.invoke('config:import')
|
||||
},
|
||||
|
||||
// Groupes : lecture/écriture YAML directe (fonctionne sans serveur)
|
||||
groups: {
|
||||
list: () => ipcRenderer.invoke('groups:list'),
|
||||
create: (data) => ipcRenderer.invoke('groups:create', data),
|
||||
update: (data) => ipcRenderer.invoke('groups:update', data),
|
||||
delete: (data) => ipcRenderer.invoke('groups:delete', data)
|
||||
},
|
||||
|
||||
// Utilisateurs audio serveur : lecture/écriture YAML directe (fonctionne sans serveur)
|
||||
serverAudioUsers: {
|
||||
list: () => ipcRenderer.invoke('server-audio-users:list'),
|
||||
create: (data) => ipcRenderer.invoke('server-audio-users:create', data),
|
||||
update: (data) => ipcRenderer.invoke('server-audio-users:update', data),
|
||||
delete: (data) => ipcRenderer.invoke('server-audio-users:delete', data)
|
||||
},
|
||||
|
||||
// Routing audio : lecture/écriture YAML directe (fonctionne sans serveur)
|
||||
routing: {
|
||||
get: () => ipcRenderer.invoke('routing:get'),
|
||||
save: (data) => ipcRenderer.invoke('routing:save', data)
|
||||
},
|
||||
|
||||
// Découverte canaux physiques de la carte son sélectionnée
|
||||
devices: {
|
||||
getChannels: () => ipcRenderer.invoke('devices:getChannels')
|
||||
},
|
||||
|
||||
// Helpers
|
||||
platform: process.platform,
|
||||
version: process.env.npm_package_version || '0.3.0'
|
||||
});
|
||||
|
||||
console.log('✅ Preload script chargé');
|
||||
@@ -0,0 +1,249 @@
|
||||
/**
|
||||
* PTT Live Desktop - Setup Helper
|
||||
* Automatise l'installation des dépendances et certificats
|
||||
*/
|
||||
|
||||
const { exec } = require('child_process');
|
||||
const { promisify } = require('util');
|
||||
const { existsSync } = require('fs');
|
||||
const { join } = require('path');
|
||||
const os = require('os');
|
||||
|
||||
const execPromise = promisify(exec);
|
||||
|
||||
/**
|
||||
* Vérifie si mkcert est installé
|
||||
*/
|
||||
async function isMkcertInstalled() {
|
||||
try {
|
||||
await execPromise('mkcert -version');
|
||||
return true;
|
||||
} catch (error) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Installe mkcert automatiquement
|
||||
*/
|
||||
async function installMkcert() {
|
||||
const platform = os.platform();
|
||||
|
||||
console.log('📦 Installation de mkcert...');
|
||||
|
||||
try {
|
||||
if (platform === 'darwin') {
|
||||
// macOS - via Homebrew
|
||||
if (await isHomebrewInstalled()) {
|
||||
await execPromise('brew install mkcert nss');
|
||||
console.log('✅ mkcert installé via Homebrew');
|
||||
return true;
|
||||
} else {
|
||||
throw new Error('Homebrew requis sur macOS');
|
||||
}
|
||||
} else if (platform === 'linux') {
|
||||
// Linux - téléchargement direct
|
||||
await execPromise('curl -JLO "https://dl.filippo.io/mkcert/latest?for=linux/amd64"');
|
||||
await execPromise('chmod +x mkcert-v*-linux-amd64');
|
||||
await execPromise('sudo mv mkcert-v*-linux-amd64 /usr/local/bin/mkcert');
|
||||
console.log('✅ mkcert installé');
|
||||
return true;
|
||||
} else {
|
||||
throw new Error(`Plateforme non supportée: ${platform}`);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('❌ Erreur installation mkcert:', error.message);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Vérifie si Homebrew est installé
|
||||
*/
|
||||
async function isHomebrewInstalled() {
|
||||
try {
|
||||
await execPromise('brew --version');
|
||||
return true;
|
||||
} catch (error) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Installe la CA locale
|
||||
*/
|
||||
async function installCA() {
|
||||
try {
|
||||
console.log('🔑 Installation de la Certificate Authority locale...');
|
||||
await execPromise('mkcert -install');
|
||||
console.log('✅ CA locale installée');
|
||||
return true;
|
||||
} catch (error) {
|
||||
console.error('❌ Erreur installation CA:', error.message);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Détecte l'IP réseau locale
|
||||
*/
|
||||
function getNetworkIP() {
|
||||
const interfaces = os.networkInterfaces();
|
||||
|
||||
// Priorité : WiFi > Ethernet
|
||||
const priority = ['en0', 'en1', 'eth0', 'wlan0'];
|
||||
|
||||
for (const name of priority) {
|
||||
const iface = interfaces[name];
|
||||
if (iface) {
|
||||
for (const net of iface) {
|
||||
if (net.family === 'IPv4' && !net.internal) {
|
||||
return net.address;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Fallback : première IP non-interne
|
||||
for (const name of Object.keys(interfaces)) {
|
||||
for (const net of interfaces[name]) {
|
||||
if (net.family === 'IPv4' && !net.internal) {
|
||||
return net.address;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return '192.168.1.100'; // Fallback ultime
|
||||
}
|
||||
|
||||
/**
|
||||
* Génère les certificats SSL
|
||||
*/
|
||||
async function generateCertificates(certsDir) {
|
||||
try {
|
||||
const networkIP = getNetworkIP();
|
||||
const hostname = os.hostname();
|
||||
|
||||
console.log('📜 Génération des certificats...');
|
||||
console.log(` IP réseau : ${networkIP}`);
|
||||
|
||||
// Créer répertoire si nécessaire
|
||||
if (!existsSync(certsDir)) {
|
||||
await execPromise(`mkdir -p "${certsDir}"`);
|
||||
}
|
||||
|
||||
// Générer certificats
|
||||
const cmd = `cd "${certsDir}" && mkcert localhost 127.0.0.1 ::1 "${networkIP}" "*.local" "${hostname}.local"`;
|
||||
await execPromise(cmd);
|
||||
|
||||
// Renommer pour simplifier
|
||||
const files = await execPromise(`ls "${certsDir}"/*.pem`);
|
||||
const fileList = files.stdout.trim().split('\n');
|
||||
|
||||
// Trouver les fichiers générés
|
||||
const certFile = fileList.find(f => !f.includes('-key.pem'));
|
||||
const keyFile = fileList.find(f => f.includes('-key.pem'));
|
||||
|
||||
if (certFile && keyFile) {
|
||||
// Copier avec noms standards
|
||||
await execPromise(`cp "${certFile}" "${join(certsDir, 'localhost.pem')}"`);
|
||||
await execPromise(`cp "${keyFile}" "${join(certsDir, 'localhost-key.pem')}"`);
|
||||
}
|
||||
|
||||
console.log('✅ Certificats générés');
|
||||
return { networkIP, certPath: join(certsDir, 'localhost.pem'), keyPath: join(certsDir, 'localhost-key.pem') };
|
||||
} catch (error) {
|
||||
console.error('❌ Erreur génération certificats:', error.message);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Vérifie si les certificats existent et sont valides
|
||||
*/
|
||||
function certificatesExist(certsDir) {
|
||||
const certPath = join(certsDir, 'localhost.pem');
|
||||
const keyPath = join(certsDir, 'localhost-key.pem');
|
||||
|
||||
return existsSync(certPath) && existsSync(keyPath);
|
||||
}
|
||||
|
||||
/**
|
||||
* Setup complet automatique
|
||||
*/
|
||||
async function autoSetup(projectRoot) {
|
||||
const certsDir = join(projectRoot, 'certs');
|
||||
|
||||
console.log('🚀 Configuration automatique PTT Live...\n');
|
||||
|
||||
// 1. Vérifier certificats existants
|
||||
if (certificatesExist(certsDir)) {
|
||||
console.log('✅ Certificats déjà présents');
|
||||
return { success: true, needsRestart: false };
|
||||
}
|
||||
|
||||
console.log('⚠️ Certificats SSL non trouvés\n');
|
||||
|
||||
// 2. Vérifier mkcert
|
||||
const hasMkcert = await isMkcertInstalled();
|
||||
|
||||
if (!hasMkcert) {
|
||||
console.log('📦 mkcert non installé, installation...\n');
|
||||
|
||||
const installed = await installMkcert();
|
||||
if (!installed) {
|
||||
return {
|
||||
success: false,
|
||||
error: 'Installation mkcert échouée',
|
||||
manual: true,
|
||||
instructions: 'Installez mkcert manuellement : https://github.com/FiloSottile/mkcert'
|
||||
};
|
||||
}
|
||||
} else {
|
||||
console.log('✅ mkcert déjà installé\n');
|
||||
}
|
||||
|
||||
// 3. Installer CA locale
|
||||
const caInstalled = await installCA();
|
||||
if (!caInstalled) {
|
||||
return {
|
||||
success: false,
|
||||
error: 'Installation CA échouée',
|
||||
manual: true
|
||||
};
|
||||
}
|
||||
|
||||
console.log('');
|
||||
|
||||
// 4. Générer certificats
|
||||
const result = await generateCertificates(certsDir);
|
||||
if (!result) {
|
||||
return {
|
||||
success: false,
|
||||
error: 'Génération certificats échouée',
|
||||
manual: true
|
||||
};
|
||||
}
|
||||
|
||||
console.log('\n✅ Configuration terminée !');
|
||||
console.log(` Certificats : ${certsDir}`);
|
||||
console.log(` IP réseau : ${result.networkIP}\n`);
|
||||
|
||||
return {
|
||||
success: true,
|
||||
needsRestart: false,
|
||||
networkIP: result.networkIP,
|
||||
certPath: result.certPath,
|
||||
keyPath: result.keyPath
|
||||
};
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
isMkcertInstalled,
|
||||
installMkcert,
|
||||
installCA,
|
||||
generateCertificates,
|
||||
certificatesExist,
|
||||
getNetworkIP,
|
||||
autoSetup
|
||||
};
|
||||
+1428
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,266 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="fr">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>PTT Live Server</title>
|
||||
<link rel="stylesheet" href="styles.css">
|
||||
</head>
|
||||
<body>
|
||||
<!-- Toast Container -->
|
||||
<div class="toast-container" id="toast-container"></div>
|
||||
|
||||
<div id="app">
|
||||
<!-- Header -->
|
||||
<header class="header">
|
||||
<div class="header-left">
|
||||
<h1>🎙️ PTT Live Server</h1>
|
||||
<span class="version" id="version">v0.3.0</span>
|
||||
</div>
|
||||
<div class="header-right">
|
||||
<div class="server-status">
|
||||
<span class="status-indicator" id="status-indicator">⚪</span>
|
||||
<span id="status-text">Arrêté</span>
|
||||
</div>
|
||||
<button id="btn-start" class="btn btn-primary">Démarrer</button>
|
||||
<button id="btn-stop" class="btn btn-secondary" disabled>Arrêter</button>
|
||||
</div>
|
||||
</header>
|
||||
|
||||
<!-- Main Content -->
|
||||
<main class="main-content">
|
||||
<!-- Sidebar Navigation -->
|
||||
<nav class="sidebar">
|
||||
<button class="nav-item active" data-view="dashboard">
|
||||
📊 Dashboard
|
||||
</button>
|
||||
<button class="nav-item" data-view="config">
|
||||
⚙️ Configuration
|
||||
</button>
|
||||
<button class="nav-item" data-view="groups">
|
||||
👥 Groupes
|
||||
</button>
|
||||
<button class="nav-item" data-view="routing">
|
||||
🔀 Routing
|
||||
</button>
|
||||
<button class="nav-item" data-view="monitoring">
|
||||
📈 Monitoring
|
||||
</button>
|
||||
<button class="nav-item" data-view="logs">
|
||||
📝 Logs
|
||||
</button>
|
||||
</nav>
|
||||
|
||||
<!-- Content Area -->
|
||||
<div class="content">
|
||||
<!-- Dashboard View -->
|
||||
<div id="view-dashboard" class="view active">
|
||||
<h2>Dashboard</h2>
|
||||
|
||||
<!-- Stats Cards -->
|
||||
<div class="stats-grid">
|
||||
<div class="stat-card">
|
||||
<div class="stat-label">Uptime</div>
|
||||
<div class="stat-value" id="stat-uptime">--</div>
|
||||
</div>
|
||||
<div class="stat-card">
|
||||
<div class="stat-label">Utilisateurs</div>
|
||||
<div class="stat-value" id="stat-users">--</div>
|
||||
</div>
|
||||
<div class="stat-card">
|
||||
<div class="stat-label">Groupes actifs</div>
|
||||
<div class="stat-value" id="stat-groups">--</div>
|
||||
</div>
|
||||
<div class="stat-card">
|
||||
<div class="stat-label">Connexions totales</div>
|
||||
<div class="stat-value" id="stat-total-connections">--</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- QR Code Section -->
|
||||
<div class="section">
|
||||
<h3>📱 Connexion rapide clients</h3>
|
||||
<div class="qr-container">
|
||||
<div class="qr-wrapper">
|
||||
<img id="qr-code" width="256" height="256" alt="QR Code connexion" />
|
||||
<div class="qr-placeholder" id="qr-placeholder">
|
||||
<span class="qr-placeholder-icon">📷</span>
|
||||
<span>En attente du démarrage du serveur</span>
|
||||
</div>
|
||||
</div>
|
||||
<div class="qr-info">
|
||||
<p><strong>URL clients :</strong></p>
|
||||
<p class="url-text" id="client-url">--</p>
|
||||
<button class="btn btn-small" id="btn-copy-url">Copier l'URL</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Active Users -->
|
||||
<div class="section">
|
||||
<h3>👤 Utilisateurs connectés</h3>
|
||||
<div id="users-list" class="users-list">
|
||||
<p class="empty-state">Aucun utilisateur connecté</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Configuration View -->
|
||||
<div id="view-config" class="view">
|
||||
<h2>Configuration Audio</h2>
|
||||
|
||||
<div class="section">
|
||||
<h3>🔌 Périphériques Audio</h3>
|
||||
<div class="form-group">
|
||||
<label>Device Input</label>
|
||||
<select id="input-device" class="form-control">
|
||||
<option>Chargement...</option>
|
||||
</select>
|
||||
</div>
|
||||
<div class="form-group">
|
||||
<label>Device Output</label>
|
||||
<select id="output-device" class="form-control">
|
||||
<option>Chargement...</option>
|
||||
</select>
|
||||
</div>
|
||||
<button class="btn btn-primary" id="btn-save-device">Appliquer</button>
|
||||
</div>
|
||||
|
||||
<div class="section">
|
||||
<h3>💾 Sauvegarde de configuration</h3>
|
||||
<div class="config-actions">
|
||||
<button class="btn btn-secondary" id="btn-export-config">Exporter config.yaml</button>
|
||||
<button class="btn btn-secondary" id="btn-import-config">Importer config.yaml</button>
|
||||
</div>
|
||||
<p class="config-note">L'import remplace config.yaml (backup automatique en .bak). Redémarrez le serveur pour appliquer.</p>
|
||||
</div>
|
||||
|
||||
<div class="section">
|
||||
<h3>🎚️ Paramètres Audio</h3>
|
||||
<div class="form-group">
|
||||
<label>Sample Rate</label>
|
||||
<select id="sample-rate" class="form-control">
|
||||
<option value="44100">44.1 kHz</option>
|
||||
<option value="48000" selected>48 kHz</option>
|
||||
<option value="96000">96 kHz</option>
|
||||
</select>
|
||||
</div>
|
||||
<div class="form-group">
|
||||
<label>Bitrate par défaut (kbps)</label>
|
||||
<input type="number" id="default-bitrate" class="form-control" value="96" min="32" max="320" step="32">
|
||||
</div>
|
||||
<div class="form-group">
|
||||
<label>Jitter Buffer (ms)</label>
|
||||
<input type="number" id="jitter-buffer" class="form-control" value="40" min="20" max="100" step="10">
|
||||
</div>
|
||||
<button class="btn btn-primary" id="btn-save-audio">Sauvegarder</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Groups View -->
|
||||
<div id="view-groups" class="view">
|
||||
<h2>Gestion des Groupes</h2>
|
||||
<button class="btn btn-primary" id="btn-add-group">➕ Nouveau groupe</button>
|
||||
<div id="groups-list" class="groups-list">
|
||||
<p class="empty-state">Chargement des groupes...</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Routing View -->
|
||||
<div id="view-routing" class="view">
|
||||
<h2>Routing Audio</h2>
|
||||
|
||||
<!-- Device info -->
|
||||
<div class="section">
|
||||
<div class="routing-device-banner">
|
||||
<div class="routing-device-info" id="routing-device-info">Chargement...</div>
|
||||
<button class="btn btn-small btn-secondary" id="btn-refresh-channels">🔄 Actualiser</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Labels canaux physiques -->
|
||||
<div class="section">
|
||||
<h3>🏷️ Canaux Physiques</h3>
|
||||
<p class="config-note">Labels des canaux de votre carte son. La liste est déterminée par le device sélectionné en <strong>Configuration</strong>.</p>
|
||||
<div class="channel-names-grid">
|
||||
<div class="channel-names-col">
|
||||
<h4>Entrées</h4>
|
||||
<div id="channel-names-inputs" class="channel-names-list">
|
||||
<p class="empty-state">Chargement...</p>
|
||||
</div>
|
||||
</div>
|
||||
<div class="channel-names-col">
|
||||
<h4>Sorties</h4>
|
||||
<div id="channel-names-outputs" class="channel-names-list">
|
||||
<p class="empty-state">Chargement...</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Participants Serveur -->
|
||||
<div class="section">
|
||||
<h3>🎙️ Participants Serveur</h3>
|
||||
<p class="config-note">Participants LiveKit côté serveur — chaque ligne branche des canaux physiques d'E/S sur un groupe.</p>
|
||||
<button class="btn btn-primary btn-small" id="btn-add-server-audio-user">➕ Ajouter</button>
|
||||
<div id="server-audio-users-list" class="sau-list"></div>
|
||||
</div>
|
||||
|
||||
<!-- Actions -->
|
||||
<div class="routing-actions">
|
||||
<button class="btn btn-primary" id="btn-save-routing">Sauvegarder noms de canaux</button>
|
||||
<button class="btn btn-secondary" id="btn-reload-routing">Recharger</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Monitoring View -->
|
||||
<div id="view-monitoring" class="view">
|
||||
<h2>Monitoring Audio</h2>
|
||||
<div class="section">
|
||||
<h3>🔊 VU-Mètres</h3>
|
||||
<div id="vu-meters" class="vu-meters">
|
||||
<p class="empty-state">En attente de données audio...</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Logs View -->
|
||||
<div id="view-logs" class="view">
|
||||
<h2>Logs Serveur</h2>
|
||||
<div class="logs-controls">
|
||||
<button class="btn btn-small" id="btn-clear-logs">Effacer</button>
|
||||
<button class="btn btn-small btn-secondary" id="btn-export-logs">Exporter JSON</button>
|
||||
<select id="log-level-filter" class="form-control form-control-small">
|
||||
<option value="">Tous les niveaux</option>
|
||||
<option value="error">Erreurs</option>
|
||||
<option value="warn">Warnings</option>
|
||||
<option value="info">Info</option>
|
||||
<option value="debug">Debug</option>
|
||||
</select>
|
||||
</div>
|
||||
<div id="logs-container" class="logs-container">
|
||||
<p class="empty-state">Aucun log</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</main>
|
||||
</div>
|
||||
|
||||
<!-- Modal générique -->
|
||||
<div id="modal-overlay" class="modal-overlay hidden">
|
||||
<div class="modal">
|
||||
<div class="modal-header">
|
||||
<h3 id="modal-title"></h3>
|
||||
</div>
|
||||
<div class="modal-body" id="modal-body"></div>
|
||||
<div class="modal-footer">
|
||||
<button class="btn btn-secondary" id="modal-cancel">Annuler</button>
|
||||
<button class="btn btn-primary" id="modal-confirm">Confirmer</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Le QR Code est généré côté Main Process (lib qrcode Node), pas de dépendance CDN -->
|
||||
<script src="app.js"></script>
|
||||
</body>
|
||||
</html>
|
||||
File diff suppressed because it is too large
Load Diff
@@ -529,66 +529,6 @@ router.put('/audio/channels/names', (req, res) => {
|
||||
}
|
||||
});
|
||||
|
||||
/**
|
||||
* GET /admin/audio/routing
|
||||
* Récupère la configuration de routing actuelle
|
||||
* Format: { inputToGroup: { "0": ["production"], "1": ["technique"] }, groupToOutput: { "production": ["0", "1"] } }
|
||||
*/
|
||||
router.get('/audio/routing', (req, res) => {
|
||||
try {
|
||||
const config = configManager.get();
|
||||
const routing = config.audio?.routing || { inputToGroup: {}, groupToOutput: {}, gains: {} };
|
||||
|
||||
res.json({
|
||||
routing
|
||||
});
|
||||
} catch (error) {
|
||||
console.error('Erreur GET /admin/audio/routing:', error);
|
||||
res.status(500).json({ error: 'Failed to load routing' });
|
||||
}
|
||||
});
|
||||
|
||||
/**
|
||||
* POST /audio/routing
|
||||
* Sauvegarde la configuration de routing
|
||||
* Body: { inputToGroup: {...}, groupToOutput: {...}, gains: {...} }
|
||||
*/
|
||||
router.post('/audio/routing', (req, res) => {
|
||||
try {
|
||||
const { inputToGroup, groupToOutput, gains } = req.body;
|
||||
|
||||
const config = configManager.get();
|
||||
|
||||
if (!config.audio.routing) {
|
||||
config.audio.routing = { inputToGroup: {}, groupToOutput: {}, gains: {} };
|
||||
}
|
||||
|
||||
if (inputToGroup !== undefined) {
|
||||
config.audio.routing.inputToGroup = inputToGroup;
|
||||
}
|
||||
|
||||
if (groupToOutput !== undefined) {
|
||||
config.audio.routing.groupToOutput = groupToOutput;
|
||||
}
|
||||
|
||||
if (gains !== undefined) {
|
||||
config.audio.routing.gains = gains;
|
||||
}
|
||||
|
||||
configManager.save(config);
|
||||
|
||||
addLog('info', 'Audio routing updated');
|
||||
|
||||
res.json({
|
||||
message: 'Audio routing updated',
|
||||
routing: config.audio.routing
|
||||
});
|
||||
|
||||
} catch (error) {
|
||||
console.error('Erreur POST /admin/audio/routing:', error);
|
||||
res.status(500).json({ error: 'Failed to update routing' });
|
||||
}
|
||||
});
|
||||
|
||||
/**
|
||||
* POST /admin/audio/device
|
||||
|
||||
+63
-300
@@ -17,8 +17,7 @@ import JACKBackend from './backends/JACKBackend.js';
|
||||
import PipeWireBackend from './backends/PipeWireBackend.js';
|
||||
import OpusCodec, { OpusPresets } from './OpusCodec.js';
|
||||
import JitterBuffer, { JitterBufferPresets } from './JitterBuffer.js';
|
||||
import LiveKitClient from './LiveKitClient.js';
|
||||
import GroupAudioRouter from './GroupAudioRouter.js';
|
||||
import ServerAudioUser from './ServerAudioUser.js';
|
||||
|
||||
export class AudioBridge extends EventEmitter {
|
||||
constructor(options = {}) {
|
||||
@@ -54,8 +53,6 @@ export class AudioBridge extends EventEmitter {
|
||||
this.opusEncoder = null;
|
||||
this.opusDecoder = null;
|
||||
this.jitterBuffer = null;
|
||||
this.liveKitClients = new Map(); // Map<groupName, LiveKitClient> - un client par groupe
|
||||
this.groupAudioRouter = null;
|
||||
|
||||
// État
|
||||
this.isRunning = false;
|
||||
@@ -63,10 +60,9 @@ export class AudioBridge extends EventEmitter {
|
||||
|
||||
// Buffers pour routing multi-canaux
|
||||
this.inputChannelBuffers = new Map(); // Map<channelId, Float32Array>
|
||||
this.groupBuffersFromLiveKit = new Map(); // Map<groupName, Float32Array>
|
||||
|
||||
// Frame accumulators pour LiveKit (240 samples → 960 samples)
|
||||
this.liveKitFrameAccumulators = new Map(); // Map<groupName, { buffer: Float32Array, offset: number }>
|
||||
// Utilisateurs audio gérés côté serveur (participants LiveKit avec I/O physique dédiés)
|
||||
this.serverAudioUsers = new Map(); // Map<name, ServerAudioUser>
|
||||
|
||||
// Pool de buffers pré-alloués pour éviter allocations répétées
|
||||
this.bufferPool = {
|
||||
@@ -114,13 +110,10 @@ export class AudioBridge extends EventEmitter {
|
||||
// 3. Initialisation du jitter buffer
|
||||
this._initJitterBuffer();
|
||||
|
||||
// 4. Initialisation du GroupAudioRouter
|
||||
this._initGroupAudioRouter();
|
||||
// 4. Initialisation des server audio users
|
||||
await this._initServerAudioUsers();
|
||||
|
||||
// 5. Connexion à LiveKit
|
||||
await this._initLiveKit();
|
||||
|
||||
// 6. Démarrage du routing audio
|
||||
// 5. Démarrage du routing audio
|
||||
await this._startAudioRouting();
|
||||
|
||||
this.isRunning = true;
|
||||
@@ -301,329 +294,105 @@ export class AudioBridge extends EventEmitter {
|
||||
}
|
||||
|
||||
/**
|
||||
* Initialise le GroupAudioRouter pour le routing multi-canaux
|
||||
* Initialise les utilisateurs audio serveur (participants LiveKit avec I/O physique)
|
||||
* @private
|
||||
*/
|
||||
_initGroupAudioRouter() {
|
||||
this.groupAudioRouter = new GroupAudioRouter({
|
||||
sampleRate: this.options.sampleRate,
|
||||
frameSize: this.options.frameSize,
|
||||
maxInputChannels: this.options.maxInputChannels || 32,
|
||||
maxOutputChannels: this.options.maxOutputChannels || 32,
|
||||
groups: this.options.groups || []
|
||||
});
|
||||
async _initServerAudioUsers() {
|
||||
const users = this.options.serverAudioUsers;
|
||||
if (!users || users.length === 0) return;
|
||||
|
||||
// Charger la configuration de routing depuis les options
|
||||
if (this.options.routing) {
|
||||
this.groupAudioRouter.configure(this.options.routing);
|
||||
}
|
||||
console.log(`🎤 Initialisation ${users.length} server audio user(s)...`);
|
||||
|
||||
// Events du router
|
||||
this.groupAudioRouter.on('configured', (stats) => {
|
||||
console.log(`✓ GroupAudioRouter configuré : ${stats.routesActive} routes`);
|
||||
});
|
||||
|
||||
console.log('✓ GroupAudioRouter initialisé');
|
||||
}
|
||||
|
||||
/**
|
||||
* Initialise les connexions LiveKit (une par groupe)
|
||||
* @private
|
||||
*/
|
||||
async _initLiveKit() {
|
||||
if (!this.options.liveKitTokens || !Array.isArray(this.options.liveKitTokens)) {
|
||||
throw new Error('liveKitTokens requis (tableau d\'objets { groupName, groupId, token })');
|
||||
}
|
||||
|
||||
console.log(`🔌 Initialisation ${this.options.liveKitTokens.length} connexions LiveKit (une par groupe)...`);
|
||||
|
||||
// Créer un LiveKitClient pour chaque groupe
|
||||
for (const { groupName, groupId, token } of this.options.liveKitTokens) {
|
||||
const roomName = groupId; // La room porte le nom du groupId (slugifié)
|
||||
|
||||
const client = new LiveKitClient({
|
||||
url: this.options.liveKitUrl,
|
||||
token,
|
||||
roomName,
|
||||
participantName: `AudioBridge-${groupId}`,
|
||||
for (const userConfig of users) {
|
||||
const user = new ServerAudioUser({
|
||||
name: userConfig.name,
|
||||
groupId: userConfig.groupId,
|
||||
inputChannel: userConfig.inputChannel,
|
||||
outputChannel: userConfig.outputChannel,
|
||||
publish: userConfig.publish !== false,
|
||||
liveKitUrl: this.options.liveKitUrl,
|
||||
token: userConfig.token,
|
||||
sampleRate: this.options.sampleRate,
|
||||
channels: this.options.channels,
|
||||
audioBitrate: this.opusEncoder.options.bitrate
|
||||
frameSize: this.options.frameSize
|
||||
});
|
||||
|
||||
// Events LiveKit pour ce groupe
|
||||
client.on('connected', () => {
|
||||
console.log(`✓ LiveKit connecté pour groupe "${groupName}" (room: ${roomName})`);
|
||||
// Quand une frame de mix est prête, l'envoyer vers le canal physique de sortie
|
||||
const outputCh = userConfig.outputChannel;
|
||||
user.on('outputReady', (mixBuffer) => {
|
||||
if (!this.audioBackend) return;
|
||||
const numChannels = this.options.channels || 1;
|
||||
const frameSize = this.options.frameSize;
|
||||
|
||||
if (numChannels <= 1) {
|
||||
const pcmBuffer = this._float32ToBuffer(mixBuffer);
|
||||
this.audioBackend.queueAudio(pcmBuffer);
|
||||
} else {
|
||||
// Construire un buffer multi-canaux avec l'audio du user sur son canal de sortie
|
||||
const interleaved = new Float32Array(frameSize * numChannels);
|
||||
for (let i = 0; i < frameSize; i++) {
|
||||
interleaved[i * numChannels + outputCh] = mixBuffer[i];
|
||||
}
|
||||
const pcmBuffer = this._float32ToBuffer(interleaved);
|
||||
this.audioBackend.queueAudio(pcmBuffer);
|
||||
}
|
||||
});
|
||||
|
||||
client.on('disconnected', (data) => {
|
||||
const reason = data?.reason || 'unknown';
|
||||
console.warn(`⚠️ LiveKit déconnecté pour groupe "${groupName}":`, reason);
|
||||
this.stats.errors.network++;
|
||||
});
|
||||
|
||||
client.on('reconnecting', () => {
|
||||
console.log(`🔄 LiveKit reconnexion pour groupe "${groupName}"...`);
|
||||
});
|
||||
|
||||
client.on('audioTrackSubscribed', ({ track, participant }) => {
|
||||
console.log(`🎵 Nouveau track audio dans groupe "${groupName}": ${participant.identity}`);
|
||||
});
|
||||
|
||||
// Réception audio depuis les clients LiveKit de ce groupe
|
||||
client.on('audioData', ({ participantName, pcmData, sampleRate, channels }) => {
|
||||
// Router vers le bon groupe
|
||||
this.emit('groupAudioIn', { groupName: groupId, pcmBuffer: pcmData });
|
||||
});
|
||||
|
||||
// Connexion
|
||||
await client.connect();
|
||||
|
||||
// Stocker le client par groupId
|
||||
this.liveKitClients.set(groupId, client);
|
||||
await user.start();
|
||||
this.serverAudioUsers.set(userConfig.name, user);
|
||||
const modeStr = userConfig.publish !== false
|
||||
? `canal ${userConfig.inputChannel} → sortie canal ${userConfig.outputChannel ?? 'aucune'}`
|
||||
: `écoute seule → sortie canal ${userConfig.outputChannel ?? 'aucune'}`;
|
||||
console.log(`✓ Server audio user "${userConfig.name}" démarré (${modeStr}, room: ${userConfig.groupId})`);
|
||||
}
|
||||
|
||||
console.log(`✓ ${this.liveKitClients.size} connexions LiveKit établies`);
|
||||
console.log(`✓ ${this.serverAudioUsers.size} server audio user(s) initialisés`);
|
||||
}
|
||||
|
||||
/**
|
||||
* Démarre le routing audio bidirectionnel complet
|
||||
* Démarre le routing audio : capture physique → server audio users
|
||||
* @private
|
||||
*/
|
||||
async _startAudioRouting() {
|
||||
console.log('🔄 Démarrage routing audio bidirectionnel...');
|
||||
console.log('🔄 Démarrage routing audio...');
|
||||
|
||||
// ===== FLUX 1 : CAPTURE (Carte Son → Groupes → LiveKit → Clients) =====
|
||||
this.audioBackend.on('audioData', (pcmData) => {
|
||||
try {
|
||||
// Convertir PCM Buffer → Float32Array (pour GroupAudioRouter)
|
||||
const float32Data = this._bufferToFloat32(pcmData);
|
||||
|
||||
// Séparer les canaux si audio multi-canaux (entrelacé)
|
||||
const numChannels = this.options.channels || 1;
|
||||
|
||||
if (numChannels === 1) {
|
||||
// Mono : un seul canal
|
||||
const channelId = this.options.inputDeviceChannel || 0;
|
||||
this.inputChannelBuffers.set(channelId, float32Data);
|
||||
this.inputChannelBuffers.set(0, float32Data);
|
||||
} else {
|
||||
// Multi-canaux : dé-entrelacer les samples
|
||||
// Format entrelacé : [L0, R0, L1, R1, ...] → [L0, L1, ...] et [R0, R1, ...]
|
||||
const samplesPerChannel = float32Data.length / numChannels;
|
||||
|
||||
for (let ch = 0; ch < numChannels; ch++) {
|
||||
const channelBuffer = new Float32Array(samplesPerChannel);
|
||||
|
||||
for (let i = 0; i < samplesPerChannel; i++) {
|
||||
channelBuffer[i] = float32Data[i * numChannels + ch];
|
||||
}
|
||||
|
||||
// Mapper canal hardware → canal logique (peut être configuré)
|
||||
const logicalChannelId = this.options.channelMapping?.[ch] ?? ch;
|
||||
this.inputChannelBuffers.set(logicalChannelId, channelBuffer);
|
||||
this.inputChannelBuffers.set(ch, channelBuffer);
|
||||
}
|
||||
}
|
||||
|
||||
// ÉTAPE 1 : Inputs physiques → Groupes (via GroupAudioRouter)
|
||||
const groupBuffers = this.groupAudioRouter.processInputsToGroups(
|
||||
this.inputChannelBuffers
|
||||
);
|
||||
|
||||
if (this.stats.framesCapture % 100 === 0) {
|
||||
// Détecter si l'audio est du silence (toutes les samples < 0.001)
|
||||
let totalEnergy = 0;
|
||||
this.inputChannelBuffers.forEach((buffer) => {
|
||||
for (let i = 0; i < buffer.length; i++) {
|
||||
totalEnergy += Math.abs(buffer[i]);
|
||||
}
|
||||
});
|
||||
const avgEnergy = totalEnergy / (this.inputChannelBuffers.size * (this.options.frameSize || 960));
|
||||
console.log(`[AudioBridge] Frame ${this.stats.framesCapture}: ${this.inputChannelBuffers.size} inputs → ${groupBuffers.size} groupes | Énergie audio: ${avgEnergy.toFixed(6)}`);
|
||||
}
|
||||
|
||||
// ÉTAPE 2 : Pour chaque groupe, envoyer vers le LiveKitClient correspondant
|
||||
groupBuffers.forEach((groupBuffer, groupName) => {
|
||||
// Les groupes sont MONO (Float32Array de N samples)
|
||||
// Mais la config globale peut être STÉRÉO (channels=2)
|
||||
// → Adapter selon la configuration
|
||||
|
||||
let pcmBuffer;
|
||||
const configChannels = this.options.channels || 1;
|
||||
|
||||
if (configChannels === 1) {
|
||||
// Config MONO : envoyer directement
|
||||
pcmBuffer = this._float32ToBuffer(groupBuffer);
|
||||
} else if (configChannels === 2) {
|
||||
// Config STÉRÉO : dupliquer le canal mono
|
||||
const samplesPerChannel = groupBuffer.length;
|
||||
const stereoBuffer = new Float32Array(samplesPerChannel * 2);
|
||||
|
||||
// Entrelacer : [M0, M1, M2, ...] → [M0, M0, M1, M1, M2, M2, ...]
|
||||
for (let i = 0; i < samplesPerChannel; i++) {
|
||||
stereoBuffer[i * 2] = groupBuffer[i]; // Canal gauche
|
||||
stereoBuffer[i * 2 + 1] = groupBuffer[i]; // Canal droit (dupliqué)
|
||||
}
|
||||
|
||||
pcmBuffer = this._float32ToBuffer(stereoBuffer);
|
||||
} else {
|
||||
console.error(`❌ Nombre de canaux non supporté: ${configChannels}`);
|
||||
return;
|
||||
}
|
||||
|
||||
// Récupérer le client LiveKit pour ce groupe
|
||||
const client = this.liveKitClients.get(groupName);
|
||||
|
||||
// Envoi vers LiveKit via sendAudioData (prend du PCM 16-bit)
|
||||
// Note: LiveKit gère lui-même l'encodage Opus en interne
|
||||
if (client && client.isConnected) {
|
||||
client.sendAudioData(pcmBuffer);
|
||||
if (this.stats.framesCapture % 100 === 0) {
|
||||
const channelLabel = configChannels === 1 ? 'mono' : `${configChannels}ch`;
|
||||
console.log(`[AudioBridge] → LiveKit groupe "${groupName}": ${pcmBuffer.length} bytes (${channelLabel})`);
|
||||
}
|
||||
} else {
|
||||
if (this.stats.framesCapture % 100 === 0) {
|
||||
console.log(`[AudioBridge] ⚠️ LiveKit non connecté pour groupe "${groupName}", audio non envoyé`);
|
||||
}
|
||||
}
|
||||
|
||||
// Émettre aussi pour monitoring/debug
|
||||
this.emit('groupAudioOut', { groupName, pcmBuffer });
|
||||
});
|
||||
|
||||
// ÉTAPE 3 : Loopback local - Groupes → Outputs physiques (sans passer par LiveKit)
|
||||
const outputBuffers = this.groupAudioRouter.processGroupsToOutputs(groupBuffers);
|
||||
|
||||
if (this.stats.framesCapture % 100 === 0) {
|
||||
console.log(`[AudioBridge] Loopback local: ${groupBuffers.size} groupes → ${outputBuffers.size} outputs`);
|
||||
}
|
||||
|
||||
// ÉTAPE 4 : Envoyer chaque output à la carte son
|
||||
const numOutputChannels = this.options.channels || 1;
|
||||
|
||||
if (numOutputChannels === 1) {
|
||||
// Mono : un seul output
|
||||
if (outputBuffers.size > 0) {
|
||||
const [firstChannelId, outputBuffer] = outputBuffers.entries().next().value;
|
||||
const pcmBuffer = this._float32ToBuffer(outputBuffer);
|
||||
this.audioBackend.queueAudio(pcmBuffer);
|
||||
|
||||
if (this.stats.framesCapture % 100 === 0) {
|
||||
console.log(`[AudioBridge] → Output mono (canal ${firstChannelId}): ${pcmBuffer.length} bytes`);
|
||||
}
|
||||
}
|
||||
} else {
|
||||
// Multi-canaux : entrelacer les samples
|
||||
// Récupérer les buffers dans l'ordre des canaux hardware
|
||||
const channelBuffers = [];
|
||||
const samplesPerChannel = this.options.frameSize;
|
||||
|
||||
for (let ch = 0; ch < numOutputChannels; ch++) {
|
||||
const logicalChannelId = this.options.channelMapping?.[ch] ?? ch;
|
||||
const buffer = outputBuffers.get(logicalChannelId);
|
||||
|
||||
if (buffer && buffer.length === samplesPerChannel) {
|
||||
channelBuffers.push(buffer);
|
||||
} else {
|
||||
// Canal absent ou taille incorrecte : silence
|
||||
channelBuffers.push(new Float32Array(samplesPerChannel));
|
||||
}
|
||||
}
|
||||
|
||||
// Entrelacer : [L0, L1, ...] et [R0, R1, ...] → [L0, R0, L1, R1, ...]
|
||||
const interleavedBuffer = new Float32Array(samplesPerChannel * numOutputChannels);
|
||||
|
||||
for (let i = 0; i < samplesPerChannel; i++) {
|
||||
for (let ch = 0; ch < numOutputChannels; ch++) {
|
||||
interleavedBuffer[i * numOutputChannels + ch] = channelBuffers[ch][i];
|
||||
}
|
||||
}
|
||||
|
||||
const pcmBuffer = this._float32ToBuffer(interleavedBuffer);
|
||||
this.audioBackend.queueAudio(pcmBuffer);
|
||||
|
||||
if (this.stats.framesCapture % 100 === 0) {
|
||||
console.log(`[AudioBridge] → Output multi-canaux (${numOutputChannels}ch): ${pcmBuffer.length} bytes`);
|
||||
// Alimenter chaque server audio user avec son canal d'entrée
|
||||
for (const [, user] of this.serverAudioUsers) {
|
||||
const channelData = this.inputChannelBuffers.get(user.inputChannel);
|
||||
if (channelData) {
|
||||
user.sendAudio(channelData);
|
||||
}
|
||||
}
|
||||
|
||||
this.stats.framesCapture++;
|
||||
this.stats.framesPlayback++;
|
||||
} catch (error) {
|
||||
console.error('Erreur routing capture:', error);
|
||||
this.stats.errors.capture++;
|
||||
}
|
||||
});
|
||||
|
||||
// ===== FLUX 2 : LECTURE (Clients → LiveKit → Groupes → Carte Son) =====
|
||||
|
||||
// Écouter l'audio entrant de LiveKit (sera connecté par LiveKitServerBridge)
|
||||
this.on('groupAudioIn', ({ groupName, pcmBuffer }) => {
|
||||
try {
|
||||
// Convertir PCM Buffer → Float32Array
|
||||
const float32Data = this._bufferToFloat32(pcmBuffer);
|
||||
const samplesReceived = float32Data.length;
|
||||
|
||||
// Initialiser l'accumulateur pour ce groupe si nécessaire
|
||||
if (!this.liveKitFrameAccumulators.has(groupName)) {
|
||||
this.liveKitFrameAccumulators.set(groupName, {
|
||||
buffer: new Float32Array(960), // Frame size attendu par GroupRouter
|
||||
offset: 0
|
||||
});
|
||||
}
|
||||
|
||||
const accumulator = this.liveKitFrameAccumulators.get(groupName);
|
||||
|
||||
// Vérifier que le buffer ne débordera pas
|
||||
const availableSpace = 960 - accumulator.offset;
|
||||
const samplesToCopy = Math.min(samplesReceived, availableSpace);
|
||||
|
||||
// Copier les samples dans l'accumulateur
|
||||
if (samplesToCopy > 0) {
|
||||
accumulator.buffer.set(float32Data.subarray(0, samplesToCopy), accumulator.offset);
|
||||
accumulator.offset += samplesToCopy;
|
||||
}
|
||||
|
||||
// Si on a accumulé assez de samples (960), router vers les outputs
|
||||
if (accumulator.offset >= 960) {
|
||||
// Vérifier que le backend est toujours actif (évite crash pendant shutdown)
|
||||
if (!this.audioBackend) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Stocker le buffer complet pour le routing
|
||||
this.groupBuffersFromLiveKit.set(groupName, accumulator.buffer);
|
||||
|
||||
// ÉTAPE 3 : Groupes → Outputs physiques (via GroupAudioRouter)
|
||||
const outputBuffers = this.groupAudioRouter.processGroupsToOutputs(
|
||||
this.groupBuffersFromLiveKit
|
||||
);
|
||||
|
||||
// ÉTAPE 4 : Envoyer chaque output à la carte son
|
||||
outputBuffers.forEach((outputBuffer, channelId) => {
|
||||
const pcmBuffer = this._float32ToBuffer(outputBuffer);
|
||||
this.audioBackend.queueAudio(pcmBuffer);
|
||||
});
|
||||
|
||||
// Réinitialiser l'accumulateur
|
||||
accumulator.offset = 0;
|
||||
accumulator.buffer.fill(0);
|
||||
|
||||
this.stats.framesPlayback++;
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Erreur routing lecture:', error);
|
||||
this.stats.errors.playback++;
|
||||
}
|
||||
});
|
||||
|
||||
// Démarrage des streams audio
|
||||
await this.audioBackend.startCapture();
|
||||
await this.audioBackend.startPlayback();
|
||||
|
||||
console.log('✓ Routing audio bidirectionnel actif');
|
||||
console.log(' → Carte Son → GroupRouter → LiveKit → Clients');
|
||||
console.log(' ← Carte Son ← GroupRouter ← LiveKit ← Clients');
|
||||
console.log('✓ Routing audio actif');
|
||||
console.log(' → Carte Son → Server Audio Users → LiveKit → Clients');
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -753,17 +522,12 @@ export class AudioBridge extends EventEmitter {
|
||||
this.audioBackend = null;
|
||||
}
|
||||
|
||||
// Déconnecter tous les clients LiveKit
|
||||
for (const [groupName, client] of this.liveKitClients.entries()) {
|
||||
console.log(`🔌 Déconnexion LiveKit groupe "${groupName}"...`);
|
||||
await client.destroy();
|
||||
}
|
||||
this.liveKitClients.clear();
|
||||
|
||||
if (this.groupAudioRouter) {
|
||||
this.groupAudioRouter.destroy();
|
||||
this.groupAudioRouter = null;
|
||||
// Arrêter les server audio users
|
||||
for (const [name, user] of this.serverAudioUsers.entries()) {
|
||||
console.log(`🔌 Arrêt server audio user "${name}"...`);
|
||||
await user.stop();
|
||||
}
|
||||
this.serverAudioUsers.clear();
|
||||
|
||||
if (this.jitterBuffer) {
|
||||
this.jitterBuffer.destroy();
|
||||
@@ -782,7 +546,6 @@ export class AudioBridge extends EventEmitter {
|
||||
|
||||
// Nettoyer les buffers
|
||||
this.inputChannelBuffers.clear();
|
||||
this.groupBuffersFromLiveKit.clear();
|
||||
|
||||
// Nettoyer le pool de buffers
|
||||
this.bufferPool.float32 = [];
|
||||
|
||||
@@ -34,15 +34,12 @@ class AudioBridgeManager extends EventEmitter {
|
||||
const config = configManager.get();
|
||||
console.log('🎵 Démarrage AudioBridge avec configuration:', config.audio);
|
||||
|
||||
// Générer un token JWT par groupe
|
||||
const liveKitTokens = [];
|
||||
|
||||
// Fonction pour slugifier le nom (identique à admin.js)
|
||||
const slugify = (text) => {
|
||||
return text
|
||||
.toString()
|
||||
.normalize('NFD')
|
||||
.replace(/[\u0300-\u036f]/g, '')
|
||||
.replace(/[̀-ͯ]/g, '')
|
||||
.toLowerCase()
|
||||
.trim()
|
||||
.replace(/\s+/g, '-')
|
||||
@@ -50,43 +47,51 @@ class AudioBridgeManager extends EventEmitter {
|
||||
.replace(/--+/g, '-');
|
||||
};
|
||||
|
||||
for (const group of config.groups || []) {
|
||||
const groupId = slugify(group.name);
|
||||
const groupName = group.name;
|
||||
// Générer un token JWT par server audio user
|
||||
const serverAudioUsers = [];
|
||||
|
||||
for (const user of config.server_audio_users || []) {
|
||||
const groupId = slugify(user.group);
|
||||
|
||||
const token = new AccessToken(
|
||||
config.server?.livekit?.apiKey || 'devkey',
|
||||
config.server?.livekit?.apiSecret || 'secret',
|
||||
{
|
||||
identity: `AudioBridge-${groupId}`,
|
||||
name: `Audio Bridge - ${groupName}`,
|
||||
identity: `server-${user.name}`,
|
||||
name: `Server Audio - ${user.name}`,
|
||||
metadata: JSON.stringify({
|
||||
role: 'bridge',
|
||||
group: groupId,
|
||||
capabilities: ['audio-routing', 'monitoring']
|
||||
role: 'server-audio-user',
|
||||
group: groupId
|
||||
})
|
||||
}
|
||||
);
|
||||
|
||||
// Permissions complètes pour ce groupe
|
||||
const rawInputChannel = user.input_channel ?? user.inputChannel ?? null;
|
||||
const inputChannel = rawInputChannel !== null && rawInputChannel !== undefined ? rawInputChannel : null;
|
||||
const publish = inputChannel !== null;
|
||||
|
||||
token.addGrant({
|
||||
room: groupId, // Chaque groupe a sa propre room
|
||||
room: groupId,
|
||||
roomJoin: true,
|
||||
canPublish: true,
|
||||
canPublish: publish,
|
||||
canSubscribe: true,
|
||||
canPublishData: true
|
||||
});
|
||||
|
||||
const jwt = await token.toJwt();
|
||||
liveKitTokens.push({ groupName, groupId, token: jwt });
|
||||
|
||||
console.log(`✓ Token JWT généré pour groupe "${groupName}" (room: ${groupId})`);
|
||||
}
|
||||
const outputChannel = user.output_channel ?? user.outputChannel;
|
||||
|
||||
if (liveKitTokens.length === 0) {
|
||||
console.warn('⚠️ Aucun groupe configuré, AudioBridge ne pourra pas démarrer');
|
||||
this.isRunning = false;
|
||||
return;
|
||||
serverAudioUsers.push({
|
||||
name: user.name,
|
||||
groupId,
|
||||
inputChannel,
|
||||
outputChannel: outputChannel !== null && outputChannel !== undefined ? outputChannel : null,
|
||||
publish,
|
||||
token: jwt
|
||||
});
|
||||
|
||||
console.log(`✓ Token JWT généré pour server audio user "${user.name}" (room: ${groupId})`);
|
||||
}
|
||||
|
||||
// Import dynamique du AudioBridge
|
||||
@@ -120,15 +125,11 @@ class AudioBridgeManager extends EventEmitter {
|
||||
// Créer l'instance avec la config
|
||||
this.bridge = new AudioBridge({
|
||||
...audioConfig,
|
||||
// Options LiveKit (multi-rooms)
|
||||
liveKitUrl,
|
||||
liveKitTokens, // Tableau de { groupName, groupId, token }
|
||||
// Options de routing
|
||||
routing: config.audio?.routing || {},
|
||||
serverAudioUsers,
|
||||
groups: config.groups || [],
|
||||
maxInputChannels: 32,
|
||||
maxOutputChannels: 32,
|
||||
// Device IDs extraits
|
||||
inputDeviceId,
|
||||
outputDeviceId
|
||||
});
|
||||
|
||||
@@ -1,417 +0,0 @@
|
||||
/**
|
||||
* GroupAudioRouter.js
|
||||
* Gestion du routing audio multi-canaux entre entrées physiques, groupes LiveKit et sorties physiques
|
||||
*
|
||||
* Architecture :
|
||||
* - Mix de plusieurs canaux physiques vers un groupe (avec gains individuels)
|
||||
* - Distribution d'un groupe vers plusieurs canaux physiques (avec gains individuels)
|
||||
* - Support canaux partagés (mixage additif)
|
||||
* - Gestion gains par route (-120dB à +6dB)
|
||||
*/
|
||||
|
||||
import { EventEmitter } from 'events';
|
||||
import { getLogger } from '../utils/Logger.js';
|
||||
|
||||
const logger = getLogger('Routing');
|
||||
|
||||
/**
|
||||
* Représente une route audio avec gain
|
||||
*/
|
||||
class AudioRoute {
|
||||
constructor(source, destination, gain = 0.0) {
|
||||
this.source = source; // Numéro de canal ou nom de groupe
|
||||
this.destination = destination; // Nom de groupe ou numéro de canal
|
||||
this.gain = gain; // Gain en dB (-120 à +6)
|
||||
this.linearGain = this._dbToLinear(gain);
|
||||
}
|
||||
|
||||
/**
|
||||
* Met à jour le gain en dB
|
||||
*/
|
||||
setGain(gainDb) {
|
||||
this.gain = Math.max(-120, Math.min(6, gainDb));
|
||||
this.linearGain = this._dbToLinear(this.gain);
|
||||
}
|
||||
|
||||
/**
|
||||
* Convertit dB en gain linéaire
|
||||
*/
|
||||
_dbToLinear(db) {
|
||||
if (db <= -120) return 0.0;
|
||||
return Math.pow(10, db / 20);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Router audio principal
|
||||
*/
|
||||
export class GroupAudioRouter extends EventEmitter {
|
||||
constructor(config = {}) {
|
||||
super();
|
||||
|
||||
this.config = {
|
||||
sampleRate: config.sampleRate || 48000,
|
||||
frameSize: config.frameSize || 960, // 20ms à 48kHz
|
||||
maxInputChannels: config.maxInputChannels || 32,
|
||||
maxOutputChannels: config.maxOutputChannels || 32,
|
||||
groups: config.groups || []
|
||||
};
|
||||
|
||||
// Routes : input -> group
|
||||
this.inputToGroupRoutes = new Map(); // Map<string, AudioRoute[]>
|
||||
// Routes : group -> output
|
||||
this.groupToOutputRoutes = new Map(); // Map<string, AudioRoute[]>
|
||||
|
||||
// Buffers audio
|
||||
this.inputBuffers = new Map(); // Map<number, Float32Array>
|
||||
this.groupBuffers = new Map(); // Map<string, Float32Array>
|
||||
this.outputBuffers = new Map(); // Map<number, Float32Array>
|
||||
|
||||
// Statistiques
|
||||
this.stats = {
|
||||
framesProcessed: 0,
|
||||
clippingEvents: 0,
|
||||
routesActive: 0
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Configure le routing depuis la config YAML
|
||||
*/
|
||||
configure(routingConfig) {
|
||||
logger.info('Configuration du routing audio...');
|
||||
logger.debug(' Groupes disponibles:', this.config.groups.map(g => `${g.name || g} (id: ${g.id || g})`).join(', '));
|
||||
logger.debug(' inputToGroup:', JSON.stringify(routingConfig.inputToGroup || {}));
|
||||
logger.debug(' groupToOutput:', JSON.stringify(routingConfig.groupToOutput || {}));
|
||||
|
||||
// Réinitialise les routes
|
||||
this.inputToGroupRoutes.clear();
|
||||
this.groupToOutputRoutes.clear();
|
||||
|
||||
// Configure input -> group
|
||||
if (routingConfig.inputToGroup) {
|
||||
Object.entries(routingConfig.inputToGroup).forEach(([channelId, groups]) => {
|
||||
const channel = parseInt(channelId);
|
||||
|
||||
groups.forEach(groupName => {
|
||||
this.addInputToGroupRoute(channel, groupName, this._getGain(routingConfig.gains, `in_${channel}_${groupName}`));
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
// Configure group -> output
|
||||
if (routingConfig.groupToOutput) {
|
||||
Object.entries(routingConfig.groupToOutput).forEach(([groupName, channels]) => {
|
||||
channels.forEach(channelId => {
|
||||
const channel = parseInt(channelId);
|
||||
this.addGroupToOutputRoute(groupName, channel, this._getGain(routingConfig.gains, `${groupName}_out_${channel}`));
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
this._updateStatsActiveRoutes();
|
||||
logger.success(`Routing configuré : ${this.stats.routesActive} routes actives`);
|
||||
this.emit('configured', this.stats);
|
||||
}
|
||||
|
||||
/**
|
||||
* Récupère le gain depuis la config
|
||||
*/
|
||||
_getGain(gainsConfig, routeKey) {
|
||||
return gainsConfig && gainsConfig[routeKey] ? gainsConfig[routeKey] : 0.0;
|
||||
}
|
||||
|
||||
/**
|
||||
* Ajoute une route input -> group
|
||||
*/
|
||||
addInputToGroupRoute(inputChannel, groupName, gainDb = 0.0) {
|
||||
const key = `in_${inputChannel}`;
|
||||
|
||||
if (!this.inputToGroupRoutes.has(key)) {
|
||||
this.inputToGroupRoutes.set(key, []);
|
||||
}
|
||||
|
||||
const route = new AudioRoute(inputChannel, groupName, gainDb);
|
||||
this.inputToGroupRoutes.get(key).push(route);
|
||||
|
||||
logger.info(`Input ${inputChannel} → Group "${groupName}" (${gainDb}dB)`);
|
||||
this._updateStatsActiveRoutes();
|
||||
}
|
||||
|
||||
/**
|
||||
* Ajoute une route group -> output
|
||||
*/
|
||||
addGroupToOutputRoute(groupName, outputChannel, gainDb = 0.0) {
|
||||
const key = groupName;
|
||||
|
||||
if (!this.groupToOutputRoutes.has(key)) {
|
||||
this.groupToOutputRoutes.set(key, []);
|
||||
}
|
||||
|
||||
const route = new AudioRoute(groupName, outputChannel, gainDb);
|
||||
this.groupToOutputRoutes.get(key).push(route);
|
||||
|
||||
logger.info(`Group "${groupName}" → Output ${outputChannel} (${gainDb}dB)`);
|
||||
this._updateStatsActiveRoutes();
|
||||
}
|
||||
|
||||
/**
|
||||
* Supprime toutes les routes d'une entrée
|
||||
*/
|
||||
removeInputRoutes(inputChannel) {
|
||||
this.inputToGroupRoutes.delete(`in_${inputChannel}`);
|
||||
this._updateStatsActiveRoutes();
|
||||
}
|
||||
|
||||
/**
|
||||
* Supprime toutes les routes d'un groupe vers les sorties
|
||||
*/
|
||||
removeGroupOutputRoutes(groupName) {
|
||||
this.groupToOutputRoutes.delete(groupName);
|
||||
this._updateStatsActiveRoutes();
|
||||
}
|
||||
|
||||
/**
|
||||
* Met à jour le gain d'une route spécifique
|
||||
*/
|
||||
setRouteGain(source, destination, gainDb) {
|
||||
// Cherche dans input -> group
|
||||
const inputKey = typeof source === 'number' ? `in_${source}` : null;
|
||||
if (inputKey && this.inputToGroupRoutes.has(inputKey)) {
|
||||
const routes = this.inputToGroupRoutes.get(inputKey);
|
||||
const route = routes.find(r => r.destination === destination);
|
||||
if (route) {
|
||||
route.setGain(gainDb);
|
||||
console.log(`Gain modifié : Input ${source} -> Group "${destination}" = ${gainDb}dB`);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
// Cherche dans group -> output
|
||||
if (typeof source === 'string' && this.groupToOutputRoutes.has(source)) {
|
||||
const routes = this.groupToOutputRoutes.get(source);
|
||||
const route = routes.find(r => r.destination === destination);
|
||||
if (route) {
|
||||
route.setGain(gainDb);
|
||||
console.log(`Gain modifié : Group "${source}" -> Output ${destination} = ${gainDb}dB`);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* ÉTAPE 1 : Traite les entrées audio physiques vers les buffers de groupe
|
||||
* Mixe plusieurs canaux d'entrée vers chaque groupe (avec gains individuels)
|
||||
*
|
||||
* @param {Map<number, Float32Array>} inputChannelsData - Données PCM par canal d'entrée
|
||||
*/
|
||||
processInputsToGroups(inputChannelsData) {
|
||||
// Réinitialise les buffers de groupe
|
||||
this.groupBuffers.clear();
|
||||
this.config.groups.forEach(group => {
|
||||
// Utiliser l'ID (slugifié) plutôt que le nom pour correspondre au routing
|
||||
const groupId = group.id || group.name || group;
|
||||
this.groupBuffers.set(groupId, new Float32Array(this.config.frameSize));
|
||||
});
|
||||
|
||||
// Compter le nombre de sources par groupe pour normalisation
|
||||
const groupSourceCount = new Map();
|
||||
inputChannelsData.forEach((_, channelId) => {
|
||||
const key = `in_${channelId}`;
|
||||
const routes = this.inputToGroupRoutes.get(key);
|
||||
if (routes) {
|
||||
routes.forEach(route => {
|
||||
groupSourceCount.set(
|
||||
route.destination,
|
||||
(groupSourceCount.get(route.destination) || 0) + 1
|
||||
);
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
// Pour chaque canal d'entrée
|
||||
inputChannelsData.forEach((pcmData, channelId) => {
|
||||
const key = `in_${channelId}`;
|
||||
const routes = this.inputToGroupRoutes.get(key);
|
||||
|
||||
if (!routes || routes.length === 0) return;
|
||||
|
||||
// Stocke le buffer d'entrée
|
||||
this.inputBuffers.set(channelId, pcmData);
|
||||
|
||||
// Applique chaque route (mixage additif vers les groupes)
|
||||
routes.forEach(route => {
|
||||
const groupBuffer = this.groupBuffers.get(route.destination);
|
||||
if (!groupBuffer) {
|
||||
logger.warn(`Buffer groupe "${route.destination}" introuvable pour routing depuis Input ${channelId}`);
|
||||
return;
|
||||
}
|
||||
|
||||
// Mixage avec gain + atténuation par nombre de sources
|
||||
const sourceCount = groupSourceCount.get(route.destination) || 1;
|
||||
const mixGain = route.linearGain / sourceCount;
|
||||
|
||||
for (let i = 0; i < pcmData.length && i < groupBuffer.length; i++) {
|
||||
groupBuffer[i] += pcmData[i] * mixGain;
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
// Normalisation anti-clipping (soft limiter simple)
|
||||
this.groupBuffers.forEach((buffer, groupName) => {
|
||||
for (let i = 0; i < buffer.length; i++) {
|
||||
if (Math.abs(buffer[i]) > 1.0) {
|
||||
this.stats.clippingEvents++;
|
||||
if (this.stats.clippingEvents % 1000 === 1) {
|
||||
logger.warn(`Clipping détecté sur groupe "${groupName}" (${this.stats.clippingEvents} événements)`);
|
||||
}
|
||||
buffer[i] = Math.sign(buffer[i]) * 1.0; // Hard clipping
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
this.stats.framesProcessed++;
|
||||
return this.groupBuffers;
|
||||
}
|
||||
|
||||
/**
|
||||
* ÉTAPE 2 : Traite les buffers de groupe vers les sorties audio physiques
|
||||
* Distribue chaque groupe vers plusieurs canaux de sortie (avec gains individuels)
|
||||
* Support du mixage additif si plusieurs groupes vont vers la même sortie
|
||||
*
|
||||
* @param {Map<string, Float32Array>} groupBuffersData - Données PCM par groupe (depuis LiveKit)
|
||||
* @returns {Map<number, Float32Array>} Buffers de sortie par canal physique
|
||||
*/
|
||||
processGroupsToOutputs(groupBuffersData) {
|
||||
// Réinitialise les buffers de sortie
|
||||
this.outputBuffers.clear();
|
||||
|
||||
// Pour chaque groupe
|
||||
groupBuffersData.forEach((pcmData, groupName) => {
|
||||
const routes = this.groupToOutputRoutes.get(groupName);
|
||||
|
||||
if (!routes || routes.length === 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Applique chaque route vers les sorties
|
||||
routes.forEach(route => {
|
||||
const outputChannel = route.destination;
|
||||
|
||||
// Crée le buffer de sortie si nécessaire
|
||||
if (!this.outputBuffers.has(outputChannel)) {
|
||||
this.outputBuffers.set(outputChannel, new Float32Array(this.config.frameSize));
|
||||
}
|
||||
|
||||
const outputBuffer = this.outputBuffers.get(outputChannel);
|
||||
|
||||
// Mixage avec gain (additif si canal partagé)
|
||||
for (let i = 0; i < pcmData.length && i < outputBuffer.length; i++) {
|
||||
outputBuffer[i] += pcmData[i] * route.linearGain;
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
// Normalisation anti-clipping sur les sorties
|
||||
this.outputBuffers.forEach((buffer, channelId) => {
|
||||
for (let i = 0; i < buffer.length; i++) {
|
||||
if (Math.abs(buffer[i]) > 1.0) {
|
||||
this.stats.clippingEvents++;
|
||||
buffer[i] = Math.sign(buffer[i]) * 1.0; // Hard clipping
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
return this.outputBuffers;
|
||||
}
|
||||
|
||||
/**
|
||||
* Récupère le buffer d'un groupe spécifique
|
||||
*/
|
||||
getGroupBuffer(groupName) {
|
||||
return this.groupBuffers.get(groupName) || null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Récupère le buffer d'une sortie spécifique
|
||||
*/
|
||||
getOutputBuffer(channelId) {
|
||||
return this.outputBuffers.get(channelId) || null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Récupère toutes les routes configurées
|
||||
*/
|
||||
getRoutingConfig() {
|
||||
const inputToGroup = {};
|
||||
const groupToOutput = {};
|
||||
const gains = {};
|
||||
|
||||
// Input -> Group
|
||||
this.inputToGroupRoutes.forEach((routes, key) => {
|
||||
const inputChannel = key.replace('in_', '');
|
||||
inputToGroup[inputChannel] = routes.map(r => r.destination);
|
||||
|
||||
routes.forEach(route => {
|
||||
if (route.gain !== 0.0) {
|
||||
gains[`in_${inputChannel}_${route.destination}`] = route.gain;
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
// Group -> Output
|
||||
this.groupToOutputRoutes.forEach((routes, groupName) => {
|
||||
groupToOutput[groupName] = routes.map(r => r.destination);
|
||||
|
||||
routes.forEach(route => {
|
||||
if (route.gain !== 0.0) {
|
||||
gains[`${groupName}_out_${route.destination}`] = route.gain;
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
return { inputToGroup, groupToOutput, gains };
|
||||
}
|
||||
|
||||
/**
|
||||
* Récupère les statistiques
|
||||
*/
|
||||
getStats() {
|
||||
return {
|
||||
framesProcessed: this.stats.framesProcessed,
|
||||
clippingEvents: this.stats.clippingEvents,
|
||||
routesActive: this.stats.routesActive,
|
||||
inputToGroupRoutes: this.inputToGroupRoutes.size,
|
||||
groupToOutputRoutes: this.groupToOutputRoutes.size,
|
||||
activeGroups: this.groupBuffers.size,
|
||||
activeOutputs: this.outputBuffers.size
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Met à jour le compteur de routes actives
|
||||
*/
|
||||
_updateStatsActiveRoutes() {
|
||||
let count = 0;
|
||||
this.inputToGroupRoutes.forEach(routes => count += routes.length);
|
||||
this.groupToOutputRoutes.forEach(routes => count += routes.length);
|
||||
this.stats.routesActive = count;
|
||||
}
|
||||
|
||||
/**
|
||||
* Détruit le router et libère les ressources
|
||||
*/
|
||||
destroy() {
|
||||
this.inputToGroupRoutes.clear();
|
||||
this.groupToOutputRoutes.clear();
|
||||
this.inputBuffers.clear();
|
||||
this.groupBuffers.clear();
|
||||
this.outputBuffers.clear();
|
||||
this.removeAllListeners();
|
||||
logger.info('GroupAudioRouter détruit');
|
||||
}
|
||||
}
|
||||
|
||||
export default GroupAudioRouter;
|
||||
@@ -0,0 +1,196 @@
|
||||
/**
|
||||
* ServerAudioUser.js
|
||||
* Utilisateur audio géré côté serveur : participant LiveKit indépendant
|
||||
* avec un canal physique d'entrée dédié et un canal physique de sortie dédié.
|
||||
*
|
||||
* Chaque instance :
|
||||
* - Publie son canal physique d'entrée comme track LiveKit
|
||||
* - Reçoit l'audio de tous les autres participants (mix-minus naturel)
|
||||
* - Émet 'outputReady' avec le mix Float32 quand une frame complète est prête
|
||||
*/
|
||||
|
||||
import { EventEmitter } from 'events';
|
||||
import LiveKitClient from './LiveKitClient.js';
|
||||
|
||||
class ServerAudioUser extends EventEmitter {
|
||||
constructor(options) {
|
||||
super();
|
||||
|
||||
this.name = options.name;
|
||||
this.inputChannel = (options.inputChannel !== null && options.inputChannel !== undefined)
|
||||
? parseInt(options.inputChannel, 10)
|
||||
: null;
|
||||
this.outputChannel = (options.outputChannel !== null && options.outputChannel !== undefined)
|
||||
? parseInt(options.outputChannel, 10)
|
||||
: null;
|
||||
this.publish = options.publish !== false; // false = écoute seule
|
||||
this.groupId = options.groupId;
|
||||
this.frameSize = options.frameSize || 960;
|
||||
this.sampleRate = options.sampleRate || 48000;
|
||||
|
||||
this.client = new LiveKitClient({
|
||||
url: options.liveKitUrl,
|
||||
token: options.token,
|
||||
roomName: options.groupId,
|
||||
participantName: `server-${options.name}`,
|
||||
sampleRate: this.sampleRate,
|
||||
channels: 1,
|
||||
});
|
||||
|
||||
// Accumulateurs PCM par participant distant (pour pouvoir mixer leurs frames)
|
||||
this.participantAccumulators = new Map(); // Map<participantSid, { buffer: Float32Array, offset: number }>
|
||||
|
||||
// Dernier mix calculé (prêt à être envoyé vers le canal physique de sortie)
|
||||
this.mixedOutput = null; // Float32Array de frameSize samples
|
||||
|
||||
this._setupClientEvents();
|
||||
}
|
||||
|
||||
_setupClientEvents() {
|
||||
this.client.on('connected', () => {
|
||||
const mode = this.publish ? `in:${this.inputChannel} → out:${this.outputChannel ?? 'aucune'}` : `écoute → out:${this.outputChannel ?? 'aucune'}`;
|
||||
console.log(`[ServerAudioUser:${this.name}] Connecté à room "${this.groupId}" (${mode})`);
|
||||
this.emit('connected');
|
||||
});
|
||||
|
||||
this.client.on('disconnected', (data) => {
|
||||
console.warn(`[ServerAudioUser:${this.name}] Déconnecté:`, data?.reason || 'unknown');
|
||||
this.emit('disconnected', data);
|
||||
});
|
||||
|
||||
// Réception audio depuis les autres participants → accumulation et mix
|
||||
this.client.on('audioData', ({ participantSid, pcmData }) => {
|
||||
this._accumulate(participantSid, pcmData);
|
||||
});
|
||||
|
||||
// Nettoyage des buffers quand un participant quitte
|
||||
this.client.on('participantDisconnected', (participant) => {
|
||||
this.participantAccumulators.delete(participant.sid);
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Démarre la connexion LiveKit
|
||||
*/
|
||||
async start() {
|
||||
await this.client.connect();
|
||||
}
|
||||
|
||||
/**
|
||||
* Envoie les données audio du canal d'entrée physique vers LiveKit.
|
||||
* Appelé par AudioBridge à chaque frame de capture.
|
||||
* @param {Float32Array} float32Data - Données PCM normalisées [-1.0, 1.0]
|
||||
*/
|
||||
sendAudio(float32Data) {
|
||||
if (!this.publish || !this.client.isConnected) return;
|
||||
|
||||
const pcmBuffer = this._float32ToBuffer(float32Data);
|
||||
this.client.sendAudioData(pcmBuffer);
|
||||
}
|
||||
|
||||
/**
|
||||
* Retourne le dernier mix calculé, ou null si aucune frame reçue.
|
||||
* @returns {Float32Array|null}
|
||||
*/
|
||||
getMixedOutput() {
|
||||
return this.mixedOutput;
|
||||
}
|
||||
|
||||
/**
|
||||
* Accumule les frames PCM reçues d'un participant.
|
||||
* Quand une frame complète est disponible, calcule le mix.
|
||||
* @private
|
||||
*/
|
||||
_accumulate(participantSid, pcmData) {
|
||||
const float32 = this._bufferToFloat32(pcmData);
|
||||
|
||||
if (!this.participantAccumulators.has(participantSid)) {
|
||||
this.participantAccumulators.set(participantSid, {
|
||||
buffer: new Float32Array(this.frameSize),
|
||||
offset: 0
|
||||
});
|
||||
}
|
||||
|
||||
const acc = this.participantAccumulators.get(participantSid);
|
||||
const toCopy = Math.min(float32.length, this.frameSize - acc.offset);
|
||||
|
||||
if (toCopy > 0) {
|
||||
acc.buffer.set(float32.subarray(0, toCopy), acc.offset);
|
||||
acc.offset += toCopy;
|
||||
}
|
||||
|
||||
if (acc.offset >= this.frameSize) {
|
||||
this._computeMix();
|
||||
acc.offset = 0;
|
||||
acc.buffer.fill(0);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Calcule le mix additif de tous les participants et émet 'outputReady'.
|
||||
* @private
|
||||
*/
|
||||
_computeMix() {
|
||||
const mix = new Float32Array(this.frameSize);
|
||||
|
||||
for (const { buffer } of this.participantAccumulators.values()) {
|
||||
for (let i = 0; i < this.frameSize; i++) {
|
||||
mix[i] += buffer[i];
|
||||
}
|
||||
}
|
||||
|
||||
// Clamp
|
||||
for (let i = 0; i < mix.length; i++) {
|
||||
mix[i] = Math.max(-1.0, Math.min(1.0, mix[i]));
|
||||
}
|
||||
|
||||
this.mixedOutput = mix;
|
||||
if (this.outputChannel !== null) {
|
||||
this.emit('outputReady', mix);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Convertit Buffer/Int16Array PCM 16-bit → Float32Array [-1.0, 1.0]
|
||||
* @private
|
||||
*/
|
||||
_bufferToFloat32(buffer) {
|
||||
if (buffer instanceof Int16Array) {
|
||||
const f = new Float32Array(buffer.length);
|
||||
for (let i = 0; i < buffer.length; i++) f[i] = buffer[i] / 32768.0;
|
||||
return f;
|
||||
}
|
||||
if (!(buffer instanceof Buffer)) buffer = Buffer.from(buffer);
|
||||
const samples = buffer.length / 2;
|
||||
const f = new Float32Array(samples);
|
||||
for (let i = 0; i < samples; i++) {
|
||||
f[i] = buffer.readInt16LE(i * 2) / 32768.0;
|
||||
}
|
||||
return f;
|
||||
}
|
||||
|
||||
/**
|
||||
* Convertit Float32Array [-1.0, 1.0] → Buffer PCM 16-bit
|
||||
* @private
|
||||
*/
|
||||
_float32ToBuffer(float32) {
|
||||
const buf = Buffer.alloc(float32.length * 2);
|
||||
for (let i = 0; i < float32.length; i++) {
|
||||
const clamped = Math.max(-1.0, Math.min(1.0, float32[i]));
|
||||
buf.writeInt16LE(Math.round(clamped * 32767), i * 2);
|
||||
}
|
||||
return buf;
|
||||
}
|
||||
|
||||
/**
|
||||
* Arrête l'utilisateur et libère les ressources.
|
||||
*/
|
||||
async stop() {
|
||||
await this.client.destroy();
|
||||
this.participantAccumulators.clear();
|
||||
this.mixedOutput = null;
|
||||
this.removeAllListeners();
|
||||
}
|
||||
}
|
||||
|
||||
export default ServerAudioUser;
|
||||
+13
-30
@@ -2,43 +2,26 @@ audio:
|
||||
sampleRate: 48000
|
||||
channels: 2
|
||||
frameSize: 20
|
||||
defaultBitrate: 96
|
||||
defaultBitrate: 128
|
||||
jitterBufferMs: 40
|
||||
device:
|
||||
inputDeviceId: Loopback Audio 4
|
||||
outputDeviceId: Haut-parleurs MacBook Pro
|
||||
outputDeviceId: Périphérique agrégé
|
||||
sampleRate: 48000
|
||||
routing:
|
||||
inputToGroup:
|
||||
"0":
|
||||
- default
|
||||
"1": []
|
||||
"2": []
|
||||
"4":
|
||||
- technique
|
||||
"5":
|
||||
- technique
|
||||
groupToOutput:
|
||||
technique:
|
||||
- "1"
|
||||
production:
|
||||
- "0"
|
||||
- "1"
|
||||
default:
|
||||
- "0"
|
||||
gains: {}
|
||||
channelNames:
|
||||
inputs:
|
||||
"0": Mac
|
||||
"1": Talkback FOH
|
||||
"2": Retour Console
|
||||
"3": Liaison Scène
|
||||
"4": Monitor Mix
|
||||
"5": Spare 1
|
||||
"0": Loopback L
|
||||
"1": Loopback R
|
||||
outputs:
|
||||
"0": L
|
||||
"1": R
|
||||
"2": Talkback Console
|
||||
"0": Casque L
|
||||
"1": Casque R
|
||||
"2": Mac L
|
||||
"3": Mac R
|
||||
server_audio_users:
|
||||
- name: Utilisateur Serveur
|
||||
group: default
|
||||
input_channel: 0
|
||||
output_channel: 0
|
||||
groups:
|
||||
- name: Default
|
||||
audioBitrate: 96
|
||||
|
||||
+58
-23
@@ -16,6 +16,7 @@ import configManager from './config/ConfigManager.js';
|
||||
import audioBridgeManager from './bridge/AudioBridgeManager.js';
|
||||
import AudioLevelsServer from './websocket/AudioLevelsServer.js';
|
||||
import { setGlobalLogLevel } from './utils/Logger.js';
|
||||
import httpProxy from 'http-proxy';
|
||||
|
||||
const __dirname = dirname(fileURLToPath(import.meta.url));
|
||||
|
||||
@@ -333,30 +334,12 @@ apiRouter.post('/token', async (req, res) => {
|
||||
// Enregistrer l'utilisateur dans le système admin
|
||||
registerUser(participantIdentity, username, groupId, roomName);
|
||||
|
||||
// Générer les canaux virtuels depuis le routing (inputs uniquement)
|
||||
const virtualChannels = [];
|
||||
const inputToGroup = config.audio?.routing?.inputToGroup || {};
|
||||
const channelNames = config.audio?.channelNames?.inputs || {};
|
||||
|
||||
// Trouver tous les canaux physiques routés vers ce groupe
|
||||
for (const [inputChannel, groups] of Object.entries(inputToGroup)) {
|
||||
if (groups.includes(groupId)) {
|
||||
const channelName = channelNames[inputChannel] || `Canal ${inputChannel}`;
|
||||
virtualChannels.push({
|
||||
id: `input-${inputChannel}`,
|
||||
name: channelName,
|
||||
isVirtual: true,
|
||||
audioInput: parseInt(inputChannel, 10)
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
res.json({
|
||||
token,
|
||||
url: LIVEKIT_URL,
|
||||
roomName,
|
||||
participantIdentity,
|
||||
virtualChannels
|
||||
virtualChannels: []
|
||||
});
|
||||
|
||||
} catch (error) {
|
||||
@@ -378,6 +361,33 @@ apiRouter.get('/health', (req, res) => {
|
||||
});
|
||||
});
|
||||
|
||||
// Créer proxy WebSocket natif pour LiveKit (wss → ws)
|
||||
const livekitProxy = httpProxy.createProxyServer({
|
||||
target: 'http://localhost:7880',
|
||||
ws: true,
|
||||
changeOrigin: true
|
||||
});
|
||||
|
||||
livekitProxy.on('error', (err, req, res) => {
|
||||
log('error', `❌ Erreur proxy LiveKit: ${err.message}`);
|
||||
if (res && res.writeHead) {
|
||||
res.writeHead(502, { 'Content-Type': 'text/plain' });
|
||||
res.end('Proxy error');
|
||||
}
|
||||
});
|
||||
|
||||
livekitProxy.on('proxyReqWs', (proxyReq, req, socket, options, head) => {
|
||||
log('debug', `🔀 Proxy WebSocket: ${req.url} → ws://localhost:7880`);
|
||||
});
|
||||
|
||||
// Proxy HTTP pour LiveKit (requêtes REST comme /rtc/validate)
|
||||
app.use('/livekit', (req, res) => {
|
||||
log('debug', `🔀 Proxy HTTP: ${req.originalUrl} → http://localhost:7880${req.url}`);
|
||||
livekitProxy.web(req, res, {
|
||||
target: 'http://localhost:7880'
|
||||
});
|
||||
});
|
||||
|
||||
// Monter le router API sous /api ET à la racine (rétrocompatibilité)
|
||||
app.use('/api', apiRouter);
|
||||
app.use(apiRouter); // Routes accessibles aussi sans préfixe /api
|
||||
@@ -437,11 +447,19 @@ async function start() {
|
||||
let server;
|
||||
|
||||
if (ENABLE_HTTPS) {
|
||||
// Charger certificats SSL (mêmes que Vite)
|
||||
const certPath = join(__dirname, '..', 'client');
|
||||
// Charger certificats SSL depuis .env ou fallback
|
||||
const certPath = process.env.SSL_CERT || join(__dirname, '..', 'certs', 'localhost.pem');
|
||||
const keyPath = process.env.SSL_KEY || join(__dirname, '..', 'certs', 'localhost-key.pem');
|
||||
|
||||
if (!existsSync(certPath) || !existsSync(keyPath)) {
|
||||
log('error', '❌ Certificats SSL introuvables');
|
||||
log('info', '💡 Exécutez : ./setup-certificates.sh');
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
const httpsOptions = {
|
||||
key: readFileSync(join(certPath, 'localhost+3-key.pem')),
|
||||
cert: readFileSync(join(certPath, 'localhost+3.pem'))
|
||||
key: readFileSync(keyPath),
|
||||
cert: readFileSync(certPath)
|
||||
};
|
||||
|
||||
server = https.createServer(httpsOptions, app);
|
||||
@@ -485,8 +503,25 @@ async function start() {
|
||||
}
|
||||
|
||||
// 2.5 Démarrer WebSocket Audio Levels (même port que l'API)
|
||||
// noServer: true en interne, l'upgrade est dispatché ci-dessous
|
||||
const audioLevelsServer = new AudioLevelsServer({ server });
|
||||
audioLevelsServer.start();
|
||||
|
||||
// 2.6 Dispatcher unique pour les upgrades WebSocket du port HTTP/HTTPS
|
||||
// (proxy LiveKit et audio-levels partagent le même serveur, donc le même
|
||||
// événement 'upgrade' : un seul listener doit trancher par chemin)
|
||||
server.on('upgrade', (req, socket, head) => {
|
||||
if (req.url.startsWith('/livekit')) {
|
||||
req.url = req.url.replace(/^\/livekit/, '');
|
||||
livekitProxy.ws(req, socket, head);
|
||||
} else if (req.url.startsWith('/audio-levels')) {
|
||||
audioLevelsServer.handleUpgrade(req, socket, head);
|
||||
} else {
|
||||
log('warn', `⚠️ Unknown WebSocket path: ${req.url}`);
|
||||
socket.destroy();
|
||||
}
|
||||
});
|
||||
|
||||
const wsProtocol = ENABLE_HTTPS ? 'wss' : 'ws';
|
||||
log('info', `✓ WebSocket Audio Levels démarré sur ${wsProtocol}://${SERVER_HOST}:${SERVER_PORT}`);
|
||||
|
||||
|
||||
@@ -22,6 +22,8 @@
|
||||
"@livekit/rtc-node": "^0.13.28",
|
||||
"dotenv": "^17.4.2",
|
||||
"express": "^4.19.2",
|
||||
"http-proxy": "^1.18.1",
|
||||
"http-proxy-middleware": "^4.1.1",
|
||||
"livekit-server-sdk": "^2.6.0",
|
||||
"opusscript": "^0.1.1",
|
||||
"qrcode-terminal": "^0.12.0",
|
||||
|
||||
@@ -91,9 +91,11 @@ export class AudioLevelsServer extends EventEmitter {
|
||||
return new Promise((resolve, reject) => {
|
||||
try {
|
||||
// Si un serveur HTTP est fourni, utiliser le même port (upgrade HTTP → WebSocket)
|
||||
// noServer: true car l'upgrade est dispatché manuellement par server/index.js
|
||||
// (un seul listener 'upgrade' partagé avec le proxy LiveKit, voir handleUpgrade())
|
||||
// Sinon, créer un serveur WebSocket standalone sur son propre port
|
||||
const wsOptions = this.options.server
|
||||
? { server: this.options.server, path: '/audio-levels' }
|
||||
? { noServer: true }
|
||||
: { port: this.options.port };
|
||||
|
||||
this.wss = new WebSocketServer(wsOptions);
|
||||
@@ -125,6 +127,16 @@ export class AudioLevelsServer extends EventEmitter {
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Complète l'upgrade WebSocket pour une requête déjà identifiée comme
|
||||
* ciblant ce serveur (voir le dispatcher 'upgrade' dans server/index.js)
|
||||
*/
|
||||
handleUpgrade(req, socket, head) {
|
||||
this.wss.handleUpgrade(req, socket, head, (ws) => {
|
||||
this.wss.emit('connection', ws, req);
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Gère une nouvelle connexion client
|
||||
*/
|
||||
|
||||
Executable
+324
@@ -0,0 +1,324 @@
|
||||
#!/bin/bash
|
||||
|
||||
# PTT Live - Configuration Certificats SSL Locaux
|
||||
# Génère des certificats auto-signés DE CONFIANCE pour développement local
|
||||
|
||||
set -e
|
||||
|
||||
echo "🔐 Configuration Certificats SSL Locaux PTT Live"
|
||||
echo ""
|
||||
|
||||
# Détection OS
|
||||
OS="$(uname -s)"
|
||||
|
||||
# Couleurs
|
||||
GREEN='\033[0;32m'
|
||||
YELLOW='\033[1;33m'
|
||||
RED='\033[0;31m'
|
||||
NC='\033[0m' # No Color
|
||||
|
||||
# ========== Installation mkcert ==========
|
||||
|
||||
echo "📦 Vérification mkcert..."
|
||||
|
||||
if ! command -v mkcert &> /dev/null; then
|
||||
echo -e "${YELLOW}⚠️ mkcert non installé${NC}"
|
||||
echo ""
|
||||
echo "Installation de mkcert (génère certificats de confiance)..."
|
||||
echo ""
|
||||
|
||||
if [[ "$OS" == "Darwin" ]]; then
|
||||
# macOS
|
||||
if command -v brew &> /dev/null; then
|
||||
brew install mkcert
|
||||
brew install nss # Pour Firefox
|
||||
else
|
||||
echo -e "${RED}❌ Homebrew requis sur macOS${NC}"
|
||||
echo "Installez Homebrew : https://brew.sh"
|
||||
exit 1
|
||||
fi
|
||||
elif [[ "$OS" == "Linux" ]]; then
|
||||
# Linux
|
||||
if command -v apt-get &> /dev/null; then
|
||||
# Debian/Ubuntu
|
||||
sudo apt-get update
|
||||
sudo apt-get install -y libnss3-tools
|
||||
|
||||
# Télécharger mkcert
|
||||
curl -JLO "https://dl.filippo.io/mkcert/latest?for=linux/amd64"
|
||||
chmod +x mkcert-v*-linux-amd64
|
||||
sudo mv mkcert-v*-linux-amd64 /usr/local/bin/mkcert
|
||||
elif command -v yum &> /dev/null; then
|
||||
# RedHat/CentOS
|
||||
sudo yum install -y nss-tools
|
||||
|
||||
curl -JLO "https://dl.filippo.io/mkcert/latest?for=linux/amd64"
|
||||
chmod +x mkcert-v*-linux-amd64
|
||||
sudo mv mkcert-v*-linux-amd64 /usr/local/bin/mkcert
|
||||
else
|
||||
echo -e "${RED}❌ Gestionnaire de paquets non supporté${NC}"
|
||||
echo "Installez mkcert manuellement : https://github.com/FiloSottile/mkcert"
|
||||
exit 1
|
||||
fi
|
||||
else
|
||||
echo -e "${RED}❌ OS non supporté : $OS${NC}"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
echo -e "${GREEN}✅ mkcert installé${NC}"
|
||||
echo ""
|
||||
else
|
||||
echo -e "${GREEN}✅ mkcert déjà installé${NC}"
|
||||
echo ""
|
||||
fi
|
||||
|
||||
# ========== Installation CA Locale ==========
|
||||
|
||||
echo "🔑 Installation Certificate Authority (CA) locale..."
|
||||
echo ""
|
||||
echo "⚠️ Ceci va ajouter une CA locale au système"
|
||||
echo " Les certificats générés seront automatiquement approuvés"
|
||||
echo ""
|
||||
|
||||
# Installer la CA locale (une seule fois par machine)
|
||||
mkcert -install
|
||||
|
||||
if [ $? -eq 0 ]; then
|
||||
echo -e "${GREEN}✅ CA locale installée${NC}"
|
||||
else
|
||||
echo -e "${RED}❌ Erreur installation CA${NC}"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
echo ""
|
||||
|
||||
# ========== Génération Certificats ==========
|
||||
|
||||
echo "📜 Génération certificats pour PTT Live..."
|
||||
echo ""
|
||||
|
||||
# Détecter l'IP réseau
|
||||
if [[ "$OS" == "Darwin" ]]; then
|
||||
# macOS
|
||||
NETWORK_IP=$(ipconfig getifaddr en0 || ipconfig getifaddr en1 || echo "192.168.1.100")
|
||||
elif [[ "$OS" == "Linux" ]]; then
|
||||
# Linux
|
||||
NETWORK_IP=$(ip route get 1 | awk '{print $7; exit}' || echo "192.168.1.100")
|
||||
fi
|
||||
|
||||
echo "🌐 IP réseau détectée : $NETWORK_IP"
|
||||
echo ""
|
||||
|
||||
# Créer répertoire certificats
|
||||
CERT_DIR="$(pwd)/certs"
|
||||
mkdir -p "$CERT_DIR"
|
||||
|
||||
cd "$CERT_DIR"
|
||||
|
||||
# Générer certificats pour :
|
||||
# - localhost
|
||||
# - IP réseau locale
|
||||
# - *.local (wildcard)
|
||||
|
||||
echo "Génération certificats pour :"
|
||||
echo " - localhost"
|
||||
echo " - $NETWORK_IP"
|
||||
echo " - *.local"
|
||||
echo ""
|
||||
|
||||
mkcert \
|
||||
localhost \
|
||||
127.0.0.1 \
|
||||
::1 \
|
||||
"$NETWORK_IP" \
|
||||
"*.local" \
|
||||
"$(hostname).local"
|
||||
|
||||
if [ $? -eq 0 ]; then
|
||||
echo ""
|
||||
echo -e "${GREEN}✅ Certificats générés dans : $CERT_DIR${NC}"
|
||||
echo ""
|
||||
|
||||
# Renommer pour simplifier
|
||||
mv localhost+*.pem localhost.pem 2>/dev/null || true
|
||||
mv localhost+*-key.pem localhost-key.pem 2>/dev/null || true
|
||||
|
||||
echo "📁 Fichiers créés :"
|
||||
ls -lh "$CERT_DIR"/*.pem
|
||||
else
|
||||
echo -e "${RED}❌ Erreur génération certificats${NC}"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
echo ""
|
||||
|
||||
# ========== Configuration Serveur ==========
|
||||
|
||||
echo "⚙️ Configuration automatique du serveur..."
|
||||
echo ""
|
||||
|
||||
# Créer/mettre à jour .env serveur
|
||||
SERVER_ENV="$(pwd)/../server/.env"
|
||||
|
||||
if [ -f "$SERVER_ENV" ]; then
|
||||
# Backup
|
||||
cp "$SERVER_ENV" "$SERVER_ENV.backup"
|
||||
echo "💾 Backup : $SERVER_ENV.backup"
|
||||
fi
|
||||
|
||||
# Détecter les fichiers de certificats générés
|
||||
CERT_FILE=$(ls "$CERT_DIR"/localhost.pem 2>/dev/null || ls "$CERT_DIR"/*+*.pem | head -1)
|
||||
KEY_FILE=$(ls "$CERT_DIR"/localhost-key.pem 2>/dev/null || ls "$CERT_DIR"/*-key.pem | head -1)
|
||||
|
||||
if [ -z "$CERT_FILE" ] || [ -z "$KEY_FILE" ]; then
|
||||
echo -e "${RED}❌ Certificats introuvables${NC}"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
# Mettre à jour .env avec chemins absolus
|
||||
cat > "$SERVER_ENV" << EOF
|
||||
# PTT Live Server - Configuration
|
||||
# Généré automatiquement par setup-certificates.sh
|
||||
|
||||
# LiveKit Local
|
||||
USE_LOCAL_LIVEKIT=true
|
||||
LIVEKIT_API_KEY=devkey
|
||||
LIVEKIT_API_SECRET=secret
|
||||
LIVEKIT_URL=AUTO
|
||||
|
||||
# Serveur
|
||||
PORT=3000
|
||||
ENABLE_HTTPS=true
|
||||
|
||||
# Certificats SSL (chemins absolus)
|
||||
SSL_CERT=$CERT_FILE
|
||||
SSL_KEY=$KEY_FILE
|
||||
|
||||
# Réseau
|
||||
NETWORK_IP=$NETWORK_IP
|
||||
EOF
|
||||
|
||||
echo -e "${GREEN}✅ .env serveur mis à jour${NC}"
|
||||
echo ""
|
||||
|
||||
# ========== Configuration Client ==========
|
||||
|
||||
echo "⚙️ Configuration client..."
|
||||
echo ""
|
||||
|
||||
CLIENT_ENV="$(pwd)/../client/.env"
|
||||
|
||||
cat > "$CLIENT_ENV" << EOF
|
||||
# PTT Live Client - Configuration
|
||||
# Généré automatiquement par setup-certificates.sh
|
||||
|
||||
VITE_SERVER_URL=https://$NETWORK_IP:3000
|
||||
EOF
|
||||
|
||||
echo -e "${GREEN}✅ .env client créé${NC}"
|
||||
echo ""
|
||||
|
||||
# ========== Mettre à jour Vite Config ==========
|
||||
|
||||
echo "⚙️ Configuration Vite HTTPS..."
|
||||
echo ""
|
||||
|
||||
VITE_CONFIG="$(pwd)/../client/vite.config.js"
|
||||
|
||||
cat > "$VITE_CONFIG" << EOF
|
||||
import { defineConfig } from 'vite';
|
||||
import react from '@vitejs/plugin-react';
|
||||
import { VitePWA } from 'vite-plugin-pwa';
|
||||
import fs from 'fs';
|
||||
import path from 'path';
|
||||
|
||||
// https://vitejs.dev/config/
|
||||
export default defineConfig({
|
||||
plugins: [
|
||||
react(),
|
||||
VitePWA({
|
||||
registerType: 'autoUpdate',
|
||||
includeAssets: ['favicon.ico', 'apple-touch-icon.png', 'masked-icon.svg'],
|
||||
manifest: {
|
||||
name: 'PTT Live',
|
||||
short_name: 'PTT Live',
|
||||
description: 'Professional WebRTC Intercom',
|
||||
theme_color: '#1a1a1a',
|
||||
icons: [
|
||||
{
|
||||
src: 'pwa-192x192.png',
|
||||
sizes: '192x192',
|
||||
type: 'image/png'
|
||||
},
|
||||
{
|
||||
src: 'pwa-512x512.png',
|
||||
sizes: '512x512',
|
||||
type: 'image/png'
|
||||
}
|
||||
]
|
||||
}
|
||||
})
|
||||
],
|
||||
server: {
|
||||
host: '0.0.0.0',
|
||||
port: 5173,
|
||||
https: {
|
||||
key: fs.readFileSync(path.resolve(__dirname, '../certs/$KEY_FILE')),
|
||||
cert: fs.readFileSync(path.resolve(__dirname, '../certs/$CERT_FILE'))
|
||||
}
|
||||
}
|
||||
});
|
||||
EOF
|
||||
|
||||
echo -e "${GREEN}✅ vite.config.js mis à jour avec HTTPS${NC}"
|
||||
echo ""
|
||||
|
||||
# ========== Mettre à jour serveur index.js ==========
|
||||
|
||||
echo "⚙️ Configuration serveur Express HTTPS..."
|
||||
echo ""
|
||||
|
||||
# Le serveur lira SSL_CERT et SSL_KEY depuis .env
|
||||
# Pas besoin de modifier index.js si déjà compatible
|
||||
|
||||
echo -e "${GREEN}✅ Configuration terminée${NC}"
|
||||
echo ""
|
||||
|
||||
# ========== Récapitulatif ==========
|
||||
|
||||
echo ""
|
||||
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
|
||||
echo -e "${GREEN}✅ CONFIGURATION CERTIFICATS TERMINÉE${NC}"
|
||||
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
|
||||
echo ""
|
||||
echo "📜 Certificats générés :"
|
||||
echo " $CERT_DIR"
|
||||
echo ""
|
||||
echo "🌐 URLs d'accès :"
|
||||
echo ""
|
||||
echo " Serveur : https://$NETWORK_IP:3000"
|
||||
echo " Client : https://$NETWORK_IP:5173"
|
||||
echo ""
|
||||
echo "🔐 Les certificats sont automatiquement approuvés par :"
|
||||
echo " - Chrome/Edge/Safari"
|
||||
echo " - Firefox (si nss installé)"
|
||||
echo " - Système d'exploitation"
|
||||
echo ""
|
||||
echo "📱 Scan QR Code au démarrage pour connexion rapide"
|
||||
echo ""
|
||||
echo "🚀 Démarrer le système :"
|
||||
echo ""
|
||||
echo " ./start.sh --dev"
|
||||
echo " # OU"
|
||||
echo " ./start-desktop.sh"
|
||||
echo ""
|
||||
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
|
||||
echo ""
|
||||
echo "💡 Pour smartphones iOS/Android :"
|
||||
echo ""
|
||||
echo " 1. Scanner le QR Code affiché au démarrage"
|
||||
echo " 2. Accepter le certificat (une seule fois)"
|
||||
echo " 3. Installer la PWA sur l'écran d'accueil"
|
||||
echo ""
|
||||
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
|
||||
echo ""
|
||||
Executable
+9
@@ -0,0 +1,9 @@
|
||||
#!/bin/bash
|
||||
|
||||
# PTT Live - Lancement application desktop
|
||||
|
||||
echo "🖥️ Démarrage PTT Live Desktop..."
|
||||
echo ""
|
||||
|
||||
cd electron
|
||||
npm start
|
||||
Reference in New Issue
Block a user