BlueGit

ict rusty-teams

Files

rusty-teams / crates / core / src / avatars.rs

avatars.rs

23a3899b History
avatars.rs 4.2 KiB Download Raw
1use chrono::{Duration, Utc};
2use store::{AvatarRecord, is_bot_id};
3
4use crate::engine::SyncEngine;
5use crate::error::Result;
6use crate::events::CoreEvent;
7use crate::remote::Remote;
8
9const AVATAR_MAX_AGE_DAYS: i64 = 7;
10const AVATAR_BATCH: usize = 60;
11
12#[derive(Debug, Clone, PartialEq, Eq)]
13pub struct Avatar {
14 pub bytes: Vec<u8>,
15 pub content_type: String,
16}
17
18impl<R: Remote> SyncEngine<R> {
19 pub fn avatar(&self, user_id: &str) -> Option<Avatar> {
20 let record = self.store.avatar(user_id).ok().flatten()?;
21 Some(Avatar {
22 bytes: record.bytes?,
23 content_type: record.content_type,
24 })
25 }
26
27 pub async fn fetch_avatars(&self, user_ids: &[String]) -> Result<()> {
28 let cutoff = Utc::now() - Duration::days(AVATAR_MAX_AGE_DAYS);
29 let mut unique = user_ids.to_vec();
30 unique.sort();
31 unique.dedup();
32 let wanted = self.store.avatar_ids_needing_fetch(&unique, cutoff)?;
33 let claimed = self.claim_avatar_ids(wanted);
34 let outcome = self.fetch_claimed_avatars(&claimed).await;
35 self.release_avatar_ids(&claimed);
36 outcome
37 }
38
39 async fn fetch_claimed_avatars(&self, claimed: &[String]) -> Result<()> {
40 let (bots, people): (Vec<String>, Vec<String>) = claimed
41 .iter()
42 .cloned()
43 .partition(|user_id| is_bot_id(user_id));
44 let mut first_error = None;
45 let mut fetched_any = false;
46 if !bots.is_empty() {
47 match self.fetch_bot_icons(&bots).await {
48 Ok(changed) => {
49 fetched_any = true;
50 if !changed.is_empty() {
51 let _ = self
52 .events
53 .send(CoreEvent::AvatarsChanged { user_ids: changed });
54 }
55 }
56 Err(error) => {
57 first_error.get_or_insert(error);
58 }
59 }
60 }
61 for chunk in people.chunks(AVATAR_BATCH) {
62 let photos = match self.remote.user_photos(chunk).await {
63 Ok(photos) => photos,
64 Err(error) => {
65 first_error.get_or_insert(error);
66 continue;
67 }
68 };
69 let mut changed = Vec::new();
70 for (user_id, photo) in chunk.iter().zip(photos) {
71 let (bytes, content_type) = match photo {
72 Ok(Some(photo)) => (Some(photo.bytes), photo.content_type),
73 Ok(None) => (None, String::new()),
74 Err(error) => {
75 first_error.get_or_insert(error);
76 continue;
77 }
78 };
79 fetched_any = true;
80 if bytes.is_some() {
81 changed.push(user_id.clone());
82 }
83 self.store.upsert_avatar(&AvatarRecord {
84 user_id: user_id.clone(),
85 bytes,
86 content_type,
87 fetched_at: Utc::now(),
88 })?;
89 }
90 if !changed.is_empty() {
91 let _ = self
92 .events
93 .send(CoreEvent::AvatarsChanged { user_ids: changed });
94 }
95 }
96 match first_error {
97 Some(error) if !fetched_any => Err(error),
98 Some(error) => {
99 self.report(format!("some avatars could not be fetched: {error}"));
100 Ok(())
101 }
102 None => Ok(()),
103 }
104 }
105
106 fn claim_avatar_ids(&self, wanted: Vec<String>) -> Vec<String> {
107 let mut in_flight = self
108 .avatars_in_flight
109 .lock()
110 .unwrap_or_else(|poisoned| poisoned.into_inner());
111 wanted
112 .into_iter()
113 .filter(|user_id| in_flight.insert(user_id.clone()))
114 .collect()
115 }
116
117 fn release_avatar_ids(&self, claimed: &[String]) {
118 let mut in_flight = self
119 .avatars_in_flight
120 .lock()
121 .unwrap_or_else(|poisoned| poisoned.into_inner());
122 for user_id in claimed {
123 in_flight.remove(user_id);
124 }
125 }
126}