563 lines
17 KiB
Rust
563 lines
17 KiB
Rust
use cosmic::widget::image::Handle;
|
|
use crisp::types::{Keyword, Symbol, Value};
|
|
use itertools::Itertools;
|
|
use miette::{IntoDiagnostic, Result, miette};
|
|
use mupdf::{Colorspace, Document, Matrix};
|
|
use serde::{Deserialize, Serialize};
|
|
use sqlx::prelude::FromRow;
|
|
use sqlx::sqlite::SqliteRow;
|
|
use sqlx::types::chrono::{DateTime, Local};
|
|
use sqlx::{AssertSqlSafe, Row, SqliteConnection, SqlitePool, query};
|
|
use std::mem::replace;
|
|
use std::path::{Path, PathBuf};
|
|
use std::sync::Arc;
|
|
use tracing::{debug, error};
|
|
|
|
use crate::core::model::Sort;
|
|
use crate::{Background, Slide, SlideBuilder, TextAlignment};
|
|
|
|
use super::content::Content;
|
|
use super::kinds::ServiceItemKind;
|
|
use super::model::{LibraryKind, Model};
|
|
use super::service_items::ServiceTrait;
|
|
|
|
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
|
|
pub enum PresKind {
|
|
Html,
|
|
Pdf {
|
|
starting_index: i32,
|
|
ending_index: i32,
|
|
},
|
|
#[default]
|
|
Generic,
|
|
}
|
|
|
|
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
|
|
pub struct Presentation {
|
|
pub id: i32,
|
|
pub title: String,
|
|
pub path: PathBuf,
|
|
pub kind: PresKind,
|
|
#[serde(skip)]
|
|
pub created_at: DateTime<Local>,
|
|
#[serde(skip)]
|
|
pub accessed_at: DateTime<Local>,
|
|
}
|
|
|
|
impl Eq for Presentation {}
|
|
|
|
impl PartialEq for Presentation {
|
|
fn eq(&self, other: &Self) -> bool {
|
|
self.id == other.id
|
|
&& self.title == other.title
|
|
&& self.path == other.path
|
|
&& self.kind == other.kind
|
|
}
|
|
}
|
|
|
|
impl From<PathBuf> for Presentation {
|
|
fn from(value: PathBuf) -> Self {
|
|
let title = value
|
|
.file_name()
|
|
.unwrap_or_default()
|
|
.to_str()
|
|
.unwrap_or_default()
|
|
.to_string();
|
|
let kind = match value
|
|
.extension()
|
|
.unwrap_or_default()
|
|
.to_str()
|
|
.unwrap_or_default()
|
|
{
|
|
"pdf" => Document::open(&value.to_str().unwrap_or_default()).map_or(
|
|
PresKind::Pdf {
|
|
starting_index: 0,
|
|
ending_index: 0,
|
|
},
|
|
|document| {
|
|
document.page_count().map_or(
|
|
PresKind::Pdf {
|
|
starting_index: 0,
|
|
ending_index: 0,
|
|
},
|
|
|count| PresKind::Pdf {
|
|
starting_index: 0,
|
|
ending_index: count - 1,
|
|
},
|
|
)
|
|
},
|
|
),
|
|
"html" => PresKind::Html,
|
|
_ => PresKind::Generic,
|
|
};
|
|
Self {
|
|
id: 0,
|
|
title,
|
|
path: value.canonicalize().unwrap_or(value),
|
|
kind,
|
|
created_at: Local::now(),
|
|
accessed_at: Local::now(),
|
|
}
|
|
}
|
|
}
|
|
|
|
impl From<&Path> for Presentation {
|
|
fn from(value: &Path) -> Self {
|
|
Self::from(value.to_owned())
|
|
}
|
|
}
|
|
|
|
impl From<&Presentation> for Value {
|
|
fn from(_value: &Presentation) -> Self {
|
|
Self::List(vec![Self::Symbol(Symbol("presentation".into()))])
|
|
}
|
|
}
|
|
|
|
impl Content for Presentation {
|
|
fn title(&self) -> String {
|
|
self.title.clone()
|
|
}
|
|
|
|
fn kind(&self) -> ServiceItemKind {
|
|
ServiceItemKind::Presentation(self.clone())
|
|
}
|
|
|
|
fn to_service_item(&self) -> super::service_items::ServiceItem {
|
|
self.into()
|
|
}
|
|
|
|
fn background(&self) -> Option<Background> {
|
|
Background::try_from(self.path.clone()).ok()
|
|
}
|
|
|
|
fn subtext(&self) -> String {
|
|
if self.path.exists() {
|
|
self.path.file_name().map_or_else(
|
|
|| "Missing presentation".into(),
|
|
|f| f.to_string_lossy().to_string(),
|
|
)
|
|
} else {
|
|
"Missing presentation".into()
|
|
}
|
|
}
|
|
}
|
|
|
|
impl From<Value> for Presentation {
|
|
fn from(value: Value) -> Self {
|
|
Self::from(&value)
|
|
}
|
|
}
|
|
|
|
#[allow(clippy::option_if_let_else)]
|
|
impl From<&Value> for Presentation {
|
|
fn from(value: &Value) -> Self {
|
|
match value {
|
|
Value::List(list) => {
|
|
let path = if let Some(path_pos) = list
|
|
.iter()
|
|
.position(|v| v == &Value::Keyword(Keyword::from("source")))
|
|
{
|
|
let pos = path_pos + 1;
|
|
list.get(pos).map(|p| PathBuf::from(String::from(p)))
|
|
} else {
|
|
None
|
|
};
|
|
|
|
let title = path
|
|
.clone()
|
|
.map(|p| p.to_str().unwrap_or_default().to_string());
|
|
Self {
|
|
title: title.unwrap_or_default(),
|
|
path: path.unwrap_or_default(),
|
|
..Default::default()
|
|
}
|
|
}
|
|
_ => todo!(),
|
|
}
|
|
}
|
|
}
|
|
|
|
impl ServiceTrait for Presentation {
|
|
fn title(&self) -> String {
|
|
self.title.clone()
|
|
}
|
|
|
|
fn id(&self) -> i32 {
|
|
self.id
|
|
}
|
|
|
|
fn to_slides(&self) -> Result<Vec<Slide>> {
|
|
debug!(?self);
|
|
let PresKind::Pdf {
|
|
starting_index,
|
|
ending_index,
|
|
} = self.kind
|
|
else {
|
|
return Err(miette::miette!("This is not a pdf presentation"));
|
|
};
|
|
let background = Background::try_from(self.path.clone()).into_diagnostic()?;
|
|
debug!(?background);
|
|
let document = Document::open(background.path.to_str().unwrap_or_default())
|
|
.into_diagnostic()?;
|
|
debug!(?document);
|
|
let pages = document.pages().into_diagnostic()?;
|
|
debug!(?pages);
|
|
let pages: Vec<Handle> = pages
|
|
.enumerate()
|
|
.filter_map(|(index, page)| {
|
|
let index = i32::try_from(index).expect("Shouldn't be that high");
|
|
|
|
if index < starting_index || index > ending_index {
|
|
return None;
|
|
}
|
|
|
|
let page = page.ok()?;
|
|
let matrix = Matrix::IDENTITY;
|
|
let colorspace = Colorspace::device_rgb();
|
|
let Ok(pixmap) = page
|
|
.to_pixmap(&matrix, &colorspace, true, true)
|
|
.into_diagnostic()
|
|
else {
|
|
error!("Can't turn this page into pixmap");
|
|
return None;
|
|
};
|
|
debug!(?pixmap);
|
|
Some(Handle::from_rgba(
|
|
pixmap.width(),
|
|
pixmap.height(),
|
|
pixmap.samples().to_vec(),
|
|
))
|
|
})
|
|
.collect();
|
|
|
|
let mut slides: Vec<Slide> = vec![];
|
|
for (index, page) in pages.into_iter().enumerate() {
|
|
let slide = SlideBuilder::new()
|
|
.background(Background::try_from(self.path.clone()).into_diagnostic()?)
|
|
.text("")
|
|
.audio("")
|
|
.font("")
|
|
.font_size(50)
|
|
.text_alignment(TextAlignment::MiddleCenter)
|
|
.video_loop(false)
|
|
.video_start_time(0.0)
|
|
.video_end_time(0.0)
|
|
.pdf_index(u32::try_from(index).expect("Shouldn't get that high"))
|
|
.pdf_page(page)
|
|
.build()?;
|
|
slides.push(slide);
|
|
}
|
|
debug!(?slides);
|
|
Ok(slides)
|
|
}
|
|
|
|
fn box_clone(&self) -> Box<dyn ServiceTrait> {
|
|
Box::new((*self).clone())
|
|
}
|
|
}
|
|
|
|
impl Presentation {
|
|
#[must_use]
|
|
pub fn new() -> Self {
|
|
Self {
|
|
title: String::new(),
|
|
..Default::default()
|
|
}
|
|
}
|
|
|
|
#[must_use]
|
|
pub const fn get_kind(&self) -> &PresKind {
|
|
&self.kind
|
|
}
|
|
}
|
|
|
|
impl FromRow<'_, SqliteRow> for Presentation {
|
|
fn from_row(row: &SqliteRow) -> sqlx::Result<Self> {
|
|
Ok(Self {
|
|
id: row.try_get(0)?,
|
|
title: row.try_get(1)?,
|
|
path: PathBuf::from({
|
|
let string: String = row.try_get(2)?;
|
|
string
|
|
}),
|
|
kind: if row.try_get(3)? {
|
|
PresKind::Html
|
|
} else {
|
|
PresKind::Pdf {
|
|
starting_index: row.try_get(4)?,
|
|
ending_index: row.try_get(5)?,
|
|
}
|
|
},
|
|
created_at: Local::now(),
|
|
accessed_at: Local::now(),
|
|
})
|
|
}
|
|
}
|
|
|
|
impl Model<Presentation> {
|
|
pub async fn new_presentation_model(db: Arc<SqlitePool>) -> Self {
|
|
let mut model = Self {
|
|
items: vec![],
|
|
kind: LibraryKind::Presentation,
|
|
sorting_method: Sort::AccessTime,
|
|
};
|
|
model.load_from_db(db).await;
|
|
model
|
|
}
|
|
|
|
pub async fn load_from_db(&mut self, db: Arc<SqlitePool>) {
|
|
let result = query!(
|
|
r#"SELECT id as "id: i32", title, file_path as "path", html, starting_index, ending_index, accessed_at as "accessed_at!: DateTime<Local>", created_at as "created_at!: DateTime<Local>" from presentations"#
|
|
)
|
|
.fetch_all(&*db)
|
|
.await;
|
|
|
|
match result {
|
|
Ok(v) => {
|
|
for presentation in v {
|
|
let _ = self.add_item(Presentation {
|
|
id: presentation.id,
|
|
title: presentation.title,
|
|
path: presentation.path.clone().into(),
|
|
kind: if presentation.html {
|
|
PresKind::Html
|
|
} else if let (Some(starting_index), Some(ending_index)) =
|
|
(presentation.starting_index, presentation.ending_index)
|
|
{
|
|
PresKind::Pdf {
|
|
starting_index: i32::try_from(starting_index)
|
|
.expect("Shouldn't get that high"),
|
|
ending_index: i32::try_from(ending_index)
|
|
.expect("Shouldn't get that high"),
|
|
}
|
|
} else {
|
|
let path = PathBuf::from(presentation.path);
|
|
|
|
Document::open(path.to_str().unwrap_or_default()).map_or(
|
|
PresKind::Generic,
|
|
|document| {
|
|
document.page_count().map_or(
|
|
PresKind::Pdf {
|
|
starting_index: 0,
|
|
ending_index: 0,
|
|
},
|
|
|count| {
|
|
let ending_index = count - 1;
|
|
PresKind::Pdf {
|
|
starting_index: 0,
|
|
ending_index,
|
|
}
|
|
},
|
|
)
|
|
},
|
|
)
|
|
},
|
|
created_at: presentation.created_at,
|
|
accessed_at: presentation.accessed_at,
|
|
});
|
|
}
|
|
}
|
|
Err(e) => error!("There was an error in converting presentations: {e}"),
|
|
}
|
|
}
|
|
|
|
pub fn sort(&mut self) {
|
|
match self.sorting_method {
|
|
Sort::AccessTime => {
|
|
self.items.sort_by(|a, b| b.accessed_at.cmp(&a.accessed_at))
|
|
}
|
|
Sort::CreatedTime => todo!(),
|
|
Sort::Title => todo!(),
|
|
Sort::Secondary => todo!(),
|
|
}
|
|
}
|
|
|
|
pub fn set_sort(mut self, method: Sort) -> Self {
|
|
self.sorting_method = method;
|
|
self.sort();
|
|
self
|
|
}
|
|
}
|
|
|
|
pub async fn remove_presentations(
|
|
db: Arc<SqlitePool>,
|
|
presentations: Vec<Presentation>,
|
|
ids: Vec<i32>,
|
|
) -> Result<Vec<Presentation>> {
|
|
let presentations = presentations
|
|
.into_iter()
|
|
.filter(|current_presentation| !ids.contains(¤t_presentation.id))
|
|
.collect();
|
|
|
|
let delete = format!(
|
|
"DELETE FROM presentations WHERE id IN ({:})",
|
|
ids.iter().map(ToString::to_string).join(", ")
|
|
);
|
|
|
|
query(AssertSqlSafe(delete))
|
|
.execute(&*db)
|
|
.await
|
|
.into_diagnostic()
|
|
.map(|_| presentations)
|
|
}
|
|
|
|
pub async fn remove_presentation(
|
|
db: Arc<SqlitePool>,
|
|
mut presentations: Vec<Presentation>,
|
|
id: i32,
|
|
) -> Result<Vec<Presentation>> {
|
|
query!("DELETE FROM presentations WHERE id = $1", id)
|
|
.execute(&*db)
|
|
.await
|
|
.into_diagnostic()
|
|
.map(|_| ())?;
|
|
|
|
let index = presentations
|
|
.iter()
|
|
.position(|current_presentation| current_presentation.id == id)
|
|
.ok_or_else(|| miette!("Could not find presentation in model"))?;
|
|
presentations.remove(index);
|
|
Ok(presentations)
|
|
}
|
|
|
|
pub async fn add_presentation(
|
|
new_presentations: Vec<Presentation>,
|
|
mut current_presentations: Vec<Presentation>,
|
|
db: Arc<SqlitePool>,
|
|
) -> Result<Vec<Presentation>> {
|
|
for presentation in new_presentations {
|
|
let path = presentation
|
|
.path
|
|
.to_str()
|
|
.map(std::string::ToString::to_string)
|
|
.unwrap_or_default();
|
|
let html = presentation.kind == PresKind::Html;
|
|
let (starting_index, ending_index) = if let PresKind::Pdf {
|
|
starting_index,
|
|
ending_index,
|
|
} = presentation.kind
|
|
{
|
|
(starting_index, ending_index)
|
|
} else {
|
|
(0, 0)
|
|
};
|
|
query!(
|
|
r#"INSERT INTO presentations (title, file_path, html, starting_index, ending_index) VALUES ($1, $2, $3, $4, $5)"#,
|
|
presentation.title,
|
|
path,
|
|
html,
|
|
starting_index,
|
|
ending_index
|
|
)
|
|
.execute(&*db)
|
|
.await
|
|
.into_diagnostic()?;
|
|
|
|
current_presentations.push(presentation);
|
|
}
|
|
Ok(current_presentations)
|
|
}
|
|
|
|
pub async fn update_presentation(
|
|
presentation: Presentation,
|
|
mut presentations: Vec<Presentation>,
|
|
db: Arc<SqlitePool>,
|
|
) -> Result<Vec<Presentation>> {
|
|
let path = presentation
|
|
.path
|
|
.to_str()
|
|
.map(std::string::ToString::to_string)
|
|
.unwrap_or_default();
|
|
let html = presentation.kind == PresKind::Html;
|
|
let (starting_index, ending_index) = if let PresKind::Pdf {
|
|
starting_index: s_index,
|
|
ending_index: e_index,
|
|
} = presentation.get_kind()
|
|
{
|
|
(*s_index, *e_index)
|
|
} else {
|
|
(0, 0)
|
|
};
|
|
debug!(starting_index, ending_index);
|
|
|
|
query!(
|
|
r#"UPDATE presentations SET title = $2, file_path = $3, html = $4, starting_index = $5, ending_index = $6 WHERE id = $1"#,
|
|
presentation.id,
|
|
presentation.title,
|
|
path,
|
|
html,
|
|
starting_index,
|
|
ending_index
|
|
)
|
|
.execute(&*db)
|
|
.await.into_diagnostic()?;
|
|
|
|
let current_presentation = presentations
|
|
.iter()
|
|
.position(|current_presentation| current_presentation.id == presentation.id)
|
|
.ok_or_else(|| miette!("Could not find presentation in model"))
|
|
.map(|index| {
|
|
presentations
|
|
.get_mut(index)
|
|
.expect("We should have this presentation already")
|
|
})?;
|
|
|
|
let _ = replace(current_presentation, presentation);
|
|
Ok(presentations)
|
|
}
|
|
|
|
pub async fn get_presentation_from_db(
|
|
database_id: i32,
|
|
db: &mut SqliteConnection,
|
|
) -> Result<Presentation> {
|
|
let row = query(r#"SELECT id as "id: i32", title, file_path as "path", html, accessed_at as "accessed_at!: DateTime<Local>", created_at as "created_at!: DateTime<Local>" from presentations where id = $1"#).bind(database_id).fetch_one(db).await.into_diagnostic()?;
|
|
Presentation::from_row(&row).into_diagnostic()
|
|
}
|
|
|
|
#[cfg(test)]
|
|
mod test {
|
|
use super::*;
|
|
use pretty_assertions::assert_eq;
|
|
|
|
fn test_presentation() -> Presentation {
|
|
Presentation {
|
|
id: 4,
|
|
title: "mzt52.pdf".into(),
|
|
path: PathBuf::from("/home/chris/docs/mzt52.pdf"),
|
|
kind: PresKind::Pdf {
|
|
starting_index: 0,
|
|
ending_index: 67,
|
|
},
|
|
created_at: Local::now(),
|
|
accessed_at: Local::now(),
|
|
}
|
|
}
|
|
|
|
#[test]
|
|
pub fn test_pres() {
|
|
let pres = Presentation::new();
|
|
assert_eq!(pres.get_kind(), &PresKind::Generic);
|
|
}
|
|
|
|
async fn add_db() -> Result<SqlitePool> {
|
|
let db_url = String::from("sqlite://./test.db");
|
|
SqlitePool::connect(&db_url).await.into_diagnostic()
|
|
}
|
|
|
|
#[tokio::test]
|
|
async fn test_db_and_model() {
|
|
let mut presentation_model: Model<Presentation> = Model {
|
|
items: vec![],
|
|
kind: LibraryKind::Presentation,
|
|
sorting_method: Sort::AccessTime,
|
|
};
|
|
let db = Arc::new(add_db().await.expect("Getting db error"));
|
|
presentation_model.load_from_db(db).await;
|
|
if let Some(presentation) = presentation_model.find(|p| p.id == 4) {
|
|
let test_presentation = test_presentation();
|
|
assert_eq!(&test_presentation, presentation);
|
|
} else {
|
|
panic!();
|
|
}
|
|
}
|
|
}
|