Skip to content

Commit 285a1c4

Browse files
refactor image caching code
1 parent 64f4bef commit 285a1c4

File tree

1 file changed

+13
-28
lines changed

1 file changed

+13
-28
lines changed

src/core/caching.rs

+13-28
Original file line numberDiff line numberDiff line change
@@ -93,8 +93,6 @@ impl Cacher {
9393

9494
/// Loads the image from the provided url
9595
pub async fn load_image(image_url: String) -> Option<Vec<u8>> {
96-
let mut image_path = CACHER.get_cache_folder_path(CacheFolderType::Images);
97-
9896
// Hashing the image url as a file name as the forward slashes in web urls
9997
// mimic paths
10098
use sha2::{Digest, Sha256};
@@ -103,36 +101,23 @@ pub async fn load_image(image_url: String) -> Option<Vec<u8>> {
103101
hasher.update(&image_url);
104102
let image_hash = format!("{:x}", hasher.finalize());
105103

104+
let mut image_path = CACHER.get_cache_folder_path(CacheFolderType::Images);
106105
image_path.push(&image_hash);
107106

108107
match fs::read(&image_path).await {
109108
Ok(image_bytes) => return Some(image_bytes),
110109
Err(err) => {
111-
let images_directory = CACHER.get_cache_folder_path(CacheFolderType::Images);
112-
if !images_directory.exists() {
113-
info!("creating images cache directory as none exists");
114-
fs::DirBuilder::new()
115-
.recursive(true)
116-
.create(images_directory)
117-
.await
118-
.unwrap();
119-
};
120-
info!(
121-
"falling back online for image with link {}: {}",
122-
image_url, err
123-
);
124-
return if let Some(image_bytes) = api::lload_image(image_url).await {
125-
let mut image_file = fs::OpenOptions::new()
126-
.create(true)
127-
.write(true)
128-
.open(image_path)
129-
.await
130-
.unwrap();
131-
image_file.write(&image_bytes).await.unwrap();
132-
Some(image_bytes)
110+
if err.kind() == ErrorKind::NotFound {
111+
info!("falling back online for image with link {}", image_url);
112+
return if let Some(image_bytes) = api::lload_image(image_url).await {
113+
write_cache(&image_bytes, &image_path).await;
114+
Some(image_bytes)
115+
} else {
116+
None
117+
};
133118
} else {
134-
None
135-
};
119+
return None;
120+
}
136121
}
137122
};
138123
}
@@ -141,9 +126,9 @@ pub async fn read_cache(cache_filepath: impl AsRef<path::Path>) -> io::Result<St
141126
fs::read_to_string(cache_filepath).await
142127
}
143128

144-
pub async fn write_cache(cache_data: &str, cache_filepath: &path::Path) {
129+
pub async fn write_cache(cache_data: impl AsRef<[u8]>, cache_filepath: &path::Path) {
145130
loop {
146-
if let Err(err) = fs::write(cache_filepath, cache_data).await {
131+
if let Err(err) = fs::write(cache_filepath, &cache_data).await {
147132
if err.kind() == ErrorKind::NotFound {
148133
let mut cache_folder = path::PathBuf::from(cache_filepath);
149134
cache_folder.pop();

0 commit comments

Comments
 (0)