fix(media): return an error when content is failed to be parsed as an image

This commit is contained in:
Matthias Ahouansou 2024-06-05 13:34:35 +01:00
parent c45e52f45a
commit ad6fc93249
No known key found for this signature in database

View file

@ -2,6 +2,7 @@ mod data;
use std::io::Cursor;
pub use data::Data;
use ruma::api::client::error::ErrorKind;
use crate::{services, Result};
use image::imageops::FilterType;
@ -117,6 +118,7 @@ impl Service {
.thumbnail_properties(width, height)
.unwrap_or((0, 0, false)); // 0, 0 because that's the original file
Ok(
if let Ok((content_disposition, content_type, key)) =
self.db.search_file_metadata(mxc.clone(), width, height)
{
@ -125,11 +127,11 @@ impl Service {
let mut file = Vec::new();
File::open(path).await?.read_to_end(&mut file).await?;
Ok(Some(FileMeta {
Some(FileMeta {
content_disposition,
content_type,
file: file.to_vec(),
}))
})
} else if let Ok((content_disposition, content_type, key)) =
self.db.search_file_metadata(mxc.clone(), 0, 0)
{
@ -142,13 +144,12 @@ impl Service {
let original_width = image.width();
let original_height = image.height();
if width > original_width || height > original_height {
return Ok(Some(FileMeta {
Some(FileMeta {
content_disposition,
content_type,
file: file.to_vec(),
}));
}
})
} else {
let thumbnail = if crop {
image.resize_to_fill(width, height, FilterType::CatmullRom)
} else {
@ -170,7 +171,8 @@ impl Service {
(width, intermediate as u32)
} else {
(
(u64::from(width) * u64::from(::std::u32::MAX) / intermediate)
(u64::from(width) * u64::from(::std::u32::MAX)
/ intermediate)
as u32,
::std::u32::MAX,
)
@ -180,7 +182,8 @@ impl Service {
} else {
(
::std::u32::MAX,
(u64::from(height) * u64::from(::std::u32::MAX) / intermediate)
(u64::from(height) * u64::from(::std::u32::MAX)
/ intermediate)
as u32,
)
}
@ -208,21 +211,22 @@ impl Service {
let mut f = File::create(path).await?;
f.write_all(&thumbnail_bytes).await?;
Ok(Some(FileMeta {
Some(FileMeta {
content_disposition,
content_type,
file: thumbnail_bytes.to_vec(),
}))
} else {
// Couldn't parse file to generate thumbnail, send original
Ok(Some(FileMeta {
content_disposition,
content_type,
file: file.to_vec(),
}))
})
}
} else {
Ok(None)
}
// Couldn't parse file to generate thumbnail, likely not an image
return Err(crate::Error::BadRequest(
ErrorKind::Unknown,
"Unable to generate thumbnail for the requested content",
));
}
} else {
None
},
)
}
}