diff --git a/gateway/src/config.ts b/gateway/src/config.ts index 8534743..b14e4ae 100644 --- a/gateway/src/config.ts +++ b/gateway/src/config.ts @@ -39,6 +39,7 @@ export const SETTINGS: Setting[] = [ { group: "Connect dialog", staticOnly: true, key: "DEFAULT_SERVER", kind: "text", help: "Server address prefilled in the connect dialog." }, { group: "Connect dialog", staticOnly: true, key: "DEFAULT_CHANNEL", kind: "text", help: "Channel prefilled in the connect dialog." }, { group: "Connect dialog", staticOnly: true, key: "SYNC_URL", kind: "text", help: "Own account-sync server (sync-server.js). Empty = the official one." }, + { group: "Connections & limits", key: "IDLE_TIMEOUT_MINUTES", kind: "number", fallback: "0", help: "Ask \"Are you still there?\" after this many minutes without input in the client; no answer within 60 s disconnects (0 = off)." }, { group: "Features", key: "FEEDBACK_ENABLED", kind: "bool", fallback: "0", help: "Accept in-app feedback (/api/feedback)." }, { group: "Features", key: "STORE_ENABLED", kind: "bool", fallback: "0", help: "Run the Design Store (theme submissions and downloads)." }, { group: "Features", key: "LOG_CONNECTIONS", kind: "bool", fallback: "0", help: "Log connects/disconnects (hashed client tags, no plain IPs)." }, diff --git a/gateway/src/index.ts b/gateway/src/index.ts index f11d75d..0f1ddb4 100644 --- a/gateway/src/index.ts +++ b/gateway/src/index.ts @@ -624,8 +624,17 @@ const HEARTBEAT_INTERVAL_MS = 20_000; interface HeartbeatState { isAlive: boolean; + /** Last "active" message (user input in the page) or connect. */ + lastActive: number; } +/** IDLE_TIMEOUT_MINUTES in ms, 0 = off. Read per check, the admin panel changes it live. */ +const idleTimeoutMs = () => Math.max(0, Number(process.env.IDLE_TIMEOUT_MINUTES) || 0) * 60_000; +// The page asks "Are you still there?" after the timeout and waits 60 s; the +// gateway only steps in after that plus slack, for pages that never asked +// (outdated or modified). Throttled "active" messages keep it away. +const IDLE_GRACE_MS = 3 * 60_000; + const heartbeats = new WeakMap(); // Tracked so SIGTERM (below) can tell every live TS3/TeaSpeak session to @@ -647,6 +656,15 @@ const heartbeatTimer = setInterval(() => { socket.terminate(); continue; } + const idleMs = idleTimeoutMs(); + if (idleMs > 0 && Date.now() - state.lastActive > idleMs + IDLE_GRACE_MS) { + // Close handler disconnects the TS session; the message tells the page + // this was deliberate, so it doesn't auto-reconnect. + socket.send('{"type":"idleTimeout"}'); + socket.close(4000, "idle"); + heartbeats.delete(socket); + continue; + } state.isAlive = false; socket.ping(); // Protocol pings are invisible to browser JS; this lets the page notice @@ -730,9 +748,16 @@ wss.on("connection", (socket: WebSocket, req: IncomingMessage) => { // pulled, so the browser must not assume a feature exists just because it // knows about it. A gateway without "hello" (before v0.15) supports the // v0.14 feature set, streaming included; anything newer gets a name here. - socket.send(JSON.stringify({ type: "hello", features: gatewayFeatures(), iceServers: turnServers() })); + socket.send( + JSON.stringify({ + type: "hello", + features: gatewayFeatures(), + iceServers: turnServers(), + idleTimeoutMinutes: idleTimeoutMs() / 60_000, + }), + ); - heartbeats.set(socket, { isAlive: true }); + heartbeats.set(socket, { isAlive: true, lastActive: Date.now() }); socket.on("pong", () => { const state = heartbeats.get(socket); if (state) state.isAlive = true; @@ -764,6 +789,11 @@ wss.on("connection", (socket: WebSocket, req: IncomingMessage) => { } async function handleMessage(msg: any): Promise { + if (msg.type === "active" || msg.type === "connect") { + const state = heartbeats.get(socket); + if (state) state.lastActive = Date.now(); + if (msg.type === "active") return; + } switch (msg.type) { case "connect": { if (!isValidHost(msg.host) || !isValidNickname(msg.nickname)) { diff --git a/web/src/App.css b/web/src/App.css index 292aea1..17fe83e 100644 --- a/web/src/App.css +++ b/web/src/App.css @@ -26,7 +26,6 @@ --log-bg: #f7f8f9; --log-text: #333; --log-error: #b3261e; - --alpha-badge: #a15c07; display: flex; flex-direction: column; @@ -72,7 +71,6 @@ --log-bg: #202124; --log-text: #c7c9cc; --log-error: #f2867a; - --alpha-badge: #e0a23c; color-scheme: dark; } @@ -116,7 +114,6 @@ --log-bg: oklch(0.17 0.014 258); --log-text: oklch(0.62 0.014 258); --log-error: oklch(0.68 0.16 25); - --alpha-badge: oklch(0.75 0.14 70); color-scheme: dark; font-family: "Manrope", ui-sans-serif, system-ui, -apple-system, "Segoe UI", sans-serif; } @@ -865,7 +862,6 @@ --log-bg: oklch(0.155 0.018 290); --log-text: oklch(0.64 0.014 290); --log-error: oklch(0.68 0.16 25); - --alpha-badge: oklch(0.75 0.14 70); color-scheme: dark; font-family: "Manrope", ui-sans-serif, system-ui, -apple-system, "Segoe UI", sans-serif; } @@ -1511,30 +1507,6 @@ /* Deliberately loud: the feature speaks an undocumented TS6 protocol, so the user should never be in doubt that it is experimental. */ -.ts-alpha-badge { - display: inline-block; - padding: 0 0.35em; - border: 1px solid var(--alpha-badge); - border-radius: 3px; - color: var(--alpha-badge); - font-size: 0.7em; - font-weight: 700; - letter-spacing: 0.06em; - text-transform: uppercase; - vertical-align: middle; - white-space: nowrap; -} - -.ts-alpha-note { - margin: 0 0 0.75rem; - padding: 0.5rem 0.6rem; - border-left: 3px solid var(--alpha-badge); - background: var(--log-bg); - color: var(--text-muted); - font-size: 0.85em; - line-height: 1.4; -} - .ts-stream-panel-close { padding: 0 0.35rem; background: none; diff --git a/web/src/App.tsx b/web/src/App.tsx index 712c74c..eab65c1 100644 --- a/web/src/App.tsx +++ b/web/src/App.tsx @@ -2616,6 +2616,32 @@ function AboutDialog({ onClose }: { onClose: () => void }) { ); } +/** Seconds the "Are you still there?" dialog waits before disconnecting. */ +const IDLE_CHECK_SECONDS = 60; + +function IdleCheckDialog({ secondsLeft, onStay }: { secondsLeft: number; onStay: () => void }) { + const t = useT(); + return ( +
+
e.stopPropagation()}> +
+ {t("idleCheck.title")} +
+
+

{t("idleCheck.body", { seconds: String(secondsLeft) })}

+
+
+
+ +
+
+
+
+ ); +} + function RestartNoticeDialog({ message, onAck }: { message: string; onAck: () => void }) { const t = useT(); return ( @@ -2766,18 +2792,6 @@ const RESOLUTION_CHOICES = [360, 480, 720, 1080, 1440, 0]; const FPS_CHOICES = [5, 30, 60]; const AUDIO_BITRATE_CHOICES = [64, 96, 128, 192, 256, 320]; -// Streaming talks to TS6 over a protocol nobody published, so it is marked -// alpha everywhere the user can reach it: the settings dialog, both stream -// panels, and the toolbar button's tooltip. -function AlphaBadge() { - const t = useT(); - return ( - - {t("publish.alpha")} - - ); -} - function SegmentedChoice({ value, options, @@ -2857,14 +2871,13 @@ function StreamSettingsDialog({
e.stopPropagation()}>
- {t("publish.dialog.title")} + {t("publish.dialog.title")}
-

{t("publish.alphaNote")}

{t("publish.dialog.basic")}

@@ -9047,6 +9060,12 @@ function AppInner() { const [gatewayFeatures, setGatewayFeatures] = useState>(new Set()); // TURN relay the gateway offers for screen streams (TURN_URLS), if any. const [turnServers, setTurnServers] = useState([]); + // IDLE_TIMEOUT_MINUTES from the hello; 0 = the gateway never asks. + const [idleTimeoutMin, setIdleTimeoutMin] = useState(0); + const lastActivityRef = useRef(Date.now()); + // Countdown of the "Are you still there?" dialog, null while it is closed. + const [idleCheckLeft, setIdleCheckLeft] = useState(null); + const [idleDisconnected, setIdleDisconnected] = useState(false); // Terms of use, own-hosted instance only (see IS_OWN_HOSTED_INSTANCE): shown // mandatorily on first visit, reopenable any time from the menu afterwards. const [tosOpen, setTosOpen] = useState(false); @@ -10180,6 +10199,14 @@ function AppInner() { if (data.type === "hello") { setGatewayFeatures(new Set(Array.isArray(data.features) ? data.features : [])); setTurnServers(Array.isArray(data.iceServers) ? data.iceServers : []); + setIdleTimeoutMin(Math.max(0, Number(data.idleTimeoutMinutes) || 0)); + return; + } + if (data.type === "idleTimeout") { + // The gateway dropped us for inactivity: deliberate, no auto-reconnect. + setIdleCheckLeft(null); + handleDisconnectAll(); + setIdleDisconnected(true); return; } if (data.type === "turnstileRequired") { @@ -12911,6 +12938,62 @@ function AppInner() { } if (ownMicClicks && !outputMuted) void notify(selfTalking ? "SPECIAL_MIC_CLICK_SELF_ON" : "SPECIAL_MIC_CLICK_SELF_OFF"); }, [selfTalking]); // eslint-disable-line react-hooks/exhaustive-deps + + // "Are you still there?": input in the main window or the stream pop-out, + // talking and broadcasting all count as activity. After IDLE_TIMEOUT_MINUTES + // without any, ask; no answer within IDLE_CHECK_SECONDS disconnects all tabs. + // ponytail: enforced by the client only, a modified client can skip it. + useEffect(() => { + const bump = () => { + lastActivityRef.current = Date.now(); + }; + const targets: Window[] = streamPopout ? [window, streamPopout] : [window]; + const events = ["pointerdown", "keydown", "wheel", "touchstart"]; + for (const w of targets) for (const e of events) w.addEventListener(e, bump, { passive: true }); + return () => { + for (const w of targets) for (const e of events) w.removeEventListener(e, bump); + }; + }, [streamPopout]); + const keepAwakeRef = useRef(false); + useEffect(() => { + keepAwakeRef.current = selfTalking || publishersRef.current.size > 0; + }); + const connectedTabs = sessionTabs.length; + // Tells the gateway, at most once a minute, that someone is here - it + // enforces the timeout too, for pages that don't ask. + const activeSentRef = useRef(0); + const sendActive = () => { + activeSentRef.current = Date.now(); + for (const rec of sessionsRef.current.values()) + if (rec.socket?.readyState === WebSocket.OPEN) rec.socket.send('{"type":"active"}'); + }; + useEffect(() => { + if (!idleTimeoutMin || connectedTabs === 0) return; + lastActivityRef.current = Math.max(lastActivityRef.current, Date.now() - 1000); + const timer = window.setInterval(() => { + if (keepAwakeRef.current) lastActivityRef.current = Date.now(); + if (lastActivityRef.current > activeSentRef.current && Date.now() - activeSentRef.current > 60_000) sendActive(); + if (Date.now() - lastActivityRef.current > idleTimeoutMin * 60_000) + setIdleCheckLeft((left) => left ?? IDLE_CHECK_SECONDS); + }, 10_000); + return () => window.clearInterval(timer); + }, [idleTimeoutMin, connectedTabs]); + useEffect(() => { + if (idleCheckLeft === null) return; + if (connectedTabs === 0) { + setIdleCheckLeft(null); + return; + } + if (idleCheckLeft <= 0) { + setIdleCheckLeft(null); + handleDisconnectAll(); + setIdleDisconnected(true); + return; + } + const timer = window.setTimeout(() => setIdleCheckLeft((left) => (left === null ? null : left - 1)), 1000); + return () => window.clearTimeout(timer); + // eslint-disable-next-line react-hooks/exhaustive-deps + }, [idleCheckLeft, connectedTabs]); const showServerQueryClients = activeFavoriteId != null && favorites.some((f) => f.id === activeFavoriteId && f.showServerQueryClients); @@ -12956,7 +13039,7 @@ function AppInner() { const micLabel = !micOn ? t("toolbar.micEnable") : inputMuted ? t("toolbar.micUnmute") : t("toolbar.micMute"); const streamLabel = DEMO_MODE ? t("publish.demoUnavailable") - : `${publishingAll ? t("publish.stop") : t("publish.start")} (${t("publish.alpha")})`; + : `${publishingAll ? t("publish.stop") : t("publish.start")}`; const themeClassName = `ts-app ts-theme-${theme}${designThemeClassName(designTheme)}${ activeCustomTheme ? " ts-design-custom" : "" @@ -13943,6 +14026,19 @@ function AppInner() {
)} {restartNotice && setRestartNotice(null)} />} + {idleCheckLeft !== null && ( + { + lastActivityRef.current = Date.now(); + sendActive(); + setIdleCheckLeft(null); + }} + /> + )} + {idleDisconnected && ( + setIdleDisconnected(false)} /> + )} {aboutOpen && (
- {source === "camera" ? "📷" : "🖥️"} {t("publish.title")} + {source === "camera" ? "📷" : "🖥️"} {t("publish.title")} {tile.state === "live" @@ -14532,7 +14628,7 @@ function AppInner() {
- {streamIcon(watched.info)} {watched.info.name || t("stream.untitled")} + {streamIcon(watched.info)} {watched.info.name || t("stream.untitled")} {watched.state === "connected" ? t("stream.live") : t(`stream.state.${watched.state}`)} @@ -14563,7 +14659,7 @@ function AppInner() {
- {streamIcon(info)} {info.name || t("stream.untitled")} + {streamIcon(info)} {info.name || t("stream.untitled")} {publishClientName(info.clientId)}
diff --git a/web/src/locales/cs-CZ.json b/web/src/locales/cs-CZ.json index 3761dfc..3d61ec9 100644 --- a/web/src/locales/cs-CZ.json +++ b/web/src/locales/cs-CZ.json @@ -492,10 +492,7 @@ "tree.noTalkPower": "V tomto kanálu nemáte právo mluvit", "tree.soundMuted": "Zvuk ztlumen (ohluchnutí)", "tree.streaming": "Vysílá stream", - "publish.alpha": "Alfa", - "publish.alphaTitle": "Alfa – nestabilní, může se kdykoli změnit nebo přestat fungovat", "publish.demoUnavailable": "Streamování není v demu dostupné – vyžaduje skutečný server TeamSpeak 6.", - "publish.alphaNote": "Streamování je ve fázi alfa. Používá nezdokumentovaný protokol Stream/Call služby TeamSpeak 6, takže připojení, kvalita obrazu i práce s diváky mohou selhat nebo se bez upozornění změnit. Není určeno pro produkční použití.", "publish.start": "Sdílet obrazovku nebo kameru", "publish.stop": "Zastavit sdílení", "publish.title": "Vaše vysílání", diff --git a/web/src/locales/de.json b/web/src/locales/de.json index fe2eb4e..fd44ebe 100644 --- a/web/src/locales/de.json +++ b/web/src/locales/de.json @@ -492,10 +492,7 @@ "tree.noTalkPower": "Keine Redeerlaubnis in diesem Channel", "tree.soundMuted": "Ton stummgeschaltet (deafened)", "tree.streaming": "Überträgt einen Stream", - "publish.alpha": "Alpha", - "publish.alphaTitle": "Alpha – instabil, kann sich jederzeit ändern oder brechen", "publish.demoUnavailable": "Übertragen ist in der Demo nicht verfügbar – dafür braucht es einen echten TeamSpeak-6-Server.", - "publish.alphaNote": "Streaming ist Alpha. Es spricht TeamSpeak 6s Stream/Call-Protokoll, das nicht dokumentiert ist – Verbindungsaufbau, Bildqualität und Zuschauerverwaltung können fehlschlagen oder sich ohne Vorankündigung ändern. Nicht für produktive Nutzung gedacht.", "publish.start": "Bildschirm oder Kamera übertragen", "publish.stop": "Übertragung beenden", "publish.title": "Deine Übertragung", @@ -1020,5 +1017,9 @@ "mobile.mic": "Mikro", "mobile.sound": "Ton", "mobile.leave": "Trennen", - "mobile.talk": "Sprechen" + "mobile.talk": "Sprechen", + "idleCheck.title": "Bist du noch da?", + "idleCheck.body": "Du hast eine Weile nichts im Client gemacht. Ohne Antwort wirst du in {seconds} s getrennt.", + "idleCheck.stay": "Ich bin noch da", + "idleCheck.disconnected": "Du wurdest getrennt, weil du auf „Bist du noch da?“ nicht geantwortet hast." } diff --git a/web/src/locales/en.json b/web/src/locales/en.json index ff239ff..d5d5075 100644 --- a/web/src/locales/en.json +++ b/web/src/locales/en.json @@ -492,10 +492,7 @@ "tree.noTalkPower": "No talk power in this channel", "tree.soundMuted": "Sound muted (deafened)", "tree.streaming": "Broadcasting a stream", - "publish.alpha": "Alpha", - "publish.alphaTitle": "Alpha - unstable, may change or break at any time", "publish.demoUnavailable": "Streaming is not available in the demo - it needs a real TeamSpeak 6 server.", - "publish.alphaNote": "Streaming is alpha. It speaks TeamSpeak 6's undocumented Stream/Call protocol, so connecting, picture quality and viewer handling can fail or change without notice. Not meant for production use.", "publish.start": "Share your screen or camera", "publish.stop": "Stop sharing", "publish.title": "Your broadcast", @@ -1020,5 +1017,9 @@ "mobile.mic": "Mic", "mobile.sound": "Sound", "mobile.leave": "Leave", - "mobile.talk": "Talk" + "mobile.talk": "Talk", + "idleCheck.title": "Are you still there?", + "idleCheck.body": "You haven't done anything in the client for a while. Without an answer you will be disconnected in {seconds} s.", + "idleCheck.stay": "I'm still here", + "idleCheck.disconnected": "You were disconnected because you didn't answer \"Are you still there?\"." } diff --git a/web/src/locales/fa.json b/web/src/locales/fa.json index 5efae3c..abeab33 100644 --- a/web/src/locales/fa.json +++ b/web/src/locales/fa.json @@ -491,10 +491,7 @@ "tree.noTalkPower": "در این کانال حق صحبت ندارد", "tree.soundMuted": "صدا بی‌صدا (کر)", "tree.streaming": "در حال پخش زنده", - "publish.alpha": "آلفا", - "publish.alphaTitle": "آلفا - ناپایدار، ممکن است هر زمان تغییر کند یا از کار بیفتد", "publish.demoUnavailable": "پخش زنده در حالت دمو در دسترس نیست - به یک سرور واقعی TeamSpeak 6 نیاز دارد.", - "publish.alphaNote": "پخش زنده در مرحله آلفا است. این ویژگی از پروتکل مستندنشده Stream/Call در TeamSpeak 6 استفاده می‌کند، بنابراین اتصال، کیفیت تصویر و مدیریت بینندگان ممکن است بدون اطلاع قبلی دچار خطا شوند یا تغییر کنند. برای استفاده تولیدی مناسب نیست.", "publish.start": "اشتراک‌گذاری صفحه یا دوربین", "publish.stop": "توقف اشتراک‌گذاری", "publish.title": "پخش زنده تو", diff --git a/web/src/locales/ru.json b/web/src/locales/ru.json index 2816ab5..4930f06 100644 --- a/web/src/locales/ru.json +++ b/web/src/locales/ru.json @@ -492,10 +492,7 @@ "tree.noTalkPower": "Нет права голоса в этом канале", "tree.soundMuted": "Звук выключен", "tree.streaming": "Ведёт трансляцию", - "publish.alpha": "Альфа", - "publish.alphaTitle": "Альфа - нестабильно, может измениться или сломаться в любой момент", "publish.demoUnavailable": "Трансляция недоступна в демо - нужен настоящий сервер TeamSpeak 6.", - "publish.alphaNote": "Трансляция находится в альфе. Она использует недокументированный протокол Stream/Call TeamSpeak 6, поэтому подключение, качество изображения и работа со зрителями могут сбоить или меняться без предупреждения. Не для рабочего использования.", "publish.start": "Показать экран или камеру", "publish.stop": "Остановить показ", "publish.title": "Ваша трансляция", diff --git a/web/src/locales/zh-CN.json b/web/src/locales/zh-CN.json index bc2defd..2777326 100644 --- a/web/src/locales/zh-CN.json +++ b/web/src/locales/zh-CN.json @@ -705,10 +705,7 @@ "design.store.publish.error": "发布失败。", "recording.autoGainControl": "自动增益控制", "tree.streaming": "正在直播", - "publish.alpha": "内测", - "publish.alphaTitle": "内测阶段 —— 不稳定,可能随时变更或失效", "publish.demoUnavailable": "演示模式下无法使用直播功能 —— 需要真实的 TeamSpeak 6 服务器。", - "publish.alphaNote": "直播功能处于内测阶段,使用的是 TeamSpeak 6 未公开文档的 Stream/Call 协议,因此连接、画质和观众处理可能会出错或在无预警的情况下发生变化,不建议用于正式场合。", "publish.start": "共享屏幕或摄像头", "publish.stop": "停止共享", "publish.title": "你的直播",