| 1 | use std::fs; |
| 2 | use std::io; |
| 3 | use std::path::{Path, PathBuf}; |
| 4 | use std::sync::Arc; |
| 5 | use std::sync::atomic::{AtomicBool, Ordering}; |
| 6 | |
| 7 | use gpui_kit::App; |
| 8 | |
| 9 | use super::platform; |
| 10 | |
| 11 | pub const TEAMS_SOUND_BASE_URL: &str = |
| 12 | "https://statics.teams.cdn.office.net/evergreen-assets/audio/"; |
| 13 | const SOUND_DIRECTORY: &str = "sounds"; |
| 14 | const PARTIAL_SUFFIX: &str = ".partial"; |
| 15 | |
| 16 | pub fn cache_directory() -> Option<PathBuf> { |
| 17 | directories::ProjectDirs::from("", "", store::DATA_DIR_NAME) |
| 18 | .map(|directories| directories.cache_dir().join(SOUND_DIRECTORY)) |
| 19 | } |
| 20 | |
| 21 | pub fn is_mp3(bytes: &[u8]) -> bool { |
| 22 | bytes.starts_with(b"ID3") || matches!(bytes, [0xFF, second, ..] if second & 0xE0 == 0xE0) |
| 23 | } |
| 24 | |
| 25 | pub fn read_cached(directory: &Path, file_name: &str) -> Option<Vec<u8>> { |
| 26 | fs::read(directory.join(file_name)) |
| 27 | .ok() |
| 28 | .filter(|bytes| is_mp3(bytes)) |
| 29 | } |
| 30 | |
| 31 | pub fn write_cached(directory: &Path, file_name: &str, bytes: &[u8]) -> io::Result<()> { |
| 32 | fs::create_dir_all(directory)?; |
| 33 | let partial = directory.join(format!("{file_name}{PARTIAL_SUFFIX}")); |
| 34 | fs::write(&partial, bytes)?; |
| 35 | fs::rename(&partial, directory.join(file_name)) |
| 36 | } |
| 37 | |
| 38 | fn load(file_name: &'static str, cx: &App) -> gpui_kit::Task<Option<Vec<u8>>> { |
| 39 | let client = cx.http_client(); |
| 40 | cx.background_executor().spawn(async move { |
| 41 | let directory = cache_directory()?; |
| 42 | if let Some(bytes) = read_cached(&directory, file_name) { |
| 43 | return Some(bytes); |
| 44 | } |
| 45 | use futures_util::AsyncReadExt as _; |
| 46 | let url = format!("{TEAMS_SOUND_BASE_URL}{file_name}"); |
| 47 | let mut response = client.get(&url, ().into(), true).await.ok()?; |
| 48 | let mut body = Vec::new(); |
| 49 | response.body_mut().read_to_end(&mut body).await.ok()?; |
| 50 | if !response.status().is_success() || !is_mp3(&body) { |
| 51 | log::warn!( |
| 52 | "teams sound {file_name} not loaded: status {}", |
| 53 | response.status() |
| 54 | ); |
| 55 | return None; |
| 56 | } |
| 57 | if let Err(error) = write_cached(&directory, file_name, &body) { |
| 58 | log::warn!("teams sound {file_name} not cached: {error}"); |
| 59 | } |
| 60 | Some(body) |
| 61 | }) |
| 62 | } |
| 63 | |
| 64 | pub fn prefetch(file_names: &[&'static str], cx: &App) { |
| 65 | for file_name in file_names { |
| 66 | load(file_name, cx).detach(); |
| 67 | } |
| 68 | } |
| 69 | |
| 70 | pub fn play(file_name: &'static str, cx: &App) { |
| 71 | play_or(file_name, || {}, cx); |
| 72 | } |
| 73 | |
| 74 | pub fn play_or(file_name: &'static str, fallback: fn(), cx: &App) { |
| 75 | let loading = load(file_name, cx); |
| 76 | cx.background_executor() |
| 77 | .spawn(async move { |
| 78 | match loading.await { |
| 79 | Some(bytes) => platform::play_mp3(bytes), |
| 80 | None => fallback(), |
| 81 | } |
| 82 | }) |
| 83 | .detach(); |
| 84 | } |
| 85 | |
| 86 | pub struct SoundHandle { |
| 87 | stop: Arc<AtomicBool>, |
| 88 | } |
| 89 | |
| 90 | impl Drop for SoundHandle { |
| 91 | fn drop(&mut self) { |
| 92 | self.stop.store(true, Ordering::SeqCst); |
| 93 | } |
| 94 | } |
| 95 | |
| 96 | pub fn start(file_name: &'static str, looped: bool, cx: &App) -> SoundHandle { |
| 97 | let stop = Arc::new(AtomicBool::new(false)); |
| 98 | let flag = stop.clone(); |
| 99 | let loading = load(file_name, cx); |
| 100 | cx.background_executor() |
| 101 | .spawn(async move { |
| 102 | if let Some(bytes) = loading.await |
| 103 | && !flag.load(Ordering::SeqCst) |
| 104 | { |
| 105 | platform::play_mp3_until(bytes, looped, flag); |
| 106 | } |
| 107 | }) |
| 108 | .detach(); |
| 109 | SoundHandle { stop } |
| 110 | } |
| 111 | |
| 112 | #[cfg(test)] |
| 113 | mod tests { |
| 114 | use super::*; |
| 115 | |
| 116 | #[test] |
| 117 | fn mp3_files_start_with_a_tag_or_a_frame_sync() { |
| 118 | assert!(is_mp3(b"ID3\x04\x00")); |
| 119 | assert!(is_mp3(&[0xFF, 0xFB, 0x90])); |
| 120 | assert!(!is_mp3(b"<?xml version")); |
| 121 | assert!(!is_mp3(&[])); |
| 122 | } |
| 123 | |
| 124 | #[test] |
| 125 | fn a_cached_sound_round_trips_and_junk_is_ignored() { |
| 126 | let directory = tempfile::tempdir().unwrap(); |
| 127 | let sounds = directory.path().join("sounds"); |
| 128 | write_cached(&sounds, "end.mp3", b"ID3 tone").unwrap(); |
| 129 | assert_eq!( |
| 130 | read_cached(&sounds, "end.mp3").as_deref(), |
| 131 | Some(&b"ID3 tone"[..]) |
| 132 | ); |
| 133 | assert!(!sounds.join("end.mp3.partial").exists()); |
| 134 | write_cached(&sounds, "junk.mp3", b"<Error/>").unwrap(); |
| 135 | assert_eq!(read_cached(&sounds, "junk.mp3"), None); |
| 136 | assert_eq!(read_cached(&sounds, "missing.mp3"), None); |
| 137 | } |
| 138 | } |