Implement album index and image resize.

This commit is contained in:
2020-02-15 08:12:13 -08:00
parent 8abeef8859
commit 4bb2354fdf
5 changed files with 244 additions and 6 deletions

View File

@@ -2,6 +2,7 @@ use std::error::Error;
use std::net::SocketAddr;
use std::path::PathBuf;
use log::info;
use log::warn;
use prometheus::Encoder;
use serde::Deserialize;
@@ -34,6 +35,14 @@ fn index() -> Result<impl warp::Reply, warp::Rejection> {
Ok("Hello world")
}
fn albums(lib: Library) -> Result<impl warp::Reply, warp::Rejection> {
let albums = lib.albums().map_err(|e| {
warn!("Couldn't find albums: {}", e);
warp::reject::not_found()
})?;
Ok(warp::reply::json(&albums))
}
fn album(lib: Library, id: String) -> Result<impl warp::Reply, warp::Rejection> {
let album = lib.album(&id).map_err(|e| {
warn!("Couldn't find album {}: {}", id, e);
@@ -44,17 +53,53 @@ fn album(lib: Library, id: String) -> Result<impl warp::Reply, warp::Rejection>
#[derive(Debug, Deserialize)]
struct ImageParams {
w: Option<usize>,
h: Option<usize>,
w: Option<u32>,
h: Option<u32>,
c: Option<bool>,
}
fn image(
lib: Library,
image_id: String,
media_items_id: String,
params: ImageParams,
) -> Result<impl warp::Reply, warp::Rejection> {
Ok(format!("Hello world: {} {:?}", image_id, params))
info!("image_id {} params {:?}", media_items_id, params);
match lib.original(&media_items_id) {
None => {
warn!("Couldn't find original {}", &media_items_id);
Err(warp::reject::not_found())
}
Some(path) => {
let orig_img = image::io::Reader::open(&path)
.map_err(|e| {
warn!("Couldn't open {}: {}", path.to_string_lossy(), e);
warp::reject::not_found()
})?
.with_guessed_format()
.map_err(|e| {
warn!("Couldn't guess format {}: {}", path.to_string_lossy(), e);
warp::reject::not_found()
})?
.decode()
.map_err(|e| {
warn!("Couldn't decode {}: {}", path.to_string_lossy(), e);
warp::reject::not_found()
})?;
let img = orig_img.resize(
params.w.unwrap_or(0),
params.h.unwrap_or(0),
image::imageops::FilterType::CatmullRom,
);
let mut buf = Vec::new();
img.write_to(&mut buf, image::ImageFormat::Jpeg)
.map_err(|e| {
warn!("Couldn't write_to {}: {}", path.to_string_lossy(), e);
warp::reject::not_found()
})?;
Ok(buf)
}
}
}
pub fn run(addr: SocketAddr, root: PathBuf) -> Result<(), Box<dyn Error>> {
@@ -62,18 +107,20 @@ pub fn run(addr: SocketAddr, root: PathBuf) -> Result<(), Box<dyn Error>> {
let lib = warp::any().map(move || lib.clone());
let index = warp::path::end().and_then(index);
// TODO(wathiede): implement album index
let albums = warp::path("albums").and(lib.clone()).and_then(albums);
let album = warp::path("album")
.and(lib.clone())
.and(warp::path::param())
.and_then(album);
let image = warp::path("image")
.and(lib.clone())
.and(warp::path::param())
.and(warp::query::<ImageParams>())
.and_then(image);
let api = album.or(image);
let api = albums.or(album).or(image);
let api = warp::path("api").and(api);
// Fallback, always keep this last.