Skip to content

Commit 5ba3abe

Browse files
committed
tanoshi: image: better content_type
Signed-off-by: Luis Garcia <git@luigi311.com>
1 parent abb9945 commit 5ba3abe

File tree

1 file changed

+22
-6
lines changed
  • crates/tanoshi/src/domain/services

1 file changed

+22
-6
lines changed

crates/tanoshi/src/domain/services/image.rs

Lines changed: 22 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -64,18 +64,18 @@ where
6464
image
6565
}
6666
ImageUri::ExtensionRemote { source_id, url } => {
67+
// determine content type from the URL
68+
let content_type = Self::extract_image_type_from_url(&url);
69+
6770
let bytes = self
6871
.ext
69-
.get_image_bytes(source_id, url)
72+
.get_image_bytes(source_id, url.clone())
7073
.await
7174
.map_err(|e| ImageError::Other(anyhow::anyhow!("{e}")))?;
7275

73-
// You *must* decide a content-type. Either:
74-
// 1) sniff via header in extension API (best), or
75-
// 2) sniff by magic bytes, or
76-
// 3) default "image/jpeg" (least safe)
76+
debug!("fetched image from extension source_id={source_id}, url={}, content_type={content_type}, size={} bytes", &url, bytes.len());
7777
let image = Image {
78-
content_type: "image/jpeg".to_string(), // TODO: improve
78+
content_type,
7979
data: bytes,
8080
};
8181

@@ -112,4 +112,20 @@ where
112112

113113
Ok(image_uri.into_encrypted(secret)?)
114114
}
115+
116+
fn extract_image_type_from_url(url: &str) -> String {
117+
let extension = url.split('.').last();
118+
119+
match extension {
120+
Some(ext) => match ext.to_lowercase().as_str() {
121+
"jpg" | "jpeg" => "image/jpeg".to_string(),
122+
"png" => "image/png".to_string(),
123+
"gif" => "image/gif".to_string(),
124+
"bmp" => "image/bmp".to_string(),
125+
"webp" => "image/webp".to_string(),
126+
_ => "application/octet-stream".to_string(),
127+
},
128+
None => "application/octet-stream".to_string(),
129+
}
130+
}
115131
}

0 commit comments

Comments
 (0)