//! Code exécuté uniquement côté serveur : base de données et accès au contexte. use crate::{ model::{ FileSort, FileSummary, LogFormat, LogKind, ProjectSummary, Settings, Summary, is_hidden, parse_log_dirs, }, scanner::Scanner, }; use leptos::prelude::*; use sqlx::{ SqlitePool, sqlite::{SqliteConnectOptions, SqliteJournalMode, SqlitePoolOptions}, }; use std::{error::Error, fmt::Display, str::FromStr, sync::Arc, time::Duration}; /// Ouvre le pool SQLite (en créant le fichier au besoin), vérifie son intégrité /// et applique les migrations. pub async fn connect_db(url: &str) -> Result> { let options = SqliteConnectOptions::from_str(url)? .create_if_missing(true) .foreign_keys(true) .journal_mode(SqliteJournalMode::Wal) .busy_timeout(Duration::from_secs(5)); let pool = SqlitePoolOptions::new() .max_connections(5) .connect_with(options) .await?; let check: String = sqlx::query_scalar("PRAGMA quick_check") .fetch_one(&pool) .await?; if check != "ok" { return Err(format!("base corrompue : {check}").into()); } sqlx::migrate!().run(&pool).await?; Ok(pool) } /// Récupère le pool fourni en contexte par `main`. pub fn pool() -> Result { use_context::().ok_or_else(|| internal_error("SqlitePool absent du contexte")) } /// Récupère le scanner fourni en contexte par `main`. pub fn scanner() -> Result, ServerFnError> { use_context::>().ok_or_else(|| internal_error("Scanner absent du contexte")) } /// Journalise l'erreur réelle et renvoie au client un message générique. pub fn internal_error(error: impl Display) -> ServerFnError { leptos::logging::error!("erreur interne : {error}"); ServerFnError::new("Une erreur interne est survenue.") } /// Erreur renvoyée quand un projet ou un fichier demandé n'existe plus. pub fn not_found() -> ServerFnError { ServerFnError::new("Élément introuvable, la liste a été rafraîchie.") } /// Horodatage courant, au format stocké en base. pub fn now() -> String { format_ts(time::OffsetDateTime::now_utc()) } pub fn format_ts(ts: time::OffsetDateTime) -> String { use time::macros::format_description; ts.format(format_description!( "[year]-[month]-[day] [hour]:[minute]:[second]" )) .unwrap_or_default() } async fn setting(pool: &SqlitePool, key: &str) -> sqlx::Result> { sqlx::query_scalar("SELECT value FROM settings WHERE key = ?") .bind(key) .fetch_optional(pool) .await } pub async fn set_setting(pool: &SqlitePool, key: &str, value: &str) -> sqlx::Result<()> { sqlx::query( "INSERT INTO settings (key, value) VALUES (?, ?) ON CONFLICT (key) DO UPDATE SET value = excluded.value", ) .bind(key) .bind(value) .execute(pool) .await?; Ok(()) } pub async fn load_settings(pool: &SqlitePool) -> sqlx::Result { let file_sort = setting(pool, "file_sort") .await? .and_then(|v| FileSort::parse(&v)) .unwrap_or_default(); let paused = setting(pool, "paused").await?.as_deref() == Some("1"); Ok(Settings { file_sort, paused }) } /// (id, project_id, relative_path, kind, format, size, modifié le, manquant, erreur, non-lus) type FileRow = ( i64, i64, String, String, Option, i64, Option, bool, Option, i64, ); /// Projets, fichiers et compteurs de non-lus. /// /// Un fichier manquant ou un projet introuvable sur le disque ne compte aucun non-lu, ni un /// log d'accès (cf. [`LogFormat::notifies`]). Les fichiers masqués (trop anciens, cf. /// [`is_hidden`]) ne sont ni listés ni comptés. pub async fn load_summary(pool: &SqlitePool) -> sqlx::Result { type ProjectRow = ( i64, String, String, i64, Option, String, Option, Option, Option, ); let projects: Vec = sqlx::query_as( "SELECT id, name, root_path, refresh_seconds, hide_after_days, log_dirs, last_error, vhost_path, vhost_error FROM projects ORDER BY name COLLATE NOCASE, id", ) .fetch_all(pool) .await?; let files: Vec = sqlx::query_as( "SELECT f.id, f.project_id, f.relative_path, f.kind, f.format, f.size, f.modified_at, f.missing_since IS NOT NULL, f.last_error, (SELECT COUNT(*) FROM log_entries_index e WHERE e.log_file_id = f.id AND e.start_offset >= c.read_offset) FROM log_files f JOIN read_cursors c ON c.log_file_id = f.id ORDER BY f.relative_path", ) .fetch_all(pool) .await?; let now = time::OffsetDateTime::now_utc().unix_timestamp(); let mut summary = Summary { total: 0, now, projects: Vec::with_capacity(projects.len()), }; for ( id, name, root_path, refresh_seconds, hide_after_days, log_dirs, error, vhost_path, vhost_error, ) in projects { let project_ok = error.is_none(); let hide_after_days = hide_after_days.map(|d| d as u32); let (hidden, visible): (Vec<&FileRow>, Vec<&FileRow>) = files .iter() .filter(|f| f.1 == id) .partition(|f| is_hidden(f.6, now, hide_after_days)); let files: Vec = visible .into_iter() .map( |(fid, _, rel, kind, format, size, modified, missing, ferr, unread)| { let kind = LogKind::parse(kind).unwrap_or_default(); let notifies = format .as_deref() .and_then(LogFormat::parse) .is_none_or(LogFormat::notifies); let counted = !*missing && notifies && (project_ok || kind != LogKind::Project); FileSummary { id: *fid, kind, relative_path: rel.clone(), size: *size as u64, modified: *modified, missing: *missing, error: ferr.clone(), unread: if counted { *unread as u64 } else { 0 }, } }, ) .collect(); let unread = files.iter().map(|f| f.unread).sum(); summary.total += unread; summary.projects.push(ProjectSummary { id, name, root_path, refresh_seconds: refresh_seconds as u32, hide_after_days, hidden_files: hidden.len() as u32, log_dirs: parse_log_dirs(&log_dirs), error, vhost_path, vhost_error, unread, files, }); } Ok(summary) }