Skip to content

Commit

Permalink
Guess image mime type from file extension (fixes #5196) (#5212)
Browse files Browse the repository at this point in the history
* Guess image mime type from file extension (fixes #5196)

* Mime check fixes. (#5213)

* Mime check fixes.

* Adding back comment.

---------

Co-authored-by: Dessalines <[email protected]>
  • Loading branch information
Nutomic and dessalines authored Nov 19, 2024
1 parent 417e18e commit 63ea99d
Show file tree
Hide file tree
Showing 3 changed files with 33 additions and 7 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
20 changes: 14 additions & 6 deletions crates/api_common/src/request.rs
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,6 @@ use lemmy_utils::{
REQWEST_TIMEOUT,
VERSION,
};
use mime::Mime;
use reqwest::{
header::{CONTENT_TYPE, RANGE},
Client,
Expand Down Expand Up @@ -64,11 +63,20 @@ pub async fn fetch_link_metadata(url: &Url, context: &LemmyContext) -> LemmyResu
.await?
.error_for_status()?;

let 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 content_type = mime_guess::from_path(url.path())
.first()
// If you can guess that its an image type, then return that first.
.filter(|guess| guess.type_() == mime::IMAGE)
// Otherwise, get the content type from the headers
.or(
response
.headers()
.get(CONTENT_TYPE)
.and_then(|h| h.to_str().ok())
.and_then(|h| h.parse().ok()),
);

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

0 comments on commit 63ea99d

Please sign in to comment.