diff --git a/crates/in-core/migrations/0004_downloads_settings.sql b/crates/in-core/migrations/0004_downloads_settings.sql new file mode 100644 index 0000000..3644218 --- /dev/null +++ b/crates/in-core/migrations/0004_downloads_settings.sql @@ -0,0 +1,19 @@ +-- Per-file download counts and instance-level key/value settings. +-- +-- `file.download_count` counts user-facing byte serves: the download route +-- and the public-link bytes bump it through `record_download`, and nothing +-- internal — thumbnails, sniffing, the boot sweep — ever touches it. The +-- DEFAULT is the backfill: SQLite fills every existing row with 0 as the +-- column is added. Databases already carrying the column never see this file +-- applied piecemeal — they reach the declared shape through `in reconcile`, +-- whose copy map backfills the same value. +-- +-- `setting` is the instance's key/value drawer, one row per key, read and +-- written through `get_setting`/`set_setting`. A fresh table, so an old +-- database simply gains it empty on rebuild. +ALTER TABLE file ADD COLUMN download_count INTEGER NOT NULL DEFAULT 0; + +CREATE TABLE setting ( + key TEXT PRIMARY KEY, + value TEXT NOT NULL +); diff --git a/crates/in-core/src/config.rs b/crates/in-core/src/config.rs index d231918..87f9f9c 100644 --- a/crates/in-core/src/config.rs +++ b/crates/in-core/src/config.rs @@ -60,6 +60,10 @@ live_seconds = 300 purge_after_days = 30 # The quota a newly provisioned account starts on, in bytes. 10 GiB. default_quota_bytes = 10737418240 +# The default per-file upload ceiling, in bytes. 1 GiB. An admin can move it +# from the settings page without touching this file; this key is only the +# default the stored setting falls back to. +max_upload_bytes = 1073741824 # Where drive files, thumbnails and staged upload chunks live as files, # created on boot. Not written here: it defaults to beside the database file, # and the boot completes this file with the value it resolved. @@ -101,6 +105,10 @@ const DEFAULT_PURGE_AFTER_DAYS: u32 = 30; /// The quota a newly provisioned account starts on: 10 GiB. const DEFAULT_QUOTA_BYTES: u64 = 10 * 1024 * 1024 * 1024; +/// The per-file upload ceiling when neither the stored setting nor the config +/// key names one: 1 GiB. +const DEFAULT_MAX_UPLOAD_BYTES: u64 = 1024 * 1024 * 1024; + /// Every completable top-level key, with the comment and default a file /// missing it is completed with. `database` is not here: it has no default /// worth guessing, so its absence stops the boot instead. `storage` is @@ -140,6 +148,15 @@ const OPTIONAL_KEYS: &[(&str, &str)] = &[ "default_quota_bytes = 10737418240\n" ), ), + ( + "max_upload_bytes", + concat!( + "# The default per-file upload ceiling, in bytes. 1 GiB. The settings\n", + "# page stores the live value in the database; this key is only the\n", + "# default it falls back to.\n", + "max_upload_bytes = 1073741824\n" + ), + ), ]; /// The `[oidc]` table of `config/in.toml`, before the values are checked. @@ -166,6 +183,7 @@ struct Toml { live_seconds: Option, purge_after_days: Option, default_quota_bytes: Option, + max_upload_bytes: Option, oidc: Option, #[serde(flatten)] other: std::collections::BTreeMap, @@ -206,6 +224,9 @@ pub struct Config { pub purge_after_days: u32, /// The quota a newly provisioned account starts on, in bytes. pub default_quota_bytes: u64, + /// The default per-file upload ceiling, in bytes. The settings page's + /// live value wins over this; this is only what an unset install enforces. + pub max_upload_bytes: u64, /// The OIDC provider In trusts. pub oidc: OidcConfig, /// Keys the file sets that nothing here reads, in the order the file @@ -334,6 +355,12 @@ impl Config { let purge_after_days = toml.purge_after_days.unwrap_or(DEFAULT_PURGE_AFTER_DAYS); let default_quota_bytes = toml.default_quota_bytes.unwrap_or(DEFAULT_QUOTA_BYTES); + // Zero names no usable ceiling — it would refuse every upload — so it + // reads as unset and falls through to the 1 GiB default. + let max_upload_bytes = toml + .max_upload_bytes + .filter(|limit| *limit > 0) + .unwrap_or(DEFAULT_MAX_UPLOAD_BYTES); let oidc_toml = toml.oidc.ok_or(ConfigError::Missing("[oidc]"))?; let issuer = value(oidc_toml.issuer).ok_or(ConfigError::Missing("oidc.issuer"))?; @@ -355,6 +382,7 @@ impl Config { live_seconds, purge_after_days, default_quota_bytes, + max_upload_bytes, oidc: OidcConfig { issuer, client_id, @@ -588,6 +616,7 @@ mod tests { const FULL: &str = r#"database = "in.db" listen = "127.0.0.1:7655" live_seconds = 300 +max_upload_bytes = 1073741824 purge_after_days = 30 default_quota_bytes = 10737418240 [oidc] @@ -628,6 +657,7 @@ client_secret = "s3cret" assert_eq!(config.live_seconds, 300); assert_eq!(config.purge_after_days, 30); assert_eq!(config.default_quota_bytes, 10 * 1024 * 1024 * 1024); + assert_eq!(config.max_upload_bytes, 1024 * 1024 * 1024); assert_eq!(config.oidc.issuer, "https://id.example.com"); assert_eq!( config.oidc.redirect_uri, @@ -743,4 +773,39 @@ client_secret = "s3cret" .join("storage") ); } + + #[test] + fn an_explicit_max_upload_bytes_wins_and_absence_defaults_to_1gib() { + let scratch = Scratch::new(); + scratch.write(&FULL.replace( + "max_upload_bytes = 1073741824", + "max_upload_bytes = 67108864", + )); + assert_eq!(scratch.load().unwrap().max_upload_bytes, 67108864); + // A file silent about the key still loads, at the 1 GiB default, and + // is completed with the key for the next boot to read. + let scratch = Scratch::new(); + scratch.write(&FULL.replace("max_upload_bytes = 1073741824\n", "")); + assert_eq!( + scratch.load().unwrap().max_upload_bytes, + 1024 * 1024 * 1024 + ); + let completed = std::fs::read_to_string(scratch.dir.join(FILE_NAME)).unwrap(); + assert!(completed.contains("max_upload_bytes = 1073741824")); + } + + #[test] + fn zero_max_upload_bytes_reads_as_unset() { + // Zero names no usable ceiling — it would refuse every upload — so it + // falls through to the 1 GiB default instead of becoming the limit. + let scratch = Scratch::new(); + scratch.write(&FULL.replace( + "max_upload_bytes = 1073741824", + "max_upload_bytes = 0", + )); + assert_eq!( + scratch.load().unwrap().max_upload_bytes, + 1024 * 1024 * 1024 + ); + } } diff --git a/crates/in-core/src/store/mod.rs b/crates/in-core/src/store/mod.rs index a9439c9..5e446b1 100644 --- a/crates/in-core/src/store/mod.rs +++ b/crates/in-core/src/store/mod.rs @@ -134,6 +134,10 @@ pub struct File { /// What the server decided the bytes are, never what the upload claimed. pub mime: String, pub size_bytes: u64, + /// How many times the bytes went to a reader: the download route and the + /// public-link bytes bump it through [`Store::record_download`], and + /// nothing internal — thumbnails, sniffing, the boot sweep — ever does. + pub download_count: u64, pub thumb_state: ThumbState, pub created_at: OffsetDateTime, pub updated_at: OffsetDateTime, @@ -390,7 +394,8 @@ pub trait Store: 'static + Send + Sync { /// means for its screen. async fn folder(&self, id: &str) -> Result>; - /// Renames a folder. A name a live sibling wears is [`StoreError::NameTaken`]. + /// Renames a folder. Names are labels, never identities: a live sibling + /// may already wear the name, and the rename still lands. async fn rename_folder(&self, id: &str, name: &str) -> Result<()>; /// Moves a folder. Into its own descendant is [`StoreError::Cycle`]; @@ -445,6 +450,13 @@ pub trait Store: 'static + Send + Sync { /// when no thumbnail was made, or its file went missing. async fn thumb_bytes(&self, id: &str) -> Result>>; + /// Counts one user-facing serve of a file's bytes. Byte routes call this + /// once per download they complete — not per range chunk, not per + /// thumbnail, never from internal reads (sniffing, the boot sweep). + /// [`Store::file_bytes`] is a pure read and does not call it. Unknown + /// ids are [`StoreError::NotFound`]. + async fn record_download(&self, id: &str) -> Result<()>; + // -- trash ------------------------------------------------------------- /// Everything the person trashed and has not purged: folders and files @@ -459,7 +471,9 @@ pub trait Store: 'static + Send + Sync { /// Restores a trashed folder and everything under it that it took with /// it — descendants wearing the folder's own trash timestamp. Anything /// trashed individually before the folder keeps its earlier moment and - /// stays trashed. Same refusals as [`Store::restore_file`]. + /// stays trashed. Refused with [`StoreError::AncestorTrashed`] while any + /// ancestor folder is still trashed; a live sibling wearing the name is + /// no refusal — folder names may repeat. async fn restore_folder(&self, id: &str) -> Result<()>; /// Purges one trashed file for good: the row goes and the bytes and @@ -611,6 +625,16 @@ pub trait Store: 'static + Send + Sync { /// The boot sweep calls this with now; a janitor may call it any time. async fn prune_expired_uploads(&self, now: OffsetDateTime) -> Result; + // -- instance settings ------------------------------------------------- + + /// One instance-level setting, by key. `None` when the key was never + /// set — the caller owns the default, not the row. + async fn get_setting(&self, key: &str) -> Result>; + + /// Writes one instance-level setting, creating or replacing the row. + /// Keys are free-form; the web layer is the only writer today. + async fn set_setting(&self, key: &str, value: &str) -> Result<()>; + // -- search ------------------------------------------------------------ /// Owner-scoped substring search over live file and folder names, files diff --git a/crates/in-core/src/store/reconcile.rs b/crates/in-core/src/store/reconcile.rs index 74a2529..bc3582c 100644 --- a/crates/in-core/src/store/reconcile.rs +++ b/crates/in-core/src/store/reconcile.rs @@ -204,10 +204,18 @@ struct TableMap { /// Builds the explicit column map. Unchanged tables map every column to its /// old self; the user table carries the migration-specific expressions for -/// `ui`, `theme` and `language`: a database old enough to predate a column -/// starts on the schema's own default rather than on an empty string, which -/// no writer would ever store and no reader would ever honour. -fn build_maps(old_has_ui: bool, old_has_theme: bool, old_has_language: bool) -> Vec { +/// `ui`, `theme` and `language`, and the file table one for +/// `download_count`: a database old enough to predate a column starts on the +/// schema's own default rather than on an empty string, which no writer +/// would ever store and no reader would ever honour. Tables the old database +/// predates entirely (today: `setting`) map column-for-column and are +/// skipped at copy time, starting empty. +fn build_maps( + old_has_ui: bool, + old_has_theme: bool, + old_has_language: bool, + old_has_download_count: bool, +) -> Vec { vec![ TableMap { name: "user", @@ -254,18 +262,26 @@ fn build_maps(old_has_ui: bool, old_has_theme: bool, old_has_language: bool) -> }, TableMap { name: "file", - columns: old_cols(&[ - "id", - "owner_id", - "folder_id", - "name", - "mime", - "size_bytes", - "thumb_state", - "created_at", - "updated_at", - "deleted_at", - ]), + columns: { + let mut columns = old_cols(&[ + "id", + "owner_id", + "folder_id", + "name", + "mime", + "size_bytes", + "thumb_state", + "created_at", + "updated_at", + "deleted_at", + ]); + columns.push(if old_has_download_count { + ("download_count", "old.download_count".into()) + } else { + ("download_count", "0".into()) + }); + columns + }, }, TableMap { name: "share_link", @@ -300,6 +316,10 @@ fn build_maps(old_has_ui: bool, old_has_theme: bool, old_has_language: bool) -> "expires_at", ]), }, + TableMap { + name: "setting", + columns: old_cols(&["key", "value"]), + }, ] } @@ -391,7 +411,13 @@ async fn copy_data(old_conn: &Connection, new_conn: &Connection, path: &str) -> let old_has_ui = old_has_column(old_conn, "user", "ui").await?; let old_has_theme = old_has_column(old_conn, "user", "theme").await?; let old_has_language = old_has_column(old_conn, "user", "language").await?; - let maps = build_maps(old_has_ui, old_has_theme, old_has_language); + let old_has_download_count = old_has_column(old_conn, "file", "download_count").await?; + let maps = build_maps( + old_has_ui, + old_has_theme, + old_has_language, + old_has_download_count, + ); validate_maps(new_conn, &maps).await?; // Foreign keys stay off during the copy and are checked by `verify` @@ -403,6 +429,11 @@ async fn copy_data(old_conn: &Connection, new_conn: &Connection, path: &str) -> .await .map_err(|e| StoreError::Backend(e.to_string()))?; for map in maps { + // A table the old database predates entirely (today: `setting`) + // has no rows to copy; it starts empty in the rebuilt file. + if !old_has_table(old_conn, map.name).await? { + continue; + } let cols = map .columns .iter() @@ -496,9 +527,16 @@ async fn verify(old_conn: &Connection, new_conn: &Connection) -> Result<()> { "share_link", "share_user", "upload_session", + "setting", ]; for table in tables { - let old_count = count_rows(old_conn, table).await?; + // A table the old database predates starts empty: 0 old rows is + // the count a missing table would have kept. + let old_count = if old_has_table(old_conn, table).await? { + count_rows(old_conn, table).await? + } else { + 0 + }; let new_count = count_rows(new_conn, table).await?; if old_count != new_count { return Err(StoreError::Backend(format!( @@ -597,3 +635,21 @@ async fn old_has_column(conn: &Connection, table: &str, column: &str) -> Result< } Ok(false) } + +/// A probe the copy plan asks: whether the old database carries `table` at +/// all. A table a later migration added is absent on a database old enough +/// to predate it; its copy is skipped and its verify count starts at 0. +async fn old_has_table(conn: &Connection, table: &str) -> Result { + let mut rows = conn + .query( + "SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = ?1", + turso::params![table], + ) + .await + .map_err(|e| StoreError::Backend(e.to_string()))?; + Ok(rows + .next() + .await + .map_err(|e| StoreError::Backend(e.to_string()))? + .is_some()) +} diff --git a/crates/in-core/src/store/schema.rs b/crates/in-core/src/store/schema.rs index e0db0f8..faf3e7d 100644 --- a/crates/in-core/src/store/schema.rs +++ b/crates/in-core/src/store/schema.rs @@ -17,6 +17,7 @@ pub(crate) const MIGRATIONS: &[&str] = &[ include_str!("../../migrations/0001_init.sql"), include_str!("../../migrations/0002_ui.sql"), include_str!("../../migrations/0003_preferences.sql"), + include_str!("../../migrations/0004_downloads_settings.sql"), ]; /// The whole declared schema — every migration applied in order — as one diff --git a/crates/in-core/src/store/turso_store.rs b/crates/in-core/src/store/turso_store.rs index 00adbe9..591fdb2 100644 --- a/crates/in-core/src/store/turso_store.rs +++ b/crates/in-core/src/store/turso_store.rs @@ -39,7 +39,7 @@ const USER_COLUMNS: &str = "id, oidc_sub, email, display_name, admin, disabled, quota_bytes, used_bytes, ui, created_at, last_seen_at, theme, language"; const FOLDER_COLUMNS: &str = "id, owner_id, parent_id, name, created_at, deleted_at"; const FILE_COLUMNS: &str = - "id, owner_id, folder_id, name, mime, size_bytes, thumb_state, created_at, updated_at, deleted_at"; + "id, owner_id, folder_id, name, mime, size_bytes, thumb_state, created_at, updated_at, deleted_at, download_count"; const LINK_COLUMNS: &str = "id, token_hash, kind, target_id, created_by, can_download, created_at, expires_at, revoked_at"; const SESSION_COLUMNS: &str = @@ -743,6 +743,7 @@ fn file_from(row: &Row) -> Result { name: text(row, 3)?, mime: text(row, 4)?, size_bytes: row.get::(5).map_err(backend)?.max(0) as u64, + download_count: row.get::(10).map_err(backend)?.max(0) as u64, thumb_state: ThumbState::parse(&text(row, 6)?)?, created_at: parse_stamp(&text(row, 7)?)?, updated_at: parse_stamp(&text(row, 8)?)?, @@ -982,18 +983,15 @@ impl Store for TursoStore { name: &str, ) -> Result { let name = label_of(name); - // IMMEDIATE: the name check is read-then-write. Two concurrent - // creates of one name each read no sibling, each pass, and the pair - // leaves two folders with one name. + // IMMEDIATE: the parent check and the insert are one write set, so a + // parent trashed mid-create still refuses. Names are not checked: + // two folders may wear one name in one place. let mut conn = self.tx_conn().await?; let tx = conn .transaction_with_behavior(TransactionBehavior::Immediate) .await .map_err(backend)?; check_live_parent(&tx, owner_id, parent_id).await?; - if folder_name_taken(&tx, owner_id, parent_id, &name, None).await? { - return Err(StoreError::NameTaken); - } let id = Ulid::new().to_string(); let now = now_text()?; tx.execute( @@ -1037,11 +1035,6 @@ impl Store for TursoStore { if folder.deleted_at.is_some() { return Err(StoreError::NotFound); } - if folder_name_taken(&tx, &folder.owner_id, folder.parent_id.as_deref(), &name, Some(id)) - .await? - { - return Err(StoreError::NameTaken); - } tx.execute("UPDATE folder SET name = ?1 WHERE id = ?2", params![name, id]) .await .map_err(|e| map_constraint(e, StoreError::NameTaken))?; @@ -1073,9 +1066,6 @@ impl Store for TursoStore { } cursor = parent_of(&tx, ¤t).await?; } - if folder_name_taken(&tx, &folder.owner_id, parent_id, &folder.name, Some(id)).await? { - return Err(StoreError::NameTaken); - } tx.execute( "UPDATE folder SET parent_id = ?1 WHERE id = ?2", params![parent_id, id], @@ -1402,6 +1392,50 @@ impl Store for TursoStore { } } + async fn record_download(&self, id: &str) -> Result<()> { + let conn = self.conn.lock().await; + let mut rows = conn + .query("SELECT owner_id FROM file WHERE id = ?1", params![id]) + .await + .map_err(backend)?; + let owner = match rows.next().await.map_err(backend)? { + Some(row) => text(&row, 0)?, + None => return Err(StoreError::NotFound), + }; + drop(rows); + conn.execute( + "UPDATE file SET download_count = download_count + 1 WHERE id = ?1", + params![id], + ) + .await + .map_err(backend)?; + drop(conn); + self.announce([Topic::Library(owner)]); + Ok(()) + } + + async fn get_setting(&self, key: &str) -> Result> { + match self + .one_row("SELECT value FROM setting WHERE key = ?1", params![key]) + .await? + { + Some(row) => Ok(Some(text(&row, 0)?)), + None => Ok(None), + } + } + + async fn set_setting(&self, key: &str, value: &str) -> Result<()> { + let conn = self.conn.lock().await; + conn.execute( + "INSERT INTO setting (key, value) VALUES (?1, ?2) \ + ON CONFLICT (key) DO UPDATE SET value = excluded.value", + params![key, value], + ) + .await + .map_err(backend)?; + Ok(()) + } + async fn thumb_bytes(&self, id: &str) -> Result>> { let conn = self.conn.lock().await; let mut rows = conn @@ -1519,17 +1553,6 @@ impl Store for TursoStore { if let Some(parent_id) = folder.parent_id.as_deref() { ancestor_trashed(&tx, parent_id).await?; } - if folder_name_taken( - &tx, - &folder.owner_id, - folder.parent_id.as_deref(), - &folder.name, - Some(id), - ) - .await? - { - return Err(StoreError::NameTaken); - } let now = now_text()?; // Only the cascade comes back: descendants wear the folder's own // trash timestamp when the folder took them with it, while anything @@ -2532,43 +2555,10 @@ async fn check_live_parent_on( check_live_parent(conn, owner_id, parent_id).await } -/// Whether a live sibling folder already wears `name`. Trashed rows do not +/// Whether a live sibling file already wears `name`. Trashed rows do not /// count — deleting a name frees it — and `exclude` skips the row being -/// renamed or moved. -async fn folder_name_taken( - conn: &Connection, - owner_id: &str, - parent_id: Option<&str>, - name: &str, - exclude: Option<&str>, -) -> Result { - let exclude = exclude.unwrap_or(""); - let mut rows = match parent_id { - Some(parent) => { - conn.query( - "SELECT 1 FROM folder WHERE owner_id = ?1 AND parent_id = ?2 \ - AND name = ?3 AND deleted_at IS NULL AND id <> ?4", - params![owner_id, parent, name, exclude], - ) - .await - .map_err(backend)? - } - None => { - conn.query( - "SELECT 1 FROM folder WHERE owner_id = ?1 AND parent_id IS NULL \ - AND name = ?2 AND deleted_at IS NULL AND id <> ?3", - params![owner_id, name, exclude], - ) - .await - .map_err(backend)? - } - }; - Ok(rows.next().await.map_err(backend)?.is_some()) -} - -/// Whether a live sibling file already wears `name`, same rules as -/// [`folder_name_taken`]. Folders and files keep separate namespaces: a -/// folder and a file may share a name in one directory. +/// renamed or moved. Folders and files keep separate namespaces: a folder +/// and a file may share a name in one directory. async fn file_name_taken( conn: &Connection, owner_id: &str, diff --git a/crates/in-core/tests/store.rs b/crates/in-core/tests/store.rs index 9f7d4eb..9db63c7 100644 --- a/crates/in-core/tests/store.rs +++ b/crates/in-core/tests/store.rs @@ -169,7 +169,7 @@ async fn quota_and_disablement_round_trip() { } #[tokio::test] -async fn folders_nest_and_names_are_unique_among_live_siblings() { +async fn folders_allow_duplicate_names_among_live_siblings() { let scratch = Scratch::open().await; let user = alice(&scratch.store).await; let root = scratch @@ -184,11 +184,10 @@ async fn folders_nest_and_names_are_unique_among_live_siblings() { .unwrap(); assert_eq!(kid.parent_id.as_deref(), Some(root.id.as_str())); - assert!(matches!( - scratch.store.create_folder(&user.id, None, "root").await, - Err(StoreError::NameTaken) - )); - // Same name in a different directory is a different name. + // A live sibling wearing the name is no refusal: folders share names. + let twin = scratch.store.create_folder(&user.id, None, "root").await.unwrap(); + assert_ne!(twin.id, root.id); + // Same name in a different directory is a different name, as before. scratch .store .create_folder(&user.id, Some(&root.id), "root") @@ -196,7 +195,7 @@ async fn folders_nest_and_names_are_unique_among_live_siblings() { .unwrap(); let listing = scratch.store.list_children(&user.id, None).await.unwrap(); - assert_eq!(listing.folders.len(), 1); + assert_eq!(listing.folders.len(), 2); let listing = scratch .store .list_children(&user.id, Some(&root.id)) @@ -508,19 +507,18 @@ async fn trashing_a_folder_cascades_and_restore_needs_live_ancestors() { } #[tokio::test] -async fn a_trashed_name_is_free_until_restored() { +async fn a_trashed_folder_name_restores_beside_a_live_twin() { let scratch = Scratch::open().await; let user = alice(&scratch.store).await; let first = scratch.store.create_folder(&user.id, None, "x").await.unwrap(); scratch.store.delete_folder(&first.id).await.unwrap(); - // Deleting frees the name; restoring onto a live squatter is refused. + // Deleting frees the name, and restoring beside the squatter is fine: + // folder names may repeat. scratch.store.create_folder(&user.id, None, "x").await.unwrap(); - assert!(matches!( - scratch.store.restore_folder(&first.id).await, - Err(StoreError::NameTaken) - )); + scratch.store.restore_folder(&first.id).await.unwrap(); + let listing = scratch.store.list_children(&user.id, None).await.unwrap(); + assert_eq!(listing.folders.iter().filter(|folder| folder.name == "x").count(), 2); } - #[tokio::test] async fn used_bytes_counts_trash_and_purge_frees_it() { let scratch = Scratch::open().await; @@ -1215,3 +1213,104 @@ async fn a_second_migration_database_gains_the_preference_columns_on_open() { drop(store); let _ = std::fs::remove_dir_all(&dir); } + +#[tokio::test] +async fn renaming_or_moving_a_folder_onto_a_live_sibling_name_succeeds() { + let scratch = Scratch::open().await; + let user = alice(&scratch.store).await; + let parent = scratch.store.create_folder(&user.id, None, "parent").await.unwrap(); + let other = scratch.store.create_folder(&user.id, None, "other").await.unwrap(); + + // Renaming onto a live sibling's name lands. + scratch.store.rename_folder(&other.id, "parent").await.unwrap(); + let back: Folder = scratch.store.folder(&other.id).await.unwrap().unwrap(); + assert_eq!(back.name, "parent"); + + // Moving under a parent is refused for strangers and the trashed, but + // never for a name: a live child wearing the name is no obstacle. + let kid = scratch + .store + .create_folder(&user.id, Some(&parent.id), "kid") + .await + .unwrap(); + scratch.store.create_folder(&user.id, None, "kid").await.unwrap(); + scratch.store.move_folder(&kid.id, None).await.unwrap(); + let back: Folder = scratch.store.folder(&kid.id).await.unwrap().unwrap(); + assert_eq!(back.parent_id, None); + let listing = scratch.store.list_children(&user.id, None).await.unwrap(); + assert_eq!(listing.folders.iter().filter(|folder| folder.name == "kid").count(), 2); +} + +#[tokio::test] +async fn file_names_stay_unique_among_live_siblings() { + let scratch = Scratch::open().await; + let user = alice(&scratch.store).await; + let first = scratch.store.insert_file(&user.id, None, "note", b"one").await.unwrap(); + // A live sibling wearing the name still refuses: files, unlike folders, + // keep one name per directory. + assert!(matches!( + scratch.store.insert_file(&user.id, None, "note", b"two").await, + Err(StoreError::NameTaken) + )); + let other = scratch.store.insert_file(&user.id, None, "other", b"two").await.unwrap(); + assert!(matches!( + scratch.store.rename_file(&other.id, "note").await, + Err(StoreError::NameTaken) + )); + // Trashing frees the name; restoring onto a squatter still refuses. + scratch.store.delete_file(&first.id).await.unwrap(); + scratch.store.insert_file(&user.id, None, "note", b"three").await.unwrap(); + assert!(matches!( + scratch.store.restore_file(&first.id).await, + Err(StoreError::NameTaken) + )); +} + +#[tokio::test] +async fn download_count_starts_at_zero_and_counts_serves() { + let scratch = Scratch::open().await; + let user = alice(&scratch.store).await; + let bytes = b"count me"; + let file = scratch.store.insert_file(&user.id, None, "counted", bytes).await.unwrap(); + assert_eq!(file.download_count, 0); + + // The row agrees: a fresh insert was never served. + let back = scratch.store.file(&file.id).await.unwrap().unwrap(); + assert_eq!(back.download_count, 0); + + scratch.store.record_download(&file.id).await.unwrap(); + scratch.store.record_download(&file.id).await.unwrap(); + let back = scratch.store.file(&file.id).await.unwrap().unwrap(); + assert_eq!(back.download_count, 2); + + // A byte read is pure: it serves the bytes without counting, so range + // probes and chunks never inflate the count — only record_download does. + let served = scratch.store.file_bytes(&file.id).await.unwrap().unwrap(); + assert_eq!(served, bytes); + let back = scratch.store.file(&file.id).await.unwrap().unwrap(); + assert_eq!(back.download_count, 2); + assert!(scratch.store.file_bytes("no-such-file").await.unwrap().is_none()); + assert!(matches!( + scratch.store.record_download("no-such-file").await, + Err(StoreError::NotFound) + )); +} + +#[tokio::test] +async fn settings_round_trip_from_missing() { + let scratch = Scratch::open().await; + let store = &scratch.store; + assert_eq!(store.get_setting("ui.density").await.unwrap(), None); + store.set_setting("ui.density", "ledger").await.unwrap(); + assert_eq!( + store.get_setting("ui.density").await.unwrap(), + Some("ledger".to_string()) + ); + // Replacing the value replaces the row, and other keys are untouched. + store.set_setting("ui.density", "instrument").await.unwrap(); + assert_eq!( + store.get_setting("ui.density").await.unwrap(), + Some("instrument".to_string()) + ); + assert_eq!(store.get_setting("ui.other").await.unwrap(), None); +} diff --git a/crates/in-web/src/drive.rs b/crates/in-web/src/drive.rs index 8a8bb85..8e8646f 100644 --- a/crates/in-web/src/drive.rs +++ b/crates/in-web/src/drive.rs @@ -13,7 +13,7 @@ //! plain GET form. The old `GET /search?q=` address 303s here, so old links //! keep working. -use in_core::store::{Folder, Store, StoreError, ThumbState}; +use in_core::store::{Folder, Store, StoreError}; use topcoat::router::request::uri; use topcoat::router::{HeaderName, HeaderValue, StatusCode, header, page, query_params, route}; @@ -61,6 +61,9 @@ struct DriveQuery { folder: Option, q: Option, edit: Option, + sort: Option, + dir: Option, + kind: Option, } /// The folder the query names, if it names one this account may open: owned, @@ -161,6 +164,129 @@ fn created_token(query: &str) -> Option { (name == "created" && !value.is_empty()).then(|| value.to_string()) }) } +/// The drive listing's sort key: `None` is the standing order — +/// folders-then-files as the store listed them — anything else re-orders +/// each group in place. Unknown values fall back to the standing order, +/// never to a refusal: a hand-edited query names nothing fancy, not an +/// error. +#[derive(Clone, Copy, PartialEq, Eq)] +enum SortKey { + Name, + Uploaded, + Size, + Downloads, +} + +impl SortKey { + fn as_str(self) -> &'static str { + match self { + SortKey::Name => "name", + SortKey::Uploaded => "uploaded", + SortKey::Size => "size", + SortKey::Downloads => "downloads", + } + } +} + +/// The sort direction. Absent or unknown falls back per key — ascending +/// for names, descending for the recency/count keys — the way iz reads. +#[derive(Clone, Copy, PartialEq, Eq)] +enum SortDir { + Asc, + Desc, +} + +impl SortDir { + fn as_str(self) -> &'static str { + match self { + SortDir::Asc => "asc", + SortDir::Desc => "desc", + } + } +} + +/// The kind filter: everything, folders only, files only. +#[derive(Clone, Copy, PartialEq, Eq)] +enum KindFilter { + All, + Folders, + Files, +} + +impl KindFilter { + fn as_str(self) -> &'static str { + match self { + KindFilter::All => "all", + KindFilter::Folders => "folders", + KindFilter::Files => "files", + } + } +} + +fn parse_sort(raw: Option<&str>) -> Option { + match raw.unwrap_or("") { + "name" => Some(SortKey::Name), + "uploaded" => Some(SortKey::Uploaded), + "size" => Some(SortKey::Size), + "downloads" => Some(SortKey::Downloads), + _ => None, + } +} + +fn parse_dir(raw: Option<&str>, key: Option) -> SortDir { + match raw.unwrap_or("") { + "asc" => SortDir::Asc, + "desc" => SortDir::Desc, + _ => match key { + Some(SortKey::Name) | None => SortDir::Asc, + _ => SortDir::Desc, + }, + } +} + +fn parse_kind(raw: Option<&str>) -> KindFilter { + match raw.unwrap_or("") { + "folders" => KindFilter::Folders, + "files" => KindFilter::Files, + _ => KindFilter::All, + } +} + +/// Order one folder group in place. Folders carry no size or download +/// count, so those keys fall back to the name order rather than inventing +/// one; the direction still applies. +fn sort_folders(folders: &mut [Folder], key: SortKey, dir: SortDir) { + folders.sort_by(|a, b| { + let order = match key { + SortKey::Name | SortKey::Size | SortKey::Downloads => { + a.name.to_lowercase().cmp(&b.name.to_lowercase()) + } + SortKey::Uploaded => a.created_at.cmp(&b.created_at), + } + .then_with(|| a.id.cmp(&b.id)); + match dir { + SortDir::Asc => order, + SortDir::Desc => order.reverse(), + } + }); +} + +/// Order one file group in place. +fn sort_files(files: &mut [in_core::store::File], key: SortKey, dir: SortDir) { + files.sort_by(|a, b| { + let order = match key { + SortKey::Name => a.name.to_lowercase().cmp(&b.name.to_lowercase()), + SortKey::Uploaded => a.created_at.cmp(&b.created_at), + SortKey::Size => a.size_bytes.cmp(&b.size_bytes), + SortKey::Downloads => a.download_count.cmp(&b.download_count), + } + .then_with(|| a.id.cmp(&b.id)); + match dir { + SortDir::Asc => order, + SortDir::Desc => order.reverse(), + } + }); +} /// `GET /drive?folder=`: one directory. #[page("/drive")] @@ -189,20 +315,57 @@ async fn drive(cx: &Cx) -> Result { .and_then(|query| query.q.clone()) .map(|query| query.trim().to_string()) .filter(|query| !query.is_empty()); - let hits = match asked.as_deref() { + // The toolbar's listing controls: unknown values fall back to the + // standing order (folders-then-files as listed), ascending names, and + // the unfiltered kind — a hand-edited query re-orders nothing, it + // never refuses. + let sort_key = params + .as_ref() + .and_then(|query| parse_sort(query.sort.as_deref())); + let sort_dir = parse_dir( + params.as_ref().and_then(|query| query.dir.as_deref()), + sort_key, + ); + let kind = params + .as_ref() + .map(|query| parse_kind(query.kind.as_deref())) + .unwrap_or(KindFilter::All); + let mut hits = match asked.as_deref() { Some(query) => Some(store.search(&user.id, query, LIMIT).await?), None => None, }; let box_text = asked.clone().unwrap_or_default(); let current = current_folder(store.as_ref(), &user.id, wanted.as_deref()).await?; let crumbs = breadcrumbs(store.as_ref(), current.as_ref()).await; - let listing = match store + let mut listing = match store .list_children(&user.id, current.as_ref().map(|folder| folder.id.as_str())) .await { Ok(listing) => listing, Err(_) => return Err(not_found().into()), }; + // Sort and filter in the page layer, after the fetch — no store API + // change. Each group keeps its own order; folders-then-files stands. + if let Some(key) = sort_key { + sort_folders(&mut listing.folders, key, sort_dir); + sort_files(&mut listing.files, key, sort_dir); + } + match kind { + KindFilter::All => {} + KindFilter::Folders => listing.files.clear(), + KindFilter::Files => listing.folders.clear(), + } + if let Some(found) = hits.as_mut() { + if let Some(key) = sort_key { + sort_folders(&mut found.folders, key, sort_dir); + sort_files(&mut found.files, key, sort_dir); + } + match kind { + KindFilter::All => {} + KindFilter::Folders => found.files.clear(), + KindFilter::Files => found.folders.clear(), + } + } let destinations = folder_tree(store.as_ref(), &user.id).await; let refusal = page_refusal(cx); // Which folder row (if any) renders as its rename form: iz's `?edit=` @@ -222,15 +385,43 @@ async fn drive(cx: &Cx) -> Result { .map(|folder| folder.name.clone()) .unwrap_or_else(|| t(language, Key::Drive).to_string()); // The folder view without `?edit=`: the rename form's cancel target and - // the base the edit links extend. - let here = if current_id.is_empty() { + // the base the edit links extend. The listing controls ride along so a + // rename round-trip keeps the order and filter the reader chose; every + // value here is an id or a fixed vocabulary word, so no encoding is + // owed. + let mut here_bits: Vec = Vec::new(); + if !current_id.is_empty() { + here_bits.push(format!("folder={current_id}")); + } + if let Some(key) = sort_key { + here_bits.push(format!("sort={}", key.as_str())); + } + if params + .as_ref() + .and_then(|query| query.dir.clone()) + .is_some_and(|dir| dir == "asc" || dir == "desc") + { + here_bits.push(format!("dir={}", sort_dir.as_str())); + } + if kind != KindFilter::All { + here_bits.push(format!("kind={}", kind.as_str())); + } + let here = if here_bits.is_empty() { "/drive".to_string() } else { - format!("/drive?folder={current_id}") + format!("/drive?{}", here_bits.join("&")) + }; + // The edit links extend `here` with the matching separator. + let edit_sep = if here.contains('?') { "&" } else { "?" }; + // The direction the toggle offers: the opposite of what is showing. + let dir_flip = match sort_dir { + SortDir::Asc => "desc", + SortDir::Desc => "asc", + }; + let dir_glyph = match sort_dir { + SortDir::Asc => "↑", + SortDir::Desc => "↓", }; - // `here` carries no query at the root, one under a folder — the edit - // links extend it with the matching separator. - let edit_sep = if current_id.is_empty() { "?" } else { "&" }; view! { cx => @@ -250,17 +441,69 @@ async fn drive(cx: &Cx) -> Result { } } -
+
+ (t(language, Key::Sort)) + + + + + if kind != KindFilter::All { + + } + +
+
+ + + if sort_key.is_some() { + + } + + if kind != KindFilter::All { + + } + +
+
+ (t(language, Key::Kind)) + + + + if sort_key.is_some() { + + } + + +
"+ "
@@ -271,7 +514,17 @@ async fn drive(cx: &Cx) -> Result {
- + + // The persistent notice stack: client-side upload errors and + // completions render here and stay until dismissed. The region + // itself is server HTML, but every card is client-made + // (`__inAdded`) and mirrored in `window.__inNotices`, which the + // status script re-renders on every `in:wire` — so the cards + // survive both swap paths (the live morph keeps client-made + // nodes; the full replace rebuilds them from the array, which + // lives on `window` and outlives the body). +
if let Some(refusal) = refusal {

(refusal.message_in(language))

} @@ -287,12 +540,22 @@ async fn drive(cx: &Cx) -> Result { // The upload control sits outside the list so the + menu's // "Upload files" label and the page-wide drop handler find it on // every drive view, folder or search. The input stays hidden via - // the file-upload-input rule. + // the file-upload-input rule; the progress list below it carries + // the per-upload bars the script builds.
+ enctype="multipart/form-data" data-hard="" + data-failed-label=(t(language, Key::UploadFailed)) + data-complete-label=(t(language, Key::UploadComplete))>
+
+ // The full-page drop affordance: hidden until a file drag is + // over the window, pointer-transparent so it never blocks the + // drop itself. + if let Some(hits) = hits { if hits.folders.is_empty() && hits.files.is_empty() {

(t(language, Key::NoResults))

@@ -306,7 +569,7 @@ async fn drive(cx: &Cx) -> Result { } for file in &hits.files { } @@ -321,76 +584,93 @@ async fn drive(cx: &Cx) -> Result { for folder in listing.folders.iter() {
if edit_id.as_deref() == Some(folder.id.as_str()) { -
+ +
(t(language, Key::Cancel))
} else { - (folder.name.clone()) + + (folder.name.clone()) + + (t(language, Key::UploadedLabel))" "(folder.created_at.date().to_string())
- (t(language, Key::Rename)) -
- - - -
-
- - -
+
+ (t(language, Key::Options))" ▾" +
+ (t(language, Key::Rename)) +
+ +
+ + +
+
+
+ + +
+
+
}
} for file in listing.files.iter() {
- if file.thumb_state == ThumbState::Ready { - - } else { - - } + (crate::files::entry_chip(cx, file).await?) if edit_id.as_deref() == Some(file.id.as_str()) { -
+ +
(t(language, Key::Cancel))
} else { - (file.name.clone()) - } + + (file.name.clone()) + (human_size(file.size_bytes)) + (t(language, Key::UploadedLabel))" "(file.created_at.date().to_string()) + (t(language, Key::DownloadsLabel))" "(file.download_count.to_string())
- if edit_id.as_deref() != Some(file.id.as_str()) { - (t(language, Key::Rename)) -
- - - -
-
- - -
+
+ (t(language, Key::Options))" ▾" +
+ (t(language, Key::Rename)) +
+ +
+ + +
+
+
+ + +
+
+
}
} @@ -400,6 +680,7 @@ async fn drive(cx: &Cx) -> Result { (crate::dropdown::dropdown_script(cx).await?) (upload_script(cx).await?) + (status_script(cx).await?) } } @@ -431,19 +712,35 @@ fn query_value(query: &str, key: &str) -> Option { }) } -/// The upload control's client half: files under 8 MiB ride the form's own -/// multipart post; files at or over it are split into the chunked protocol's -/// calls with a progress bar. +/// The upload control's client half: files under 8 MiB ride one multipart +/// post, files at or over it are split into the chunked protocol's calls — +/// and every upload, small or big, draws the same live progress row (name, +/// bar, percent) into `#upload-progress-list`. /// /// The form wears `data-hard` so the soft-nav's multipart replay leaves it /// alone — two uploaders racing the same bytes would double-insert, and the /// progress the soft-nav draws knows nothing of chunks. Without script the /// form posts plainly and the 303 lands back on the folder. /// +/// Failures never append inline notes anymore: they go through +/// `window.__inNotify` into the persistent stack ([`status_script`]), which +/// survives the swaps that used to wipe them. Completions announce there +/// too, then the page navigates to the landing the post answered. +/// /// The same block carries the `?edit=` row's focus: the rename input the /// server renders open gets focused with its name selected on arrival, so a /// quick-created folder is ready to name. Guarded lookups — most visits /// render no such input. +/// +/// And the page-wide drop: dragging files anywhere over a drive view raises +/// the `#drop-overlay` affordance (a dragenter/dragleave counter, hidden on +/// drop or on leaving), and dropping feeds the upload input, whose change +/// the soft-nav's listener turns into the submit below. The overlay wears +/// `pointer-events: none` so it never blocks the drop itself. +/// +/// The Rust `\`-continuations strip newlines, so the emitted script is one +/// long line: only `/* */` comments survive inside it — a `//` would eat +/// the rest of the script and kill every handler silently. async fn upload_script(cx: &Cx) -> Result { use topcoat::view::Unescaped; const JS: &str = "\ @@ -451,21 +748,39 @@ async fn upload_script(cx: &Cx) -> Result { if (window.__inUpload) { return; } \ window.__inUpload = true; \ var LIMIT = 8388608; \ - function bar(box, label) { \ - var wrap = document.createElement('div'); \ - wrap.className = 'upload-progress'; \ + function progressList() { return document.getElementById('upload-progress-list'); } \ + function bar(label) { \ + var row = document.createElement('div'); \ + row.className = 'upload-progress-row'; \ + var name = document.createElement('span'); \ + name.className = 'upload-progress-name'; \ + name.textContent = label || ''; \ + var track = document.createElement('div'); \ + track.className = 'upload-progress'; \ var fill = document.createElement('div'); \ fill.className = 'upload-progress-fill'; \ - wrap.appendChild(fill); \ - box.appendChild(window.__inAdded(wrap)); \ - if (label) { wrap.setAttribute('aria-label', label); } \ - return fill; \ + track.appendChild(fill); \ + var pct = document.createElement('span'); \ + pct.className = 'upload-progress-pct'; \ + pct.textContent = '0%'; \ + row.appendChild(name); \ + row.appendChild(track); \ + row.appendChild(pct); \ + if (label) { row.setAttribute('aria-label', label); } \ + var list = progressList(); \ + if (list) { list.appendChild(window.__inAdded(row)); } \ + return { row: row, fill: fill, pct: pct }; \ + } \ + function setProgress(ui, frac) { \ + var text = Math.min(100, Math.round(frac * 100)) + '%'; \ + ui.fill.style.width = text; \ + ui.pct.textContent = text; \ + } \ + function dropRow(ui) { \ + if (ui.row.parentNode) { ui.row.parentNode.removeChild(ui.row); } \ } \ - function fail(box, message) { \ - var note = document.createElement('p'); \ - note.className = 'field-error'; \ - note.textContent = message; \ - box.appendChild(window.__inAdded(note)); \ + function notify(kind, message) { \ + if (window.__inNotify) { window.__inNotify(kind, message); } \ } \ async function startChunked(folder, name, size) { \ var r = await fetch('/api/upload/start', { \ @@ -477,8 +792,9 @@ async fn upload_script(cx: &Cx) -> Result { if (!answer.ok) { throw new Error(answer.err || 'start'); } \ return answer.ok; \ } \ - async function sendBig(file, folder, fill) { \ + async function sendBig(file, folder, onProgress) { \ var session = await startChunked(folder, file.name, file.size); \ + var total = Math.max(1, file.size); \ var index = 0; \ for (var off = 0; off < file.size; off += LIMIT, index++) { \ var piece = file.slice(off, Math.min(file.size, off + LIMIT)); \ @@ -488,18 +804,38 @@ async fn upload_script(cx: &Cx) -> Result { body: piece \ }); \ if (!r.ok) { throw new Error('chunk'); } \ - fill.style.width = Math.round(((off + piece.size) / file.size) * 100) + '%'; \ + onProgress((off + piece.size) / total); \ } \ var done = await fetch('/api/upload/' + session.id + '/finish', { method: 'POST' }); \ var fin = await done.json(); \ if (!fin.ok) { throw new Error((fin.err) || 'finish'); } \ + onProgress(1); \ + } \ + function sendSmall(action, folder, files, onProgress) { \ + return new Promise(function (resolve, reject) { \ + var data = new FormData(); \ + data.append('folder_id', folder); \ + files.forEach(function (f) { data.append('file', f, f.name); }); \ + var x = new XMLHttpRequest(); \ + x.open('POST', action); \ + x.setRequestHeader('accept', 'text/html'); \ + x.upload.onprogress = function (ev) { \ + if (ev.lengthComputable && ev.total > 0) { onProgress(ev.loaded / ev.total); } \ + }; \ + x.onload = function () { \ + onProgress(1); \ + if (x.status >= 200 && x.status < 300) { resolve(x.responseURL || ''); } \ + else { reject(new Error('small')); } \ + }; \ + x.onerror = function () { reject(new Error('small')); }; \ + x.send(data); \ + }); \ } \ document.addEventListener('submit', function (e) { \ var form = e.target; \ if (!form || form.id !== 'upload-form') { return; } \ e.preventDefault(); \ var input = form.querySelector('.file-upload-input'); \ - var box = form.querySelector('.file-upload-box') || form; \ var folder = form.querySelector('input[name=folder_id]').value; \ var files = input && input.files ? Array.prototype.slice.call(input.files) : []; \ if (!files.length) { return; } \ @@ -509,29 +845,41 @@ async fn upload_script(cx: &Cx) -> Result { var small = files.filter(function (f) { return f.size < LIMIT; }); \ var big = files.filter(function (f) { return f.size >= LIMIT; }); \ var failLabel = form.getAttribute('data-failed-label') || 'upload failed'; \ + var doneLabel = form.getAttribute('data-complete-label') || ''; \ var landing = window.location.href; \ + function settle() { \ + input.value = ''; \ + form.__inBusy = false; \ + if (input) { input.disabled = false; } \ + } \ (async function () { \ + var rows = []; \ try { \ if (small.length) { \ - var data = new FormData(); \ - data.append('folder_id', folder); \ - small.forEach(function (f) { data.append('file', f, f.name); }); \ - var fill = bar(box); \ - var r = await fetch(form.getAttribute('action'), { \ - method: 'POST', headers: { accept: 'text/html' }, body: data \ - }); \ - fill.style.width = '100%'; \ - landing = r.url || landing; \ - if (!r.ok) { fail(box, failLabel); } \ + var title = small.length === 1 ? small[0].name : (small.length + ' files'); \ + var ui = bar(title); \ + rows.push(ui); \ + var url = await sendSmall(form.getAttribute('action'), folder, small, function (frac) { setProgress(ui, frac); }); \ + if (url) { landing = url; } \ } \ for (var i = 0; i < big.length; i++) { \ - var fill2 = bar(box, big[i].name); \ - await sendBig(big[i], folder, fill2); \ + await (function (file) { \ + var ui2 = bar(file.name); \ + rows.push(ui2); \ + return sendBig(file, folder, function (frac) { setProgress(ui2, frac); }); \ + })(big[i]); \ } \ - } catch (err) { fail(box, failLabel); } \ - input.value = ''; \ - form.__inBusy = false; \ - if (input) { input.disabled = false; } \ + } catch (err) { \ + rows.forEach(dropRow); \ + var why = err && err.message ? err.message : String(err); \ + notify('error', failLabel + ' (' + why + ')'); \ + settle(); \ + return; \ + } \ + rows.forEach(dropRow); \ + /* A refused upload answers 303 into a refusal banner page, which the XHR follows to a 200: the banner carries the message, so only trumpet success when no refusal rode the redirect. */ \ + if (doneLabel && !/[?&]refusal=/.test(landing)) { notify('ok', doneLabel); } \ + settle(); \ if (window.__inGo) { window.__inGo(landing); } \ else { window.location.href = landing; } \ })(); \ @@ -549,11 +897,33 @@ async fn upload_script(cx: &Cx) -> Result { (function () { \ if (window.__inDrop) { return; } \ window.__inDrop = true; \ + var depth = 0; \ function uploadForm() { return document.getElementById('upload-form'); } \ + function overlay() { return document.getElementById('drop-overlay'); } \ + function hasFiles(e) { \ + return !!(e.dataTransfer && e.dataTransfer.types && Array.prototype.indexOf.call(e.dataTransfer.types, 'Files') !== -1); \ + } \ + function show(on) { \ + var ov = overlay(); \ + if (ov) { ov.classList.toggle('drop-overlay-show', !!on); } \ + } \ + document.addEventListener('dragenter', function (e) { \ + if (!uploadForm() || !hasFiles(e)) { return; } \ + e.preventDefault(); \ + depth++; \ + show(true); \ + }); \ document.addEventListener('dragover', function (e) { \ - if (uploadForm() && e.dataTransfer && e.dataTransfer.types && Array.prototype.indexOf.call(e.dataTransfer.types, 'Files') !== -1) { e.preventDefault(); } \ + if (uploadForm() && hasFiles(e)) { e.preventDefault(); } \ + }); \ + document.addEventListener('dragleave', function (e) { \ + if (!uploadForm()) { return; } \ + depth = Math.max(0, depth - 1); \ + if (depth === 0) { show(false); } \ }); \ document.addEventListener('drop', function (e) { \ + depth = 0; \ + show(false); \ var form = uploadForm(); \ if (!form || !e.dataTransfer || !e.dataTransfer.files || !e.dataTransfer.files.length) { return; } \ e.preventDefault(); \ @@ -567,6 +937,73 @@ async fn upload_script(cx: &Cx) -> Result { view! { cx => } } +/// The persistent notice stack's client half: upload errors and completions +/// that must stay until dismissed. +/// +/// How the cards survive the swaps: every card is registered through +/// `__inAdded`, so the live path's morph — which pairs only server-rendered +/// nodes and leaves client-made ones alone — keeps them where they are. The +/// full-replace path (navigations, form posts) rebuilds the body and would +/// drop them, so every notice is also mirrored in `window.__inNotices`, +/// which lives on the document's `window` and outlives any one body; the +/// `in:wire` pass `swap()` runs after every paint re-renders the stack from +/// that array. Dismissing (the ✕, labelled from the stack's +/// `data-dismiss-label`) drops the notice from both. Nothing here +/// auto-times out. +/// +/// The server-rendered `?refusal` banner needs no such route: it rides the +/// redirect URL the swap just painted, so both paths re-render it from the +/// server's own bytes. +async fn status_script(cx: &Cx) -> Result { + use topcoat::view::Unescaped; + const JS: &str = "\ + (function () { \ + if (window.__inStatus) { return; } \ + window.__inStatus = true; \ + if (!window.__inNotices) { window.__inNotices = []; } \ + var seq = 0; \ + window.__inNotices.forEach(function (n) { if (n.id > seq) { seq = n.id; } }); \ + function box() { return document.getElementById('in-status'); } \ + function dismissLabel() { \ + var b = box(); \ + return (b && b.getAttribute('data-dismiss-label')) || 'dismiss'; \ + } \ + window.__inNotify = function (kind, text) { \ + seq++; \ + window.__inNotices.push({ id: seq, kind: kind, text: text }); \ + render(); \ + }; \ + function render() { \ + var target = box(); \ + if (!target) { return; } \ + target.querySelectorAll('[data-notice]').forEach(function (old) { old.remove(); }); \ + window.__inNotices.forEach(function (n) { \ + var card = document.createElement('div'); \ + card.className = 'in-status-card in-status-' + n.kind; \ + card.setAttribute('data-notice', String(n.id)); \ + var text = document.createElement('span'); \ + text.className = 'in-status-text'; \ + text.textContent = n.text; \ + var shut = document.createElement('button'); \ + shut.type = 'button'; \ + shut.className = 'in-status-dismiss'; \ + shut.textContent = '✕'; \ + shut.setAttribute('aria-label', dismissLabel()); \ + shut.addEventListener('click', function () { \ + window.__inNotices = window.__inNotices.filter(function (x) { return x.id !== n.id; }); \ + card.remove(); \ + }); \ + card.appendChild(text); \ + card.appendChild(shut); \ + target.appendChild(window.__inAdded(card)); \ + }); \ + } \ + document.addEventListener('in:wire', render); \ + render(); \ + })();"; + view! { cx => } +} + #[derive(serde::Deserialize)] struct CreateFolderForm { #[serde(default)] diff --git a/crates/in-web/src/files.rs b/crates/in-web/src/files.rs index 04eed39..9f62583 100644 --- a/crates/in-web/src/files.rs +++ b/crates/in-web/src/files.rs @@ -1,25 +1,32 @@ -//! File bytes and small uploads. +//! File bytes, the viewer page, and small uploads. //! //! `GET /file/{id}` streams one file its owner may see — or a grantee may, //! when the grant says so — honoring `?dl=1` (download disposition) and //! `Range` (206 partial content), stamped `Cache-Control: private, //! immutable`. `GET /thumb/{id}` serves the webp thumbnail under the same -//! visibility. `POST /files` (multipart, 64 MiB cap) takes files under 8 -//! MiB through the same pipeline the chunked protocol uses — the store -//! sanitises the name, sniffs the mime, checks the quota and attempts the -//! thumbnail — and `POST /api/file/rename|move|delete` mutate the row. -//! Bytes for another owner's file answer 404, not 403. - -use in_core::store::{ShareKind, Store, StoreError}; +//! visibility. `GET /view/{id}` renders the viewer page: the inline viewer +//! for the file's kind (`viewer_kind`), a download link while the reader +//! may download, and its details. `POST /files` (multipart) takes files +//! through the same pipeline the chunked protocol uses — each part capped +//! at the instance upload ceiling first — the store sanitises the name, +//! sniffs the mime, checks the quota +//! and attempts the thumbnail — and `POST /api/file/rename|move|delete` +//! mutate the row. Bytes for another owner's file answer 404, not 403. + +use in_core::store::{File, ShareKind, Store, StoreError, ThumbState}; use topcoat::Result; use topcoat::context::Cx; use topcoat::router::content::multipart::Multipart; use topcoat::router::content::{Form, Json}; +use topcoat::router::error::not_found as page_not_found; use topcoat::router::request::headers as request_headers; use topcoat::router::{ - HeaderMap, HeaderName, HeaderValue, StatusCode, header, path_param, query_params, route, + HeaderMap, HeaderName, HeaderValue, StatusCode, header, page, path_param, query_params, route, }; +use topcoat::view::view; +use crate::i18n::{Key, lang, t}; +use crate::layout::{NavPage, topbar}; use crate::server::{Refusal, app, back_to, require_user}; path_param!(id); @@ -261,6 +268,11 @@ async fn download(cx: &Cx) -> topcoat::Result<(StatusCode, HeaderMap, Vec)> .and_then(|value| value.to_str().ok()); match range.and_then(|range| parse_range(range, total)) { Some(Ok((start, end))) => { + // A play counts once, on its first chunk; later seeks are the + // same view going on, not a new one. + if start == 0 { + let _ = store.record_download(id).await; + } let slice = bytes[start as usize..=end as usize].to_vec(); headers.insert( header::CONTENT_RANGE, @@ -275,7 +287,10 @@ async fn download(cx: &Cx) -> topcoat::Result<(StatusCode, HeaderMap, Vec)> ); Ok((StatusCode::RANGE_NOT_SATISFIABLE, headers, Vec::new())) } - None => Ok((StatusCode::OK, headers, bytes)), + None => { + let _ = store.record_download(id).await; + Ok((StatusCode::OK, headers, bytes)) + } } } @@ -324,10 +339,197 @@ async fn thumb(cx: &Cx) -> topcoat::Result<(StatusCode, HeaderMap, Vec)> { Ok((StatusCode::OK, headers, bytes)) } +/// What the viewer page shows inline: images, video and audio through their +/// native elements, PDFs through the browser's reader, plain text through a +/// sandboxed frame. Anything else — archives, office documents, unknown +/// bytes — is download-only. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum ViewerKind { + Image, + Video, + Audio, + Pdf, + Text, +} + +/// The inline viewer for one stored mime, if it has one. Trusts the stored +/// mime alone, the way [`renders_inline`] does; `image/heic` stays +/// download-only because no engine decodes it, and only `text/plain` opens +/// as text — anything juicier stays a download, the way [`inline_ok`] +/// keeps it off this origin. +pub(crate) fn viewer_kind(mime: &str) -> Option { + if mime == "image/heic" { + None + } else if mime.starts_with("image/") { + Some(ViewerKind::Image) + } else if mime.starts_with("video/") { + Some(ViewerKind::Video) + } else if mime.starts_with("audio/") { + Some(ViewerKind::Audio) + } else if mime == "application/pdf" { + Some(ViewerKind::Pdf) + } else if mime == "text/plain" { + Some(ViewerKind::Text) + } else { + None + } +} + +/// One file's list icon: the webp thumbnail where one is ready, else a +/// mime-class glyph. The glyphs are decorative — the file's name beside +/// them carries the meaning — so they hide from assistive technology. +/// +/// Lists embed this beside the name: `(crate::files::entry_chip(cx, +/// file).await?)`. +pub(crate) async fn entry_chip(cx: &Cx, file: &File) -> Result { + if file.thumb_state == ThumbState::Ready { + return view! { + cx => + + }; + } + let (class, glyph) = chip_mark(&file.mime); + view! { + cx => + + } +} + +/// The chip's modifier class and its glyph, by stored mime: one distinct +/// mark per class — image, video, audio, pdf, text, archive, generic. +fn chip_mark(mime: &str) -> (&'static str, &'static str) { + if mime.starts_with("image/") { + ("image", "◫") + } else if mime.starts_with("video/") { + ("video", "▶") + } else if mime.starts_with("audio/") { + ("audio", "♫") + } else if mime == "application/pdf" { + ("pdf", "☰") + } else if mime.starts_with("text/") { + ("text", "¶") + } else if is_archive_mime(mime) { + ("archive", "⊞") + } else { + ("generic", "▦") + } +} + +/// The stored mimes that are bundles of other files: plain zips, the OOXML +/// and OpenDocument documents (all zips underneath), gzip blobs and the +/// legacy OLE container. +fn is_archive_mime(mime: &str) -> bool { + mime == "application/zip" + || mime == "application/gzip" + || mime == "application/x-ole-storage" + || mime == "application/vnd.ms-excel" + || mime.contains("openxml") + || mime.contains("opendocument") +} + +/// `GET /view/{id}`: one file's viewer page — its name, the inline viewer +/// for its kind, a download link and its details. Authorization mirrors +/// trashed files open for nobody. A view-only grant opens the page but not +/// the bytes: the download link shows only while the reader may download, +/// and the inline viewer gives way to the unavailable note, since every +/// viewer element reads the same gated bytes. Bytes for another owner's +/// file answer 404, not 403. +#[page("/view/{id}")] +async fn view_file(cx: &Cx) -> Result { + let id: &str = path_param::(cx); + + let user = match require_user(cx).await { + Ok(user) => user, + Err(_) => { + let location = (header::LOCATION, HeaderValue::from_static("/")); + return view! { + cx => + (StatusCode::SEE_OTHER) + (location) + }; + } + }; + let language = lang(cx).await; + + let store = app(cx).store.clone(); + let Some(file) = visible_file(store.as_ref(), &user.id, id).await else { + return Err(page_not_found().into()); + }; + let may_download = file.owner_id == user.id + || store + .can_download(ShareKind::File, &file.id, &user.id) + .await + .unwrap_or(false); + + let src = format!("/file/{}", file.id); + let download_href = format!("/file/{}?dl=1", file.id); + let meta = format!( + "{} · {}", + file.mime, + crate::settings::human_bytes(file.size_bytes) + ); + let uploaded = file.created_at.date().to_string(); + view! { + cx => + (topbar(cx, NavPage::Drive, &user, language).await?) +
+

(t(language, Key::BackToDrive))

+

(entry_chip(cx, &file).await?) (file.name.clone())

+

(meta)

+
+ if may_download { + match viewer_kind(&file.mime) { + Some(ViewerKind::Image) => (file.name.clone()), + Some(ViewerKind::Video) => , + Some(ViewerKind::Audio) => , + Some(ViewerKind::Pdf) => +

(t(language, Key::PreviewUnavailable))

+
, + Some(ViewerKind::Text) => , + None =>
+

(t(language, Key::PreviewUnavailable))

+
+ } + } else { + // A view-only grant opens the page but not the bytes, so + // the viewer elements — every one reads /file/{id} — + // would only frame a 404. The note instead. +
+

(t(language, Key::PreviewUnavailable))

+
+ } +
+ if may_download { +

(t(language, Key::Download))

+ } +
+
+

(t(language, Key::FileDetails))

+
+
+
+ (t(language, Key::SizeColumn)) + (crate::settings::human_bytes(file.size_bytes)) +
+
+ (t(language, Key::UploadedLabel)) + (uploaded) +
+
+ (t(language, Key::DownloadsLabel)) + (file.download_count.to_string()) +
+
+
+
+ } +} + /// Takes the files the drive's upload form carries — one per `file` part, -/// and a `multiple` picker posts several. The route already caps the whole -/// request body at 64 MiB (`main.rs`); each part is buffered whole because -/// the store writes it in one go. Fields arrive in request order: +/// and a `multiple` picker posts several. The route's body guard sits at 2 +/// GiB (`main.rs`); each part is buffered whole because the store writes +/// it in one go, capped at the instance upload ceiling before it gets +/// there. Fields arrive in request order: /// `folder_id` before the `file` parts, so the destination is known before /// a byte of any file is kept. #[route(POST "/files")] @@ -397,8 +599,16 @@ async fn upload( return Ok(back_to_folder(folder_id.as_deref(), None)); } + let limit = crate::server::effective_upload_limit(cx).await; + let mut refusal: Option = None; for (name, bytes) in files { + // One file may not pass the instance ceiling; oversize files never + // reach the store. + if bytes.len() as u64 > limit { + refusal = Some(Refusal::UploadTooLarge); + break; + } // The store sanitises the label, sniffs the mime off the bytes, // checks the quota, writes the file and attempts the thumbnail. if let Err(error) = store diff --git a/crates/in-web/src/i18n.rs b/crates/in-web/src/i18n.rs index 419c770..80021da 100644 --- a/crates/in-web/src/i18n.rs +++ b/crates/in-web/src/i18n.rs @@ -178,6 +178,29 @@ pub enum Key { DarkOption, LanguageLabel, Saved, + // File viewer. + UploadedLabel, + DownloadsLabel, + // Wave-1 upload limits. + UploadLimits, + CurrentUploadLimit, + MaxUploadBytes, + // Wave-2 drive additions (DriveBuild owns this block). + Options, + DropFilesToUpload, + Dismiss, + Sort, + SortName, + SortUploaded, + SortSize, + SortDownloads, + Kind, + KindAll, + KindFolders, + KindFiles, + // Wave-2 trash/share extras (TrashShareBuild owns this block). + SortDeleted, + SortOwner, } pub fn t(lang: Lang, key: Key) -> &'static str { @@ -283,6 +306,25 @@ pub fn t(lang: Lang, key: Key) -> &'static str { DarkOption => "Dark", LanguageLabel => "LANGUAGE", Saved => "Saved.", + UploadedLabel => "Uploaded", + DownloadsLabel => "Downloads", + UploadLimits => "Upload limits", + CurrentUploadLimit => "Current limit", + MaxUploadBytes => "Limit in bytes", + Options => "Options", + DropFilesToUpload => "Drop files to upload", + Dismiss => "Dismiss", + Sort => "Sort", + SortName => "Name", + SortUploaded => "Uploaded", + SortSize => "Size", + SortDownloads => "Downloads", + Kind => "Kind", + KindAll => "All", + KindFolders => "Folders", + KindFiles => "Files", + SortDeleted => "Deleted", + SortOwner => "Owner", }, Lang::Tr => match key { Cancel => "Vazgeç", @@ -384,6 +426,25 @@ pub fn t(lang: Lang, key: Key) -> &'static str { DarkOption => "Koyu", LanguageLabel => "DİL", Saved => "Kaydedildi.", + UploadedLabel => "Yüklendi", + DownloadsLabel => "İndirme", + UploadLimits => "Yükleme sınırları", + CurrentUploadLimit => "Geçerli sınır", + MaxUploadBytes => "Bayt olarak sınır", + Options => "Seçenekler", + DropFilesToUpload => "Yüklemek için dosyaları bırakın", + Dismiss => "Kapat", + Sort => "Sırala", + SortName => "Ad", + SortUploaded => "Yüklenme", + SortSize => "Boyut", + SortDownloads => "İndirme", + Kind => "Tür", + KindAll => "Tümü", + KindFolders => "Klasörler", + KindFiles => "Dosyalar", + SortDeleted => "Silindi", + SortOwner => "Sahibi", }, } } diff --git a/crates/in-web/src/main.rs b/crates/in-web/src/main.rs index ad99183..d98b88d 100644 --- a/crates/in-web/src/main.rs +++ b/crates/in-web/src/main.rs @@ -150,8 +150,13 @@ async fn main() { let router = in_client::mount( Router::builder() .discover() - .layer(BodyLimit::max(16 * 1024 * 1024).at("/api/upload")) - .layer(BodyLimit::max(64 * 1024 * 1024).at("/files")) + // BodyLimit is only a memory guard here, not the upload policy: the + // real per-file ceiling is the admin-controlled limit enforced in + // the handlers (`effective_upload_limit`). `/files` takes whole + // multipart bodies, so its guard sits at a hard 2 GiB; `/api/upload` + // carries single 8 MiB chunks, so 32 MiB leaves ample headroom. + .layer(BodyLimit::max(32 * 1024 * 1024).at("/api/upload")) + .layer(BodyLimit::max(2usize * 1024 * 1024 * 1024).at("/files")) .cookies() .assets(bundle), oidc, diff --git a/crates/in-web/src/server.rs b/crates/in-web/src/server.rs index 23e7de9..f5fb738 100644 --- a/crates/in-web/src/server.rs +++ b/crates/in-web/src/server.rs @@ -218,6 +218,11 @@ pub enum Refusal { BadTheme, /// The language field was not one of the values the form offers. BadLanguage, + /// One file carries more bytes than the instance upload ceiling allows. + UploadTooLarge, + /// The admin's upload-limit form named zero, which would refuse every upload. + /// (The form speaks bytes, so nothing can overflow; zero is the only refusal.) + BadLimit, } impl Refusal { @@ -241,6 +246,8 @@ impl Refusal { Refusal::BadUi => "That interface choice is not offered.".to_string(), Refusal::BadTheme => "That is not a theme.".to_string(), Refusal::BadLanguage => "That is not a language.".to_string(), + Refusal::UploadTooLarge => "That file is larger than the upload limit.".to_string(), + Refusal::BadLimit => "That limit is not usable.".to_string(), } } @@ -266,6 +273,8 @@ impl Refusal { Refusal::BadUi => "Bu arayüz seçeneği sunulmuyor.".to_string(), Refusal::BadTheme => "Bu bir tema değil.".to_string(), Refusal::BadLanguage => "Bu bir dil değil.".to_string(), + Refusal::UploadTooLarge => "Bu dosya yükleme sınırından büyük.".to_string(), + Refusal::BadLimit => "Bu sınır kullanılamaz.".to_string(), } } @@ -289,6 +298,8 @@ impl Refusal { "bad-ui" => Refusal::BadUi, "bad-theme" => Refusal::BadTheme, "bad-language" => Refusal::BadLanguage, + "upload-too-large" => Refusal::UploadTooLarge, + "bad-limit" => Refusal::BadLimit, _ => return None, }) } @@ -316,10 +327,38 @@ impl Refusal { Refusal::BadUi => "bad-ui", Refusal::BadTheme => "bad-theme", Refusal::BadLanguage => "bad-language", + Refusal::UploadTooLarge => "upload-too-large", + Refusal::BadLimit => "bad-limit", } } } +/// The instance setting holding the per-file upload ceiling, in bytes. +/// Written by the admin's upload-limit form; read here. +pub(crate) const MAX_UPLOAD_SETTING: &str = "max_upload_bytes"; + +/// The per-file upload ceiling in force for this request: the +/// [`MAX_UPLOAD_SETTING`] instance setting first, then the +/// `max_upload_bytes` key from `config/in.toml`, then 1 GiB when neither +/// names one. +/// +/// A setting that is missing, unreadable, unparseable or zero falls through +/// to the config default — the save form only ever writes positive integers, +/// so anything else is a hand-edited row, not a choice. Quota is untouched: +/// this caps one file's size, quota caps an account's total. +pub(crate) async fn effective_upload_limit(cx: &Cx) -> u64 { + let ctx = app(cx); + match ctx.store.get_setting(MAX_UPLOAD_SETTING).await { + Ok(Some(raw)) => raw + .trim() + .parse::() + .ok() + .filter(|limit| *limit > 0) + .unwrap_or(ctx.config.max_upload_bytes), + Ok(None) | Err(_) => ctx.config.max_upload_bytes, + } +} + /// Which call a carried refusal belongs to. Two forms on one page must not both /// claim the same sentence, so the redirect names the call and this is the name: /// the last piece of the server function's path, with anything that is not a diff --git a/crates/in-web/src/settings.rs b/crates/in-web/src/settings.rs index f643676..f4cd42c 100644 --- a/crates/in-web/src/settings.rs +++ b/crates/in-web/src/settings.rs @@ -84,6 +84,37 @@ async fn set_quota(cx: &Cx, Form(input): Form) -> Redirect { } } +#[derive(Deserialize)] +struct UploadLimitForm { + max_upload_bytes: u64, +} + +/// Sets the instance-wide per-file upload ceiling, in bytes — the same unit +/// the `max_upload_bytes` instance setting stores, so the round trip is +/// exact: what the panel shows is what a save writes back. The bytes already +/// held are untouched — a ceiling lowered under an existing file refuses new +/// uploads past it, rather than deleting anything. +#[route(POST "/api/settings/upload-limit")] +async fn set_upload_limit(cx: &Cx, Form(input): Form) -> Redirect { + if let Err(refusal) = require_admin(cx).await { + return redirect_back(cx, "upload-limit", Some(refusal)); + } + if input.max_upload_bytes == 0 { + return redirect_back(cx, "upload-limit", Some(Refusal::BadLimit)); + } + match app(cx) + .store + .set_setting( + crate::server::MAX_UPLOAD_SETTING, + &input.max_upload_bytes.to_string(), + ) + .await + { + Ok(()) => redirect_back(cx, "upload-limit", None), + Err(error) => redirect_back(cx, "upload-limit", Some(refusal_of(error))), + } +} + #[derive(Deserialize)] struct DisableForm { user_id: String, @@ -200,6 +231,13 @@ async fn settings(cx: &Cx) -> Result { } else { Vec::new() }; + // The live per-file ceiling, read once for the admin panel below. Only + // admins see it, so only they pay the extra setting read. + let upload_limit = if fresh.admin { + Some(crate::server::effective_upload_limit(cx).await) + } else { + None + }; let created = created_token(uri(cx).query().unwrap_or("")); let origin = app(cx).config.listen_url(); view! { @@ -208,7 +246,7 @@ async fn settings(cx: &Cx) -> Result {

(t(language, Key::Settings))

- (refusal_banner(cx, language, &["create", "revoke", "add", "remove", "quota", "disable", "preferences"]).await?) + (refusal_banner(cx, language, &["create", "revoke", "add", "remove", "quota", "disable", "preferences", "upload-limit"]).await?) if let Some(token) = created {
@@ -290,6 +328,20 @@ async fn settings(cx: &Cx) -> Result {
if fresh.admin { + if let Some(limit) = upload_limit { +
+
+

(t(language, Key::UploadLimits))

+
+
+

(format!("{}: {}", t(language, Key::CurrentUploadLimit), human_bytes(limit)))

+
+ + +
+
+
+ }

(t(language, Key::AdminPanel))

diff --git a/crates/in-web/src/share.rs b/crates/in-web/src/share.rs index 5a5888b..1fc52d3 100644 --- a/crates/in-web/src/share.rs +++ b/crates/in-web/src/share.rs @@ -17,7 +17,7 @@ //! render the copy-once banner off that pair. use in_core::hash_share_token; -use in_core::store::{ShareKind, Store, StoreError, User}; +use in_core::store::{ShareKind, Store, StoreError, ThumbState, User}; use serde::Deserialize; use time::OffsetDateTime; use topcoat::Result; @@ -25,10 +25,11 @@ use topcoat::context::Cx; use topcoat::router::content::Form; use topcoat::router::request::{headers as request_headers, uri}; use topcoat::router::response::IntoResponse; -use topcoat::router::{HeaderName, StatusCode, header, page, path_param, route}; +use topcoat::router::{HeaderName, StatusCode, header, page, path_param, query_params, route}; use topcoat::view::view; use crate::i18n::{Key, Lang, lang, t}; +use crate::files::entry_chip; use crate::layout::{NavPage, topbar, wordmark}; use crate::server::{Refusal, app, back_to, require_user}; @@ -526,6 +527,19 @@ async fn download_bytes( let Ok(Some(bytes)) = bytes else { return dead_link(cx).await.into_response(cx); }; + // A fetch counts once: a full fetch, or a range resuming from byte 0. + // A mid-file chunk is the same view going on, not a new one — the way + // the signed-in download route counts its first chunk only. + let range = request_headers(cx) + .get(header::RANGE) + .and_then(|value| value.to_str().ok()); + let counts = match range { + None => true, + Some(header) => range_starts_at_zero(header), + }; + if counts { + let _ = store.record_download(file_id).await; + } let mut headers = HeaderMap::new(); if let Ok(value) = HeaderValue::from_str(mime) { headers.insert(header::CONTENT_TYPE, value); @@ -541,6 +555,22 @@ async fn download_bytes( Ok((StatusCode::OK, headers, bytes).into_response(cx)?) } +/// Whether a `Range` header starts at byte 0: only those ranges (and the +/// header's absence) count a download. Anything else — a mid-file resume, +/// a suffix probe, several ranges, garbage — does not. +fn range_starts_at_zero(header: &str) -> bool { + let Some(spec) = header.strip_prefix("bytes=") else { + return false; + }; + if spec.contains(',') { + return false; + } + match spec.split_once('-') { + Some(("0", _)) => true, + _ => false, + } +} + /// The stored webp preview behind a public link. Unlike the bytes, the /// preview is what a view-only link grants, so this answers regardless of /// `can_download` — and anything unservable is the dead card, like every @@ -623,8 +653,53 @@ async fn file_card( .into_response(cx) } -/// A shared folder's listing: subfolders then files, downloads gated on the -/// link's flag. Subfolders browse in place under the same token. +/// One file's chip on the public card: the link's own thumbnail where one +/// is ready, else the same mime-class glyph the signed-in lists wear. +/// `/thumb/{id}` needs a session, so this points at the public `?thumb=1` +/// route behind the same token instead. +async fn public_chip(cx: &Cx, thumb_src: &str, file: &in_core::store::File) -> Result { + if file.thumb_state == ThumbState::Ready { + return view! { + cx => + + }; + } + entry_chip(cx, file).await +} + +/// One shared file's chip: the thumbnail image while the target is live, +/// the mime-class glyph once it is trashed — `/thumb/{id}` 404s trashed +/// rows, so a Ready image would render broken if the target went into the +/// trash after the grant. The clone only clears the thumbnail flag for the +/// render. +async fn shared_chip(cx: &Cx, file: &in_core::store::File) -> Result { + if file.deleted_at.is_some() { + let mut unthumb = file.clone(); + unthumb.thumb_state = ThumbState::None; + return entry_chip(cx, &unthumb).await; + } + entry_chip(cx, file).await +} + +/// One row of the public folder listing, folder or file, for the unified +/// list. +enum PublicEntry<'a> { + Folder(&'a in_core::store::Folder), + File(&'a in_core::store::File), +} + +impl PublicEntry<'_> { + fn name(&self) -> &str { + match self { + PublicEntry::Folder(folder) => &folder.name, + PublicEntry::File(file) => &file.name, + } + } +} + +/// A shared folder's listing: folders and files in one list, downloads +/// gated on the link's flag. Subfolders browse in place under the same +/// token. async fn folder_card( cx: &Cx, store: &dyn Store, @@ -644,44 +719,38 @@ async fn folder_card( .list_children(&root.owner_id, Some(at)) .await?; let base = format!("/s/{token}"); + let mut rows: Vec = Vec::new(); + rows.extend(listing.folders.iter().map(PublicEntry::Folder)); + rows.extend(listing.files.iter().map(PublicEntry::File)); + rows.sort_by(|a, b| a.name().to_lowercase().cmp(&b.name().to_lowercase())); view! { cx => (wordmark(cx).await?)

(here.name.clone())

-
-

(t(language, Key::FoldersHeading))

- (format!("{}", listing.folders.len())) -
-
- if listing.folders.is_empty() { -

(t(language, Key::EmptyFolder))

- } - for folder in &listing.folders { -

(folder.name.clone())

- } -
-
-
-
-

(t(language, Key::FilesHeading))

- (format!("{}", listing.files.len())) -
- if listing.files.is_empty() { + if rows.is_empty() {

(t(language, Key::EmptyFolder))

} - for file in &listing.files { -

- (file.name.clone()) - (format!(" · {}", crate::settings::human_bytes(file.size_bytes))) - if link.can_download { - (t(language, Key::Download)) - } else { - (t(language, Key::ViewOnly)) - } -

+ for row in &rows { + match row { + PublicEntry::Folder(folder) =>
+ + (folder.name.clone()) +
, + PublicEntry::File(file) =>
+ (public_chip(cx, &format!("{base}?folder={at}&file={}&thumb=1", file.id), file).await?) + (file.name.clone()) + (crate::settings::human_bytes(file.size_bytes)) +
+ if link.can_download { + (t(language, Key::Download)) + } else { + (t(language, Key::ViewOnly)) + } +
, + } }
@@ -697,8 +766,86 @@ fn current_path(cx: &Cx) -> String { if path.is_empty() { "/".to_string() } else { path.to_string() } } -/// Everything others shared with the reader, files and folders in their own -/// groups, newest grant first. The reader's own library never appears here. +#[query_params] +struct SharedPageQuery { + sort: Option, + kind: Option, + q: Option, +} + +/// The shared list's sort, off the query: name, uploaded, size or owner. +/// Anything else is the default — by name. +fn valid_shared_sort(raw: Option<&str>) -> &'static str { + match raw { + Some("name") => "name", + Some("uploaded") => "uploaded", + Some("size") => "size", + Some("owner") => "owner", + _ => "name", + } +} + +/// The kind filter, off the query: all, folders or files. Anything else +/// shows everything. +fn valid_shared_kind(raw: Option<&str>) -> &'static str { + match raw { + Some("folders") => "folders", + Some("files") => "files", + _ => "all", + } +} + +/// One grant with the target's own dates and counters, for the unified +/// list. The file row stays aboard for the list chip; folders carry none. +struct SharedRow { + item: in_core::store::SharedItem, + owner_name: String, + file: Option, + uploaded: OffsetDateTime, +} + +impl SharedRow { + fn size(&self) -> u64 { + self.file.as_ref().map(|file| file.size_bytes).unwrap_or(0) + } + + fn downloads(&self) -> u64 { + self.file + .as_ref() + .map(|file| file.download_count) + .unwrap_or(0) + } +} + +/// The muted line at each shared row's right edge: what the grant opens, +/// who opened it, when the target went up — and the size and download +/// count for files. +fn shared_details(language: Lang, row: &SharedRow) -> String { + let owner = if row.owner_name.is_empty() { + String::new() + } else { + format!(" · {}", row.owner_name) + }; + let mut out = format!( + "{}{} · {} {}", + access_chip(language, row.item.can_download), + owner, + t(language, Key::UploadedLabel), + row.uploaded.date() + ); + if row.item.kind == ShareKind::File { + out.push_str(&format!( + " · {} · {} {}", + crate::settings::human_bytes(row.size()), + row.downloads(), + t(language, Key::DownloadsLabel) + )); + } + out +} + +/// Everything others shared with the reader, folders and files in one +/// list. The reader's own library never appears here. #[page("/shared")] async fn shared(cx: &Cx) -> Result { let user = match require_user(cx).await { @@ -715,6 +862,15 @@ async fn shared(cx: &Cx) -> Result { } }; let language = lang(cx).await; + let params = query_params::(cx).ok(); + let sort = valid_shared_sort(params.as_ref().and_then(|query| query.sort.as_deref())); + let kind = valid_shared_kind(params.as_ref().and_then(|query| query.kind.as_deref())); + let asked = params + .as_ref() + .and_then(|query| query.q.clone()) + .map(|query| query.trim().to_string()) + .filter(|query| !query.is_empty()); + let box_text = asked.clone().unwrap_or_default(); let store = app(cx).store; let items = store .shares_for_user(&user.id) @@ -732,43 +888,145 @@ async fn shared(cx: &Cx) -> Result { owners.insert(item.owner_id.clone(), name); } } - let folder_count = items.iter().filter(|item| item.kind == ShareKind::Folder).count(); - let file_count = items.iter().filter(|item| item.kind == ShareKind::File).count(); + let mut rows: Vec = Vec::new(); + for item in items { + if kind == "folders" && item.kind != ShareKind::Folder { + continue; + } + if kind == "files" && item.kind != ShareKind::File { + continue; + } + if let Some(needle) = asked.as_deref() { + if !item.name.to_lowercase().contains(&needle.to_lowercase()) { + continue; + } + } + let owner_name = owners.get(&item.owner_id).cloned().unwrap_or_default(); + // The grant carries no dates or counters of its own: the file row + // brings the upload date, size and downloads, the folder row its + // upload date. A target that went missing since the grant keeps + // its row on the grant's own date. + let (file, uploaded) = match item.kind { + ShareKind::File => match store.file(&item.target_id).await.ok().flatten() { + Some(file) => { + let uploaded = file.created_at; + (Some(file), uploaded) + } + None => (None, item.created_at), + }, + ShareKind::Folder => { + let uploaded = store + .folder(&item.target_id) + .await + .ok() + .flatten() + .map(|folder| folder.created_at) + .unwrap_or(item.created_at); + (None, uploaded) + } + }; + rows.push(SharedRow { + item, + owner_name, + file, + uploaded, + }); + } + let nothing_shared = rows.is_empty() && asked.is_none() && kind == "all"; + match sort { + "uploaded" => rows.sort_by(|a, b| { + b.uploaded + .cmp(&a.uploaded) + .then_with(|| a.item.name.to_lowercase().cmp(&b.item.name.to_lowercase())) + }), + "size" => rows.sort_by(|a, b| { + b.size() + .cmp(&a.size()) + .then_with(|| a.item.name.to_lowercase().cmp(&b.item.name.to_lowercase())) + }), + "owner" => rows.sort_by(|a, b| { + a.owner_name + .to_lowercase() + .cmp(&b.owner_name.to_lowercase()) + .then_with(|| a.item.name.to_lowercase().cmp(&b.item.name.to_lowercase())) + }), + _ => rows.sort_by(|a, b| { + a.item + .name + .to_lowercase() + .cmp(&b.item.name.to_lowercase()) + .then_with(|| a.item.target_id.cmp(&b.item.target_id)) + }), + } view! { cx => (topbar(cx, NavPage::Shared, &user, language).await?)

(t(language, Key::SharedWithMe))

- if items.is_empty() { -

(t(language, Key::NoSharedItems))

- } +
+
+ (t(language, Key::Sort)) + + + +
+
+ (t(language, Key::Kind)) + + + +
+ +
-

(t(language, Key::FoldersHeading))

- (format!("{folder_count}")) +

(t(language, Key::SharedWithMe))

+ (rows.len().to_string())
- for item in items.iter().filter(|item| item.kind == ShareKind::Folder) { -

- (item.name.clone()) - (owner_chip(item, &owners)) - (access_chip(language, item.can_download)) -

+ if rows.is_empty() { + if nothing_shared { +

(t(language, Key::NoSharedItems))

+ } else { +

(t(language, Key::NoResults))

+ } } -
-
-
-
-

(t(language, Key::FilesHeading))

- (format!("{file_count}")) -
-
- for item in items.iter().filter(|item| item.kind == ShareKind::File) { -

- (item.name.clone()) - (owner_chip(item, &owners)) - (access_chip(language, item.can_download)) -

+ for row in &rows { +
+ if row.item.kind == ShareKind::Folder { + + (row.item.name.clone()) + } else { + match &row.file { + Some(file) => (shared_chip(cx, file).await?), + None => , + } + (row.item.name.clone()) + } +
+ (shared_details(language, row)) +
}
@@ -776,17 +1034,6 @@ async fn shared(cx: &Cx) -> Result { } } -/// `by `, when the owner's name is known. -fn owner_chip( - item: &in_core::store::SharedItem, - owners: &std::collections::HashMap, -) -> String { - match owners.get(&item.owner_id) { - Some(name) if !name.is_empty() => format!(" · {name}"), - _ => String::new(), - } -} - /// What the grant opens: the download, or the view alone. fn access_chip(language: Lang, can_download: bool) -> &'static str { if can_download { diff --git a/crates/in-web/src/trash.rs b/crates/in-web/src/trash.rs index 19a3612..71c90a1 100644 --- a/crates/in-web/src/trash.rs +++ b/crates/in-web/src/trash.rs @@ -9,15 +9,17 @@ //! the filesystem. Folder purge has no store method yet (hubbed to Main via //! the orchestrator) and is refused until it lands. -use in_core::store::{ShareKind, Store, User}; +use in_core::store::{File, Folder, ShareKind, Store, ThumbState, User}; use serde::Deserialize; +use time::OffsetDateTime; use topcoat::Result; use topcoat::context::Cx; use topcoat::router::content::Form; -use topcoat::router::{HeaderName, StatusCode, header, page, route}; +use topcoat::router::{HeaderName, StatusCode, header, page, query_params, route}; use topcoat::view::view; -use crate::i18n::{Key, lang, t}; +use crate::files::entry_chip; +use crate::i18n::{Key, Lang, lang, t}; use crate::layout::{NavPage, topbar}; use crate::server::{Refusal, app, back_to, require_user}; use crate::share::{refusal_banner, refusal_of}; @@ -135,9 +137,109 @@ async fn empty(cx: &Cx) -> Redirect { } } -/// The reader's trash: every trashed folder and file, newest trash first, -/// each row carrying its way back and its way gone, plus the button that -/// destroys them all. +/// A trashed file's chip: always the mime-class glyph, never the thumbnail +/// image — `/thumb/{id}` 404s trashed rows, so a Ready row would render a +/// broken image. The clone only clears the thumbnail flag for the render. +async fn trash_chip(cx: &Cx, file: &File) -> Result { + let mut unthumb = file.clone(); + unthumb.thumb_state = ThumbState::None; + entry_chip(cx, &unthumb).await +} + +#[query_params] +struct TrashQuery { + sort: Option, + kind: Option, + q: Option, +} + +/// The trash's sort, off the query: name, deleted, uploaded or size. +/// Anything else is the default — newest trash first. +fn valid_trash_sort(raw: Option<&str>) -> &'static str { + match raw { + Some("name") => "name", + Some("deleted") => "deleted", + Some("uploaded") => "uploaded", + Some("size") => "size", + _ => "deleted", + } +} + +/// The kind filter, off the query: all, folders or files. Anything else +/// shows everything. +fn valid_kind(raw: Option<&str>) -> &'static str { + match raw { + Some("folders") => "folders", + Some("files") => "files", + _ => "all", + } +} + +/// One trashed row, folder or file, for the unified list. +enum TrashEntry<'a> { + Folder(&'a Folder), + File(&'a File), +} + +impl TrashEntry<'_> { + fn id(&self) -> &str { + match self { + TrashEntry::Folder(folder) => &folder.id, + TrashEntry::File(file) => &file.id, + } + } + + fn name(&self) -> &str { + match self { + TrashEntry::Folder(folder) => &folder.name, + TrashEntry::File(file) => &file.name, + } + } + + fn uploaded(&self) -> OffsetDateTime { + match self { + TrashEntry::Folder(folder) => folder.created_at, + TrashEntry::File(file) => file.created_at, + } + } + + /// The trash timestamp. Always present on trashed rows; the upload + /// date covers a row that lost it. + fn deleted(&self) -> OffsetDateTime { + let stamped = match self { + TrashEntry::Folder(folder) => folder.deleted_at, + TrashEntry::File(file) => file.deleted_at, + }; + stamped.unwrap_or_else(|| self.uploaded()) + } + + /// Folders carry no size of their own and sort as zero. + fn size(&self) -> u64 { + match self { + TrashEntry::Folder(_) => 0, + TrashEntry::File(file) => file.size_bytes, + } + } +} + +/// The muted line under each trashed name: the trash date, the upload date, +/// and the size for files. +fn trash_details(language: Lang, row: &TrashEntry) -> String { + let mut out = format!( + "{} {} · {} {}", + t(language, Key::SortDeleted), + row.deleted().date(), + t(language, Key::UploadedLabel), + row.uploaded().date() + ); + if let TrashEntry::File(file) = row { + out.push_str(&format!(" · {}", crate::settings::human_bytes(file.size_bytes))); + } + out +} + +/// The reader's trash: folders and files in one list, each row carrying its +/// way back and its way gone, plus the button that destroys them all. #[page("/trash")] async fn trash(cx: &Cx) -> Result { let user = match require_user(cx).await { @@ -154,75 +256,152 @@ async fn trash(cx: &Cx) -> Result { } }; let language = lang(cx).await; + let params = query_params::(cx).ok(); + let sort = valid_trash_sort(params.as_ref().and_then(|query| query.sort.as_deref())); + let kind = valid_kind(params.as_ref().and_then(|query| query.kind.as_deref())); + let asked = params + .as_ref() + .and_then(|query| query.q.clone()) + .map(|query| query.trim().to_string()) + .filter(|query| !query.is_empty()); + let box_text = asked.clone().unwrap_or_default(); let listing = app(cx) .store .list_trash(&user.id) .await?; + let nothing_trashed = listing.folders.is_empty() && listing.files.is_empty(); + let mut rows: Vec = Vec::new(); + if kind == "all" || kind == "folders" { + rows.extend(listing.folders.iter().map(TrashEntry::Folder)); + } + if kind == "all" || kind == "files" { + rows.extend(listing.files.iter().map(TrashEntry::File)); + } + if let Some(needle) = asked.as_deref() { + let needle = needle.to_lowercase(); + rows.retain(|row| row.name().to_lowercase().contains(&needle)); + } + match sort { + "name" => rows.sort_by(|a, b| { + a.name() + .to_lowercase() + .cmp(&b.name().to_lowercase()) + .then_with(|| a.id().cmp(b.id())) + }), + "uploaded" => rows.sort_by(|a, b| { + b.uploaded() + .cmp(&a.uploaded()) + .then_with(|| a.name().to_lowercase().cmp(&b.name().to_lowercase())) + }), + "size" => rows.sort_by(|a, b| { + b.size() + .cmp(&a.size()) + .then_with(|| a.name().to_lowercase().cmp(&b.name().to_lowercase())) + }), + _ => rows.sort_by(|a, b| { + b.deleted() + .cmp(&a.deleted()) + .then_with(|| a.name().to_lowercase().cmp(&b.name().to_lowercase())) + }), + } view! { cx => (topbar(cx, NavPage::Trash, &user, language).await?)

(t(language, Key::Trash))

+
+
+ (t(language, Key::Sort)) + + + +
+
+ (t(language, Key::Kind)) + + + +
+ +
(refusal_banner(cx, language, &["restore", "purge", "empty"]).await?) - if listing.folders.is_empty() && listing.files.is_empty() { -

(t(language, Key::TrashEmpty))

- } - if !listing.folders.is_empty() || !listing.files.is_empty() { + if !nothing_trashed {
} - if !listing.folders.is_empty() { -
-
-

(t(language, Key::FoldersHeading))

- (format!("{}", listing.folders.len())) -
-
- for folder in &listing.folders { -
+
+
+

(t(language, Key::Trash))

+ (rows.len().to_string()) +
+
+ if rows.is_empty() { + if nothing_trashed { +

(t(language, Key::TrashEmpty))

+ } else { +

(t(language, Key::NoResults))

+ } + } + for row in &rows { + match row { + TrashEntry::Folder(folder) =>
+ (folder.name.clone()) + (trash_details(language, row)) +
- +
- +
-
- } -
-
- } - if !listing.files.is_empty() { -
-
-

(t(language, Key::FilesHeading))

- (format!("{}", listing.files.len())) -
-
- for file in &listing.files { -
+
, + TrashEntry::File(file) =>
+ (trash_chip(cx, file).await?) (file.name.clone()) - (crate::settings::human_bytes(file.size_bytes)) + (trash_details(language, row)) +
- +
- +
-
+
, } -
-
- } + } +
+
} } diff --git a/crates/in-web/src/upload.rs b/crates/in-web/src/upload.rs index 9ebfa58..d7d4a53 100644 --- a/crates/in-web/src/upload.rs +++ b/crates/in-web/src/upload.rs @@ -3,8 +3,10 @@ //! Four owner-only JSON calls, all UTF-8: `POST /api/upload/start` //! `{folder_id, name, size_bytes}` answers `{id, chunk_size}` with the //! server-fixed 8 MiB chunk size (`Refusal::QuotaExceeded` when the quota -//! says no); `PUT /api/upload/{id}/{index}` takes one raw chunk (16 MiB -//! cap, layered in `main.rs`); `POST /api/upload/{id}/finish` assembles the +//! says no, `Refusal::UploadTooLarge` past the instance upload ceiling); +//! `PUT /api/upload/{id}/{index}` takes one raw chunk (32 MiB cap, layered +//! in `main.rs` — the real per-file ceiling lives in the start handler); +//! `POST /api/upload/{id}/finish` assembles the //! staged chunks, sniffs the mime, moves the bytes to `files/` //! and answers with the created file id; `POST /api/upload/{id}/abort` //! drops the session and its staged bytes. Quota is enforced at start *and* @@ -27,8 +29,28 @@ use crate::server::{Refusal, app, require_user}; path_param!(id); /// What the script side reads: the value, or the refusal it failed with. -/// Serialises as `{"ok":...}` / `{"err":...}`. -type Answer = std::result::Result; +/// Serialises as `{"ok":...}` / `{"err":...}` — a hand-rolled enum because +/// serde's own `Result` would say `Ok`/`Err`, which the UI script does not +/// read. +enum Answer { + Ok(T), + Err(Refusal), +} + +impl serde::Serialize for Answer { + fn serialize( + &self, + serializer: S, + ) -> std::result::Result { + use serde::ser::SerializeMap; + let mut map = serializer.serialize_map(Some(1))?; + match self { + Answer::Ok(value) => map.serialize_entry("ok", value)?, + Answer::Err(refusal) => map.serialize_entry("err", refusal)?, + } + map.end() + } +} /// A [`StoreError`] in the upload's own words. Another owner's session id /// answers [`Refusal::NotFound`]: the id space is not theirs to probe. @@ -78,26 +100,32 @@ struct StartOut { async fn start(cx: &Cx, Json(input): Json) -> Result>> { let user = match require_user(cx).await { Ok(user) => user, - Err(refusal) => return Ok(Json(Err(refusal))), + Err(refusal) => return Ok(Json(Answer::Err(refusal))), }; let store = app(cx).store.clone(); let folder = input.folder_id.as_deref().filter(|id| !id.is_empty()); if let Some(id) = folder { match store.folder(id).await { Ok(Some(row)) if row.owner_id == user.id && row.deleted_at.is_none() => {} - Ok(_) => return Ok(Json(Err(Refusal::NotFound))), - Err(_) => return Ok(Json(Err(Refusal::Unavailable))), + Ok(_) => return Ok(Json(Answer::Err(Refusal::NotFound))), + Err(_) => return Ok(Json(Answer::Err(Refusal::Unavailable))), } } + // The instance ceiling is checked against the declared total before a + // single chunk is sent: chunks can never add past the declared total + // (the store refuses that), so this one check caps the whole session. + if input.size_bytes > crate::server::effective_upload_limit(cx).await { + return Ok(Json(Answer::Err(Refusal::UploadTooLarge))); + } match store .create_upload_session(&user.id, folder, &input.name, input.size_bytes) .await { - Ok(session) => Ok(Json(Ok(StartOut { + Ok(session) => Ok(Json(Answer::Ok(StartOut { id: session.id, chunk_size: session.chunk_size, }))), - Err(error) => Ok(Json(Err(store_refusal(error)))), + Err(error) => Ok(Json(Answer::Err(store_refusal(error)))), } } @@ -113,21 +141,26 @@ struct ChunkOut { #[route(PUT "/api/upload/{id}/{index}")] async fn chunk(cx: &Cx, body: Bytes) -> Result>> { let id: &str = path_param::(cx); - let index: u64 = match uri(cx).path().rsplit('/').next().and_then(|raw| raw.parse().ok()) { + let index: u64 = match uri(cx) + .path() + .rsplit('/') + .next() + .and_then(|raw| raw.parse().ok()) + { Some(index) => index, - None => return Ok(Json(Err(Refusal::BadChunk))), + None => return Ok(Json(Answer::Err(Refusal::BadChunk))), }; let session = match owned_session(cx, id).await { Ok(session) => session, - Err(refusal) => return Ok(Json(Err(refusal))), + Err(refusal) => return Ok(Json(Answer::Err(refusal))), }; let store = app(cx).store.clone(); match store.record_chunk(&session.id, index, &body).await { - Ok(session) => Ok(Json(Ok(ChunkOut { + Ok(session) => Ok(Json(Answer::Ok(ChunkOut { received_bytes: session.received_bytes, size_bytes: session.size_bytes, }))), - Err(error) => Ok(Json(Err(store_refusal(error)))), + Err(error) => Ok(Json(Answer::Err(store_refusal(error)))), } } @@ -139,12 +172,12 @@ async fn finish(cx: &Cx) -> Result>> { let id: &str = path_param::(cx); let session = match owned_session(cx, id).await { Ok(session) => session, - Err(refusal) => return Ok(Json(Err(refusal))), + Err(refusal) => return Ok(Json(Answer::Err(refusal))), }; let store = app(cx).store.clone(); match store.finish_upload(&session.id).await { - Ok(file) => Ok(Json(Ok(file.id))), - Err(error) => Ok(Json(Err(store_refusal(error)))), + Ok(file) => Ok(Json(Answer::Ok(file.id))), + Err(error) => Ok(Json(Answer::Err(store_refusal(error)))), } } @@ -155,11 +188,11 @@ async fn abort(cx: &Cx) -> Result>> { let id: &str = path_param::(cx); let session = match owned_session(cx, id).await { Ok(session) => session, - Err(refusal) => return Ok(Json(Err(refusal))), + Err(refusal) => return Ok(Json(Answer::Err(refusal))), }; let store = app(cx).store.clone(); match store.abort_upload(&session.id).await { - Ok(_) => Ok(Json(Ok(()))), - Err(error) => Ok(Json(Err(store_refusal(error)))), + Ok(_) => Ok(Json(Answer::Ok(()))), + Err(error) => Ok(Json(Answer::Err(store_refusal(error)))), } } diff --git a/crates/in-web/tests/http.rs b/crates/in-web/tests/http.rs index c118493..a1522e3 100644 --- a/crates/in-web/tests/http.rs +++ b/crates/in-web/tests/http.rs @@ -97,20 +97,21 @@ impl FakeIm { let len = content_length(&head); let body: Vec = req[body_start..body_start + len].to_vec(); req.drain(..body_start + len); - let (status, content_type, payload) = match photo_answer(&pmap, &head, &first) { - Some(photo) => photo, - None => match answer_for(&map, &first, &body) { - Some(answer) => ( - "200 OK", - "application/json".to_string(), - serde_json::to_vec(&answer).unwrap(), - ), - // Anything but the introspection route is - // nothing at all, the way the real im 404s - // unknown paths rather than answering them. - None => ("404 Not Found", "text/plain".to_string(), Vec::new()), - }, - }; + let (status, content_type, payload) = + match photo_answer(&pmap, &head, &first) { + Some(photo) => photo, + None => match answer_for(&map, &first, &body) { + Some(answer) => ( + "200 OK", + "application/json".to_string(), + serde_json::to_vec(&answer).unwrap(), + ), + // Anything but the introspection route is + // nothing at all, the way the real im 404s + // unknown paths rather than answering them. + None => ("404 Not Found", "text/plain".to_string(), Vec::new()), + }, + }; let response = format!( "HTTP/1.1 {status}\r\ncontent-type: {content_type}\r\ncontent-length: {}\r\n\r\n", payload.len() @@ -125,7 +126,11 @@ impl FakeIm { }); } }); - Self { addr, tokens, photos } + Self { + addr, + tokens, + photos, + } } fn url(&self) -> String { @@ -158,7 +163,10 @@ fn photo_answer( return None; } let target = parts.next().unwrap_or(""); - let path = target.split_once('?').map(|(path, _)| path).unwrap_or(target); + let path = target + .split_once('?') + .map(|(path, _)| path) + .unwrap_or(target); let id = path.strip_prefix("/photo/")?; if id.is_empty() || id.contains('/') { return None; @@ -218,7 +226,8 @@ fn answer_for( body: &[u8], ) -> Option { let mut head = request_line.split_whitespace(); - let is_introspect = head.next() == Some("POST") && head.next() == Some(in_client::introspect_path()); + let is_introspect = + head.next() == Some("POST") && head.next() == Some(in_client::introspect_path()); if !is_introspect { return None; } @@ -273,6 +282,7 @@ impl TestApp { live_seconds: 300, purge_after_days: 30, default_quota_bytes: 10 * 1024 * 1024 * 1024, + max_upload_bytes: 1024 * 1024 * 1024, oidc: OidcConfig { issuer: fake.url(), client_id: "in-test".to_string(), @@ -286,8 +296,8 @@ impl TestApp { let router = in_client::mount( Router::builder() .discover() - .layer(BodyLimit::max(16 * 1024 * 1024).at("/api/upload")) - .layer(BodyLimit::max(64 * 1024 * 1024).at("/files")) + .layer(BodyLimit::max(32 * 1024 * 1024).at("/api/upload")) + .layer(BodyLimit::max(2usize * 1024 * 1024 * 1024).at("/files")) .cookies() .assets( AssetBundle::load_dir(asset_dir()) @@ -547,12 +557,10 @@ impl Answer { fn refused(&self, code: &str, call: &str) -> bool { self.status == StatusCode::SEE_OTHER - && self - .location - .as_deref() - .is_some_and(|location| { - location.contains(&format!("refusal={code}")) && location.contains(&format!("on={call}")) - }) + && self.location.as_deref().is_some_and(|location| { + location.contains(&format!("refusal={code}")) + && location.contains(&format!("on={call}")) + }) } fn accepted(&self) -> bool { @@ -601,11 +609,11 @@ fn encode(raw: &str) -> String { /// The 1x1 transparent PNG: the smallest thing the thumbnailer must accept. fn tiny_png() -> Vec { vec![ - 0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A, 0x00, 0x00, 0x00, 0x0D, 0x49, 0x48, - 0x44, 0x52, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x08, 0x06, 0x00, 0x00, - 0x00, 0x1F, 0x15, 0xC4, 0x89, 0x00, 0x00, 0x00, 0x0A, 0x49, 0x44, 0x41, 0x54, 0x78, - 0x9C, 0x63, 0x00, 0x01, 0x00, 0x00, 0x05, 0x00, 0x01, 0x0D, 0x0A, 0x2D, 0xB4, 0x00, - 0x00, 0x00, 0x00, 0x49, 0x45, 0x4E, 0x44, 0xAE, 0x42, 0x60, 0x82, + 0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A, 0x00, 0x00, 0x00, 0x0D, 0x49, 0x48, 0x44, + 0x52, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x08, 0x06, 0x00, 0x00, 0x00, 0x1F, + 0x15, 0xC4, 0x89, 0x00, 0x00, 0x00, 0x0A, 0x49, 0x44, 0x41, 0x54, 0x78, 0x9C, 0x63, 0x00, + 0x01, 0x00, 0x00, 0x05, 0x00, 0x01, 0x0D, 0x0A, 0x2D, 0xB4, 0x00, 0x00, 0x00, 0x00, 0x49, + 0x45, 0x4E, 0x44, 0xAE, 0x42, 0x60, 0x82, ] } @@ -625,7 +633,10 @@ async fn folder_id(app: &TestApp, owner: &str, parent: Option<&str>, name: &str) } /// The token off a creation redirect's `?created=` pair. fn created_token(location: &str) -> String { - let query = location.split_once('?').map(|(_, query)| query).unwrap_or(""); + let query = location + .split_once('?') + .map(|(_, query)| query) + .unwrap_or(""); query .split('&') .filter_map(|pair| pair.split_once('=')) @@ -670,7 +681,11 @@ async fn folder_crud_and_cycle_is_refused() { .unwrap(); let answer = app - .post("/api/folder/create", Some(&cookie), &[("parent_id", ""), ("name", "projects")]) + .post( + "/api/folder/create", + Some(&cookie), + &[("parent_id", ""), ("name", "projects")], + ) .await; assert_eq!(answer.status, StatusCode::SEE_OTHER, "{}", answer.body); assert_eq!(answer.body, "null", "creating was refused"); @@ -703,7 +718,11 @@ async fn folder_crud_and_cycle_is_refused() { // A legal move, a rename and a delete all land clean. let answer = app - .post("/api/folder/move", Some(&cookie), &[("id", &sub), ("parent_id", "")]) + .post( + "/api/folder/move", + Some(&cookie), + &[("id", &sub), ("parent_id", "")], + ) .await; assert_eq!(answer.body, "null", "moving was refused: {}", answer.body); let answer = app @@ -745,9 +764,18 @@ async fn small_upload_round_trip() { &[("hello.txt", "text/plain", bytes)], ) .await; - assert_eq!(answer.status, StatusCode::SEE_OTHER, "{}", answer.location.unwrap_or_default()); + assert_eq!( + answer.status, + StatusCode::SEE_OTHER, + "{}", + answer.location.unwrap_or_default() + ); assert!( - !answer.location.as_deref().unwrap_or("").contains("refusal="), + !answer + .location + .as_deref() + .unwrap_or("") + .contains("refusal="), "upload was refused: {}", answer.location.unwrap_or_default() ); @@ -768,7 +796,10 @@ async fn small_upload_round_trip() { assert_eq!(got.bytes, bytes); assert_eq!(got.accept_ranges.as_deref(), Some("bytes")); assert!( - got.cache_control.as_deref().unwrap_or("").contains("immutable"), + got.cache_control + .as_deref() + .unwrap_or("") + .contains("immutable"), "missing immutable cache directive" ); } @@ -801,8 +832,11 @@ async fn chunked_upload_round_trip() { .await; assert_eq!(answer.status, StatusCode::OK, "{}", answer.body); let started = answer.json(); - let session = started["Ok"]["id"].as_str().expect("start was refused").to_string(); - assert_eq!(started["Ok"]["chunk_size"].as_u64(), Some(8 * 1024 * 1024)); + let session = started["ok"]["id"] + .as_str() + .expect("start was refused") + .to_string(); + assert_eq!(started["ok"]["chunk_size"].as_u64(), Some(8 * 1024 * 1024)); let answer = app .put_bytes( @@ -812,13 +846,23 @@ async fn chunked_upload_round_trip() { ) .await; assert_eq!(answer.status, StatusCode::OK, "{}", answer.body); - assert_eq!(answer.json()["Ok"]["received_bytes"].as_u64(), Some(8 * 1024 * 1024)); + assert_eq!( + answer.json()["ok"]["received_bytes"].as_u64(), + Some(8 * 1024 * 1024) + ); let answer = app - .put_bytes(&format!("/api/upload/{session}/1"), Some(&cookie), &bytes[8 * 1024 * 1024..]) + .put_bytes( + &format!("/api/upload/{session}/1"), + Some(&cookie), + &bytes[8 * 1024 * 1024..], + ) .await; assert_eq!(answer.status, StatusCode::OK, "{}", answer.body); - assert_eq!(answer.json()["Ok"]["received_bytes"].as_u64(), Some(total as u64)); + assert_eq!( + answer.json()["ok"]["received_bytes"].as_u64(), + Some(total as u64) + ); let answer = app .post_json( @@ -828,7 +872,10 @@ async fn chunked_upload_round_trip() { ) .await; assert_eq!(answer.status, StatusCode::OK, "{}", answer.body); - let file_id = answer.json()["Ok"].as_str().expect("finish was refused").to_string(); + let file_id = answer.json()["ok"] + .as_str() + .expect("finish was refused") + .to_string(); let got = app.get(&format!("/file/{file_id}"), Some(&cookie)).await; assert_eq!(got.status, StatusCode::OK); @@ -901,7 +948,7 @@ async fn quota_is_refused_before_and_during_upload() { .await; assert_eq!(answer.status, StatusCode::OK, "{}", answer.body); assert_eq!( - answer.json()["Err"].as_str(), + answer.json()["err"].as_str(), Some("QuotaExceeded"), "start was not refused: {}", answer.body @@ -944,7 +991,11 @@ async fn thumbnail_is_served_after_image_upload() { ) .await; assert!( - !answer.location.as_deref().unwrap_or("").contains("refusal="), + !answer + .location + .as_deref() + .unwrap_or("") + .contains("refusal="), "image upload was refused: {}", answer.location.unwrap_or_default() ); @@ -976,11 +1027,20 @@ async fn thumbnail_is_served_after_image_upload() { async fn cross_owner_answers_not_found() { let app = TestApp::build().await; let alice = app.sign_in("sub-alice", "alice@in.test", "Alice").await; - let alice_user = app.store.user_by_oidc_sub("sub-alice").await.unwrap().unwrap(); + let alice_user = app + .store + .user_by_oidc_sub("sub-alice") + .await + .unwrap() + .unwrap(); let bob = app.sign_in("sub-bob", "bob@in.test", "Bob").await; - app.post("/api/folder/create", Some(&alice), &[("parent_id", ""), ("name", "hers")]) - .await; + app.post( + "/api/folder/create", + Some(&alice), + &[("parent_id", ""), ("name", "hers")], + ) + .await; let hers = folder_id(&app, &alice_user.id, None, "hers").await; app.post_multipart( "/files", @@ -1007,7 +1067,11 @@ async fn cross_owner_answers_not_found() { assert_eq!(page.status, StatusCode::NOT_FOUND); let answer = app - .post("/api/folder/rename", Some(&bob), &[("id", &hers), ("name", "theirs")]) + .post( + "/api/folder/rename", + Some(&bob), + &[("id", &hers), ("name", "theirs")], + ) .await; assert!( answer.body.contains("NotFound"), @@ -1028,10 +1092,19 @@ async fn cross_owner_answers_not_found() { async fn file_rename_move_and_delete() { let app = TestApp::build().await; let cookie = app.sign_in("sub-fops", "fops@in.test", "Fops").await; - let user = app.store.user_by_oidc_sub("sub-fops").await.unwrap().unwrap(); + let user = app + .store + .user_by_oidc_sub("sub-fops") + .await + .unwrap() + .unwrap(); - app.post("/api/folder/create", Some(&cookie), &[("parent_id", ""), ("name", "box")]) - .await; + app.post( + "/api/folder/create", + Some(&cookie), + &[("parent_id", ""), ("name", "box")], + ) + .await; let boxed = folder_id(&app, &user.id, None, "box").await; app.post_multipart( "/files", @@ -1051,21 +1124,34 @@ async fn file_rename_move_and_delete() { .unwrap(); let answer = app - .post("/api/file/rename", Some(&cookie), &[("id", &file.id), ("name", "renamed.txt")]) + .post( + "/api/file/rename", + Some(&cookie), + &[("id", &file.id), ("name", "renamed.txt")], + ) .await; assert_eq!(answer.body, "null", "renaming was refused: {}", answer.body); let answer = app - .post("/api/file/move", Some(&cookie), &[("id", &file.id), ("folder_id", &boxed)]) + .post( + "/api/file/move", + Some(&cookie), + &[("id", &file.id), ("folder_id", &boxed)], + ) .await; assert_eq!(answer.body, "null", "moving was refused: {}", answer.body); let moved = app.store.file(&file.id).await.unwrap().unwrap(); assert_eq!(moved.name, "renamed.txt"); assert_eq!(moved.folder_id.as_deref(), Some(boxed.as_str())); - let answer = app.post("/api/file/delete", Some(&cookie), &[("id", &file.id)]).await; + let answer = app + .post("/api/file/delete", Some(&cookie), &[("id", &file.id)]) + .await; assert_eq!(answer.body, "null", "deleting was refused: {}", answer.body); let trashed = app.store.file(&file.id).await.unwrap().unwrap(); - assert!(trashed.deleted_at.is_some(), "delete did not trash the file"); + assert!( + trashed.deleted_at.is_some(), + "delete did not trash the file" + ); // And the bytes answer 404 once trashed. let gone = app.get(&format!("/file/{}", file.id), Some(&cookie)).await; assert_eq!(gone.status, StatusCode::NOT_FOUND); @@ -1083,29 +1169,44 @@ async fn upload_abort_and_bad_chunk() { serde_json::json!({"folder_id": null, "name": "never.bin", "size_bytes": 100}), ) .await; - let session = answer.json()["Ok"]["id"].as_str().unwrap().to_string(); + let session = answer.json()["ok"]["id"].as_str().unwrap().to_string(); // A short piece is a bad chunk, not a short file. - let answer = app.put_bytes(&format!("/api/upload/{session}/0"), Some(&cookie), b"short").await; + let answer = app + .put_bytes(&format!("/api/upload/{session}/0"), Some(&cookie), b"short") + .await; assert_eq!( - answer.json()["Err"].as_str(), + answer.json()["err"].as_str(), Some("BadChunk"), "short chunk was not refused: {}", answer.body ); let answer = app - .post_json(&format!("/api/upload/{session}/abort"), Some(&cookie), serde_json::json!({})) + .post_json( + &format!("/api/upload/{session}/abort"), + Some(&cookie), + serde_json::json!({}), + ) .await; - assert_eq!(answer.json()["Ok"], serde_json::Value::Null, "{}", answer.body); + assert_eq!( + answer.json()["ok"], + serde_json::Value::Null, + "{}", + answer.body + ); // The finish after the abort finds an expired session, with the chunks // still staged for nothing. let answer = app - .post_json(&format!("/api/upload/{session}/finish"), Some(&cookie), serde_json::json!({})) + .post_json( + &format!("/api/upload/{session}/finish"), + Some(&cookie), + serde_json::json!({}), + ) .await; assert_eq!( - answer.json()["Err"].as_str(), + answer.json()["err"].as_str(), Some("UploadExpired"), "finish after abort was not refused: {}", answer.body @@ -1137,14 +1238,24 @@ async fn forced_download_is_attachment() { let inline = app.get(&format!("/file/{}", file.id), Some(&cookie)).await; assert!( - inline.disposition.as_deref().unwrap_or("").starts_with("inline"), + inline + .disposition + .as_deref() + .unwrap_or("") + .starts_with("inline"), "text should render inline: {:?}", inline.disposition ); - let forced = app.get(&format!("/file/{}?dl=1", file.id), Some(&cookie)).await; + let forced = app + .get(&format!("/file/{}?dl=1", file.id), Some(&cookie)) + .await; assert_eq!(forced.status, StatusCode::OK); assert!( - forced.disposition.as_deref().unwrap_or("").starts_with("attachment"), + forced + .disposition + .as_deref() + .unwrap_or("") + .starts_with("attachment"), "?dl=1 did not force attachment: {:?}", forced.disposition ); @@ -1316,10 +1427,18 @@ async fn cross_owner_link_create_is_not_found() { .post( "/api/share/link/create", Some(&admin), - &[("kind", "file"), ("target_id", &file), ("can_download", "1")], + &[ + ("kind", "file"), + ("target_id", &file), + ("can_download", "1"), + ], ) .await; - assert!(answer.refused("not-found", "create"), "{:?}", answer.location); + assert!( + answer.refused("not-found", "create"), + "{:?}", + answer.location + ); } // -- per-user shares -------------------------------------------------------- @@ -1406,16 +1525,30 @@ async fn trash_restore_purge_empty_flows() { // Restore one: it leaves the trash and keeps its bytes. let answer = app - .post("/api/trash/restore", Some(&admin), &[("kind", "file"), ("id", &one)]) + .post( + "/api/trash/restore", + Some(&admin), + &[("kind", "file"), ("id", &one)], + ) .await; assert!(answer.accepted(), "restore refused: {:?}", answer.location); assert!( - app.store.file(&one).await.unwrap().unwrap().deleted_at.is_none() + app.store + .file(&one) + .await + .unwrap() + .unwrap() + .deleted_at + .is_none() ); // Purge the other: the row and its bytes go. let answer = app - .post("/api/trash/purge", Some(&admin), &[("kind", "file"), ("id", &two)]) + .post( + "/api/trash/purge", + Some(&admin), + &[("kind", "file"), ("id", &two)], + ) .await; assert!(answer.accepted(), "purge refused: {:?}", answer.location); assert!(app.store.file(&two).await.unwrap().is_none()); @@ -1425,14 +1558,7 @@ async fn trash_restore_purge_empty_flows() { app.store.delete_file(&three).await.unwrap(); let answer = app.post("/api/trash/empty", Some(&admin), &[]).await; assert!(answer.accepted(), "empty refused: {:?}", answer.location); - assert!( - app.store - .list_trash(&owner) - .await - .unwrap() - .files - .is_empty() - ); + assert!(app.store.list_trash(&owner).await.unwrap().files.is_empty()); } #[tokio::test] @@ -1440,11 +1566,7 @@ async fn restore_under_trashed_ancestor_is_refused() { let app = TestApp::build().await; let admin = app.sign_in("sub-admin", "ada@in.test", "Ada").await; let owner = owner_of(&app, "sub-admin").await; - let folder = app - .store - .create_folder(&owner, None, "box") - .await - .unwrap(); + let folder = app.store.create_folder(&owner, None, "box").await.unwrap(); let file = app .store .insert_file(&owner, Some(&folder.id), "inbox.txt", b"in") @@ -1523,25 +1645,51 @@ async fn search_scopes_to_owner_and_hides_trashed() { // name: the upload control renders, no results caption does. let page = app.get("/drive", Some(&admin)).await; assert_eq!(page.status, StatusCode::OK, "{}", page.text()); - assert!(page.text().contains("id=\"upload-form\""), "{}", page.text()); + assert!( + page.text().contains("id=\"upload-form\""), + "{}", + page.text() + ); assert!(!page.text().contains("Search results"), "{}", page.text()); let page = app.get("/drive?q=quarterly", Some(&admin)).await; assert_eq!(page.status, StatusCode::OK, "{}", page.text()); - assert!(page.text().contains("quarterly report.txt"), "{}", page.text()); - assert!(!page.text().contains("quarterly notes.txt"), "{}", page.text()); - assert!(!page.text().contains("quarterly draft.txt"), "{}", page.text()); + assert!( + page.text().contains("quarterly report.txt"), + "{}", + page.text() + ); + assert!( + !page.text().contains("quarterly notes.txt"), + "{}", + page.text() + ); + assert!( + !page.text().contains("quarterly draft.txt"), + "{}", + page.text() + ); assert!(app.store.file(&mine).await.unwrap().is_some()); let page = app.get("/drive?q=quarterly", Some(&bob)).await; - assert!(page.text().contains("quarterly notes.txt"), "{}", page.text()); - assert!(!page.text().contains("quarterly report.txt"), "{}", page.text()); + assert!( + page.text().contains("quarterly notes.txt"), + "{}", + page.text() + ); + assert!( + !page.text().contains("quarterly report.txt"), + "{}", + page.text() + ); } #[tokio::test] async fn drive_search_results_merge_into_one_panel() { let app = TestApp::build().await; - let cookie = app.sign_in("sub-search-in-place", "inplace@in.test", "InPlace").await; + let cookie = app + .sign_in("sub-search-in-place", "inplace@in.test", "InPlace") + .await; let owner = owner_of(&app, "sub-search-in-place").await; let answer = app .post( @@ -1561,12 +1709,16 @@ async fn drive_search_results_merge_into_one_panel() { assert!(body.contains("holiday photos"), "{body}"); assert!(body.contains("holiday report.txt"), "{body}"); assert!(body.contains(&format!("/drive?folder={folder}")), "{body}"); - assert!(body.contains(&format!("/file/{file}")), "{body}"); + assert!(body.contains(&format!("/view/{file}")), "{body}"); let folder_at = body.find("holiday photos").expect("no folder hit"); let file_at = body.find("holiday report.txt").expect("no file hit"); assert!(folder_at < file_at, "file hit precedes folder hit: {body}"); // One panel, no heads or chips. - assert_eq!(body.matches("
").count(), 1, "{body}"); + assert_eq!( + body.matches("
").count(), + 1, + "{body}" + ); assert!(!body.contains("panel-head"), "{body}"); assert!(!body.contains("class=\"chip\""), "{body}"); assert!(!body.contains(">Folders"), "{body}"); @@ -1619,7 +1771,9 @@ async fn drive_search_never_shows_other_owners_hits() { #[tokio::test] async fn drive_search_empty_query_is_the_folder_view() { let app = TestApp::build().await; - let cookie = app.sign_in("sub-search-empty", "empty@in.test", "Empty").await; + let cookie = app + .sign_in("sub-search-empty", "empty@in.test", "Empty") + .await; let owner = owner_of(&app, "sub-search-empty").await; let _ = file_id(&app, &owner, "plain.txt", b"p").await; @@ -1673,7 +1827,10 @@ async fn topbar_nav_has_no_search_link() { assert!(nav.contains("href=\"/drive\""), "{nav}"); assert!(nav.contains("href=\"/shared\""), "{nav}"); assert!(nav.contains("href=\"/trash\""), "{nav}"); - assert!(!nav.contains("/search"), "search leaked into the nav: {nav}"); + assert!( + !nav.contains("/search"), + "search leaked into the nav: {nav}" + ); assert!(!nav.contains("Search"), "search leaked into the nav: {nav}"); } @@ -1700,7 +1857,10 @@ async fn settings_quota_and_disable_guards() { ) .await; assert!(answer.accepted(), "quota refused: {:?}", answer.location); - assert_eq!(app.store.user(&bob_id).await.unwrap().unwrap().quota_bytes, 123456); + assert_eq!( + app.store.user(&bob_id).await.unwrap().unwrap().quota_bytes, + 123456 + ); // A non-admin is refused the same call. let answer = app @@ -1710,7 +1870,11 @@ async fn settings_quota_and_disable_guards() { &[("user_id", &bob_id), ("quota_bytes", "999")], ) .await; - assert!(answer.refused("forbidden", "quota"), "{:?}", answer.location); + assert!( + answer.refused("forbidden", "quota"), + "{:?}", + answer.location + ); // Disabling yourself is refused; disabling Bob signs him out. let answer = app @@ -1720,7 +1884,11 @@ async fn settings_quota_and_disable_guards() { &[("user_id", &admin_id), ("disabled", "1")], ) .await; - assert!(answer.refused("forbidden", "disable"), "{:?}", answer.location); + assert!( + answer.refused("forbidden", "disable"), + "{:?}", + answer.location + ); let answer = app .post( @@ -1798,9 +1966,18 @@ async fn empty_file_upload_round_trip() { &[("empty.txt", "text/plain", &[])], ) .await; - assert_eq!(answer.status, StatusCode::SEE_OTHER, "{}", answer.location.clone().unwrap_or_default()); + assert_eq!( + answer.status, + StatusCode::SEE_OTHER, + "{}", + answer.location.clone().unwrap_or_default() + ); assert!( - !answer.location.as_deref().unwrap_or("").contains("refusal="), + !answer + .location + .as_deref() + .unwrap_or("") + .contains("refusal="), "empty upload was refused: {}", answer.location.clone().unwrap_or_default() ); @@ -1818,7 +1995,11 @@ async fn empty_file_upload_round_trip() { let got = app.get(&format!("/file/{}", file.id), Some(&cookie)).await; assert_eq!(got.status, StatusCode::OK); - assert!(got.bytes.is_empty(), "expected 0 bytes, got {}", got.bytes.len()); + assert!( + got.bytes.is_empty(), + "expected 0 bytes, got {}", + got.bytes.len() + ); } // -- share review regressions (FullSilkworm) ------------------------------------ @@ -1906,7 +2087,11 @@ async fn malformed_expiry_is_forbidden() { ], ) .await; - assert!(answer.accepted(), "good expiry refused: {:?}", answer.location); + assert!( + answer.accepted(), + "good expiry refused: {:?}", + answer.location + ); let links = app.store.share_links(&owner).await.unwrap(); assert_eq!(links.len(), 1); assert!( @@ -1925,7 +2110,11 @@ async fn malformed_expiry_is_forbidden() { ], ) .await; - assert!(answer.accepted(), "empty expiry refused: {:?}", answer.location); + assert!( + answer.accepted(), + "empty expiry refused: {:?}", + answer.location + ); let links = app.store.share_links(&owner).await.unwrap(); assert_eq!(links.len(), 2); assert!( @@ -1963,7 +2152,11 @@ async fn unshare_trashed_target_still_revokes() { .post( "/api/share/user/remove", Some(&admin), - &[("kind", "file"), ("target_id", &file), ("email", "bob@in.test")], + &[ + ("kind", "file"), + ("target_id", &file), + ("email", "bob@in.test"), + ], ) .await; assert!(answer.accepted(), "remove refused: {:?}", answer.location); @@ -1989,7 +2182,11 @@ async fn view_only_public_thumb_serves_webp() { ) .await; assert!( - !answer.location.as_deref().unwrap_or("").contains("refusal="), + !answer + .location + .as_deref() + .unwrap_or("") + .contains("refusal="), "image upload was refused: {}", answer.location.unwrap_or_default() ); @@ -2115,8 +2312,16 @@ async fn settings_preferences_round_trip() { assert_eq!(user.language, "en"); let page = app.get("/settings", Some(&cookie)).await; assert_eq!(page.status, StatusCode::OK, "{}", page.text()); - assert!(page.text().contains("data-ui=\"instrument\""), "{}", page.text()); - assert!(page.text().contains("data-theme=\"dark\""), "{}", page.text()); + assert!( + page.text().contains("data-ui=\"instrument\""), + "{}", + page.text() + ); + assert!( + page.text().contains("data-theme=\"dark\""), + "{}", + page.text() + ); assert!(page.text().contains("lang=\"en\""), "{}", page.text()); // Saving all three writes the row and re-renders the chrome — away from @@ -2181,7 +2386,9 @@ async fn settings_preferences_round_trip() { #[tokio::test] async fn settings_preferences_rejects_unknown_values() { let app = TestApp::build().await; - let cookie = app.sign_in("sub-prefs-bad", "prefsbad@in.test", "PrefsBad").await; + let cookie = app + .sign_in("sub-prefs-bad", "prefsbad@in.test", "PrefsBad") + .await; let me = owner_of(&app, "sub-prefs-bad").await; // Each field is refused with its own code, and the row keeps the last @@ -2193,7 +2400,11 @@ async fn settings_preferences_rejects_unknown_values() { &[("ui", "mosaic"), ("theme", "light"), ("language", "en")], ) .await; - assert!(answer.refused("bad-ui", "preferences"), "{:?}", answer.location); + assert!( + answer.refused("bad-ui", "preferences"), + "{:?}", + answer.location + ); let answer = app .post( "/api/settings/preferences", @@ -2289,8 +2500,16 @@ async fn signed_out_settings_falls_back_to_accept_language() { let page = app.get("/settings", None).await; assert_eq!(page.status, StatusCode::OK, "{}", page.text()); assert!(page.text().contains("lang=\"en\""), "{}", page.text()); - assert!(page.text().contains("data-theme=\"dark\""), "{}", page.text()); - assert!(page.text().contains("data-ui=\"instrument\""), "{}", page.text()); + assert!( + page.text().contains("data-theme=\"dark\""), + "{}", + page.text() + ); + assert!( + page.text().contains("data-ui=\"instrument\""), + "{}", + page.text() + ); assert!(page.text().contains("Sign in first."), "{}", page.text()); // A Turkish browser is answered in Turkish. let page = app @@ -2343,8 +2562,12 @@ fn assert_stage_nests(body: &str, markers: &[&str]) { #[tokio::test] async fn shared_lists_nest_inside_the_stage() { let app = TestApp::build().await; - let admin = app.sign_in("sub-stage-sharer", "sharer@in.test", "Sharer").await; - let bob = app.sign_in("sub-stage-bob", "stagebob@in.test", "StageBob").await; + let admin = app + .sign_in("sub-stage-sharer", "sharer@in.test", "Sharer") + .await; + let bob = app + .sign_in("sub-stage-bob", "stagebob@in.test", "StageBob") + .await; let owner = owner_of(&app, "sub-stage-sharer").await; let file = file_id(&app, &owner, "staged.txt", b"staged").await; let answer = app @@ -2371,7 +2594,9 @@ async fn shared_lists_nest_inside_the_stage() { #[tokio::test] async fn trash_panels_nest_inside_the_stage() { let app = TestApp::build().await; - let admin = app.sign_in("sub-stage-trash", "stagetrash@in.test", "StageTrash").await; + let admin = app + .sign_in("sub-stage-trash", "stagetrash@in.test", "StageTrash") + .await; let owner = owner_of(&app, "sub-stage-trash").await; let one = file_id(&app, &owner, "staged-trash.txt", b"staged").await; app.store.delete_file(&one).await.unwrap(); @@ -2391,7 +2616,9 @@ async fn trash_panels_nest_inside_the_stage() { #[tokio::test] async fn drive_search_panel_nests_inside_the_stage() { let app = TestApp::build().await; - let admin = app.sign_in("sub-stage-search", "stagesearch@in.test", "StageSearch").await; + let admin = app + .sign_in("sub-stage-search", "stagesearch@in.test", "StageSearch") + .await; let owner = owner_of(&app, "sub-stage-search").await; file_id(&app, &owner, "staged-report.txt", b"staged").await; let page = app.get("/drive?q=staged-report", Some(&admin)).await; @@ -2427,7 +2654,11 @@ async fn drive_root_hides_crumbs_while_a_subfolder_shows_them() { assert_eq!(page.status, StatusCode::OK, "{}", page.text()); assert!(!page.text().contains("detail-crumbs"), "{}", page.text()); // The filterbar itself stays, holding the search box and the create form. - assert!(page.text().contains("class=\"filterbar\""), "{}", page.text()); + assert!( + page.text().contains("class=\"filterbar\""), + "{}", + page.text() + ); assert!(page.text().contains("name=\"q\""), "{}", page.text()); assert!( page.text().contains("action=\"/api/folder/create\""), @@ -2437,7 +2668,11 @@ async fn drive_root_hides_crumbs_while_a_subfolder_shows_them() { // Inside a folder the way back renders. let answer = app - .post("/api/folder/create", Some(&cookie), &[("parent_id", ""), ("name", "inside")]) + .post( + "/api/folder/create", + Some(&cookie), + &[("parent_id", ""), ("name", "inside")], + ) .await; assert_eq!(answer.status, StatusCode::SEE_OTHER, "{}", answer.body); let folder = folder_id(&app, &owner, None, "inside").await; @@ -2452,7 +2687,9 @@ async fn drive_root_hides_crumbs_while_a_subfolder_shows_them() { #[tokio::test] async fn settings_quota_button_wears_the_quiet_class() { let app = TestApp::build().await; - let admin = app.sign_in("sub-quota-btn", "quotabtn@in.test", "QuotaBtn").await; + let admin = app + .sign_in("sub-quota-btn", "quotabtn@in.test", "QuotaBtn") + .await; let page = app.get("/settings", Some(&admin)).await; assert_eq!(page.status, StatusCode::OK, "{}", page.text()); let body = page.text(); @@ -2462,12 +2699,19 @@ async fn settings_quota_button_wears_the_quiet_class() { body.contains("
") .expect("quota submit is not quiet"); - let form_end = body[quota_at..].find("
").expect("quota form never closes"); - assert!(button_at < form_end, "quiet button escapes the quota form: {body}"); + let form_end = body[quota_at..] + .find("") + .expect("quota form never closes"); + assert!( + button_at < form_end, + "quiet button escapes the quota form: {body}" + ); } #[tokio::test] @@ -2482,14 +2726,20 @@ async fn settings_lives_in_the_user_menu_not_the_topbar() { let nav_start = body.find("topbar-nav-links").expect("no nav"); let nav_end = body[nav_start..].find("").expect("nav never closes"); let nav = &body[nav_start..nav_start + nav_end]; - assert!(!nav.contains("/settings"), "settings leaked into the nav: {nav}"); + assert!( + !nav.contains("/settings"), + "settings leaked into the nav: {nav}" + ); // …the user menu carries it, plus the profile link out to im. let menu_start = body.find("user-menu-panel").expect("no user menu"); let menu = &body[menu_start..]; assert!(menu.contains("href=\"/settings\""), "{menu}"); let issuer = format!("href=\"{}/\"", app.config.oidc.issuer); - assert!(menu.contains(&issuer), "no profile link to the issuer: {menu}"); + assert!( + menu.contains(&issuer), + "no profile link to the issuer: {menu}" + ); } #[tokio::test] @@ -2523,7 +2773,10 @@ async fn avatar_serves_own_photo_with_etag() { body.contains(&format!("src=\"/avatar/{me}\"")), "menu wears no photo img" ); - assert!(body.contains("avatar-stack"), "no initials stack under the photo"); + assert!( + body.contains("avatar-stack"), + "no initials stack under the photo" + ); assert!(body.contains("__inAvatar"), "no avatar fallback script"); } @@ -2541,7 +2794,9 @@ async fn avatar_without_photo_is_not_found() { #[tokio::test] async fn avatar_for_someone_else_is_not_found() { let app = TestApp::build().await; - let alice = app.sign_in("sub-alice-face", "alice@in.test", "Alice").await; + let alice = app + .sign_in("sub-alice-face", "alice@in.test", "Alice") + .await; let bob = app.sign_in("sub-bob-face", "bob@in.test", "Bob").await; let bob_id = owner_of(&app, "sub-bob-face").await; app.fake.set_photo("sub-bob-face", tiny_png(), "image/png"); @@ -2590,32 +2845,54 @@ async fn avatar_resolves_local_id_to_oidc_sub() { #[tokio::test] async fn drive_add_menu_has_two_items() { let app = TestApp::build().await; - let cookie = app.sign_in("sub-addmenu", "addmenu@in.test", "AddMenu").await; + let cookie = app + .sign_in("sub-addmenu", "addmenu@in.test", "AddMenu") + .await; let page = app.get("/drive", Some(&cookie)).await; assert_eq!(page.status, StatusCode::OK); let body = page.text(); // The filterbar carries one + menu, not the old confirm modal. - assert!(!body.contains("confirm-details"), "confirm modal still rendered"); - assert!(!body.contains("new-folder-form"), "modal form still rendered"); + assert!( + !body.contains("confirm-details"), + "confirm modal still rendered" + ); + assert!( + !body.contains("new-folder-form"), + "modal form still rendered" + ); let details_at = body.find("drive-add").expect("no + menu on the drive"); - let details_end = body[details_at..].find("").expect("menu never closes"); + let details_end = body[details_at..] + .find("") + .expect("menu never closes"); let details = &body[details_at..details_at + details_end]; // New folder: a button-only quick form posting just the parent. assert!( details.contains("action=\"/api/folder/create\""), "quick form escapes the menu: {details}" ); - assert!(details.contains("name=\"parent_id\""), "no parent field: {details}"); - assert!(!details.contains("name=\"name\""), "quick form asks for a name: {details}"); - assert!(details.contains("New folder"), "no New folder item: {details}"); + assert!( + details.contains("name=\"parent_id\""), + "no parent field: {details}" + ); + assert!( + !details.contains("name=\"name\""), + "quick form asks for a name: {details}" + ); + assert!( + details.contains("New folder"), + "no New folder item: {details}" + ); // Upload files: a label for the panel's own picker, no script needed. assert!( details.contains("for=\"drive-upload-input\""), "no upload label in the menu: {details}" ); - assert!(details.contains("Upload files"), "no Upload files item: {details}"); + assert!( + details.contains("Upload files"), + "no Upload files item: {details}" + ); assert!( body.contains("id=\"drive-upload-input\""), "upload input carries no id for the label" @@ -2629,11 +2906,22 @@ async fn drive_quick_create_names_and_edits() { let me = owner_of(&app, "sub-quick").await; // The + menu posts no name: generic name, 303 into that row's edit mode. - let answer = app.post("/api/folder/create", Some(&cookie), &[("parent_id", "")]).await; + let answer = app + .post("/api/folder/create", Some(&cookie), &[("parent_id", "")]) + .await; assert_eq!(answer.status, StatusCode::SEE_OTHER); - let location = answer.location.clone().expect("quick create redirects nowhere"); - assert!(location.starts_with("/drive?"), "quick create leaves the drive: {location}"); - assert!(location.contains("edit="), "quick create skips edit mode: {location}"); + let location = answer + .location + .clone() + .expect("quick create redirects nowhere"); + assert!( + location.starts_with("/drive?"), + "quick create leaves the drive: {location}" + ); + assert!( + location.contains("edit="), + "quick create skips edit mode: {location}" + ); let edit = location .split("edit=") .nth(1) @@ -2643,62 +2931,113 @@ async fn drive_quick_create_names_and_edits() { .unwrap(); assert_eq!(folder_id(&app, &me, None, "New folder").await, edit); - // A second quick create collision-suffixes instead of colliding. - let answer = app.post("/api/folder/create", Some(&cookie), &[("parent_id", "")]).await; - let location = answer.location.clone().expect("second quick create redirects nowhere"); - let edit = location + // Duplicate folder names are allowed: a second quick create takes the + // same generic name on a new row instead of suffixing. + let answer = app + .post("/api/folder/create", Some(&cookie), &[("parent_id", "")]) + .await; + let location = answer + .location + .clone() + .expect("second quick create redirects nowhere"); + let edit2 = location .split("edit=") .nth(1) .expect("no edit id") .split('&') .next() .unwrap(); - assert_eq!(folder_id(&app, &me, None, "New folder 2").await, edit); + assert_ne!(edit, edit2, "second quick create reused the row"); + let root = app.store.list_children(&me, None).await.unwrap(); + assert_eq!( + root.folders + .iter() + .filter(|folder| folder.name == "New folder") + .count(), + 2, + "second quick create did not repeat the generic name" + ); // A typed name keeps the old answer: back to the page, no edit mode. let answer = app - .post("/api/folder/create", Some(&cookie), &[("parent_id", ""), ("name", "typed")]) + .post( + "/api/folder/create", + Some(&cookie), + &[("parent_id", ""), ("name", "typed")], + ) .await; - assert!(answer.accepted(), "typed create refused: {:?}", answer.location); assert!( - answer.location.as_deref().is_some_and(|location| !location.contains("edit=")), + answer.accepted(), + "typed create refused: {:?}", + answer.location + ); + assert!( + answer + .location + .as_deref() + .is_some_and(|location| !location.contains("edit=")), "typed create enters edit mode: {:?}", answer.location ); folder_id(&app, &me, None, "typed").await; - // A refused typed create surfaces on the page line, once. + // A typed duplicate is accepted too — folders share names now. let answer = app - .post("/api/folder/create", Some(&cookie), &[("parent_id", ""), ("name", "typed")]) + .post( + "/api/folder/create", + Some(&cookie), + &[("parent_id", ""), ("name", "typed")], + ) .await; - assert_eq!(answer.status, StatusCode::SEE_OTHER); - assert!(answer.body.contains("NameTaken"), "dupe was not refused: {}", answer.body); - let page = app.get("/drive?refusal=name-taken&on=create", Some(&cookie)).await; - assert_eq!(page.status, StatusCode::OK); + assert!( + answer.accepted(), + "typed dupe refused: {:?}", + answer.location + ); + let root = app.store.list_children(&me, None).await.unwrap(); assert_eq!( - page.text().matches("

").count(), 1, "{body}"); + assert_eq!( + body.matches("

").count(), + 1, + "{body}" + ); assert!(!body.contains("panel-head"), "{body}"); assert!(!body.contains("class=\"chip\""), "{body}"); assert!(!body.contains(">Folders"), "{body}"); @@ -2766,10 +3123,16 @@ async fn an_empty_folder_says_how_to_fill_it() { let body = page.text(); // The single empty state names both ways to fill the folder. assert!( - body.contains("This folder is empty. Press + to create or upload, or drop files on this page."), + body.contains( + "This folder is empty. Press + to create or upload, or drop files on this page." + ), "no empty-state hint: {body}" ); - assert_eq!(body.matches("
").count(), 1, "{body}"); + assert_eq!( + body.matches("
").count(), + 1, + "{body}" + ); assert!(!body.contains("panel-head"), "{body}"); // And the upload control plus the drop handler the hint promises are on the page. assert!(body.contains("id=\"upload-form\""), "{body}"); diff --git a/style/main.scss b/style/main.scss index bb352c4..67d3d98 100644 --- a/style/main.scss +++ b/style/main.scss @@ -4354,3 +4354,248 @@ input[type="radio"] { .auth-stage { padding: 0 16px 24px; } } + +// -- file viewer page ------------------------------------------------------------ +// GET /view/{id}: the preview on its own page. The media elements reuse the +// in-app viewer classes (.viewer-media, .viewer-pdf); the stage centers +// them, the audio element takes a readable width, and the text frame wears +// the pdf box's shape. +.viewer-stage { + display: flex; + justify-content: center; + margin: 16px 0; +} + +.viewer-audio { width: min(480px, 100%); } + +.viewer-text { + width: 100%; + height: 70vh; + border: 1px solid var(--border); + border-radius: var(--radius-md); + background: var(--surface); +} + +.viewer-fallback { + display: flex; + flex-direction: column; + align-items: center; + gap: 8px; + padding: 24px 0; +} + +// -- file chips ------------------------------------------------------------------ +// entry_chip's mime-class marks: one glyph each, decorative beside the name. +// The shared rule keeps every glyph chip the same footprint next to a +// thumbnail; the tints reuse the semantic tokens, quiet enough to sit in a +// row. +.file-chip-image, +.file-chip-video, +.file-chip-audio, +.file-chip-pdf, +.file-chip-text, +.file-chip-archive, +.file-chip-generic { + justify-content: center; + min-width: 40px; + font-size: 13px; +} + +.file-chip-video { color: var(--accent-ink); } +.file-chip-audio { color: var(--violet-ink); } +.file-chip-pdf { color: var(--danger); } +.file-chip-text { color: var(--positive-ink); } +.file-chip-archive { color: var(--warn-ink); } + +// -- trash/share unified rows (TrashShareBuild) -------------------------------------- +// The folder chip beside trashed, shared and publicly-shared names: the same +// footprint as entry_chip's mime glyphs, the accent tint because folders are +// the rows' way in. +.file-chip-folder { + justify-content: center; + min-width: 40px; + font-size: 13px; + color: var(--accent-ink); +} + +// -- drive wave-2 (DriveBuild) ------------------------------------------------------- +// Options menus, rename rows, progress rows, the drop overlay and the +// persistent notice stack. One contiguous section; the house panel, chip and +// quiet rules above do the rest. + +// The row's Options menu wears the house user-menu panel; the summary hides +// its disclosure marker the way the drive-add trigger does. +.entry-options-trigger { + list-style: none; + white-space: nowrap; + + &::marker, &::-webkit-details-marker { display: none; } +} + +// The move form inside the menu: picker and submit side by side, padded like +// the link items around them. +.user-menu-item-move { + display: flex; + align-items: center; + gap: 8px; + padding: 4px 14px; + + .field-input { + flex: 1; + min-width: 0; + } +} + +// The rename row: the form itself fills the row so the input takes the +// middle and Rename/Cancel sit at the right edge, exactly where the Options +// trigger sits in the plain row. +.dep-edit-form { + display: flex; + flex: 1; + align-items: center; + gap: 10px; + min-width: 0; + + .field-input { + flex: 1; + min-width: 0; + } +} + +// Row details keep the chip-note voice: muted, small, single line. The +// dep-note never wraps mid-row; the name's ellipsis absorbs the pressure. +.dep-row > .dep-note { + white-space: nowrap; +} + +// Upload progress rows under the filterbar: name, bar, percent. The track is +// the house upload-progress rule freed of its upload-box geometry (it was +// absolutely positioned into a box the drive form never renders) — here it +// flexes beside the name it belongs to. +.upload-progress-list { + display: flex; + flex-direction: column; + gap: 8px; + margin-top: 10px; + + &:empty { display: none; } +} + +.upload-progress-row { + display: flex; + align-items: center; + gap: 10px; +} + +.upload-progress-name { + flex: 1; + min-width: 0; + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; + font-size: 12px; + color: var(--muted); +} + +.upload-progress-list .upload-progress { + position: relative; + flex: 1; + left: auto; + right: auto; + bottom: auto; + min-width: 80px; + height: 4px; +} + +.upload-progress-pct { + flex: none; + font-family: var(--font-mono); + font-size: 11px; + color: var(--muted-soft); +} + +// The full-page drop affordance: a fixed veil with the invitation centred, +// pointer-transparent so it never blocks the drop it announces. +.drop-overlay { + position: fixed; + inset: 0; + z-index: 90; + display: flex; + align-items: center; + justify-content: center; + background: var(--accent-tint, rgba(70, 85, 123, 0.12)); + border: 2px dashed var(--accent); + opacity: 0; + visibility: hidden; + pointer-events: none; + transition: opacity var(--dur-fast) var(--ease), visibility var(--dur-fast) var(--ease); +} + +.drop-overlay-show { + opacity: 1; + visibility: visible; +} + +.drop-overlay-text { + padding: 12px 20px; + background: var(--surface); + border: 1px solid var(--border-strong); + border-radius: var(--radius-lg); + box-shadow: var(--shadow-2); + font-size: 14px; + color: var(--ink); +} + +// The persistent notice stack: fixed corner cards for upload errors and +// completions, dismissed only by their ✕ — never by a swap, never by time. +.in-status-stack { + position: fixed; + right: 16px; + bottom: 16px; + z-index: 100; + display: flex; + flex-direction: column; + gap: 8px; + max-width: min(360px, 90vw); + + &:empty { display: none; } +} + +.in-status-card { + display: flex; + align-items: center; + gap: 10px; + padding: 10px 12px; + background: var(--surface); + border: 1px solid var(--border-strong); + border-radius: var(--radius-md); + box-shadow: var(--shadow-2); + font-size: 13px; + color: var(--ink); +} + +.in-status-error { + border-color: var(--danger-border); +} + +.in-status-text { + flex: 1; + min-width: 0; +} + +.in-status-dismiss { + flex: none; + display: inline-flex; + align-items: center; + justify-content: center; + width: 24px; + height: 24px; + padding: 0; + border: none; + border-radius: var(--radius-sm); + background: transparent; + color: var(--muted-soft); + cursor: pointer; + + &:hover { color: var(--danger); } +}