73 lines
2.8 KiB
JavaScript
73 lines
2.8 KiB
JavaScript
'use strict';
|
||
|
||
const express = require('express');
|
||
const http = require('http');
|
||
const path = require('path');
|
||
const { createSnapshotRouter } = require('./src/snapshotService');
|
||
|
||
const PORT = parseInt(process.env.PORT ?? '8444', 10);
|
||
const GO2RTC_URL = process.env.GO2RTC_URL ?? 'http://localhost:1984';
|
||
|
||
const app = express();
|
||
|
||
app.use(express.static(path.join(__dirname, 'public')));
|
||
app.use('/api/snapshot', createSnapshotRouter(GO2RTC_URL));
|
||
|
||
// ── WebRTC signaling proxy ────────────────────────────────────────────────────
|
||
// Browser postet SDP-Offer hierher; wir leiten es an go2rtc weiter und
|
||
// geben die SDP-Answer zurück. Nur ein HTTP-Port nach aussen nötig.
|
||
app.post(
|
||
'/api/webrtc',
|
||
express.text({ type: 'application/sdp', limit: '64kb' }),
|
||
async (req, res) => {
|
||
const src = req.query.src ?? '';
|
||
try {
|
||
const upstream = await fetch(
|
||
`${GO2RTC_URL}/api/webrtc?src=${encodeURIComponent(src)}`,
|
||
{
|
||
method: 'POST',
|
||
headers: { 'Content-Type': 'application/sdp' },
|
||
body: req.body,
|
||
}
|
||
);
|
||
if (!upstream.ok) {
|
||
const msg = await upstream.text();
|
||
return res.status(upstream.status).send(msg);
|
||
}
|
||
const answer = await upstream.text();
|
||
res.set('Content-Type', 'application/sdp');
|
||
res.send(answer);
|
||
} catch (err) {
|
||
res.status(503).json({ error: `go2rtc nicht erreichbar: ${err.message}` });
|
||
}
|
||
}
|
||
);
|
||
|
||
// ── Health ────────────────────────────────────────────────────────────────────
|
||
app.get('/health', async (_req, res) => {
|
||
let go2rtcOk = false;
|
||
try {
|
||
const r = await fetch(`${GO2RTC_URL}/api/streams`);
|
||
go2rtcOk = r.ok;
|
||
} catch { /* not reachable */ }
|
||
|
||
res.json({ status: go2rtcOk ? 'ok' : 'degraded', go2rtc: go2rtcOk });
|
||
});
|
||
|
||
// ── Start ─────────────────────────────────────────────────────────────────────
|
||
const server = http.createServer(app);
|
||
|
||
server.listen(PORT, '0.0.0.0', () => {
|
||
console.log(`AppRobotWebcam on http://0.0.0.0:${PORT}`);
|
||
console.log(` go2rtc backend: ${GO2RTC_URL}`);
|
||
console.log(` WebRTC signaling proxy: POST /api/webrtc?src=cam0`);
|
||
console.log(` Snapshot API: GET /api/snapshot/cam0`);
|
||
});
|
||
|
||
const shutdown = (sig) => {
|
||
console.log(`\n${sig} – shutting down`);
|
||
server.close(() => process.exit(0));
|
||
};
|
||
process.on('SIGINT', () => shutdown('SIGINT'));
|
||
process.on('SIGTERM', () => shutdown('SIGTERM'));
|