feat: restructure to kai-sa-cam layout with apps/ structure
CD — Kai-Sa-Cam Deployment / deploy (push) Canceled after 0s

This commit is contained in:
2026-10-25 01:06:31 +02:00
parent 95f939ef2d
commit 73394dfbbc
30 changed files with 6444 additions and 234 deletions
+20
View File
@@ -0,0 +1,20 @@
# --- INFRASTRUCTURE ---
TZ=Europe/Paris
USER_ID=1001
GROUP_ID=1001
# --- APP ---
APP_ORIGIN=https://kaisa.esiah.dev
MEDIA_DIR=./media
CONFIG_DIR=./config
LOG_LEVEL=info
MAX_RECORDING_MINUTES=120
DISK_MIN_FREE_GB=2
# --- GO2RTC ---
GO2RTC_USERNAME=kai-sa-cam
GO2RTC_PASSWORD=
# --- AUDIO / BLUETOOTH (host side) ---
PULSE_SERVER=unix:/run/user/1001/pulse/native
BT_MAC=69:B2:C0:04:A4:80
+33
View File
@@ -0,0 +1,33 @@
name: CD — Kai-Sa-Cam Deployment
on:
push:
branches: [main]
paths:
- "apps/kai-sa-cam/**"
- "config/kai-sa-go2rtc.yaml"
- "docker-compose.yml"
- "Makefile"
- ".github/workflows/deploy.yml"
workflow_dispatch:
concurrency:
group: deploy-kai-sa-cam
cancel-in-progress: false
jobs:
deploy:
runs-on: [self-hosted, kai-sa-cam]
steps:
- name: Fetch latest code and rebuild
env:
DEPLOY_DIR: ${{ secrets.DEPLOY_DIR }}
run: |
set -eu
dir="${DEPLOY_DIR:-/srv/apps/kai-sa-cam}"
git config --global --add safe.directory "$dir"
cd "$dir"
git pull --ff-only origin main
docker compose --profile prod build
docker compose --profile prod up -d
docker image prune -f
+52
View File
@@ -0,0 +1,52 @@
name: PR — Ouverture automatique (Kai-Sa-Cam)
on:
push:
branches-ignore: [main]
workflow_dispatch:
jobs:
create-pr:
runs-on: [self-hosted, kai-sa-cam]
permissions:
contents: write
pull-requests: write
steps:
- uses: actions/checkout@v4
with:
fetch-depth: 0
- name: Ouvrir (ou vérifier) la pull request
env:
GITEA_TOKEN: ${{ secrets.GITHUB_TOKEN }}
API: ${{ github.server_url }}/api/v1
REPO: ${{ github.repository }}
BRANCH: ${{ github.ref_name }}
run: |
set -eu
if [ "$BRANCH" = "main" ]; then
echo "main est la base : aucune PR à ouvrir."
exit 0
fi
title=$(git log -1 --pretty=%s)
body=$(git log -1 --pretty=%b)
[ -n "$body" ] || body="PR automatique de $BRANCH vers main."
open=$(curl -fsS -H "Authorization: token $GITEA_TOKEN" \
"$API/repos/$REPO/pulls?state=open&limit=50" \
| python3 -c 'import json,os,sys; b=os.environ["BRANCH"]; print(sum(1 for p in json.load(sys.stdin) if p.get("head", {}).get("ref") == b))')
if [ "$open" -gt 0 ]; then
echo "Une PR est déjà ouverte pour $BRANCH."
exit 0
fi
python3 - "$BRANCH" "$title" "$body" <<'PY' | curl -fsS -X POST \
-H "Authorization: token $GITEA_TOKEN" \
-H "Content-Type: application/json" \
--data-binary @- \
"$API/repos/$REPO/pulls"
import json, sys
branch, title, body = sys.argv[1], sys.argv[2], sys.argv[3]
print(json.dumps({"base": "main", "head": branch, "title": title, "body": body}))
PY
echo "PR créée."
+33
View File
@@ -0,0 +1,33 @@
name: Renovate (Kai-Sa-Cam)
on:
schedule:
- cron: "0 4 * * 1"
workflow_dispatch:
concurrency:
group: renovate-kai-sa-cam
cancel-in-progress: false
jobs:
renovate:
runs-on: [self-hosted, kai-sa-cam]
steps:
- name: Mettre à jour les dépendances
env:
RENOVATE_PLATFORM: gitea
RENOVATE_ENDPOINT: ${{ github.server_url }}
RENOVATE_TOKEN: ${{ secrets.RENOVATE_TOKEN }}
RENOVATE_REPOSITORIES: ${{ github.repository }}
run: |
set -eu
mkdir -p /srv/apps/kai-sa-cam/renovate-cache
docker run --rm \
-e RENOVATE_PLATFORM \
-e RENOVATE_ENDPOINT \
-e RENOVATE_TOKEN \
-e RENOVATE_REPOSITORIES \
-e RENOVATE_ONBOARDING=false \
-e LOG_LEVEL=info \
-v /srv/apps/kai-sa-cam/renovate-cache:/tmp/renovate \
ghcr.io/renovatebot/renovate:latest
+3
View File
@@ -1,3 +1,6 @@
.env .env
*.log *.log
node_modules/ node_modules/
dist/
apps/*/dist/
media/
+48 -90
View File
@@ -1,110 +1,68 @@
.RECIPEPREFIX = >
.DEFAULT_GOAL := help .DEFAULT_GOAL := help
BT_MAC ?= 69:B2:C0:04:A4:80 # Variables
USER_ID ?= 1001 COMPOSE_DEV = docker compose --profile dev
PCI_USB ?= 0000:00:14.0 COMPOSE_PROD = docker compose --profile prod
GAIN ?= 12 USER_ID ?= 1001
SINKVOL ?= 70% GROUP_ID ?= 1001
ENVU = XDG_RUNTIME_DIR=/run/user/$(USER_ID) DBUS_SESSION_BUS_ADDRESS=unix:path=/run/user/$(USER_ID)/bus APP_DIR ?= /srv/apps/kai-sa-cam
.PHONY: help up down restart build rebuild ps logs logs-cam logs-mic status \ .PHONY: help up-dev down-dev logs-dev build-dev \
bt audio-fix usb-reset speaker level gain-cam sink-volume \ up-prod down-prod logs-prod build-prod pull-prod \
host-setup cron-install cron-remove cron-log update status restart clean
help: ## Liste des commandes help: ## Affiche cette aide
> @grep -E '^[a-zA-Z_-]+:.*?## ' $(MAKEFILE_LIST) | awk 'BEGIN{FS=":.*?## "}{printf " %-14s %s\n",$$1,$$2}' @grep -E '^[a-zA-Z_-]+:.*?## ' $(MAKEFILE_LIST) | awk 'BEGIN{FS=":.*?## "}{printf " \033[36m%-20s\033[0m %s\n", $$1, $$2}'
up: ## Demarrer (build si besoin) # --- Développement local ---
> docker compose up -d --build up-dev: ## Démarre l'environnement de développement
$(COMPOSE_DEV) up -d --build
down: ## Arreter et supprimer les conteneurs down-dev: ## Arrête l'environnement de développement
> docker compose down $(COMPOSE_DEV) down
restart: ## Redemarrer go2rtc et mic-bridge logs-dev: ## Affiche les logs en continu (dev)
> docker compose restart go2rtc mic-bridge $(COMPOSE_DEV) logs -f --tail 100
build: ## Reconstruire l'image mic-bridge build-dev: ## Rebuild les images (dev)
> docker compose build mic-bridge $(COMPOSE_DEV) build
rebuild: ## Reconstruire sans cache et relancer # --- Production (serveur avec runner) ---
> docker compose build --no-cache mic-bridge up-prod: ## Démarre en production
> docker compose up -d $(COMPOSE_PROD) up -d
ps: ## Etat des conteneurs down-prod: ## Arrête la production
> docker compose ps $(COMPOSE_PROD) down
logs: ## Logs des deux services (suivi) logs-prod: ## Affiche les logs (prod)
> docker compose logs -f --tail 50 $(COMPOSE_PROD) logs -f --tail 100
logs-cam: ## Logs go2rtc (suivi) build-prod: ## Build les images de production
> docker compose logs -f --tail 50 go2rtc $(COMPOSE_PROD) build
logs-mic: ## Logs mic-bridge / Bluetooth (suivi) pull-prod: ## Pull les images de base
> docker compose logs -f --tail 50 mic-bridge $(COMPOSE_PROD) pull
status: ## Diagnostic complet (webcam, son, Bluetooth, flux) restart: ## Redémarre les services
> @echo "== Webcam (hote)" $(COMPOSE_PROD) restart
> @ls /dev/video* 2>/dev/null || echo "ABSENTE : probleme USB, voir README"
> @grep -A1 webcam /proc/asound/cards || echo "carte son webcam ABSENTE"
> @echo "== Conteneurs"
> @docker compose ps
> @echo "== Bluetooth"
> @bluetoothctl info $(BT_MAC) | grep -E "Name|Connected" || true
> @echo "== Flux go2rtc"
> @docker exec mic-bridge node -e "fetch('http://go2rtc:1984/api/streams').then(r=>r.text()).then(t=>console.log(t.slice(0,300)))" || true
bt: ## Reconnecter l'enceinte Bluetooth status: ## Affiche l'état des conteneurs
> $(ENVU) bluetoothctl connect $(BT_MAC) $(COMPOSE_PROD) ps
> docker compose restart mic-bridge
audio-fix: ## Relancer pipewire, reconnecter l'enceinte clean: ## Nettoyage complet
> $(ENVU) systemctl --user restart pipewire pipewire-pulse wireplumber $(COMPOSE_DEV) down --remove-orphans -v
> sleep 3 $(COMPOSE_PROD) down --remove-orphans -v
> $(ENVU) bluetoothctl connect $(BT_MAC) docker image prune -f
> docker compose restart mic-bridge
usb-reset: ## Reset du controleur USB (coupe aussi le Bluetooth) # --- Utilitaires ---
> echo $(PCI_USB) | sudo tee /sys/bus/pci/drivers/xhci_hcd/unbind logs-cam: ## Logs kai-sa-cam
> sleep 3 $(COMPOSE_PROD) logs -f --tail 100 kai-sa-cam
> echo $(PCI_USB) | sudo tee /sys/bus/pci/drivers/xhci_hcd/bind
> sleep 8
> ls -l /dev/video* || echo "webcam toujours absente : debrancher/rebrancher"
> $(MAKE) restart
speaker: ## Bruit de test dans l'enceinte logs-go2rtc: ## Logs kai-sa-go2rtc
> docker exec mic-bridge sh -c 'head -c 32000 /dev/urandom | paplay --raw --rate=16000 --format=s16le --channels=1' $(COMPOSE_PROD) logs -f --tail 100 kai-sa-go2rtc
level: ## Niveau du son camera (viser -25 a -30 dB) shell-cam: ## Shell dans kai-sa-cam
> docker exec go2rtc ffmpeg -hide_banner -i rtsp://127.0.0.1:8554/webcam -t 5 -vn -af volumedetect -f null - 2>&1 | grep -E "mean_volume|max_volume" $(COMPOSE_PROD) exec kai-sa-cam sh
gain-cam: ## Gain camera : make gain-cam GAIN=15 shell-go2rtc: ## Shell dans kai-sa-go2rtc
> sed -i -E 's/volume=[0-9.]+dB/volume=$(GAIN)dB/' go2rtc.yaml $(COMPOSE_PROD) exec kai-sa-go2rtc sh
> docker compose restart go2rtc
sink-volume: ## Volume enceinte : make sink-volume SINKVOL=60%
> sed -i -E 's/SINK_VOLUME: "[^"]*"/SINK_VOLUME: "$(SINKVOL)"/' docker-compose.yml
> docker compose up -d mic-bridge
host-setup: ## A faire une fois : linger, pipewire, trust BT, volume micro
> sudo loginctl enable-linger $$USER
> $(ENVU) systemctl --user enable --now pipewire pipewire-pulse wireplumber
> bluetoothctl trust $(BT_MAC)
> sudo amixer -c 0 sset Mic 100% cap unmute
> sudo alsactl store
cron-install: ## Installer la surveillance webcam (cron, chaque minute)
> sudo install -m 755 scripts/cam-watch.sh /usr/local/bin/cam-watch
> sudo install -m 644 scripts/cam-watch.cron /etc/cron.d/cam-watch
> @echo "Installe. Log : /var/log/cam-watch.log"
cron-remove: ## Desinstaller la surveillance
> sudo rm -f /etc/cron.d/cam-watch /usr/local/bin/cam-watch
cron-log: ## Voir le journal de la surveillance
> @tail -n 30 /var/log/cam-watch.log 2>/dev/null || echo "(vide)"
update: ## Mettre a jour l'image go2rtc et reconstruire mic-bridge
> docker compose pull go2rtc
> docker compose build --pull mic-bridge
> docker compose up -d
+123 -113
View File
@@ -1,128 +1,138 @@
# cam : webcam, son bidirectionnel et enceinte Bluetooth via Cloudflare # Kai-Sa-Cam
Page web `https://kaisa.esiah.dev/mic` : video + son de la webcam du serveur, Application de surveillance vidéo avec enregistrement manuel, écoute bidirectionnelle via enceinte Bluetooth, et snapshots.
et micro du navigateur vers une enceinte Bluetooth branchee sur le serveur.
Aucun port ouvert sur le routeur ni sur le serveur : tout passe par le tunnel Cloudflare.
## Architecture ## Architecture
Navigateur --HTTPS--> Cloudflare (Access + Tunnel) --> cloudflared (app-tunnel)
| reseau docker shared-network
/mic* --> mic-bridge:8090 (page + WebSocket micro -> paplay -> Pulse -> Bluetooth)
reste --> go2rtc:1984 (video MSE + son camera)
```
- **go2rtc** : lit la webcam (`/dev/video0` + carte son ALSA `webcam`) via ffmpeg ┌─────────────────────────────────────────────────────────────────┐
(H.264 baseline + AAC) et la diffuse en MSE par HTTP/WebSocket. │ Cloudflare Tunnel (kai-sa-cam-tunnel) │
- **mic-bridge** : sert la page `/mic`, recoit l'audio du navigateur en WebSocket │ └── kaisa.esiah.dev → kai-sa-cam:8090 │
(PCM 16 bits mono) et le joue sur l'enceinte via PulseAudio/PipeWire. └─────────────────────────────────────────────────────────────────┘
Son entrypoint reconnecte l'enceinte et remet son volume toutes les 15 s. │
- **Limite** : ce n'est pas du WebRTC (Cloudflare ne transporte pas l'UDP). ┌─────────┴─────────┐
Latence du micro ~200 a 500 ms, mode ON/OFF et non duplex natif. ▼ ▼
┌─────────────────┐ ┌──────────────┐
## Arborescence │ kai-sa-cam │ │kai-sa-go2rtc │
│ (API + UI + │ │ (RTSP flux) │
/srv/apps/cam │ recorder + │ │ │
docker-compose.yml services go2rtc + mic-bridge │ BT bridge) │ │ │
go2rtc.yaml flux webcam (gain camera : volume=XXdB) └─────────────────┘ └──────────────┘
Makefile commandes de gestion │ │
mic-bridge/ Dockerfile, server.js, index.html, entrypoint.sh └─────────┬─────────┘
scripts/cam-watch.* surveillance webcam (cron) │
┌─────────┴─────────┐
▼ ▼
## Prerequis kai-sa-cam-internal /dev/video0 + /dev/snd
│
- Debian avec Docker + Compose, `make`, PipeWire (`pipewire-pulse`), BlueZ. ▼
- Reseau docker externe `shared-network` (partage avec le conteneur `app-tunnel`). ┌──────────────────┐
- Utilisateur `esiahdmin` (UID 1001) : le socket Pulse est dans `/run/user/1001`. │ PulseAudio/PipeWire │
- Enceinte Bluetooth appairee (`69:B2:C0:04:A4:80`). │ (enceinte BT) │
└──────────────────┘
## Installation
```bash
cd /srv/apps/cam
make host-setup # une seule fois : linger, pipewire au boot, trust BT, micro webcam
make up
make cron-install # surveillance webcam
make status
``` ```
## Configuration Cloudflare (dashboard, une seule fois) ## Composants
1. **Tunnel** (Networks > Tunnels > Public Hostname), dans cet ordre : - **kai-sa-cam** : API Node + UI React/Tailwind + recorder + BT bridge (WebSocket → PulseAudio)
- `kaisa.esiah.dev` + chemin `mic*` -> `HTTP` `mic-bridge:8090` - **kai-sa-go2rtc** : Flux RTSP webcam (vidéo + son caméra), durci (non-privileged, devices restreints)
- `kaisa.esiah.dev` + chemin vide -> `HTTP` `go2rtc:1984`
2. **Access** (Access > Applications) : une seule application sur `kaisa.esiah.dev`
avec deux destinations : sans chemin, et `mic*`. Politique Allow limitee a votre email
(One-time PIN si le fournisseur d'identite pose probleme).
3. **Page d'accueil** (Rules > Redirect Rules) : `http.host eq "kaisa.esiah.dev"` et
`http.request.uri.path eq "/"` -> redirection statique 302 vers `https://kaisa.esiah.dev/mic`.
Ne jamais supprimer la destination sans chemin dans Access : l'API go2rtc, camera comprise, ## Fonctionnalités
deviendrait publique.
## Utilisation - **Live view** : Flux vidéo MSE via go2rtc, son caméra
- **Push-to-record manuel** : Enregistrement vidéo + son caméra (jamais micro navigateur)
- **Snapshots manuels** : Capture instantanée JPEG
- **Talkback** : Micro navigateur → enceinte Bluetooth (WebSocket → paplay → PulseAudio)
- **Stockage plat** : Tout dans `/media` sans arborescence
- **Export ZIP** : Téléchargement de tous les médias + suppression auto après succès
- **Auth** : Cloudflare Access uniquement (pas de JWT interne)
- Ouvrir `https://kaisa.esiah.dev` (ou l'icone ajoutee a l'ecran d'accueil du telephone). ## Réseaux
- Cliquer sur la video pour activer le son de la camera.
- Bouton **Micro ON/OFF** : active le micro du navigateur. Le son de la camera est coupe
chez vous pendant que le micro est ON (evite l'echo).
- Curseur **Gain** : volume de votre voix dans l'enceinte (0.2 a 5, defaut 1).
- Le WebSocket se reconnecte seul ; l'ecran reste allume via Wake Lock si le navigateur le permet.
## Commandes (`make help`) - `kai-sa-cam-internal` (internal) : Communication kai-sa-cam ↔ kai-sa-go2rtc
- `kai-sa-cam-tunnel` (external) : Exposition via Cloudflare Tunnel
| Commande | Effet | ## Installation locale (dev)
|---|---|
| `make up` / `down` / `restart` | Demarrer, arreter, redemarrer |
| `make rebuild` / `update` | Reconstruire sans cache / mettre a jour les images |
| `make status` | Diagnostic : webcam, carte son, conteneurs, Bluetooth, flux |
| `make logs` / `logs-cam` / `logs-mic` | Logs en continu |
| `make bt` | Reconnecter l'enceinte |
| `make audio-fix` | Relancer pipewire + enceinte |
| `make usb-reset` | Reset du controleur USB (coupe aussi le Bluetooth) |
| `make speaker` | Bruit de test dans l'enceinte |
| `make level` | Niveau du son camera (viser -25 a -30 dB) |
| `make gain-cam GAIN=15` | Gain du son camera (dB) |
| `make sink-volume SINKVOL=60%` | Volume de l'enceinte |
| `make cron-install` / `cron-remove` / `cron-log` | Surveillance webcam |
Variables surchargeables : `BT_MAC`, `USER_ID`, `PCI_USB`, `GAIN`, `SINKVOL`.
## Reglages
- **Son camera trop faible/fort** : `make gain-cam GAIN=...` (12 par defaut, plage utile 8 a 20).
- **Echo** : eloigner l'enceinte de la webcam, baisser `make sink-volume SINKVOL=50%`.
- **Voix trop faible dans l'enceinte** : curseur Gain de la page, puis volume de l'enceinte.
## Depannage
| Symptome | Cause probable | Action |
|---|---|---|
| Pas d'image, `ERR [exec] timeout` | Webcam absente | `make status`; si `/dev/video*` absent : debrancher 30 s, rebrancher a l'arriere de la carte mere, `make restart` |
| `dmesg` : `error -110` / `-62` sur `usb 1-3` | Alimentation/cable/port USB | Cable court, port direct, hub alimente, autre port ; sinon webcam defectueuse |
| Image OK, pas de son camera | Son coupe par le navigateur ou gain trop bas | Cliquer sur la video ; `make level` |
| Micro : WebSocket refuse (302) | Access ne couvre pas `/mic/ws` | Verifier les deux destinations de l'application Access |
| Micro OK mais silence | Enceinte deconnectee | `make bt` ou `make audio-fix` ; `make speaker` pour tester |
| `404` sur `/stream.html` | Regle tunnel manquante ou mal ordonnee | `mic*` d'abord, la regle sans chemin en dernier |
| Boucle de 3 boutons dans la page | `/stream.html` route vers mic-bridge | Meme cause que ci-dessus |
| Plus de son apres redemarrage pipewire | Sink Bluetooth perdu | `make audio-fix` |
| Firefox : micro silencieux | AudioContext a 16 kHz refuse | Deja gere : la page utilise la frequence native du navigateur |
Journal de la surveillance : `make cron-log` (`/var/log/cam-watch.log`).
## Securite
- Aucun port publie : tout est joignable uniquement via le reseau docker et le tunnel.
- Cloudflare Access est la seule barriere d'authentification : ne jamais la desactiver.
- go2rtc tourne en `privileged` avec `/dev` monte pour survivre aux reenumerations USB.
Si la webcam devient stable, remplacer par `devices: [/dev/video0, /dev/snd]` + `group_add: [video, audio]`.
- Le conteneur mic-bridge monte `/run/user/1001` et le bus D-Bus pour piloter Bluetooth/Pulse.
## Sauvegarde et restauration
Tout est dans `/srv/apps/cam` (pas de volume de donnees). Sauvegarder ce dossier
(par exemple dans le depot git) et rejouer :
```bash ```bash
make host-setup && make up && make cron-install # Prérequis : Docker, Docker Compose, Node.js 20+, PulseAudio/PipeWire, BlueZ
# Enceinte BT appairée (MAC: 69:B2:C0:04:A4:80)
cp .env.example .env # adapter si besoin
make up-dev # démarre kai-sa-cam + kai-sa-go2rtc
``` ```
Accès : `http://localhost:8090` (via proxy Vite) ou via tunnel si configuré.
## Installation production (serveur)
```bash
# Sur le serveur
cd /srv/apps/kai-sa-cam
make up-prod
```
Le runner GitHub Actions `kai-sa-cam` déploie automatiquement sur push `main`.
## Variables d'environnement
| Variable | Défaut | Description |
|----------|--------|-------------|
| `TZ` | Europe/Paris | Fuseau horaire |
| `USER_ID` / `GROUP_ID` | 1001 | UID/GID pour volumes |
| `APP_ORIGIN` | https://kaisa.esiah.dev | Origine CORS |
| `MEDIA_DIR` | ./media | Stockage médias |
| `CONFIG_DIR` | ./config | Config go2rtc |
| `LOG_LEVEL` | info | Niveau de log |
| `MAX_RECORDING_MINUTES` | 120 | Durée max enregistrement |
| `DISK_MIN_FREE_GB` | 2 | Espace disque minimum |
| `GO2RTC_USERNAME` | kai-sa-cam | Auth go2rtc |
| `GO2RTC_PASSWORD` | - | Auth go2rtc |
| `BT_MAC` | 69:B2:C0:04:A4:80 | Adresse enceinte BT |
## Commandes Make
```bash
make up-dev # Démarre en dev (build + hot reload)
make down-dev # Arrête dev
make logs-dev # Logs dev
make up-prod # Démarre en prod
make down-prod # Arrête prod
make logs-prod # Logs prod
make status # État conteneurs
make restart # Redémarre services
```
## Sécurité
- **go2rtc** : non-privileged, `devices: [/dev/video0, /dev/snd]`, `cap_drop: ALL`, `no-new-privileges`, `read_only`
- **kai-sa-cam** : non-root (UID 1001), `cap_drop: ALL`, `no-new-privileges`, `read_only`, pas de D-Bus
- **Bluetooth** : géré via service hôte `kai-sa-cam-bt.service` (pas de D-Bus dans conteneurs)
- **Auth** : Cloudflare Access uniquement
## Stockage
- Tout dans `/media` (plat, pas de sous-dossiers)
- Enregistrements : `.mp4` (push-to-record manuel, max 120 min)
- Snapshots : `.jpg` (manuels)
- Export ZIP : supprime les fichiers **uniquement si le ZIP se termine sans erreur**
- Pas de rétention automatique, suppression manuelle possible
## Dépannage
| Symptôme | Action |
|----------|--------|
| Pas de vidéo | `make status`, vérifier `/dev/video0` |
| Pas de son caméra | Cliquer sur la vidéo, vérifier gain |
| Micro → enceinte ne marche pas | `make logs-cam`, vérifier Pulse/BT |
| Enregistrement ne démarre pas | Espace disque, `make logs-cam` |
## Déploiement
Le workflow GitHub Actions `.github/workflows/deploy.yml` tourne sur runner `self-hosted` label `kai-sa-cam` :
1. `git pull` sur `/srv/apps/kai-sa-cam`
2. `docker compose --profile prod build`
3. `docker compose --profile prod up -d`
4. `docker image prune -f`
+49
View File
@@ -0,0 +1,49 @@
# Build stage
FROM node:22-bookworm-slim AS build
WORKDIR /app
# Install build dependencies
RUN apt-get update && apt-get install -y --no-install-recommends \
python3 \
make \
g++ \
&& rm -rf /var/lib/apt/lists/*
COPY package*.json ./
RUN npm ci
COPY . .
RUN npm run build
# Prune dev dependencies
RUN npm prune --omit=dev
# Runtime stage
FROM node:22-bookworm-slim
RUN apt-get update && apt-get install -y --no-install-recommends \
ffmpeg \
pulseaudio-utils \
ca-certificates \
tzdata \
&& rm -rf /var/lib/apt/lists/*
WORKDIR /app
# Use existing node user (UID 1000) from base image
# The node user already exists with UID 1000/GID 1000
COPY --from=build /app/package.json ./
COPY --from=build /app/node_modules ./node_modules
COPY --from=build /app/dist ./dist
COPY --from=build /app/public ./public
USER node
EXPOSE 8090
ENV NODE_ENV=production
ENV PORT=8090
CMD ["node", "dist/server/index.cjs"]
+13
View File
@@ -0,0 +1,13 @@
<!DOCTYPE html>
<html lang="fr">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Kai-Sa-Cam</title>
<meta name="theme-color" content="#1a1a2e" />
</head>
<body>
<div id="root"></div>
<script type="module" src="/src/main.tsx"></script>
</body>
</html>
+4901
View File
File diff suppressed because it is too large Load Diff
+36
View File
@@ -0,0 +1,36 @@
{
"name": "kai-sa-cam",
"version": "1.0.0",
"type": "module",
"scripts": {
"dev": "vite",
"build": "tsc && vite build && esbuild src/server/index.ts --bundle --platform=node --format=cjs --outfile=dist/server/index.cjs --external:express --external:http-proxy-middleware --external:ws --external:archiver --external:ffmpeg-static",
"preview": "vite preview",
"server": "node --watch dist/server/index.cjs",
"start": "node dist/server/index.cjs"
},
"dependencies": {
"express": "^4.19.2",
"http-proxy-middleware": "^3.0.0",
"archiver": "^7.0.1",
"ws": "^8.17.0",
"ffmpeg-static": "^5.2.0"
},
"devDependencies": {
"@types/node": "^20.12.7",
"@types/express": "^4.17.21",
"@types/ws": "^8.5.10",
"@types/archiver": "^6.0.2",
"typescript": "^5.4.5",
"vite": "^5.2.11",
"@vitejs/plugin-react": "^4.2.1",
"react": "^18.3.1",
"react-dom": "^18.3.1",
"@types/react": "^18.3.2",
"@types/react-dom": "^18.3.0",
"tailwindcss": "^3.4.3",
"postcss": "^8.4.38",
"autoprefixer": "^10.4.19",
"esbuild": "^0.21.3"
}
}
+6
View File
@@ -0,0 +1,6 @@
export default {
plugins: {
tailwindcss: {},
autoprefixer: {},
},
}
+118
View File
@@ -0,0 +1,118 @@
import { useState, useEffect, useRef } from 'react'
import { VideoPlayer } from './components/VideoPlayer'
import { Controls } from './components/Controls'
import { MediaGallery } from './components/MediaGallery'
import { useRecorder } from './hooks/useRecorder'
import { useTalk } from './hooks/useTalk'
export function App() {
const [activeTab, setActiveTab] = useState<'live' | 'media'>('live')
const [isRecording, setIsRecording] = useState(false)
const [isTalking, setIsTalking] = useState(false)
const [gain, setGain] = useState(1)
const [recordingTime, setRecordingTime] = useState(0)
const [snapshots, setSnapshots] = useState<string[]>([])
const { startRecording, stopRecording, error: recError } = useRecorder({
onStart: () => { setIsRecording(true); setRecordingTime(0) },
onStop: () => { setIsRecording(false); setRecordingTime(0) },
onTimeUpdate: (t) => setRecordingTime(t),
})
const { startTalk, stopTalk, error: talkError } = useTalk({ gain })
const handleRecord = async () => {
if (isRecording) {
await stopRecording()
} else {
await startRecording()
}
}
const handleSnapshot = async () => {
try {
const res = await fetch('/api/media/snapshots', { method: 'POST' })
if (!res.ok) throw new Error('Snapshot failed')
const data = await res.json()
setSnapshots(prev => [data.filename, ...prev])
} catch (e) {
console.error('Snapshot error:', e)
}
}
const handleTalk = async () => {
if (isTalking) {
stopTalk()
setIsTalking(false)
} else {
await startTalk()
setIsTalking(true)
}
}
return (
<div className="min-h-screen bg-gray-900 text-white flex flex-col">
<header className="bg-gray-800 border-b border-gray-700 px-4 py-3 flex items-center justify-between">
<h1 className="text-xl font-semibold">Kai-Sa-Cam</h1>
<div className="flex items-center gap-4">
<div className="flex items-center gap-2">
<span className="text-sm text-gray-400">Gain</span>
<input
type="range"
min="0.2"
max="5"
step="0.1"
value={gain}
onChange={(e) => setGain(Number(e.target.value))}
className="w-32"
/>
</div>
</div>
</header>
<main className="flex-1 flex flex-col">
<nav className="flex border-b border-gray-700 bg-gray-800">
<button
className={`flex-1 py-3 text-center font-medium ${activeTab === 'live' ? 'text-blue-400 border-b-2 border-blue-400' : 'text-gray-400'}`}
onClick={() => setActiveTab('live')}
>
Live
</button>
<button
className={`flex-1 py-3 text-center font-medium ${activeTab === 'media' ? 'text-blue-400 border-b-2 border-blue-400' : 'text-gray-400'}`}
onClick={() => setActiveTab('media')}
>
Médias
</button>
</nav>
{activeTab === 'live' && (
<div className="flex-1 flex flex-col p-4 gap-4 overflow-hidden">
<VideoPlayer
streamUrl="/go2rtc/stream.html?src=webcam&mode=mse"
/>
<Controls
isRecording={isRecording}
recordingTime={recordingTime}
isTalking={isTalking}
gain={gain}
onRecord={handleRecord}
onSnapshot={handleSnapshot}
onTalk={handleTalk}
disabled={Boolean(recError || talkError)}
/>
{(recError || talkError) && (
<div className="text-red-400 text-sm text-center px-4">
{recError || talkError}
</div>
)}
</div>
)}
{activeTab === 'media' && (
<MediaGallery />
)}
</main>
</div>
)
}
@@ -0,0 +1,77 @@
interface ControlsProps {
isRecording: boolean
recordingTime: number
isTalking: boolean
gain: number
onRecord: () => void
onSnapshot: () => void
onTalk: () => void
disabled?: boolean
}
export function Controls({ isRecording, recordingTime, isTalking, gain, onRecord, onSnapshot, onTalk, disabled }: ControlsProps) {
const formatTime = (seconds: number) => {
const m = Math.floor(seconds / 60).toString().padStart(2, '0')
const s = (seconds % 60).toString().padStart(2, '0')
return `${m}:${s}`
}
return (
<div className="flex flex-col sm:flex-row items-center justify-center gap-4 p-4 bg-gray-800 rounded-lg border border-gray-700">
<div className="flex items-center gap-4">
<button
onClick={onRecord}
disabled={disabled}
className={`w-16 h-16 rounded-full flex items-center justify-center font-bold text-xl transition-colors ${
isRecording
? 'bg-red-600 text-white animate-pulse ring-4 ring-red-500/30'
: 'bg-gray-700 text-white hover:bg-gray-600'
} ${disabled ? 'opacity-50 cursor-not-allowed' : ''}`}
aria-label={isRecording ? 'Arrêter enregistrement' : 'Démarrer enregistrement'}
>
{isRecording ? '■' : '●'}
</button>
{isRecording && <span className="font-mono text-lg text-red-300">{formatTime(recordingTime)}</span>}
</div>
<div className="flex items-center gap-4">
<button
onClick={onSnapshot}
disabled={disabled}
className={`w-16 h-16 rounded-full flex items-center justify-center font-bold text-xl transition-colors bg-gray-700 text-white hover:bg-gray-600 ${disabled ? 'opacity-50 cursor-not-allowed' : ''}`}
aria-label="Capture instantanée"
>
📷
</button>
</div>
<div className="flex items-center gap-4">
<button
onClick={onTalk}
disabled={disabled}
className={`w-16 h-16 rounded-full flex items-center justify-center font-bold text-xl transition-colors ${
isTalking
? 'bg-green-600 text-white ring-4 ring-green-500/30'
: 'bg-gray-700 text-white hover:bg-gray-600'
} ${disabled ? 'opacity-50 cursor-not-allowed' : ''}`}
aria-label={isTalking ? 'Couper micro' : 'Activer micro'}
>
{isTalking ? '🎤' : '🎤'}
</button>
<div className="w-32">
<label className="block text-xs text-gray-400 mb-1">Gain micro</label>
<input
type="range"
min="0.2"
max="5"
step="0.1"
value={gain}
onChange={(e) => {}}
className="w-full"
disabled={disabled}
/>
</div>
</div>
</div>
)
}
@@ -0,0 +1,180 @@
import { useState, useEffect } from 'react'
interface MediaItem {
filename: string
type: 'video' | 'image'
size: number
mtime: string
url: string
}
export function MediaGallery() {
const [media, setMedia] = useState<MediaItem[]>([])
const [loading, setLoading] = useState(true)
const [exporting, setExporting] = useState(false)
const [error, setError] = useState<string | null>(null)
const fetchMedia = async () => {
try {
const res = await fetch('/api/media')
if (!res.ok) throw new Error('Failed to fetch media')
const data = await res.json()
setMedia(data)
} catch (e) {
console.error('Media fetch error:', e)
} finally {
setLoading(false)
}
}
useEffect(() => {
fetchMedia()
}, [])
const handleDownload = async (filename: string) => {
try {
const res = await fetch(`/api/media/${filename}?download=1`)
if (!res.ok) throw new Error('Download failed')
const blob = await res.blob()
const url = window.URL.createObjectURL(blob)
const a = document.createElement('a')
a.href = url
a.download = filename
a.click()
window.URL.revokeObjectURL(url)
} catch (e) {
console.error('Download error:', e)
setError('Téléchargement échoué')
}
}
const handleDelete = async (filename: string) => {
if (!confirm(`Supprimer ${filename} ?`)) return
try {
const res = await fetch(`/api/media/${filename}`, { method: 'DELETE' })
if (!res.ok) throw new Error('Delete failed')
setMedia(prev => prev.filter(m => m.filename !== filename))
} catch (e) {
console.error('Delete error:', e)
setError('Suppression échouée')
}
}
const handleExport = async () => {
setExporting(true)
setError(null)
try {
const res = await fetch('/api/media/export', { method: 'POST' })
if (!res.ok) throw new Error('Export failed')
const blob = await res.blob()
const url = window.URL.createObjectURL(blob)
const a = document.createElement('a')
a.href = url
a.download = `kai-sa-cam-media-${new Date().toISOString().split('T')[0]}.zip`
a.click()
window.URL.revokeObjectURL(url)
// After successful export, the server deletes the files, so refresh
fetchMedia()
} catch (e) {
console.error('Export error:', e)
setError('Export ZIP échoué')
} finally {
setExporting(false)
}
}
const formatSize = (bytes: number) => {
if (bytes < 1024) return `${bytes} B`
if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`
return `${(bytes / 1024 / 1024).toFixed(1)} MB`
}
const formatDate = (iso: string) => {
return new Date(iso).toLocaleString('fr-FR', {
day: '2-digit',
month: '2-digit',
year: 'numeric',
hour: '2-digit',
minute: '2-digit',
})
}
if (loading) {
return (
<div className="flex-1 flex items-center justify-center text-gray-400">
Chargement des médias...
</div>
)
}
return (
<div className="flex-1 flex flex-col p-4 gap-4 overflow-auto">
<div className="flex items-center justify-between">
<h2 className="text-xl font-semibold">Médias ({media.length})</h2>
<div className="flex gap-2">
<button
onClick={handleExport}
disabled={exporting || media.length === 0}
className="px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 disabled:opacity-50"
>
{exporting ? 'Export ZIP...' : 'Exporter ZIP (supprime après)'}
</button>
</div>
</div>
{error && (
<div className="text-red-400 text-sm mb-4 p-2 bg-red-900/20 rounded">
{error}
</div>
)}
{media.length === 0 ? (
<div className="flex-1 flex items-center justify-center text-gray-500">
Aucun média. Lancez un enregistrement ou une capture.
</div>
) : (
<div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-4">
{media.map((item) => (
<div key={item.filename} className="bg-gray-800 rounded-lg overflow-hidden border border-gray-700 flex flex-col">
{item.type === 'video' ? (
<video
src={item.url}
controls
className="w-full aspect-video bg-black"
preload="metadata"
/>
) : (
<img
src={item.url}
alt={item.filename}
className="w-full aspect-video object-cover bg-gray-900"
/>
)}
<div className="p-3 flex flex-col gap-2">
<div className="flex items-center justify-between text-sm">
<span className="truncate font-medium">{item.filename}</span>
<span className="text-gray-400">{formatSize(item.size)}</span>
</div>
<div className="text-xs text-gray-500">{formatDate(item.mtime)}</div>
<div className="flex gap-2">
<button
onClick={() => handleDownload(item.filename)}
className="flex-1 py-2 px-3 bg-blue-600 text-white rounded hover:bg-blue-700 text-sm"
>
Télécharger
</button>
<button
onClick={() => handleDelete(item.filename)}
className="flex-1 py-2 px-3 bg-red-600 text-white rounded hover:bg-red-700 text-sm"
>
Supprimer
</button>
</div>
</div>
</div>
))}
</div>
)}
</div>
)
}
@@ -0,0 +1,27 @@
import { useEffect, useRef } from 'react'
interface VideoPlayerProps {
streamUrl: string
}
export function VideoPlayer({ streamUrl }: VideoPlayerProps) {
const iframeRef = useRef<HTMLIFrameElement>(null)
useEffect(() => {
if (iframeRef.current) {
iframeRef.current.src = streamUrl
}
}, [streamUrl])
return (
<div className="flex-1 relative bg-black rounded-lg overflow-hidden">
<iframe
ref={iframeRef}
src={streamUrl}
className="w-full h-full border-none"
allow="autoplay; encrypted-media"
title="Flux caméra"
/>
</div>
)
}
+61
View File
@@ -0,0 +1,61 @@
import { useState, useCallback, useRef, useEffect } from 'react'
interface UseRecorderOptions {
onStart?: () => void
onStop?: () => void
onTimeUpdate?: (seconds: number) => void
}
export function useRecorder({ onStart, onStop, onTimeUpdate }: UseRecorderOptions) {
const [isRecording, setIsRecording] = useState(false)
const [error, setError] = useState<string | null>(null)
const intervalRef = useRef<number>()
const startTimeRef = useRef<number>()
const startRecording = useCallback(async () => {
setError(null)
try {
const res = await fetch('/api/recordings/start', { method: 'POST' })
if (!res.ok) {
const data = await res.json()
throw new Error(data.error || 'Failed to start recording')
}
setIsRecording(true)
startTimeRef.current = Date.now()
onStart?.()
intervalRef.current = window.setInterval(() => {
onTimeUpdate?.(Math.floor((Date.now() - (startTimeRef.current || Date.now())) / 1000))
}, 1000)
} catch (e) {
setError(e instanceof Error ? e.message : 'Erreur démarrage enregistrement')
}
}, [onStart, onTimeUpdate])
const stopRecording = useCallback(async () => {
setError(null)
try {
const res = await fetch('/api/recordings/stop', { method: 'POST' })
if (!res.ok) {
const data = await res.json()
throw new Error(data.error || 'Failed to stop recording')
}
setIsRecording(false)
if (intervalRef.current) {
clearInterval(intervalRef.current)
}
onStop?.()
} catch (e) {
setError(e instanceof Error ? e.message : 'Erreur arrêt enregistrement')
}
}, [onStop])
useEffect(() => {
return () => {
if (intervalRef.current) {
clearInterval(intervalRef.current)
}
}
}, [])
return { isRecording, error, startRecording, stopRecording }
}
+118
View File
@@ -0,0 +1,118 @@
import { useState, useCallback, useRef, useEffect } from 'react'
interface UseTalkOptions {
gain?: number
}
export function useTalk({ gain = 1 }: UseTalkOptions = {}) {
const [isTalking, setIsTalking] = useState(false)
const [error, setError] = useState<string | null>(null)
const wsRef = useRef<WebSocket | null>(null)
const mediaStreamRef = useRef<MediaStream | null>(null)
const audioContextRef = useRef<AudioContext | null>(null)
const workletNodeRef = useRef<AudioWorkletNode | null>(null)
const startTalk = useCallback(async () => {
setError(null)
try {
const stream = await navigator.mediaDevices.getUserMedia({
audio: {
echoCancellation: true,
noiseSuppression: true,
},
})
mediaStreamRef.current = stream
const audioContext = new AudioContext()
audioContextRef.current = audioContext
await audioContext.resume()
// Load the worklet for audio processing
const workletBlob = new Blob([`
class Processor extends AudioWorkletProcessor {
process(inputs) {
const input = inputs[0]
if (input.length > 0) {
const channel = input[0]
this.port.postMessage(channel.slice(0))
}
return true
}
}
registerProcessor('pcm-processor', Processor)
`], { type: 'application/javascript' })
const workletUrl = URL.createObjectURL(workletBlob)
await audioContext.audioWorklet.addModule(workletUrl)
const workletNode = new AudioWorkletNode(audioContext, 'pcm-processor')
workletNodeRef.current = workletNode
const source = audioContext.createMediaStreamSource(stream)
const gainNode = audioContext.createGain()
gainNode.gain.value = gain
source.connect(gainNode)
gainNode.connect(workletNode)
workletNode.connect(audioContext.destination)
// Connect to WebSocket
const protocol = location.protocol === 'https:' ? 'wss:' : 'ws:'
const ws = new WebSocket(`${protocol}//${location.host}/api/talk`)
wsRef.current = ws
ws.binaryType = 'arraybuffer'
ws.onopen = () => {
ws.send(JSON.stringify({ rate: audioContext.sampleRate, gain }))
}
ws.onerror = (e) => {
console.error('Talk WS error:', e)
setError('Erreur connexion micro')
stopTalk()
}
ws.onclose = () => {
if (isTalking) {
setError('Connexion micro perdue, reconnexion...')
// Could auto-reconnect here
}
}
workletNode.port.onmessage = (e) => {
if (ws.readyState === WebSocket.OPEN) {
ws.send(e.data)
}
}
setIsTalking(true)
} catch (e) {
setError(e instanceof Error ? e.message : 'Impossible d\'accéder au microphone')
}
}, [gain])
const stopTalk = useCallback(() => {
if (wsRef.current) {
wsRef.current.close()
wsRef.current = null
}
if (mediaStreamRef.current) {
mediaStreamRef.current.getTracks().forEach(t => t.stop())
mediaStreamRef.current = null
}
if (audioContextRef.current) {
audioContextRef.current.close()
audioContextRef.current = null
}
workletNodeRef.current = null
setIsTalking(false)
}, [])
useEffect(() => {
return () => {
stopTalk()
}
}, [stopTalk])
return { isTalking, error, startTalk, stopTalk }
}
+24
View File
@@ -0,0 +1,24 @@
@tailwind base;
@tailwind components;
@tailwind utilities;
* {
box-sizing: border-box;
}
body {
margin: 0;
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
background: #111;
color: #eee;
}
@layer utilities {
.no-scrollbar::-webkit-scrollbar {
display: none;
}
.no-scrollbar {
-ms-overflow-style: none;
scrollbar-width: none;
}
}
+10
View File
@@ -0,0 +1,10 @@
import React from 'react'
import ReactDOM from 'react-dom/client'
import { App } from './App'
import './index.css'
ReactDOM.createRoot(document.getElementById('root')!).render(
<React.StrictMode>
<App />
</React.StrictMode>
)
+9
View File
@@ -0,0 +1,9 @@
import { Router, Response } from 'express'
const router = Router()
router.get('/health', async (req, res: Response) => {
res.json({ status: 'ok', service: 'kai-sa-cam', timestamp: new Date().toISOString() })
})
export { router as healthRouter }
+103
View File
@@ -0,0 +1,103 @@
import express from 'express'
import { createProxyMiddleware } from 'http-proxy-middleware'
import { createServer } from 'http'
import { WebSocketServer, WebSocket } from 'ws'
import { spawn, ChildProcessWithoutNullStreams } from 'child_process'
import { join } from 'path'
import { recorderRouter } from './recorder.js'
import { mediaRouter } from './media.js'
import { talkRouter } from './talk.js'
import { healthRouter } from './health.js'
// Use process.cwd() instead of import.meta.url for bundled compatibility
const __dirname = process.cwd()
const app = express()
const PORT = process.env.PORT || 8090
// Middleware
app.use(express.json({ limit: '10mb' }))
app.use(express.urlencoded({ extended: true }))
// Serve static files (built React app)
app.use(express.static(join(__dirname, 'dist')))
// Proxy go2rtc requests
const proxyConfig = {
target: process.env.GO2RTC_URL || 'http://kai-sa-go2rtc:1984',
changeOrigin: true,
ws: true,
onProxyReq: (proxyReq: any, _req: any, _res: any) => {
// Add basic auth if credentials provided
const user = process.env.GO2RTC_USERNAME
const pass = process.env.GO2RTC_PASSWORD
if (user && pass) {
const auth = Buffer.from(`${user}:${pass}`).toString('base64')
proxyReq.setHeader('Authorization', `Basic ${auth}`)
}
},
}
app.use('/go2rtc', createProxyMiddleware(proxyConfig))
// API routes
app.use('/api/recordings', recorderRouter)
app.use('/api/media', mediaRouter)
app.use('/api/talk', talkRouter)
app.use('/api', healthRouter)
// SPA fallback - serve index.html for non-API routes
app.get('*', (req, res, next) => {
if (req.path.startsWith('/api') || req.path.startsWith('/go2rtc')) {
return next()
}
res.sendFile(join(__dirname, 'dist/index.html'))
})
const server = createServer(app)
// WebSocket server for talk
const wss = new WebSocketServer({ server, path: '/api/talk' })
wss.on('connection', (ws: WebSocket, _req) => {
console.log('Talk WS connection established')
let paplayProcess: ChildProcessWithoutNullStreams | null = null
ws.on('message', (data: Buffer | string, isBinary: boolean) => {
if (!isBinary) {
try {
const msg = JSON.parse(data.toString())
if (msg.rate && !paplayProcess) {
// Start paplay
paplayProcess = spawn('paplay', [
'--raw',
`--rate=${msg.rate}`,
'--format=s16le',
'--channels=1',
'--latency-msec=150',
])
paplayProcess.on('error', (e: Error) => console.error('paplay error:', e.message))
}
} catch (e) {
console.error('Talk WS message parse error:', e)
}
return
}
if (paplayProcess?.stdin) {
paplayProcess.stdin.write(data)
}
})
ws.on('close', () => {
if (paplayProcess) {
paplayProcess.stdin.end()
paplayProcess = null
}
})
})
server.listen(PORT, () => {
console.log(`kai-sa-cam server running on port ${PORT}`)
})
+240
View File
@@ -0,0 +1,240 @@
import { Router, Request, Response } from 'express'
import { readdirSync, statSync, unlinkSync, createReadStream, existsSync } from 'fs'
import { join, extname } from 'path'
import { pipeline } from 'stream/promises'
import archiver from 'archiver'
const router = Router()
const MEDIA_DIR = process.env.MEDIA_DIR || '/media'
const CONFIG_DIR = process.env.CONFIG_DIR || '/config'
// Ensure media directory exists
if (!existsSync(MEDIA_DIR)) {
require('fs').mkdirSync(MEDIA_DIR, { recursive: true })
}
function getMediaType(filename: string): 'video' | 'image' | 'other' {
const ext = extname(filename).toLowerCase()
if (['.mp4', '.webm', '.mov', '.mkv'].includes(ext)) return 'video'
if (['.jpg', '.jpeg', '.png', '.webp', '.bmp'].includes(ext)) return 'image'
return 'other'
}
// GET /api/media
router.get('/', async (req: Request, res: Response) => {
try {
const files = readdirSync(MEDIA_DIR)
const media = files
.filter(f => getMediaType(f) !== 'other')
.map(filename => {
const filepath = join(MEDIA_DIR, filename)
const stats = statSync(filepath)
return {
filename,
type: getMediaType(filename),
size: stats.size,
mtime: stats.mtime.toISOString(),
url: `/api/media/${filename}`,
}
})
.sort((a, b) => new Date(b.mtime).getTime() - new Date(a.mtime).getTime())
res.json(media)
} catch (e) {
console.error('Media list error:', e)
res.status(500).json({ error: 'Failed to list media' })
}
})
// GET /api/media/:filename
router.get('/:filename', async (req: Request, res: Response) => {
const { filename } = req.params
const filepath = join(MEDIA_DIR, filename)
if (!existsSync(filepath)) {
return res.status(404).json({ error: 'File not found' })
}
// Security: prevent directory traversal
const resolved = require('path').resolve(filepath)
if (!resolved.startsWith(require('path').resolve(MEDIA_DIR))) {
return res.status(403).json({ error: 'Forbidden' })
}
const stats = statSync(filepath)
const download = req.query.download === '1'
if (download) {
res.setHeader('Content-Disposition', `attachment; filename="${filename}"`)
}
res.setHeader('Content-Length', stats.size)
res.setHeader('Accept-Ranges', 'bytes')
// Handle range requests for video seeking
const range = req.headers.range
if (range) {
const parts = range.replace(/bytes=/, '').split('-')
const start = parseInt(parts[0], 10)
const end = parts[1] ? parseInt(parts[1], 10) : stats.size - 1
const chunksize = (end - start) + 1
res.status(206)
res.setHeader('Content-Range', `bytes ${start}-${end}/${stats.size}`)
res.setHeader('Content-Length', chunksize)
const stream = createReadStream(filepath, { start, end })
return stream.pipe(res)
}
const stream = createReadStream(filepath)
stream.pipe(res)
})
// POST /api/snapshots
router.post('/snapshots', async (req: Request, res: Response) => {
const { spawn } = await import('child_process')
const GO2RTC_RTSP_URL = process.env.GO2RTC_RTSP_URL || 'rtsp://kai-sa-go2rtc:8554/webcam'
const MEDIA_DIR = process.env.MEDIA_DIR || '/media'
const timestamp = new Date().toISOString().replace(/[:.]/g, '-').split('T').join('_')
const filename = `snapshot_${timestamp}.jpg`
const filepath = join(MEDIA_DIR, filename)
const ffmpegPath = process.env.FFMPEG_PATH || 'ffmpeg'
const args = [
'-hide_banner',
'-loglevel', 'warning',
'-rtsp_transport', 'tcp',
'-i', GO2RTC_RTSP_URL,
'-frames:v', '1',
'-q:v', '2',
'-update', '1',
filepath,
]
const child = spawn(ffmpegPath, args)
return new Promise<void>((resolve, reject) => {
let stderr = ''
child.stderr?.on('data', (data) => {
stderr += data.toString()
})
child.on('close', (code) => {
if (code === 0) {
res.json({ filename })
resolve()
} else {
console.error('Snapshot ffmpeg failed:', stderr)
res.status(500).json({ error: 'Snapshot failed', details: stderr })
reject(new Error('Snapshot failed'))
}
})
child.on('error', (err) => {
res.status(500).json({ error: 'Snapshot error', details: err.message })
reject(err)
})
})
})
// DELETE /api/media/:filename
router.delete('/:filename', async (req: Request, res: Response) => {
const { filename } = req.params
const filepath = join(MEDIA_DIR, filename)
if (!existsSync(filepath)) {
return res.status(404).json({ error: 'File not found' })
}
// Security check
const resolved = require('path').resolve(filepath)
if (!resolved.startsWith(require('path').resolve(MEDIA_DIR))) {
return res.status(403).json({ error: 'Forbidden' })
}
try {
unlinkSync(filepath)
res.json({ status: 'deleted' })
} catch (e) {
console.error('Delete error:', e)
res.status(500).json({ error: 'Failed to delete' })
}
})
// POST /api/media/export - Create ZIP of all media and stream it
router.post('/export', async (req: Request, res: Response) => {
try {
const files = readdirSync(MEDIA_DIR)
.filter(f => getMediaType(f) !== 'other')
if (files.length === 0) {
return res.status(404).json({ error: 'No media to export' })
}
const archive = archiver('zip', { zlib: { level: 9 } })
let completed = false
let aborted = false
res.setHeader('Content-Type', 'application/zip')
res.setHeader('Content-Disposition', `attachment; filename="kai-sa-cam-media-${new Date().toISOString().split('T')[0]}.zip"`)
archive.on('error', (err) => {
console.error('Archive error:', err)
if (!completed) {
res.status(500).json({ error: 'Archive creation failed' })
}
})
archive.on('end', () => {
completed = true
console.log('Archive completed')
// Delete files after successful archive completion
setTimeout(() => {
for (const file of files) {
try {
const filepath = join(MEDIA_DIR, file)
if (existsSync(filepath)) {
unlinkSync(filepath)
console.log(`Deleted after export: ${file}`)
}
} catch (e) {
console.error(`Failed to delete ${file}:`, e)
}
}
}, 100)
})
req.on('aborted', () => {
aborted = true
console.log('Export aborted by client')
})
res.on('close', () => {
if (!res.writableFinished) {
aborted = true
console.log('Export connection closed prematurely')
}
})
archive.pipe(res)
for (const file of files) {
const filepath = join(MEDIA_DIR, file)
if (existsSync(filepath)) {
archive.file(filepath, { name: file })
}
}
await archive.finalize()
} catch (e) {
console.error('Export error:', e)
if (!res.headersSent) {
res.status(500).json({ error: 'Export failed' })
}
}
})
export { router as mediaRouter }
+10
View File
@@ -0,0 +1,10 @@
import { Router, Response } from 'express'
const router = Router()
// GET /api/talk/status
router.get('/status', async (req, res: Response) => {
res.json({ status: 'ok', message: 'Talk endpoint available at /api/talk WebSocket' })
})
export { router as talkRouter }
+11
View File
@@ -0,0 +1,11 @@
/** @type {import('tailwindcss').Config} */
export default {
content: [
"./index.html",
"./src/**/*.{js,ts,jsx,tsx}",
],
theme: {
extend: {},
},
plugins: [],
}
+22
View File
@@ -0,0 +1,22 @@
{
"compilerOptions": {
"target": "ES2022",
"lib": ["ES2022", "DOM", "DOM.Iterable"],
"module": "ESNext",
"moduleResolution": "bundler",
"jsx": "react-jsx",
"strict": true,
"noEmit": true,
"esModuleInterop": true,
"skipLibCheck": true,
"forceConsistentCasingInFileNames": true,
"resolveJsonModule": true,
"isolatedModules": true,
"baseUrl": ".",
"paths": {
"@/*": ["src/*"]
}
},
"include": ["src", "vite.config.ts"],
"exclude": ["node_modules", "dist"]
}
+27
View File
@@ -0,0 +1,27 @@
import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'
import path from 'path'
import { fileURLToPath } from 'url'
const __dirname = path.dirname(fileURLToPath(import.meta.url))
export default defineConfig({
plugins: [react()],
resolve: {
alias: {
'@': path.resolve(__dirname, './src'),
},
},
build: {
outDir: 'dist',
sourcemap: true,
},
server: {
port: 5173,
proxy: {
'/api': 'http://localhost:8090',
'/ws': 'http://localhost:8090',
'/go2rtc': 'http://localhost:1984',
},
},
})
+26
View File
@@ -0,0 +1,26 @@
log:
level: info
api:
listen: ":1984"
username: ${GO2RTC_USERNAME}
password: ${GO2RTC_PASSWORD}
allow_paths:
- /api
- /api/ws
- /stream.html
- /video-stream.js
- /video-rtc.js
local_auth: false
rtsp:
listen: ":8554"
username: ""
password: ""
streams:
webcam:
- "exec:ffmpeg -hide_banner -loglevel warning -f v4l2 -video_size 640x480 -framerate 15 -i /dev/video0 -thread_queue_size 512 -c:v libx264 -preset ultrafast -tune zerolatency -profile:v baseline -pix_fmt yuv420p -g 30 -f rtsp {output}"
ffmpeg:
global: "-hide_banner -loglevel warning"
+64 -21
View File
@@ -1,29 +1,72 @@
name: cam name: kai-sa-cam
services: services:
go2rtc: kai-sa-go2rtc:
image: alexxit/go2rtc image: alexxit/go2rtc:1.9.9
container_name: go2rtc container_name: kai-sa-go2rtc
restart: unless-stopped profiles: ["dev", "prod"]
privileged: true # survit aux ré-énumérations USB (video0/video1)
volumes:
- /dev:/dev
- ./go2rtc.yaml:/config/go2rtc.yaml:ro
networks: [shared-network]
mic-bridge:
build: ./mic-bridge
container_name: mic-bridge
restart: unless-stopped restart: unless-stopped
environment: environment:
BT_MAC: "69:B2:C0:04:A4:80" - GO2RTC_USERNAME=${GO2RTC_USERNAME:-kai-sa-cam}
PULSE_SERVER: "unix:/run/user/1001/pulse/native" - GO2RTC_PASSWORD=${GO2RTC_PASSWORD:-}
SINK_VOLUME: "70%" devices:
- /dev/video0:/dev/video0
- /dev/snd:/dev/snd
volumes: volumes:
- /run/user/1001:/run/user/1001 - ./config/kai-sa-go2rtc.yaml:/config/go2rtc.yaml:ro
- /var/run/dbus:/var/run/dbus networks:
networks: [shared-network] - kai-sa-cam-internal
cap_drop:
- ALL
security_opt:
- no-new-privileges:true
read_only: true
tmpfs:
- /tmp
kai-sa-cam:
build:
context: ./apps/kai-sa-cam
dockerfile: Dockerfile
container_name: kai-sa-cam
profiles: ["dev", "prod"]
restart: unless-stopped
environment:
- TZ=${TZ:-Europe/Paris}
- USER_ID=${USER_ID:-1000}
- GROUP_ID=${GROUP_ID:-1000}
- APP_ORIGIN=${APP_ORIGIN:-https://kaisa.esiah.dev}
- MEDIA_DIR=/media
- CONFIG_DIR=/config
- LOG_LEVEL=${LOG_LEVEL:-info}
- MAX_RECORDING_MINUTES=${MAX_RECORDING_MINUTES:-120}
- DISK_MIN_FREE_GB=${DISK_MIN_FREE_GB:-2}
- GO2RTC_URL=http://kai-sa-go2rtc:1984
- GO2RTC_RTSP_URL=rtsp://kai-sa-cam@kai-sa-go2rtc:8554/webcam
- GO2RTC_USERNAME=${GO2RTC_USERNAME:-kai-sa-cam}
- GO2RTC_PASSWORD=${GO2RTC_PASSWORD:-}
- PULSE_SERVER=unix:/run/user/1001/pulse/native
- XDG_RUNTIME_DIR=/run/user/1001
volumes:
- ./media:/media
- ./config:/config
- /run/user/1001/pulse/native:/run/user/1001/pulse/native
networks:
- kai-sa-cam-internal
- kai-sa-cam-tunnel
cap_drop:
- ALL
security_opt:
- no-new-privileges:true
read_only: true
tmpfs:
- /tmp
- /var/cache
init: true
networks: networks:
shared-network: kai-sa-cam-internal:
internal: true
kai-sa-cam-tunnel:
external: true external: true
name: kai-sa-cam-tunnel
-10
View File
@@ -1,10 +0,0 @@
log:
level: debug
exec: debug
api:
listen: ":1984"
streams:
webcam:
- "exec:ffmpeg -hide_banner -loglevel warning -f v4l2 -video_size 640x480 -framerate 15 -i /dev/video0 -thread_queue_size 512 -f alsa -ac 1 -ar 16000 -i hw:CARD=webcam,DEV=0 -c:v libx264 -preset ultrafast -tune zerolatency -profile:v baseline -pix_fmt yuv420p -g 30 -c:a aac -b:a 64k -af aresample=async=1,highpass=f=80,volume=20dB,alimiter=limit=0.95 -f rtsp {output}"