//! Book data. use rusqlite::{Connection, Row, named_params}; use serde::Serialize; use snafu::{ResultExt, Snafu}; use time::OffsetDateTime; use super::pagination::{HasPrevOrMoreError, Pagination, PaginationError, SortOrder}; /// Book in calibre. #[derive(Debug, Clone, Serialize)] pub struct Book { /// Id in database. pub id: u64, /// Book title. pub title: String, /// Book title for sorting. pub sort: String, /// Folder of the book within the calibre library. pub path: String, /// Uuid of the book. pub uuid: String, /// When was the book last modified. pub last_modified: OffsetDateTime, /// Optional description. pub description: Option, } #[derive(Debug, Snafu)] #[snafu(display("Failed to fetch multiple books."))] pub struct MultipleBooksError { source: PaginationError, } #[derive(Debug, Snafu)] #[snafu(display("Failed to fetch author's books."))] pub struct AuthorBooksError { source: PaginationError, } #[derive(Debug, Snafu)] /// Errors that can occur when fetching a series' books. pub enum SeriesBookError { /// A failure to prepare the SQL statement. #[snafu(display("Failed to prepare statement."))] PrepareSeriesBook { source: rusqlite::Error }, /// A failure to execute the SQL statement. #[snafu(display("Failed to execute statement."))] ExecuteSeriesBook { source: rusqlite::Error }, } #[derive(Debug, Snafu)] /// Errors that can occur when fetching recent books. pub enum RecentBooksError { /// A failure to prepare the SQL statement. #[snafu(display("Failed to prepare statement."))] PrepareRecentBooks { source: rusqlite::Error }, /// A failure to execute the SQL statement. #[snafu(display("Failed to execute statement."))] ExecuteRecentBooks { source: rusqlite::Error }, } #[derive(Debug, Snafu)] /// Errors that can occur when fetching a single book. pub enum ScalarBookError { /// A failure to prepare the SQL statement. #[snafu(display("Failed to prepare statement."))] PrepareScalarBook { source: rusqlite::Error }, /// A failure to execute the SQL statement. #[snafu(display("Failed to execute statement."))] ExecuteScalarBook { source: rusqlite::Error }, } #[derive(Debug, Snafu)] #[snafu(display("Failed to check for previous books."))] pub struct PreviousBooksError { source: HasPrevOrMoreError, } #[derive(Debug, Snafu)] #[snafu(display("Failed to check for more books."))] pub struct MoreBooksError { source: HasPrevOrMoreError, } impl Book { /// Create a book from a database row. fn from_row(row: &Row<'_>) -> Result { Ok(Self { id: row.get(0)?, title: row.get(1)?, sort: row.get(2)?, path: row.get(3)?, uuid: row.get(4)?, last_modified: row.get(5)?, description: row.get(6)?, }) } /// Fetch book data from calibre, starting at `cursor`, fetching up to an amount of `limit` and /// ordering by `sort_order`. pub fn multiple( conn: &Connection, limit: u64, cursor: Option<&str>, sort_order: &SortOrder, ) -> Result, MultipleBooksError> { let pagination = Pagination::new("sort", cursor, limit, *sort_order); pagination.paginate( conn, "SELECT books.id, books.title, books.sort, books.path, books.uuid, books.last_modified, comments.text \ FROM books LEFT JOIN comments ON books.id = comments.book", &[], Self::from_row, ).context(MultipleBooksSnafu) } /// Fetch books for an author specified by `author_id`, paginate the books by starting at `cursor`, /// fetching up to an amount of `limit` and ordering by `sort_order`. pub fn author_books( conn: &Connection, author_id: u64, limit: u64, cursor: Option<&str>, sort_order: SortOrder, ) -> Result, AuthorBooksError> { let pagination = Pagination::new("books.sort", cursor, limit, sort_order); pagination.paginate( conn, "SELECT books.id, books.title, books.sort, books.path, books.uuid, books.last_modified, comments.text FROM books \ INNER JOIN books_authors_link ON books.id = books_authors_link.book \ LEFT JOIN comments ON books.id = comments.book \ WHERE books_authors_link.author = (:author_id) AND", &[(":author_id", &author_id)], Self::from_row, ).context(AuthorBooksSnafu) } /// Get all books belonging to the series with id `id`. pub fn series_books(conn: &Connection, id: u64) -> Result, SeriesBookError> { let mut stmt = conn.prepare( "SELECT books.id, books.title, books.sort, books.path, books.uuid, books.last_modified, comments.text FROM series \ INNER JOIN books_series_link ON series.id = books_series_link.series \ INNER JOIN books ON books.id = books_series_link.book \ LEFT JOIN comments ON books.id = comments.book \ WHERE books_series_link.series = (:id) \ ORDER BY books.series_index", ).context(PrepareSeriesBookSnafu)?; let params = named_params! { ":id": id }; let iter = stmt .query_map(params, Self::from_row) .context(ExecuteSeriesBookSnafu)?; Ok(iter.filter_map(Result::ok).collect()) } /// Get recent books up to a limit of `limit`. pub fn recents(conn: &Connection, limit: u64) -> Result, RecentBooksError> { let mut stmt = conn.prepare( "SELECT books.id, books.title, books.sort, books.path, books.uuid, books.last_modified, comments.text \ FROM books LEFT JOIN comments ON books.id = comments.book ORDER BY books.timestamp DESC LIMIT (:limit)" ).context(PrepareRecentBooksSnafu)?; let params = named_params! { ":limit": limit }; let iter = stmt .query_map(params, Self::from_row) .context(ExecuteRecentBooksSnafu)?; Ok(iter.filter_map(Result::ok).collect()) } /// Get a single book, specified `id`. pub fn scalar_book(conn: &Connection, id: u64) -> Result { let mut stmt = conn.prepare( "SELECT books.id, books.title, books.sort, books.path, books.uuid, books.last_modified, comments.text \ FROM books LEFT JOIN comments WHERE books.id = (:id)", ).context(PrepareScalarBookSnafu)?; let params = named_params! { ":id": id }; stmt.query_row(params, Self::from_row) .context(ExecuteScalarBookSnafu) } /// Check if there are more books before the specified cursor. pub fn has_previous_books( conn: &Connection, sort_title: &str, ) -> Result { Pagination::has_prev_or_more(conn, "books", sort_title, &SortOrder::DESC) .context(PreviousBooksSnafu) } /// Check if there are more books after the specified cursor. pub fn has_more_books(conn: &Connection, sort_title: &str) -> Result { Pagination::has_prev_or_more(conn, "books", sort_title, &SortOrder::ASC) .context(MoreBooksSnafu) } }