forked from Keelrleek/SoulStream
the soulseek hub: the whole Qt client as one area, wired to the wire
Kyle: "this is going to be a soulseek menu now — essentially the soulseek
app in our app." Approved against research/soulseek-search/hub2.html, a
one-to-one mock in the real frame, then built in three layers.
THE AREA. Search and Downloads leave the sidebar; one Soulseek entry
(globe) opens src/views/Soulseek.svelte, whose tab row is SoulseekQt's own
anatomy: Transfers, Search, Browse, Rooms, Chat, Users. The old view ids
stay routable — App.svelte aliases "search" and "downloads" to the hub and
the component syncs its tab off them — so the title bar's download ring,
"get on soulseek" hand-offs, history entries and restored sessions all
land on the right tab. The glass bar rides the hub with the connection
line on its right (online as X · sharing N files), the page takes Home's
below-the-bar inset, and the bar arrows join the chrome spec (16px glyphs)
alongside the sidebar toggle's disc. The replaced Search.svelte and
Downloads.svelte are deleted; Transfers carries their data forward in Qt's
own columns (User/File/Progress/Status/ETA/Speed/Size/Place, cancel and
play/reveal/add on the rows, clear-complete and open-folder in the
toolbar, live speed totals in the footer) and Search re-skins the peer
search as the Qt table: results regrouped user -> folder -> file,
slot/queue chips, format filter chips that actually filter, fold-out
files with stream-and-download on hover.
THE WIRE. soulseek-proto learns the rest of the protocol: rooms 13-17
(say/join/leave/user-joined/user-left), private messages 22/23, the
watch/status/stats family 5/6/7/36, the room list 64, and the peer-side
browse pair 4/5 with Directory::read to decode what our own responder
already encoded. Parsers are tolerant where the wire is baroque — roster
sections consume their own declared counts even when they disagree with
the name list, RoomList ignores the private-room tail, truncated stats
default instead of failing the frame. Codec tests ride along, including a
browse round-trip against our own encoder.
soulseek-client turns those into Events (RoomList/RoomJoined/RoomMessage/
PrivateMessage/UserWatched/...), auto-acks every private message the
moment it lands — unacked DMs are redelivered on every login — and grows
a spawn-shaped browse(): the returned future owns an Arc of the internals
so the caller drops the client lock before awaiting the 45s worst case.
THE APP. The event pump forwards everything as soulseek:* events; new
commands cover join/leave/say/message/room-list/browse plus a buddy list
persisted in config and re-watched on every login so status and stats
stream while connected. The frontend slsk store drains it all into the
four tabs: Rooms (joined + popular lists, live roster column, per-user
colored feed, say box — the server echoes our own lines so nothing is
appended locally), Chat (recency-sorted conversations, unread badges, DM
bubbles — our half appended locally since DMs are NOT echoed), Users
(add/remove buddies, status chips, one-click Browse/Chat cross-wiring),
and Browse (type a name, walk their tree, stream or download any file).
And the sharing side finally taps the shoulder: UploadToast announces the
first event of every new upload in the shared toast slot, folding a
same-user burst into one counting pill ("nikac is taking 12 files")
instead of twelve entrances.
Live-verified against the real network: the server handed 703 rooms after
login, and a browse of a live peer returned 3,796 directories / 34,773
files in 929ms with full paths, sizes and attributes. Join/say and DMs
are wired but deliberately unexercised — the first hello in a real room
is Kyle's to say, not a probe's.
This commit is contained in:
1 parent
913289a297
commit
63a0357651
17 files changed
+2843
-773
No files matched your search
@@ -195,6 +195,88 @@ fn handle_server_frame(inner: &Arc<Inner>, mut body: Bytes) {
|
||||
crate::responder::respond_to_search(inner.clone(), username, token, query);
|
||||
}
|
||||
}
|
||||
server::ServerEvent::RoomList { rooms } => {
|
||||
let _ = inner.event_tx.send(Event::RoomList { rooms });
|
||||
}
|
||||
server::ServerEvent::RoomJoined { room, users } => {
|
||||
let _ = inner.event_tx.send(Event::RoomJoined { room, users });
|
||||
}
|
||||
server::ServerEvent::RoomLeft { room } => {
|
||||
let _ = inner.event_tx.send(Event::RoomLeft { room });
|
||||
}
|
||||
server::ServerEvent::RoomUserJoined { room, user } => {
|
||||
let _ = inner.event_tx.send(Event::RoomUserJoined { room, user });
|
||||
}
|
||||
server::ServerEvent::RoomUserLeft { room, username } => {
|
||||
let _ = inner.event_tx.send(Event::RoomUserLeft { room, username });
|
||||
}
|
||||
server::ServerEvent::RoomChat {
|
||||
room,
|
||||
username,
|
||||
message,
|
||||
} => {
|
||||
let _ = inner.event_tx.send(Event::RoomMessage {
|
||||
room,
|
||||
username,
|
||||
message,
|
||||
});
|
||||
}
|
||||
server::ServerEvent::PrivateMessage {
|
||||
id,
|
||||
timestamp,
|
||||
username,
|
||||
message,
|
||||
} => {
|
||||
// Ack immediately or the server redelivers it on every login.
|
||||
let _ = inner.send_server(server::message_acked(id));
|
||||
let _ = inner.event_tx.send(Event::PrivateMessage {
|
||||
id,
|
||||
timestamp,
|
||||
username,
|
||||
message,
|
||||
});
|
||||
}
|
||||
server::ServerEvent::UserWatched {
|
||||
username,
|
||||
exists,
|
||||
status,
|
||||
avg_speed,
|
||||
file_count,
|
||||
dir_count,
|
||||
} => {
|
||||
let _ = inner.event_tx.send(Event::UserWatched {
|
||||
username,
|
||||
exists,
|
||||
status,
|
||||
avg_speed,
|
||||
file_count,
|
||||
dir_count,
|
||||
});
|
||||
}
|
||||
server::ServerEvent::UserStatus {
|
||||
username,
|
||||
status,
|
||||
privileged,
|
||||
} => {
|
||||
let _ = inner.event_tx.send(Event::UserStatus {
|
||||
username,
|
||||
status,
|
||||
privileged,
|
||||
});
|
||||
}
|
||||
server::ServerEvent::UserStats {
|
||||
username,
|
||||
avg_speed,
|
||||
file_count,
|
||||
dir_count,
|
||||
} => {
|
||||
let _ = inner.event_tx.send(Event::UserStats {
|
||||
username,
|
||||
avg_speed,
|
||||
file_count,
|
||||
dir_count,
|
||||
});
|
||||
}
|
||||
server::ServerEvent::CannotConnect { .. } | server::ServerEvent::Unhandled { .. } => {}
|
||||
}
|
||||
}
|
||||
@@ -507,6 +589,25 @@ fn route_peer_event(inner: &Arc<Inner>, username: &str, ev: peer::PeerEvent) {
|
||||
crate::responder::respond_browse(inner, h);
|
||||
}
|
||||
}
|
||||
BrowseResponse { dirs, .. } => {
|
||||
let waiters = inner
|
||||
.pending_browses
|
||||
.lock()
|
||||
.unwrap()
|
||||
.remove(username)
|
||||
.unwrap_or_default();
|
||||
match waiters.len() {
|
||||
0 => log::debug!("unsolicited browse response from {username}"),
|
||||
1 => {
|
||||
let _ = waiters.into_iter().next().unwrap().send(dirs);
|
||||
}
|
||||
_ => {
|
||||
for tx in waiters {
|
||||
let _ = tx.send(dirs.clone());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
UserInfoRequest => {
|
||||
if let Some(h) = inner.peers.lock().unwrap().get(username) {
|
||||
crate::responder::respond_user_info(inner, h);
|
||||
|
||||
@@ -29,7 +29,13 @@ use tokio::net::TcpStream;
|
||||
use tokio::sync::{mpsc, oneshot};
|
||||
use tokio_util::sync::CancellationToken;
|
||||
|
||||
use soulseek_proto::{server, types::SearchResponse};
|
||||
use soulseek_proto::{
|
||||
peer, server,
|
||||
types::{Directory, SearchResponse},
|
||||
};
|
||||
|
||||
pub use soulseek_proto::server::RoomUser;
|
||||
pub use soulseek_proto::types::Directory as BrowseDirectory;
|
||||
|
||||
pub const DEFAULT_SERVER: (&str, u16) = ("server.slsknet.org", 2242);
|
||||
pub const DEFAULT_LISTEN_PORT: u16 = 50300;
|
||||
@@ -86,6 +92,56 @@ pub enum Event {
|
||||
username: String,
|
||||
files: usize,
|
||||
},
|
||||
// ---- rooms / chat / users (the Soulseek hub's seats) ----
|
||||
RoomList {
|
||||
rooms: Vec<(String, u32)>,
|
||||
},
|
||||
RoomJoined {
|
||||
room: String,
|
||||
users: Vec<RoomUser>,
|
||||
},
|
||||
RoomLeft {
|
||||
room: String,
|
||||
},
|
||||
RoomUserJoined {
|
||||
room: String,
|
||||
user: RoomUser,
|
||||
},
|
||||
RoomUserLeft {
|
||||
room: String,
|
||||
username: String,
|
||||
},
|
||||
RoomMessage {
|
||||
room: String,
|
||||
username: String,
|
||||
message: String,
|
||||
},
|
||||
/// Already acked to the server by the time it is emitted.
|
||||
PrivateMessage {
|
||||
id: u32,
|
||||
timestamp: u32,
|
||||
username: String,
|
||||
message: String,
|
||||
},
|
||||
UserWatched {
|
||||
username: String,
|
||||
exists: bool,
|
||||
status: u32,
|
||||
avg_speed: u32,
|
||||
file_count: u32,
|
||||
dir_count: u32,
|
||||
},
|
||||
UserStatus {
|
||||
username: String,
|
||||
status: u32,
|
||||
privileged: bool,
|
||||
},
|
||||
UserStats {
|
||||
username: String,
|
||||
avg_speed: u32,
|
||||
file_count: u32,
|
||||
dir_count: u32,
|
||||
},
|
||||
}
|
||||
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
@@ -148,6 +204,8 @@ pub(crate) struct Inner {
|
||||
pub expected_transfers: Mutex<HashMap<(String, u32), oneshot::Sender<TcpStream>>>,
|
||||
/// Live peer message connections.
|
||||
pub peers: Mutex<HashMap<String, PeerHandle>>,
|
||||
/// Browse requests awaiting a peer's share listing, by username.
|
||||
pub pending_browses: Mutex<HashMap<String, Vec<oneshot::Sender<Vec<Directory>>>>>,
|
||||
/// TransferResponse waits: (username, our token).
|
||||
pub transfer_waits: Mutex<HashMap<(String, u32), oneshot::Sender<TransferAck>>>,
|
||||
/// TransferRequest(upload) waits: (username, remote filename).
|
||||
@@ -258,6 +316,7 @@ impl Client {
|
||||
pending_pierce: Mutex::new(HashMap::new()),
|
||||
expected_transfers: Mutex::new(HashMap::new()),
|
||||
peers: Mutex::new(HashMap::new()),
|
||||
pending_browses: Mutex::new(HashMap::new()),
|
||||
transfer_waits: Mutex::new(HashMap::new()),
|
||||
upload_offers: Mutex::new(HashMap::new()),
|
||||
downloads_by_file: Mutex::new(HashMap::new()),
|
||||
@@ -415,6 +474,81 @@ impl Client {
|
||||
}
|
||||
}
|
||||
|
||||
// ---- rooms / chat / users ----
|
||||
|
||||
/// Join (or create) a public room. The roster arrives as
|
||||
/// [`Event::RoomJoined`]; traffic as [`Event::RoomMessage`].
|
||||
pub fn join_room(&self, room: &str) -> Result<()> {
|
||||
self.inner.send_server(server::join_room(room))
|
||||
}
|
||||
|
||||
pub fn leave_room(&self, room: &str) -> Result<()> {
|
||||
self.inner.send_server(server::leave_room(room))
|
||||
}
|
||||
|
||||
pub fn say_room(&self, room: &str, message: &str) -> Result<()> {
|
||||
self.inner.send_server(server::say_chatroom(room, message))
|
||||
}
|
||||
|
||||
/// Send a private message. Delivery/acks are the server's business;
|
||||
/// incoming replies arrive as [`Event::PrivateMessage`].
|
||||
pub fn message_user(&self, username: &str, message: &str) -> Result<()> {
|
||||
self.inner.send_server(server::message_user(username, message))
|
||||
}
|
||||
|
||||
/// Watch a user: stats now, status pushes until unwatched.
|
||||
pub fn watch_user(&self, username: &str) -> Result<()> {
|
||||
self.inner.send_server(server::watch_user(username))
|
||||
}
|
||||
|
||||
pub fn unwatch_user(&self, username: &str) -> Result<()> {
|
||||
self.inner.send_server(server::unwatch_user(username))
|
||||
}
|
||||
|
||||
pub fn get_user_stats(&self, username: &str) -> Result<()> {
|
||||
self.inner.send_server(server::get_user_stats(username))
|
||||
}
|
||||
|
||||
/// Ask for the public room list (also pushed unprompted after login).
|
||||
pub fn request_room_list(&self) -> Result<()> {
|
||||
self.inner.send_server(server::room_list())
|
||||
}
|
||||
|
||||
/// Fetch a user's full shared listing over a peer connection. Slow for
|
||||
/// big shares — the reply is one large compressed frame — so this is
|
||||
/// spawn-shaped: the returned future owns everything it needs and the
|
||||
/// caller can drop whatever lock guarded the `Client` before awaiting.
|
||||
pub fn browse(
|
||||
&self,
|
||||
username: &str,
|
||||
) -> impl std::future::Future<Output = Result<Vec<Directory>>> + Send + 'static {
|
||||
let inner = self.inner.clone();
|
||||
let username = username.to_string();
|
||||
async move {
|
||||
let handle = conn::get_or_connect_peer(&inner, &username).await?;
|
||||
let (tx, rx) = oneshot::channel();
|
||||
inner
|
||||
.pending_browses
|
||||
.lock()
|
||||
.unwrap()
|
||||
.entry(username.clone())
|
||||
.or_default()
|
||||
.push(tx);
|
||||
handle
|
||||
.write_tx
|
||||
.send(peer::browse_request())
|
||||
.map_err(|_| ClientError::PeerUnreachable(username.clone()))?;
|
||||
|
||||
match tokio::time::timeout(std::time::Duration::from_secs(45), rx).await {
|
||||
Ok(Ok(dirs)) => Ok(dirs),
|
||||
_ => {
|
||||
inner.pending_browses.lock().unwrap().remove(&username);
|
||||
Err(ClientError::Timeout)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn listen_port(&self) -> u16 {
|
||||
self.inner.listen_port
|
||||
}
|
||||
|
||||
@@ -120,6 +120,11 @@ pub fn transfer_response_rejected(token: u32, reason: &str) -> Vec<u8> {
|
||||
.finish_u32(code::TRANSFER_RESPONSE)
|
||||
}
|
||||
|
||||
/// Ask a peer for their full shared listing (answered with code 5).
|
||||
pub fn browse_request() -> Vec<u8> {
|
||||
Writer::new().finish_u32(code::BROWSE_REQUEST)
|
||||
}
|
||||
|
||||
/// Legacy enqueue message; some clients expect it before TransferRequest.
|
||||
pub fn queue_download(filename: &str) -> Vec<u8> {
|
||||
Writer::new()
|
||||
@@ -210,6 +215,12 @@ pub fn user_info_response(
|
||||
#[derive(Debug, Clone)]
|
||||
pub enum PeerEvent {
|
||||
SearchResponse(SearchResponse),
|
||||
/// A peer's answer to our browse_request: their shared tree.
|
||||
BrowseResponse {
|
||||
dirs: Vec<Directory>,
|
||||
/// Count only — locked directories need a password we don't speak.
|
||||
locked_dirs: u32,
|
||||
},
|
||||
/// Peer is ready to send us a file (direction=upload) or wants one
|
||||
/// from us (direction=download → an upload request we service).
|
||||
TransferRequest {
|
||||
@@ -260,6 +271,9 @@ pub fn decode(code: u32, payload: Bytes) -> Result<PeerEvent> {
|
||||
if code == code::SEARCH_RESPONSE {
|
||||
return Ok(PeerEvent::SearchResponse(decode_search_response(payload)?));
|
||||
}
|
||||
if code == code::BROWSE_RESPONSE {
|
||||
return decode_browse_response(payload);
|
||||
}
|
||||
let mut r = Reader::new(payload);
|
||||
Ok(match code {
|
||||
code::TRANSFER_REQUEST => {
|
||||
@@ -322,6 +336,24 @@ pub fn decode(code: u32, payload: Bytes) -> Result<PeerEvent> {
|
||||
})
|
||||
}
|
||||
|
||||
/// Payload is zlib-compressed: directory count then directories — the exact
|
||||
/// shape `browse_response` writes. The trailer (unknown u32 + locked
|
||||
/// directory section) is read for its count and otherwise ignored.
|
||||
fn decode_browse_response(payload: Bytes) -> Result<PeerEvent> {
|
||||
let mut r = Reader::new(payload);
|
||||
r.decompress()?;
|
||||
let count = r.u32()?.min(100_000);
|
||||
let mut dirs = Vec::with_capacity(count.min(4096) as usize);
|
||||
for _ in 0..count {
|
||||
dirs.push(Directory::read(&mut r)?);
|
||||
}
|
||||
if r.has_more() {
|
||||
let _unknown = r.u32()?;
|
||||
}
|
||||
let locked_dirs = if r.has_more() { r.u32().unwrap_or(0) } else { 0 };
|
||||
Ok(PeerEvent::BrowseResponse { dirs, locked_dirs })
|
||||
}
|
||||
|
||||
/// Payload is zlib-compressed: username, token, files, slot/speed/queue,
|
||||
/// optional unknown u32, optional locked file list.
|
||||
fn decode_search_response(payload: Bytes) -> Result<SearchResponse> {
|
||||
@@ -398,6 +430,35 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn browse_roundtrip() {
|
||||
// Our own responder encoding must decode with our own reader — the
|
||||
// two sides of the same wire shape.
|
||||
let dirs = vec![crate::types::Directory {
|
||||
name: "Music\\Panda Bear\\A ? of WHEN [FLAC]".into(),
|
||||
files: vec![crate::types::File {
|
||||
filename: "01 Never givin' in.flac".into(),
|
||||
size: 38_900_000,
|
||||
extension: "flac".into(),
|
||||
attributes: vec![(crate::types::ATTR_DURATION, 330)],
|
||||
}],
|
||||
}];
|
||||
let msg = browse_response(&dirs);
|
||||
// Strip length + code, decode the compressed payload.
|
||||
let ev = decode(code::BROWSE_RESPONSE, Bytes::copy_from_slice(&msg[8..])).unwrap();
|
||||
match ev {
|
||||
PeerEvent::BrowseResponse { dirs, locked_dirs } => {
|
||||
assert_eq!(dirs.len(), 1);
|
||||
assert_eq!(dirs[0].name, "Music\\Panda Bear\\A ? of WHEN [FLAC]");
|
||||
assert_eq!(dirs[0].files.len(), 1);
|
||||
assert_eq!(dirs[0].files[0].size, 38_900_000);
|
||||
assert_eq!(dirs[0].files[0].duration_secs(), Some(330));
|
||||
assert_eq!(locked_dirs, 0);
|
||||
}
|
||||
other => panic!("wrong event: {other:?}"),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn search_response_decode() {
|
||||
// Build the uncompressed body by hand.
|
||||
|
||||
@@ -17,10 +17,21 @@ pub mod code {
|
||||
pub const SET_LISTEN_PORT: u32 = 2;
|
||||
pub const GET_PEER_ADDRESS: u32 = 3;
|
||||
pub const WATCH_USER: u32 = 5;
|
||||
pub const UNWATCH_USER: u32 = 6;
|
||||
pub const GET_USER_STATUS: u32 = 7;
|
||||
pub const SAY_CHATROOM: u32 = 13;
|
||||
pub const JOIN_ROOM: u32 = 14;
|
||||
pub const LEAVE_ROOM: u32 = 15;
|
||||
pub const USER_JOINED_ROOM: u32 = 16;
|
||||
pub const USER_LEFT_ROOM: u32 = 17;
|
||||
pub const CONNECT_TO_PEER: u32 = 18;
|
||||
pub const MESSAGE_USER: u32 = 22;
|
||||
pub const MESSAGE_ACKED: u32 = 23;
|
||||
pub const FILE_SEARCH: u32 = 26;
|
||||
pub const PING: u32 = 32;
|
||||
pub const SHARED_FOLDERS_AND_FILES: u32 = 35;
|
||||
pub const GET_USER_STATS: u32 = 36;
|
||||
pub const ROOM_LIST: u32 = 64;
|
||||
pub const HAVE_NO_PARENTS: u32 = 71;
|
||||
pub const PARENT_MIN_SPEED: u32 = 83;
|
||||
pub const PARENT_SPEED_RATIO: u32 = 84;
|
||||
@@ -101,8 +112,76 @@ pub fn have_no_parents(value: bool) -> Vec<u8> {
|
||||
Writer::new().bool(value).finish_u32(code::HAVE_NO_PARENTS)
|
||||
}
|
||||
|
||||
// ---- rooms / chat / users (outgoing) ----
|
||||
|
||||
/// Watch a user: the server answers with their stats and then pushes status
|
||||
/// changes until unwatched. The buddy list rides on this.
|
||||
pub fn watch_user(username: &str) -> Vec<u8> {
|
||||
Writer::new().string(username).finish_u32(code::WATCH_USER)
|
||||
}
|
||||
|
||||
pub fn unwatch_user(username: &str) -> Vec<u8> {
|
||||
Writer::new().string(username).finish_u32(code::UNWATCH_USER)
|
||||
}
|
||||
|
||||
pub fn get_user_status(username: &str) -> Vec<u8> {
|
||||
Writer::new()
|
||||
.string(username)
|
||||
.finish_u32(code::GET_USER_STATUS)
|
||||
}
|
||||
|
||||
pub fn get_user_stats(username: &str) -> Vec<u8> {
|
||||
Writer::new()
|
||||
.string(username)
|
||||
.finish_u32(code::GET_USER_STATS)
|
||||
}
|
||||
|
||||
pub fn say_chatroom(room: &str, message: &str) -> Vec<u8> {
|
||||
Writer::new()
|
||||
.string(room)
|
||||
.string(message)
|
||||
.finish_u32(code::SAY_CHATROOM)
|
||||
}
|
||||
|
||||
/// The trailing u32 is the private flag; 0 joins/creates a public room.
|
||||
pub fn join_room(room: &str) -> Vec<u8> {
|
||||
Writer::new().string(room).u32(0).finish_u32(code::JOIN_ROOM)
|
||||
}
|
||||
|
||||
pub fn leave_room(room: &str) -> Vec<u8> {
|
||||
Writer::new().string(room).finish_u32(code::LEAVE_ROOM)
|
||||
}
|
||||
|
||||
pub fn message_user(username: &str, message: &str) -> Vec<u8> {
|
||||
Writer::new()
|
||||
.string(username)
|
||||
.string(message)
|
||||
.finish_u32(code::MESSAGE_USER)
|
||||
}
|
||||
|
||||
/// Acknowledge a private message so the server stops redelivering it.
|
||||
pub fn message_acked(id: u32) -> Vec<u8> {
|
||||
Writer::new().u32(id).finish_u32(code::MESSAGE_ACKED)
|
||||
}
|
||||
|
||||
/// Ask for the room list (the server also pushes one after login).
|
||||
pub fn room_list() -> Vec<u8> {
|
||||
Writer::new().finish_u32(code::ROOM_LIST)
|
||||
}
|
||||
|
||||
// ---- incoming ----
|
||||
|
||||
/// A user as a room roster reports them (join replies and join notices).
|
||||
#[derive(Debug, Clone, Default)]
|
||||
pub struct RoomUser {
|
||||
pub username: String,
|
||||
/// 0 offline · 1 away · 2 online.
|
||||
pub status: u32,
|
||||
pub avg_speed: u32,
|
||||
pub file_count: u32,
|
||||
pub dir_count: u32,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub enum ServerEvent {
|
||||
LoginOk {
|
||||
@@ -145,6 +224,63 @@ pub enum ServerEvent {
|
||||
/// bytes are a distributed frame starting with its code byte — decode
|
||||
/// with `dist::decode`.
|
||||
Embedded(Bytes),
|
||||
/// Public rooms and their user counts (pushed after login, and on
|
||||
/// request). Private-room sections in the payload are ignored.
|
||||
RoomList {
|
||||
rooms: Vec<(String, u32)>,
|
||||
},
|
||||
/// We are in the room now; the full roster rides along.
|
||||
RoomJoined {
|
||||
room: String,
|
||||
users: Vec<RoomUser>,
|
||||
},
|
||||
RoomLeft {
|
||||
room: String,
|
||||
},
|
||||
RoomUserJoined {
|
||||
room: String,
|
||||
user: RoomUser,
|
||||
},
|
||||
RoomUserLeft {
|
||||
room: String,
|
||||
username: String,
|
||||
},
|
||||
/// A line said in a room we are in.
|
||||
RoomChat {
|
||||
room: String,
|
||||
username: String,
|
||||
message: String,
|
||||
},
|
||||
/// A private message. Ack with `message_acked(id)` or the server
|
||||
/// redelivers it on every login.
|
||||
PrivateMessage {
|
||||
id: u32,
|
||||
timestamp: u32,
|
||||
username: String,
|
||||
message: String,
|
||||
},
|
||||
/// Answer to watch_user.
|
||||
UserWatched {
|
||||
username: String,
|
||||
exists: bool,
|
||||
status: u32,
|
||||
avg_speed: u32,
|
||||
file_count: u32,
|
||||
dir_count: u32,
|
||||
},
|
||||
/// Pushed for watched users, and the answer to get_user_status.
|
||||
UserStatus {
|
||||
username: String,
|
||||
status: u32,
|
||||
privileged: bool,
|
||||
},
|
||||
/// Answer to get_user_stats.
|
||||
UserStats {
|
||||
username: String,
|
||||
avg_speed: u32,
|
||||
file_count: u32,
|
||||
dir_count: u32,
|
||||
},
|
||||
Unhandled {
|
||||
code: u32,
|
||||
},
|
||||
@@ -224,6 +360,143 @@ pub fn decode(code: u32, payload: Bytes) -> Result<ServerEvent> {
|
||||
}
|
||||
}
|
||||
code::EMBEDDED_MESSAGE => ServerEvent::Embedded(r.rest()),
|
||||
code::SAY_CHATROOM => ServerEvent::RoomChat {
|
||||
room: r.string()?,
|
||||
username: r.string()?,
|
||||
message: r.string()?,
|
||||
},
|
||||
code::JOIN_ROOM => {
|
||||
// room; N names; N statuses; N stats (speed u32, uploads u64,
|
||||
// files u32, dirs u32); then slots-free and country sections we
|
||||
// don't need. Sections beyond the names are tolerated missing —
|
||||
// rosters from older servers stop early.
|
||||
let room = r.string()?;
|
||||
let count = r.u32()?.min(10_000) as usize;
|
||||
let mut users: Vec<RoomUser> = Vec::with_capacity(count.min(4096));
|
||||
for _ in 0..count {
|
||||
users.push(RoomUser {
|
||||
username: r.string()?,
|
||||
..Default::default()
|
||||
});
|
||||
}
|
||||
// Each section carries its own count; consume EVERY entry it
|
||||
// declares (misaligned reads poison everything after), assign
|
||||
// only the ones with a roster slot.
|
||||
if r.has_more() {
|
||||
let n = r.u32()?.min(10_000) as usize;
|
||||
for i in 0..n {
|
||||
let status = r.u32()?;
|
||||
if let Some(user) = users.get_mut(i) {
|
||||
user.status = status;
|
||||
}
|
||||
}
|
||||
}
|
||||
if r.has_more() {
|
||||
let n = r.u32()?.min(10_000) as usize;
|
||||
for i in 0..n {
|
||||
let avg_speed = r.u32()?;
|
||||
let _upload_count = r.u64()?;
|
||||
let file_count = r.u32()?;
|
||||
let dir_count = r.u32()?;
|
||||
if let Some(user) = users.get_mut(i) {
|
||||
user.avg_speed = avg_speed;
|
||||
user.file_count = file_count;
|
||||
user.dir_count = dir_count;
|
||||
}
|
||||
}
|
||||
}
|
||||
ServerEvent::RoomJoined { room, users }
|
||||
}
|
||||
code::LEAVE_ROOM => ServerEvent::RoomLeft { room: r.string()? },
|
||||
code::USER_JOINED_ROOM => {
|
||||
let room = r.string()?;
|
||||
let username = r.string()?;
|
||||
let status = r.u32().unwrap_or(2);
|
||||
let avg_speed = r.u32().unwrap_or(0);
|
||||
let _upload_count = r.u64().unwrap_or(0);
|
||||
let file_count = r.u32().unwrap_or(0);
|
||||
let dir_count = r.u32().unwrap_or(0);
|
||||
ServerEvent::RoomUserJoined {
|
||||
room,
|
||||
user: RoomUser {
|
||||
username,
|
||||
status,
|
||||
avg_speed,
|
||||
file_count,
|
||||
dir_count,
|
||||
},
|
||||
}
|
||||
}
|
||||
code::USER_LEFT_ROOM => ServerEvent::RoomUserLeft {
|
||||
room: r.string()?,
|
||||
username: r.string()?,
|
||||
},
|
||||
code::MESSAGE_USER => ServerEvent::PrivateMessage {
|
||||
id: r.u32()?,
|
||||
timestamp: r.u32()?,
|
||||
username: r.string()?,
|
||||
message: r.string()?,
|
||||
},
|
||||
code::WATCH_USER => {
|
||||
let username = r.string()?;
|
||||
let exists = r.bool()?;
|
||||
let (mut status, mut avg_speed, mut file_count, mut dir_count) = (0, 0, 0, 0);
|
||||
if exists && r.has_more() {
|
||||
status = r.u32()?;
|
||||
avg_speed = r.u32()?;
|
||||
let _upload_count = r.u64()?;
|
||||
file_count = r.u32()?;
|
||||
dir_count = r.u32()?;
|
||||
}
|
||||
ServerEvent::UserWatched {
|
||||
username,
|
||||
exists,
|
||||
status,
|
||||
avg_speed,
|
||||
file_count,
|
||||
dir_count,
|
||||
}
|
||||
}
|
||||
code::GET_USER_STATUS => ServerEvent::UserStatus {
|
||||
username: r.string()?,
|
||||
status: r.u32()?,
|
||||
privileged: r.bool().unwrap_or(false),
|
||||
},
|
||||
code::GET_USER_STATS => {
|
||||
let username = r.string()?;
|
||||
let avg_speed = r.u32()?;
|
||||
let _upload_count = r.u64()?;
|
||||
ServerEvent::UserStats {
|
||||
username,
|
||||
avg_speed,
|
||||
file_count: r.u32()?,
|
||||
dir_count: r.u32()?,
|
||||
}
|
||||
}
|
||||
code::ROOM_LIST => {
|
||||
// Public names + counts; the private-room sections that follow
|
||||
// are deliberately not parsed.
|
||||
let count = r.u32()?.min(50_000) as usize;
|
||||
let mut names = Vec::with_capacity(count.min(8192));
|
||||
for _ in 0..count {
|
||||
names.push(r.string()?);
|
||||
}
|
||||
let ccount = if r.has_more() {
|
||||
r.u32()?.min(50_000) as usize
|
||||
} else {
|
||||
0
|
||||
};
|
||||
let mut counts = Vec::with_capacity(ccount.min(8192));
|
||||
for _ in 0..ccount {
|
||||
counts.push(r.u32()?);
|
||||
}
|
||||
let rooms = names
|
||||
.into_iter()
|
||||
.enumerate()
|
||||
.map(|(i, name)| (name, counts.get(i).copied().unwrap_or(0)))
|
||||
.collect();
|
||||
ServerEvent::RoomList { rooms }
|
||||
}
|
||||
code::EXCLUDED_SEARCH_PHRASES => {
|
||||
let count = r.u32()?.min(10_000);
|
||||
let mut phrases = Vec::with_capacity(count as usize);
|
||||
@@ -257,6 +530,103 @@ mod tests {
|
||||
assert_eq!(r.u32().unwrap(), MINOR_VERSION);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn decode_room_traffic() {
|
||||
// A said line.
|
||||
let payload = Writer::new()
|
||||
.string("indie")
|
||||
.string("nikac")
|
||||
.string("browse me")
|
||||
.finish_u32(13);
|
||||
match decode(13, Bytes::copy_from_slice(&payload[8..])).unwrap() {
|
||||
ServerEvent::RoomChat {
|
||||
room,
|
||||
username,
|
||||
message,
|
||||
} => {
|
||||
assert_eq!((room.as_str(), username.as_str()), ("indie", "nikac"));
|
||||
assert_eq!(message, "browse me");
|
||||
}
|
||||
other => panic!("wrong event: {other:?}"),
|
||||
}
|
||||
|
||||
// A join reply: 2 users, statuses and stats sections.
|
||||
let payload = Writer::new()
|
||||
.string("indie")
|
||||
.u32(2)
|
||||
.string("alice")
|
||||
.string("bob")
|
||||
.u32(2)
|
||||
.u32(2)
|
||||
.u32(1)
|
||||
.u32(2)
|
||||
.u32(500_000)
|
||||
.u64(3)
|
||||
.u32(1200)
|
||||
.u32(80)
|
||||
.u32(90_000)
|
||||
.u64(0)
|
||||
.u32(64)
|
||||
.u32(7)
|
||||
.finish_u32(14);
|
||||
match decode(14, Bytes::copy_from_slice(&payload[8..])).unwrap() {
|
||||
ServerEvent::RoomJoined { room, users } => {
|
||||
assert_eq!(room, "indie");
|
||||
assert_eq!(users.len(), 2);
|
||||
assert_eq!(users[0].username, "alice");
|
||||
assert_eq!(users[0].status, 2);
|
||||
assert_eq!(users[0].avg_speed, 500_000);
|
||||
assert_eq!(users[0].file_count, 1200);
|
||||
assert_eq!(users[1].username, "bob");
|
||||
assert_eq!(users[1].status, 1);
|
||||
assert_eq!(users[1].dir_count, 7);
|
||||
}
|
||||
other => panic!("wrong event: {other:?}"),
|
||||
}
|
||||
|
||||
// A private message.
|
||||
let payload = Writer::new()
|
||||
.u32(77)
|
||||
.u32(1_788_000_000)
|
||||
.string("seaside58")
|
||||
.string("queued you up")
|
||||
.bool(true)
|
||||
.finish_u32(22);
|
||||
match decode(22, Bytes::copy_from_slice(&payload[8..])).unwrap() {
|
||||
ServerEvent::PrivateMessage {
|
||||
id,
|
||||
username,
|
||||
message,
|
||||
..
|
||||
} => {
|
||||
assert_eq!(id, 77);
|
||||
assert_eq!(username, "seaside58");
|
||||
assert_eq!(message, "queued you up");
|
||||
}
|
||||
other => panic!("wrong event: {other:?}"),
|
||||
}
|
||||
|
||||
// A room list with a private tail we ignore.
|
||||
let payload = Writer::new()
|
||||
.u32(2)
|
||||
.string("indie")
|
||||
.string("electronic")
|
||||
.u32(2)
|
||||
.u32(214)
|
||||
.u32(642)
|
||||
.u32(0) // owned-private names, ignored
|
||||
.u32(0) // owned-private counts, ignored
|
||||
.finish_u32(64);
|
||||
match decode(64, Bytes::copy_from_slice(&payload[8..])).unwrap() {
|
||||
ServerEvent::RoomList { rooms } => {
|
||||
assert_eq!(rooms.len(), 2);
|
||||
assert_eq!(rooms[0], ("indie".to_string(), 214));
|
||||
assert_eq!(rooms[1], ("electronic".to_string(), 642));
|
||||
}
|
||||
other => panic!("wrong event: {other:?}"),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn decode_connect_to_peer() {
|
||||
let payload = Writer::new()
|
||||
|
||||
@@ -104,6 +104,16 @@ pub struct Directory {
|
||||
}
|
||||
|
||||
impl Directory {
|
||||
pub(crate) fn read(r: &mut Reader) -> Result<Directory> {
|
||||
let name = r.string()?;
|
||||
let count = r.u32()?.min(100_000);
|
||||
let mut files = Vec::with_capacity(count.min(4096) as usize);
|
||||
for _ in 0..count {
|
||||
files.push(File::read(r)?);
|
||||
}
|
||||
Ok(Directory { name, files })
|
||||
}
|
||||
|
||||
pub fn write(&self, mut w: Writer) -> Writer {
|
||||
w = w.string(&self.name).u32(self.files.len() as u32);
|
||||
for f in &self.files {
|
||||
|
||||
Reference in new issue
Block a user