stream covers (chunked encoding)

This commit is contained in:
Sebastian Hugentobler 2024-05-11 09:06:08 +02:00
parent 8f698c0e7d
commit 13aae44163
Signed by: shu
GPG Key ID: BB32CF3CA052C2F0

View File

@ -1,31 +1,32 @@
//! Handle requests for cover images.
use std::{fs::File, io::Read, sync::Arc};
use std::sync::Arc;
use poem::{
error::NotFoundError,
handler,
web::{headers::ContentType, Data, Path, WithContentType},
IntoResponse,
web::{headers::ContentType, Data, Path},
Body, IntoResponse, Response,
};
use tokio::fs::File;
use tokio_util::io::ReaderStream;
use crate::{app_state::AppState, handlers::error::HandlerError};
/// Handle a request for the cover image of book with id `id`.
#[handler]
pub async fn handler(
id: Path<u64>,
state: Data<&Arc<AppState>>,
) -> Result<WithContentType<Vec<u8>>, poem::Error> {
pub async fn handler(id: Path<u64>, state: Data<&Arc<AppState>>) -> Result<Response, poem::Error> {
let book = state
.calibre
.scalar_book(*id)
.map_err(HandlerError::DataError)?;
let cover_path = state.config.library_path.join(book.path).join("cover.jpg");
let mut cover = File::open(cover_path).map_err(|_| NotFoundError)?;
let mut cover = File::open(cover_path).await.map_err(|_| NotFoundError)?;
let stream = ReaderStream::new(cover);
let body = Body::from_bytes_stream(stream);
let mut data = Vec::new();
cover.read_to_end(&mut data).map_err(|_| NotFoundError)?;
Ok(data.with_content_type(ContentType::jpeg().to_string()))
Ok(body
.with_content_type(ContentType::jpeg().to_string())
.with_header("Content-Disposition", "filename=\"cover.jpg\"")
.into_response())
}