stream covers (chunked encoding)
This commit is contained in:
parent
8f698c0e7d
commit
13aae44163
@ -1,31 +1,32 @@
|
|||||||
//! Handle requests for cover images.
|
//! Handle requests for cover images.
|
||||||
|
|
||||||
use std::{fs::File, io::Read, sync::Arc};
|
use std::sync::Arc;
|
||||||
|
|
||||||
use poem::{
|
use poem::{
|
||||||
error::NotFoundError,
|
error::NotFoundError,
|
||||||
handler,
|
handler,
|
||||||
web::{headers::ContentType, Data, Path, WithContentType},
|
web::{headers::ContentType, Data, Path},
|
||||||
IntoResponse,
|
Body, IntoResponse, Response,
|
||||||
};
|
};
|
||||||
|
use tokio::fs::File;
|
||||||
|
use tokio_util::io::ReaderStream;
|
||||||
|
|
||||||
use crate::{app_state::AppState, handlers::error::HandlerError};
|
use crate::{app_state::AppState, handlers::error::HandlerError};
|
||||||
|
|
||||||
/// Handle a request for the cover image of book with id `id`.
|
/// Handle a request for the cover image of book with id `id`.
|
||||||
#[handler]
|
#[handler]
|
||||||
pub async fn handler(
|
pub async fn handler(id: Path<u64>, state: Data<&Arc<AppState>>) -> Result<Response, poem::Error> {
|
||||||
id: Path<u64>,
|
|
||||||
state: Data<&Arc<AppState>>,
|
|
||||||
) -> Result<WithContentType<Vec<u8>>, poem::Error> {
|
|
||||||
let book = state
|
let book = state
|
||||||
.calibre
|
.calibre
|
||||||
.scalar_book(*id)
|
.scalar_book(*id)
|
||||||
.map_err(HandlerError::DataError)?;
|
.map_err(HandlerError::DataError)?;
|
||||||
let cover_path = state.config.library_path.join(book.path).join("cover.jpg");
|
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();
|
Ok(body
|
||||||
cover.read_to_end(&mut data).map_err(|_| NotFoundError)?;
|
.with_content_type(ContentType::jpeg().to_string())
|
||||||
|
.with_header("Content-Disposition", "filename=\"cover.jpg\"")
|
||||||
Ok(data.with_content_type(ContentType::jpeg().to_string()))
|
.into_response())
|
||||||
}
|
}
|
||||||
|
Loading…
Reference in New Issue
Block a user