music_player_audio/fetch/
cache.rs

1use anyhow::Error;
2use music_player_settings::get_application_directory;
3use std::{
4    fs::File,
5    io::{self, Read},
6    path::Path,
7};
8pub struct Cache {
9    cache_dir: String,
10}
11
12impl Cache {
13    pub fn new() -> Self {
14        let cache_dir = format!("{}/cache", get_application_directory());
15        Self { cache_dir }
16    }
17
18    pub fn save_file<F: Read>(&self, name: &str, contents: &mut F) -> Result<(), Error> {
19        if self.is_file_cached(name) {
20            return Ok(());
21        }
22        let mut file = File::create(format!("{}/{}", self.cache_dir, name))?;
23        io::copy(contents, &mut file)?;
24        Ok(())
25    }
26
27    pub fn is_file_cached(&self, name: &str) -> bool {
28        Path::new(&format!("{}/{}", self.cache_dir, name)).exists()
29    }
30
31    pub fn open_file(&self, name: &str) -> Result<File, Error> {
32        Ok(File::open(format!("{}/{}", self.cache_dir, name))?)
33    }
34}