* Opting to return a URI pathname to thumbnails now

Because of this the backend now only has to serve data that browsers req
Also helps out api clients since responses are generally smaller
And helps out servers since responses are faster
This commit is contained in:
shockrah 2021-10-12 11:18:32 -07:00
parent cf55dcfde0
commit d5b8fba7f6

View File

@ -1,4 +1,3 @@
use base64;
use serde::Serialize;
use std::fs::DirEntry;
use std::{io, env};
@ -7,38 +6,20 @@ use rocket::serde::json::Json;
#[derive(Serialize)]
pub struct Category {
name: String,
thumbnail: Option<String>
// NOTE: this is simply a URI pathname
// EXAMPLE: /thumbnail/<category>/.thumbnail.png
thumbnail: String
}
#[derive(Serialize)]
struct List {
categories: Vec<Category>
}
fn get_category_metadata(entry: DirEntry) -> io::Result<(String, Option<String>)> {
use std::io::Read;
let name = entry.file_name().to_string_lossy().to_string();
let mut p = entry.path(); p.push(".thumbnail.jpg");
if p.is_file() {
let mut buf = Vec::new();
let mut file = std::fs::File::open(p)?;
file.read_to_end(&mut buf)?;
let nail = base64::encode(buf).to_string();
return match nail.len() {
0 => Ok((name, None)),
_ => Ok((name, Some(nail)))
};
}
return Ok((String::new(), None));
}
fn get_category_dirs(path: &str) -> std::io::Result<Vec<DirEntry>> {
let path = std::path::Path::new(path);
if !path.is_dir() {
panic!("<{:?}> is not a valid directory", path);
let e = io::Error::new(io::ErrorKind::NotFound, "Unable to open");
return Err(e);
}
let mut ret: Vec<DirEntry> = Vec::new();
@ -58,24 +39,17 @@ pub fn list() -> Json<Vec<Category>> {
Ok(val) => val,
Err(_) => "/media/clips/".to_string()
};
match get_category_dirs(&dir) {
Ok(entries) => {
let mut cats: Vec<Category> = Vec::new();
for ent in entries {
match get_category_metadata(ent) {
Ok((name, thumbnail)) => {
cats.push(Category {name, thumbnail});
},
_ => continue
}
}
return Json(cats);
},
Err(e) => {
eprintln!("ERROR: {}", e);
let mut cats: Vec<Category> = Vec::new();
if let Ok(dirs) = get_category_dirs(&dir) {
// Let's just assume that each item in this directory is a folder
// That way we can do this blindly without 9999 allocs
for d in dirs {
let name = d.file_name().to_string_lossy().to_string();
let thumbnail = format!("/thumbnail/{}/category-thumbnail.jpg", name);
cats.push(Category {name, thumbnail});
}
}
Json(Vec::new())
Json(cats)
}