From ead3672570311ab1123e31e90c6173144c0cc627 Mon Sep 17 00:00:00 2001 From: Sebastian Hugentobler Date: Mon, 6 May 2024 13:51:49 +0200 Subject: [PATCH] paginated authors --- calibre-db/src/calibre.rs | 22 ++++++++---- calibre-db/src/data/author.rs | 25 ++++++++++++-- calibre-db/src/data/pagination.rs | 12 +++++-- rusty-library/src/handlers/authors.rs | 32 ++++++++++++++--- rusty-library/src/handlers/paginated.rs | 46 +++++++++++++++++++++++++ rusty-library/src/handlers/recents.rs | 4 ++- rusty-library/src/main.rs | 7 +++- rusty-library/src/templates.rs | 1 + rusty-library/static/style.css | 15 ++++++++ rusty-library/templates/authors.html | 19 ++++++++++ rusty-library/templates/base.html | 14 ++++---- rusty-library/templates/recents.html | 1 - 12 files changed, 175 insertions(+), 23 deletions(-) create mode 100644 rusty-library/src/handlers/paginated.rs create mode 100644 rusty-library/templates/authors.html diff --git a/calibre-db/src/calibre.rs b/calibre-db/src/calibre.rs index 8356b91..93277fa 100644 --- a/calibre-db/src/calibre.rs +++ b/calibre-db/src/calibre.rs @@ -34,7 +34,7 @@ impl Calibre { &self, limit: u64, cursor: Option<&str>, - sort_order: SortOrder, + sort_order: &SortOrder, ) -> Result, DataStoreError> { let conn = self.pool.get()?; Author::multiple(&conn, limit, cursor, sort_order) @@ -80,6 +80,16 @@ impl Calibre { let conn = self.pool.get()?; Series::book_series(&conn, id) } + + pub fn has_previous_authors(&self, author_sort: &str) -> Result { + let conn = self.pool.get()?; + Author::has_previous_authors(&conn, author_sort) + } + + pub fn has_more_authors(&self, author_sort: &str) -> Result { + let conn = self.pool.get()?; + Author::has_more_authors(&conn, author_sort) + } } #[cfg(test)] @@ -100,7 +110,7 @@ mod tests { #[test] fn authors() { 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); } @@ -114,24 +124,24 @@ mod tests { #[test] fn pagination() { 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[0].name, "Kevin R. Grazier"); let authors = c - .authors(1, Some(&authors[0].sort), SortOrder::ASC) + .authors(1, Some(&authors[0].sort), &SortOrder::ASC) .unwrap(); assert_eq!(authors.len(), 1); assert_eq!(authors[0].name, "Terry Pratchett"); let authors = c - .authors(1, Some(&authors[0].sort), SortOrder::ASC) + .authors(1, Some(&authors[0].sort), &SortOrder::ASC) .unwrap(); assert_eq!(authors.len(), 1); assert_eq!(authors[0].name, "Edward Noyes Westcott"); let authors = c - .authors(1, Some(&authors[0].sort), SortOrder::DESC) + .authors(1, Some(&authors[0].sort), &SortOrder::DESC) .unwrap(); assert_eq!(authors.len(), 1); assert_eq!(authors[0].name, "Terry Pratchett"); diff --git a/calibre-db/src/data/author.rs b/calibre-db/src/data/author.rs index 6bcb988..7e09caa 100644 --- a/calibre-db/src/data/author.rs +++ b/calibre-db/src/data/author.rs @@ -26,9 +26,9 @@ impl Author { conn: &Connection, limit: u64, cursor: Option<&str>, - sort_order: SortOrder, + sort_order: &SortOrder, ) -> Result, DataStoreError> { - let pagination = Pagination::new("sort", cursor, limit, sort_order); + let pagination = Pagination::new("sort", cursor, limit, *sort_order); pagination.paginate( conn, "SELECT id, name, sort FROM authors", @@ -46,4 +46,25 @@ impl Author { let params = named_params! { ":id": id }; Ok(stmt.query_row(params, Self::from_row)?) } + + pub fn has_previous_authors( + conn: &Connection, + sort_name: &str, + ) -> Result { + let mut stmt = conn + .prepare("SELECT Count(1) FROM authors WHERE sort < (:sort_name) ORDER BY sort DESC")?; + let params = named_params! { ":sort_name": sort_name }; + let count: u64 = stmt.query_row(params, |x| x.get(0))?; + + Ok(count > 0) + } + + pub fn has_more_authors(conn: &Connection, sort_name: &str) -> Result { + let mut stmt = conn + .prepare("SELECT Count(1) FROM authors WHERE sort > (:sort_name) ORDER BY sort ASC")?; + let params = named_params! { ":sort_name": sort_name }; + let count: u64 = stmt.query_row(params, |x| x.get(0))?; + + Ok(count > 0) + } } diff --git a/calibre-db/src/data/pagination.rs b/calibre-db/src/data/pagination.rs index 6c7c90d..988dc17 100644 --- a/calibre-db/src/data/pagination.rs +++ b/calibre-db/src/data/pagination.rs @@ -1,8 +1,9 @@ use rusqlite::{Connection, Row, ToSql}; +use serde::{Deserialize, Serialize}; use super::error::DataStoreError; -#[derive(Debug, PartialEq)] +#[derive(Debug, Copy, Clone, PartialEq, Deserialize, Serialize)] pub enum SortOrder { ASC, DESC, @@ -53,10 +54,17 @@ impl<'a> Pagination<'a> { }; let sort_col = self.sort_col; + // otherwise paginated statements with join will fail + let sort_col_wrapped = if let Some(index) = sort_col.find('.') { + let right_part = &sort_col[index..]; + "t".to_owned() + right_part + } else { + sort_col.to_owned() + }; let sort_order = &self.sort_order; // DANGER: vulnerable to SQL injection if statement or sort_col variable is influenced by user input let mut stmt = conn.prepare(&format!( - "{statement} {where_sql} {sort_col} {comparison} (:cursor) ORDER BY {sort_col} {sort_order:?} LIMIT (:limit)" + "SELECT * FROM ({statement} {where_sql} {sort_col} {comparison} (:cursor) ORDER BY {sort_col} {sort_order:?} LIMIT (:limit)) AS t ORDER BY {sort_col_wrapped} ASC" ))?; let params = [ &[ diff --git a/rusty-library/src/handlers/authors.rs b/rusty-library/src/handlers/authors.rs index 73cd468..08da35a 100644 --- a/rusty-library/src/handlers/authors.rs +++ b/rusty-library/src/handlers/authors.rs @@ -1,10 +1,34 @@ use std::sync::Arc; -use poem::{handler, web::Data}; +use calibre_db::data::pagination::SortOrder; +use poem::{ + handler, + web::{Data, Html, Path}, +}; -use crate::app_state::AppState; +use crate::{app_state::AppState, handlers::paginated}; #[handler] -pub async fn handler(state: Data<&Arc>) -> Result { - Ok("authors".to_string()) +pub async fn handler_init(state: Data<&Arc>) -> Result, poem::Error> { + paginated::render( + "authors", + || state.calibre.authors(25, None, &SortOrder::ASC), + |author| author.sort.clone(), + |cursor| state.calibre.has_previous_authors(cursor), + |cursor| state.calibre.has_more_authors(cursor), + ) +} + +#[handler] +pub async fn handler( + Path((cursor, sort_order)): Path<(String, SortOrder)>, + state: Data<&Arc>, +) -> Result, poem::Error> { + paginated::render( + "authors", + || state.calibre.authors(25, Some(&cursor), &sort_order), + |author| author.sort.clone(), + |cursor| state.calibre.has_previous_authors(cursor), + |cursor| state.calibre.has_more_authors(cursor), + ) } diff --git a/rusty-library/src/handlers/paginated.rs b/rusty-library/src/handlers/paginated.rs new file mode 100644 index 0000000..9bbfbce --- /dev/null +++ b/rusty-library/src/handlers/paginated.rs @@ -0,0 +1,46 @@ +use calibre_db::data::error::DataStoreError; +use poem::{error::InternalServerError, web::Html}; +use serde::Serialize; +use tera::Context; + +use crate::templates::TEMPLATES; + +use super::error::SqliteError; + +pub fn render( + template: &str, + fetcher: F, + sort_field: S, + has_previous: P, + has_more: M, +) -> Result, poem::Error> +where + F: Fn() -> Result, DataStoreError>, + S: Fn(&T) -> String, + P: Fn(&str) -> Result, + M: Fn(&str) -> Result, +{ + let items = fetcher().map_err(SqliteError)?; + + let mut context = Context::new(); + + // fails already in the sql query if there is nothing returned + let first_item = items.first().unwrap(); + let last_item = items.last().unwrap(); + + let (backward_cursor, forward_cursor) = (sort_field(first_item), sort_field(last_item)); + + let has_previous = has_previous(&backward_cursor).map_err(SqliteError)?; + let has_more = has_more(&forward_cursor).map_err(SqliteError)?; + + context.insert("has_previous", &has_previous); + context.insert("has_more", &has_more); + context.insert("backward_cursor", &backward_cursor); + context.insert("forward_cursor", &forward_cursor); + context.insert("nav", template); + context.insert(template, &items); + TEMPLATES + .render(template, &context) + .map_err(InternalServerError) + .map(Html) +} diff --git a/rusty-library/src/handlers/recents.rs b/rusty-library/src/handlers/recents.rs index 793086c..e3ce040 100644 --- a/rusty-library/src/handlers/recents.rs +++ b/rusty-library/src/handlers/recents.rs @@ -13,13 +13,15 @@ use crate::{ #[handler] pub async fn handler(state: Data<&Arc>) -> Result, poem::Error> { - let recent_books = state.calibre.recent_books(50).map_err(SqliteError)?; + let recent_books = state.calibre.recent_books(25).map_err(SqliteError)?; let recent_books = recent_books .iter() .filter_map(|x| Book::full_book(x, &state)) .collect::>(); let mut context = Context::new(); + context.insert("title", "Recent Books"); + context.insert("nav", "recent"); context.insert("books", &recent_books); TEMPLATES .render("recents", &context) diff --git a/rusty-library/src/main.rs b/rusty-library/src/main.rs index 117c31f..f31870c 100644 --- a/rusty-library/src/main.rs +++ b/rusty-library/src/main.rs @@ -23,6 +23,7 @@ mod handlers { pub mod cover; pub mod download; pub mod error; + pub mod paginated; pub mod recents; pub mod series; } @@ -48,7 +49,11 @@ async fn main() -> Result<(), std::io::Error> { let app = Route::new() .at("/", get(handlers::recents::handler)) .at("/books", get(handlers::books::handler)) - .at("/authors", get(handlers::authors::handler)) + .at("/authors", get(handlers::authors::handler_init)) + .at( + "/authors/:cursor/:sort_order", + get(handlers::authors::handler), + ) .at("/series", get(handlers::series::handler)) .at("/cover/:id", get(handlers::cover::handler)) .at("/book/:id/:format", get(handlers::download::handler)) diff --git a/rusty-library/src/templates.rs b/rusty-library/src/templates.rs index 6a14a14..371b844 100644 --- a/rusty-library/src/templates.rs +++ b/rusty-library/src/templates.rs @@ -6,6 +6,7 @@ pub static TEMPLATES: Lazy = Lazy::new(|| { tera.add_raw_templates(vec![ ("base", include_str!("../templates/base.html")), ("book_card", include_str!("../templates/book_card.html")), + ("authors", include_str!("../templates/authors.html")), ("recents", include_str!("../templates/recents.html")), ]) .expect("failed to parse tera templates"); diff --git a/rusty-library/static/style.css b/rusty-library/static/style.css index 81a4170..f60713c 100644 --- a/rusty-library/static/style.css +++ b/rusty-library/static/style.css @@ -3,6 +3,21 @@ overflow: scroll; text-overflow: ellipsis; } +header.fixed { + position: sticky; + top: 0; + z-index: 1000; + background: var(--pico-background-color) +} + +nav ul li { + padding-top: 0rem; + padding-bottom: 0.25rem; +} + +.nav-active { + border-bottom: solid var(--pico-primary-underline); +} .book-card hgroup { margin-bottom: 0; diff --git a/rusty-library/templates/authors.html b/rusty-library/templates/authors.html new file mode 100644 index 0000000..a9a208e --- /dev/null +++ b/rusty-library/templates/authors.html @@ -0,0 +1,19 @@ +{% extends "base" %} +{% block title %} +{% if has_previous %} +← back +{% endif %} +{% if has_previous and has_more %}|{% endif%} + +{% if has_more %} +more → +{% endif %} +{% endblock title %} + +{% block content %} +
+ {% for author in authors %} +
{{ author.name }}
+ {% endfor %} +
+{% endblock content %} diff --git a/rusty-library/templates/base.html b/rusty-library/templates/base.html index a813a53..e073704 100644 --- a/rusty-library/templates/base.html +++ b/rusty-library/templates/base.html @@ -9,18 +9,20 @@ Rusty Library -
+
+
+
{% block content %}{% endblock content %}
diff --git a/rusty-library/templates/recents.html b/rusty-library/templates/recents.html index a292932..b69059f 100644 --- a/rusty-library/templates/recents.html +++ b/rusty-library/templates/recents.html @@ -1,6 +1,5 @@ {% extends "base" %} {% block content %} -

Recent Books

{% for book in books %} {% include "book_card" %}