diff --git a/src/db.rs b/src/db.rs index 6bbf9d3..aa2e582 100644 --- a/src/db.rs +++ b/src/db.rs @@ -131,13 +131,36 @@ pub struct UploadLogRow { pub expires_at: Option, } +/// What an `upload_log` row records; `as_str()` is the stored `kind` value. +/// Also the `kind` query parameter of `/api/pastes` (one dashboard section each). +#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Deserialize)] +#[serde(rename_all = "lowercase")] +pub enum UploadKind { + Paste, + File, + Url, +} + +impl UploadKind { + /// Dashboard section order. + pub const ALL: [UploadKind; 3] = [UploadKind::Paste, UploadKind::File, UploadKind::Url]; + + pub fn as_str(self) -> &'static str { + match self { + UploadKind::Paste => "paste", + UploadKind::File => "file", + UploadKind::Url => "url", + } + } +} + pub struct NewUploadLog<'a> { pub id: &'a str, pub user_sub: &'a str, pub email: &'a str, pub display_name: &'a str, pub paste_url: &'a str, - pub kind: &'a str, + pub kind: UploadKind, pub encrypted: bool, pub created_at: i64, pub expires_at: Option, @@ -154,7 +177,7 @@ pub async fn insert_upload_log(db: &Db, u: NewUploadLog<'_>) -> sqlx::Result<()> .bind(u.email) .bind(u.display_name) .bind(u.paste_url) - .bind(u.kind) + .bind(u.kind.as_str()) .bind(u.encrypted) .bind(u.created_at) .bind(u.expires_at) @@ -163,11 +186,12 @@ pub async fn insert_upload_log(db: &Db, u: NewUploadLog<'_>) -> sqlx::Result<()> Ok(()) } -/// Keyset pagination: returns up to `limit` rows for `user_sub` older than `before_created_at` -/// (or the most recent rows if `before_created_at` is `None`), newest first. +/// Keyset pagination: returns up to `limit` rows of `kind` for `user_sub` older than +/// `before_created_at` (or the most recent rows if `before_created_at` is `None`), newest first. pub async fn list_uploads_page( db: &Db, user_sub: &str, + kind: UploadKind, before_created_at: Option, limit: i64, ) -> sqlx::Result> { @@ -175,10 +199,11 @@ pub async fn list_uploads_page( Some(before) => { sqlx::query_as::<_, UploadLogRow>( "SELECT * FROM upload_log - WHERE user_sub = ? AND created_at < ? + WHERE user_sub = ? AND kind = ? AND created_at < ? ORDER BY created_at DESC LIMIT ?", ) .bind(user_sub) + .bind(kind.as_str()) .bind(before) .bind(limit) .fetch_all(db) @@ -187,10 +212,11 @@ pub async fn list_uploads_page( None => { sqlx::query_as::<_, UploadLogRow>( "SELECT * FROM upload_log - WHERE user_sub = ? + WHERE user_sub = ? AND kind = ? ORDER BY created_at DESC LIMIT ?", ) .bind(user_sub) + .bind(kind.as_str()) .bind(limit) .fetch_all(db) .await @@ -217,3 +243,57 @@ pub async fn delete_upload_log(db: &Db, id: &str) -> sqlx::Result<()> { .await?; Ok(()) } + +#[cfg(test)] +mod tests { + use super::*; + + async fn insert(db: &Db, id: &str, user_sub: &str, kind: UploadKind, created_at: i64) { + insert_upload_log( + db, + NewUploadLog { + id, + user_sub, + email: "someone@example.com", + display_name: id, + paste_url: "https://paste.example.com/x.txt", + kind, + encrypted: false, + created_at, + expires_at: None, + }, + ) + .await + .unwrap(); + } + + fn ids(rows: Vec) -> Vec { + rows.into_iter().map(|r| r.id).collect() + } + + #[tokio::test] + async fn list_uploads_page_filters_by_kind_and_paginates() { + // A file, not `:memory:`: each pooled connection would get its own empty DB. + let path = std::env::temp_dir().join(format!("watari-test-{}.db", uuid::Uuid::new_v4())); + let db = connect(path.to_str().unwrap()).await.unwrap(); + + insert(&db, "a", "alice", UploadKind::Paste, 1).await; + insert(&db, "b", "alice", UploadKind::File, 2).await; + insert(&db, "c", "alice", UploadKind::Paste, 3).await; + insert(&db, "d", "alice", UploadKind::Url, 4).await; + insert(&db, "e", "alice", UploadKind::Paste, 5).await; + insert(&db, "z", "bob", UploadKind::Paste, 6).await; + + let first = list_uploads_page(&db, "alice", UploadKind::Paste, None, 2).await; + assert_eq!(ids(first.unwrap()), ["e", "c"]); + let next = list_uploads_page(&db, "alice", UploadKind::Paste, Some(3), 2).await; + assert_eq!(ids(next.unwrap()), ["a"]); + let files = list_uploads_page(&db, "alice", UploadKind::File, None, 20).await; + assert_eq!(ids(files.unwrap()), ["b"]); + let urls = list_uploads_page(&db, "alice", UploadKind::Url, None, 20).await; + assert_eq!(ids(urls.unwrap()), ["d"]); + + db.close().await; + let _ = std::fs::remove_file(&path); + } +} diff --git a/src/routes/api.rs b/src/routes/api.rs index 20eae70..580fdb5 100644 --- a/src/routes/api.rs +++ b/src/routes/api.rs @@ -5,6 +5,7 @@ use axum::response::{IntoResponse, Response}; use axum_csrf::CsrfToken; use serde::Deserialize; +use crate::db::UploadKind; use crate::error::AppError; use crate::rustypaste::{FileMode, RustypasteError, UrlMode}; use crate::session::UserSession; @@ -13,7 +14,7 @@ use crate::templates::Tpl; use crate::token_map::Permission; use crate::{csrf, db}; -use super::pages::{LoadMoreTemplate, PAGE_SIZE, PasteRowsTemplate, UploadRowView}; +use super::pages::{LoadMoreTemplate, PasteRowsTemplate, load_section_page}; #[derive(Template)] #[template(path = "partials/flash.html")] @@ -172,7 +173,7 @@ async fn log_upload( session: &UserSession, display_name: &str, paste_url: &str, - kind: &str, + kind: UploadKind, encrypted: bool, expire: &Option, ) { @@ -251,7 +252,7 @@ pub async fn upload( &session, &filename, &url, - "file", + UploadKind::File, encrypted, &parsed.expire, ) @@ -325,7 +326,7 @@ pub async fn paste( &session, &display_name, &url, - "paste", + UploadKind::Paste, encrypted, &parsed.expire, ) @@ -380,7 +381,7 @@ pub async fn shorten( &session, &url, &short_url, - "url", + UploadKind::Url, false, &parsed.expire, ) @@ -418,7 +419,7 @@ pub async fn shorten( &session, &filename, &url, - "url", + UploadKind::Url, encrypted, &parsed.expire, ) @@ -505,6 +506,8 @@ pub async fn delete_paste( #[derive(Deserialize)] pub struct PastesQuery { + /// Which dashboard section is paginating. + kind: UploadKind, before: Option, } @@ -513,24 +516,25 @@ pub async fn list_pastes( session: UserSession, Query(query): Query, ) -> Response { - let db_rows = db::list_uploads_page(&state.db, &session.user_sub, query.before, PAGE_SIZE) - .await - .unwrap_or_default(); - let has_more = db_rows.len() as i64 == PAGE_SIZE; - let next_cursor = db_rows.last().map(|r| r.created_at); - let rows: Vec = db_rows.iter().map(UploadRowView::from).collect(); + let kind = query.kind; + let page = load_section_page(&state, &session.user_sub, kind, query.before).await; let can_delete = state .token_map .get(&session.token_id) .map(|b| b.has(Permission::Delete)) .unwrap_or(false); - let rows_html = PasteRowsTemplate { rows, can_delete } - .render() - .unwrap_or_default(); + let rows_html = PasteRowsTemplate { + kind, + rows: page.rows, + can_delete, + } + .render() + .unwrap_or_default(); let load_more_html = LoadMoreTemplate { - has_more, - next_cursor, + kind, + has_more: page.has_more, + next_cursor: page.next_cursor, } .render() .unwrap_or_default(); diff --git a/src/routes/pages.rs b/src/routes/pages.rs index 846a7e5..1f23a70 100644 --- a/src/routes/pages.rs +++ b/src/routes/pages.rs @@ -18,14 +18,89 @@ pub struct UploadRowView { pub id: String, pub display_name: String, pub paste_url: String, - pub kind: String, pub encrypted: bool, - pub created_at_display: String, + /// RFC 3339 (UTC); `static/app.js` turns it into "14:05" / "3 days ago" in + /// the viewer's timezone. + pub created_at_iso: String, +} + +/// Dashboard wording for each section (one per `UploadKind`). +impl db::UploadKind { + pub fn title(self) -> &'static str { + match self { + db::UploadKind::Paste => "Pastes", + db::UploadKind::File => "Uploads", + db::UploadKind::Url => "Short URLs", + } + } + + pub fn name_header(self) -> &'static str { + match self { + db::UploadKind::Paste => "Content", + db::UploadKind::File => "File", + db::UploadKind::Url => "Target", + } + } + + pub fn link_header(self) -> &'static str { + match self { + db::UploadKind::Paste | db::UploadKind::File => "Link", + db::UploadKind::Url => "Short link", + } + } + + /// Singular noun, used in "Delete this …?" and "No …s yet." + pub fn noun(self) -> &'static str { + match self { + db::UploadKind::Paste => "paste", + db::UploadKind::File => "upload", + db::UploadKind::Url => "short URL", + } + } + + pub fn create_page(self) -> &'static str { + match self { + db::UploadKind::Paste => "/paste", + db::UploadKind::File => "/upload", + db::UploadKind::Url => "/shorten", + } + } + + pub fn create_label(self) -> &'static str { + match self { + db::UploadKind::Paste => "Paste some text", + db::UploadKind::File => "Upload a file", + db::UploadKind::Url => "Shorten a URL", + } + } +} + +/// One page of a dashboard section, newest first. +pub struct SectionPage { + pub rows: Vec, + pub has_more: bool, + pub next_cursor: Option, +} + +pub async fn load_section_page( + state: &AppState, + user_sub: &str, + kind: db::UploadKind, + before: Option, +) -> SectionPage { + let db_rows = db::list_uploads_page(&state.db, user_sub, kind, before, PAGE_SIZE) + .await + .unwrap_or_default(); + SectionPage { + has_more: db_rows.len() as i64 == PAGE_SIZE, + next_cursor: db_rows.last().map(|r| r.created_at), + rows: db_rows.iter().map(UploadRowView::from).collect(), + } } impl From<&db::UploadLogRow> for UploadRowView { fn from(row: &db::UploadLogRow) -> Self { - let created_at_display = OffsetDateTime::from_unix_timestamp(row.created_at) + let created_at_iso = OffsetDateTime::from_unix_timestamp(row.created_at) .ok() .and_then(|t| t.format(&Rfc3339).ok()) .unwrap_or_default(); @@ -33,9 +108,8 @@ impl From<&db::UploadLogRow> for UploadRowView { id: row.id.clone(), display_name: row.display_name.clone(), paste_url: row.paste_url.clone(), - kind: row.kind.clone(), encrypted: row.encrypted, - created_at_display, + created_at_iso, } } } @@ -43,6 +117,7 @@ impl From<&db::UploadLogRow> for UploadRowView { #[derive(Template)] #[template(path = "partials/paste_row.html")] pub struct PasteRowsTemplate { + pub kind: db::UploadKind, pub rows: Vec, pub can_delete: bool, } @@ -50,6 +125,7 @@ pub struct PasteRowsTemplate { #[derive(Template)] #[template(path = "partials/load_more.html")] pub struct LoadMoreTemplate { + pub kind: db::UploadKind, pub has_more: bool, pub next_cursor: Option, } @@ -86,14 +162,17 @@ fn layout_for( )) } +struct DashboardSection { + kind: db::UploadKind, + page: SectionPage, +} + #[derive(Template)] #[template(path = "dashboard.html")] struct DashboardTemplate { layout: Layout, - rows: Vec, + sections: Vec, can_delete: bool, - has_more: bool, - next_cursor: Option, } pub async fn dashboard( @@ -106,21 +185,18 @@ pub async fn dashboard( Err(e) => return crate::error::AppError::Internal(e).into_response(), }; - let db_rows = db::list_uploads_page(&state.db, &session.user_sub, None, PAGE_SIZE) - .await - .unwrap_or_default(); - let has_more = db_rows.len() as i64 == PAGE_SIZE; - let next_cursor = db_rows.last().map(|r| r.created_at); - let rows = db_rows.iter().map(UploadRowView::from).collect(); + let mut sections = Vec::with_capacity(db::UploadKind::ALL.len()); + for kind in db::UploadKind::ALL { + let page = load_section_page(&state, &session.user_sub, kind, None).await; + sections.push(DashboardSection { kind, page }); + } ( csrf_token, Tpl(DashboardTemplate { layout, - rows, + sections, can_delete: can_delete(&state, &session.token_id), - has_more, - next_cursor, }), ) .into_response() diff --git a/static/app.css b/static/app.css index 890f73a..e97f854 100644 --- a/static/app.css +++ b/static/app.css @@ -167,6 +167,13 @@ main { h1 { font-size: 1.4rem; } +/* --- Dashboard sections --- */ +.dashboard-section { margin-top: 2rem; } +.dashboard-section h2 { font-size: 1.1rem; margin: 0; } +.dashboard-section .upload-table { margin-top: 0.5rem; } +.empty-state { margin: 0.5rem 0 0; font-size: 0.9rem; opacity: 0.7; } +.dashboard-section [id^="load-more-"] button { margin-top: 0.75rem; } + /* --- Home page --- */ .home p, .home ul { max-width: 42rem; line-height: 1.55; } diff --git a/static/app.js b/static/app.js index 58da3ea..99a0ba6 100644 --- a/static/app.js +++ b/static/app.js @@ -108,6 +108,51 @@ document.addEventListener("click", (e) => { if (text) navigator.clipboard?.writeText(text); }); +// --- Human-friendly timestamps (dashboard "Created" column) --- +// The server renders