Skip to content

Commit

Permalink
Guess image mime type from file extension (fixes #5196)
Browse files Browse the repository at this point in the history
  • Loading branch information
Nutomic committed Nov 19, 2024
1 parent 417e18e commit 73f516d
Show file tree
Hide file tree
Showing 3 changed files with 29 additions and 2 deletions.
19 changes: 18 additions & 1 deletion Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions crates/api_common/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,7 @@ actix-web = { workspace = true, optional = true }
enum-map = { workspace = true }
urlencoding = { workspace = true }
mime = { version = "0.3.17", optional = true }
mime_guess = "2.0.5"
webpage = { version = "2.0", default-features = false, features = [
"serde",
], optional = true }
Expand Down
11 changes: 10 additions & 1 deletion crates/api_common/src/request.rs
Original file line number Diff line number Diff line change
Expand Up @@ -64,12 +64,21 @@ pub async fn fetch_link_metadata(url: &Url, context: &LemmyContext) -> LemmyResu
.await?
.error_for_status()?;

let content_type: Option<Mime> = response
let mut content_type: Option<Mime> = response
.headers()
.get(CONTENT_TYPE)
.and_then(|h| h.to_str().ok())
.and_then(|h| h.parse().ok());

// In some cases servers send a wrong mime type for images, which prevents thumbnail
// generation. To avoid this we also try to guess the mime type from file extension.
let guess = mime_guess::from_path(url.path());
if let Some(guess) = guess.first() {
if guess.type_() == mime::IMAGE {
content_type = Some(guess);
}
}

let opengraph_data = {
// if the content type is not text/html, we don't need to parse it
let is_html = content_type
Expand Down

0 comments on commit 73f516d

Please sign in to comment.