Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
92 changes: 86 additions & 6 deletions src/db.rs
Original file line number Diff line number Diff line change
Expand Up @@ -131,13 +131,36 @@ pub struct UploadLogRow {
pub expires_at: Option<i64>,
}

/// 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<i64>,
Expand All @@ -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)
Expand All @@ -163,22 +186,24 @@ 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<i64>,
limit: i64,
) -> sqlx::Result<Vec<UploadLogRow>> {
match before_created_at {
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)
Expand All @@ -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
Expand All @@ -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<UploadLogRow>) -> Vec<String> {
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);
}
}
38 changes: 21 additions & 17 deletions src/routes/api.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -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")]
Expand Down Expand Up @@ -172,7 +173,7 @@ async fn log_upload(
session: &UserSession,
display_name: &str,
paste_url: &str,
kind: &str,
kind: UploadKind,
encrypted: bool,
expire: &Option<String>,
) {
Expand Down Expand Up @@ -251,7 +252,7 @@ pub async fn upload(
&session,
&filename,
&url,
"file",
UploadKind::File,
encrypted,
&parsed.expire,
)
Expand Down Expand Up @@ -325,7 +326,7 @@ pub async fn paste(
&session,
&display_name,
&url,
"paste",
UploadKind::Paste,
encrypted,
&parsed.expire,
)
Expand Down Expand Up @@ -380,7 +381,7 @@ pub async fn shorten(
&session,
&url,
&short_url,
"url",
UploadKind::Url,
false,
&parsed.expire,
)
Expand Down Expand Up @@ -418,7 +419,7 @@ pub async fn shorten(
&session,
&filename,
&url,
"url",
UploadKind::Url,
encrypted,
&parsed.expire,
)
Expand Down Expand Up @@ -505,6 +506,8 @@ pub async fn delete_paste(

#[derive(Deserialize)]
pub struct PastesQuery {
/// Which dashboard section is paginating.
kind: UploadKind,
before: Option<i64>,
}

Expand All @@ -513,24 +516,25 @@ pub async fn list_pastes(
session: UserSession,
Query(query): Query<PastesQuery>,
) -> 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<UploadRowView> = 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();
Expand Down
Loading
Loading