@@ -93,8 +93,6 @@ impl Cacher {
93
93
94
94
/// Loads the image from the provided url
95
95
pub async fn load_image ( image_url : String ) -> Option < Vec < u8 > > {
96
- let mut image_path = CACHER . get_cache_folder_path ( CacheFolderType :: Images ) ;
97
-
98
96
// Hashing the image url as a file name as the forward slashes in web urls
99
97
// mimic paths
100
98
use sha2:: { Digest , Sha256 } ;
@@ -103,36 +101,23 @@ pub async fn load_image(image_url: String) -> Option<Vec<u8>> {
103
101
hasher. update ( & image_url) ;
104
102
let image_hash = format ! ( "{:x}" , hasher. finalize( ) ) ;
105
103
104
+ let mut image_path = CACHER . get_cache_folder_path ( CacheFolderType :: Images ) ;
106
105
image_path. push ( & image_hash) ;
107
106
108
107
match fs:: read ( & image_path) . await {
109
108
Ok ( image_bytes) => return Some ( image_bytes) ,
110
109
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
+ } ;
133
118
} else {
134
- None
135
- } ;
119
+ return None ;
120
+ }
136
121
}
137
122
} ;
138
123
}
@@ -141,9 +126,9 @@ pub async fn read_cache(cache_filepath: impl AsRef<path::Path>) -> io::Result<St
141
126
fs:: read_to_string ( cache_filepath) . await
142
127
}
143
128
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 ) {
145
130
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 {
147
132
if err. kind ( ) == ErrorKind :: NotFound {
148
133
let mut cache_folder = path:: PathBuf :: from ( cache_filepath) ;
149
134
cache_folder. pop ( ) ;
0 commit comments