BlueGit

ict rusty-teams

Files

rusty-teams / crates / chatsvc / examples / live.rs

live.rs

live.rs 2.8 KiB Download Raw
1use std::time::Duration;
2
3use chatsvc::{EventKind, Realtime, RealtimeEvent, mask_conversation_id};
4use chrono::Local;
5use session::{DEFAULT_ENDPOINT, Session};
6
7#[tokio::main]
8async 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
32fn 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::Typing(typing) => format!(
49 "{} typing {} conv={}",
50 typing
51 .received_at
52 .with_timezone(&Local)
53 .format("%H:%M:%S%.3f"),
54 if typing.active { "start" } else { "clear" },
55 mask_conversation_id(&typing.conversation_id),
56 ),
57 RealtimeEvent::Status(status) => format!("# status {:?} {}", status.kind, status.detail),
58 RealtimeEvent::Presence(updates) => format!("# presence updates={}", updates.len()),
59 RealtimeEvent::Endpoint(endpoint) => format!(
60 "# endpoint host={}",
61 endpoint
62 .trouter_uri
63 .trim_start_matches("https://")
64 .split('/')
65 .next()
66 .unwrap_or("-")
67 ),
68 }
69}
70
71fn kind_name(kind: EventKind) -> &'static str {
72 match kind {
73 EventKind::NewMessage => "new_message",
74 EventKind::MessageUpdate => "message_update",
75 EventKind::ThreadUpdate => "thread_update",
76 EventKind::Typing => "typing",
77 EventKind::ReadReceipt => "read_receipt",
78 EventKind::PinsChanged => "pins_changed",
79 EventKind::ThreadActivity => "thread_activity",
80 EventKind::Control => "control",
81 EventKind::Other => "other",
82 }
83}