Files
VoelinClient/crates/voelin-stream/src/signal.rs
T
Claude e050148a32 Rename the project to Voelin; packages hold only the app, tsgw is a Linux server package
The product is Voelin (app id io.github.faumaray.Voelin), everywhere:
- crates tsc-* -> voelin-* (and voelin-fuzz), the desktop binary
  tsc-desktop -> voelin, the development CLI tsctl -> voelinctl;
- the Android app: applicationId, Kotlin package io.github.faumaray.voelin,
  VoelinApp, libvoelin_android.so (JNI class names follow);
- TSC_* environment variables -> VOELIN_*, Gradle properties tsc.* ->
  voelin.*, signing secrets VOELIN_SIGNING_*;
- the data/config/cache/state folder tsc -> voelin, the keyring service,
  thread names, the dev compose project;
- desktop file, metainfo, icon, Flatpak manifest, NSIS installer, docs.
The gateway keeps its name: bin tsgw (crate voelin-gateway), TSGW_* env
vars, the tsgw.v1+json protocol, the tsgw image. The window title and the
About page show "Voelin <version>" from voelin_platform::APP_NAME.

Packages (scripts/package.sh): the app only (voelin, voelin.exe, APKs,
Flatpak). voelinctl is a development tool and in no package. tsgw is for
servers and now its own Linux package, tsgw_<v>_amd64.deb and
tsgw-<v>-linux-x86_64.tar.gz, with a sandboxed systemd unit
(packaging/linux/tsgw.service; /etc/tsgw config, /var/lib/tsgw state) and
dependencies of its own (no GUI libraries). docs/gateway-admin.md has an
Install section.

Fixes:
- package-windows: makensis on Windows found no file through "D:/a/..."
  paths; pass Windows paths (cygpath -w).
- StartupWMClass is the app id, which the app sets as its X11 WM_CLASS
  (it was the binary name, so desktops could not match the window).
- Gradle wrapper download timeout 10 s -> 60 s (slow proxies).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01NJvYyRmTjKcb9i8eyYXK5G
2026-09-26 21:11:17 +00:00

139 lines
4.7 KiB
Rust

//! JSON messages carried in `streamsignaling` / `notifystreamsignaling`.
//!
//! The server passes the `json` parameter through unchanged. The format is
//! `{"cmd": <name>, "args": {...}}`; different clients spell the argument keys
//! differently, so parsing accepts every known variant and serializing uses the
//! spelling the official client sends.
use serde_json::{Map, Value, json};
/// One signalling message between streamer and viewer.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum Signal {
/// SDP offer. `reconnect` is set for `reconnectOffer` (ICE restart).
Offer { sdp: String, reconnect: bool },
/// SDP answer to an offer.
Answer { sdp: String },
/// Trickled ICE candidate (`candidate:...` line, with or without the `a=` prefix).
IceCandidate { candidate: String, mid: Option<String>, mline_index: Option<u32> },
/// The other side asks for a new offer.
Reconnect,
/// A command this client does not know; kept for logging.
Unknown { cmd: String, args: Value },
}
/// The `json` parameter could not be understood.
#[derive(Debug, thiserror::Error)]
pub enum SignalError {
#[error("invalid JSON: {0}")]
Json(#[from] serde_json::Error),
#[error("missing \"cmd\"")]
MissingCmd,
#[error("{cmd}: missing argument {arg}")]
MissingArg { cmd: String, arg: &'static str },
}
fn string_arg(args: &Map<String, Value>, keys: &[&str]) -> Option<String> {
keys.iter().find_map(|k| args.get(*k)).and_then(|v| v.as_str()).map(str::to_owned)
}
impl Signal {
pub fn parse(text: &str) -> Result<Self, SignalError> {
let value: Value = serde_json::from_str(text)?;
let cmd = value.get("cmd").and_then(Value::as_str).ok_or(SignalError::MissingCmd)?;
let empty = Map::new();
let args = value.get("args").and_then(Value::as_object).unwrap_or(&empty);
let missing = |arg| SignalError::MissingArg { cmd: cmd.to_owned(), arg };
Ok(match cmd {
"offer" | "reconnectOffer" => Signal::Offer {
sdp: string_arg(args, &["offer", "sdp"]).ok_or_else(|| missing("offer"))?,
reconnect: cmd == "reconnectOffer",
},
"answer" => Signal::Answer {
sdp: string_arg(args, &["answer", "sdp"]).ok_or_else(|| missing("answer"))?,
},
"iceCandidate" | "candidate" => Signal::IceCandidate {
candidate: string_arg(args, &["candidate", "sdp"])
.ok_or_else(|| missing("candidate"))?,
mid: string_arg(args, &["mid", "sdpMid", "sdp_mid"]),
mline_index: ["mLine", "sdpMLineIndex", "sdpMlineIndex", "sdp_mline_index"]
.iter()
.find_map(|k| args.get(*k))
.and_then(Value::as_u64)
.and_then(|v| u32::try_from(v).ok()),
},
"reconnect" => Signal::Reconnect,
other => Signal::Unknown { cmd: other.to_owned(), args: Value::Object(args.clone()) },
})
}
pub fn to_json(&self) -> String {
let value = match self {
Signal::Offer { sdp, reconnect } => json!({
"cmd": if *reconnect { "reconnectOffer" } else { "offer" },
"args": { "offer": sdp },
}),
Signal::Answer { sdp } => json!({ "cmd": "answer", "args": { "answer": sdp } }),
Signal::IceCandidate { candidate, mid, mline_index } => json!({
"cmd": "iceCandidate",
"args": { "candidate": candidate, "sdpMid": mid, "sdpMLineIndex": mline_index },
}),
Signal::Reconnect => json!({ "cmd": "reconnect", "args": {} }),
Signal::Unknown { cmd, args } => json!({ "cmd": cmd, "args": args }),
};
value.to_string()
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn roundtrip() {
let signals = [
Signal::Offer { sdp: "v=0\r\n".into(), reconnect: false },
Signal::Offer { sdp: "v=0\r\n".into(), reconnect: true },
Signal::Answer { sdp: "v=0\r\n".into() },
Signal::IceCandidate {
candidate: "candidate:1 1 udp 2130706431 10.0.0.2 50000 typ host".into(),
mid: Some("0".into()),
mline_index: Some(0),
},
Signal::Reconnect,
];
for s in signals {
assert_eq!(Signal::parse(&s.to_json()).unwrap(), s);
}
}
#[test]
fn key_variants() {
let s = Signal::parse(r#"{"cmd":"answer","args":{"sdp":"x"}}"#).unwrap();
assert_eq!(s, Signal::Answer { sdp: "x".into() });
let s = Signal::parse(r#"{"cmd":"iceCandidate","args":{"sdp":"c","mid":"1","mLine":1}}"#)
.unwrap();
assert_eq!(
s,
Signal::IceCandidate {
candidate: "c".into(),
mid: Some("1".into()),
mline_index: Some(1)
}
);
let s = Signal::parse(r#"{"cmd":"reconnectOffer","args":{"offer":"o"}}"#).unwrap();
assert_eq!(s, Signal::Offer { sdp: "o".into(), reconnect: true });
}
#[test]
fn errors() {
assert!(matches!(Signal::parse("nope"), Err(SignalError::Json(_))));
assert!(matches!(Signal::parse("{}"), Err(SignalError::MissingCmd)));
assert!(matches!(
Signal::parse(r#"{"cmd":"answer","args":{}}"#),
Err(SignalError::MissingArg { arg: "answer", .. })
));
assert!(matches!(Signal::parse(r#"{"cmd":"future"}"#), Ok(Signal::Unknown { .. })));
}
}