Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 4 additions & 3 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ members = [
opt-level = 1

[workspace.package]
version = "0.0.8-alpha"
version = "0.0.9-beta"
edition = "2021"
license = "MIT"
repository = "https://github.com/lag-app/cli"
Expand Down
17 changes: 17 additions & 0 deletions crates/cli/src/api.rs
Original file line number Diff line number Diff line change
Expand Up @@ -161,6 +161,23 @@ impl ApiClient {
pub fn base_url(&self) -> &str {
&self.base_url
}

/// Fetch a messages endpoint that returns `{"messages": [...]}` or a bare array.
pub async fn get_messages(&mut self, path: &str) -> Result<Vec<serde_json::Value>> {
let val: serde_json::Value = self.get(path).await?;
Ok(extract_messages(val))
}
}

/// Extract messages from either `{"messages": [...]}` or a bare `[...]`.
pub fn extract_messages(val: serde_json::Value) -> Vec<serde_json::Value> {
if let Some(arr) = val.as_array() {
arr.clone()
} else if let Some(arr) = val["messages"].as_array() {
arr.clone()
} else {
Vec::new()
}
}

async fn parse_response<T: DeserializeOwned>(resp: reqwest::Response) -> Result<T> {
Expand Down
7 changes: 7 additions & 0 deletions crates/cli/src/cli.rs
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,9 @@ pub enum Commands {
/// Show room text chat alongside voice
#[arg(long)]
with_chat: bool,
/// Voice server region (e.g. eu, us)
#[arg(long)]
region: Option<String>,
},

/// Audio device configuration
Expand Down Expand Up @@ -176,6 +179,7 @@ impl Cli {
input_device,
output_device,
with_chat,
region,
}) => {
crate::commands::join::run(
server,
Expand All @@ -185,6 +189,7 @@ impl Cli {
input_device,
output_device,
with_chat,
region,
)
.await
}
Expand Down Expand Up @@ -247,6 +252,7 @@ mod tests {
input_device,
output_device,
with_chat,
region,
}) => {
assert_eq!(server, "my-server");
assert_eq!(room, "general");
Expand All @@ -255,6 +261,7 @@ mod tests {
assert_eq!(input_device.as_deref(), Some("Blue Yeti"));
assert_eq!(output_device.as_deref(), Some("Speakers"));
assert!(with_chat);
assert!(region.is_none());
}
_ => panic!("expected Join"),
}
Expand Down
24 changes: 15 additions & 9 deletions crates/cli/src/commands/chat.rs
Original file line number Diff line number Diff line change
Expand Up @@ -51,8 +51,8 @@ async fn send_message(
async fn open_chat(api: &mut ApiClient, server_query: &str, room_query: &str) -> Result<()> {
let (server_id, room_id) = resolve_server_room(api, server_query, room_query).await?;

let messages: Vec<serde_json::Value> = api
.get(&format!(
let messages = api
.get_messages(&format!(
"/servers/{}/rooms/{}/messages?limit=50",
server_id, room_id
))
Expand All @@ -66,9 +66,8 @@ async fn open_chat(api: &mut ApiClient, server_query: &str, room_query: &str) ->
}

let mut ws = WsClient::connect(api.base_url(), api.access_token()).await?;
ws.send(WsClientMessage::SubscribeServerRoom {
server_id: server_id.clone(),
room_id: Some(room_id.clone()),
ws.send(WsClientMessage::SubscribeServers {
server_ids: vec![server_id.clone()],
})?;

terminal::enable_raw_mode()?;
Expand All @@ -82,18 +81,23 @@ async fn open_chat(api: &mut ApiClient, server_query: &str, room_query: &str) ->
ws_msg = ws.recv() => {
match ws_msg {
Some(WsServerMessage::RoomMessage(val)) => {
let msg_room_id = val["roomId"].as_str().unwrap_or("");
let msg = if val.get("message").is_some() {
val["message"].clone()
} else {
val
};
let msg_room_id = msg["roomId"].as_str().unwrap_or("");
if msg_room_id == room_id {
clear_line();
print_message(&val);
print_message(&msg);
print_prompt(&input_buf);
}
}
None => break,
_ => {}
}
}
_ = async {
should_quit = async {
if event::poll(std::time::Duration::from_millis(50)).unwrap_or(false) {
if let Ok(Event::Key(key)) = event::read() {
match (key.code, key.modifiers) {
Expand Down Expand Up @@ -127,7 +131,9 @@ async fn open_chat(api: &mut ApiClient, server_query: &str, room_query: &str) ->
}
}
false
} => {}
} => {
if should_quit { break; }
}
}
}

Expand Down
4 changes: 2 additions & 2 deletions crates/cli/src/commands/dms.rs
Original file line number Diff line number Diff line change
Expand Up @@ -70,8 +70,8 @@ async fn open_dm(api: &mut ApiClient, username: &str) -> Result<()> {
let conv_id = conv["id"].as_str().unwrap().to_string();

// Load recent messages
let messages: Vec<serde_json::Value> = api
.get(&format!("/dms/{}/messages?limit=50", conv_id))
let messages = api
.get_messages(&format!("/dms/{}/messages?limit=50", conv_id))
.await?;

println!("-- DM with {} --", username);
Expand Down
29 changes: 18 additions & 11 deletions crates/cli/src/commands/join.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ use parking_lot::Mutex;
use std::io::Write;
use std::sync::Arc;

#[allow(clippy::too_many_arguments)]
pub async fn run(
server: String,
room: String,
Expand All @@ -21,6 +22,7 @@ pub async fn run(
input_device: Option<String>,
output_device: Option<String>,
with_chat: bool,
region: Option<String>,
) -> Result<()> {
let creds = auth::ensure_auth().await?;
let mut api = ApiClient::new(creds)?;
Expand All @@ -30,11 +32,12 @@ pub async fn run(
resolve_voice_room(&mut api, &server, &room).await?;

// Get voice token
let body = match region {
Some(ref r) => serde_json::json!({ "region": r }),
None => serde_json::json!({}),
};
let token_resp: serde_json::Value = api
.post(
&format!("/voice/rooms/{}/token", room_id),
&serde_json::json!({}),
)
.post(&format!("/voice/rooms/{}/token", room_id), &body)
.await?;

let voice_url = token_resp["voiceUrl"]
Expand Down Expand Up @@ -115,9 +118,8 @@ pub async fn run(
// Optionally connect WS for chat
let mut ws = if with_chat {
let ws = WsClient::connect(api.base_url(), api.access_token()).await?;
ws.send(crate::ws::WsClientMessage::SubscribeServerRoom {
server_id: server_id.clone(),
room_id: Some(room_id.clone()),
ws.send(crate::ws::WsClientMessage::SubscribeServers {
server_ids: vec![server_id.clone()],
})?;
Some(ws)
} else {
Expand All @@ -126,8 +128,8 @@ pub async fn run(

if with_chat {
// Load recent messages
let messages: Vec<serde_json::Value> = api
.get(&format!(
let messages = api
.get_messages(&format!(
"/servers/{}/rooms/{}/messages?limit=20",
server_id, room_id
))
Expand Down Expand Up @@ -196,8 +198,13 @@ pub async fn run(
}
} => {
if let Some(WsServerMessage::RoomMessage(val)) = ws_msg {
let username = val["username"].as_str().unwrap_or("?");
let content = val["content"].as_str().unwrap_or("");
let msg = if val.get("message").is_some() {
val["message"].clone()
} else {
val
};
let username = msg["username"].as_str().unwrap_or("?");
let content = msg["content"].as_str().unwrap_or("");
println!("\r[chat] {}: {}\x1b[K", username, content);
if with_chat {
print!("> {}", input_buf);
Expand Down
2 changes: 2 additions & 0 deletions crates/cli/src/commands/servers.rs
Original file line number Diff line number Diff line change
Expand Up @@ -121,6 +121,7 @@ async fn interactive_room_picker_inner(
None,
None,
false,
None,
)
.await
}
Expand All @@ -133,6 +134,7 @@ async fn interactive_room_picker_inner(
None,
None,
true,
None,
)
.await
}
Expand Down
Loading
Loading