Initial commit: split VNOX monorepo into VNOX-Client
Desktop client with egui + wgpu UI, audio pipeline (cpal/opus/rodio), networking (LNEx protocol), and identity management with encrypted vault. Jitter buffer module extracted from voice-node for standalone operation.
This commit is contained in:
commit
bf0b237afd
112 changed files with 19113 additions and 0 deletions
46
src/net/crypto/cipher.rs
Normal file
46
src/net/crypto/cipher.rs
Normal file
|
|
@ -0,0 +1,46 @@
|
|||
use chacha20poly1305::{
|
||||
ChaCha20Poly1305, Key, KeyInit, Nonce,
|
||||
aead::{Aead, Payload},
|
||||
};
|
||||
|
||||
fn make_nonce(cid: &[u8; 8], seq: u64) -> [u8; 12] {
|
||||
let mut nonce = [0u8; 12];
|
||||
nonce[..8].copy_from_slice(cid);
|
||||
nonce[8..12].copy_from_slice(&(seq as u32).to_le_bytes());
|
||||
nonce
|
||||
}
|
||||
|
||||
pub fn encrypt_with_key(key: &[u8; 32], cid: &[u8; 8], seq: u64, plaintext: &[u8]) -> Vec<u8> {
|
||||
let cipher = ChaCha20Poly1305::new(Key::from_slice(key));
|
||||
let nonce_bytes = make_nonce(cid, seq);
|
||||
let nonce = Nonce::from_slice(&nonce_bytes);
|
||||
cipher
|
||||
.encrypt(
|
||||
nonce,
|
||||
Payload {
|
||||
msg: plaintext,
|
||||
aad: &[],
|
||||
},
|
||||
)
|
||||
.expect("ChaCha20-Poly1305 encryption infallible")
|
||||
}
|
||||
|
||||
pub fn decrypt_with_key(
|
||||
key: &[u8; 32],
|
||||
cid: &[u8; 8],
|
||||
seq: u64,
|
||||
ciphertext: &[u8],
|
||||
) -> anyhow::Result<Vec<u8>> {
|
||||
let cipher = ChaCha20Poly1305::new(Key::from_slice(key));
|
||||
let nonce_bytes = make_nonce(cid, seq);
|
||||
let nonce = Nonce::from_slice(&nonce_bytes);
|
||||
cipher
|
||||
.decrypt(
|
||||
nonce,
|
||||
Payload {
|
||||
msg: ciphertext,
|
||||
aad: &[],
|
||||
},
|
||||
)
|
||||
.map_err(|e| anyhow::anyhow!("decryption failed: {e:?}"))
|
||||
}
|
||||
99
src/net/crypto/mod.rs
Normal file
99
src/net/crypto/mod.rs
Normal file
|
|
@ -0,0 +1,99 @@
|
|||
use hkdf::Hkdf;
|
||||
use sha2::{Digest, Sha256};
|
||||
use x25519_dalek::{EphemeralSecret, PublicKey, SharedSecret};
|
||||
|
||||
pub mod cipher;
|
||||
|
||||
/// Session encryption context (mirrors gateway/src/proto/crypto.rs).
|
||||
///
|
||||
/// Two derived keys:
|
||||
/// - `c2s_key`: client → server
|
||||
/// - `s2c_key`: server → client
|
||||
///
|
||||
/// Nonce: `cid (8 bytes) || packet_seq (4 bytes LE)`.
|
||||
#[derive(Clone)]
|
||||
pub struct SessionCrypto {
|
||||
c2s_key: [u8; 32],
|
||||
s2c_key: [u8; 32],
|
||||
cid: [u8; 8],
|
||||
}
|
||||
|
||||
impl SessionCrypto {
|
||||
pub fn derive(shared_secret: &[u8; 32], session_id: &str) -> Self {
|
||||
let salt = b"VNOX-LNEx-KDF-v1";
|
||||
let hk = Hkdf::<Sha256>::new(Some(salt), shared_secret);
|
||||
|
||||
let mut keys = [0u8; 64];
|
||||
hk.expand(b"session-keys", &mut keys)
|
||||
.expect("64 bytes within HKDF max");
|
||||
|
||||
let c2s_key: [u8; 32] = keys[..32].try_into().unwrap();
|
||||
let s2c_key: [u8; 32] = keys[32..64].try_into().unwrap();
|
||||
|
||||
let hash = Sha256::digest(session_id.as_bytes());
|
||||
let cid: [u8; 8] = hash[..8].try_into().unwrap();
|
||||
|
||||
Self {
|
||||
c2s_key,
|
||||
s2c_key,
|
||||
cid,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn encrypt_c2s(&self, seq: u64, plaintext: &[u8]) -> Vec<u8> {
|
||||
cipher::encrypt_with_key(&self.c2s_key, &self.cid, seq, plaintext)
|
||||
}
|
||||
|
||||
pub fn decrypt_s2c(&self, seq: u64, ciphertext: &[u8]) -> anyhow::Result<Vec<u8>> {
|
||||
cipher::decrypt_with_key(&self.s2c_key, &self.cid, seq, ciphertext)
|
||||
}
|
||||
|
||||
pub fn decrypt_c2s(&self, seq: u64, ciphertext: &[u8]) -> anyhow::Result<Vec<u8>> {
|
||||
cipher::decrypt_with_key(&self.c2s_key, &self.cid, seq, ciphertext)
|
||||
}
|
||||
|
||||
pub fn c2s_key(&self) -> &[u8; 32] {
|
||||
&self.c2s_key
|
||||
}
|
||||
|
||||
pub fn cid(&self) -> &[u8; 8] {
|
||||
&self.cid
|
||||
}
|
||||
|
||||
pub fn new_ephemeral() -> (EphemeralSecret, PublicKey) {
|
||||
let mut rng = rand::thread_rng();
|
||||
let sk = EphemeralSecret::random_from_rng(&mut rng);
|
||||
let pk = PublicKey::from(&sk);
|
||||
(sk, pk)
|
||||
}
|
||||
|
||||
pub fn ecdh(secret: EphemeralSecret, peer_public: &PublicKey) -> SharedSecret {
|
||||
secret.diffie_hellman(peer_public)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn encrypt_then_decrypt_roundtrip() {
|
||||
let shared_secret = [0xABu8; 32];
|
||||
let crypto = SessionCrypto::derive(&shared_secret, "test-session");
|
||||
|
||||
let plaintext = b"hello encrypted world";
|
||||
let ct = crypto.encrypt_c2s(42, plaintext);
|
||||
let decrypted = crypto.decrypt_c2s(42, &ct).unwrap();
|
||||
assert_eq!(decrypted, plaintext);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tampered_ciphertext_fails() {
|
||||
let shared_secret = [0xABu8; 32];
|
||||
let crypto = SessionCrypto::derive(&shared_secret, "test-session");
|
||||
|
||||
let mut ct = crypto.encrypt_c2s(0, b"data");
|
||||
ct[5] ^= 0xFF;
|
||||
assert!(crypto.decrypt_c2s(0, &ct).is_err());
|
||||
}
|
||||
}
|
||||
51
src/net/framing/io.rs
Normal file
51
src/net/framing/io.rs
Normal file
|
|
@ -0,0 +1,51 @@
|
|||
use anyhow::{Result, anyhow};
|
||||
use tokio::io::AsyncReadExt;
|
||||
use tokio::io::AsyncWriteExt;
|
||||
use tokio::net::TcpStream;
|
||||
|
||||
use super::super::crypto::SessionCrypto;
|
||||
use super::super::payloads::HDR_SIZE;
|
||||
use super::RawPacket;
|
||||
use super::parse_header;
|
||||
|
||||
const ENCRYPTED_FLAG: u16 = 1 << 1;
|
||||
const KNOWN_FLAGS: u16 = ENCRYPTED_FLAG;
|
||||
|
||||
pub async fn read_encrypted(stream: &mut TcpStream, crypto: &SessionCrypto) -> Result<RawPacket> {
|
||||
let mut buf = [0u8; HDR_SIZE];
|
||||
stream.read_exact(&mut buf).await?;
|
||||
let (packet_id, flags, sequence, payload_length) = parse_header(&buf)?;
|
||||
if flags & !KNOWN_FLAGS != 0 {
|
||||
return Err(anyhow!("unknown packet flags: 0x{:04X}", flags));
|
||||
}
|
||||
if flags & ENCRYPTED_FLAG == 0 {
|
||||
return Err(anyhow!("packet not encrypted"));
|
||||
}
|
||||
let mut encrypted = vec![0u8; payload_length as usize];
|
||||
if !encrypted.is_empty() {
|
||||
stream.read_exact(&mut encrypted).await?;
|
||||
}
|
||||
let payload = crypto.decrypt_s2c(sequence as u64, &encrypted)?;
|
||||
Ok(RawPacket { packet_id, payload })
|
||||
}
|
||||
|
||||
pub async fn write_encrypted(
|
||||
stream: &mut TcpStream,
|
||||
id: u16,
|
||||
seq: &mut u32,
|
||||
payload: &[u8],
|
||||
crypto: &SessionCrypto,
|
||||
) -> Result<()> {
|
||||
let encrypted = crypto.encrypt_c2s(*seq as u64, payload);
|
||||
let mut hdr = [0u8; HDR_SIZE];
|
||||
hdr[0..2].copy_from_slice(&id.to_be_bytes());
|
||||
hdr[2..4].copy_from_slice(&ENCRYPTED_FLAG.to_be_bytes());
|
||||
hdr[4..8].copy_from_slice(&seq.to_be_bytes());
|
||||
hdr[8..12].copy_from_slice(&(encrypted.len() as u32).to_be_bytes());
|
||||
*seq = seq.wrapping_add(1);
|
||||
let mut frame = Vec::with_capacity(HDR_SIZE + encrypted.len());
|
||||
frame.extend_from_slice(&hdr);
|
||||
frame.extend_from_slice(&encrypted);
|
||||
stream.write_all(&frame).await?;
|
||||
Ok(())
|
||||
}
|
||||
101
src/net/framing/mod.rs
Normal file
101
src/net/framing/mod.rs
Normal file
|
|
@ -0,0 +1,101 @@
|
|||
use anyhow::{Result, anyhow};
|
||||
use tokio::io::{AsyncReadExt, AsyncWriteExt};
|
||||
use tokio::net::TcpStream;
|
||||
|
||||
use super::payloads::{HDR_SIZE, MAX_PAYLOAD};
|
||||
|
||||
pub struct RawPacket {
|
||||
pub packet_id: u16,
|
||||
pub payload: Vec<u8>,
|
||||
}
|
||||
|
||||
pub(super) fn parse_header(buf: &[u8; HDR_SIZE]) -> Result<(u16, u16, u32, u32)> {
|
||||
let packet_id = u16::from_be_bytes([buf[0], buf[1]]);
|
||||
let flags = u16::from_be_bytes([buf[2], buf[3]]);
|
||||
let sequence = u32::from_be_bytes([buf[4], buf[5], buf[6], buf[7]]);
|
||||
let payload_length = u32::from_be_bytes([buf[8], buf[9], buf[10], buf[11]]);
|
||||
if payload_length > MAX_PAYLOAD {
|
||||
return Err(anyhow!("payload too large: {payload_length}"));
|
||||
}
|
||||
Ok((packet_id, flags, sequence, payload_length))
|
||||
}
|
||||
|
||||
pub fn encode_frame(id: u16, seq: &mut u32, payload: &[u8]) -> Vec<u8> {
|
||||
let mut hdr = [0u8; HDR_SIZE];
|
||||
hdr[0..2].copy_from_slice(&id.to_be_bytes());
|
||||
hdr[4..8].copy_from_slice(&seq.to_be_bytes());
|
||||
hdr[8..12].copy_from_slice(&(payload.len() as u32).to_be_bytes());
|
||||
*seq = seq.wrapping_add(1);
|
||||
let mut frame = Vec::with_capacity(HDR_SIZE + payload.len());
|
||||
frame.extend_from_slice(&hdr);
|
||||
frame.extend_from_slice(payload);
|
||||
frame
|
||||
}
|
||||
|
||||
pub fn decode_frame(bytes: &[u8]) -> Result<RawPacket> {
|
||||
if bytes.len() < HDR_SIZE {
|
||||
return Err(anyhow!("frame too short"));
|
||||
}
|
||||
let hdr: [u8; HDR_SIZE] = bytes[..HDR_SIZE].try_into().expect("header length");
|
||||
let (packet_id, _, _, payload_length) = parse_header(&hdr)?;
|
||||
let end = HDR_SIZE + payload_length as usize;
|
||||
if bytes.len() < end {
|
||||
return Err(anyhow!("truncated frame"));
|
||||
}
|
||||
Ok(RawPacket {
|
||||
packet_id,
|
||||
payload: bytes[HDR_SIZE..end].to_vec(),
|
||||
})
|
||||
}
|
||||
|
||||
pub async fn read(stream: &mut TcpStream) -> Result<RawPacket> {
|
||||
let mut buf = [0u8; HDR_SIZE];
|
||||
stream.read_exact(&mut buf).await?;
|
||||
let (packet_id, _, _, payload_length) = parse_header(&buf)?;
|
||||
let mut payload = vec![0u8; payload_length as usize];
|
||||
if !payload.is_empty() {
|
||||
stream.read_exact(&mut payload).await?;
|
||||
}
|
||||
Ok(RawPacket { packet_id, payload })
|
||||
}
|
||||
|
||||
pub async fn write(stream: &mut TcpStream, id: u16, seq: &mut u32, payload: &[u8]) -> Result<()> {
|
||||
let frame = encode_frame(id, seq, payload);
|
||||
stream.write_all(&frame).await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub mod io;
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::net::payloads::PID_PING;
|
||||
|
||||
#[test]
|
||||
fn encode_decode_roundtrip() {
|
||||
let payload = br#"{"ping":true}"#;
|
||||
let mut seq = 7u32;
|
||||
let frame = encode_frame(PID_PING, &mut seq, payload);
|
||||
assert_eq!(seq, 8);
|
||||
let pkt = decode_frame(&frame).unwrap();
|
||||
assert_eq!(pkt.packet_id, PID_PING);
|
||||
assert_eq!(pkt.payload, payload);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn decode_rejects_oversized_length() {
|
||||
let mut hdr = [0u8; HDR_SIZE];
|
||||
hdr[0..2].copy_from_slice(&PID_PING.to_be_bytes());
|
||||
hdr[8..12].copy_from_slice(&(MAX_PAYLOAD + 1).to_be_bytes());
|
||||
assert!(decode_frame(&hdr).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn decode_rejects_truncated_body() {
|
||||
let mut seq = 0u32;
|
||||
let frame = encode_frame(PID_PING, &mut seq, b"x");
|
||||
let truncated = &frame[..frame.len() - 1];
|
||||
assert!(decode_frame(truncated).is_err());
|
||||
}
|
||||
}
|
||||
78
src/net/handshake.rs
Normal file
78
src/net/handshake.rs
Normal file
|
|
@ -0,0 +1,78 @@
|
|||
use anyhow::{Result, anyhow};
|
||||
use tokio::net::TcpStream;
|
||||
use tracing::{debug, info};
|
||||
|
||||
use super::crypto::SessionCrypto;
|
||||
use super::framing;
|
||||
use super::payloads::*;
|
||||
use crate::identity::Identity;
|
||||
|
||||
/// Perform HELLO → AUTH → SESSION with X25519 ECDH key exchange.
|
||||
///
|
||||
/// Returns (session_id, node_name, private_mode, crypto).
|
||||
/// All subsequent packets must be encrypted with `crypto`.
|
||||
pub async fn run(
|
||||
stream: &mut TcpStream,
|
||||
identity: &Identity,
|
||||
seq: &mut u32,
|
||||
) -> Result<(String, String, bool, SessionCrypto)> {
|
||||
// HELLO — receive server's ephemeral X25519 public key
|
||||
let pkt = framing::read(stream).await?;
|
||||
if pkt.packet_id != PID_HELLO {
|
||||
return Err(anyhow!("expected HELLO, got 0x{:04X}", pkt.packet_id));
|
||||
}
|
||||
let hello: HelloPayload = serde_json::from_slice(&pkt.payload)?;
|
||||
debug!("← HELLO node={}", hello.node_name);
|
||||
|
||||
// Generate our own ephemeral X25519 keypair
|
||||
let (eph_sk, eph_pk) = SessionCrypto::new_ephemeral();
|
||||
let eph_pk_hex = hex::encode(eph_pk.as_bytes());
|
||||
|
||||
// Parse server's ephemeral key from HELLO
|
||||
let server_eph_raw =
|
||||
hex::decode(&hello.server_eph_pubkey).map_err(|_| anyhow!("bad server_eph_pubkey hex"))?;
|
||||
let server_eph_key: [u8; 32] = server_eph_raw
|
||||
.try_into()
|
||||
.map_err(|_| anyhow!("bad server_eph_pubkey length"))?;
|
||||
let server_eph_pk = x25519_dalek::PublicKey::from(server_eph_key);
|
||||
|
||||
// AUTH — include our ephemeral public key
|
||||
let nonce = hex::decode(&hello.challenge_nonce)?;
|
||||
let sk = identity
|
||||
.signing_key()
|
||||
.ok_or_else(|| anyhow!("no signing key"))?;
|
||||
use ed25519_dalek::Signer;
|
||||
let sig = sk.sign(&nonce);
|
||||
|
||||
let auth = AuthPayload {
|
||||
client_pubkey: identity.pubkey_hex.clone(),
|
||||
nickname: identity.nickname.clone(),
|
||||
lnex_version: LNEX_VERSION.into(),
|
||||
signature: hex::encode(sig.to_bytes()),
|
||||
client_eph_pubkey: eph_pk_hex,
|
||||
};
|
||||
framing::write(stream, PID_AUTH, seq, &serde_json::to_vec(&auth)?).await?;
|
||||
debug!("→ AUTH nick={}", identity.nickname);
|
||||
|
||||
// SESSION
|
||||
let pkt = framing::read(stream).await?;
|
||||
if pkt.packet_id == PID_ERROR {
|
||||
let e: ErrorPayload = serde_json::from_slice(&pkt.payload)?;
|
||||
return Err(anyhow!("auth rejected: {}", e.message));
|
||||
}
|
||||
if pkt.packet_id != PID_SESSION {
|
||||
return Err(anyhow!("expected SESSION, got 0x{:04X}", pkt.packet_id));
|
||||
}
|
||||
let sess: SessionPayload = serde_json::from_slice(&pkt.payload)?;
|
||||
|
||||
// Derive encryption keys from ECDH shared secret
|
||||
let shared_secret = SessionCrypto::ecdh(eph_sk, &server_eph_pk);
|
||||
let crypto = SessionCrypto::derive(shared_secret.as_bytes(), &sess.session_id);
|
||||
|
||||
info!(
|
||||
"authenticated — session {} encrypted",
|
||||
&sess.session_id[..8]
|
||||
);
|
||||
|
||||
Ok((sess.session_id, hello.node_name, hello.private_mode, crypto))
|
||||
}
|
||||
162
src/net/internal/dispatch/channel.rs
Normal file
162
src/net/internal/dispatch/channel.rs
Normal file
|
|
@ -0,0 +1,162 @@
|
|||
use anyhow::{Result, anyhow};
|
||||
use serde_json;
|
||||
use tokio::sync::mpsc;
|
||||
|
||||
use super::super::super::payloads::*;
|
||||
use super::super::super::types::NetEvent;
|
||||
use super::super::super::types::{ChannelListItem as InfoChannelListItem, ChatMsg, MemberInfo};
|
||||
|
||||
pub async fn handle(pid: u16, payload: &[u8], tx: &mpsc::Sender<NetEvent>) -> Result<()> {
|
||||
match pid {
|
||||
PID_CHANNEL_STATE => {
|
||||
let p: ChannelStatePayload = serde_json::from_slice(payload)?;
|
||||
let _ = tx
|
||||
.send(NetEvent::ChannelState {
|
||||
channel_id: p.channel_id,
|
||||
channel_name: p.channel_name,
|
||||
kind: p.kind,
|
||||
members: p
|
||||
.members
|
||||
.into_iter()
|
||||
.map(|m| MemberInfo {
|
||||
user_id: m.user_id,
|
||||
nickname: m.nickname,
|
||||
in_voice: m.in_voice,
|
||||
})
|
||||
.collect(),
|
||||
voice_endpoint: p.voice_endpoint,
|
||||
})
|
||||
.await;
|
||||
}
|
||||
PID_CHANNEL_CREATE => {
|
||||
let p: ChannelCreatePayload = serde_json::from_slice(payload)?;
|
||||
let _ = tx
|
||||
.send(NetEvent::ChannelCreated {
|
||||
channel_id: p.channel_id,
|
||||
channel_name: p.channel_name,
|
||||
kind: p.kind,
|
||||
})
|
||||
.await;
|
||||
}
|
||||
PID_CHANNEL_DELETE => {
|
||||
let p: ChannelDeletePayload = serde_json::from_slice(payload)?;
|
||||
let _ = tx
|
||||
.send(NetEvent::ChannelDeleted {
|
||||
channel_id: p.channel_id,
|
||||
})
|
||||
.await;
|
||||
}
|
||||
PID_CHANNEL_LIST => {
|
||||
let p: ChannelListPayload = serde_json::from_slice(payload)?;
|
||||
let _ = tx
|
||||
.send(NetEvent::ChannelListEvent {
|
||||
channels: p
|
||||
.channels
|
||||
.into_iter()
|
||||
.map(|c| InfoChannelListItem {
|
||||
channel_id: c.channel_id,
|
||||
channel_name: c.channel_name,
|
||||
kind: c.kind,
|
||||
})
|
||||
.collect(),
|
||||
})
|
||||
.await;
|
||||
}
|
||||
PID_CHAT_MESSAGE => {
|
||||
let p: ChatMessagePayload = serde_json::from_slice(payload)?;
|
||||
let _ = tx
|
||||
.send(NetEvent::ChatMessage {
|
||||
message_id: p.message_id,
|
||||
channel_id: p.channel_id,
|
||||
sender_id: p.sender_id.clone(),
|
||||
nickname: p.sender_id,
|
||||
content: p.content,
|
||||
timestamp: p.timestamp,
|
||||
reply_to: p.reply_to,
|
||||
})
|
||||
.await;
|
||||
}
|
||||
PID_CHAT_HISTORY => {
|
||||
let p: ChatHistoryPayload = serde_json::from_slice(payload)?;
|
||||
let _ = tx
|
||||
.send(NetEvent::ChatHistory {
|
||||
channel_id: p.channel_id,
|
||||
messages: p
|
||||
.messages
|
||||
.into_iter()
|
||||
.map(|m| ChatMsg {
|
||||
message_id: m.message_id,
|
||||
sender_id: m.sender_id,
|
||||
content: m.content,
|
||||
timestamp: m.timestamp,
|
||||
reply_to: m.reply_to,
|
||||
})
|
||||
.collect(),
|
||||
})
|
||||
.await;
|
||||
}
|
||||
PID_USER_JOIN => {
|
||||
let p: UserJoinPayload = serde_json::from_slice(payload)?;
|
||||
let _ = tx
|
||||
.send(NetEvent::UserJoin {
|
||||
channel_id: p.channel_id,
|
||||
user_id: p.user_id,
|
||||
nickname: p.nickname,
|
||||
})
|
||||
.await;
|
||||
}
|
||||
PID_USER_LEAVE => {
|
||||
let p: UserLeavePayload = serde_json::from_slice(payload)?;
|
||||
let _ = tx
|
||||
.send(NetEvent::UserLeave {
|
||||
channel_id: p.channel_id,
|
||||
user_id: p.user_id,
|
||||
})
|
||||
.await;
|
||||
}
|
||||
PID_PONG => {
|
||||
let p: PongPayload = serde_json::from_slice(payload)?;
|
||||
let now = std::time::SystemTime::now()
|
||||
.duration_since(std::time::UNIX_EPOCH)
|
||||
.unwrap_or_default()
|
||||
.as_millis() as i64;
|
||||
let rtt_ms = (now - p.timestamp).max(0) as u32;
|
||||
let _ = tx.send(NetEvent::LatencyUpdate { rtt_ms }).await;
|
||||
}
|
||||
PID_READ_RECEIPT_BROADCAST => {
|
||||
let p: serde_json::Value = serde_json::from_slice(payload)?;
|
||||
let _ = tx
|
||||
.send(NetEvent::ReadReceiptBroadcast {
|
||||
channel_id: p["channel_id"].as_str().unwrap_or_default().into(),
|
||||
user_id: p["user_id"].as_str().unwrap_or_default().into(),
|
||||
last_read_message_id: p["last_read_message_id"]
|
||||
.as_str()
|
||||
.unwrap_or_default()
|
||||
.into(),
|
||||
})
|
||||
.await;
|
||||
}
|
||||
PID_ERROR => {
|
||||
let p: ErrorPayload = serde_json::from_slice(payload)?;
|
||||
let _ = tx
|
||||
.send(NetEvent::Error {
|
||||
code: p.code,
|
||||
message: p.message,
|
||||
})
|
||||
.await;
|
||||
}
|
||||
PID_DISCONNECT => return Err(anyhow!("server disconnected")),
|
||||
PID_TYPING_START => {
|
||||
let p: serde_json::Value = serde_json::from_slice(payload)?;
|
||||
let _ = tx
|
||||
.send(NetEvent::TypingStart {
|
||||
user_id: p["user_id"].as_str().unwrap_or_default().into(),
|
||||
nickname: p["nickname"].as_str().unwrap_or_default().into(),
|
||||
channel_id: p["channel_id"].as_str().unwrap_or_default().into(),
|
||||
})
|
||||
.await;
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
152
src/net/internal/dispatch/dm.rs
Normal file
152
src/net/internal/dispatch/dm.rs
Normal file
|
|
@ -0,0 +1,152 @@
|
|||
use anyhow::Result;
|
||||
use serde_json;
|
||||
use tokio::sync::mpsc;
|
||||
use tracing::debug;
|
||||
|
||||
use super::super::super::payloads::*;
|
||||
use super::super::super::types::*;
|
||||
|
||||
pub async fn handle(pid: u16, payload: &[u8], tx: &mpsc::Sender<NetEvent>) -> Result<()> {
|
||||
match pid {
|
||||
PID_DM_START => {
|
||||
let p: DmStartResponsePayload = serde_json::from_slice(payload)?;
|
||||
let _ = tx
|
||||
.send(NetEvent::DmStart {
|
||||
dm_id: p.dm_id,
|
||||
other_user_id: p.other_user_id,
|
||||
other_nickname: p.other_nickname,
|
||||
messages: p
|
||||
.messages
|
||||
.into_iter()
|
||||
.map(|m| ChatMsg {
|
||||
message_id: String::new(),
|
||||
sender_id: m.sender_id,
|
||||
content: m.content,
|
||||
timestamp: m.timestamp,
|
||||
reply_to: None,
|
||||
})
|
||||
.collect(),
|
||||
unread_count: p.unread_count,
|
||||
})
|
||||
.await;
|
||||
}
|
||||
PID_DM_MESSAGE => {
|
||||
let p: DmMessagePayload = serde_json::from_slice(payload)?;
|
||||
let _ = tx
|
||||
.send(NetEvent::DmMessage {
|
||||
dm_id: p.dm_id,
|
||||
sender_id: p.sender_id,
|
||||
content: p.content,
|
||||
timestamp: p.timestamp,
|
||||
})
|
||||
.await;
|
||||
}
|
||||
PID_DM_HISTORY => {
|
||||
let p: DmHistoryPayload = serde_json::from_slice(payload)?;
|
||||
let _ = tx
|
||||
.send(NetEvent::DmHistory {
|
||||
dm_id: p.dm_id,
|
||||
messages: p
|
||||
.messages
|
||||
.into_iter()
|
||||
.map(|m| ChatMsg {
|
||||
message_id: String::new(),
|
||||
sender_id: m.sender_id,
|
||||
content: m.content,
|
||||
timestamp: m.timestamp,
|
||||
reply_to: None,
|
||||
})
|
||||
.collect(),
|
||||
})
|
||||
.await;
|
||||
}
|
||||
PID_FRIEND_LIST => {
|
||||
let p: FriendListPayload = serde_json::from_slice(payload)?;
|
||||
let _ = tx
|
||||
.send(NetEvent::FriendList {
|
||||
friends: p
|
||||
.friends
|
||||
.into_iter()
|
||||
.map(|f| FriendInfo {
|
||||
user_id: f.user_id,
|
||||
nickname: f.nickname,
|
||||
status: f.status,
|
||||
since: f.since,
|
||||
})
|
||||
.collect(),
|
||||
})
|
||||
.await;
|
||||
}
|
||||
PID_MESSAGE_REACTION_ADD => {
|
||||
let p: ReactionPayload = serde_json::from_slice(payload)?;
|
||||
let _ = tx
|
||||
.send(NetEvent::ReactionAdded {
|
||||
channel_id: p.channel_id,
|
||||
message_id: p.message_id,
|
||||
user_id: p.user_id,
|
||||
emoji: p.emoji,
|
||||
})
|
||||
.await;
|
||||
}
|
||||
PID_MESSAGE_REACTION_REMOVE => {
|
||||
let p: ReactionPayload = serde_json::from_slice(payload)?;
|
||||
let _ = tx
|
||||
.send(NetEvent::ReactionRemoved {
|
||||
channel_id: p.channel_id,
|
||||
message_id: p.message_id,
|
||||
user_id: p.user_id,
|
||||
emoji: p.emoji,
|
||||
})
|
||||
.await;
|
||||
}
|
||||
PID_MESSAGE_EDIT => {
|
||||
let p: ChatMessagePayload = serde_json::from_slice(payload)?;
|
||||
let _ = tx
|
||||
.send(NetEvent::MessageEdited {
|
||||
channel_id: p.channel_id,
|
||||
message_id: p.message_id,
|
||||
content: p.content,
|
||||
edited: p.edited,
|
||||
})
|
||||
.await;
|
||||
}
|
||||
PID_MESSAGE_DELETE => {
|
||||
let p: MessageDeletePayload = serde_json::from_slice(payload)?;
|
||||
let _ = tx
|
||||
.send(NetEvent::MessageDeleted {
|
||||
channel_id: p.channel_id,
|
||||
message_id: p.message_id,
|
||||
})
|
||||
.await;
|
||||
}
|
||||
PID_FRIEND_EVENT => {
|
||||
let p: FriendEventPayload = serde_json::from_slice(payload)?;
|
||||
match p.event_type.as_str() {
|
||||
"request" => {
|
||||
let _ = tx
|
||||
.send(NetEvent::FriendRequested {
|
||||
user_id: p.user_id,
|
||||
nickname: p.nickname.unwrap_or_default(),
|
||||
})
|
||||
.await;
|
||||
}
|
||||
"accepted" => {
|
||||
let _ = tx
|
||||
.send(NetEvent::FriendAccepted {
|
||||
user_id: p.user_id,
|
||||
nickname: p.nickname.unwrap_or_default(),
|
||||
})
|
||||
.await;
|
||||
}
|
||||
"removed" => {
|
||||
let _ = tx
|
||||
.send(NetEvent::FriendRemoved { user_id: p.user_id })
|
||||
.await;
|
||||
}
|
||||
_ => debug!("unhandled friend event: {}", p.event_type),
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
53
src/net/internal/dispatch/mod.rs
Normal file
53
src/net/internal/dispatch/mod.rs
Normal file
|
|
@ -0,0 +1,53 @@
|
|||
use anyhow::Result;
|
||||
use tokio::sync::mpsc;
|
||||
use tracing::debug;
|
||||
|
||||
use super::super::payloads::*;
|
||||
use super::super::types::*;
|
||||
|
||||
mod channel;
|
||||
mod dm;
|
||||
mod social;
|
||||
|
||||
pub async fn incoming(pid: u16, payload: &[u8], tx: &mpsc::Sender<NetEvent>) -> Result<()> {
|
||||
match pid {
|
||||
PID_CHANNEL_STATE
|
||||
| PID_CHAT_MESSAGE
|
||||
| PID_CHAT_HISTORY
|
||||
| PID_USER_JOIN
|
||||
| PID_USER_LEAVE
|
||||
| PID_PONG
|
||||
| PID_READ_RECEIPT_BROADCAST
|
||||
| PID_ERROR
|
||||
| PID_DISCONNECT
|
||||
| PID_TYPING_START => channel::handle(pid, payload, tx).await?,
|
||||
|
||||
PID_DM_START
|
||||
| PID_DM_MESSAGE
|
||||
| PID_DM_HISTORY
|
||||
| PID_FRIEND_LIST
|
||||
| PID_MESSAGE_REACTION_ADD
|
||||
| PID_MESSAGE_REACTION_REMOVE
|
||||
| PID_MESSAGE_EDIT
|
||||
| PID_MESSAGE_DELETE
|
||||
| PID_FRIEND_EVENT => dm::handle(pid, payload, tx).await?,
|
||||
|
||||
PID_GUILD_LIST
|
||||
| PID_GUILD_CREATE
|
||||
| PID_GUILD_DELETE
|
||||
| PID_GUILD_MEMBER_JOIN
|
||||
| PID_GUILD_MEMBER_LEAVE
|
||||
| PID_GUILD_MEMBER_KICK
|
||||
| PID_INVITE_CREATE
|
||||
| PID_INVITE_ACCEPT
|
||||
| PID_INVITE_DELETE
|
||||
| PID_ROLE_CREATE
|
||||
| PID_ROLE_DELETE
|
||||
| PID_USER_ROLE_UPDATE
|
||||
| PID_PRESENCE_SYNC
|
||||
| PID_PRESENCE_EVENT => social::handle(pid, payload, tx).await?,
|
||||
|
||||
other => debug!("unhandled 0x{:04X}", other),
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
232
src/net/internal/dispatch/social.rs
Normal file
232
src/net/internal/dispatch/social.rs
Normal file
|
|
@ -0,0 +1,232 @@
|
|||
use anyhow::Result;
|
||||
use serde_json;
|
||||
use tokio::sync::mpsc;
|
||||
|
||||
use super::super::super::payloads::*;
|
||||
use super::super::super::types::*;
|
||||
|
||||
pub async fn handle(pid: u16, payload: &[u8], tx: &mpsc::Sender<NetEvent>) -> Result<()> {
|
||||
match pid {
|
||||
PID_GUILD_LIST => {
|
||||
let p: GuildListPayload = serde_json::from_slice(payload)?;
|
||||
let _ = tx
|
||||
.send(NetEvent::GuildList {
|
||||
guilds: p
|
||||
.guilds
|
||||
.into_iter()
|
||||
.map(|g| GuildInfo {
|
||||
guild_id: g.guild_id,
|
||||
name: g.name,
|
||||
owner_id: g.owner_id,
|
||||
icon_url: g.icon_url,
|
||||
member_count: g.member_count,
|
||||
})
|
||||
.collect(),
|
||||
})
|
||||
.await;
|
||||
}
|
||||
PID_GUILD_CREATE => {
|
||||
let p: GuildInfoPayload = serde_json::from_slice(payload)?;
|
||||
let _ = tx
|
||||
.send(NetEvent::GuildCreated {
|
||||
guild_id: p.guild_id,
|
||||
name: p.name,
|
||||
owner_id: p.owner_id,
|
||||
})
|
||||
.await;
|
||||
}
|
||||
PID_GUILD_DELETE => {
|
||||
let p: GuildDeletePayload = serde_json::from_slice(payload)?;
|
||||
let _ = tx
|
||||
.send(NetEvent::GuildDeleted {
|
||||
guild_id: p.guild_id,
|
||||
})
|
||||
.await;
|
||||
}
|
||||
PID_GUILD_MEMBER_JOIN => {
|
||||
let p: serde_json::Value = serde_json::from_slice(payload)?;
|
||||
let _ = tx
|
||||
.send(NetEvent::GuildMemberJoined {
|
||||
guild_id: p["guild_id"].as_str().unwrap_or_default().into(),
|
||||
user_id: p["user_id"].as_str().unwrap_or_default().into(),
|
||||
nickname: p["nickname"].as_str().unwrap_or_default().into(),
|
||||
})
|
||||
.await;
|
||||
}
|
||||
PID_GUILD_MEMBER_LEAVE => {
|
||||
let p: serde_json::Value = serde_json::from_slice(payload)?;
|
||||
let _ = tx
|
||||
.send(NetEvent::GuildMemberLeft {
|
||||
guild_id: p["guild_id"].as_str().unwrap_or_default().into(),
|
||||
user_id: p["user_id"].as_str().unwrap_or_default().into(),
|
||||
})
|
||||
.await;
|
||||
}
|
||||
PID_USER_ROLE_UPDATE => {
|
||||
let p: UserRoleUpdatePayload = serde_json::from_slice(payload)?;
|
||||
let _ = tx
|
||||
.send(NetEvent::UserColor {
|
||||
user_id: p.user_id,
|
||||
color: p.color,
|
||||
})
|
||||
.await;
|
||||
}
|
||||
PID_PRESENCE_SYNC => {
|
||||
let p: PresenceSyncPayload = serde_json::from_slice(payload)?;
|
||||
let _ = tx
|
||||
.send(NetEvent::PresenceSync {
|
||||
presences: p
|
||||
.presences
|
||||
.into_iter()
|
||||
.map(|p| PresenceInfo {
|
||||
user_id: p.user_id,
|
||||
status: p.status,
|
||||
custom_status: p.custom_status,
|
||||
activity: p.activity,
|
||||
activity_text: p.activity_text,
|
||||
})
|
||||
.collect(),
|
||||
})
|
||||
.await;
|
||||
}
|
||||
PID_PRESENCE_EVENT => {
|
||||
let p: PresenceEventPayload = serde_json::from_slice(payload)?;
|
||||
let _ = tx
|
||||
.send(NetEvent::PresenceUpdated {
|
||||
user_id: p.user_id,
|
||||
status: p.status,
|
||||
custom_status: p.custom_status,
|
||||
activity: p.activity,
|
||||
})
|
||||
.await;
|
||||
}
|
||||
PID_GUILD_MEMBER_KICK => {
|
||||
let p: serde_json::Value = serde_json::from_slice(payload)?;
|
||||
let _ = tx
|
||||
.send(NetEvent::GuildMemberKicked {
|
||||
guild_id: p["guild_id"].as_str().unwrap_or_default().into(),
|
||||
user_id: p["user_id"].as_str().unwrap_or_default().into(),
|
||||
})
|
||||
.await;
|
||||
}
|
||||
PID_INVITE_CREATE => {
|
||||
let p: InviteInfoPayload = serde_json::from_slice(payload)?;
|
||||
let _ = tx
|
||||
.send(NetEvent::InviteCreated {
|
||||
id: p.id,
|
||||
guild_id: p.guild_id,
|
||||
guild_name: p.guild_name,
|
||||
code: p.code,
|
||||
creator_id: p.creator_id,
|
||||
max_uses: p.max_uses,
|
||||
uses: p.uses,
|
||||
expires_at: p.expires_at,
|
||||
created_at: p.created_at,
|
||||
})
|
||||
.await;
|
||||
}
|
||||
PID_INVITE_ACCEPT => {
|
||||
let p: serde_json::Value = serde_json::from_slice(payload)?;
|
||||
let _ = tx
|
||||
.send(NetEvent::InviteAccepted {
|
||||
guild_id: p["guild_id"].as_str().unwrap_or_default().into(),
|
||||
guild_name: p["guild_name"].as_str().unwrap_or_default().into(),
|
||||
})
|
||||
.await;
|
||||
}
|
||||
PID_INVITE_DELETE => {
|
||||
let p: InviteDeletePayload = serde_json::from_slice(payload)?;
|
||||
let _ = tx
|
||||
.send(NetEvent::InviteDeleted {
|
||||
guild_id: p.guild_id,
|
||||
invite_id: p.invite_id,
|
||||
})
|
||||
.await;
|
||||
}
|
||||
PID_ROLE_CREATE => {
|
||||
let p: serde_json::Value = serde_json::from_slice(payload)?;
|
||||
let _ = tx
|
||||
.send(NetEvent::RoleCreated {
|
||||
role_id: p["id"].as_str().unwrap_or_default().into(),
|
||||
guild_id: p["guild_id"].as_str().unwrap_or_default().into(),
|
||||
name: p["name"].as_str().unwrap_or_default().into(),
|
||||
})
|
||||
.await;
|
||||
}
|
||||
PID_ROLE_DELETE => {
|
||||
let p: RoleDeletePayload = serde_json::from_slice(payload)?;
|
||||
let _ = tx
|
||||
.send(NetEvent::RoleDeleted {
|
||||
role_id: p.role_id,
|
||||
guild_id: p.guild_id,
|
||||
})
|
||||
.await;
|
||||
}
|
||||
PID_GUILD_AUDIT_LOG => {
|
||||
let p: GuildAuditLogPayload = serde_json::from_slice(payload)?;
|
||||
let _ = tx
|
||||
.send(NetEvent::GuildAuditLog {
|
||||
guild_id: p.guild_id,
|
||||
entries: p.entries,
|
||||
})
|
||||
.await;
|
||||
}
|
||||
PID_GUILD_MEMBER_LIST => {
|
||||
let p: GuildMemberListPayload = serde_json::from_slice(payload)?;
|
||||
let _ = tx
|
||||
.send(NetEvent::GuildMemberList {
|
||||
guild_id: p.guild_id,
|
||||
members: p.members,
|
||||
})
|
||||
.await;
|
||||
}
|
||||
PID_GUILD_ROLE_LIST => {
|
||||
let p: GuildRoleListPayload = serde_json::from_slice(payload)?;
|
||||
let _ = tx
|
||||
.send(NetEvent::GuildRoleList {
|
||||
guild_id: p.guild_id,
|
||||
roles: p.roles,
|
||||
})
|
||||
.await;
|
||||
}
|
||||
PID_BLOCK_LIST => {
|
||||
// Server may send {"blocked": [...]} — try to parse properly first,
|
||||
// fall back to JSON value extraction.
|
||||
let blocked: Vec<String> = match serde_json::from_slice::<BlockListPayload>(payload) {
|
||||
Ok(p) => p.blocked,
|
||||
Err(_) => {
|
||||
let v: serde_json::Value = serde_json::from_slice(payload)?;
|
||||
v["blocked"]
|
||||
.as_array()
|
||||
.map(|arr| {
|
||||
arr.iter()
|
||||
.filter_map(|x| x.as_str().map(String::from))
|
||||
.collect()
|
||||
})
|
||||
.unwrap_or_default()
|
||||
}
|
||||
};
|
||||
let _ = tx.send(NetEvent::BlockList { blocked }).await;
|
||||
}
|
||||
PID_BLOCK_USER => {
|
||||
let v: serde_json::Value = serde_json::from_slice(payload).unwrap_or_default();
|
||||
let user_id = v["user_id"]
|
||||
.as_str()
|
||||
.or_else(|| v["blocked"].as_str())
|
||||
.unwrap_or_default()
|
||||
.to_string();
|
||||
let _ = tx.send(NetEvent::BlockedUser { user_id }).await;
|
||||
}
|
||||
PID_UNBLOCK_USER => {
|
||||
let v: serde_json::Value = serde_json::from_slice(payload).unwrap_or_default();
|
||||
let user_id = v["user_id"]
|
||||
.as_str()
|
||||
.or_else(|| v["unblocked"].as_str())
|
||||
.unwrap_or_default()
|
||||
.to_string();
|
||||
let _ = tx.send(NetEvent::UnblockedUser { user_id }).await;
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
1
src/net/internal/mod.rs
Normal file
1
src/net/internal/mod.rs
Normal file
|
|
@ -0,0 +1 @@
|
|||
pub(super) mod dispatch;
|
||||
43
src/net/mod.rs
Normal file
43
src/net/mod.rs
Normal file
|
|
@ -0,0 +1,43 @@
|
|||
pub mod crypto;
|
||||
pub mod framing;
|
||||
pub mod handshake;
|
||||
mod internal;
|
||||
pub mod payloads;
|
||||
mod session;
|
||||
mod types;
|
||||
pub mod voice;
|
||||
|
||||
pub use types::{ChatMsg, FriendInfo, GuildInfo, MemberInfo, NetCommand, NetEvent, PresenceInfo};
|
||||
|
||||
use std::sync::Arc;
|
||||
use std::sync::Mutex;
|
||||
use tokio::sync::mpsc;
|
||||
|
||||
use crate::identity::Identity;
|
||||
|
||||
// ─── Handle ──────────────────────────────────────────────────────────────────
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct NetHandle {
|
||||
cmd_tx: mpsc::Sender<NetCommand>,
|
||||
event_rx: Arc<Mutex<mpsc::Receiver<NetEvent>>>,
|
||||
}
|
||||
|
||||
impl NetHandle {
|
||||
pub async fn send(&self, cmd: NetCommand) {
|
||||
let _ = self.cmd_tx.send(cmd).await;
|
||||
}
|
||||
pub fn try_recv(&self) -> Option<NetEvent> {
|
||||
self.event_rx.try_lock().ok()?.try_recv().ok()
|
||||
}
|
||||
}
|
||||
|
||||
pub fn spawn(identity: Identity) -> NetHandle {
|
||||
let (cmd_tx, cmd_rx) = mpsc::channel::<NetCommand>(64);
|
||||
let (event_tx, event_rx) = mpsc::channel::<NetEvent>(256);
|
||||
tokio::spawn(session::net_task(identity, cmd_rx, event_tx));
|
||||
NetHandle {
|
||||
cmd_tx,
|
||||
event_rx: Arc::new(Mutex::new(event_rx)),
|
||||
}
|
||||
}
|
||||
152
src/net/payloads/channel.rs
Normal file
152
src/net/payloads/channel.rs
Normal file
|
|
@ -0,0 +1,152 @@
|
|||
use serde::{Deserialize, Serialize};
|
||||
|
||||
#[derive(Serialize, Deserialize, Debug)]
|
||||
pub struct HelloPayload {
|
||||
pub lnex_version: String,
|
||||
pub server_pubkey: String,
|
||||
pub challenge_nonce: String,
|
||||
pub node_name: String,
|
||||
pub server_eph_pubkey: String,
|
||||
#[serde(default)]
|
||||
pub private_mode: bool,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize, Debug)]
|
||||
pub struct AuthPayload {
|
||||
pub client_pubkey: String,
|
||||
pub nickname: String,
|
||||
pub lnex_version: String,
|
||||
pub signature: String,
|
||||
pub client_eph_pubkey: String,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize, Debug)]
|
||||
pub struct SessionPayload {
|
||||
pub session_id: String,
|
||||
pub token: String,
|
||||
pub expires_at: i64,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize, Debug)]
|
||||
pub struct PingPayload {
|
||||
pub timestamp: i64,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize, Debug)]
|
||||
pub struct PongPayload {
|
||||
pub timestamp: i64,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize, Debug)]
|
||||
pub struct JoinChannelPayload {
|
||||
pub channel_id: String,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize, Debug)]
|
||||
pub struct LeaveChannelPayload {
|
||||
pub channel_id: String,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize, Debug)]
|
||||
pub struct ChannelStatePayload {
|
||||
pub channel_id: String,
|
||||
pub channel_name: String,
|
||||
pub kind: String,
|
||||
pub members: Vec<WireMember>,
|
||||
pub voice_endpoint: String,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize, Debug, Clone)]
|
||||
pub struct ChannelCreatePayload {
|
||||
pub channel_id: String,
|
||||
pub channel_name: String,
|
||||
/// "text" or "voice".
|
||||
pub kind: String,
|
||||
#[serde(default)]
|
||||
pub guild_id: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize, Debug, Clone)]
|
||||
pub struct ChannelDeletePayload {
|
||||
pub channel_id: String,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize, Debug, Clone)]
|
||||
pub struct ChannelListPayload {
|
||||
pub channels: Vec<ChannelListItem>,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize, Debug, Clone)]
|
||||
pub struct ChannelListItem {
|
||||
pub channel_id: String,
|
||||
pub channel_name: String,
|
||||
pub kind: String,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize, Debug, Clone)]
|
||||
pub struct WireMember {
|
||||
pub user_id: String,
|
||||
pub nickname: String,
|
||||
pub in_voice: bool,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize, Debug, Clone)]
|
||||
pub struct ChatMessagePayload {
|
||||
pub message_id: String,
|
||||
pub channel_id: String,
|
||||
pub sender_id: String,
|
||||
pub content: String,
|
||||
pub timestamp: i64,
|
||||
#[serde(default)]
|
||||
pub edited: bool,
|
||||
/// Optional message_id this message is replying to.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub reply_to: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize, Debug)]
|
||||
pub struct ChatHistoryPayload {
|
||||
pub channel_id: String,
|
||||
pub messages: Vec<ChatMessagePayload>,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize, Debug)]
|
||||
pub struct ReactionPayload {
|
||||
pub message_id: String,
|
||||
pub channel_id: String,
|
||||
pub emoji: String,
|
||||
#[serde(default)]
|
||||
pub user_id: String,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize, Debug)]
|
||||
pub struct MessageEditPayload {
|
||||
pub message_id: String,
|
||||
pub channel_id: String,
|
||||
pub content: String,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize, Debug)]
|
||||
pub struct MessageDeletePayload {
|
||||
pub message_id: String,
|
||||
pub channel_id: String,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize, Debug)]
|
||||
pub struct UserJoinPayload {
|
||||
pub channel_id: String,
|
||||
pub user_id: String,
|
||||
pub nickname: String,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize, Debug)]
|
||||
pub struct UserLeavePayload {
|
||||
pub channel_id: String,
|
||||
pub user_id: String,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize, Debug)]
|
||||
pub struct ErrorPayload {
|
||||
pub code: u32,
|
||||
pub message: String,
|
||||
}
|
||||
133
src/net/payloads/dm.rs
Normal file
133
src/net/payloads/dm.rs
Normal file
|
|
@ -0,0 +1,133 @@
|
|||
use serde::{Deserialize, Serialize};
|
||||
|
||||
#[derive(Serialize, Deserialize, Debug)]
|
||||
pub struct DmStartPayload {
|
||||
pub target_user_id: String,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize, Debug)]
|
||||
pub struct DmStartResponsePayload {
|
||||
pub dm_id: String,
|
||||
pub other_user_id: String,
|
||||
pub other_nickname: String,
|
||||
pub messages: Vec<DmMessagePayload>,
|
||||
#[serde(default)]
|
||||
pub unread_count: u32,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize, Debug, Clone)]
|
||||
pub struct DmMessagePayload {
|
||||
pub dm_id: String,
|
||||
pub sender_id: String,
|
||||
pub content: String,
|
||||
pub timestamp: i64,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize, Debug)]
|
||||
pub struct DmHistoryPayload {
|
||||
pub dm_id: String,
|
||||
#[serde(default)]
|
||||
pub messages: Vec<DmMessagePayload>,
|
||||
#[serde(default)]
|
||||
pub search_query: Option<String>,
|
||||
#[serde(default)]
|
||||
pub limit: Option<i64>,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize, Debug)]
|
||||
pub struct PresenceUpdatePayload {
|
||||
pub status: String,
|
||||
/// Free-form activity type ("playing", "listening", "watching", "streaming").
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub activity_type: Option<String>,
|
||||
/// Free-form activity text (e.g. "CS2 ranked").
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub activity_text: Option<String>,
|
||||
/// Free-form custom status text (Discord-style "what's on your mind?").
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub custom_status: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize, Debug, Clone)]
|
||||
pub struct PresenceInfoPayload {
|
||||
pub user_id: String,
|
||||
pub status: String,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub custom_status: Option<String>,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub activity: Option<String>,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub activity_text: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize, Debug)]
|
||||
pub struct PresenceSyncPayload {
|
||||
pub presences: Vec<PresenceInfoPayload>,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize, Debug)]
|
||||
pub struct PresenceEventPayload {
|
||||
pub user_id: String,
|
||||
pub status: String,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub custom_status: Option<String>,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub activity: Option<String>,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub activity_text: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize, Debug)]
|
||||
pub struct FriendRequestPayload {
|
||||
pub target_user_id: String,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize, Debug)]
|
||||
pub struct FriendAcceptPayload {
|
||||
pub user_id: String,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize, Debug)]
|
||||
pub struct FriendDeclinePayload {
|
||||
pub user_id: String,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize, Debug)]
|
||||
pub struct FriendRemovePayload {
|
||||
pub user_id: String,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize, Debug, Clone)]
|
||||
pub struct FriendInfoPayload {
|
||||
pub user_id: String,
|
||||
pub nickname: String,
|
||||
pub status: String,
|
||||
pub since: i64,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize, Debug)]
|
||||
pub struct FriendListPayload {
|
||||
pub friends: Vec<FriendInfoPayload>,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize, Debug)]
|
||||
pub struct BlockUserPayload {
|
||||
pub user_id: String,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize, Debug)]
|
||||
pub struct UnblockUserPayload {
|
||||
pub user_id: String,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize, Debug)]
|
||||
pub struct BlockListPayload {
|
||||
pub blocked: Vec<String>,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize, Debug)]
|
||||
pub struct FriendEventPayload {
|
||||
pub event_type: String,
|
||||
pub user_id: String,
|
||||
pub nickname: Option<String>,
|
||||
}
|
||||
176
src/net/payloads/guild.rs
Normal file
176
src/net/payloads/guild.rs
Normal file
|
|
@ -0,0 +1,176 @@
|
|||
use serde::{Deserialize, Serialize};
|
||||
|
||||
#[derive(Serialize, Deserialize, Debug)]
|
||||
pub struct GuildCreatePayload {
|
||||
pub name: String,
|
||||
pub icon_url: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize, Debug, Clone)]
|
||||
pub struct GuildInfoPayload {
|
||||
pub guild_id: String,
|
||||
pub name: String,
|
||||
pub owner_id: String,
|
||||
pub icon_url: Option<String>,
|
||||
pub member_count: u32,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize, Debug)]
|
||||
pub struct GuildListPayload {
|
||||
pub guilds: Vec<GuildInfoPayload>,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize, Debug)]
|
||||
pub struct GuildDeletePayload {
|
||||
pub guild_id: String,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize, Debug)]
|
||||
pub struct GuildJoinPayload {
|
||||
pub guild_id: String,
|
||||
pub invite_code: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize, Debug)]
|
||||
pub struct GuildLeavePayload {
|
||||
pub guild_id: String,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize, Debug)]
|
||||
pub struct UserRoleUpdatePayload {
|
||||
pub user_id: String,
|
||||
pub guild_id: String,
|
||||
pub color: String,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize, Debug)]
|
||||
pub struct InviteCreatePayload {
|
||||
pub guild_id: String,
|
||||
pub max_uses: Option<i64>,
|
||||
pub expires_in_seconds: Option<i64>,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize, Debug)]
|
||||
pub struct InviteAcceptPayload {
|
||||
pub code: String,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize, Debug)]
|
||||
pub struct InviteDeletePayload {
|
||||
pub guild_id: String,
|
||||
pub invite_id: String,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize, Debug)]
|
||||
pub struct RoleCreatePayload {
|
||||
pub guild_id: String,
|
||||
pub name: String,
|
||||
pub color: Option<String>,
|
||||
pub permissions: Option<u64>,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize, Debug)]
|
||||
pub struct RoleDeletePayload {
|
||||
pub guild_id: String,
|
||||
pub role_id: String,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize, Debug)]
|
||||
pub struct GuildMemberKickPayload {
|
||||
pub guild_id: String,
|
||||
pub user_id: String,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize, Debug, Clone)]
|
||||
pub struct InviteInfoPayload {
|
||||
pub id: String,
|
||||
pub guild_id: String,
|
||||
pub guild_name: String,
|
||||
pub code: String,
|
||||
pub creator_id: String,
|
||||
pub max_uses: Option<i64>,
|
||||
pub uses: i64,
|
||||
pub expires_at: Option<i64>,
|
||||
pub created_at: i64,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize, Debug)]
|
||||
pub struct GuildAuditLogFetchPayload {
|
||||
pub guild_id: String,
|
||||
#[serde(default = "default_audit_limit")]
|
||||
pub limit: i64,
|
||||
}
|
||||
|
||||
fn default_audit_limit() -> i64 {
|
||||
50
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize, Debug, Clone)]
|
||||
pub struct AuditLogEntryPayload {
|
||||
pub id: String,
|
||||
pub guild_id: String,
|
||||
pub actor_id: String,
|
||||
pub action: String,
|
||||
#[serde(default)]
|
||||
pub target_id: Option<String>,
|
||||
#[serde(default)]
|
||||
pub target_type: Option<String>,
|
||||
#[serde(default)]
|
||||
pub reason: Option<String>,
|
||||
pub created_at: i64,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize, Debug, Clone)]
|
||||
pub struct GuildAuditLogPayload {
|
||||
pub guild_id: String,
|
||||
pub entries: Vec<AuditLogEntryPayload>,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize, Debug)]
|
||||
pub struct GuildMemberListFetchPayload {
|
||||
pub guild_id: String,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize, Debug, Clone)]
|
||||
pub struct GuildMemberInfoPayload {
|
||||
pub user_id: String,
|
||||
pub nickname: String,
|
||||
pub joined_at: i64,
|
||||
pub role_color: String,
|
||||
pub role_name: String,
|
||||
pub is_owner: bool,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize, Debug, Clone)]
|
||||
pub struct GuildMemberListPayload {
|
||||
pub guild_id: String,
|
||||
pub members: Vec<GuildMemberInfoPayload>,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize, Debug)]
|
||||
pub struct RoleAssignPayload {
|
||||
pub guild_id: String,
|
||||
pub user_id: String,
|
||||
pub role_id: String,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize, Debug)]
|
||||
pub struct GuildRoleListFetchPayload {
|
||||
pub guild_id: String,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize, Debug, Clone)]
|
||||
pub struct GuildRoleInfoPayload {
|
||||
pub id: String,
|
||||
pub guild_id: String,
|
||||
pub name: String,
|
||||
pub color: String,
|
||||
pub permissions: u64,
|
||||
pub position: i32,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize, Debug, Clone)]
|
||||
pub struct GuildRoleListPayload {
|
||||
pub guild_id: String,
|
||||
pub roles: Vec<GuildRoleInfoPayload>,
|
||||
}
|
||||
76
src/net/payloads/mod.rs
Normal file
76
src/net/payloads/mod.rs
Normal file
|
|
@ -0,0 +1,76 @@
|
|||
/// Wire payload types and packet ID constants.
|
||||
pub const PID_HELLO: u16 = 0x0001;
|
||||
pub const PID_AUTH: u16 = 0x0002;
|
||||
pub const PID_SESSION: u16 = 0x0003;
|
||||
pub const PID_PING: u16 = 0x0004;
|
||||
pub const PID_PONG: u16 = 0x0005;
|
||||
pub const PID_VOICE_PACKET: u16 = 0x0010;
|
||||
pub const PID_CHAT_MESSAGE: u16 = 0x0020;
|
||||
pub const PID_CHAT_HISTORY: u16 = 0x0021;
|
||||
pub const PID_JOIN_CHANNEL: u16 = 0x0030;
|
||||
pub const PID_LEAVE_CHANNEL: u16 = 0x0031;
|
||||
pub const PID_CHANNEL_STATE: u16 = 0x0032;
|
||||
pub const PID_CHANNEL_CREATE: u16 = 0x0033;
|
||||
pub const PID_CHANNEL_DELETE: u16 = 0x0034;
|
||||
pub const PID_CHANNEL_LIST: u16 = 0x0035;
|
||||
pub const PID_USER_JOIN: u16 = 0x0040;
|
||||
pub const PID_USER_LEAVE: u16 = 0x0041;
|
||||
pub const PID_DM_START: u16 = 0x0060;
|
||||
pub const PID_DM_MESSAGE: u16 = 0x0061;
|
||||
pub const PID_DM_HISTORY: u16 = 0x0062;
|
||||
pub const PID_DM_READ_ACK: u16 = 0x0063;
|
||||
pub const PID_MESSAGE_REACTION_ADD: u16 = 0x0066;
|
||||
pub const PID_MESSAGE_REACTION_REMOVE: u16 = 0x0067;
|
||||
pub const PID_MESSAGE_EDIT: u16 = 0x0068;
|
||||
pub const PID_MESSAGE_DELETE: u16 = 0x0069;
|
||||
pub const PID_READ_RECEIPT: u16 = 0x0064;
|
||||
pub const PID_READ_RECEIPT_BROADCAST: u16 = 0x0065;
|
||||
pub const PID_TYPING_START: u16 = 0x0070;
|
||||
pub const PID_GUILD_CREATE: u16 = 0x0100;
|
||||
pub const PID_GUILD_DELETE: u16 = 0x0101;
|
||||
pub const PID_GUILD_LIST: u16 = 0x0102;
|
||||
pub const PID_GUILD_MEMBER_JOIN: u16 = 0x0103;
|
||||
pub const PID_GUILD_MEMBER_LEAVE: u16 = 0x0104;
|
||||
pub const PID_GUILD_MEMBER_KICK: u16 = 0x0105;
|
||||
pub const PID_ROLE_CREATE: u16 = 0x0106;
|
||||
pub const PID_ROLE_DELETE: u16 = 0x0107;
|
||||
pub const PID_INVITE_CREATE: u16 = 0x0108;
|
||||
pub const PID_INVITE_ACCEPT: u16 = 0x0109;
|
||||
pub const PID_INVITE_DELETE: u16 = 0x010A;
|
||||
pub const PID_USER_ROLE_UPDATE: u16 = 0x010B;
|
||||
pub const PID_GUILD_AUDIT_LOG_FETCH: u16 = 0x010C;
|
||||
pub const PID_GUILD_AUDIT_LOG: u16 = 0x010D;
|
||||
pub const PID_GUILD_MEMBER_LIST_FETCH: u16 = 0x010E;
|
||||
pub const PID_GUILD_MEMBER_LIST: u16 = 0x010F;
|
||||
pub const PID_GUILD_ROLE_ASSIGN: u16 = 0x0110;
|
||||
pub const PID_GUILD_ROLE_UNASSIGN: u16 = 0x0111;
|
||||
pub const PID_GUILD_ROLE_LIST_FETCH: u16 = 0x0112;
|
||||
pub const PID_GUILD_ROLE_LIST: u16 = 0x0113;
|
||||
pub const PID_PERMISSION_CHECK: u16 = 0x0050;
|
||||
pub const PID_PERMISSION_DENY: u16 = 0x0051;
|
||||
pub const PID_PRESENCE_UPDATE: u16 = 0x0140;
|
||||
pub const PID_PRESENCE_SYNC: u16 = 0x0141;
|
||||
pub const PID_PRESENCE_EVENT: u16 = 0x0142;
|
||||
pub const PID_FRIEND_REQUEST: u16 = 0x0150;
|
||||
pub const PID_FRIEND_ACCEPT: u16 = 0x0151;
|
||||
pub const PID_FRIEND_DECLINE: u16 = 0x0152;
|
||||
pub const PID_FRIEND_REMOVE: u16 = 0x0153;
|
||||
pub const PID_FRIEND_LIST: u16 = 0x0154;
|
||||
pub const PID_BLOCK_USER: u16 = 0x0155;
|
||||
pub const PID_UNBLOCK_USER: u16 = 0x0156;
|
||||
pub const PID_BLOCK_LIST: u16 = 0x0157;
|
||||
pub const PID_FRIEND_EVENT: u16 = 0x0158;
|
||||
pub const PID_ERROR: u16 = 0x00F0;
|
||||
pub const PID_DISCONNECT: u16 = 0x00FF;
|
||||
|
||||
pub const LNEX_VERSION: &str = "v1";
|
||||
pub const HDR_SIZE: usize = 12;
|
||||
pub const MAX_PAYLOAD: u32 = 4 * 1024 * 1024;
|
||||
|
||||
mod channel;
|
||||
mod dm;
|
||||
mod guild;
|
||||
|
||||
pub use channel::*;
|
||||
pub use dm::*;
|
||||
pub use guild::*;
|
||||
167
src/net/session/handlers/core.rs
Normal file
167
src/net/session/handlers/core.rs
Normal file
|
|
@ -0,0 +1,167 @@
|
|||
use std::time::Duration;
|
||||
|
||||
use anyhow::Result;
|
||||
use tokio::net::TcpStream;
|
||||
use tokio::sync::mpsc;
|
||||
use tokio::time::{MissedTickBehavior, interval};
|
||||
use tracing::warn;
|
||||
|
||||
use crate::identity::Identity;
|
||||
use crate::net::{
|
||||
framing, handshake, internal,
|
||||
payloads::*,
|
||||
types::{NetCommand, NetEvent},
|
||||
};
|
||||
use serde_json;
|
||||
|
||||
use super::super::switch::ReconnectRequested;
|
||||
use super::{VoiceState, handle_cmd};
|
||||
|
||||
pub async fn session_loop(
|
||||
identity: &Identity,
|
||||
address: &str,
|
||||
channels: &mut Vec<String>,
|
||||
restored: bool,
|
||||
cmd_rx: &mut mpsc::Receiver<NetCommand>,
|
||||
event_tx: &mpsc::Sender<NetEvent>,
|
||||
) -> Result<()> {
|
||||
let mut stream = TcpStream::connect(address).await?;
|
||||
let mut seq = 0u32;
|
||||
|
||||
let (session_id, node_name, private_mode, crypto) =
|
||||
handshake::run(&mut stream, identity, &mut seq).await?;
|
||||
let _ = event_tx
|
||||
.send(NetEvent::Connected {
|
||||
session_id: session_id.clone(),
|
||||
node_name,
|
||||
restored,
|
||||
private_mode,
|
||||
})
|
||||
.await;
|
||||
|
||||
for channel_id in channels.clone() {
|
||||
framing::io::write_encrypted(
|
||||
&mut stream,
|
||||
PID_JOIN_CHANNEL,
|
||||
&mut seq,
|
||||
&serde_json::to_vec(&JoinChannelPayload { channel_id })?,
|
||||
&crypto,
|
||||
)
|
||||
.await?;
|
||||
}
|
||||
|
||||
let mut voice_state = VoiceState::new(&crypto, event_tx).await?;
|
||||
let mut voice_endpoint: Option<std::net::SocketAddr> = None;
|
||||
let mut ping_tick = interval(Duration::from_secs(2));
|
||||
ping_tick.set_missed_tick_behavior(MissedTickBehavior::Delay);
|
||||
|
||||
loop {
|
||||
tokio::select! {
|
||||
_ = ping_tick.tick() => {
|
||||
let ts = now_ms();
|
||||
let payload = serde_json::to_vec(&PingPayload { timestamp: ts })?;
|
||||
framing::io::write_encrypted(&mut stream, PID_PING, &mut seq, &payload, &crypto).await?;
|
||||
}
|
||||
result = framing::io::read_encrypted(&mut stream, &crypto) => {
|
||||
let pkt = result?;
|
||||
if pkt.packet_id == PID_CHANNEL_STATE
|
||||
&& let Ok(p) = serde_json::from_slice::<ChannelStatePayload>(&pkt.payload)
|
||||
{
|
||||
voice_endpoint = if p.voice_endpoint.is_empty() {
|
||||
None
|
||||
} else {
|
||||
p.voice_endpoint.parse().ok()
|
||||
};
|
||||
}
|
||||
internal::dispatch::incoming(pkt.packet_id, &pkt.payload, event_tx).await?;
|
||||
}
|
||||
cmd = cmd_rx.recv() => {
|
||||
match cmd {
|
||||
None | Some(NetCommand::Disconnect) => {
|
||||
let _ = framing::io::write_encrypted(&mut stream, PID_DISCONNECT, &mut seq,
|
||||
&serde_json::to_vec(&serde_json::json!({"reason":"bye"})).unwrap(), &crypto).await;
|
||||
return Ok(());
|
||||
}
|
||||
Some(NetCommand::Connect { address, auto_reconnect }) => {
|
||||
warn!("connect while connected to {address}, reconnecting");
|
||||
if channels.is_empty() {
|
||||
*channels = vec!["general".into()];
|
||||
}
|
||||
return Err(anyhow::Error::new(ReconnectRequested {
|
||||
address,
|
||||
auto_reconnect,
|
||||
}));
|
||||
}
|
||||
Some(NetCommand::JoinChannel { channel_id }) => {
|
||||
track_channel(channels, &channel_id);
|
||||
framing::io::write_encrypted(&mut stream, PID_JOIN_CHANNEL, &mut seq,
|
||||
&serde_json::to_vec(&JoinChannelPayload { channel_id })?, &crypto).await?;
|
||||
}
|
||||
Some(NetCommand::LeaveChannel { channel_id }) => {
|
||||
channels.retain(|c| c != &channel_id);
|
||||
framing::io::write_encrypted(&mut stream, PID_LEAVE_CHANNEL, &mut seq,
|
||||
&serde_json::to_vec(&LeaveChannelPayload { channel_id })?, &crypto).await?;
|
||||
}
|
||||
Some(NetCommand::ChannelCreate { channel_id, channel_name, kind }) => {
|
||||
let payload = serde_json::to_vec(&ChannelCreatePayload {
|
||||
channel_id,
|
||||
channel_name,
|
||||
kind,
|
||||
guild_id: None,
|
||||
})?;
|
||||
framing::io::write_encrypted(&mut stream, PID_CHANNEL_CREATE, &mut seq, &payload, &crypto).await?;
|
||||
}
|
||||
Some(NetCommand::ChannelDelete { channel_id }) => {
|
||||
let payload = serde_json::to_vec(&ChannelDeletePayload { channel_id })?;
|
||||
framing::io::write_encrypted(&mut stream, PID_CHANNEL_DELETE, &mut seq, &payload, &crypto).await?;
|
||||
}
|
||||
Some(NetCommand::ChannelList) => {
|
||||
framing::io::write_encrypted(&mut stream, PID_CHANNEL_LIST, &mut seq, b"{}", &crypto).await?;
|
||||
}
|
||||
Some(NetCommand::SendChat { channel_id, content, reply_to }) => {
|
||||
let msg = ChatMessagePayload {
|
||||
message_id: uuid_v4(), channel_id,
|
||||
sender_id: identity.pubkey_hex.clone(),
|
||||
content, timestamp: now_ms(),
|
||||
edited: false,
|
||||
reply_to,
|
||||
};
|
||||
framing::io::write_encrypted(&mut stream, PID_CHAT_MESSAGE, &mut seq, &serde_json::to_vec(&msg)?, &crypto).await?;
|
||||
}
|
||||
Some(NetCommand::SendVoice { channel_id, voice_seq: voice_pkt_seq, timestamp, opus_data }) => {
|
||||
let sender_pubkey = identity.verifying_key()
|
||||
.map(|k| k.to_bytes())
|
||||
.unwrap_or([0u8; 32]);
|
||||
voice_state.send_voice(channel_id, voice_pkt_seq, timestamp, &opus_data, &crypto, voice_endpoint, &sender_pubkey).await?;
|
||||
}
|
||||
Some(NetCommand::ReadReceipt { channel_id, last_read_message_id }) => {
|
||||
let payload = serde_json::to_vec(&serde_json::json!({
|
||||
"channel_id": channel_id,
|
||||
"last_read_message_id": last_read_message_id,
|
||||
"user_id": identity.pubkey_hex.clone(),
|
||||
}))?;
|
||||
framing::io::write_encrypted(&mut stream, PID_READ_RECEIPT, &mut seq, &payload, &crypto).await?;
|
||||
}
|
||||
Some(other) => handle_cmd(other, &mut stream, &mut seq, &crypto, identity).await?,
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn now_ms() -> i64 {
|
||||
std::time::SystemTime::now()
|
||||
.duration_since(std::time::UNIX_EPOCH)
|
||||
.unwrap_or_default()
|
||||
.as_millis() as i64
|
||||
}
|
||||
|
||||
pub(super) fn uuid_v4() -> String {
|
||||
uuid::Uuid::new_v4().to_string()
|
||||
}
|
||||
|
||||
fn track_channel(channels: &mut Vec<String>, channel_id: &str) {
|
||||
if !channels.iter().any(|c| c == channel_id) {
|
||||
channels.push(channel_id.to_string());
|
||||
}
|
||||
}
|
||||
7
src/net/session/handlers/mod.rs
Normal file
7
src/net/session/handlers/mod.rs
Normal file
|
|
@ -0,0 +1,7 @@
|
|||
mod core;
|
||||
mod social;
|
||||
mod voice;
|
||||
|
||||
pub use core::session_loop;
|
||||
pub use social::handle_cmd;
|
||||
pub use voice::State as VoiceState;
|
||||
62
src/net/session/handlers/social/friends.rs
Normal file
62
src/net/session/handlers/social/friends.rs
Normal file
|
|
@ -0,0 +1,62 @@
|
|||
use anyhow::Result;
|
||||
use serde_json;
|
||||
use tokio::net::TcpStream;
|
||||
|
||||
use crate::net::{crypto::SessionCrypto, framing, payloads::*, types::NetCommand};
|
||||
|
||||
pub async fn handle_cmd(
|
||||
cmd: NetCommand,
|
||||
stream: &mut TcpStream,
|
||||
seq: &mut u32,
|
||||
crypto: &SessionCrypto,
|
||||
) -> Result<()> {
|
||||
match cmd {
|
||||
NetCommand::PresenceUpdate {
|
||||
status,
|
||||
custom_status,
|
||||
activity,
|
||||
activity_text,
|
||||
} => {
|
||||
let payload = serde_json::to_vec(&PresenceUpdatePayload {
|
||||
status,
|
||||
activity_type: activity,
|
||||
activity_text,
|
||||
custom_status,
|
||||
})?;
|
||||
framing::io::write_encrypted(stream, PID_PRESENCE_UPDATE, seq, &payload, crypto)
|
||||
.await?;
|
||||
}
|
||||
NetCommand::FriendRequest { target_user_id } => {
|
||||
let payload = serde_json::to_vec(&FriendRequestPayload { target_user_id })?;
|
||||
framing::io::write_encrypted(stream, PID_FRIEND_REQUEST, seq, &payload, crypto).await?;
|
||||
}
|
||||
NetCommand::FriendAccept { user_id } => {
|
||||
let payload = serde_json::to_vec(&FriendAcceptPayload { user_id })?;
|
||||
framing::io::write_encrypted(stream, PID_FRIEND_ACCEPT, seq, &payload, crypto).await?;
|
||||
}
|
||||
NetCommand::FriendDecline { user_id } => {
|
||||
let payload = serde_json::to_vec(&FriendDeclinePayload { user_id })?;
|
||||
framing::io::write_encrypted(stream, PID_FRIEND_DECLINE, seq, &payload, crypto).await?;
|
||||
}
|
||||
NetCommand::FriendRemove { user_id } => {
|
||||
let payload = serde_json::to_vec(&FriendRemovePayload { user_id })?;
|
||||
framing::io::write_encrypted(stream, PID_FRIEND_REMOVE, seq, &payload, crypto).await?;
|
||||
}
|
||||
NetCommand::FriendList => {
|
||||
framing::io::write_encrypted(stream, PID_FRIEND_LIST, seq, b"{}", crypto).await?;
|
||||
}
|
||||
NetCommand::BlockUser { user_id } => {
|
||||
let payload = serde_json::to_vec(&BlockUserPayload { user_id })?;
|
||||
framing::io::write_encrypted(stream, PID_BLOCK_USER, seq, &payload, crypto).await?;
|
||||
}
|
||||
NetCommand::UnblockUser { user_id } => {
|
||||
let payload = serde_json::to_vec(&UnblockUserPayload { user_id })?;
|
||||
framing::io::write_encrypted(stream, PID_UNBLOCK_USER, seq, &payload, crypto).await?;
|
||||
}
|
||||
NetCommand::BlockList => {
|
||||
framing::io::write_encrypted(stream, PID_BLOCK_LIST, seq, b"{}", crypto).await?;
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
143
src/net/session/handlers/social/guild.rs
Normal file
143
src/net/session/handlers/social/guild.rs
Normal file
|
|
@ -0,0 +1,143 @@
|
|||
use anyhow::Result;
|
||||
use serde_json;
|
||||
use tokio::net::TcpStream;
|
||||
|
||||
use crate::net::{crypto::SessionCrypto, framing, payloads::*, types::NetCommand};
|
||||
|
||||
pub async fn handle_cmd(
|
||||
cmd: NetCommand,
|
||||
stream: &mut TcpStream,
|
||||
seq: &mut u32,
|
||||
crypto: &SessionCrypto,
|
||||
) -> Result<()> {
|
||||
match cmd {
|
||||
NetCommand::GuildCreate { name } => {
|
||||
let payload = serde_json::to_vec(&GuildCreatePayload {
|
||||
name,
|
||||
icon_url: None,
|
||||
})?;
|
||||
framing::io::write_encrypted(stream, PID_GUILD_CREATE, seq, &payload, crypto).await?;
|
||||
}
|
||||
NetCommand::GuildDelete { guild_id } => {
|
||||
let payload = serde_json::to_vec(&GuildDeletePayload { guild_id })?;
|
||||
framing::io::write_encrypted(stream, PID_GUILD_DELETE, seq, &payload, crypto).await?;
|
||||
}
|
||||
NetCommand::GuildList => {
|
||||
framing::io::write_encrypted(stream, PID_GUILD_LIST, seq, b"{}", crypto).await?;
|
||||
}
|
||||
NetCommand::GuildJoin {
|
||||
guild_id,
|
||||
invite_code,
|
||||
} => {
|
||||
let payload = serde_json::to_vec(&GuildJoinPayload {
|
||||
guild_id,
|
||||
invite_code,
|
||||
})?;
|
||||
framing::io::write_encrypted(stream, PID_GUILD_MEMBER_JOIN, seq, &payload, crypto)
|
||||
.await?;
|
||||
}
|
||||
NetCommand::GuildLeave { guild_id } => {
|
||||
let payload = serde_json::to_vec(&GuildLeavePayload { guild_id })?;
|
||||
framing::io::write_encrypted(stream, PID_GUILD_MEMBER_LEAVE, seq, &payload, crypto)
|
||||
.await?;
|
||||
}
|
||||
NetCommand::InviteCreate {
|
||||
guild_id,
|
||||
max_uses,
|
||||
expires_in_seconds,
|
||||
} => {
|
||||
let payload = serde_json::to_vec(&InviteCreatePayload {
|
||||
guild_id,
|
||||
max_uses,
|
||||
expires_in_seconds,
|
||||
})?;
|
||||
framing::io::write_encrypted(stream, PID_INVITE_CREATE, seq, &payload, crypto).await?;
|
||||
}
|
||||
NetCommand::InviteAccept { code } => {
|
||||
let payload = serde_json::to_vec(&InviteAcceptPayload { code })?;
|
||||
framing::io::write_encrypted(stream, PID_INVITE_ACCEPT, seq, &payload, crypto).await?;
|
||||
}
|
||||
NetCommand::InviteDelete {
|
||||
guild_id,
|
||||
invite_id,
|
||||
} => {
|
||||
let payload = serde_json::to_vec(&InviteDeletePayload {
|
||||
guild_id,
|
||||
invite_id,
|
||||
})?;
|
||||
framing::io::write_encrypted(stream, PID_INVITE_DELETE, seq, &payload, crypto).await?;
|
||||
}
|
||||
NetCommand::RoleCreate {
|
||||
guild_id,
|
||||
name,
|
||||
color,
|
||||
permissions,
|
||||
} => {
|
||||
let payload = serde_json::to_vec(&RoleCreatePayload {
|
||||
guild_id,
|
||||
name,
|
||||
color,
|
||||
permissions,
|
||||
})?;
|
||||
framing::io::write_encrypted(stream, PID_ROLE_CREATE, seq, &payload, crypto).await?;
|
||||
}
|
||||
NetCommand::RoleDelete { guild_id, role_id } => {
|
||||
let payload = serde_json::to_vec(&RoleDeletePayload { guild_id, role_id })?;
|
||||
framing::io::write_encrypted(stream, PID_ROLE_DELETE, seq, &payload, crypto).await?;
|
||||
}
|
||||
NetCommand::GuildMemberKick { guild_id, user_id } => {
|
||||
let payload = serde_json::to_vec(&GuildMemberKickPayload { guild_id, user_id })?;
|
||||
framing::io::write_encrypted(stream, PID_GUILD_MEMBER_KICK, seq, &payload, crypto)
|
||||
.await?;
|
||||
}
|
||||
NetCommand::GuildAuditLogFetch { guild_id, limit } => {
|
||||
let payload = serde_json::to_vec(&GuildAuditLogFetchPayload { guild_id, limit })?;
|
||||
framing::io::write_encrypted(stream, PID_GUILD_AUDIT_LOG_FETCH, seq, &payload, crypto)
|
||||
.await?;
|
||||
}
|
||||
NetCommand::GuildMemberListFetch { guild_id } => {
|
||||
let payload = serde_json::to_vec(&GuildMemberListFetchPayload { guild_id })?;
|
||||
framing::io::write_encrypted(
|
||||
stream,
|
||||
PID_GUILD_MEMBER_LIST_FETCH,
|
||||
seq,
|
||||
&payload,
|
||||
crypto,
|
||||
)
|
||||
.await?;
|
||||
}
|
||||
NetCommand::GuildRoleAssign {
|
||||
guild_id,
|
||||
user_id,
|
||||
role_id,
|
||||
} => {
|
||||
let payload = serde_json::to_vec(&RoleAssignPayload {
|
||||
guild_id,
|
||||
user_id,
|
||||
role_id,
|
||||
})?;
|
||||
framing::io::write_encrypted(stream, PID_GUILD_ROLE_ASSIGN, seq, &payload, crypto)
|
||||
.await?;
|
||||
}
|
||||
NetCommand::GuildRoleUnassign {
|
||||
guild_id,
|
||||
user_id,
|
||||
role_id,
|
||||
} => {
|
||||
let payload = serde_json::to_vec(&RoleAssignPayload {
|
||||
guild_id,
|
||||
user_id,
|
||||
role_id,
|
||||
})?;
|
||||
framing::io::write_encrypted(stream, PID_GUILD_ROLE_UNASSIGN, seq, &payload, crypto)
|
||||
.await?;
|
||||
}
|
||||
NetCommand::GuildRoleListFetch { guild_id } => {
|
||||
let payload = serde_json::to_vec(&GuildRoleListFetchPayload { guild_id })?;
|
||||
framing::io::write_encrypted(stream, PID_GUILD_ROLE_LIST_FETCH, seq, &payload, crypto)
|
||||
.await?;
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
146
src/net/session/handlers/social/mod.rs
Normal file
146
src/net/session/handlers/social/mod.rs
Normal file
|
|
@ -0,0 +1,146 @@
|
|||
mod friends;
|
||||
mod guild;
|
||||
|
||||
use anyhow::Result;
|
||||
use serde_json;
|
||||
use tokio::net::TcpStream;
|
||||
|
||||
use crate::identity::Identity;
|
||||
use crate::net::{crypto::SessionCrypto, framing, payloads::*, types::NetCommand};
|
||||
|
||||
use super::core::now_ms;
|
||||
|
||||
pub async fn handle_cmd(
|
||||
cmd: NetCommand,
|
||||
stream: &mut TcpStream,
|
||||
seq: &mut u32,
|
||||
crypto: &SessionCrypto,
|
||||
identity: &Identity,
|
||||
) -> Result<()> {
|
||||
match cmd {
|
||||
cmd @ (NetCommand::GuildCreate { .. }
|
||||
| NetCommand::GuildDelete { .. }
|
||||
| NetCommand::GuildList
|
||||
| NetCommand::GuildJoin { .. }
|
||||
| NetCommand::GuildLeave { .. }
|
||||
| NetCommand::InviteCreate { .. }
|
||||
| NetCommand::InviteAccept { .. }
|
||||
| NetCommand::InviteDelete { .. }
|
||||
| NetCommand::RoleCreate { .. }
|
||||
| NetCommand::RoleDelete { .. }
|
||||
| NetCommand::GuildMemberKick { .. }
|
||||
| NetCommand::GuildAuditLogFetch { .. }
|
||||
| NetCommand::GuildMemberListFetch { .. }
|
||||
| NetCommand::GuildRoleAssign { .. }
|
||||
| NetCommand::GuildRoleUnassign { .. }
|
||||
| NetCommand::GuildRoleListFetch { .. }) => {
|
||||
guild::handle_cmd(cmd, stream, seq, crypto).await?
|
||||
}
|
||||
|
||||
cmd @ (NetCommand::PresenceUpdate { .. }
|
||||
| NetCommand::FriendRequest { .. }
|
||||
| NetCommand::FriendAccept { .. }
|
||||
| NetCommand::FriendDecline { .. }
|
||||
| NetCommand::FriendRemove { .. }
|
||||
| NetCommand::FriendList
|
||||
| NetCommand::BlockUser { .. }
|
||||
| NetCommand::UnblockUser { .. }
|
||||
| NetCommand::BlockList) => friends::handle_cmd(cmd, stream, seq, crypto).await?,
|
||||
|
||||
NetCommand::ReactionAdd {
|
||||
channel_id,
|
||||
message_id,
|
||||
emoji,
|
||||
} => {
|
||||
let payload = serde_json::to_vec(&ReactionPayload {
|
||||
message_id,
|
||||
channel_id,
|
||||
emoji,
|
||||
user_id: String::new(),
|
||||
})?;
|
||||
framing::io::write_encrypted(stream, PID_MESSAGE_REACTION_ADD, seq, &payload, crypto)
|
||||
.await?;
|
||||
}
|
||||
NetCommand::ReactionRemove {
|
||||
channel_id,
|
||||
message_id,
|
||||
emoji,
|
||||
} => {
|
||||
let payload = serde_json::to_vec(&ReactionPayload {
|
||||
message_id,
|
||||
channel_id,
|
||||
emoji,
|
||||
user_id: String::new(),
|
||||
})?;
|
||||
framing::io::write_encrypted(
|
||||
stream,
|
||||
PID_MESSAGE_REACTION_REMOVE,
|
||||
seq,
|
||||
&payload,
|
||||
crypto,
|
||||
)
|
||||
.await?;
|
||||
}
|
||||
NetCommand::MessageEdit {
|
||||
channel_id,
|
||||
message_id,
|
||||
content,
|
||||
} => {
|
||||
let payload = serde_json::to_vec(&MessageEditPayload {
|
||||
message_id,
|
||||
channel_id,
|
||||
content,
|
||||
})?;
|
||||
framing::io::write_encrypted(stream, PID_MESSAGE_EDIT, seq, &payload, crypto).await?;
|
||||
}
|
||||
NetCommand::MessageDelete {
|
||||
channel_id,
|
||||
message_id,
|
||||
} => {
|
||||
let payload = serde_json::to_vec(&MessageDeletePayload {
|
||||
message_id,
|
||||
channel_id,
|
||||
})?;
|
||||
framing::io::write_encrypted(stream, PID_MESSAGE_DELETE, seq, &payload, crypto).await?;
|
||||
}
|
||||
NetCommand::DmStart { target_user_id } => {
|
||||
let payload = serde_json::to_vec(&DmStartPayload { target_user_id })?;
|
||||
framing::io::write_encrypted(stream, PID_DM_START, seq, &payload, crypto).await?;
|
||||
}
|
||||
NetCommand::DmSend { dm_id, content } => {
|
||||
let msg = DmMessagePayload {
|
||||
dm_id,
|
||||
sender_id: identity.pubkey_hex.clone(),
|
||||
content,
|
||||
timestamp: now_ms(),
|
||||
};
|
||||
framing::io::write_encrypted(
|
||||
stream,
|
||||
PID_DM_MESSAGE,
|
||||
seq,
|
||||
&serde_json::to_vec(&msg)?,
|
||||
crypto,
|
||||
)
|
||||
.await?;
|
||||
}
|
||||
NetCommand::TypingStart { channel_id } => {
|
||||
let payload = serde_json::to_vec(&serde_json::json!({"channel_id": channel_id}))?;
|
||||
framing::io::write_encrypted(stream, PID_TYPING_START, seq, &payload, crypto).await?;
|
||||
}
|
||||
NetCommand::DmReadAck { dm_id } => {
|
||||
let payload = serde_json::to_vec(&serde_json::json!({"dm_id": dm_id}))?;
|
||||
framing::io::write_encrypted(stream, PID_DM_READ_ACK, seq, &payload, crypto).await?;
|
||||
}
|
||||
NetCommand::DmSearch { dm_id, query } => {
|
||||
let payload = serde_json::to_vec(&DmHistoryPayload {
|
||||
dm_id,
|
||||
messages: vec![],
|
||||
search_query: if query.is_empty() { None } else { Some(query) },
|
||||
limit: None,
|
||||
})?;
|
||||
framing::io::write_encrypted(stream, PID_DM_HISTORY, seq, &payload, crypto).await?;
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
47
src/net/session/handlers/voice.rs
Normal file
47
src/net/session/handlers/voice.rs
Normal file
|
|
@ -0,0 +1,47 @@
|
|||
use std::sync::Arc;
|
||||
|
||||
use anyhow::Result;
|
||||
use tokio::net::UdpSocket;
|
||||
use tokio::sync::mpsc;
|
||||
|
||||
use crate::net::{crypto::SessionCrypto, types::NetEvent};
|
||||
|
||||
pub struct State {
|
||||
pub udp: Arc<UdpSocket>,
|
||||
pub seq: u64,
|
||||
}
|
||||
|
||||
impl State {
|
||||
pub async fn new(crypto: &SessionCrypto, event_tx: &mpsc::Sender<NetEvent>) -> Result<Self> {
|
||||
let udp = Arc::new(UdpSocket::bind("0.0.0.0:0").await?);
|
||||
crate::net::voice::spawn_recv(udp.clone(), (*crypto).clone(), event_tx.clone());
|
||||
Ok(Self { udp, seq: 0 })
|
||||
}
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub async fn send_voice(
|
||||
&mut self,
|
||||
channel_id: u64,
|
||||
voice_pkt_seq: u32,
|
||||
timestamp: u32,
|
||||
opus_data: &[u8],
|
||||
crypto: &SessionCrypto,
|
||||
endpoint: Option<std::net::SocketAddr>,
|
||||
sender_pubkey: &[u8; 32],
|
||||
) -> Result<()> {
|
||||
if let Some(ep) = endpoint {
|
||||
let pkt = crate::net::voice::build_packet(
|
||||
channel_id,
|
||||
voice_pkt_seq,
|
||||
timestamp,
|
||||
opus_data,
|
||||
crypto,
|
||||
self.seq,
|
||||
sender_pubkey,
|
||||
);
|
||||
let _ = self.udp.send_to(&pkt, ep).await;
|
||||
self.seq += 1;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
6
src/net/session/mod.rs
Normal file
6
src/net/session/mod.rs
Normal file
|
|
@ -0,0 +1,6 @@
|
|||
mod handlers;
|
||||
mod reconnect;
|
||||
mod switch;
|
||||
mod task;
|
||||
|
||||
pub use task::net_task;
|
||||
24
src/net/session/reconnect.rs
Normal file
24
src/net/session/reconnect.rs
Normal file
|
|
@ -0,0 +1,24 @@
|
|||
use std::time::Duration;
|
||||
|
||||
/// Max delay between reconnect attempts.
|
||||
pub const MAX_BACKOFF_SECS: u64 = 30;
|
||||
|
||||
/// Exponential backoff after a failed session (1s, 2s, 4s, … capped at 30s).
|
||||
pub fn backoff_delay(failure_count: u32) -> Duration {
|
||||
let shift = failure_count.min(5);
|
||||
let secs = (1u64 << shift).min(MAX_BACKOFF_SECS);
|
||||
Duration::from_secs(secs)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn backoff_grows_and_caps() {
|
||||
assert_eq!(backoff_delay(0).as_secs(), 1);
|
||||
assert_eq!(backoff_delay(1).as_secs(), 2);
|
||||
assert_eq!(backoff_delay(3).as_secs(), 8);
|
||||
assert_eq!(backoff_delay(10).as_secs(), MAX_BACKOFF_SECS);
|
||||
}
|
||||
}
|
||||
20
src/net/session/switch.rs
Normal file
20
src/net/session/switch.rs
Normal file
|
|
@ -0,0 +1,20 @@
|
|||
/// User switched node while connected (`NetCommand::Connect`).
|
||||
#[derive(Debug)]
|
||||
pub struct ReconnectRequested {
|
||||
pub address: String,
|
||||
pub auto_reconnect: bool,
|
||||
}
|
||||
|
||||
impl std::fmt::Display for ReconnectRequested {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
write!(f, "reconnect to {}", self.address)
|
||||
}
|
||||
}
|
||||
|
||||
impl std::error::Error for ReconnectRequested {}
|
||||
|
||||
pub struct SessionTarget {
|
||||
pub address: String,
|
||||
pub auto_reconnect: bool,
|
||||
pub channels: Vec<String>,
|
||||
}
|
||||
116
src/net/session/task.rs
Normal file
116
src/net/session/task.rs
Normal file
|
|
@ -0,0 +1,116 @@
|
|||
use tokio::sync::mpsc;
|
||||
use tokio::time::sleep;
|
||||
use tracing::{error, info};
|
||||
|
||||
use crate::identity::Identity;
|
||||
use crate::net::types::{NetCommand, NetEvent};
|
||||
|
||||
use super::{
|
||||
handlers::session_loop,
|
||||
reconnect,
|
||||
switch::{ReconnectRequested, SessionTarget},
|
||||
};
|
||||
|
||||
pub async fn net_task(
|
||||
identity: Identity,
|
||||
mut cmd_rx: mpsc::Receiver<NetCommand>,
|
||||
event_tx: mpsc::Sender<NetEvent>,
|
||||
) {
|
||||
let mut target: Option<SessionTarget> = None;
|
||||
let mut failures: u32 = 0;
|
||||
|
||||
loop {
|
||||
let Some(mut session) = target.take() else {
|
||||
match wait_for_connect(&mut cmd_rx).await {
|
||||
Some(t) => {
|
||||
failures = 0;
|
||||
target = Some(t);
|
||||
}
|
||||
None => return,
|
||||
}
|
||||
continue;
|
||||
};
|
||||
|
||||
if failures > 0 {
|
||||
let delay = reconnect::backoff_delay(failures - 1);
|
||||
let _ = event_tx
|
||||
.send(NetEvent::Reconnecting {
|
||||
attempt: failures,
|
||||
delay_secs: delay.as_secs(),
|
||||
})
|
||||
.await;
|
||||
sleep(delay).await;
|
||||
}
|
||||
|
||||
info!(
|
||||
"connecting to {} (attempt {})",
|
||||
session.address,
|
||||
failures + 1
|
||||
);
|
||||
|
||||
let restored = failures > 0;
|
||||
match session_loop(
|
||||
&identity,
|
||||
&session.address,
|
||||
&mut session.channels,
|
||||
restored,
|
||||
&mut cmd_rx,
|
||||
&event_tx,
|
||||
)
|
||||
.await
|
||||
{
|
||||
Ok(()) => {
|
||||
failures = 0;
|
||||
let _ = event_tx
|
||||
.send(NetEvent::Disconnected {
|
||||
reason: "disconnected".into(),
|
||||
will_retry: false,
|
||||
})
|
||||
.await;
|
||||
}
|
||||
Err(e) => {
|
||||
if let Some(req) = e.downcast_ref::<ReconnectRequested>() {
|
||||
info!("switching node to {}", req.address);
|
||||
session.address = req.address.clone();
|
||||
session.auto_reconnect = req.auto_reconnect;
|
||||
failures = 0;
|
||||
target = Some(session);
|
||||
continue;
|
||||
}
|
||||
error!("session ended: {e}");
|
||||
let retry = session.auto_reconnect;
|
||||
let _ = event_tx
|
||||
.send(NetEvent::Disconnected {
|
||||
reason: e.to_string(),
|
||||
will_retry: retry,
|
||||
})
|
||||
.await;
|
||||
if retry {
|
||||
failures = failures.saturating_add(1);
|
||||
target = Some(session);
|
||||
} else {
|
||||
failures = 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async fn wait_for_connect(cmd_rx: &mut mpsc::Receiver<NetCommand>) -> Option<SessionTarget> {
|
||||
loop {
|
||||
match cmd_rx.recv().await {
|
||||
Some(NetCommand::Connect {
|
||||
address,
|
||||
auto_reconnect,
|
||||
}) => {
|
||||
return Some(SessionTarget {
|
||||
address,
|
||||
auto_reconnect,
|
||||
channels: vec!["general".into()],
|
||||
});
|
||||
}
|
||||
Some(NetCommand::Disconnect) | None => return None,
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
162
src/net/types/command.rs
Normal file
162
src/net/types/command.rs
Normal file
|
|
@ -0,0 +1,162 @@
|
|||
#[derive(Debug)]
|
||||
pub enum NetCommand {
|
||||
Connect {
|
||||
address: String,
|
||||
auto_reconnect: bool,
|
||||
},
|
||||
JoinChannel {
|
||||
channel_id: String,
|
||||
},
|
||||
LeaveChannel {
|
||||
channel_id: String,
|
||||
},
|
||||
ChannelCreate {
|
||||
channel_id: String,
|
||||
channel_name: String,
|
||||
kind: String,
|
||||
},
|
||||
ChannelDelete {
|
||||
channel_id: String,
|
||||
},
|
||||
ChannelList,
|
||||
SendChat {
|
||||
channel_id: String,
|
||||
content: String,
|
||||
/// Optional message_id this message is replying to.
|
||||
reply_to: Option<String>,
|
||||
},
|
||||
SendVoice {
|
||||
channel_id: u64,
|
||||
voice_seq: u32,
|
||||
timestamp: u32,
|
||||
opus_data: Vec<u8>,
|
||||
},
|
||||
DmStart {
|
||||
target_user_id: String,
|
||||
},
|
||||
DmSend {
|
||||
dm_id: String,
|
||||
content: String,
|
||||
},
|
||||
DmReadAck {
|
||||
dm_id: String,
|
||||
},
|
||||
DmSearch {
|
||||
dm_id: String,
|
||||
query: String,
|
||||
},
|
||||
GuildCreate {
|
||||
name: String,
|
||||
},
|
||||
GuildDelete {
|
||||
guild_id: String,
|
||||
},
|
||||
GuildList,
|
||||
GuildJoin {
|
||||
guild_id: String,
|
||||
invite_code: Option<String>,
|
||||
},
|
||||
GuildLeave {
|
||||
guild_id: String,
|
||||
},
|
||||
InviteCreate {
|
||||
guild_id: String,
|
||||
max_uses: Option<i64>,
|
||||
expires_in_seconds: Option<i64>,
|
||||
},
|
||||
InviteAccept {
|
||||
code: String,
|
||||
},
|
||||
InviteDelete {
|
||||
guild_id: String,
|
||||
invite_id: String,
|
||||
},
|
||||
RoleCreate {
|
||||
guild_id: String,
|
||||
name: String,
|
||||
color: Option<String>,
|
||||
permissions: Option<u64>,
|
||||
},
|
||||
RoleDelete {
|
||||
guild_id: String,
|
||||
role_id: String,
|
||||
},
|
||||
GuildMemberKick {
|
||||
guild_id: String,
|
||||
user_id: String,
|
||||
},
|
||||
GuildAuditLogFetch {
|
||||
guild_id: String,
|
||||
limit: i64,
|
||||
},
|
||||
GuildMemberListFetch {
|
||||
guild_id: String,
|
||||
},
|
||||
GuildRoleAssign {
|
||||
guild_id: String,
|
||||
user_id: String,
|
||||
role_id: String,
|
||||
},
|
||||
GuildRoleUnassign {
|
||||
guild_id: String,
|
||||
user_id: String,
|
||||
role_id: String,
|
||||
},
|
||||
GuildRoleListFetch {
|
||||
guild_id: String,
|
||||
},
|
||||
PresenceUpdate {
|
||||
status: String,
|
||||
custom_status: Option<String>,
|
||||
activity: Option<String>,
|
||||
/// Free-form text describing the current activity (e.g. "playing CS2").
|
||||
activity_text: Option<String>,
|
||||
},
|
||||
TypingStart {
|
||||
channel_id: String,
|
||||
},
|
||||
ReadReceipt {
|
||||
channel_id: String,
|
||||
last_read_message_id: String,
|
||||
},
|
||||
FriendRequest {
|
||||
target_user_id: String,
|
||||
},
|
||||
FriendAccept {
|
||||
user_id: String,
|
||||
},
|
||||
FriendDecline {
|
||||
user_id: String,
|
||||
},
|
||||
FriendRemove {
|
||||
user_id: String,
|
||||
},
|
||||
FriendList,
|
||||
BlockUser {
|
||||
user_id: String,
|
||||
},
|
||||
UnblockUser {
|
||||
user_id: String,
|
||||
},
|
||||
BlockList,
|
||||
ReactionAdd {
|
||||
channel_id: String,
|
||||
message_id: String,
|
||||
emoji: String,
|
||||
},
|
||||
ReactionRemove {
|
||||
channel_id: String,
|
||||
message_id: String,
|
||||
emoji: String,
|
||||
},
|
||||
MessageEdit {
|
||||
channel_id: String,
|
||||
message_id: String,
|
||||
content: String,
|
||||
},
|
||||
MessageDelete {
|
||||
channel_id: String,
|
||||
message_id: String,
|
||||
},
|
||||
Disconnect,
|
||||
}
|
||||
227
src/net/types/event.rs
Normal file
227
src/net/types/event.rs
Normal file
|
|
@ -0,0 +1,227 @@
|
|||
use super::info::{ChannelListItem, ChatMsg, FriendInfo, GuildInfo, MemberInfo, PresenceInfo};
|
||||
use std::net::SocketAddr;
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub enum NetEvent {
|
||||
Connected {
|
||||
session_id: String,
|
||||
node_name: String,
|
||||
restored: bool,
|
||||
private_mode: bool,
|
||||
},
|
||||
Disconnected {
|
||||
reason: String,
|
||||
will_retry: bool,
|
||||
},
|
||||
Reconnecting {
|
||||
attempt: u32,
|
||||
delay_secs: u64,
|
||||
},
|
||||
ChannelState {
|
||||
channel_id: String,
|
||||
channel_name: String,
|
||||
kind: String,
|
||||
members: Vec<MemberInfo>,
|
||||
voice_endpoint: String,
|
||||
},
|
||||
ChannelCreated {
|
||||
channel_id: String,
|
||||
channel_name: String,
|
||||
kind: String,
|
||||
},
|
||||
ChannelDeleted {
|
||||
channel_id: String,
|
||||
},
|
||||
ChannelListEvent {
|
||||
channels: Vec<ChannelListItem>,
|
||||
},
|
||||
ChatMessage {
|
||||
message_id: String,
|
||||
channel_id: String,
|
||||
sender_id: String,
|
||||
nickname: String,
|
||||
content: String,
|
||||
timestamp: i64,
|
||||
/// Optional message_id this message is replying to.
|
||||
reply_to: Option<String>,
|
||||
},
|
||||
ChatHistory {
|
||||
channel_id: String,
|
||||
messages: Vec<ChatMsg>,
|
||||
},
|
||||
UserJoin {
|
||||
channel_id: String,
|
||||
user_id: String,
|
||||
nickname: String,
|
||||
},
|
||||
UserLeave {
|
||||
channel_id: String,
|
||||
user_id: String,
|
||||
},
|
||||
VoicePacket {
|
||||
channel_id: u64,
|
||||
voice_seq: u32,
|
||||
timestamp: u32,
|
||||
sender: SocketAddr,
|
||||
/// Hex-encoded Ed25519 public key of the sender (Phase 1.3 attribution).
|
||||
/// Empty for legacy packets that didn't include sender_id.
|
||||
sender_id: String,
|
||||
opus_data: Vec<u8>,
|
||||
},
|
||||
Error {
|
||||
code: u32,
|
||||
message: String,
|
||||
},
|
||||
LatencyUpdate {
|
||||
rtt_ms: u32,
|
||||
},
|
||||
DmStart {
|
||||
dm_id: String,
|
||||
other_user_id: String,
|
||||
other_nickname: String,
|
||||
messages: Vec<ChatMsg>,
|
||||
unread_count: u32,
|
||||
},
|
||||
DmMessage {
|
||||
dm_id: String,
|
||||
sender_id: String,
|
||||
content: String,
|
||||
timestamp: i64,
|
||||
},
|
||||
DmHistory {
|
||||
dm_id: String,
|
||||
messages: Vec<ChatMsg>,
|
||||
},
|
||||
TypingStart {
|
||||
user_id: String,
|
||||
nickname: String,
|
||||
channel_id: String,
|
||||
},
|
||||
ReadReceiptBroadcast {
|
||||
channel_id: String,
|
||||
user_id: String,
|
||||
last_read_message_id: String,
|
||||
},
|
||||
GuildList {
|
||||
guilds: Vec<GuildInfo>,
|
||||
},
|
||||
GuildCreated {
|
||||
guild_id: String,
|
||||
name: String,
|
||||
owner_id: String,
|
||||
},
|
||||
GuildDeleted {
|
||||
guild_id: String,
|
||||
},
|
||||
GuildMemberJoined {
|
||||
guild_id: String,
|
||||
user_id: String,
|
||||
nickname: String,
|
||||
},
|
||||
GuildMemberLeft {
|
||||
guild_id: String,
|
||||
user_id: String,
|
||||
},
|
||||
GuildMemberKicked {
|
||||
guild_id: String,
|
||||
user_id: String,
|
||||
},
|
||||
InviteCreated {
|
||||
id: String,
|
||||
guild_id: String,
|
||||
guild_name: String,
|
||||
code: String,
|
||||
creator_id: String,
|
||||
max_uses: Option<i64>,
|
||||
uses: i64,
|
||||
expires_at: Option<i64>,
|
||||
created_at: i64,
|
||||
},
|
||||
InviteAccepted {
|
||||
guild_id: String,
|
||||
guild_name: String,
|
||||
},
|
||||
InviteDeleted {
|
||||
guild_id: String,
|
||||
invite_id: String,
|
||||
},
|
||||
RoleCreated {
|
||||
role_id: String,
|
||||
guild_id: String,
|
||||
name: String,
|
||||
},
|
||||
RoleDeleted {
|
||||
role_id: String,
|
||||
guild_id: String,
|
||||
},
|
||||
GuildAuditLog {
|
||||
guild_id: String,
|
||||
entries: Vec<crate::net::payloads::AuditLogEntryPayload>,
|
||||
},
|
||||
GuildMemberList {
|
||||
guild_id: String,
|
||||
members: Vec<crate::net::payloads::GuildMemberInfoPayload>,
|
||||
},
|
||||
GuildRoleList {
|
||||
guild_id: String,
|
||||
roles: Vec<crate::net::payloads::GuildRoleInfoPayload>,
|
||||
},
|
||||
UserColor {
|
||||
user_id: String,
|
||||
color: String,
|
||||
},
|
||||
PresenceSync {
|
||||
presences: Vec<PresenceInfo>,
|
||||
},
|
||||
PresenceUpdated {
|
||||
user_id: String,
|
||||
status: String,
|
||||
custom_status: Option<String>,
|
||||
activity: Option<String>,
|
||||
},
|
||||
FriendList {
|
||||
friends: Vec<FriendInfo>,
|
||||
},
|
||||
FriendRequested {
|
||||
user_id: String,
|
||||
nickname: String,
|
||||
},
|
||||
FriendAccepted {
|
||||
user_id: String,
|
||||
nickname: String,
|
||||
},
|
||||
FriendRemoved {
|
||||
user_id: String,
|
||||
},
|
||||
BlockList {
|
||||
blocked: Vec<String>,
|
||||
},
|
||||
BlockedUser {
|
||||
user_id: String,
|
||||
},
|
||||
UnblockedUser {
|
||||
user_id: String,
|
||||
},
|
||||
ReactionAdded {
|
||||
channel_id: String,
|
||||
message_id: String,
|
||||
user_id: String,
|
||||
emoji: String,
|
||||
},
|
||||
ReactionRemoved {
|
||||
channel_id: String,
|
||||
message_id: String,
|
||||
user_id: String,
|
||||
emoji: String,
|
||||
},
|
||||
MessageEdited {
|
||||
channel_id: String,
|
||||
message_id: String,
|
||||
content: String,
|
||||
edited: bool,
|
||||
},
|
||||
MessageDeleted {
|
||||
channel_id: String,
|
||||
message_id: String,
|
||||
},
|
||||
}
|
||||
49
src/net/types/info.rs
Normal file
49
src/net/types/info.rs
Normal file
|
|
@ -0,0 +1,49 @@
|
|||
#[derive(Debug, Clone)]
|
||||
pub struct MemberInfo {
|
||||
pub user_id: String,
|
||||
pub nickname: String,
|
||||
pub in_voice: bool,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct ChannelListItem {
|
||||
pub channel_id: String,
|
||||
pub channel_name: String,
|
||||
pub kind: String,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct ChatMsg {
|
||||
pub message_id: String,
|
||||
pub sender_id: String,
|
||||
pub content: String,
|
||||
pub timestamp: i64,
|
||||
/// Optional message_id this message is replying to.
|
||||
pub reply_to: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct GuildInfo {
|
||||
pub guild_id: String,
|
||||
pub name: String,
|
||||
pub owner_id: String,
|
||||
pub icon_url: Option<String>,
|
||||
pub member_count: u32,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct PresenceInfo {
|
||||
pub user_id: String,
|
||||
pub status: String,
|
||||
pub custom_status: Option<String>,
|
||||
pub activity: Option<String>,
|
||||
pub activity_text: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct FriendInfo {
|
||||
pub user_id: String,
|
||||
pub nickname: String,
|
||||
pub status: String,
|
||||
pub since: i64,
|
||||
}
|
||||
8
src/net/types/mod.rs
Normal file
8
src/net/types/mod.rs
Normal file
|
|
@ -0,0 +1,8 @@
|
|||
/// Public API types: commands UI→net and events net→UI.
|
||||
mod command;
|
||||
mod event;
|
||||
mod info;
|
||||
|
||||
pub use command::NetCommand;
|
||||
pub use event::NetEvent;
|
||||
pub use info::{ChannelListItem, ChatMsg, FriendInfo, GuildInfo, MemberInfo, PresenceInfo};
|
||||
84
src/net/voice/mod.rs
Normal file
84
src/net/voice/mod.rs
Normal file
|
|
@ -0,0 +1,84 @@
|
|||
use super::crypto::SessionCrypto;
|
||||
use super::payloads::PID_VOICE_PACKET;
|
||||
|
||||
mod receive;
|
||||
pub use receive::spawn_recv;
|
||||
|
||||
/// Stable string channel id to u64 key for UDP voice packets.
|
||||
pub fn channel_key(id: &str) -> u64 {
|
||||
let mut h: u64 = 5381;
|
||||
for b in id.bytes() {
|
||||
h = h.wrapping_mul(33).wrapping_add(u64::from(b));
|
||||
}
|
||||
h
|
||||
}
|
||||
|
||||
/// Build a UDP voice packet with encryption.
|
||||
///
|
||||
/// Plaintext layout (Phase 1.2+):
|
||||
/// `[voice_seq:4][timestamp:4][channel_id:8][sender_id:32][opus_data:N]`
|
||||
///
|
||||
/// `sender_id` is the raw Ed25519 public key of the sender, so receivers can
|
||||
/// attribute the voice activity to a specific user (Phase 1.3 speaking indicators).
|
||||
pub fn build_packet(
|
||||
channel_id: u64,
|
||||
voice_seq: u32,
|
||||
timestamp: u32,
|
||||
opus: &[u8],
|
||||
crypto: &SessionCrypto,
|
||||
packet_seq: u64,
|
||||
sender_pubkey: &[u8; 32],
|
||||
) -> Vec<u8> {
|
||||
let mut plaintext = Vec::with_capacity(16 + 32 + opus.len());
|
||||
plaintext.extend_from_slice(&voice_seq.to_be_bytes());
|
||||
plaintext.extend_from_slice(×tamp.to_be_bytes());
|
||||
plaintext.extend_from_slice(&channel_id.to_be_bytes());
|
||||
plaintext.extend_from_slice(sender_pubkey);
|
||||
plaintext.extend_from_slice(opus);
|
||||
|
||||
let encrypted = crypto.encrypt_c2s(packet_seq, &plaintext);
|
||||
|
||||
let mut buf = Vec::with_capacity(4 + encrypted.len());
|
||||
buf.extend_from_slice(&PID_VOICE_PACKET.to_be_bytes());
|
||||
buf.extend_from_slice(&0u16.to_be_bytes());
|
||||
buf.extend_from_slice(&encrypted);
|
||||
buf
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn channel_key_is_stable() {
|
||||
assert_eq!(channel_key("voice"), channel_key("voice"));
|
||||
assert_ne!(channel_key("voice"), channel_key("general"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn build_packet_header_layout() {
|
||||
let key = channel_key("voice");
|
||||
let shared = [0u8; 32];
|
||||
let crypto = SessionCrypto::derive(&shared, "test");
|
||||
let sender = [0xABu8; 32];
|
||||
let pkt = build_packet(key, 42, 1000, b"opus", &crypto, 0, &sender);
|
||||
|
||||
let packet_id = u16::from_be_bytes([pkt[0], pkt[1]]);
|
||||
assert_eq!(packet_id, PID_VOICE_PACKET);
|
||||
|
||||
let encrypted_payload = &pkt[4..];
|
||||
let plaintext = crypto.decrypt_c2s(0, encrypted_payload).unwrap();
|
||||
assert_eq!(plaintext.len(), 16 + 32 + 4);
|
||||
|
||||
let pkt_voice_seq = u32::from_be_bytes(plaintext[0..4].try_into().unwrap());
|
||||
let timestamp = u32::from_be_bytes(plaintext[4..8].try_into().unwrap());
|
||||
let channel_id = u64::from_be_bytes(plaintext[8..16].try_into().unwrap());
|
||||
let sender_id: [u8; 32] = plaintext[16..48].try_into().unwrap();
|
||||
|
||||
assert_eq!(pkt_voice_seq, 42);
|
||||
assert_eq!(timestamp, 1000);
|
||||
assert_eq!(channel_id, key);
|
||||
assert_eq!(sender_id, sender);
|
||||
assert_eq!(&plaintext[48..], b"opus");
|
||||
}
|
||||
}
|
||||
80
src/net/voice/receive.rs
Normal file
80
src/net/voice/receive.rs
Normal file
|
|
@ -0,0 +1,80 @@
|
|||
use std::sync::Arc;
|
||||
use tokio::net::UdpSocket;
|
||||
use tokio::sync::mpsc;
|
||||
use tracing::warn;
|
||||
|
||||
use super::super::crypto::SessionCrypto;
|
||||
use super::super::payloads::PID_VOICE_PACKET;
|
||||
use super::super::types::NetEvent;
|
||||
|
||||
/// Spawn a task that reads UDP datagrams, decrypts them, and forwards as VoicePacket events.
|
||||
pub fn spawn_recv(udp: Arc<UdpSocket>, crypto: SessionCrypto, tx: mpsc::Sender<NetEvent>) {
|
||||
tokio::spawn(async move {
|
||||
let mut buf = vec![0u8; 1472];
|
||||
let mut voice_seq: u64 = 0;
|
||||
|
||||
loop {
|
||||
match udp.recv_from(&mut buf).await {
|
||||
Ok((len, src)) => {
|
||||
if len < 4 {
|
||||
continue;
|
||||
}
|
||||
|
||||
let packet_id = u16::from_be_bytes([buf[0], buf[1]]);
|
||||
if packet_id != PID_VOICE_PACKET {
|
||||
continue;
|
||||
}
|
||||
|
||||
let encrypted_payload = &buf[4..len];
|
||||
let plaintext = match crypto.decrypt_s2c(voice_seq, encrypted_payload) {
|
||||
Ok(p) => p,
|
||||
Err(e) => {
|
||||
warn!("voice packet decryption failed from {src}: {e}");
|
||||
voice_seq += 1;
|
||||
continue;
|
||||
}
|
||||
};
|
||||
|
||||
// Layout: [voice_seq:4][timestamp:4][channel_id:8][sender_id:32][opus]
|
||||
// Legacy format (no sender_id) is 16+ bytes — gracefully handle.
|
||||
if plaintext.len() < 16 {
|
||||
warn!("voice packet payload too short from {src}");
|
||||
voice_seq += 1;
|
||||
continue;
|
||||
}
|
||||
|
||||
let pkt_voice_seq = u32::from_be_bytes(plaintext[0..4].try_into().unwrap());
|
||||
let timestamp = u32::from_be_bytes(plaintext[4..8].try_into().unwrap());
|
||||
let channel_id = u64::from_be_bytes(plaintext[8..16].try_into().unwrap());
|
||||
|
||||
// sender_id: 32 raw bytes if present, hex-encoded.
|
||||
// Empty string when packet is from legacy sender without sender_id.
|
||||
let (sender_id_hex, opus_data) = if plaintext.len() >= 48 {
|
||||
let sender_bytes: [u8; 32] = plaintext[16..48].try_into().unwrap();
|
||||
(hex::encode(sender_bytes), plaintext[48..].to_vec())
|
||||
} else {
|
||||
// Legacy: no sender_id in payload.
|
||||
(String::new(), plaintext[16..].to_vec())
|
||||
};
|
||||
|
||||
let _ = tx
|
||||
.send(NetEvent::VoicePacket {
|
||||
channel_id,
|
||||
voice_seq: pkt_voice_seq,
|
||||
timestamp,
|
||||
sender: src,
|
||||
sender_id: sender_id_hex,
|
||||
opus_data,
|
||||
})
|
||||
.await;
|
||||
|
||||
voice_seq += 1;
|
||||
}
|
||||
Err(e) => {
|
||||
warn!("UDP recv: {e}");
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue