| 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") { source.to_owned() } else { format!("{CDN_ROOT}{source}") } |
| 35 | } |
| 36 | |
| 37 | fn file_id(id: &str) -> String { |
| 38 | id.chars().map(|letter| if letter.is_ascii_alphanumeric() || letter == '-' || letter == '_' { letter } else { '_' }).collect() |
| 39 | } |
| 40 | |
| 41 | fn extension_of(url: &str) -> &str { |
| 42 | let path = url.split(['?', '#']).next().unwrap_or(url); |
| 43 | path.rsplit_once('.').map(|(_, extension)| extension).filter(|extension| (2..=4).contains(&extension.len())).unwrap_or("jpg") |
| 44 | } |
| 45 | |
| 46 | pub fn parse_catalog(body: &Value) -> Vec<DefaultBackground> { |
| 47 | body["videoBackgroundImages"] |
| 48 | .as_array() |
| 49 | .into_iter() |
| 50 | .flatten() |
| 51 | .filter_map(|entry| { |
| 52 | let source = entry["src"].as_str().filter(|source| !source.is_empty())?; |
| 53 | let id = entry["id"].as_str().filter(|id| !id.is_empty())?; |
| 54 | Some(DefaultBackground { |
| 55 | id: id.to_owned(), |
| 56 | name: entry["name"].as_str().unwrap_or(id).to_owned(), |
| 57 | image_url: absolute(source), |
| 58 | thumbnail_url: absolute(entry["thumb_src"].as_str().filter(|thumb| !thumb.is_empty()).unwrap_or(source)), |
| 59 | }) |
| 60 | }) |
| 61 | .collect() |
| 62 | } |
| 63 | |
| 64 | #[derive(Debug, Clone)] |
| 65 | pub struct BackgroundCache { |
| 66 | directory: PathBuf, |
| 67 | } |
| 68 | |
| 69 | impl BackgroundCache { |
| 70 | pub fn new(directory: PathBuf) -> Self { |
| 71 | BackgroundCache { directory } |
| 72 | } |
| 73 | |
| 74 | pub fn thumbnail_path(&self, background: &DefaultBackground) -> PathBuf { |
| 75 | self.directory.join(THUMBNAIL_DIR).join(format!("{}.{}", file_id(&background.id), extension_of(&background.thumbnail_url))) |
| 76 | } |
| 77 | |
| 78 | pub fn image_path(&self, background: &DefaultBackground) -> PathBuf { |
| 79 | self.directory.join(IMAGE_DIR).join(format!("{}.{}", file_id(&background.id), extension_of(&background.image_url))) |
| 80 | } |
| 81 | |
| 82 | pub fn cached_catalog(&self) -> Vec<DefaultBackground> { |
| 83 | std::fs::read(self.directory.join(CATALOG_FILE)) |
| 84 | .ok() |
| 85 | .and_then(|bytes| serde_json::from_slice::<Value>(&bytes).ok()) |
| 86 | .map(|body| parse_catalog(&body)) |
| 87 | .unwrap_or_default() |
| 88 | } |
| 89 | |
| 90 | pub async fn refresh_catalog(&self, session: &Session) -> Result<Vec<DefaultBackground>> { |
| 91 | let bytes = download(session, CATALOG_URL).await?; |
| 92 | let body: Value = serde_json::from_slice(&bytes).map_err(|error| Error::Signaling(format!("background list is not JSON: {error}")))?; |
| 93 | let catalog = parse_catalog(&body); |
| 94 | if !catalog.is_empty() { |
| 95 | std::fs::create_dir_all(&self.directory).map_err(|error| Error::Webrtc(format!("background cache: {error}")))?; |
| 96 | let _ = std::fs::write(self.directory.join(CATALOG_FILE), &bytes); |
| 97 | } |
| 98 | Ok(catalog) |
| 99 | } |
| 100 | |
| 101 | pub async fn ensure_thumbnail(&self, session: &Session, background: &DefaultBackground) -> Result<PathBuf> { |
| 102 | fetch_once(session, &background.thumbnail_url, self.thumbnail_path(background)).await |
| 103 | } |
| 104 | |
| 105 | pub async fn ensure_image(&self, session: &Session, background: &DefaultBackground) -> Result<PathBuf> { |
| 106 | fetch_once(session, &background.image_url, self.image_path(background)).await |
| 107 | } |
| 108 | } |
| 109 | |
| 110 | async fn fetch_once(session: &Session, url: &str, path: PathBuf) -> Result<PathBuf> { |
| 111 | if path.exists() { |
| 112 | return Ok(path); |
| 113 | } |
| 114 | let bytes = download(session, url).await?; |
| 115 | if let Some(parent) = path.parent() { |
| 116 | std::fs::create_dir_all(parent).map_err(|error| Error::Webrtc(format!("background cache: {error}")))?; |
| 117 | } |
| 118 | let partial = path.with_extension("part"); |
| 119 | std::fs::write(&partial, bytes).and_then(|()| std::fs::rename(&partial, &path)).map_err(|error| Error::Webrtc(format!("background cache: {error}")))?; |
| 120 | Ok(path) |
| 121 | } |
| 122 | |
| 123 | async fn download(session: &Session, url: &str) -> Result<Vec<u8>> { |
| 124 | let answer = session.send(Request::anonymous_binary_get(url, Vec::new()), &Scope::graph(FETCH_SCOPE)).await?; |
| 125 | let encoded = answer.body["base64"].as_str().ok_or_else(|| Error::Signaling("download without a body".into()))?; |
| 126 | base64::engine::general_purpose::STANDARD |
| 127 | .decode(encoded) |
| 128 | .map_err(|error| Error::Signaling(format!("download is not base64: {error}"))) |
| 129 | } |
| 130 | |
| 131 | #[derive(Debug, Clone)] |
| 132 | pub struct BackgroundPicture { |
| 133 | rgb: Vec<u8>, |
| 134 | width: usize, |
| 135 | height: usize, |
| 136 | } |
| 137 | |
| 138 | impl BackgroundPicture { |
| 139 | pub fn from_rgb(rgb: Vec<u8>, width: usize, height: usize) -> Option<Self> { |
| 140 | (width > 0 && height > 0 && rgb.len() == width * height * CHANNELS).then_some(BackgroundPicture { rgb, width, height }) |
| 141 | } |
| 142 | |
| 143 | pub fn load(path: &Path) -> Result<Self> { |
| 144 | let mut picture = image::open(path).map_err(|error| Error::Webrtc(format!("background image: {error}")))?; |
| 145 | if picture.width().max(picture.height()) > MAX_SIDE { |
| 146 | picture = picture.resize(MAX_SIDE, MAX_SIDE, image::imageops::FilterType::Triangle); |
| 147 | } |
| 148 | let rgb = picture.to_rgb8(); |
| 149 | let (width, height) = (rgb.width() as usize, rgb.height() as usize); |
| 150 | BackgroundPicture::from_rgb(rgb.into_raw(), width, height).ok_or_else(|| Error::Webrtc("background image is empty".into())) |
| 151 | } |
| 152 | |
| 153 | pub fn size(&self) -> (usize, usize) { |
| 154 | (self.width, self.height) |
| 155 | } |
| 156 | |
| 157 | fn sample(&self, x: f32, y: f32, channel: usize) -> f32 { |
| 158 | let (x, y) = (x.clamp(0., (self.width - 1) as f32), y.clamp(0., (self.height - 1) as f32)); |
| 159 | let (left, top) = (x.floor() as usize, y.floor() as usize); |
| 160 | let (right, bottom) = ((left + 1).min(self.width - 1), (top + 1).min(self.height - 1)); |
| 161 | let (across, down) = (x - left as f32, y - top as f32); |
| 162 | let at = |column: usize, row: usize| f32::from(self.rgb[(row * self.width + column) * CHANNELS + channel]); |
| 163 | let upper = at(left, top) * (1. - across) + at(right, top) * across; |
| 164 | let lower = at(left, bottom) * (1. - across) + at(right, bottom) * across; |
| 165 | upper * (1. - down) + lower * down |
| 166 | } |
| 167 | |
| 168 | pub fn covering(&self, width: usize, height: usize) -> Vec<u8> { |
| 169 | let scale = (width as f32 / self.width as f32).max(height as f32 / self.height as f32); |
| 170 | let offset_x = (self.width as f32 * scale - width as f32) / 2.; |
| 171 | let offset_y = (self.height as f32 * scale - height as f32) / 2.; |
| 172 | let mut covered = vec![0u8; width * height * CHANNELS]; |
| 173 | for row in 0..height { |
| 174 | let source_y = (row as f32 + 0.5 + offset_y) / scale - 0.5; |
| 175 | for column in 0..width { |
| 176 | let source_x = (column as f32 + 0.5 + offset_x) / scale - 0.5; |
| 177 | for channel in 0..CHANNELS { |
| 178 | covered[(row * width + column) * CHANNELS + channel] = (self.sample(source_x, source_y, channel) + 0.5) as u8; |
| 179 | } |
| 180 | } |
| 181 | } |
| 182 | covered |
| 183 | } |
| 184 | } |
| 185 | |
| 186 | #[cfg(test)] |
| 187 | mod tests { |
| 188 | use serde_json::json; |
| 189 | |
| 190 | use super::*; |
| 191 | |
| 192 | fn catalog() -> Value { |
| 193 | json!({"videoBackgroundImages": [ |
| 194 | {"id": "office_01", "name": "Modern office", "filetype": "jpg", "src": "/evergreen-assets/backgroundimages/office_01.jpg", "thumb_src": "/evergreen-assets/backgroundimages/office_01_thumb.jpg"}, |
| 195 | {"id": "beach", "name": "Beach", "src": "https://cdn.example/beach.png"}, |
| 196 | {"id": "", "src": "/x.jpg"}, |
| 197 | {"id": "no_source"}, |
| 198 | ]}) |
| 199 | } |
| 200 | |
| 201 | #[test] |
| 202 | fn the_catalog_lists_images_with_absolute_urls_and_skips_broken_entries() { |
| 203 | let images = parse_catalog(&catalog()); |
| 204 | assert_eq!(images.len(), 2); |
| 205 | assert_eq!(images[0].id, "office_01"); |
| 206 | assert_eq!(images[0].name, "Modern office"); |
| 207 | assert_eq!(images[0].image_url, "https://statics.teams.cdn.office.net/evergreen-assets/backgroundimages/office_01.jpg"); |
| 208 | assert_eq!(images[0].thumbnail_url, "https://statics.teams.cdn.office.net/evergreen-assets/backgroundimages/office_01_thumb.jpg"); |
| 209 | assert_eq!(images[1].image_url, "https://cdn.example/beach.png"); |
| 210 | assert_eq!(images[1].thumbnail_url, "https://cdn.example/beach.png"); |
| 211 | assert!(parse_catalog(&json!({})).is_empty()); |
| 212 | } |
| 213 | |
| 214 | #[test] |
| 215 | fn cached_files_live_under_the_cache_directory_by_id() { |
| 216 | let cache = BackgroundCache::new(PathBuf::from("cache")); |
| 217 | let images = parse_catalog(&catalog()); |
| 218 | assert_eq!(cache.thumbnail_path(&images[0]), Path::new("cache/thumbnails/office_01.jpg")); |
| 219 | assert_eq!(cache.image_path(&images[1]), Path::new("cache/images/beach.png")); |
| 220 | let odd = DefaultBackground { id: "a/b c".into(), name: String::new(), image_url: "https://x/y".into(), thumbnail_url: "https://x/y.webp?v=3".into() }; |
| 221 | assert_eq!(cache.thumbnail_path(&odd), Path::new("cache/thumbnails/a_b_c.webp")); |
| 222 | assert_eq!(cache.image_path(&odd), Path::new("cache/images/a_b_c.jpg")); |
| 223 | } |
| 224 | |
| 225 | #[test] |
| 226 | fn a_saved_catalog_is_read_back_and_a_missing_one_is_empty() { |
| 227 | let directory = tempfile_directory("catalog"); |
| 228 | let cache = BackgroundCache::new(directory.clone()); |
| 229 | assert!(cache.cached_catalog().is_empty()); |
| 230 | std::fs::write(directory.join("config.json"), catalog().to_string()).unwrap(); |
| 231 | assert_eq!(cache.cached_catalog().len(), 2); |
| 232 | let _ = std::fs::remove_dir_all(directory); |
| 233 | } |
| 234 | |
| 235 | fn tempfile_directory(name: &str) -> PathBuf { |
| 236 | let directory = std::env::temp_dir().join(format!("calling-background-{name}-{}", uuid::Uuid::new_v4())); |
| 237 | std::fs::create_dir_all(&directory).unwrap(); |
| 238 | directory |
| 239 | } |
| 240 | |
| 241 | fn halves(width: usize, height: usize) -> BackgroundPicture { |
| 242 | let rgb = (0..width * height).flat_map(|index| if index % width < width / 2 { [200, 0, 0] } else { [0, 0, 200] }).collect(); |
| 243 | BackgroundPicture::from_rgb(rgb, width, height).unwrap() |
| 244 | } |
| 245 | |
| 246 | #[test] |
| 247 | fn a_wide_picture_covers_a_narrow_frame_and_crops_the_sides_evenly() { |
| 248 | let covered = halves(40, 10).covering(10, 10); |
| 249 | assert_eq!(covered.len(), 10 * 10 * 3); |
| 250 | assert_eq!(&covered[(5 * 10) * 3..(5 * 10) * 3 + 3], &[200, 0, 0]); |
| 251 | assert_eq!(&covered[(5 * 10 + 9) * 3..(5 * 10 + 9) * 3 + 3], &[0, 0, 200]); |
| 252 | } |
| 253 | |
| 254 | #[test] |
| 255 | fn a_picture_of_the_frame_shape_is_only_resampled() { |
| 256 | let covered = halves(8, 4).covering(16, 8); |
| 257 | assert_eq!(&covered[0..3], &[200, 0, 0]); |
| 258 | assert_eq!(&covered[15 * 3..15 * 3 + 3], &[0, 0, 200]); |
| 259 | assert_eq!(covered.len(), 16 * 8 * 3); |
| 260 | } |
| 261 | |
| 262 | #[test] |
| 263 | fn pictures_need_pixels_for_their_size() { |
| 264 | assert!(BackgroundPicture::from_rgb(vec![0; 5], 2, 2).is_none()); |
| 265 | assert!(BackgroundPicture::from_rgb(Vec::new(), 0, 0).is_none()); |
| 266 | } |
| 267 | |
| 268 | #[test] |
| 269 | fn a_picture_file_is_loaded_and_missing_ones_fail() { |
| 270 | let directory = tempfile_directory("load"); |
| 271 | let path = directory.join("pic.png"); |
| 272 | image::RgbImage::from_pixel(6, 4, image::Rgb([10, 20, 30])).save(&path).unwrap(); |
| 273 | let picture = BackgroundPicture::load(&path).unwrap(); |
| 274 | assert_eq!(picture.size(), (6, 4)); |
| 275 | assert!(BackgroundPicture::load(&directory.join("none.png")).is_err()); |
| 276 | let _ = std::fs::remove_dir_all(directory); |
| 277 | } |
| 278 | } |