BlueGit

ict rusty-teams

Files

rusty-teams / crates / graph / examples / live_data.rs

live_data.rs

live_data.rs 2.9 KiB Download Raw
1use std::collections::BTreeMap;
2use std::time::Instant;
3
4use graph::Graph;
5use session::{DEFAULT_ENDPOINT, Session};
6
7#[tokio::main]
8async fn main() {
9 let endpoint = std::env::var("CDP_ENDPOINT").unwrap_or_else(|_| DEFAULT_ENDPOINT.to_owned());
10 let graph = Graph::new(Session::connect(&endpoint).await.expect("browser"));
11 let me = graph.me().await.expect("me").id;
12 let chats = graph.chats_page(50).await.expect("chats").items;
13 let with_preview = chats
14 .iter()
15 .filter(|chat| chat.last_message_preview.is_some())
16 .count();
17 let with_body = chats
18 .iter()
19 .filter_map(|chat| {
20 chat.last_message_preview
21 .as_ref()?
22 .body
23 .as_ref()?
24 .content
25 .as_ref()
26 })
27 .filter(|content| !content.trim().is_empty())
28 .count();
29 println!(
30 "chats {} with_preview {with_preview} with_body {with_body}",
31 chats.len()
32 );
33 let mut user_ids: Vec<String> = chats
34 .iter()
35 .flat_map(|chat| chat.members.iter())
36 .filter_map(|member| member.user_id.clone())
37 .filter(|id| *id != me)
38 .collect();
39 user_ids.sort();
40 user_ids.dedup();
41 user_ids.truncate(40);
42 println!("distinct users {}", user_ids.len());
43
44 let started = Instant::now();
45 match graph.user_photos(&user_ids).await {
46 Ok(results) => {
47 let mut kinds: BTreeMap<String, usize> = BTreeMap::new();
48 let (mut hits, mut misses, mut errors, mut total_bytes) = (0, 0, 0, 0usize);
49 for result in &results {
50 match result {
51 Ok(Some(photo)) => {
52 hits += 1;
53 total_bytes += photo.bytes.len();
54 *kinds.entry(photo.content_type.clone()).or_default() += 1;
55 }
56 Ok(None) => misses += 1,
57 Err(error) => {
58 errors += 1;
59 if errors == 1 {
60 println!("first photo error status: {}", status_of(error));
61 }
62 }
63 }
64 }
65 println!(
66 "photos hits {hits} misses {misses} errors {errors} bytes {total_bytes} types {kinds:?} in {} ms",
67 started.elapsed().as_millis()
68 );
69 }
70 Err(error) => println!("photos failed: {}", status_of(&error)),
71 }
72}
73
74fn status_of(error: &graph::Error) -> String {
75 match error {
76 graph::Error::Session(session::Error::Api { status, .. }) => format!("HTTP {status}"),
77 graph::Error::Session(session::Error::NoFreshToken { .. }) => {
78 "no fresh token (scope not granted)".into()
79 }
80 graph::Error::Session(session::Error::LoginRequired(_)) => {
81 "login required (scope not granted)".into()
82 }
83 _ => "other error".into(),
84 }
85}