speki_backend/media.rs
1//use rodio::Source;
2
3use serde::{Deserialize, Serialize};
4
5#[derive(Ord, PartialOrd, Eq, PartialEq, Hash, Deserialize, Clone, Serialize, Debug, Default)]
6pub struct AudioSource {
7 #[serde(default)]
8 #[serde(rename = "audio_local")]
9 local_name: Option<String>,
10 #[serde(default)]
11 #[serde(rename = "audio_url")]
12 url_backup: Option<String>,
13}
14
15impl AudioSource {
16 pub fn new(local_name: Option<String>, url_backup: Option<String>) -> Self {
17 Self {
18 local_name,
19 url_backup,
20 }
21 }
22
23 /*
24
25 pub fn _play_audio(&mut self) -> Option<std::thread::JoinHandle<()>> {
26 if !Config::load().ok()?.play_audio {
27 return None;
28 }
29
30 let path = self.get_path()?;
31
32 let handle = std::thread::spawn(move || {
33 let (_stream, stream_handle) = rodio::OutputStream::try_default().unwrap();
34
35 // Load a sound from a file
36 let file = BufReader::new(File::open(path).unwrap());
37 let source = rodio::Decoder::new(file).unwrap();
38
39 // Play the sound
40 stream_handle.play_raw(source.convert_samples()).unwrap();
41
42 // Block the thread until audio is done.
43 std::thread::sleep(std::time::Duration::from_secs(30));
44 });
45
46 Some(handle)
47 }
48 */
49}
50
51/*
52impl GetMedia for AudioSource {
53 fn local_name(&self) -> Option<String> {
54 self.local_name.clone()
55 }
56
57 fn url_backup(&self) -> Option<String> {
58 self.url_backup.clone()
59 }
60
61 fn update_local(&mut self, name: &str) {
62 self.local_name = Some(name.into());
63 }
64}
65
66pub trait GetMedia {
67 fn local_name(&self) -> Option<String>;
68 fn url_backup(&self) -> Option<String>;
69 fn update_local(&mut self, name: &str);
70
71 fn local_name_as_path(&self) -> Option<PathBuf> {
72 let local_file = self.local_name()?;
73 Some(get_media_path().join(local_file))
74 }
75
76 fn get_local_path(&self) -> Option<PathBuf> {
77 let local_name = self.local_name_as_path()?;
78 if local_name.exists() {
79 return Some(local_name);
80 }
81 None
82 }
83
84 fn download_media(&mut self) -> Option<PathBuf> {
85 let url = self.url_backup()?;
86
87 let response = ureq::get(&url).call().unwrap();
88
89 let fname = url.rsplit('/').next().unwrap();
90 let path = get_media_path().join(fname);
91
92 let mut out = std::fs::File::create(&path).unwrap();
93
94 let mut reader = response.into_reader();
95 std::io::copy(&mut reader, &mut out).ok()?;
96
97 self.update_local(fname);
98
99 Some(path)
100 }
101
102 fn get_path(&mut self) -> Option<PathBuf> {
103 self.get_local_path().or_else(|| self.download_media())
104 }
105}
106
107#[cfg(test)]
108mod tests {
109 use super::*;
110
111 #[test]
112 fn test_download_media() {
113 let mut media = AudioSource {
114 local_name: None,
115 url_backup: Some("https://tatoeba.org/en/audio/download/269099".into()),
116 };
117 let path = media.get_path().unwrap();
118 assert_eq!(media.local_name.unwrap(), "269099");
119 std::fs::remove_file(path).unwrap();
120 }
121}
122*/