| 1 | use std::time::Duration; |
| 2 | |
| 3 | use chatsvc::{EventKind, Realtime, RealtimeEvent, mask_conversation_id}; |
| 4 | use chrono::Local; |
| 5 | use session::{DEFAULT_ENDPOINT, Session}; |
| 6 | |
| 7 | #[tokio::main] |
| 8 | async fn main() { |
| 9 | let seconds: u64 = std::env::args() |
| 10 | .nth(1) |
| 11 | .and_then(|value| value.parse().ok()) |
| 12 | .unwrap_or(60); |
| 13 | let endpoint = std::env::var("CDP_ENDPOINT").unwrap_or_else(|_| DEFAULT_ENDPOINT.to_owned()); |
| 14 | let session = Session::connect(&endpoint).await.expect("browser"); |
| 15 | let mut realtime = Realtime::start(&session).await.expect("realtime start"); |
| 16 | println!("# started host={} for {seconds}s", realtime.host()); |
| 17 | let deadline = tokio::time::sleep(Duration::from_secs(seconds)); |
| 18 | tokio::pin!(deadline); |
| 19 | loop { |
| 20 | tokio::select! { |
| 21 | event = realtime.recv() => { |
| 22 | let Some(event) = event else { break }; |
| 23 | println!("{}", describe(&event)); |
| 24 | } |
| 25 | _ = &mut deadline => break, |
| 26 | } |
| 27 | } |
| 28 | realtime.stop().await; |
| 29 | println!("# stopped"); |
| 30 | } |
| 31 | |
| 32 | fn describe(event: &RealtimeEvent) -> String { |
| 33 | match event { |
| 34 | RealtimeEvent::Message(message) => format!( |
| 35 | "{} {} {} conv={}", |
| 36 | message |
| 37 | .received_at |
| 38 | .with_timezone(&Local) |
| 39 | .format("%H:%M:%S%.3f"), |
| 40 | kind_name(message.kind), |
| 41 | message.resource_type, |
| 42 | message |
| 43 | .conversation_id |
| 44 | .as_deref() |
| 45 | .map(mask_conversation_id) |
| 46 | .unwrap_or_else(|| "-".into()), |
| 47 | ), |
| 48 | RealtimeEvent::Status(status) => format!("# status {:?} {}", status.kind, status.detail), |
| 49 | } |
| 50 | } |
| 51 | |
| 52 | fn kind_name(kind: EventKind) -> &'static str { |
| 53 | match kind { |
| 54 | EventKind::NewMessage => "new_message", |
| 55 | EventKind::MessageUpdate => "message_update", |
| 56 | EventKind::ThreadUpdate => "thread_update", |
| 57 | EventKind::Typing => "typing", |
| 58 | EventKind::ReadReceipt => "read_receipt", |
| 59 | EventKind::ThreadActivity => "thread_activity", |
| 60 | EventKind::Control => "control", |
| 61 | EventKind::Presence => "presence", |
| 62 | EventKind::Other => "other", |
| 63 | } |
| 64 | } |