basic recents view

This commit is contained in:
Sebastian Hugentobler 2024-05-02 18:10:29 +02:00
parent 65e17fc55b
commit 687c33829f
Signed by: shu
GPG Key ID: BB32CF3CA052C2F0
20 changed files with 2156 additions and 20 deletions

1800
Cargo.lock generated

File diff suppressed because it is too large Load Diff

View File

@ -1,5 +1,9 @@
[workspace] [workspace]
resolver = "2" resolver = "2"
members = [ members = [
"calibre-db", "calibre-db", "cops-web",
] ]
[workspace.dependencies]
serde = "1.0.200"
thiserror = "1.0.59"

View File

@ -4,5 +4,8 @@ version = "0.1.0"
edition = "2021" edition = "2021"
[dependencies] [dependencies]
r2d2 = "0.8.10"
r2d2_sqlite = "0.24.0"
rusqlite = { version = "0.31.0", features = ["bundled"] } rusqlite = { version = "0.31.0", features = ["bundled"] }
thiserror = "1.0.59" serde = { workspace = true }
thiserror = { workspace = true }

View File

@ -1,15 +1,21 @@
use rusqlite::Connection; use std::path::Path;
use r2d2::Pool;
use r2d2_sqlite::SqliteConnectionManager;
use crate::data::{author::Author, book::Book, error::DataStoreError, pagination::SortOrder}; use crate::data::{author::Author, book::Book, error::DataStoreError, pagination::SortOrder};
#[derive(Debug, Clone)]
pub struct Calibre { pub struct Calibre {
conn: Connection, pool: Pool<SqliteConnectionManager>,
} }
impl Calibre { impl Calibre {
pub fn load(url: &str) -> Result<Self, DataStoreError> { pub fn load(path: &Path) -> Result<Self, DataStoreError> {
let conn = Connection::open(url)?; let manager = SqliteConnectionManager::file(path);
Ok(Self { conn }) let pool = r2d2::Pool::new(manager)?;
Ok(Self { pool })
} }
pub fn books( pub fn books(
@ -18,7 +24,8 @@ impl Calibre {
cursor: Option<&str>, cursor: Option<&str>,
sort_order: SortOrder, sort_order: SortOrder,
) -> Result<Vec<Book>, DataStoreError> { ) -> Result<Vec<Book>, DataStoreError> {
Book::books(&self.conn, limit, cursor, sort_order) let conn = self.pool.get()?;
Book::books(&conn, limit, cursor, sort_order)
} }
pub fn authors( pub fn authors(
@ -27,7 +34,8 @@ impl Calibre {
cursor: Option<&str>, cursor: Option<&str>,
sort_order: SortOrder, sort_order: SortOrder,
) -> Result<Vec<Author>, DataStoreError> { ) -> Result<Vec<Author>, DataStoreError> {
Author::authors(&self.conn, limit, cursor, sort_order) let conn = self.pool.get()?;
Author::authors(&conn, limit, cursor, sort_order)
} }
pub fn author_books( pub fn author_books(
@ -37,7 +45,18 @@ impl Calibre {
cursor: Option<&str>, cursor: Option<&str>,
sort_order: SortOrder, sort_order: SortOrder,
) -> Result<Vec<Book>, DataStoreError> { ) -> Result<Vec<Book>, DataStoreError> {
Book::author_books(&self.conn, author_id, limit, cursor, sort_order) let conn = self.pool.get()?;
Book::author_books(&conn, author_id, limit, cursor, sort_order)
}
pub fn recent_books(&self, limit: u64) -> Result<Vec<Book>, DataStoreError> {
let conn = self.pool.get()?;
Book::recents(&conn, limit)
}
pub fn scalar_book(&self, id: u64) -> Result<Book, DataStoreError> {
let conn = self.pool.get()?;
Book::scalar_book(&conn, id)
} }
} }
@ -45,30 +64,34 @@ impl Calibre {
mod tests { mod tests {
use super::*; use super::*;
fn init_calibre() -> Calibre {
Calibre::load(Path::new("./testdata/metadata.db")).unwrap()
}
#[test] #[test]
fn books() { fn books() {
let c = Calibre::load("./testdata/metadata.db").unwrap(); let c = init_calibre();
let books = c.books(10, None, SortOrder::ASC).unwrap(); let books = c.books(10, None, SortOrder::ASC).unwrap();
assert_eq!(books.len(), 4); assert_eq!(books.len(), 4);
} }
#[test] #[test]
fn authors() { fn authors() {
let c = Calibre::load("./testdata/metadata.db").unwrap(); let c = init_calibre();
let authors = c.authors(10, None, SortOrder::ASC).unwrap(); let authors = c.authors(10, None, SortOrder::ASC).unwrap();
assert_eq!(authors.len(), 3); assert_eq!(authors.len(), 3);
} }
#[test] #[test]
fn author_books() { fn author_books() {
let c = Calibre::load("./testdata/metadata.db").unwrap(); let c = init_calibre();
let books = c.author_books(1, 10, None, SortOrder::ASC).unwrap(); let books = c.author_books(1, 10, None, SortOrder::ASC).unwrap();
assert_eq!(books.len(), 2); assert_eq!(books.len(), 2);
} }
#[test] #[test]
fn pagination() { fn pagination() {
let c = Calibre::load("./testdata/metadata.db").unwrap(); let c = init_calibre();
let authors = c.authors(1, None, SortOrder::ASC).unwrap(); let authors = c.authors(1, None, SortOrder::ASC).unwrap();
assert_eq!(authors.len(), 1); assert_eq!(authors.len(), 1);
assert_eq!(authors[0].name, "Kevin R. Grazier"); assert_eq!(authors[0].name, "Kevin R. Grazier");

View File

@ -1,11 +1,12 @@
use rusqlite::{Connection, Row}; use rusqlite::{Connection, Row};
use serde::Serialize;
use super::{ use super::{
error::DataStoreError, error::DataStoreError,
pagination::{Pagination, SortOrder}, pagination::{Pagination, SortOrder},
}; };
#[derive(Debug)] #[derive(Debug, Serialize)]
pub struct Author { pub struct Author {
pub id: i32, pub id: i32,
pub name: String, pub name: String,

View File

@ -1,15 +1,17 @@
use rusqlite::{Connection, Row}; use rusqlite::{named_params, Connection, Row};
use serde::Serialize;
use super::{ use super::{
error::DataStoreError, error::DataStoreError,
pagination::{Pagination, SortOrder}, pagination::{Pagination, SortOrder},
}; };
#[derive(Debug)] #[derive(Debug, Serialize)]
pub struct Book { pub struct Book {
pub id: i32, pub id: i32,
pub title: String, pub title: String,
pub sort: String, pub sort: String,
pub path: String,
} }
impl Book { impl Book {
@ -18,6 +20,7 @@ impl Book {
id: row.get(0)?, id: row.get(0)?,
title: row.get(1)?, title: row.get(1)?,
sort: row.get(2)?, sort: row.get(2)?,
path: row.get(3)?,
}) })
} }
@ -30,7 +33,7 @@ impl Book {
let pagination = Pagination::new("sort", cursor, limit, sort_order); let pagination = Pagination::new("sort", cursor, limit, sort_order);
pagination.paginate( pagination.paginate(
conn, conn,
"SELECT id, title, sort FROM books", "SELECT id, title, sort, path FROM books",
&[], &[],
Self::from_row, Self::from_row,
) )
@ -46,11 +49,26 @@ impl Book {
let pagination = Pagination::new("books.sort", cursor, limit, sort_order); let pagination = Pagination::new("books.sort", cursor, limit, sort_order);
pagination.paginate( pagination.paginate(
conn, conn,
"SELECT books.id, books.title, books.sort FROM books \ "SELECT books.id, books.title, books.sort, books.path FROM books \
INNER JOIN books_authors_link ON books.id = books_authors_link.book \ INNER JOIN books_authors_link ON books.id = books_authors_link.book \
WHERE books_authors_link.author = (:author_id) AND", WHERE books_authors_link.author = (:author_id) AND",
&[(":author_id", &author_id)], &[(":author_id", &author_id)],
Self::from_row, Self::from_row,
) )
} }
pub fn recents(conn: &Connection, limit: u64) -> Result<Vec<Book>, DataStoreError> {
let mut stmt = conn.prepare(
"SELECT id, title, sort, path FROM books ORDER BY timestamp DESC LIMIT (:limit)",
)?;
let params = named_params! { ":limit": limit };
let iter = stmt.query_map(params, Self::from_row)?;
Ok(iter.filter_map(Result::ok).collect())
}
pub fn scalar_book(conn: &Connection, id: u64) -> Result<Book, DataStoreError> {
let mut stmt = conn.prepare("SELECT id, title, sort, path FROM books WHERE id = (:id)")?;
let params = named_params! { ":id": id };
Ok(stmt.query_row(params, Self::from_row)?)
}
} }

View File

@ -4,4 +4,6 @@ use thiserror::Error;
pub enum DataStoreError { pub enum DataStoreError {
#[error("sqlite error")] #[error("sqlite error")]
SqliteError(#[from] rusqlite::Error), SqliteError(#[from] rusqlite::Error),
#[error("connection error")]
ConnectionError(#[from] r2d2::Error),
} }

15
cops-web/Cargo.toml Normal file
View File

@ -0,0 +1,15 @@
[package]
name = "cops-web"
version = "0.1.0"
edition = "2021"
[dependencies]
calibre-db = { path = "../calibre-db/" }
clap = { version = "4.5.4", features = ["derive"] }
once_cell = "1.19.0"
poem = { version = "3.0.0", features = ["embed", "static-files"] }
rust-embed = "8.3.0"
tera = "1.19.1"
thiserror = { workspace = true }
tokio = { version = "1.37.0", features = ["rt-multi-thread", "macros"] }
tracing-subscriber = "0.3.18"

View File

@ -0,0 +1,8 @@
use calibre_db::calibre::Calibre;
use crate::config::Config;
pub struct AppState {
pub calibre: Calibre,
pub config: Config,
}

View File

@ -0,0 +1,44 @@
use poem::{
http::StatusCode,
web::{
headers,
headers::{authorization::Basic, HeaderMapExt},
},
Endpoint, Error, Middleware, Request, Result,
};
pub struct BasicAuth {
pub username: String,
pub password: String,
}
impl<E: Endpoint> Middleware<E> for BasicAuth {
type Output = BasicAuthEndpoint<E>;
fn transform(&self, ep: E) -> Self::Output {
BasicAuthEndpoint {
ep,
username: self.username.clone(),
password: self.password.clone(),
}
}
}
pub struct BasicAuthEndpoint<E> {
ep: E,
username: String,
password: String,
}
impl<E: Endpoint> Endpoint for BasicAuthEndpoint<E> {
type Output = E::Output;
async fn call(&self, req: Request) -> Result<Self::Output> {
if let Some(auth) = req.headers().typed_get::<headers::Authorization<Basic>>() {
if auth.0.username() == self.username && auth.0.password() == self.password {
return self.ep.call(req).await;
}
}
Err(Error::from_status(StatusCode::UNAUTHORIZED))
}
}

10
cops-web/src/cli.rs Normal file
View File

@ -0,0 +1,10 @@
use clap::Parser;
/// Simple odps server for calibre
#[derive(Parser)]
#[command(version, about, long_about = None)]
pub struct Cli {
/// Calibre library path
#[arg(last = true)]
pub library_path: String,
}

48
cops-web/src/config.rs Normal file
View File

@ -0,0 +1,48 @@
use std::path::{Path, PathBuf};
use thiserror::Error;
use crate::cli::Cli;
#[derive(Error, Debug)]
pub enum ConfigError {
#[error("no folder at {0}")]
LibraryPathNotFound(String),
#[error("no metadata.db in {0}")]
MetadataNotFound(String),
}
pub struct Config {
pub library_path: PathBuf,
pub metadata_path: PathBuf,
}
impl Config {
pub fn load(args: &Cli) -> Result<Self, ConfigError> {
let library_path = Path::new(&args.library_path).to_path_buf();
if !library_path.exists() {
let library_path = library_path
.as_os_str()
.to_str()
.unwrap_or("<failed to parse path>")
.to_string();
return Err(ConfigError::LibraryPathNotFound(library_path));
}
let metadata_path = library_path.join("metadata.db");
if !metadata_path.exists() {
let metadata_path = metadata_path
.as_os_str()
.to_str()
.unwrap_or("<failed to parse path>")
.to_string();
return Err(ConfigError::MetadataNotFound(metadata_path));
}
Ok(Self {
library_path,
metadata_path,
})
}
}

View File

@ -0,0 +1,23 @@
use std::{fs::File, io::Read, sync::Arc};
use poem::{
handler,
web::{headers::ContentType, Data, Path, WithContentType},
IntoResponse,
};
use crate::app_state::AppState;
#[handler]
pub async fn handler(
id: Path<u64>,
state: Data<&Arc<AppState>>,
) -> Result<WithContentType<Vec<u8>>, poem::Error> {
let book = state.calibre.scalar_book(*id).unwrap();
let cover_path = state.config.library_path.join(book.path).join("cover.jpg");
let mut cover = File::open(cover_path).unwrap();
let mut data = Vec::new();
cover.read_to_end(&mut data).unwrap();
Ok(data.with_content_type(ContentType::jpeg().to_string()))
}

View File

@ -0,0 +1,22 @@
use std::sync::Arc;
use poem::{
error::InternalServerError,
handler,
web::{Data, Html},
};
use tera::Context;
use crate::{app_state::AppState, templates::TEMPLATES};
#[handler]
pub async fn handler(state: Data<&Arc<AppState>>) -> Result<Html<String>, poem::Error> {
let recent_books = state.calibre.recent_books(50).unwrap();
let mut context = Context::new();
context.insert("books", &recent_books);
TEMPLATES
.render("recents", &context)
.map_err(InternalServerError)
.map(Html)
}

50
cops-web/src/main.rs Normal file
View File

@ -0,0 +1,50 @@
use std::sync::Arc;
use app_state::AppState;
use calibre_db::calibre::Calibre;
use clap::Parser;
use cli::Cli;
use config::Config;
use poem::{
endpoint::EmbeddedFilesEndpoint, get, listener::TcpListener, EndpointExt, Route, Server,
};
use rust_embed::RustEmbed;
mod app_state;
mod basic_auth;
mod cli;
mod config;
mod handlers {
pub mod cover;
pub mod recents;
}
mod templates;
#[derive(RustEmbed)]
#[folder = "static"]
pub struct Files;
#[tokio::main]
async fn main() -> Result<(), std::io::Error> {
if std::env::var_os("RUST_LOG").is_none() {
std::env::set_var("RUST_LOG", "debug");
}
tracing_subscriber::fmt::init();
let args = Cli::parse();
let config = Config::load(&args).expect("failed to load configuration");
let calibre = Calibre::load(&config.metadata_path).expect("failed to load calibre database");
let app_state = Arc::new(AppState { calibre, config });
let app = Route::new()
.at("/", get(handlers::recents::handler))
.at("/cover/:id", get(handlers::cover::handler))
.nest("/static", EmbeddedFilesEndpoint::<Files>::new())
.data(app_state);
Server::new(TcpListener::bind("[::]:3000"))
.name("cops-web")
.run(app)
.await
}

13
cops-web/src/templates.rs Normal file
View File

@ -0,0 +1,13 @@
use once_cell::sync::Lazy;
use tera::Tera;
pub static TEMPLATES: Lazy<Tera> = Lazy::new(|| {
let mut tera = Tera::default();
tera.add_raw_templates(vec![
("base", include_str!("../templates/base.html")),
("recents", include_str!("../templates/recents.html")),
])
.expect("failed to parse tera templates");
tera
});

4
cops-web/static/pico.min.css vendored Normal file

File diff suppressed because one or more lines are too long

21
cops-web/static/style.css Normal file
View File

@ -0,0 +1,21 @@
.book-card header {
white-space: nowrap;
overflow: scroll;
text-overflow: ellipsis;
}
.cover {
width: 100%;
object-fit: contain;
height: 25rem;
}
.grid-container {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(18rem, 1fr));
gap: 10px;
}
.grid-item {
text-align: center;
}

View File

@ -0,0 +1,16 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="color-scheme" content="light dark" />
<link rel="stylesheet" href="/static/pico.min.css" />
<link rel="stylesheet" href="/static/style.css" />
<title>Hello world!</title>
</head>
<body>
<main class="container">
{% block content %}{% endblock content %}
</main>
</body>
</html>

View File

@ -0,0 +1,13 @@
{% extends "base" %}
{% block content %}
<h1>Recent Books</h1>
<div class="grid-container">
{% for book in books %}
<article class="book-card grid-item">
<header>{{ book.title }}</header>
<img class="cover" src="/cover/{{ book.id }}" alt="book cover">
<!-- <footer>{{ book.title }}</footer> -->
</article>
{% endfor %}
</div>
{% endblock content %}