mirror of
https://github.com/Moepchi/webspeak3.git
synced 2026-12-01 08:52:51 +08:00
Compare commits
10
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
958095fbf4 | ||
|
|
fc33843179 | ||
|
|
e923181e14 | ||
|
|
ebe162fafb | ||
|
|
968a266684 | ||
|
|
8fbd591efa | ||
|
|
73ae268dfb | ||
|
|
f2d9115782 | ||
|
|
54a580dc39 | ||
|
|
abecd4e14d |
No files matched your search
+52
-5
@@ -63,6 +63,27 @@ async fn ft_pace(limit: &AtomicU64, bytes: usize, started: std::time::Instant) {
|
||||
tokio::time::sleep(rest).await;
|
||||
}
|
||||
}
|
||||
/// Upload bodies held at once (waiting for the server or being sent, which
|
||||
/// ftlimit can stretch to days). Without a cap a client could park any
|
||||
/// amount of memory in the connector.
|
||||
const MAX_UPLOADS_HELD: u64 = 2 * MAX_UPLOAD_BYTES;
|
||||
static UPLOADS_HELD: AtomicU64 = AtomicU64::new(0);
|
||||
|
||||
/// A share of MAX_UPLOADS_HELD, given back when dropped.
|
||||
struct HeldUpload(u64);
|
||||
impl Drop for HeldUpload {
|
||||
fn drop(&mut self) {
|
||||
UPLOADS_HELD.fetch_sub(self.0, Ordering::Relaxed);
|
||||
}
|
||||
}
|
||||
fn hold_upload(size: u64) -> Option<HeldUpload> {
|
||||
UPLOADS_HELD
|
||||
.fetch_update(Ordering::Relaxed, Ordering::Relaxed, |held| (held + size <= MAX_UPLOADS_HELD).then_some(held + size))
|
||||
.ok()
|
||||
.map(|_| HeldUpload(size))
|
||||
}
|
||||
const UPLOADS_BUSY: &str = "Upload refused: too many uploads in progress, try again when they are done";
|
||||
|
||||
/// Half-received chunked uploads per connection - each can hold up to
|
||||
/// MAX_UPLOAD_BYTES until it completes.
|
||||
const MAX_PARTIAL_UPLOADS: usize = 4;
|
||||
@@ -1201,7 +1222,7 @@ async fn run(args: Args) -> Result<()> {
|
||||
// (StreamItem::FileDownload/FileUpload below); these just remember which
|
||||
// request that stream belongs to.
|
||||
let mut pending_downloads: HashMap<u16, (u64, String)> = HashMap::new();
|
||||
let mut pending_uploads: HashMap<u16, (u64, String, Vec<u8>)> = HashMap::new();
|
||||
let mut pending_uploads: HashMap<u16, (u64, String, Vec<u8>, HeldUpload)> = HashMap::new();
|
||||
// Chunked uploads still arriving from the browser: (cid, path) -> (total size, bytes so far).
|
||||
let mut partial_uploads: HashMap<(u64, String), (u64, Vec<u8>)> = HashMap::new();
|
||||
// Set by "permissionlist" while waiting to emit the full permission
|
||||
@@ -2333,9 +2354,19 @@ async fn run(args: Args) -> Result<()> {
|
||||
) {
|
||||
(Ok(cid), Ok(bytes)) => {
|
||||
let size = bytes.len() as u64;
|
||||
let held = if size > MAX_UPLOAD_BYTES { None } else { hold_upload(size) };
|
||||
let Some(held) = held else {
|
||||
let message = if size > MAX_UPLOAD_BYTES {
|
||||
format!("Upload refused: {path} is larger than {} KiB", MAX_UPLOAD_BYTES >> 10)
|
||||
} else {
|
||||
UPLOADS_BUSY.into()
|
||||
};
|
||||
emit(&Event::TransferError { message, cid, path: path.to_string() });
|
||||
continue;
|
||||
};
|
||||
match con.upload_file(ChannelId(cid), path, None, size, true, false) {
|
||||
Ok(handle) => {
|
||||
pending_uploads.insert(handle.0, (cid, path.to_string(), bytes));
|
||||
pending_uploads.insert(handle.0, (cid, path.to_string(), bytes, held));
|
||||
}
|
||||
Err(e) => emit(&Event::TransferError {
|
||||
message: format!("Upload failed: {e}"),
|
||||
@@ -2349,9 +2380,13 @@ async fn run(args: Args) -> Result<()> {
|
||||
} else if let Some(rest) = l.strip_prefix("ftuploadchunk ") {
|
||||
match take_upload_chunk(&mut partial_uploads, rest) {
|
||||
Ok(Some((cid, path, bytes))) => {
|
||||
let Some(held) = hold_upload(bytes.len() as u64) else {
|
||||
emit(&Event::TransferError { message: UPLOADS_BUSY.into(), cid, path });
|
||||
continue;
|
||||
};
|
||||
match con.upload_file(ChannelId(cid), &path, None, bytes.len() as u64, true, false) {
|
||||
Ok(handle) => {
|
||||
pending_uploads.insert(handle.0, (cid, path, bytes));
|
||||
pending_uploads.insert(handle.0, (cid, path, bytes, held));
|
||||
}
|
||||
Err(e) => emit(&Event::TransferError { message: format!("Upload failed: {e}"), cid, path }),
|
||||
}
|
||||
@@ -3244,10 +3279,11 @@ async fn run(args: Args) -> Result<()> {
|
||||
}
|
||||
}
|
||||
Some(Ok(StreamItem::FileUpload(handle, result))) => {
|
||||
if let Some((cid, path, data)) = pending_uploads.remove(&handle.0) {
|
||||
if let Some((cid, path, data, held)) = pending_uploads.remove(&handle.0) {
|
||||
let seek = result.seek_position as usize;
|
||||
let mut stream = result.stream;
|
||||
tokio::spawn(async move {
|
||||
let _held = held;
|
||||
let slice = if seek < data.len() { &data[seek..] } else { &[][..] };
|
||||
for piece in slice.chunks(TRANSFER_CHUNK_BYTES) {
|
||||
let started = std::time::Instant::now();
|
||||
@@ -3264,7 +3300,7 @@ async fn run(args: Args) -> Result<()> {
|
||||
Some(Ok(StreamItem::FiletransferFailed(handle, e))) => {
|
||||
let failed = pending_downloads
|
||||
.remove(&handle.0)
|
||||
.or_else(|| pending_uploads.remove(&handle.0).map(|(cid, path, _)| (cid, path)));
|
||||
.or_else(|| pending_uploads.remove(&handle.0).map(|(cid, path, ..)| (cid, path)));
|
||||
if let Some((cid, path)) = failed {
|
||||
emit(&Event::TransferError { message: format!("File transfer failed: {e}"), cid, path });
|
||||
}
|
||||
@@ -3331,6 +3367,17 @@ async fn run(args: Args) -> Result<()> {
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn held_uploads_are_capped_and_released() {
|
||||
let a = hold_upload(MAX_UPLOAD_BYTES).unwrap();
|
||||
let b = hold_upload(MAX_UPLOAD_BYTES).unwrap();
|
||||
assert!(hold_upload(1).is_none());
|
||||
drop(a);
|
||||
assert!(hold_upload(MAX_UPLOAD_BYTES).is_some());
|
||||
drop(b);
|
||||
assert_eq!(UPLOADS_HELD.load(Ordering::Relaxed), 0);
|
||||
}
|
||||
|
||||
fn chunk(offset: u64, total: u64, data: &[u8]) -> String {
|
||||
format!("7\t{offset}\t{total}\t/a b.txt\t{}", base64::engine::general_purpose::STANDARD.encode(data))
|
||||
}
|
||||
|
||||
@@ -11,11 +11,10 @@ import type { IncomingMessage, ServerResponse } from "node:http";
|
||||
import type { TLSSocket } from "node:tls";
|
||||
import { createHash, createHmac, randomBytes, scrypt, timingSafeEqual } from "node:crypto";
|
||||
import { readFileSync } from "node:fs";
|
||||
import { rename, writeFile } from "node:fs/promises";
|
||||
import path from "node:path";
|
||||
import { promisify } from "node:util";
|
||||
import qrcode from "qrcode-generator";
|
||||
import { clientIp, createRateLimiter } from "./net.js";
|
||||
import { clientIp, createRateLimiter, writeFileAtomic } from "./net.js";
|
||||
import { describeSettings, updateSettings, validate } from "./config.js";
|
||||
|
||||
const ADMIN_USER = process.env.ADMIN_USER ?? "";
|
||||
@@ -36,9 +35,7 @@ try {
|
||||
}
|
||||
const totpSecret = () => auth.totpSecret ?? ENV_TOTP;
|
||||
async function saveAuth(next: typeof auth) {
|
||||
const tmp = `${AUTH_FILE}.${process.pid}.tmp`;
|
||||
await writeFile(tmp, JSON.stringify(next, null, 2), { mode: 0o600 });
|
||||
await rename(tmp, AUTH_FILE);
|
||||
await writeFileAtomic(AUTH_FILE, JSON.stringify(next, null, 2), 0o600);
|
||||
auth = next;
|
||||
}
|
||||
|
||||
|
||||
@@ -11,7 +11,7 @@
|
||||
// Deliberately absent: CONNECTOR_BIN (would be code execution), ALLOW_PRIVATE_TARGETS (opens the
|
||||
// operator's LAN), and the admin credentials themselves.
|
||||
import { readFileSync } from "node:fs";
|
||||
import { rename, writeFile } from "node:fs/promises";
|
||||
import { writeFileAtomic } from "./net.js";
|
||||
import path from "node:path";
|
||||
|
||||
export type SettingKind = "number" | "bool" | "list" | "text" | "secret";
|
||||
@@ -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)." },
|
||||
@@ -116,9 +117,7 @@ export async function updateSettings(changes: Record<string, string | null>): Pr
|
||||
if (value === null) delete next[key];
|
||||
else next[key] = value;
|
||||
}
|
||||
const tmp = `${CONFIG_FILE}.${process.pid}.tmp`;
|
||||
await writeFile(tmp, JSON.stringify(next, null, 2), { mode: 0o600 });
|
||||
await rename(tmp, CONFIG_FILE);
|
||||
await writeFileAtomic(CONFIG_FILE, JSON.stringify(next, null, 2), 0o600);
|
||||
overrides = next;
|
||||
apply();
|
||||
}
|
||||
|
||||
+32
-2
@@ -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<WebSocket, HeartbeatState>();
|
||||
|
||||
// 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<void> {
|
||||
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)) {
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import type { IncomingMessage } from "node:http";
|
||||
import { rename, writeFile } from "node:fs/promises";
|
||||
|
||||
// Behind a reverse proxy / tunnel every request arrives from the proxy's own
|
||||
// address, so per-IP limits would lump all users into one bucket. Only set
|
||||
@@ -38,3 +39,21 @@ export function createRateLimiter(limit: number | (() => number), windowMs: numb
|
||||
return recent.length > (typeof limit === "function" ? limit() : limit);
|
||||
};
|
||||
}
|
||||
|
||||
/** Write-then-rename, one write at a time per file. Concurrent requests used
|
||||
* to share one `.tmp` path: one rename won, the others failed with ENOENT,
|
||||
* and overlapping writes could leave a mangled file. Queued, the last caller's
|
||||
* data always lands last. */
|
||||
const writeQueues = new Map<string, Promise<void>>();
|
||||
export function writeFileAtomic(file: string, data: string, mode?: number): Promise<void> {
|
||||
const run = async () => {
|
||||
const tmp = `${file}.tmp`;
|
||||
await writeFile(tmp, data, { encoding: "utf-8", mode });
|
||||
await rename(tmp, file);
|
||||
};
|
||||
const done = (writeQueues.get(file) ?? Promise.resolve()).then(run);
|
||||
const tail = done.catch(() => {});
|
||||
writeQueues.set(file, tail);
|
||||
void tail.then(() => { if (writeQueues.get(file) === tail) writeQueues.delete(file); });
|
||||
return done;
|
||||
}
|
||||
+3
-4
@@ -13,7 +13,8 @@
|
||||
//
|
||||
// Like store.ts, this file has zero private modifications.
|
||||
import type { IncomingMessage, ServerResponse } from "node:http";
|
||||
import { readFile, rename, writeFile } from "node:fs/promises";
|
||||
import { readFile } from "node:fs/promises";
|
||||
import { writeFileAtomic } from "./net.js";
|
||||
import { randomUUID } from "node:crypto";
|
||||
import { isAdminRequest, latestPublicTheme } from "./store.js";
|
||||
|
||||
@@ -43,9 +44,7 @@ async function load(): Promise<TextItem[]> {
|
||||
}
|
||||
|
||||
async function save(items: TextItem[]) {
|
||||
const tmp = `${NEWS_DATA_FILE}.tmp`;
|
||||
await writeFile(tmp, JSON.stringify(items), "utf-8");
|
||||
await rename(tmp, NEWS_DATA_FILE!);
|
||||
await writeFileAtomic(NEWS_DATA_FILE!, JSON.stringify(items));
|
||||
cache = items;
|
||||
}
|
||||
|
||||
|
||||
+3
-5
@@ -4,8 +4,8 @@
|
||||
// row per instance id: version, first and last seen. No IP addresses, no
|
||||
// request log. The admin view returns counts only.
|
||||
import type { IncomingMessage, ServerResponse } from "node:http";
|
||||
import { readFile, rename, writeFile } from "node:fs/promises";
|
||||
import { clientIp, createRateLimiter } from "./net.js";
|
||||
import { readFile } from "node:fs/promises";
|
||||
import { clientIp, createRateLimiter, writeFileAtomic } from "./net.js";
|
||||
import { isAdminRequest } from "./store.js";
|
||||
|
||||
const PING_DATA_FILE = process.env.PING_DATA_FILE;
|
||||
@@ -36,9 +36,7 @@ async function save(instances: Record<string, Instance>) {
|
||||
// Instances silent for 90 days are gone for good.
|
||||
const cutoff = Date.now() - 90 * DAY_MS;
|
||||
for (const [id, i] of Object.entries(instances)) if (Date.parse(i.lastSeen) < cutoff) delete instances[id];
|
||||
const tmp = `${PING_DATA_FILE}.tmp`;
|
||||
await writeFile(tmp, JSON.stringify(instances), "utf-8");
|
||||
await rename(tmp, PING_DATA_FILE!);
|
||||
await writeFileAtomic(PING_DATA_FILE!, JSON.stringify(instances));
|
||||
}
|
||||
|
||||
function json(res: ServerResponse, status: number, body: unknown) {
|
||||
|
||||
@@ -11,10 +11,10 @@
|
||||
// touched. It has zero private modifications, so the overlay just copies it
|
||||
// verbatim; only index.ts's small SQLite-persistence sections need patching.
|
||||
import type { IncomingMessage, ServerResponse } from "node:http";
|
||||
import { readFile, rename, writeFile } from "node:fs/promises";
|
||||
import { readFile } from "node:fs/promises";
|
||||
import { timingSafeEqual, randomUUID } from "node:crypto";
|
||||
import path from "node:path";
|
||||
import { clientIp, createRateLimiter } from "./net.js";
|
||||
import { clientIp, createRateLimiter, writeFileAtomic } from "./net.js";
|
||||
|
||||
const storeAllowedOrigin = () => process.env.STORE_ALLOWED_ORIGIN || "*";
|
||||
// Plain JSON file (whole-array read-modify-write, not JSON-lines like
|
||||
@@ -134,9 +134,7 @@ async function saveStoreThemes(themes: StoreTheme[]): Promise<void> {
|
||||
storeCache = themes;
|
||||
// Write-then-rename: a crash mid-write must not leave a truncated file,
|
||||
// which loadStoreThemes() would read as "no themes" and then overwrite.
|
||||
const tmp = `${STORE_DATA_FILE}.tmp`;
|
||||
await writeFile(tmp, JSON.stringify(themes), "utf-8");
|
||||
await rename(tmp, STORE_DATA_FILE);
|
||||
await writeFileAtomic(STORE_DATA_FILE, JSON.stringify(themes));
|
||||
}
|
||||
|
||||
export function isAdminRequest(req: IncomingMessage): boolean {
|
||||
|
||||
+3
-5
@@ -8,9 +8,9 @@
|
||||
// One JSON file per account in SYNC_DATA_DIR. Only served by sync-server.ts.
|
||||
import type { IncomingMessage, ServerResponse } from "node:http";
|
||||
import { createHash, createHmac, randomBytes, timingSafeEqual } from "node:crypto";
|
||||
import { mkdir, readdir, readFile, rename, rm, writeFile } from "node:fs/promises";
|
||||
import { mkdir, readdir, readFile, rm } from "node:fs/promises";
|
||||
import path from "node:path";
|
||||
import { clientIp, createRateLimiter } from "./net.js";
|
||||
import { clientIp, createRateLimiter, writeFileAtomic } from "./net.js";
|
||||
|
||||
const SYNC_DATA_DIR = process.env.SYNC_DATA_DIR;
|
||||
const SYNC_ALLOWED_ORIGIN = process.env.SYNC_ALLOWED_ORIGIN ?? "*";
|
||||
@@ -76,9 +76,7 @@ async function load(id: string): Promise<Account | null> {
|
||||
}
|
||||
|
||||
async function save(id: string, account: Account) {
|
||||
const tmp = `${file(id)}.tmp`;
|
||||
await writeFile(tmp, JSON.stringify(account), "utf-8");
|
||||
await rename(tmp, file(id));
|
||||
await writeFileAtomic(file(id), JSON.stringify(account));
|
||||
}
|
||||
|
||||
// Writes to one account run one after another, so the version check can't race.
|
||||
|
||||
@@ -0,0 +1,20 @@
|
||||
// Concurrent saves to one file used to share a .tmp path: all but one rename
|
||||
// failed with ENOENT (seen live from a parallel /api/ping probe).
|
||||
import { test } from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
import { mkdtempSync, readFileSync, readdirSync, rmSync } from "node:fs";
|
||||
import { tmpdir } from "node:os";
|
||||
import path from "node:path";
|
||||
import { writeFileAtomic } from "../dist/net.js";
|
||||
|
||||
test("parallel writes to one file all succeed, last one wins", async () => {
|
||||
const dir = mkdtempSync(path.join(tmpdir(), "ws3-atomic-"));
|
||||
try {
|
||||
const file = path.join(dir, "data.json");
|
||||
await Promise.all(Array.from({ length: 50 }, (_, i) => writeFileAtomic(file, JSON.stringify({ i, pad: "x".repeat(i * 500) }))));
|
||||
assert.equal(JSON.parse(readFileSync(file, "utf-8")).i, 49);
|
||||
assert.deepEqual(readdirSync(dir), ["data.json"]);
|
||||
} finally {
|
||||
rmSync(dir, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
+65
-34
@@ -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;
|
||||
}
|
||||
@@ -1480,7 +1476,7 @@
|
||||
.ts-stream-panel {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
width: min(480px, calc(100vw - 2rem));
|
||||
min-width: 0;
|
||||
background: var(--bg-toolbar-1);
|
||||
border: 1px solid var(--border);
|
||||
border-radius: 6px;
|
||||
@@ -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;
|
||||
@@ -1551,6 +1523,34 @@
|
||||
object-fit: contain;
|
||||
}
|
||||
|
||||
/* A stream in our channel nobody opened yet: same 16:9 area, one click to watch. */
|
||||
.ts-stream-panel-watch {
|
||||
aspect-ratio: 16 / 9;
|
||||
width: 100%;
|
||||
background: #000;
|
||||
border: none;
|
||||
color: #fff;
|
||||
font-size: 1.1em;
|
||||
cursor: pointer;
|
||||
opacity: 0.8;
|
||||
}
|
||||
|
||||
.ts-stream-panel-watch:hover {
|
||||
opacity: 1;
|
||||
}
|
||||
|
||||
/* Stream icons in the tree sit on the right with the group icons and are clickable. */
|
||||
.ts-stream-icon {
|
||||
padding: 0;
|
||||
font-size: 11px;
|
||||
line-height: 1;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
span.ts-stream-icon {
|
||||
cursor: default;
|
||||
}
|
||||
|
||||
.ts-stream-panel-error {
|
||||
padding: 0.35rem 0.5rem;
|
||||
color: var(--danger, #e05a5a);
|
||||
@@ -1661,21 +1661,52 @@
|
||||
border-color: var(--accent);
|
||||
}
|
||||
|
||||
/* Watching and broadcasting can run at the same time, so the two panels stack
|
||||
instead of each anchoring itself to the same corner. */
|
||||
/* Every watched stream (and our own broadcast) is a tile in one grid, like
|
||||
Discord: up to two columns in the corner, as many as fit when popped out. */
|
||||
.ts-stream-panels {
|
||||
position: fixed;
|
||||
right: 1rem;
|
||||
bottom: 1rem;
|
||||
z-index: 29;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
display: grid;
|
||||
grid-template-columns: repeat(var(--stream-cols, 1), minmax(0, 1fr));
|
||||
align-content: safe end;
|
||||
gap: 0.5rem;
|
||||
align-items: flex-end;
|
||||
width: min(calc(var(--stream-cols, 1) * 480px), calc(100vw - 2rem));
|
||||
max-height: calc(100vh - 2rem);
|
||||
overflow-y: auto;
|
||||
}
|
||||
|
||||
.ts-stream-panel-focused {
|
||||
grid-column: 1 / -1;
|
||||
}
|
||||
|
||||
/* Inside the separate window the grid owns the whole viewport. */
|
||||
.ts-stream-panels-popout {
|
||||
position: static;
|
||||
width: auto;
|
||||
max-height: none;
|
||||
padding: 0.5rem;
|
||||
grid-template-columns: repeat(auto-fit, minmax(360px, 1fr));
|
||||
align-content: start;
|
||||
}
|
||||
|
||||
/* Discord-style focus: the enlarged stream on top, the rest below it. */
|
||||
.ts-stream-panels-popout .ts-stream-panel-focused {
|
||||
order: -1;
|
||||
}
|
||||
|
||||
.ts-stream-panels-popout .ts-stream-panel-focused video {
|
||||
max-height: calc(100vh - 6rem);
|
||||
}
|
||||
|
||||
/* Wraps the grid in the popped-out window; carries the theme variables. */
|
||||
.ts-stream-popout-root {
|
||||
min-height: 100vh;
|
||||
background: var(--bg);
|
||||
color: var(--text);
|
||||
}
|
||||
|
||||
.ts-context-menu {
|
||||
position: fixed;
|
||||
z-index: 30;
|
||||
|
||||
+477
-141
@@ -9,6 +9,7 @@ import {
|
||||
useSyncExternalStore,
|
||||
type ReactNode,
|
||||
} from "react";
|
||||
import { createPortal } from "react-dom";
|
||||
import { identityUid } from "./identityUid";
|
||||
import qrcode from "qrcode-generator";
|
||||
import { useRegisterSW } from "virtual:pwa-register/react";
|
||||
@@ -135,6 +136,22 @@ import {
|
||||
type StreamPublishOptions,
|
||||
} from "./publish";
|
||||
import { DEFAULT_ICE_SERVERS, StreamViewer, parseStreamInfo, type StreamEvent, type StreamInfo } from "./stream";
|
||||
|
||||
type PublishSource = StreamPublishOptions["source"];
|
||||
|
||||
interface PublishTile {
|
||||
state: PublishState;
|
||||
viewers: number[];
|
||||
pending: [number, string][];
|
||||
error: string | null;
|
||||
}
|
||||
|
||||
interface WatchedStream {
|
||||
info: StreamInfo;
|
||||
media: MediaStream | null;
|
||||
state: RTCPeerConnectionState;
|
||||
error: string | null;
|
||||
}
|
||||
import { DEMO_HOST, DEMO_MODE, DemoSocket } from "./demoMode";
|
||||
import {
|
||||
DEFAULT_SYNC_SERVER,
|
||||
@@ -1472,6 +1489,50 @@ function TalkLamp({
|
||||
);
|
||||
}
|
||||
|
||||
/** Streams per publishing client, and how to open one - read by the channel tree. */
|
||||
const StreamsContext = createContext<{
|
||||
byClient: Record<number, StreamInfo[]>;
|
||||
watch: (streamId: string) => void;
|
||||
}>({ byClient: {}, watch: () => {} });
|
||||
|
||||
const streamIcon = (info: StreamInfo) => (info.camera ? "📷" : "🖥️");
|
||||
|
||||
/** Right-hand stream icons on a client row; a click opens that stream. */
|
||||
function ClientStreamIcons({ client, isSelf }: { client: ClientInfo; isSelf: boolean }) {
|
||||
const t = useT();
|
||||
const { byClient, watch } = useContext(StreamsContext);
|
||||
const streams = byClient[client.id] ?? [];
|
||||
if (streams.length === 0) {
|
||||
// Streaming, but the stream info has not arrived yet.
|
||||
return client.isStreaming ? <span className="ts-stream-icon" title={t("tree.streaming")}>📺</span> : null;
|
||||
}
|
||||
return (
|
||||
<>
|
||||
{streams.map((info) => {
|
||||
const label = `${t(info.camera ? "tree.streamingCamera" : "tree.streaming")}${info.name ? `: ${info.name}` : ""}`;
|
||||
return isSelf ? (
|
||||
<span key={info.id} className="ts-stream-icon" title={label}>{streamIcon(info)}</span>
|
||||
) : (
|
||||
<button
|
||||
key={info.id}
|
||||
type="button"
|
||||
className="ts-stream-icon ts-plain-button"
|
||||
title={label}
|
||||
aria-label={label}
|
||||
onClick={(e) => {
|
||||
e.stopPropagation();
|
||||
watch(info.id);
|
||||
}}
|
||||
onDoubleClick={(e) => e.stopPropagation()}
|
||||
>
|
||||
{streamIcon(info)}
|
||||
</button>
|
||||
);
|
||||
})}
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
function ClientStatusIcons({ client }: { client: ClientInfo }) {
|
||||
const t = useT();
|
||||
const { tree } = useContext(DisplayPrefsContext);
|
||||
@@ -1482,7 +1543,6 @@ function ClientStatusIcons({ client }: { client: ClientInfo }) {
|
||||
{!client.inputMuted && client.inputHardwareEnabled && !client.hasTalkPower && (
|
||||
<span title={t("tree.noTalkPower")}>🔒</span>
|
||||
)}
|
||||
{client.isStreaming && <span title={t("tree.streaming")}>📺</span>}
|
||||
</span>
|
||||
);
|
||||
}
|
||||
@@ -1872,6 +1932,7 @@ function ChannelTree({
|
||||
<span className="ts-client-away-message">({c.awayMessage})</span>
|
||||
)}
|
||||
<span className="ts-client-icons">
|
||||
<ClientStreamIcons client={c} isSelf={c.id === ownClientId} />
|
||||
{clientGroupBadges(c).map((g) => (
|
||||
<GroupIcon key={g.id} group={g} images={groupIconImages} />
|
||||
))}
|
||||
@@ -2555,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 (
|
||||
<div className="ts-dialog-backdrop">
|
||||
<div className="ts-dialog ts-restart-notice-dialog" role="alertdialog" onClick={(e) => e.stopPropagation()}>
|
||||
<div className="ts-dialog-titlebar">
|
||||
<span>{t("idleCheck.title")}</span>
|
||||
</div>
|
||||
<div className="ts-dialog-body">
|
||||
<p>{t("idleCheck.body", { seconds: String(secondsLeft) })}</p>
|
||||
</div>
|
||||
<div className="ts-dialog-buttons">
|
||||
<div className="ts-dialog-buttons-right">
|
||||
<button type="button" autoFocus onClick={onStay}>
|
||||
{t("idleCheck.stay")}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function RestartNoticeDialog({ message, onAck }: { message: string; onAck: () => void }) {
|
||||
const t = useT();
|
||||
return (
|
||||
@@ -2705,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 (
|
||||
<span className="ts-alpha-badge" title={t("publish.alphaTitle")}>
|
||||
{t("publish.alpha")}
|
||||
</span>
|
||||
);
|
||||
}
|
||||
|
||||
function SegmentedChoice<T extends string | number>({
|
||||
value,
|
||||
options,
|
||||
@@ -2748,17 +2823,19 @@ function SegmentedChoice<T extends string | number>({
|
||||
|
||||
function StreamSettingsDialog({
|
||||
ownName,
|
||||
initialSource,
|
||||
onStart,
|
||||
onCancel,
|
||||
}: {
|
||||
ownName: string;
|
||||
initialSource: "display" | "camera";
|
||||
onStart: (options: StreamPublishOptions) => void;
|
||||
onCancel: () => void;
|
||||
}) {
|
||||
const t = useT();
|
||||
const backdrop = useBackdropDismiss(onCancel);
|
||||
const [preset, setPreset] = useState<string | null>("720");
|
||||
const [source, setSource] = useState<"display" | "camera">("display");
|
||||
const [source, setSource] = useState<"display" | "camera">(initialSource);
|
||||
const [audio, setAudio] = useState(true);
|
||||
const [accessibility, setAccessibility] = useState<number>(StreamAccess.PUBLIC);
|
||||
const [advanced, setAdvanced] = useState(false);
|
||||
@@ -2794,14 +2871,13 @@ function StreamSettingsDialog({
|
||||
<div className="ts-dialog ts-stream-settings" onClick={(e) => e.stopPropagation()}>
|
||||
<div className="ts-dialog-titlebar">
|
||||
<span>
|
||||
{t("publish.dialog.title")} <AlphaBadge />
|
||||
{t("publish.dialog.title")}
|
||||
</span>
|
||||
<button onClick={onCancel} title={t("dialog.close")} aria-label={t("dialog.close")}>
|
||||
✕
|
||||
</button>
|
||||
</div>
|
||||
<div className="ts-dialog-body">
|
||||
<p className="ts-alpha-note">{t("publish.alphaNote")}</p>
|
||||
<h4 className="ts-stream-settings-section">{t("publish.dialog.basic")}</h4>
|
||||
|
||||
<div className="ts-stream-settings-row">
|
||||
@@ -8984,6 +9060,12 @@ function AppInner() {
|
||||
const [gatewayFeatures, setGatewayFeatures] = useState<ReadonlySet<string>>(new Set());
|
||||
// TURN relay the gateway offers for screen streams (TURN_URLS), if any.
|
||||
const [turnServers, setTurnServers] = useState<RTCIceServer[]>([]);
|
||||
// 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<number | null>(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);
|
||||
@@ -9006,20 +9088,22 @@ function AppInner() {
|
||||
const [treeFilter, setTreeFilter] = useState("");
|
||||
const [clientVolumes, setClientVolumes] = useState<Record<string, number>>(loadClientVolumes);
|
||||
/** Stream metadata per publishing client id, keyed by clid. */
|
||||
const [streamInfos, setStreamInfos] = useState<Record<number, StreamInfo>>({});
|
||||
const [watchedStream, setWatchedStream] = useState<StreamInfo | null>(null);
|
||||
const [streamMedia, setStreamMedia] = useState<MediaStream | null>(null);
|
||||
const [streamState, setStreamState] = useState<RTCPeerConnectionState>("new");
|
||||
const [streamError, setStreamError] = useState<string | null>(null);
|
||||
const streamViewerRef = useRef<StreamViewer | null>(null);
|
||||
const [publishState, setPublishState] = useState<PublishState>("idle");
|
||||
const [publishViewers, setPublishViewers] = useState<number[]>([]);
|
||||
const [publishPending, setPublishPending] = useState<[number, string][]>([]);
|
||||
const [publishError, setPublishError] = useState<string | null>(null);
|
||||
const publisherRef = useRef<StreamPublisher | null>(null);
|
||||
const publishPreviewRef = useRef<HTMLVideoElement | null>(null);
|
||||
const [streamInfos, setStreamInfos] = useState<Record<string, StreamInfo>>({});
|
||||
/** Streams being watched, keyed by the publisher's clid - several at once, like Discord. */
|
||||
/** Keyed by stream id: one client can send screen and camera at once. */
|
||||
const [watchedStreams, setWatchedStreams] = useState<Record<string, WatchedStream>>({});
|
||||
const streamViewersRef = useRef<Map<string, StreamViewer>>(new Map());
|
||||
/** Streams the pop-out already opened by itself; closed or refused ones are not retried. */
|
||||
const autoWatchedRef = useRef<Set<string>>(new Set());
|
||||
/** Tile shown across the whole grid, Discord's "focus" (clid, or -1 for our own broadcast). */
|
||||
const [focusedStream, setFocusedStream] = useState<string | null>(null);
|
||||
/** Separate browser window the stream grid is portalled into, if popped out. */
|
||||
const [streamPopout, setStreamPopout] = useState<Window | null>(null);
|
||||
const [popoutSize, setPopoutSize] = useState({ width: 0, height: 0 });
|
||||
/** Our own broadcasts, at most one per source, so screen and camera can run together. */
|
||||
const [publishes, setPublishes] = useState<Partial<Record<PublishSource, PublishTile>>>({});
|
||||
const publishersRef = useRef<Map<PublishSource, StreamPublisher>>(new Map());
|
||||
const [streamSettingsOpen, setStreamSettingsOpen] = useState(false);
|
||||
const streamVideoRef = useRef<HTMLVideoElement | null>(null);
|
||||
/** Clients we already pulled a `notifystreaminfo` for, so we ask only once. */
|
||||
const requestedStreamInfoRef = useRef<Set<number>>(new Set());
|
||||
/** Stable self id from the connector (`own_client_id`); nickname match is fallback only. */
|
||||
@@ -10115,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") {
|
||||
@@ -10381,21 +10473,26 @@ function AppInner() {
|
||||
const streamEvent = data as StreamEvent;
|
||||
if (streamEvent.name === "notifystreaminfo" || streamEvent.name === "notifystreamstarted") {
|
||||
const info = parseStreamInfo(streamEvent.args);
|
||||
if (info) setStreamInfos((prev) => ({ ...prev, [info.clientId]: info }));
|
||||
// notifystreaminfo may leave `type` out; keep what notifystreamstarted said.
|
||||
if (info)
|
||||
setStreamInfos((prev) => ({
|
||||
...prev,
|
||||
[info.id]: { ...info, camera: info.camera ?? prev[info.id]?.camera },
|
||||
}));
|
||||
}
|
||||
if (streamEvent.name === "notifystreamstopped") {
|
||||
const clid = Number(streamEvent.args.clid);
|
||||
if (Number.isFinite(clid)) {
|
||||
const { id } = streamEvent.args;
|
||||
if (id) {
|
||||
setStreamInfos((prev) => {
|
||||
if (!(clid in prev)) return prev;
|
||||
if (!(id in prev)) return prev;
|
||||
const next = { ...prev };
|
||||
delete next[clid];
|
||||
delete next[id];
|
||||
return next;
|
||||
});
|
||||
}
|
||||
}
|
||||
streamViewerRef.current?.handleEvent(streamEvent);
|
||||
publisherRef.current?.handleEvent(streamEvent);
|
||||
for (const viewer of streamViewersRef.current.values()) viewer.handleEvent(streamEvent);
|
||||
for (const publisher of publishersRef.current.values()) publisher.handleEvent(streamEvent);
|
||||
break;
|
||||
}
|
||||
case "poke": {
|
||||
@@ -10471,17 +10568,10 @@ function AppInner() {
|
||||
appendLog({ text: `Disconnected: ${data.reason}`, kind: "info" });
|
||||
logClient("info", "Connection", `Disconnected: ${data.reason}`);
|
||||
if (wasConnected) void notify("CONNECTION_DISCONNECTED");
|
||||
streamViewerRef.current?.close();
|
||||
streamViewerRef.current = null;
|
||||
setWatchedStream(null);
|
||||
setStreamMedia(null);
|
||||
handleStopWatchingStream();
|
||||
setStreamInfos({});
|
||||
requestedStreamInfoRef.current.clear();
|
||||
publisherRef.current?.stop();
|
||||
publisherRef.current = null;
|
||||
setPublishState("idle");
|
||||
setPublishViewers([]);
|
||||
setPublishPending([]);
|
||||
handleStopPublishing();
|
||||
removeSession(sessionId, { skipSocketClose: true });
|
||||
break;
|
||||
}
|
||||
@@ -12135,70 +12225,141 @@ function AppInner() {
|
||||
if (!streaming.has(id)) requestedStreamInfoRef.current.delete(id);
|
||||
}
|
||||
setStreamInfos((prev) => {
|
||||
const stale = Object.keys(prev).filter((id) => !streaming.has(Number(id)));
|
||||
const stale = Object.values(prev).filter((info) => !streaming.has(info.clientId));
|
||||
if (stale.length === 0) return prev;
|
||||
const next = { ...prev };
|
||||
for (const id of stale) delete next[Number(id)];
|
||||
for (const info of stale) delete next[info.id];
|
||||
return next;
|
||||
});
|
||||
}, [clients]);
|
||||
|
||||
useEffect(() => {
|
||||
const video = streamVideoRef.current;
|
||||
if (video && video.srcObject !== streamMedia) video.srcObject = streamMedia;
|
||||
}, [streamMedia, watchedStream]);
|
||||
const activePublishes = (Object.entries(publishes) as [PublishSource, PublishTile][]).filter(
|
||||
([, tile]) => tile.state !== "idle" && tile.state !== "stopped",
|
||||
);
|
||||
const streamsByClient: Record<number, StreamInfo[]> = {};
|
||||
for (const info of Object.values(streamInfos)) (streamsByClient[info.clientId] ??= []).push(info);
|
||||
// Like Discord: streams in our channel show up as tiles before anyone clicks "watch".
|
||||
const ownChannel = clients.find((c) => c.id === ownClientId)?.channel;
|
||||
const availableStreams = Object.values(streamInfos).filter(
|
||||
(info) =>
|
||||
info.clientId !== ownClientId &&
|
||||
!watchedStreams[info.id] &&
|
||||
ownChannel !== undefined &&
|
||||
clients.find((c) => c.id === info.clientId)?.channel === ownChannel,
|
||||
);
|
||||
const streamTileCount = Object.keys(watchedStreams).length + activePublishes.length + availableStreams.length;
|
||||
|
||||
useEffect(() => {
|
||||
// The publisher owns the capture; the preview only mirrors it, so it is
|
||||
// read off the peer connection's senders rather than kept in state.
|
||||
const video = publishPreviewRef.current;
|
||||
if (!video) return;
|
||||
const media = publisherRef.current?.previewStream ?? null;
|
||||
if (video.srcObject !== media) video.srcObject = media;
|
||||
}, [publishState, publishViewers]);
|
||||
|
||||
const handleStopWatchingStream = () => {
|
||||
// close() sends leaveStream and fires onClosed, which clears the rest.
|
||||
streamViewerRef.current?.close();
|
||||
streamViewerRef.current = null;
|
||||
setWatchedStream(null);
|
||||
setStreamMedia(null);
|
||||
setStreamState("new");
|
||||
const openStreamPopout = () => {
|
||||
const win = window.open("", "webspeak3-streams", "popup,width=1280,height=760");
|
||||
if (!win) return;
|
||||
win.document.title = "WebSpeak3 – Streams";
|
||||
win.document.head.replaceChildren(
|
||||
...[...document.querySelectorAll('link[rel="stylesheet"], style')].map((node) => node.cloneNode(true)),
|
||||
);
|
||||
win.document.body.style.margin = "0";
|
||||
const measure = () => setPopoutSize({ width: win.innerWidth, height: win.innerHeight });
|
||||
measure();
|
||||
win.addEventListener("resize", measure);
|
||||
// Fires when the user closes the window; the grid then moves back in here.
|
||||
win.addEventListener("pagehide", () => setStreamPopout(null));
|
||||
setStreamPopout(win);
|
||||
};
|
||||
|
||||
const handleWatchStream = (clientId: number) => {
|
||||
const info = streamInfos[clientId];
|
||||
if (!info) return;
|
||||
handleStopWatchingStream();
|
||||
setStreamError(null);
|
||||
const closeStreamPopout = () => {
|
||||
streamPopout?.close();
|
||||
setStreamPopout(null);
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
// Nothing left to show (or the tab goes away): don't leave an empty window behind.
|
||||
if (!streamPopout) return;
|
||||
if (streamTileCount === 0) {
|
||||
streamPopout.close();
|
||||
setStreamPopout(null);
|
||||
return;
|
||||
}
|
||||
const close = () => streamPopout.close();
|
||||
window.addEventListener("pagehide", close);
|
||||
return () => window.removeEventListener("pagehide", close);
|
||||
}, [streamPopout, streamTileCount]);
|
||||
|
||||
/** Stops one watched stream, or all of them without an id. */
|
||||
const handleStopWatchingStream = (streamId?: string) => {
|
||||
const viewers = streamViewersRef.current;
|
||||
const ids = streamId === undefined ? [...viewers.keys()] : [streamId];
|
||||
for (const id of ids) {
|
||||
// close() sends leaveStream; delete first so its onClosed is a no-op.
|
||||
const viewer = viewers.get(id);
|
||||
viewers.delete(id);
|
||||
viewer?.close();
|
||||
}
|
||||
setWatchedStreams((prev) => {
|
||||
if (streamId === undefined) return {};
|
||||
const next = { ...prev };
|
||||
delete next[streamId];
|
||||
return next;
|
||||
});
|
||||
};
|
||||
|
||||
const handleWatchStream = (streamId: string) => {
|
||||
const info = streamInfos[streamId];
|
||||
if (!info || streamViewersRef.current.has(streamId)) return;
|
||||
const patch = (change: Partial<WatchedStream>) =>
|
||||
setWatchedStreams((prev) => (prev[streamId] ? { ...prev, [streamId]: { ...prev[streamId], ...change } } : prev));
|
||||
const viewer = new StreamViewer(info.id, info.clientId, {
|
||||
send: (message) => socketRef.current?.send(JSON.stringify(message)),
|
||||
onTrack: setStreamMedia,
|
||||
onTrack: (media) => patch({ media }),
|
||||
iceServers: [...DEFAULT_ICE_SERVERS, ...turnServers],
|
||||
onStateChange: setStreamState,
|
||||
onError: setStreamError,
|
||||
onStateChange: (state) => patch({ state }),
|
||||
onError: (error) => patch({ error }),
|
||||
onClosed: () => {
|
||||
// Also reached when the publisher stops, not just via the close button.
|
||||
streamViewerRef.current = null;
|
||||
setWatchedStream(null);
|
||||
setStreamMedia(null);
|
||||
if (streamViewersRef.current.get(streamId) !== viewer) return;
|
||||
handleStopWatchingStream(streamId);
|
||||
},
|
||||
});
|
||||
streamViewerRef.current = viewer;
|
||||
setWatchedStream(info);
|
||||
streamViewersRef.current.set(streamId, viewer);
|
||||
setWatchedStreams((prev) => ({ ...prev, [streamId]: { info, media: null, state: "new", error: null } }));
|
||||
viewer.join();
|
||||
};
|
||||
|
||||
const handleStopPublishing = () => {
|
||||
publisherRef.current?.stop();
|
||||
publisherRef.current = null;
|
||||
setPublishState("idle");
|
||||
setPublishViewers([]);
|
||||
setPublishPending([]);
|
||||
// Popped out, the window is meant for watching: open channel streams right
|
||||
// away. Only once per stream, so closing one (or a refused join request)
|
||||
// leaves a tile to click instead of reopening it in a loop.
|
||||
const availableStreamIds = availableStreams.map((info) => info.id).join(",");
|
||||
useEffect(() => {
|
||||
if (!streamPopout) return;
|
||||
for (const info of availableStreams) {
|
||||
if (autoWatchedRef.current.has(info.id)) continue;
|
||||
autoWatchedRef.current.add(info.id);
|
||||
handleWatchStream(info.id);
|
||||
}
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [streamPopout, availableStreamIds]);
|
||||
|
||||
/** Stops one broadcast, or all of them without a source. */
|
||||
const handleStopPublishing = (source?: PublishSource) => {
|
||||
const publishers = publishersRef.current;
|
||||
for (const key of source ? [source] : [...publishers.keys()]) {
|
||||
const publisher = publishers.get(key);
|
||||
publishers.delete(key);
|
||||
publisher?.stop();
|
||||
}
|
||||
setPublishes((prev) => {
|
||||
if (!source) return {};
|
||||
const next = { ...prev };
|
||||
delete next[source];
|
||||
return next;
|
||||
});
|
||||
};
|
||||
|
||||
const publishingAll = publishersRef.current.size >= 2;
|
||||
// Two publishers waiting for notifystreamstarted at once could not tell
|
||||
// whose id it is, so a second one waits until the first is live.
|
||||
const publishStarting = activePublishes.some(([, tile]) => tile.state === "starting");
|
||||
|
||||
const handleStreamButton = () => {
|
||||
if (publisherRef.current) {
|
||||
if (publishingAll) {
|
||||
handleStopPublishing();
|
||||
return;
|
||||
}
|
||||
@@ -12209,28 +12370,32 @@ function AppInner() {
|
||||
clients.find((c) => c.id === clid)?.name ?? `#${clid}`;
|
||||
|
||||
const handleStartPublishing = (options: StreamPublishOptions) => {
|
||||
if (ownClientId === null) return;
|
||||
if (ownClientId === null || publishStarting) return;
|
||||
setStreamSettingsOpen(false);
|
||||
setPublishError(null);
|
||||
const source = options.source;
|
||||
// Same source again replaces the running one.
|
||||
if (publishersRef.current.has(source)) handleStopPublishing(source);
|
||||
const patch = (change: Partial<PublishTile>) =>
|
||||
setPublishes((prev) => (prev[source] ? { ...prev, [source]: { ...prev[source], ...change } } : prev));
|
||||
const publisher = new StreamPublisher({
|
||||
send: (message) => socketRef.current?.send(JSON.stringify(message)),
|
||||
ownClientId,
|
||||
onStateChange: (state) => {
|
||||
setPublishState(state);
|
||||
// "stopped" is also how the browser's own stop-sharing bar reports in,
|
||||
// so the ref has to be dropped here and not only in the click handler.
|
||||
// so the publisher has to be dropped here and not only on the ✕.
|
||||
if (state === "stopped" || state === "idle") {
|
||||
publisherRef.current = null;
|
||||
setPublishViewers([]);
|
||||
setPublishPending([]);
|
||||
if (publishersRef.current.get(source) === publisher) handleStopPublishing(source);
|
||||
return;
|
||||
}
|
||||
patch({ state });
|
||||
},
|
||||
onViewersChange: setPublishViewers,
|
||||
onPendingChange: setPublishPending,
|
||||
onError: setPublishError,
|
||||
onViewersChange: (viewers) => patch({ viewers }),
|
||||
onPendingChange: (pending) => patch({ pending }),
|
||||
onError: (error) => patch({ error }),
|
||||
iceServers: [...DEFAULT_ICE_SERVERS, ...turnServers],
|
||||
});
|
||||
publisherRef.current = publisher;
|
||||
publishersRef.current.set(source, publisher);
|
||||
setPublishes((prev) => ({ ...prev, [source]: { state: "idle", viewers: [], pending: [], error: null } }));
|
||||
void publisher.start(options);
|
||||
};
|
||||
|
||||
@@ -12773,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);
|
||||
@@ -12818,14 +13039,62 @@ function AppInner() {
|
||||
const micLabel = !micOn ? t("toolbar.micEnable") : inputMuted ? t("toolbar.micUnmute") : t("toolbar.micMute");
|
||||
const streamLabel = DEMO_MODE
|
||||
? t("publish.demoUnavailable")
|
||||
: `${publishState === "live" ? 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" : ""
|
||||
}`;
|
||||
|
||||
/**
|
||||
* Popped out and nothing focused: pick the column count that makes the 16:9
|
||||
* tiles largest for this window, like Discord's grid.
|
||||
*/
|
||||
const popoutGridStyle = ((): React.CSSProperties => {
|
||||
if (!streamPopout || focusedStream !== null) return {};
|
||||
const pad = 16, gap = 8, header = 30; // px: grid padding, gap, tile header
|
||||
const width = popoutSize.width - pad;
|
||||
const height = popoutSize.height - pad;
|
||||
let best = { cols: 1, tile: 0 };
|
||||
for (let cols = 1; cols <= streamTileCount; cols++) {
|
||||
const rows = Math.ceil(streamTileCount / cols);
|
||||
const tile = Math.min(
|
||||
(width - gap * (cols - 1)) / cols,
|
||||
((height - gap * (rows - 1)) / rows - header) * (16 / 9),
|
||||
);
|
||||
if (tile > best.tile) best = { cols, tile };
|
||||
}
|
||||
return {
|
||||
gridTemplateColumns: `repeat(${best.cols}, ${Math.max(160, Math.floor(best.tile))}px)`,
|
||||
justifyContent: "center",
|
||||
alignContent: "center",
|
||||
minHeight: "100vh",
|
||||
boxSizing: "border-box",
|
||||
};
|
||||
})();
|
||||
|
||||
const streamToggle = (id: string) => (
|
||||
<>
|
||||
<button
|
||||
className="ts-stream-panel-close"
|
||||
onClick={streamPopout ? closeStreamPopout : openStreamPopout}
|
||||
title={t(streamPopout ? "stream.popin" : "stream.popout")}
|
||||
>
|
||||
{streamPopout ? "⇲" : "⧉"}
|
||||
</button>
|
||||
<button
|
||||
className="ts-stream-panel-close"
|
||||
onClick={() => setFocusedStream((cur) => (cur === id ? null : id))}
|
||||
title={t(focusedStream === id ? "stream.unfocus" : "stream.focus")}
|
||||
>
|
||||
{focusedStream === id ? "⤡" : "⤢"}
|
||||
</button>
|
||||
</>
|
||||
);
|
||||
|
||||
return (
|
||||
<DisplayPrefsContext.Provider value={displayPrefs}>
|
||||
<div
|
||||
className={`ts-app ts-theme-${theme}${designThemeClassName(designTheme)}${
|
||||
activeCustomTheme ? " ts-design-custom" : ""
|
||||
}${demoForceMobile ? " ts-force-mobile" : ""}${mobile ? ` ts-mobile ts-mobile-tab-${mobileTab}` : ""}${novaSplash ? " ts-nova-splash" : ""}${
|
||||
className={`${themeClassName}${demoForceMobile ? " ts-force-mobile" : ""}${mobile ? ` ts-mobile ts-mobile-tab-${mobileTab}` : ""}${novaSplash ? " ts-nova-splash" : ""}${
|
||||
designTheme === "ide" && !idePixelFont ? " ts-ide-plain-font" : ""
|
||||
}`}
|
||||
data-custom-theme={activeCustomTheme?.id}
|
||||
@@ -13594,16 +13863,16 @@ function AppInner() {
|
||||
</label>
|
||||
)}
|
||||
<button
|
||||
className={`ts-icon-button${publishState === "live" ? " ts-mic-on" : ""}`}
|
||||
className={`ts-icon-button${activePublishes.length > 0 ? " ts-mic-on" : ""}`}
|
||||
onClick={handleStreamButton}
|
||||
// DemoSocket has no answer for setupstream, so in demo mode the
|
||||
// panel would sit at "starting" forever - after the browser has
|
||||
// already asked the visitor to pick a screen. Don't offer it.
|
||||
disabled={!connected || ownClientId === null || DEMO_MODE}
|
||||
disabled={!connected || ownClientId === null || DEMO_MODE || publishStarting}
|
||||
title={streamLabel}
|
||||
aria-label={streamLabel}
|
||||
>
|
||||
{publishState === "live" ? "🛑" : "🖥️"}
|
||||
{publishingAll ? "🛑" : "🖥️"}
|
||||
</button>
|
||||
{TAB_AUDIO_SUPPORTED && (
|
||||
<button
|
||||
@@ -13757,6 +14026,19 @@ function AppInner() {
|
||||
</div>
|
||||
)}
|
||||
{restartNotice && <RestartNoticeDialog message={restartNotice} onAck={() => setRestartNotice(null)} />}
|
||||
{idleCheckLeft !== null && (
|
||||
<IdleCheckDialog
|
||||
secondsLeft={idleCheckLeft}
|
||||
onStay={() => {
|
||||
lastActivityRef.current = Date.now();
|
||||
sendActive();
|
||||
setIdleCheckLeft(null);
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
{idleDisconnected && (
|
||||
<RestartNoticeDialog message={t("idleCheck.disconnected")} onAck={() => setIdleDisconnected(false)} />
|
||||
)}
|
||||
|
||||
{aboutOpen && (
|
||||
<AboutDialog
|
||||
@@ -14266,34 +14548,55 @@ function AppInner() {
|
||||
{streamSettingsOpen && (
|
||||
<StreamSettingsDialog
|
||||
ownName={ownClient?.name ?? "WebSpeak3"}
|
||||
// Offer the source that is not running yet, so the second start is camera after screen.
|
||||
initialSource={publishersRef.current.has("display") ? "camera" : "display"}
|
||||
onStart={handleStartPublishing}
|
||||
onCancel={() => setStreamSettingsOpen(false)}
|
||||
/>
|
||||
)}
|
||||
{(watchedStream || (publishState !== "idle" && publishState !== "stopped")) && (
|
||||
<div className="ts-stream-panels">
|
||||
{publishState !== "idle" && publishState !== "stopped" && (
|
||||
<div className="ts-stream-panel ts-stream-panel-publish">
|
||||
{streamTileCount > 0 && (() => {
|
||||
const grid = (
|
||||
<div
|
||||
className={`ts-stream-panels${streamPopout ? " ts-stream-panels-popout" : ""}`}
|
||||
style={{ "--stream-cols": Math.min(streamTileCount, 2), ...popoutGridStyle } as React.CSSProperties}
|
||||
>
|
||||
{activePublishes.map(([source, tile]) => {
|
||||
const focusId = `publish-${source}`;
|
||||
const publisher = publishersRef.current.get(source);
|
||||
return (
|
||||
<div
|
||||
key={source}
|
||||
className={`ts-stream-panel ts-stream-panel-publish${focusedStream === focusId ? " ts-stream-panel-focused" : ""}`}
|
||||
>
|
||||
<div className="ts-stream-panel-header">
|
||||
<span className="ts-stream-panel-title">
|
||||
🖥️ {t("publish.title")} <AlphaBadge />
|
||||
{source === "camera" ? "📷" : "🖥️"} {t("publish.title")}
|
||||
</span>
|
||||
<span className="ts-stream-panel-state">
|
||||
{publishState === "live"
|
||||
? t("publish.viewers", { count: String(publishViewers.length) })
|
||||
{tile.state === "live"
|
||||
? t("publish.viewers", { count: String(tile.viewers.length) })
|
||||
: t("publish.starting")}
|
||||
</span>
|
||||
{streamToggle(focusId)}
|
||||
<button
|
||||
className="ts-stream-panel-close"
|
||||
onClick={handleStopPublishing}
|
||||
onClick={() => handleStopPublishing(source)}
|
||||
title={t("publish.stop")}
|
||||
>
|
||||
✕
|
||||
</button>
|
||||
</div>
|
||||
{/* muted: this is our own capture playing back locally */}
|
||||
<video ref={publishPreviewRef} autoPlay playsInline muted />
|
||||
{publishPending.map(([clid, message]) => (
|
||||
<video
|
||||
ref={(video) => {
|
||||
const media = publisher?.previewStream ?? null;
|
||||
if (video && video.srcObject !== media) video.srcObject = media;
|
||||
}}
|
||||
autoPlay
|
||||
playsInline
|
||||
muted
|
||||
/>
|
||||
{tile.pending.map(([clid, message]) => (
|
||||
<div className="ts-stream-request" key={clid}>
|
||||
<span className="ts-stream-request-who">
|
||||
{publishClientName(clid)}
|
||||
@@ -14301,49 +14604,76 @@ function AppInner() {
|
||||
</span>
|
||||
<button
|
||||
className="ts-stream-request-allow"
|
||||
onClick={() => void publisherRef.current?.approve(clid)}
|
||||
onClick={() => void publisher?.approve(clid)}
|
||||
>
|
||||
{t("publish.request.allow")}
|
||||
</button>
|
||||
<button onClick={() => publisherRef.current?.deny(clid)}>
|
||||
<button onClick={() => publisher?.deny(clid)}>
|
||||
{t("publish.request.deny")}
|
||||
</button>
|
||||
<button
|
||||
className="ts-stream-request-block"
|
||||
onClick={() => publisherRef.current?.deny(clid, true)}
|
||||
onClick={() => publisher?.deny(clid, true)}
|
||||
title={t("publish.request.blockHint")}
|
||||
>
|
||||
{t("publish.request.block")}
|
||||
</button>
|
||||
</div>
|
||||
))}
|
||||
{publishError && <div className="ts-stream-panel-error">{publishError}</div>}
|
||||
{tile.error && <div className="ts-stream-panel-error">{tile.error}</div>}
|
||||
</div>
|
||||
)}
|
||||
{watchedStream && (
|
||||
<div className="ts-stream-panel">
|
||||
);
|
||||
})}
|
||||
{Object.entries(watchedStreams).map(([streamId, watched]) => (
|
||||
<div className={`ts-stream-panel${focusedStream === streamId ? " ts-stream-panel-focused" : ""}`} key={streamId}>
|
||||
<div className="ts-stream-panel-header">
|
||||
<span className="ts-stream-panel-title">
|
||||
📺 {watchedStream.name || t("stream.untitled")} <AlphaBadge />
|
||||
{streamIcon(watched.info)} {watched.info.name || t("stream.untitled")}
|
||||
</span>
|
||||
<span className="ts-stream-panel-state">
|
||||
{streamState === "connected" ? t("stream.live") : t(`stream.state.${streamState}`)}
|
||||
{watched.state === "connected" ? t("stream.live") : t(`stream.state.${watched.state}`)}
|
||||
</span>
|
||||
{streamToggle(streamId)}
|
||||
<button
|
||||
className="ts-stream-panel-close"
|
||||
onClick={handleStopWatchingStream}
|
||||
onClick={() => handleStopWatchingStream(streamId)}
|
||||
title={t("stream.stop")}
|
||||
>
|
||||
✕
|
||||
</button>
|
||||
</div>
|
||||
{/* muted so autoplay is never blocked; the user unmutes via the controls */}
|
||||
<video ref={streamVideoRef} autoPlay playsInline muted controls />
|
||||
{streamError && <div className="ts-stream-panel-error">{streamError}</div>}
|
||||
<video
|
||||
ref={(video) => {
|
||||
if (video && video.srcObject !== watched.media) video.srcObject = watched.media;
|
||||
}}
|
||||
autoPlay
|
||||
playsInline
|
||||
muted
|
||||
controls
|
||||
/>
|
||||
{watched.error && <div className="ts-stream-panel-error">{watched.error}</div>}
|
||||
</div>
|
||||
)}
|
||||
))}
|
||||
{availableStreams.map((info) => (
|
||||
<div className="ts-stream-panel" key={info.id}>
|
||||
<div className="ts-stream-panel-header">
|
||||
<span className="ts-stream-panel-title">
|
||||
{streamIcon(info)} {info.name || t("stream.untitled")}
|
||||
</span>
|
||||
<span className="ts-stream-panel-state">{publishClientName(info.clientId)}</span>
|
||||
</div>
|
||||
<button className="ts-stream-panel-watch" onClick={() => handleWatchStream(info.id)}>
|
||||
▶ {t("stream.watch")}
|
||||
</button>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
);
|
||||
return streamPopout
|
||||
? createPortal(<div className={`${themeClassName} ts-stream-popout-root`}>{grid}</div>, streamPopout.document.body)
|
||||
: grid;
|
||||
})()}
|
||||
{clientContextMenu && (
|
||||
<div
|
||||
ref={clientContextMenuRef}
|
||||
@@ -14410,18 +14740,22 @@ function AppInner() {
|
||||
</label>
|
||||
);
|
||||
})()}
|
||||
{!clientContextMenu.isSelf && streamInfos[clientContextMenu.clientId] && (
|
||||
<button
|
||||
className="ts-menu-item"
|
||||
onClick={() => {
|
||||
handleWatchStream(clientContextMenu.clientId);
|
||||
setClientContextMenu(null);
|
||||
}}
|
||||
>
|
||||
<span className="ts-menu-item-icon">📺</span>
|
||||
<span className="ts-menu-item-label">{t("clientContext.watchStream")}</span>
|
||||
</button>
|
||||
)}
|
||||
{!clientContextMenu.isSelf &&
|
||||
(streamsByClient[clientContextMenu.clientId] ?? []).map((info) => (
|
||||
<button
|
||||
key={info.id}
|
||||
className="ts-menu-item"
|
||||
onClick={() => {
|
||||
handleWatchStream(info.id);
|
||||
setClientContextMenu(null);
|
||||
}}
|
||||
>
|
||||
<span className="ts-menu-item-icon">{streamIcon(info)}</span>
|
||||
<span className="ts-menu-item-label">
|
||||
{t(info.camera ? "clientContext.watchCamera" : "clientContext.watchStream")}
|
||||
</span>
|
||||
</button>
|
||||
))}
|
||||
{!clientContextMenu.isSelf && (
|
||||
<button
|
||||
className="ts-menu-item"
|
||||
@@ -14713,6 +15047,7 @@ function AppInner() {
|
||||
{treeSearch && treeSearch.channels.length === 0 && (
|
||||
<div className="ts-tree-empty">{t("tree.noMatches")}</div>
|
||||
)}
|
||||
<StreamsContext.Provider value={{ byClient: streamsByClient, watch: handleWatchStream }}>
|
||||
<ChannelTree
|
||||
channels={treeSearch?.channels ?? channels}
|
||||
clients={treeSearch?.clients ?? treeClients}
|
||||
@@ -14732,6 +15067,7 @@ function AppInner() {
|
||||
onClientContextMenu={handleClientContextMenu}
|
||||
onChannelContextMenu={handleChannelContextMenu}
|
||||
/>
|
||||
</StreamsContext.Provider>
|
||||
</>
|
||||
) : (
|
||||
<div className="ts-tree-empty">
|
||||
|
||||
@@ -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í",
|
||||
|
||||
+12
-4
@@ -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",
|
||||
@@ -533,6 +530,13 @@
|
||||
"publish.mode.server": "Server",
|
||||
"publish.mode.serverUnavailable": "Der Server-Modus läuft über TS6s SFU und ist noch nicht implementiert.",
|
||||
"stream.untitled": "Stream",
|
||||
"tree.streamingCamera": "Kamera",
|
||||
"clientContext.watchCamera": "Kamera ansehen",
|
||||
"stream.watch": "Ansehen",
|
||||
"stream.popout": "In eigenem Fenster",
|
||||
"stream.popin": "Zurück ins Hauptfenster",
|
||||
"stream.focus": "Vergrößern",
|
||||
"stream.unfocus": "Zurück zum Raster",
|
||||
"stream.stop": "Stream schließen",
|
||||
"stream.live": "Live",
|
||||
"stream.state.new": "Warte auf Angebot…",
|
||||
@@ -1013,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."
|
||||
}
|
||||
+12
-4
@@ -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",
|
||||
@@ -533,6 +530,13 @@
|
||||
"publish.mode.server": "Server",
|
||||
"publish.mode.serverUnavailable": "Server mode goes through TS6's SFU and is not implemented yet.",
|
||||
"stream.untitled": "Stream",
|
||||
"tree.streamingCamera": "Camera",
|
||||
"clientContext.watchCamera": "Watch camera",
|
||||
"stream.watch": "Watch",
|
||||
"stream.popout": "Open in own window",
|
||||
"stream.popin": "Back to main window",
|
||||
"stream.focus": "Enlarge",
|
||||
"stream.unfocus": "Back to grid",
|
||||
"stream.stop": "Close stream",
|
||||
"stream.live": "Live",
|
||||
"stream.state.new": "Waiting for offer…",
|
||||
@@ -1013,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?\"."
|
||||
}
|
||||
@@ -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": "پخش زنده تو",
|
||||
|
||||
@@ -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": "Ваша трансляция",
|
||||
|
||||
@@ -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": "你的直播",
|
||||
|
||||
+30
-1
@@ -22,8 +22,37 @@ const root = createRoot(document.getElementById('root')!)
|
||||
|
||||
// App reads its stored identities/favorites while loading, so it's imported only after the vault is open
|
||||
// and the sync account (Options -> Konto) had its chance to bring in newer data.
|
||||
// After a deploy, a page (or the service worker cache) can still point at
|
||||
// chunk files that no longer exist, which used to leave a black screen. One
|
||||
// fresh load fixes that; the flag stops a reload loop if the server is broken.
|
||||
const RELOAD_FLAG = 'ws3-chunk-reload'
|
||||
function reloadOnceForStaleChunks(): boolean {
|
||||
try {
|
||||
if (sessionStorage.getItem(RELOAD_FLAG)) return false
|
||||
sessionStorage.setItem(RELOAD_FLAG, '1')
|
||||
} catch {
|
||||
return false
|
||||
}
|
||||
location.reload()
|
||||
return true
|
||||
}
|
||||
window.addEventListener('vite:preloadError', (event) => {
|
||||
if (reloadOnceForStaleChunks()) event.preventDefault()
|
||||
})
|
||||
|
||||
async function start() {
|
||||
const { default: App } = await import('./App.tsx')
|
||||
let App: typeof import('./App.tsx').default
|
||||
try {
|
||||
;({ default: App } = await import('./App.tsx'))
|
||||
} catch (error) {
|
||||
if (reloadOnceForStaleChunks()) return
|
||||
throw error
|
||||
}
|
||||
try {
|
||||
sessionStorage.removeItem(RELOAD_FLAG)
|
||||
} catch {
|
||||
// storage blocked - nothing to clear
|
||||
}
|
||||
startAutoSync()
|
||||
root.render(
|
||||
<StrictMode>
|
||||
|
||||
+9
-1
@@ -176,7 +176,15 @@ export class StreamPublisher {
|
||||
case "notifystreamstarted":
|
||||
// Everyone in the channel sees this, so the clid decides whether it
|
||||
// is the answer to our own setupstream.
|
||||
if (Number(event.args.clid) === this.opts.ownClientId && event.args.id) {
|
||||
// Several publishers can run at once (screen + camera), so only one
|
||||
// still waiting for its own id takes it; the app starts them one at
|
||||
// a time so this is never ambiguous.
|
||||
if (
|
||||
this.state === "starting" &&
|
||||
this.streamId === null &&
|
||||
Number(event.args.clid) === this.opts.ownClientId &&
|
||||
event.args.id
|
||||
) {
|
||||
this.streamId = event.args.id;
|
||||
this.setState("live");
|
||||
}
|
||||
|
||||
@@ -43,6 +43,8 @@ export interface StreamInfo {
|
||||
viewers: number;
|
||||
hasAudio: boolean;
|
||||
bitrate: number;
|
||||
/** `type` 1 (CAMERA) vs. screen/window; undefined when the notify left it out. */
|
||||
camera?: boolean;
|
||||
}
|
||||
|
||||
export interface StreamViewerOptions {
|
||||
@@ -86,6 +88,7 @@ export function parseStreamInfo(args: Record<string, string>): StreamInfo | null
|
||||
viewers: Number(args.viewer ?? 0) || 0,
|
||||
hasAudio: args.audio === "1",
|
||||
bitrate: Number(args.bitrate ?? 0) || 0,
|
||||
camera: args.type === undefined ? undefined : args.type === "1",
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
Reference in new issue
Block a user