| 1 | use std::path::{Path, PathBuf}; |
| 2 | |
| 3 | use base64::Engine as _; |
| 4 | use serde_json::Value; |
| 5 | use session::{Request, Scope, Session}; |
| 6 | |
| 7 | use crate::error::{Error, Result}; |
| 8 | |
| 9 | pub const CATALOG_URL: &str = chatsvc::teams_cdn::BACKGROUND_CATALOG_URL; |
| 10 | pub const CDN_ROOT: &str = chatsvc::teams_cdn::ROOT; |
| 11 | const FETCH_SCOPE: &str = "Chat.Read"; |
| 12 | const MAX_SIDE: u32 = 1920; |
| 13 | const CATALOG_FILE: &str = "config.json"; |
| 14 | const THUMBNAIL_DIR: &str = "thumbnails"; |
| 15 | const IMAGE_DIR: &str = "images"; |
| 16 | const CHANNELS: usize = 3; |
| 17 | |
| 18 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 19 | pub enum BackgroundChoice { |
| 20 | None, |
| 21 | Blur, |
| 22 | Image(PathBuf), |
| 23 | } |
| 24 | |
| 25 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 26 | pub struct DefaultBackground { |
| 27 | pub id: String, |
| 28 | pub name: String, |
| 29 | pub image_url: String, |
| 30 | pub thumbnail_url: String, |
| 31 | } |
| 32 | |
| 33 | fn absolute(source: &str) -> String { |
| 34 | if source.starts_with("http") { |
| 35 | source.to_owned() |
| 36 | } else { |
| 37 | format!("{CDN_ROOT}{source}") |
| 38 | } |
| 39 | } |
| 40 | |
| 41 | fn file_id(id: &str) -> String { |
| 42 | id.chars() |
| 43 | .map(|letter| { |
| 44 | if letter.is_ascii_alphanumeric() || letter == '-' || letter == '_' { |
| 45 | letter |
| 46 | } else { |
| 47 | '_' |
| 48 | } |
| 49 | }) |
| 50 | .collect() |
| 51 | } |
| 52 | |
| 53 | fn extension_of(url: &str) -> &str { |
| 54 | let path = url.split(['?', '#']).next().unwrap_or(url); |
| 55 | path.rsplit_once('.') |
| 56 | .map(|(_, extension)| extension) |
| 57 | .filter(|extension| (2..=4).contains(&extension.len())) |
| 58 | .unwrap_or("jpg") |
| 59 | } |
| 60 | |
| 61 | pub fn parse_catalog(body: &Value) -> Vec<DefaultBackground> { |
| 62 | body["videoBackgroundImages"] |
| 63 | .as_array() |
| 64 | .into_iter() |
| 65 | .flatten() |
| 66 | .filter_map(|entry| { |
| 67 | let source = entry["src"].as_str().filter(|source| !source.is_empty())?; |
| 68 | let id = entry["id"].as_str().filter(|id| !id.is_empty())?; |
| 69 | Some(DefaultBackground { |
| 70 | id: id.to_owned(), |
| 71 | name: entry["name"].as_str().unwrap_or(id).to_owned(), |
| 72 | image_url: absolute(source), |
| 73 | thumbnail_url: absolute( |
| 74 | entry["thumb_src"] |
| 75 | .as_str() |
| 76 | .filter(|thumb| !thumb.is_empty()) |
| 77 | .unwrap_or(source), |
| 78 | ), |
| 79 | }) |
| 80 | }) |
| 81 | .collect() |
| 82 | } |
| 83 | |
| 84 | #[derive(Debug, Clone)] |
| 85 | pub struct BackgroundCache { |
| 86 | directory: PathBuf, |
| 87 | } |
| 88 | |
| 89 | impl BackgroundCache { |
| 90 | pub fn new(directory: PathBuf) -> Self { |
| 91 | BackgroundCache { directory } |
| 92 | } |
| 93 | |
| 94 | pub fn thumbnail_path(&self, background: &DefaultBackground) -> PathBuf { |
| 95 | self.directory.join(THUMBNAIL_DIR).join(format!( |
| 96 | "{}.{}", |
| 97 | file_id(&background.id), |
| 98 | extension_of(&background.thumbnail_url) |
| 99 | )) |
| 100 | } |
| 101 | |
| 102 | pub fn image_path(&self, background: &DefaultBackground) -> PathBuf { |
| 103 | self.directory.join(IMAGE_DIR).join(format!( |
| 104 | "{}.{}", |
| 105 | file_id(&background.id), |
| 106 | extension_of(&background.image_url) |
| 107 | )) |
| 108 | } |
| 109 | |
| 110 | pub fn cached_catalog(&self) -> Vec<DefaultBackground> { |
| 111 | std::fs::read(self.directory.join(CATALOG_FILE)) |
| 112 | .ok() |
| 113 | .and_then(|bytes| serde_json::from_slice::<Value>(&bytes).ok()) |
| 114 | .map(|body| parse_catalog(&body)) |
| 115 | .unwrap_or_default() |
| 116 | } |
| 117 | |
| 118 | pub async fn refresh_catalog(&self, session: &Session) -> Result<Vec<DefaultBackground>> { |
| 119 | let bytes = download(session, CATALOG_URL).await?; |
| 120 | let body: Value = serde_json::from_slice(&bytes) |
| 121 | .map_err(|error| Error::Signaling(format!("background list is not JSON: {error}")))?; |
| 122 | let catalog = parse_catalog(&body); |
| 123 | if !catalog.is_empty() { |
| 124 | std::fs::create_dir_all(&self.directory) |
| 125 | .map_err(|error| Error::Webrtc(format!("background cache: {error}")))?; |
| 126 | let _ = std::fs::write(self.directory.join(CATALOG_FILE), &bytes); |
| 127 | } |
| 128 | Ok(catalog) |
| 129 | } |
| 130 | |
| 131 | pub async fn ensure_thumbnail( |
| 132 | &self, |
| 133 | session: &Session, |
| 134 | background: &DefaultBackground, |
| 135 | ) -> Result<PathBuf> { |
| 136 | fetch_once( |
| 137 | session, |
| 138 | &background.thumbnail_url, |
| 139 | self.thumbnail_path(background), |
| 140 | ) |
| 141 | .await |
| 142 | } |
| 143 | |
| 144 | pub async fn ensure_image( |
| 145 | &self, |
| 146 | session: &Session, |
| 147 | background: &DefaultBackground, |
| 148 | ) -> Result<PathBuf> { |
| 149 | fetch_once(session, &background.image_url, self.image_path(background)).await |
| 150 | } |
| 151 | } |
| 152 | |
| 153 | async fn fetch_once(session: &Session, url: &str, path: PathBuf) -> Result<PathBuf> { |
| 154 | if path.exists() { |
| 155 | return Ok(path); |
| 156 | } |
| 157 | let bytes = download(session, url).await?; |
| 158 | if let Some(parent) = path.parent() { |
| 159 | std::fs::create_dir_all(parent) |
| 160 | .map_err(|error| Error::Webrtc(format!("background cache: {error}")))?; |
| 161 | } |
| 162 | let partial = path.with_extension("part"); |
| 163 | std::fs::write(&partial, bytes) |
| 164 | .and_then(|()| std::fs::rename(&partial, &path)) |
| 165 | .map_err(|error| Error::Webrtc(format!("background cache: {error}")))?; |
| 166 | Ok(path) |
| 167 | } |
| 168 | |
| 169 | async fn download(session: &Session, url: &str) -> Result<Vec<u8>> { |
| 170 | let answer = session |
| 171 | .send( |
| 172 | Request::anonymous_binary_get(url, Vec::new()), |
| 173 | &Scope::graph(FETCH_SCOPE), |
| 174 | ) |
| 175 | .await?; |
| 176 | let encoded = answer.body["base64"] |
| 177 | .as_str() |
| 178 | .ok_or_else(|| Error::Signaling("download without a body".into()))?; |
| 179 | base64::engine::general_purpose::STANDARD |
| 180 | .decode(encoded) |
| 181 | .map_err(|error| Error::Signaling(format!("download is not base64: {error}"))) |
| 182 | } |
| 183 | |
| 184 | #[derive(Debug, Clone)] |
| 185 | pub struct BackgroundPicture { |
| 186 | rgb: Vec<u8>, |
| 187 | width: usize, |
| 188 | height: usize, |
| 189 | } |
| 190 | |
| 191 | impl BackgroundPicture { |
| 192 | pub fn from_rgb(rgb: Vec<u8>, width: usize, height: usize) -> Option<Self> { |
| 193 | (width > 0 && height > 0 && rgb.len() == width * height * CHANNELS) |
| 194 | .then_some(BackgroundPicture { rgb, width, height }) |
| 195 | } |
| 196 | |
| 197 | pub fn load(path: &Path) -> Result<Self> { |
| 198 | let mut picture = image::open(path) |
| 199 | .map_err(|error| Error::Webrtc(format!("background image: {error}")))?; |
| 200 | if picture.width().max(picture.height()) > MAX_SIDE { |
| 201 | picture = picture.resize(MAX_SIDE, MAX_SIDE, image::imageops::FilterType::Triangle); |
| 202 | } |
| 203 | let rgb = picture.to_rgb8(); |
| 204 | let (width, height) = (rgb.width() as usize, rgb.height() as usize); |
| 205 | BackgroundPicture::from_rgb(rgb.into_raw(), width, height) |
| 206 | .ok_or_else(|| Error::Webrtc("background image is empty".into())) |
| 207 | } |
| 208 | |
| 209 | pub fn size(&self) -> (usize, usize) { |
| 210 | (self.width, self.height) |
| 211 | } |
| 212 | |
| 213 | fn sample(&self, x: f32, y: f32, channel: usize) -> f32 { |
| 214 | let (x, y) = ( |
| 215 | x.clamp(0., (self.width - 1) as f32), |
| 216 | y.clamp(0., (self.height - 1) as f32), |
| 217 | ); |
| 218 | let (left, top) = (x.floor() as usize, y.floor() as usize); |
| 219 | let (right, bottom) = ( |
| 220 | (left + 1).min(self.width - 1), |
| 221 | (top + 1).min(self.height - 1), |
| 222 | ); |
| 223 | let (across, down) = (x - left as f32, y - top as f32); |
| 224 | let at = |column: usize, row: usize| { |
| 225 | f32::from(self.rgb[(row * self.width + column) * CHANNELS + channel]) |
| 226 | }; |
| 227 | let upper = at(left, top) * (1. - across) + at(right, top) * across; |
| 228 | let lower = at(left, bottom) * (1. - across) + at(right, bottom) * across; |
| 229 | upper * (1. - down) + lower * down |
| 230 | } |
| 231 | |
| 232 | pub fn covering(&self, width: usize, height: usize) -> Vec<u8> { |
| 233 | let scale = (width as f32 / self.width as f32).max(height as f32 / self.height as f32); |
| 234 | let offset_x = (self.width as f32 * scale - width as f32) / 2.; |
| 235 | let offset_y = (self.height as f32 * scale - height as f32) / 2.; |
| 236 | let mut covered = vec![0u8; width * height * CHANNELS]; |
| 237 | for row in 0..height { |
| 238 | let source_y = (row as f32 + 0.5 + offset_y) / scale - 0.5; |
| 239 | for column in 0..width { |
| 240 | let source_x = (column as f32 + 0.5 + offset_x) / scale - 0.5; |
| 241 | for channel in 0..CHANNELS { |
| 242 | covered[(row * width + column) * CHANNELS + channel] = |
| 243 | (self.sample(source_x, source_y, channel) + 0.5) as u8; |
| 244 | } |
| 245 | } |
| 246 | } |
| 247 | covered |
| 248 | } |
| 249 | } |
| 250 | |
| 251 | #[cfg(test)] |
| 252 | mod tests { |
| 253 | use serde_json::json; |
| 254 | |
| 255 | use super::*; |
| 256 | |
| 257 | fn catalog() -> Value { |
| 258 | json!({"videoBackgroundImages": [ |
| 259 | {"id": "office_01", "name": "Modern office", "filetype": "jpg", "src": "/evergreen-assets/backgroundimages/office_01.jpg", "thumb_src": "/evergreen-assets/backgroundimages/office_01_thumb.jpg"}, |
| 260 | {"id": "beach", "name": "Beach", "src": "https://cdn.example/beach.png"}, |
| 261 | {"id": "", "src": "/x.jpg"}, |
| 262 | {"id": "no_source"}, |
| 263 | ]}) |
| 264 | } |
| 265 | |
| 266 | #[test] |
| 267 | fn the_catalog_lists_images_with_absolute_urls_and_skips_broken_entries() { |
| 268 | let images = parse_catalog(&catalog()); |
| 269 | assert_eq!(images.len(), 2); |
| 270 | assert_eq!(images[0].id, "office_01"); |
| 271 | assert_eq!(images[0].name, "Modern office"); |
| 272 | assert_eq!( |
| 273 | images[0].image_url, |
| 274 | "https://statics.teams.cdn.office.net/evergreen-assets/backgroundimages/office_01.jpg" |
| 275 | ); |
| 276 | assert_eq!( |
| 277 | images[0].thumbnail_url, |
| 278 | "https://statics.teams.cdn.office.net/evergreen-assets/backgroundimages/office_01_thumb.jpg" |
| 279 | ); |
| 280 | assert_eq!(images[1].image_url, "https://cdn.example/beach.png"); |
| 281 | assert_eq!(images[1].thumbnail_url, "https://cdn.example/beach.png"); |
| 282 | assert!(parse_catalog(&json!({})).is_empty()); |
| 283 | } |
| 284 | |
| 285 | #[test] |
| 286 | fn cached_files_live_under_the_cache_directory_by_id() { |
| 287 | let cache = BackgroundCache::new(PathBuf::from("cache")); |
| 288 | let images = parse_catalog(&catalog()); |
| 289 | assert_eq!( |
| 290 | cache.thumbnail_path(&images[0]), |
| 291 | Path::new("cache/thumbnails/office_01.jpg") |
| 292 | ); |
| 293 | assert_eq!( |
| 294 | cache.image_path(&images[1]), |
| 295 | Path::new("cache/images/beach.png") |
| 296 | ); |
| 297 | let odd = DefaultBackground { |
| 298 | id: "a/b c".into(), |
| 299 | name: String::new(), |
| 300 | image_url: "https://x/y".into(), |
| 301 | thumbnail_url: "https://x/y.webp?v=3".into(), |
| 302 | }; |
| 303 | assert_eq!( |
| 304 | cache.thumbnail_path(&odd), |
| 305 | Path::new("cache/thumbnails/a_b_c.webp") |
| 306 | ); |
| 307 | assert_eq!(cache.image_path(&odd), Path::new("cache/images/a_b_c.jpg")); |
| 308 | } |
| 309 | |
| 310 | #[test] |
| 311 | fn a_saved_catalog_is_read_back_and_a_missing_one_is_empty() { |
| 312 | let directory = tempfile_directory("catalog"); |
| 313 | let cache = BackgroundCache::new(directory.clone()); |
| 314 | assert!(cache.cached_catalog().is_empty()); |
| 315 | std::fs::write(directory.join("config.json"), catalog().to_string()).unwrap(); |
| 316 | assert_eq!(cache.cached_catalog().len(), 2); |
| 317 | let _ = std::fs::remove_dir_all(directory); |
| 318 | } |
| 319 | |
| 320 | fn tempfile_directory(name: &str) -> PathBuf { |
| 321 | let directory = std::env::temp_dir().join(format!( |
| 322 | "calling-background-{name}-{}", |
| 323 | uuid::Uuid::new_v4() |
| 324 | )); |
| 325 | std::fs::create_dir_all(&directory).unwrap(); |
| 326 | directory |
| 327 | } |
| 328 | |
| 329 | fn halves(width: usize, height: usize) -> BackgroundPicture { |
| 330 | let rgb = (0..width * height) |
| 331 | .flat_map(|index| { |
| 332 | if index % width < width / 2 { |
| 333 | [200, 0, 0] |
| 334 | } else { |
| 335 | [0, 0, 200] |
| 336 | } |
| 337 | }) |
| 338 | .collect(); |
| 339 | BackgroundPicture::from_rgb(rgb, width, height).unwrap() |
| 340 | } |
| 341 | |
| 342 | #[test] |
| 343 | fn a_wide_picture_covers_a_narrow_frame_and_crops_the_sides_evenly() { |
| 344 | let covered = halves(40, 10).covering(10, 10); |
| 345 | assert_eq!(covered.len(), 10 * 10 * 3); |
| 346 | assert_eq!(&covered[(5 * 10) * 3..(5 * 10) * 3 + 3], &[200, 0, 0]); |
| 347 | assert_eq!( |
| 348 | &covered[(5 * 10 + 9) * 3..(5 * 10 + 9) * 3 + 3], |
| 349 | &[0, 0, 200] |
| 350 | ); |
| 351 | } |
| 352 | |
| 353 | #[test] |
| 354 | fn a_picture_of_the_frame_shape_is_only_resampled() { |
| 355 | let covered = halves(8, 4).covering(16, 8); |
| 356 | assert_eq!(&covered[0..3], &[200, 0, 0]); |
| 357 | assert_eq!(&covered[15 * 3..15 * 3 + 3], &[0, 0, 200]); |
| 358 | assert_eq!(covered.len(), 16 * 8 * 3); |
| 359 | } |
| 360 | |
| 361 | #[test] |
| 362 | fn pictures_need_pixels_for_their_size() { |
| 363 | assert!(BackgroundPicture::from_rgb(vec![0; 5], 2, 2).is_none()); |
| 364 | assert!(BackgroundPicture::from_rgb(Vec::new(), 0, 0).is_none()); |
| 365 | } |
| 366 | |
| 367 | #[test] |
| 368 | fn a_picture_file_is_loaded_and_missing_ones_fail() { |
| 369 | let directory = tempfile_directory("load"); |
| 370 | let path = directory.join("pic.png"); |
| 371 | image::RgbImage::from_pixel(6, 4, image::Rgb([10, 20, 30])) |
| 372 | .save(&path) |
| 373 | .unwrap(); |
| 374 | let picture = BackgroundPicture::load(&path).unwrap(); |
| 375 | assert_eq!(picture.size(), (6, 4)); |
| 376 | assert!(BackgroundPicture::load(&directory.join("none.png")).is_err()); |
| 377 | let _ = std::fs::remove_dir_all(directory); |
| 378 | } |
| 379 | } |