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