forge
Explore
Log in

Don't you dare go Hollow

Upload progress, admin limits, viewer pages, unified lists, sort/filter

Browse files at this commit

e806d74d1e1a3c9121910df07c57b563b352b20eAhmet Kaan GümüşParent: b0432eb
  • feat
    • upload progress, admin limits, viewer pages, unified lists, sort/filter
Show full message
feat: upload progress, admin limits, viewer pages, unified lists, sort/filter

- upload: real progress bar for all uploads (XHR for small, per-chunk
  for big); page-wide drag-and-drop with drop overlay; persistent
  dismissable status cards that survive live swaps; failure cards name
  the reason; refused uploads no longer cry 'Upload complete'
- fix: /api/upload/* answered serde's {"Ok"/"Err"} while the UI read
  .ok/.err — chunked uploads (>8MiB) could never complete from a browser
- settings: admin-defined instance upload limit (DB > in.toml > 1GiB),
  enforced at /api/upload/start and multipart /files; BodyLimit demoted
  to memory guard
- files: /view/{id} viewer page (audio/video/pdf/text/image) with
  download gating; per-type icon chips instead of one glyph for all
- store: duplicate folder names allowed (create/rename/move/restore);
  file.download_count with range-aware counting; instance setting kv
- drive: row actions merged into one Options menu; rename form buttons
  align to the Options slot; rows show uploaded date, size, downloads
- trash/shared: single interleaved list each (public card too), aligned
  buttons, details; sort/kind/search toolbars on drive, trash, shared
  (iz-style GET forms, no-JS-safe)

18 changed files +2633 -508

crates/in-core/migrations/0004_downloads_settings.sqladded+19 -0
@@ -0,0 +1,19 @@
1+-- Per-file download counts and instance-level key/value settings.
2+--
3+-- `file.download_count` counts user-facing byte serves: the download route
4+-- and the public-link bytes bump it through `record_download`, and nothing
5+-- internal — thumbnails, sniffing, the boot sweep — ever touches it. The
6+-- DEFAULT is the backfill: SQLite fills every existing row with 0 as the
7+-- column is added. Databases already carrying the column never see this file
8+-- applied piecemeal — they reach the declared shape through `in reconcile`,
9+-- whose copy map backfills the same value.
10+--
11+-- `setting` is the instance's key/value drawer, one row per key, read and
12+-- written through `get_setting`/`set_setting`. A fresh table, so an old
13+-- database simply gains it empty on rebuild.
14+ALTER TABLE file ADD COLUMN download_count INTEGER NOT NULL DEFAULT 0;
15+
16+CREATE TABLE setting (
17+ key TEXT PRIMARY KEY,
18+ value TEXT NOT NULL
19+);
crates/in-core/src/config.rsmodified+65 -0
@@ -60,6 +60,10 @@ live_seconds = 300
60 purge_after_days = 3060 purge_after_days = 30
61 # The quota a newly provisioned account starts on, in bytes. 10 GiB.61 # The quota a newly provisioned account starts on, in bytes. 10 GiB.
62 default_quota_bytes = 1073741824062 default_quota_bytes = 10737418240
63+# The default per-file upload ceiling, in bytes. 1 GiB. An admin can move it
64+# from the settings page without touching this file; this key is only the
65+# default the stored setting falls back to.
66+max_upload_bytes = 1073741824
63 # Where drive files, thumbnails and staged upload chunks live as files,67 # Where drive files, thumbnails and staged upload chunks live as files,
64 # created on boot. Not written here: it defaults to beside the database file,68 # created on boot. Not written here: it defaults to beside the database file,
65 # and the boot completes this file with the value it resolved.69 # and the boot completes this file with the value it resolved.
@@ -101,6 +105,10 @@ const DEFAULT_PURGE_AFTER_DAYS: u32 = 30;
101 /// The quota a newly provisioned account starts on: 10 GiB.105 /// The quota a newly provisioned account starts on: 10 GiB.
102 const DEFAULT_QUOTA_BYTES: u64 = 10 * 1024 * 1024 * 1024;106 const DEFAULT_QUOTA_BYTES: u64 = 10 * 1024 * 1024 * 1024;
103 107
108+/// The per-file upload ceiling when neither the stored setting nor the config
109+/// key names one: 1 GiB.
110+const DEFAULT_MAX_UPLOAD_BYTES: u64 = 1024 * 1024 * 1024;
111+
104 /// Every completable top-level key, with the comment and default a file112 /// Every completable top-level key, with the comment and default a file
105 /// missing it is completed with. `database` is not here: it has no default113 /// missing it is completed with. `database` is not here: it has no default
106 /// worth guessing, so its absence stops the boot instead. `storage` is114 /// worth guessing, so its absence stops the boot instead. `storage` is
@@ -140,6 +148,15 @@ const OPTIONAL_KEYS: &[(&str, &str)] = &[
140 "default_quota_bytes = 10737418240\n"148 "default_quota_bytes = 10737418240\n"
141 ),149 ),
142 ),150 ),
151+ (
152+ "max_upload_bytes",
153+ concat!(
154+ "# The default per-file upload ceiling, in bytes. 1 GiB. The settings\n",
155+ "# page stores the live value in the database; this key is only the\n",
156+ "# default it falls back to.\n",
157+ "max_upload_bytes = 1073741824\n"
158+ ),
159+ ),
143 ];160 ];
144 161
145 /// The `[oidc]` table of `config/in.toml`, before the values are checked.162 /// The `[oidc]` table of `config/in.toml`, before the values are checked.
@@ -166,6 +183,7 @@ struct Toml {
166 live_seconds: Option<u64>,183 live_seconds: Option<u64>,
167 purge_after_days: Option<u32>,184 purge_after_days: Option<u32>,
168 default_quota_bytes: Option<u64>,185 default_quota_bytes: Option<u64>,
186+ max_upload_bytes: Option<u64>,
169 oidc: Option<OidcToml>,187 oidc: Option<OidcToml>,
170 #[serde(flatten)]188 #[serde(flatten)]
171 other: std::collections::BTreeMap<String, toml::Value>,189 other: std::collections::BTreeMap<String, toml::Value>,
@@ -206,6 +224,9 @@ pub struct Config {
206 pub purge_after_days: u32,224 pub purge_after_days: u32,
207 /// The quota a newly provisioned account starts on, in bytes.225 /// The quota a newly provisioned account starts on, in bytes.
208 pub default_quota_bytes: u64,226 pub default_quota_bytes: u64,
227+ /// The default per-file upload ceiling, in bytes. The settings page's
228+ /// live value wins over this; this is only what an unset install enforces.
229+ pub max_upload_bytes: u64,
209 /// The OIDC provider In trusts.230 /// The OIDC provider In trusts.
210 pub oidc: OidcConfig,231 pub oidc: OidcConfig,
211 /// Keys the file sets that nothing here reads, in the order the file232 /// Keys the file sets that nothing here reads, in the order the file
@@ -334,6 +355,12 @@ impl Config {
334 355
335 let purge_after_days = toml.purge_after_days.unwrap_or(DEFAULT_PURGE_AFTER_DAYS);356 let purge_after_days = toml.purge_after_days.unwrap_or(DEFAULT_PURGE_AFTER_DAYS);
336 let default_quota_bytes = toml.default_quota_bytes.unwrap_or(DEFAULT_QUOTA_BYTES);357 let default_quota_bytes = toml.default_quota_bytes.unwrap_or(DEFAULT_QUOTA_BYTES);
358+ // Zero names no usable ceiling — it would refuse every upload — so it
359+ // reads as unset and falls through to the 1 GiB default.
360+ let max_upload_bytes = toml
361+ .max_upload_bytes
362+ .filter(|limit| *limit > 0)
363+ .unwrap_or(DEFAULT_MAX_UPLOAD_BYTES);
337 364
338 let oidc_toml = toml.oidc.ok_or(ConfigError::Missing("[oidc]"))?;365 let oidc_toml = toml.oidc.ok_or(ConfigError::Missing("[oidc]"))?;
339 let issuer = value(oidc_toml.issuer).ok_or(ConfigError::Missing("oidc.issuer"))?;366 let issuer = value(oidc_toml.issuer).ok_or(ConfigError::Missing("oidc.issuer"))?;
@@ -355,6 +382,7 @@ impl Config {
355 live_seconds,382 live_seconds,
356 purge_after_days,383 purge_after_days,
357 default_quota_bytes,384 default_quota_bytes,
385+ max_upload_bytes,
358 oidc: OidcConfig {386 oidc: OidcConfig {
359 issuer,387 issuer,
360 client_id,388 client_id,
@@ -588,6 +616,7 @@ mod tests {
588 const FULL: &str = r#"database = "in.db"616 const FULL: &str = r#"database = "in.db"
589 listen = "127.0.0.1:7655"617 listen = "127.0.0.1:7655"
590 live_seconds = 300618 live_seconds = 300
619+max_upload_bytes = 1073741824
591 purge_after_days = 30620 purge_after_days = 30
592 default_quota_bytes = 10737418240621 default_quota_bytes = 10737418240
593 [oidc]622 [oidc]
@@ -628,6 +657,7 @@ client_secret = "s3cret"
628 assert_eq!(config.live_seconds, 300);657 assert_eq!(config.live_seconds, 300);
629 assert_eq!(config.purge_after_days, 30);658 assert_eq!(config.purge_after_days, 30);
630 assert_eq!(config.default_quota_bytes, 10 * 1024 * 1024 * 1024);659 assert_eq!(config.default_quota_bytes, 10 * 1024 * 1024 * 1024);
660+ assert_eq!(config.max_upload_bytes, 1024 * 1024 * 1024);
631 assert_eq!(config.oidc.issuer, "https://id.example.com");661 assert_eq!(config.oidc.issuer, "https://id.example.com");
632 assert_eq!(662 assert_eq!(
633 config.oidc.redirect_uri,663 config.oidc.redirect_uri,
@@ -743,4 +773,39 @@ client_secret = "s3cret"
743 .join("storage")773 .join("storage")
744 );774 );
745 }775 }
776+
777+ #[test]
778+ fn an_explicit_max_upload_bytes_wins_and_absence_defaults_to_1gib() {
779+ let scratch = Scratch::new();
780+ scratch.write(&FULL.replace(
781+ "max_upload_bytes = 1073741824",
782+ "max_upload_bytes = 67108864",
783+ ));
784+ assert_eq!(scratch.load().unwrap().max_upload_bytes, 67108864);
785+ // A file silent about the key still loads, at the 1 GiB default, and
786+ // is completed with the key for the next boot to read.
787+ let scratch = Scratch::new();
788+ scratch.write(&FULL.replace("max_upload_bytes = 1073741824\n", ""));
789+ assert_eq!(
790+ scratch.load().unwrap().max_upload_bytes,
791+ 1024 * 1024 * 1024
792+ );
793+ let completed = std::fs::read_to_string(scratch.dir.join(FILE_NAME)).unwrap();
794+ assert!(completed.contains("max_upload_bytes = 1073741824"));
795+ }
796+
797+ #[test]
798+ fn zero_max_upload_bytes_reads_as_unset() {
799+ // Zero names no usable ceiling — it would refuse every upload — so it
800+ // falls through to the 1 GiB default instead of becoming the limit.
801+ let scratch = Scratch::new();
802+ scratch.write(&FULL.replace(
803+ "max_upload_bytes = 1073741824",
804+ "max_upload_bytes = 0",
805+ ));
806+ assert_eq!(
807+ scratch.load().unwrap().max_upload_bytes,
808+ 1024 * 1024 * 1024
809+ );
810+ }
746 }811 }
crates/in-core/src/store/mod.rsmodified+26 -2
@@ -134,6 +134,10 @@ pub struct File {
134 /// What the server decided the bytes are, never what the upload claimed.134 /// What the server decided the bytes are, never what the upload claimed.
135 pub mime: String,135 pub mime: String,
136 pub size_bytes: u64,136 pub size_bytes: u64,
137+ /// How many times the bytes went to a reader: the download route and the
138+ /// public-link bytes bump it through [`Store::record_download`], and
139+ /// nothing internal — thumbnails, sniffing, the boot sweep — ever does.
140+ pub download_count: u64,
137 pub thumb_state: ThumbState,141 pub thumb_state: ThumbState,
138 pub created_at: OffsetDateTime,142 pub created_at: OffsetDateTime,
139 pub updated_at: OffsetDateTime,143 pub updated_at: OffsetDateTime,
@@ -390,7 +394,8 @@ pub trait Store: 'static + Send + Sync {
390 /// means for its screen.394 /// means for its screen.
391 async fn folder(&self, id: &str) -> Result<Option<Folder>>;395 async fn folder(&self, id: &str) -> Result<Option<Folder>>;
392 396
393- /// Renames a folder. A name a live sibling wears is [`StoreError::NameTaken`].397+ /// Renames a folder. Names are labels, never identities: a live sibling
398+ /// may already wear the name, and the rename still lands.
394 async fn rename_folder(&self, id: &str, name: &str) -> Result<()>;399 async fn rename_folder(&self, id: &str, name: &str) -> Result<()>;
395 400
396 /// Moves a folder. Into its own descendant is [`StoreError::Cycle`];401 /// Moves a folder. Into its own descendant is [`StoreError::Cycle`];
@@ -445,6 +450,13 @@ pub trait Store: 'static + Send + Sync {
445 /// when no thumbnail was made, or its file went missing.450 /// when no thumbnail was made, or its file went missing.
446 async fn thumb_bytes(&self, id: &str) -> Result<Option<Vec<u8>>>;451 async fn thumb_bytes(&self, id: &str) -> Result<Option<Vec<u8>>>;
447 452
453+ /// Counts one user-facing serve of a file's bytes. Byte routes call this
454+ /// once per download they complete — not per range chunk, not per
455+ /// thumbnail, never from internal reads (sniffing, the boot sweep).
456+ /// [`Store::file_bytes`] is a pure read and does not call it. Unknown
457+ /// ids are [`StoreError::NotFound`].
458+ async fn record_download(&self, id: &str) -> Result<()>;
459+
448 // -- trash -------------------------------------------------------------460 // -- trash -------------------------------------------------------------
449 461
450 /// Everything the person trashed and has not purged: folders and files462 /// Everything the person trashed and has not purged: folders and files
@@ -459,7 +471,9 @@ pub trait Store: 'static + Send + Sync {
459 /// Restores a trashed folder and everything under it that it took with471 /// Restores a trashed folder and everything under it that it took with
460 /// it — descendants wearing the folder's own trash timestamp. Anything472 /// it — descendants wearing the folder's own trash timestamp. Anything
461 /// trashed individually before the folder keeps its earlier moment and473 /// trashed individually before the folder keeps its earlier moment and
462- /// stays trashed. Same refusals as [`Store::restore_file`].474+ /// stays trashed. Refused with [`StoreError::AncestorTrashed`] while any
475+ /// ancestor folder is still trashed; a live sibling wearing the name is
476+ /// no refusal — folder names may repeat.
463 async fn restore_folder(&self, id: &str) -> Result<()>;477 async fn restore_folder(&self, id: &str) -> Result<()>;
464 478
465 /// Purges one trashed file for good: the row goes and the bytes and479 /// Purges one trashed file for good: the row goes and the bytes and
@@ -611,6 +625,16 @@ pub trait Store: 'static + Send + Sync {
611 /// The boot sweep calls this with now; a janitor may call it any time.625 /// The boot sweep calls this with now; a janitor may call it any time.
612 async fn prune_expired_uploads(&self, now: OffsetDateTime) -> Result<u64>;626 async fn prune_expired_uploads(&self, now: OffsetDateTime) -> Result<u64>;
613 627
628+ // -- instance settings -------------------------------------------------
629+
630+ /// One instance-level setting, by key. `None` when the key was never
631+ /// set — the caller owns the default, not the row.
632+ async fn get_setting(&self, key: &str) -> Result<Option<String>>;
633+
634+ /// Writes one instance-level setting, creating or replacing the row.
635+ /// Keys are free-form; the web layer is the only writer today.
636+ async fn set_setting(&self, key: &str, value: &str) -> Result<()>;
637+
614 // -- search ------------------------------------------------------------638 // -- search ------------------------------------------------------------
615 639
616 /// Owner-scoped substring search over live file and folder names, files640 /// Owner-scoped substring search over live file and folder names, files
crates/in-core/src/store/reconcile.rsmodified+74 -18
@@ -204,10 +204,18 @@ struct TableMap {
204 204
205 /// Builds the explicit column map. Unchanged tables map every column to its205 /// Builds the explicit column map. Unchanged tables map every column to its
206 /// old self; the user table carries the migration-specific expressions for206 /// old self; the user table carries the migration-specific expressions for
207-/// `ui`, `theme` and `language`: a database old enough to predate a column207+/// `ui`, `theme` and `language`, and the file table one for
208-/// starts on the schema's own default rather than on an empty string, which208+/// `download_count`: a database old enough to predate a column starts on the
209-/// no writer would ever store and no reader would ever honour.209+/// schema's own default rather than on an empty string, which no writer
210-fn build_maps(old_has_ui: bool, old_has_theme: bool, old_has_language: bool) -> Vec<TableMap> {210+/// would ever store and no reader would ever honour. Tables the old database
211+/// predates entirely (today: `setting`) map column-for-column and are
212+/// skipped at copy time, starting empty.
213+fn build_maps(
214+ old_has_ui: bool,
215+ old_has_theme: bool,
216+ old_has_language: bool,
217+ old_has_download_count: bool,
218+) -> Vec<TableMap> {
211 vec![219 vec![
212 TableMap {220 TableMap {
213 name: "user",221 name: "user",
@@ -254,18 +262,26 @@ fn build_maps(old_has_ui: bool, old_has_theme: bool, old_has_language: bool) ->
254 },262 },
255 TableMap {263 TableMap {
256 name: "file",264 name: "file",
257- columns: old_cols(&[265+ columns: {
258- "id",266+ let mut columns = old_cols(&[
259- "owner_id",267+ "id",
260- "folder_id",268+ "owner_id",
261- "name",269+ "folder_id",
262- "mime",270+ "name",
263- "size_bytes",271+ "mime",
264- "thumb_state",272+ "size_bytes",
265- "created_at",273+ "thumb_state",
266- "updated_at",274+ "created_at",
267- "deleted_at",275+ "updated_at",
268- ]),276+ "deleted_at",
277+ ]);
278+ columns.push(if old_has_download_count {
279+ ("download_count", "old.download_count".into())
280+ } else {
281+ ("download_count", "0".into())
282+ });
283+ columns
284+ },
269 },285 },
270 TableMap {286 TableMap {
271 name: "share_link",287 name: "share_link",
@@ -300,6 +316,10 @@ fn build_maps(old_has_ui: bool, old_has_theme: bool, old_has_language: bool) ->
300 "expires_at",316 "expires_at",
301 ]),317 ]),
302 },318 },
319+ TableMap {
320+ name: "setting",
321+ columns: old_cols(&["key", "value"]),
322+ },
303 ]323 ]
304 }324 }
305 325
@@ -391,7 +411,13 @@ async fn copy_data(old_conn: &Connection, new_conn: &Connection, path: &str) ->
391 let old_has_ui = old_has_column(old_conn, "user", "ui").await?;411 let old_has_ui = old_has_column(old_conn, "user", "ui").await?;
392 let old_has_theme = old_has_column(old_conn, "user", "theme").await?;412 let old_has_theme = old_has_column(old_conn, "user", "theme").await?;
393 let old_has_language = old_has_column(old_conn, "user", "language").await?;413 let old_has_language = old_has_column(old_conn, "user", "language").await?;
394- let maps = build_maps(old_has_ui, old_has_theme, old_has_language);414+ let old_has_download_count = old_has_column(old_conn, "file", "download_count").await?;
415+ let maps = build_maps(
416+ old_has_ui,
417+ old_has_theme,
418+ old_has_language,
419+ old_has_download_count,
420+ );
395 validate_maps(new_conn, &maps).await?;421 validate_maps(new_conn, &maps).await?;
396 422
397 // Foreign keys stay off during the copy and are checked by `verify`423 // 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) ->
403 .await429 .await
404 .map_err(|e| StoreError::Backend(e.to_string()))?;430 .map_err(|e| StoreError::Backend(e.to_string()))?;
405 for map in maps {431 for map in maps {
432+ // A table the old database predates entirely (today: `setting`)
433+ // has no rows to copy; it starts empty in the rebuilt file.
434+ if !old_has_table(old_conn, map.name).await? {
435+ continue;
436+ }
406 let cols = map437 let cols = map
407 .columns438 .columns
408 .iter()439 .iter()
@@ -496,9 +527,16 @@ async fn verify(old_conn: &Connection, new_conn: &Connection) -> Result<()> {
496 "share_link",527 "share_link",
497 "share_user",528 "share_user",
498 "upload_session",529 "upload_session",
530+ "setting",
499 ];531 ];
500 for table in tables {532 for table in tables {
501- let old_count = count_rows(old_conn, table).await?;533+ // A table the old database predates starts empty: 0 old rows is
534+ // the count a missing table would have kept.
535+ let old_count = if old_has_table(old_conn, table).await? {
536+ count_rows(old_conn, table).await?
537+ } else {
538+ 0
539+ };
502 let new_count = count_rows(new_conn, table).await?;540 let new_count = count_rows(new_conn, table).await?;
503 if old_count != new_count {541 if old_count != new_count {
504 return Err(StoreError::Backend(format!(542 return Err(StoreError::Backend(format!(
@@ -597,3 +635,21 @@ async fn old_has_column(conn: &Connection, table: &str, column: &str) -> Result<
597 }635 }
598 Ok(false)636 Ok(false)
599 }637 }
638+
639+/// A probe the copy plan asks: whether the old database carries `table` at
640+/// all. A table a later migration added is absent on a database old enough
641+/// to predate it; its copy is skipped and its verify count starts at 0.
642+async fn old_has_table(conn: &Connection, table: &str) -> Result<bool> {
643+ let mut rows = conn
644+ .query(
645+ "SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = ?1",
646+ turso::params![table],
647+ )
648+ .await
649+ .map_err(|e| StoreError::Backend(e.to_string()))?;
650+ Ok(rows
651+ .next()
652+ .await
653+ .map_err(|e| StoreError::Backend(e.to_string()))?
654+ .is_some())
655+}
crates/in-core/src/store/schema.rsmodified+1 -0
@@ -17,6 +17,7 @@ pub(crate) const MIGRATIONS: &[&str] = &[
17 include_str!("../../migrations/0001_init.sql"),17 include_str!("../../migrations/0001_init.sql"),
18 include_str!("../../migrations/0002_ui.sql"),18 include_str!("../../migrations/0002_ui.sql"),
19 include_str!("../../migrations/0003_preferences.sql"),19 include_str!("../../migrations/0003_preferences.sql"),
20+ include_str!("../../migrations/0004_downloads_settings.sql"),
20 ];21 ];
21 22
22 /// The whole declared schema — every migration applied in order — as one23 /// The whole declared schema — every migration applied in order — as one
crates/in-core/src/store/turso_store.rsmodified+52 -62
@@ -39,7 +39,7 @@ const USER_COLUMNS: &str =
39 "id, oidc_sub, email, display_name, admin, disabled, quota_bytes, used_bytes, ui, created_at, last_seen_at, theme, language";39 "id, oidc_sub, email, display_name, admin, disabled, quota_bytes, used_bytes, ui, created_at, last_seen_at, theme, language";
40 const FOLDER_COLUMNS: &str = "id, owner_id, parent_id, name, created_at, deleted_at";40 const FOLDER_COLUMNS: &str = "id, owner_id, parent_id, name, created_at, deleted_at";
41 const FILE_COLUMNS: &str =41 const FILE_COLUMNS: &str =
42- "id, owner_id, folder_id, name, mime, size_bytes, thumb_state, created_at, updated_at, deleted_at";42+ "id, owner_id, folder_id, name, mime, size_bytes, thumb_state, created_at, updated_at, deleted_at, download_count";
43 const LINK_COLUMNS: &str =43 const LINK_COLUMNS: &str =
44 "id, token_hash, kind, target_id, created_by, can_download, created_at, expires_at, revoked_at";44 "id, token_hash, kind, target_id, created_by, can_download, created_at, expires_at, revoked_at";
45 const SESSION_COLUMNS: &str =45 const SESSION_COLUMNS: &str =
@@ -743,6 +743,7 @@ fn file_from(row: &Row) -> Result<File> {
743 name: text(row, 3)?,743 name: text(row, 3)?,
744 mime: text(row, 4)?,744 mime: text(row, 4)?,
745 size_bytes: row.get::<i64>(5).map_err(backend)?.max(0) as u64,745 size_bytes: row.get::<i64>(5).map_err(backend)?.max(0) as u64,
746+ download_count: row.get::<i64>(10).map_err(backend)?.max(0) as u64,
746 thumb_state: ThumbState::parse(&text(row, 6)?)?,747 thumb_state: ThumbState::parse(&text(row, 6)?)?,
747 created_at: parse_stamp(&text(row, 7)?)?,748 created_at: parse_stamp(&text(row, 7)?)?,
748 updated_at: parse_stamp(&text(row, 8)?)?,749 updated_at: parse_stamp(&text(row, 8)?)?,
@@ -982,18 +983,15 @@ impl Store for TursoStore {
982 name: &str,983 name: &str,
983 ) -> Result<Folder> {984 ) -> Result<Folder> {
984 let name = label_of(name);985 let name = label_of(name);
985- // IMMEDIATE: the name check is read-then-write. Two concurrent986+ // IMMEDIATE: the parent check and the insert are one write set, so a
986- // creates of one name each read no sibling, each pass, and the pair987+ // parent trashed mid-create still refuses. Names are not checked:
987- // leaves two folders with one name.988+ // two folders may wear one name in one place.
988 let mut conn = self.tx_conn().await?;989 let mut conn = self.tx_conn().await?;
989 let tx = conn990 let tx = conn
990 .transaction_with_behavior(TransactionBehavior::Immediate)991 .transaction_with_behavior(TransactionBehavior::Immediate)
991 .await992 .await
992 .map_err(backend)?;993 .map_err(backend)?;
993 check_live_parent(&tx, owner_id, parent_id).await?;994 check_live_parent(&tx, owner_id, parent_id).await?;
994- if folder_name_taken(&tx, owner_id, parent_id, &name, None).await? {
995- return Err(StoreError::NameTaken);
996- }
997 let id = Ulid::new().to_string();995 let id = Ulid::new().to_string();
998 let now = now_text()?;996 let now = now_text()?;
999 tx.execute(997 tx.execute(
@@ -1037,11 +1035,6 @@ impl Store for TursoStore {
1037 if folder.deleted_at.is_some() {1035 if folder.deleted_at.is_some() {
1038 return Err(StoreError::NotFound);1036 return Err(StoreError::NotFound);
1039 }1037 }
1040- if folder_name_taken(&tx, &folder.owner_id, folder.parent_id.as_deref(), &name, Some(id))
1041- .await?
1042- {
1043- return Err(StoreError::NameTaken);
1044- }
1045 tx.execute("UPDATE folder SET name = ?1 WHERE id = ?2", params![name, id])1038 tx.execute("UPDATE folder SET name = ?1 WHERE id = ?2", params![name, id])
1046 .await1039 .await
1047 .map_err(|e| map_constraint(e, StoreError::NameTaken))?;1040 .map_err(|e| map_constraint(e, StoreError::NameTaken))?;
@@ -1073,9 +1066,6 @@ impl Store for TursoStore {
1073 }1066 }
1074 cursor = parent_of(&tx, &current).await?;1067 cursor = parent_of(&tx, &current).await?;
1075 }1068 }
1076- if folder_name_taken(&tx, &folder.owner_id, parent_id, &folder.name, Some(id)).await? {
1077- return Err(StoreError::NameTaken);
1078- }
1079 tx.execute(1069 tx.execute(
1080 "UPDATE folder SET parent_id = ?1 WHERE id = ?2",1070 "UPDATE folder SET parent_id = ?1 WHERE id = ?2",
1081 params![parent_id, id],1071 params![parent_id, id],
@@ -1402,6 +1392,50 @@ impl Store for TursoStore {
1402 }1392 }
1403 }1393 }
1404 1394
1395+ async fn record_download(&self, id: &str) -> Result<()> {
1396+ let conn = self.conn.lock().await;
1397+ let mut rows = conn
1398+ .query("SELECT owner_id FROM file WHERE id = ?1", params![id])
1399+ .await
1400+ .map_err(backend)?;
1401+ let owner = match rows.next().await.map_err(backend)? {
1402+ Some(row) => text(&row, 0)?,
1403+ None => return Err(StoreError::NotFound),
1404+ };
1405+ drop(rows);
1406+ conn.execute(
1407+ "UPDATE file SET download_count = download_count + 1 WHERE id = ?1",
1408+ params![id],
1409+ )
1410+ .await
1411+ .map_err(backend)?;
1412+ drop(conn);
1413+ self.announce([Topic::Library(owner)]);
1414+ Ok(())
1415+ }
1416+
1417+ async fn get_setting(&self, key: &str) -> Result<Option<String>> {
1418+ match self
1419+ .one_row("SELECT value FROM setting WHERE key = ?1", params![key])
1420+ .await?
1421+ {
1422+ Some(row) => Ok(Some(text(&row, 0)?)),
1423+ None => Ok(None),
1424+ }
1425+ }
1426+
1427+ async fn set_setting(&self, key: &str, value: &str) -> Result<()> {
1428+ let conn = self.conn.lock().await;
1429+ conn.execute(
1430+ "INSERT INTO setting (key, value) VALUES (?1, ?2) \
1431+ ON CONFLICT (key) DO UPDATE SET value = excluded.value",
1432+ params![key, value],
1433+ )
1434+ .await
1435+ .map_err(backend)?;
1436+ Ok(())
1437+ }
1438+
1405 async fn thumb_bytes(&self, id: &str) -> Result<Option<Vec<u8>>> {1439 async fn thumb_bytes(&self, id: &str) -> Result<Option<Vec<u8>>> {
1406 let conn = self.conn.lock().await;1440 let conn = self.conn.lock().await;
1407 let mut rows = conn1441 let mut rows = conn
@@ -1519,17 +1553,6 @@ impl Store for TursoStore {
1519 if let Some(parent_id) = folder.parent_id.as_deref() {1553 if let Some(parent_id) = folder.parent_id.as_deref() {
1520 ancestor_trashed(&tx, parent_id).await?;1554 ancestor_trashed(&tx, parent_id).await?;
1521 }1555 }
1522- if folder_name_taken(
1523- &tx,
1524- &folder.owner_id,
1525- folder.parent_id.as_deref(),
1526- &folder.name,
1527- Some(id),
1528- )
1529- .await?
1530- {
1531- return Err(StoreError::NameTaken);
1532- }
1533 let now = now_text()?;1556 let now = now_text()?;
1534 // Only the cascade comes back: descendants wear the folder's own1557 // Only the cascade comes back: descendants wear the folder's own
1535 // trash timestamp when the folder took them with it, while anything1558 // trash timestamp when the folder took them with it, while anything
@@ -2532,43 +2555,10 @@ async fn check_live_parent_on(
2532 check_live_parent(conn, owner_id, parent_id).await2555 check_live_parent(conn, owner_id, parent_id).await
2533 }2556 }
2534 2557
2535-/// Whether a live sibling folder already wears `name`. Trashed rows do not2558+/// Whether a live sibling file already wears `name`. Trashed rows do not
2536 /// count — deleting a name frees it — and `exclude` skips the row being2559 /// count — deleting a name frees it — and `exclude` skips the row being
2537-/// renamed or moved.2560+/// renamed or moved. Folders and files keep separate namespaces: a folder
2538-async fn folder_name_taken(2561+/// and a file may share a name in one directory.
2539- conn: &Connection,
2540- owner_id: &str,
2541- parent_id: Option<&str>,
2542- name: &str,
2543- exclude: Option<&str>,
2544-) -> Result<bool> {
2545- let exclude = exclude.unwrap_or("");
2546- let mut rows = match parent_id {
2547- Some(parent) => {
2548- conn.query(
2549- "SELECT 1 FROM folder WHERE owner_id = ?1 AND parent_id = ?2 \
2550- AND name = ?3 AND deleted_at IS NULL AND id <> ?4",
2551- params![owner_id, parent, name, exclude],
2552- )
2553- .await
2554- .map_err(backend)?
2555- }
2556- None => {
2557- conn.query(
2558- "SELECT 1 FROM folder WHERE owner_id = ?1 AND parent_id IS NULL \
2559- AND name = ?2 AND deleted_at IS NULL AND id <> ?3",
2560- params![owner_id, name, exclude],
2561- )
2562- .await
2563- .map_err(backend)?
2564- }
2565- };
2566- Ok(rows.next().await.map_err(backend)?.is_some())
2567-}
2568-
2569-/// Whether a live sibling file already wears `name`, same rules as
2570-/// [`folder_name_taken`]. Folders and files keep separate namespaces: a
2571-/// folder and a file may share a name in one directory.
2572 async fn file_name_taken(2562 async fn file_name_taken(
2573 conn: &Connection,2563 conn: &Connection,
2574 owner_id: &str,2564 owner_id: &str,
crates/in-core/tests/store.rsmodified+113 -14
@@ -169,7 +169,7 @@ async fn quota_and_disablement_round_trip() {
169 }169 }
170 170
171 #[tokio::test]171 #[tokio::test]
172-async fn folders_nest_and_names_are_unique_among_live_siblings() {172+async fn folders_allow_duplicate_names_among_live_siblings() {
173 let scratch = Scratch::open().await;173 let scratch = Scratch::open().await;
174 let user = alice(&scratch.store).await;174 let user = alice(&scratch.store).await;
175 let root = scratch175 let root = scratch
@@ -184,11 +184,10 @@ async fn folders_nest_and_names_are_unique_among_live_siblings() {
184 .unwrap();184 .unwrap();
185 assert_eq!(kid.parent_id.as_deref(), Some(root.id.as_str()));185 assert_eq!(kid.parent_id.as_deref(), Some(root.id.as_str()));
186 186
187- assert!(matches!(187+ // A live sibling wearing the name is no refusal: folders share names.
188- scratch.store.create_folder(&user.id, None, "root").await,188+ let twin = scratch.store.create_folder(&user.id, None, "root").await.unwrap();
189- Err(StoreError::NameTaken)189+ assert_ne!(twin.id, root.id);
190- ));190+ // Same name in a different directory is a different name, as before.
191- // Same name in a different directory is a different name.
192 scratch191 scratch
193 .store192 .store
194 .create_folder(&user.id, Some(&root.id), "root")193 .create_folder(&user.id, Some(&root.id), "root")
@@ -196,7 +195,7 @@ async fn folders_nest_and_names_are_unique_among_live_siblings() {
196 .unwrap();195 .unwrap();
197 196
198 let listing = scratch.store.list_children(&user.id, None).await.unwrap();197 let listing = scratch.store.list_children(&user.id, None).await.unwrap();
199- assert_eq!(listing.folders.len(), 1);198+ assert_eq!(listing.folders.len(), 2);
200 let listing = scratch199 let listing = scratch
201 .store200 .store
202 .list_children(&user.id, Some(&root.id))201 .list_children(&user.id, Some(&root.id))
@@ -508,19 +507,18 @@ async fn trashing_a_folder_cascades_and_restore_needs_live_ancestors() {
508 }507 }
509 508
510 #[tokio::test]509 #[tokio::test]
511-async fn a_trashed_name_is_free_until_restored() {510+async fn a_trashed_folder_name_restores_beside_a_live_twin() {
512 let scratch = Scratch::open().await;511 let scratch = Scratch::open().await;
513 let user = alice(&scratch.store).await;512 let user = alice(&scratch.store).await;
514 let first = scratch.store.create_folder(&user.id, None, "x").await.unwrap();513 let first = scratch.store.create_folder(&user.id, None, "x").await.unwrap();
515 scratch.store.delete_folder(&first.id).await.unwrap();514 scratch.store.delete_folder(&first.id).await.unwrap();
516- // Deleting frees the name; restoring onto a live squatter is refused.515+ // Deleting frees the name, and restoring beside the squatter is fine:
516+ // folder names may repeat.
517 scratch.store.create_folder(&user.id, None, "x").await.unwrap();517 scratch.store.create_folder(&user.id, None, "x").await.unwrap();
518- assert!(matches!(518+ scratch.store.restore_folder(&first.id).await.unwrap();
519- scratch.store.restore_folder(&first.id).await,519+ let listing = scratch.store.list_children(&user.id, None).await.unwrap();
520- Err(StoreError::NameTaken)520+ assert_eq!(listing.folders.iter().filter(|folder| folder.name == "x").count(), 2);
521- ));
522 }521 }
523-
524 #[tokio::test]522 #[tokio::test]
525 async fn used_bytes_counts_trash_and_purge_frees_it() {523 async fn used_bytes_counts_trash_and_purge_frees_it() {
526 let scratch = Scratch::open().await;524 let scratch = Scratch::open().await;
@@ -1215,3 +1213,104 @@ async fn a_second_migration_database_gains_the_preference_columns_on_open() {
1215 drop(store);1213 drop(store);
1216 let _ = std::fs::remove_dir_all(&dir);1214 let _ = std::fs::remove_dir_all(&dir);
1217 }1215 }
1216+
1217+#[tokio::test]
1218+async fn renaming_or_moving_a_folder_onto_a_live_sibling_name_succeeds() {
1219+ let scratch = Scratch::open().await;
1220+ let user = alice(&scratch.store).await;
1221+ let parent = scratch.store.create_folder(&user.id, None, "parent").await.unwrap();
1222+ let other = scratch.store.create_folder(&user.id, None, "other").await.unwrap();
1223+
1224+ // Renaming onto a live sibling's name lands.
1225+ scratch.store.rename_folder(&other.id, "parent").await.unwrap();
1226+ let back: Folder = scratch.store.folder(&other.id).await.unwrap().unwrap();
1227+ assert_eq!(back.name, "parent");
1228+
1229+ // Moving under a parent is refused for strangers and the trashed, but
1230+ // never for a name: a live child wearing the name is no obstacle.
1231+ let kid = scratch
1232+ .store
1233+ .create_folder(&user.id, Some(&parent.id), "kid")
1234+ .await
1235+ .unwrap();
1236+ scratch.store.create_folder(&user.id, None, "kid").await.unwrap();
1237+ scratch.store.move_folder(&kid.id, None).await.unwrap();
1238+ let back: Folder = scratch.store.folder(&kid.id).await.unwrap().unwrap();
1239+ assert_eq!(back.parent_id, None);
1240+ let listing = scratch.store.list_children(&user.id, None).await.unwrap();
1241+ assert_eq!(listing.folders.iter().filter(|folder| folder.name == "kid").count(), 2);
1242+}
1243+
1244+#[tokio::test]
1245+async fn file_names_stay_unique_among_live_siblings() {
1246+ let scratch = Scratch::open().await;
1247+ let user = alice(&scratch.store).await;
1248+ let first = scratch.store.insert_file(&user.id, None, "note", b"one").await.unwrap();
1249+ // A live sibling wearing the name still refuses: files, unlike folders,
1250+ // keep one name per directory.
1251+ assert!(matches!(
1252+ scratch.store.insert_file(&user.id, None, "note", b"two").await,
1253+ Err(StoreError::NameTaken)
1254+ ));
1255+ let other = scratch.store.insert_file(&user.id, None, "other", b"two").await.unwrap();
1256+ assert!(matches!(
1257+ scratch.store.rename_file(&other.id, "note").await,
1258+ Err(StoreError::NameTaken)
1259+ ));
1260+ // Trashing frees the name; restoring onto a squatter still refuses.
1261+ scratch.store.delete_file(&first.id).await.unwrap();
1262+ scratch.store.insert_file(&user.id, None, "note", b"three").await.unwrap();
1263+ assert!(matches!(
1264+ scratch.store.restore_file(&first.id).await,
1265+ Err(StoreError::NameTaken)
1266+ ));
1267+}
1268+
1269+#[tokio::test]
1270+async fn download_count_starts_at_zero_and_counts_serves() {
1271+ let scratch = Scratch::open().await;
1272+ let user = alice(&scratch.store).await;
1273+ let bytes = b"count me";
1274+ let file = scratch.store.insert_file(&user.id, None, "counted", bytes).await.unwrap();
1275+ assert_eq!(file.download_count, 0);
1276+
1277+ // The row agrees: a fresh insert was never served.
1278+ let back = scratch.store.file(&file.id).await.unwrap().unwrap();
1279+ assert_eq!(back.download_count, 0);
1280+
1281+ scratch.store.record_download(&file.id).await.unwrap();
1282+ scratch.store.record_download(&file.id).await.unwrap();
1283+ let back = scratch.store.file(&file.id).await.unwrap().unwrap();
1284+ assert_eq!(back.download_count, 2);
1285+
1286+ // A byte read is pure: it serves the bytes without counting, so range
1287+ // probes and chunks never inflate the count — only record_download does.
1288+ let served = scratch.store.file_bytes(&file.id).await.unwrap().unwrap();
1289+ assert_eq!(served, bytes);
1290+ let back = scratch.store.file(&file.id).await.unwrap().unwrap();
1291+ assert_eq!(back.download_count, 2);
1292+ assert!(scratch.store.file_bytes("no-such-file").await.unwrap().is_none());
1293+ assert!(matches!(
1294+ scratch.store.record_download("no-such-file").await,
1295+ Err(StoreError::NotFound)
1296+ ));
1297+}
1298+
1299+#[tokio::test]
1300+async fn settings_round_trip_from_missing() {
1301+ let scratch = Scratch::open().await;
1302+ let store = &scratch.store;
1303+ assert_eq!(store.get_setting("ui.density").await.unwrap(), None);
1304+ store.set_setting("ui.density", "ledger").await.unwrap();
1305+ assert_eq!(
1306+ store.get_setting("ui.density").await.unwrap(),
1307+ Some("ledger".to_string())
1308+ );
1309+ // Replacing the value replaces the row, and other keys are untouched.
1310+ store.set_setting("ui.density", "instrument").await.unwrap();
1311+ assert_eq!(
1312+ store.get_setting("ui.density").await.unwrap(),
1313+ Some("instrument".to_string())
1314+ );
1315+ assert_eq!(store.get_setting("ui.other").await.unwrap(), None);
1316+}
crates/in-web/src/drive.rsmodified+533 -96
@@ -13,7 +13,7 @@
13 //! plain GET form. The old `GET /search?q=` address 303s here, so old links13 //! plain GET form. The old `GET /search?q=` address 303s here, so old links
14 //! keep working.14 //! keep working.
15 15
16-use in_core::store::{Folder, Store, StoreError, ThumbState};16+use in_core::store::{Folder, Store, StoreError};
17 use topcoat::router::request::uri;17 use topcoat::router::request::uri;
18 use topcoat::router::{HeaderName, HeaderValue, StatusCode, header, page, query_params, route};18 use topcoat::router::{HeaderName, HeaderValue, StatusCode, header, page, query_params, route};
19 19
@@ -61,6 +61,9 @@ struct DriveQuery {
61 folder: Option<String>,61 folder: Option<String>,
62 q: Option<String>,62 q: Option<String>,
63 edit: Option<String>,63 edit: Option<String>,
64+ sort: Option<String>,
65+ dir: Option<String>,
66+ kind: Option<String>,
64 }67 }
65 68
66 /// The folder the query names, if it names one this account may open: owned,69 /// The folder the query names, if it names one this account may open: owned,
@@ -161,6 +164,129 @@ fn created_token(query: &str) -> Option<String> {
161 (name == "created" && !value.is_empty()).then(|| value.to_string())164 (name == "created" && !value.is_empty()).then(|| value.to_string())
162 })165 })
163 }166 }
167+/// The drive listing's sort key: `None` is the standing order —
168+/// folders-then-files as the store listed them — anything else re-orders
169+/// each group in place. Unknown values fall back to the standing order,
170+/// never to a refusal: a hand-edited query names nothing fancy, not an
171+/// error.
172+#[derive(Clone, Copy, PartialEq, Eq)]
173+enum SortKey {
174+ Name,
175+ Uploaded,
176+ Size,
177+ Downloads,
178+}
179+
180+impl SortKey {
181+ fn as_str(self) -> &'static str {
182+ match self {
183+ SortKey::Name => "name",
184+ SortKey::Uploaded => "uploaded",
185+ SortKey::Size => "size",
186+ SortKey::Downloads => "downloads",
187+ }
188+ }
189+}
190+
191+/// The sort direction. Absent or unknown falls back per key — ascending
192+/// for names, descending for the recency/count keys — the way iz reads.
193+#[derive(Clone, Copy, PartialEq, Eq)]
194+enum SortDir {
195+ Asc,
196+ Desc,
197+}
198+
199+impl SortDir {
200+ fn as_str(self) -> &'static str {
201+ match self {
202+ SortDir::Asc => "asc",
203+ SortDir::Desc => "desc",
204+ }
205+ }
206+}
207+
208+/// The kind filter: everything, folders only, files only.
209+#[derive(Clone, Copy, PartialEq, Eq)]
210+enum KindFilter {
211+ All,
212+ Folders,
213+ Files,
214+}
215+
216+impl KindFilter {
217+ fn as_str(self) -> &'static str {
218+ match self {
219+ KindFilter::All => "all",
220+ KindFilter::Folders => "folders",
221+ KindFilter::Files => "files",
222+ }
223+ }
224+}
225+
226+fn parse_sort(raw: Option<&str>) -> Option<SortKey> {
227+ match raw.unwrap_or("") {
228+ "name" => Some(SortKey::Name),
229+ "uploaded" => Some(SortKey::Uploaded),
230+ "size" => Some(SortKey::Size),
231+ "downloads" => Some(SortKey::Downloads),
232+ _ => None,
233+ }
234+}
235+
236+fn parse_dir(raw: Option<&str>, key: Option<SortKey>) -> SortDir {
237+ match raw.unwrap_or("") {
238+ "asc" => SortDir::Asc,
239+ "desc" => SortDir::Desc,
240+ _ => match key {
241+ Some(SortKey::Name) | None => SortDir::Asc,
242+ _ => SortDir::Desc,
243+ },
244+ }
245+}
246+
247+fn parse_kind(raw: Option<&str>) -> KindFilter {
248+ match raw.unwrap_or("") {
249+ "folders" => KindFilter::Folders,
250+ "files" => KindFilter::Files,
251+ _ => KindFilter::All,
252+ }
253+}
254+
255+/// Order one folder group in place. Folders carry no size or download
256+/// count, so those keys fall back to the name order rather than inventing
257+/// one; the direction still applies.
258+fn sort_folders(folders: &mut [Folder], key: SortKey, dir: SortDir) {
259+ folders.sort_by(|a, b| {
260+ let order = match key {
261+ SortKey::Name | SortKey::Size | SortKey::Downloads => {
262+ a.name.to_lowercase().cmp(&b.name.to_lowercase())
263+ }
264+ SortKey::Uploaded => a.created_at.cmp(&b.created_at),
265+ }
266+ .then_with(|| a.id.cmp(&b.id));
267+ match dir {
268+ SortDir::Asc => order,
269+ SortDir::Desc => order.reverse(),
270+ }
271+ });
272+}
273+
274+/// Order one file group in place.
275+fn sort_files(files: &mut [in_core::store::File], key: SortKey, dir: SortDir) {
276+ files.sort_by(|a, b| {
277+ let order = match key {
278+ SortKey::Name => a.name.to_lowercase().cmp(&b.name.to_lowercase()),
279+ SortKey::Uploaded => a.created_at.cmp(&b.created_at),
280+ SortKey::Size => a.size_bytes.cmp(&b.size_bytes),
281+ SortKey::Downloads => a.download_count.cmp(&b.download_count),
282+ }
283+ .then_with(|| a.id.cmp(&b.id));
284+ match dir {
285+ SortDir::Asc => order,
286+ SortDir::Desc => order.reverse(),
287+ }
288+ });
289+}
164 290
165 /// `GET /drive?folder=<id>`: one directory.291 /// `GET /drive?folder=<id>`: one directory.
166 #[page("/drive")]292 #[page("/drive")]
@@ -189,20 +315,57 @@ async fn drive(cx: &Cx) -> Result {
189 .and_then(|query| query.q.clone())315 .and_then(|query| query.q.clone())
190 .map(|query| query.trim().to_string())316 .map(|query| query.trim().to_string())
191 .filter(|query| !query.is_empty());317 .filter(|query| !query.is_empty());
192- let hits = match asked.as_deref() {318+ // The toolbar's listing controls: unknown values fall back to the
319+ // standing order (folders-then-files as listed), ascending names, and
320+ // the unfiltered kind — a hand-edited query re-orders nothing, it
321+ // never refuses.
322+ let sort_key = params
323+ .as_ref()
324+ .and_then(|query| parse_sort(query.sort.as_deref()));
325+ let sort_dir = parse_dir(
326+ params.as_ref().and_then(|query| query.dir.as_deref()),
327+ sort_key,
328+ );
329+ let kind = params
330+ .as_ref()
331+ .map(|query| parse_kind(query.kind.as_deref()))
332+ .unwrap_or(KindFilter::All);
333+ let mut hits = match asked.as_deref() {
193 Some(query) => Some(store.search(&user.id, query, LIMIT).await?),334 Some(query) => Some(store.search(&user.id, query, LIMIT).await?),
194 None => None,335 None => None,
195 };336 };
196 let box_text = asked.clone().unwrap_or_default();337 let box_text = asked.clone().unwrap_or_default();
197 let current = current_folder(store.as_ref(), &user.id, wanted.as_deref()).await?;338 let current = current_folder(store.as_ref(), &user.id, wanted.as_deref()).await?;
198 let crumbs = breadcrumbs(store.as_ref(), current.as_ref()).await;339 let crumbs = breadcrumbs(store.as_ref(), current.as_ref()).await;
199- let listing = match store340+ let mut listing = match store
200 .list_children(&user.id, current.as_ref().map(|folder| folder.id.as_str()))341 .list_children(&user.id, current.as_ref().map(|folder| folder.id.as_str()))
201 .await342 .await
202 {343 {
203 Ok(listing) => listing,344 Ok(listing) => listing,
204 Err(_) => return Err(not_found().into()),345 Err(_) => return Err(not_found().into()),
205 };346 };
347+ // Sort and filter in the page layer, after the fetch — no store API
348+ // change. Each group keeps its own order; folders-then-files stands.
349+ if let Some(key) = sort_key {
350+ sort_folders(&mut listing.folders, key, sort_dir);
351+ sort_files(&mut listing.files, key, sort_dir);
352+ }
353+ match kind {
354+ KindFilter::All => {}
355+ KindFilter::Folders => listing.files.clear(),
356+ KindFilter::Files => listing.folders.clear(),
357+ }
358+ if let Some(found) = hits.as_mut() {
359+ if let Some(key) = sort_key {
360+ sort_folders(&mut found.folders, key, sort_dir);
361+ sort_files(&mut found.files, key, sort_dir);
362+ }
363+ match kind {
364+ KindFilter::All => {}
365+ KindFilter::Folders => found.files.clear(),
366+ KindFilter::Files => found.folders.clear(),
367+ }
368+ }
206 let destinations = folder_tree(store.as_ref(), &user.id).await;369 let destinations = folder_tree(store.as_ref(), &user.id).await;
207 let refusal = page_refusal(cx);370 let refusal = page_refusal(cx);
208 // Which folder row (if any) renders as its rename form: iz's `?edit=`371 // Which folder row (if any) renders as its rename form: iz's `?edit=`
@@ -222,15 +385,43 @@ async fn drive(cx: &Cx) -> Result {
222 .map(|folder| folder.name.clone())385 .map(|folder| folder.name.clone())
223 .unwrap_or_else(|| t(language, Key::Drive).to_string());386 .unwrap_or_else(|| t(language, Key::Drive).to_string());
224 // The folder view without `?edit=`: the rename form's cancel target and387 // The folder view without `?edit=`: the rename form's cancel target and
225- // the base the edit links extend.388+ // the base the edit links extend. The listing controls ride along so a
226- let here = if current_id.is_empty() {389+ // rename round-trip keeps the order and filter the reader chose; every
390+ // value here is an id or a fixed vocabulary word, so no encoding is
391+ // owed.
392+ let mut here_bits: Vec<String> = Vec::new();
393+ if !current_id.is_empty() {
394+ here_bits.push(format!("folder={current_id}"));
395+ }
396+ if let Some(key) = sort_key {
397+ here_bits.push(format!("sort={}", key.as_str()));
398+ }
399+ if params
400+ .as_ref()
401+ .and_then(|query| query.dir.clone())
402+ .is_some_and(|dir| dir == "asc" || dir == "desc")
403+ {
404+ here_bits.push(format!("dir={}", sort_dir.as_str()));
405+ }
406+ if kind != KindFilter::All {
407+ here_bits.push(format!("kind={}", kind.as_str()));
408+ }
409+ let here = if here_bits.is_empty() {
227 "/drive".to_string()410 "/drive".to_string()
228 } else {411 } else {
229- format!("/drive?folder={current_id}")412+ format!("/drive?{}", here_bits.join("&"))
413+ };
414+ // The edit links extend `here` with the matching separator.
415+ let edit_sep = if here.contains('?') { "&" } else { "?" };
416+ // The direction the toggle offers: the opposite of what is showing.
417+ let dir_flip = match sort_dir {
418+ SortDir::Asc => "desc",
419+ SortDir::Desc => "asc",
420+ };
421+ let dir_glyph = match sort_dir {
422+ SortDir::Asc => "↑",
423+ SortDir::Desc => "↓",
230 };424 };
231- // `here` carries no query at the root, one under a folder — the edit
232- // links extend it with the matching separator.
233- let edit_sep = if current_id.is_empty() { "?" } else { "&" };
234 425
235 view! {426 view! {
236 cx =>427 cx =>
@@ -250,17 +441,69 @@ async fn drive(cx: &Cx) -> Result {
250 </nav>441 </nav>
251 }442 }
252 }443 }
253- <form class="field-box-search" method="get" action="/drive">444+ <form class="field-box field-box-search" method="get" action="/drive">
445+ <span class="field-text">(t(language, Key::SearchPlaceholder))</span>
254 <input446 <input
255- class="field-input"447+ class="dd-search"
256 type="search"448 type="search"
257 name="q"449 name="q"
258- value=(box_text)450+ value=(box_text.clone())
259 placeholder=(t(language, Key::SearchPlaceholder))451 placeholder=(t(language, Key::SearchPlaceholder))
260 aria-label=(t(language, Key::SearchPlaceholder))452 aria-label=(t(language, Key::SearchPlaceholder))
261 >453 >
454+ <input type="hidden" name="folder" value=(current_id.clone())>
455+ if sort_key.is_some() {
456+ <input type="hidden" name="sort" value=(sort_key.map(|key| key.as_str()).unwrap_or(""))>
457+ }
458+ <input type="hidden" name="dir" value=(sort_dir.as_str())>
459+ if kind != KindFilter::All {
460+ <input type="hidden" name="kind" value=(kind.as_str())>
461+ }
262 </form>462 </form>
263 <div class="spacer"></div>463 <div class="spacer"></div>
464+ <form class="field-box field-box-sort" method="get" action="/drive">
465+ <span class="field-text">(t(language, Key::Sort))</span>
466+ <select class="status-select" name="sort" data-autosubmit="" aria-label=(t(language, Key::Sort))>
467+ <option value="name" selected=(sort_key.is_none() || sort_key == Some(SortKey::Name))>(t(language, Key::SortName))</option>
468+ <option value="uploaded" selected=(sort_key == Some(SortKey::Uploaded))>(t(language, Key::SortUploaded))</option>
469+ <option value="size" selected=(sort_key == Some(SortKey::Size))>(t(language, Key::SortSize))</option>
470+ <option value="downloads" selected=(sort_key == Some(SortKey::Downloads))>(t(language, Key::SortDownloads))</option>
471+ </select>
472+ <input type="hidden" name="folder" value=(current_id.clone())>
473+ <input type="hidden" name="q" value=(box_text.clone())>
474+ <input type="hidden" name="dir" value=(sort_dir.as_str())>
475+ if kind != KindFilter::All {
476+ <input type="hidden" name="kind" value=(kind.as_str())>
477+ }
478+ <button class="quiet" type="submit" aria-label=(t(language, Key::Sort))>"→"</button>
479+ </form>
480+ <form class="field-box field-box-sort" method="get" action="/drive">
481+ <input type="hidden" name="folder" value=(current_id.clone())>
482+ <input type="hidden" name="q" value=(box_text.clone())>
483+ if sort_key.is_some() {
484+ <input type="hidden" name="sort" value=(sort_key.map(|key| key.as_str()).unwrap_or(""))>
485+ }
486+ <input type="hidden" name="dir" value=(dir_flip)>
487+ if kind != KindFilter::All {
488+ <input type="hidden" name="kind" value=(kind.as_str())>
489+ }
490+ <button class="quiet" type="submit" aria-label=(t(language, Key::Sort))>(dir_glyph)</button>
491+ </form>
492+ <form class="field-box field-box-sort" method="get" action="/drive">
493+ <span class="field-text">(t(language, Key::Kind))</span>
494+ <select class="status-select" name="kind" data-autosubmit="" aria-label=(t(language, Key::Kind))>
495+ <option value="all" selected=(kind == KindFilter::All)>(t(language, Key::KindAll))</option>
496+ <option value="folders" selected=(kind == KindFilter::Folders)>(t(language, Key::KindFolders))</option>
497+ <option value="files" selected=(kind == KindFilter::Files)>(t(language, Key::KindFiles))</option>
498+ </select>
499+ <input type="hidden" name="folder" value=(current_id.clone())>
500+ <input type="hidden" name="q" value=(box_text.clone())>
501+ if sort_key.is_some() {
502+ <input type="hidden" name="sort" value=(sort_key.map(|key| key.as_str()).unwrap_or(""))>
503+ }
504+ <input type="hidden" name="dir" value=(sort_dir.as_str())>
505+ <button class="quiet" type="submit" aria-label=(t(language, Key::Kind))>"→"</button>
506+ </form>
264 <details class="user-menu drive-add">507 <details class="user-menu drive-add">
265 <summary class="quiet drive-add-trigger" aria-label=(t(language, Key::NewFolder))>"+ "</summary>508 <summary class="quiet drive-add-trigger" aria-label=(t(language, Key::NewFolder))>"+ "</summary>
266 <div class="user-menu-panel">509 <div class="user-menu-panel">
@@ -271,7 +514,17 @@ async fn drive(cx: &Cx) -> Result {
271 <label class="user-menu-item" for="drive-upload-input">(t(language, Key::UploadFiles))</label>514 <label class="user-menu-item" for="drive-upload-input">(t(language, Key::UploadFiles))</label>
272 </div>515 </div>
273 </details>516 </details>
274- </div>517+ </div>
518+ // The persistent notice stack: client-side upload errors and
519+ // completions render here and stay until dismissed. The region
520+ // itself is server HTML, but every card is client-made
521+ // (`__inAdded`) and mirrored in `window.__inNotices`, which the
522+ // status script re-renders on every `in:wire` — so the cards
523+ // survive both swap paths (the live morph keeps client-made
524+ // nodes; the full replace rebuilds them from the array, which
525+ // lives on `window` and outlives the body).
526+ <div id="in-status" class="in-status-stack" aria-live="polite"
527+ data-dismiss-label=(t(language, Key::Dismiss))></div>
275 if let Some(refusal) = refusal {528 if let Some(refusal) = refusal {
276 <p class="field-error">(refusal.message_in(language))</p>529 <p class="field-error">(refusal.message_in(language))</p>
277 }530 }
@@ -287,12 +540,22 @@ async fn drive(cx: &Cx) -> Result {
287 // The upload control sits outside the list so the + menu's540 // The upload control sits outside the list so the + menu's
288 // "Upload files" label and the page-wide drop handler find it on541 // "Upload files" label and the page-wide drop handler find it on
289 // every drive view, folder or search. The input stays hidden via542 // every drive view, folder or search. The input stays hidden via
290- // the file-upload-input rule.543+ // the file-upload-input rule; the progress list below it carries
544+ // the per-upload bars the script builds.
291 <form id="upload-form" class="file-upload" method="post" action="/files"545 <form id="upload-form" class="file-upload" method="post" action="/files"
292- enctype="multipart/form-data" data-hard="" data-failed-label=(t(language, Key::UploadFailed))>546+ enctype="multipart/form-data" data-hard=""
547+ data-failed-label=(t(language, Key::UploadFailed))
548+ data-complete-label=(t(language, Key::UploadComplete))>
293 <input type="hidden" name="folder_id" value=(current_id.clone())>549 <input type="hidden" name="folder_id" value=(current_id.clone())>
294 <input id="drive-upload-input" class="file-upload-input" type="file" name="file" multiple="">550 <input id="drive-upload-input" class="file-upload-input" type="file" name="file" multiple="">
295 </form>551 </form>
552+ <div id="upload-progress-list" class="upload-progress-list" aria-live="polite"></div>
553+ // The full-page drop affordance: hidden until a file drag is
554+ // over the window, pointer-transparent so it never blocks the
555+ // drop itself.
556+ <div id="drop-overlay" class="drop-overlay" aria-hidden="true">
557+ <span class="drop-overlay-text">(t(language, Key::DropFilesToUpload))</span>
558+ </div>
296 if let Some(hits) = hits {559 if let Some(hits) = hits {
297 if hits.folders.is_empty() && hits.files.is_empty() {560 if hits.folders.is_empty() && hits.files.is_empty() {
298 <p class="detail-quiet">(t(language, Key::NoResults))</p>561 <p class="detail-quiet">(t(language, Key::NoResults))</p>
@@ -306,7 +569,7 @@ async fn drive(cx: &Cx) -> Result {
306 }569 }
307 for file in &hits.files {570 for file in &hits.files {
308 <div class="dep-row">571 <div class="dep-row">
309- <a class="dep-link" href=(format!("/file/{}", file.id))>(file.name.clone())</a>572+ <a class="dep-link" href=(format!("/view/{}", file.id))>(file.name.clone())</a>
310 </div>573 </div>
311 }574 }
312 </div>575 </div>
@@ -321,76 +584,93 @@ async fn drive(cx: &Cx) -> Result {
321 for folder in listing.folders.iter() {584 for folder in listing.folders.iter() {
322 <div class="dep-row">585 <div class="dep-row">
323 if edit_id.as_deref() == Some(folder.id.as_str()) {586 if edit_id.as_deref() == Some(folder.id.as_str()) {
324- <form class="pop-row-form" method="post" action="/api/folder/rename">587+ <form class="dep-edit-form" method="post" action="/api/folder/rename">
325 <input type="hidden" name="id" value=(folder.id.clone())>588 <input type="hidden" name="id" value=(folder.id.clone())>
326 <input class="field-input" type="text" name="name" maxlength="255"589 <input class="field-input" type="text" name="name" maxlength="255"
327 value=(folder.name.clone()) required="" data-edit-focus=""590 value=(folder.name.clone()) required="" data-edit-focus=""
328 aria-label=(t(language, Key::RenameFolder))>591 aria-label=(t(language, Key::RenameFolder))>
592+ <div class="spacer"></div>
329 <button class="quiet" type="submit">(t(language, Key::Rename))</button>593 <button class="quiet" type="submit">(t(language, Key::Rename))</button>
330 <a class="quiet" href=(here.clone())>(t(language, Key::Cancel))</a>594 <a class="quiet" href=(here.clone())>(t(language, Key::Cancel))</a>
331 </form>595 </form>
332 } else {596 } else {
333- <a class="dep-link" href=(format!("/drive?folder={}", folder.id))>(folder.name.clone())</a>597+ <a class="dep-link" href=(format!("/drive?folder={}", folder.id))>
598+ <span class="dep-title">(folder.name.clone())</span>
599+ </a>
600+ <span class="dep-note">(t(language, Key::UploadedLabel))" "(folder.created_at.date().to_string())</span>
334 <div class="spacer"></div>601 <div class="spacer"></div>
335- <a class="quiet" href=(format!("{here}{edit_sep}edit={}", folder.id))602+ <details class="user-menu entry-options">
336- aria-label=(t(language, Key::RenameFolder))>(t(language, Key::Rename))</a>603+ <summary class="quiet entry-options-trigger">(t(language, Key::Options))" ▾"</summary>
337- <form class="pop-row-form" method="post" action="/api/folder/move">604+ <div class="user-menu-panel">
338- <input type="hidden" name="id" value=(folder.id.clone())>605+ <a class="user-menu-item"
339- <select class="field-input" name="parent_id" aria-label=(t(language, Key::MoveFolder))>606+ href=(format!("{here}{edit_sep}edit={}", folder.id))>(t(language, Key::Rename))</a>
340- <option value="">(t(language, Key::Drive))</option>607+ <form class="user-menu-item-form" method="post" action="/api/folder/move">
341- for dest in destinations.iter() {608+ <input type="hidden" name="id" value=(folder.id.clone())>
342- if dest.0 != folder.id {609+ <div class="user-menu-item-move">
343- <option value=(dest.0.clone())>(dest.1.clone())</option>610+ <select class="field-input" name="parent_id" aria-label=(t(language, Key::MoveFolder))>
344- }611+ <option value="">(t(language, Key::Drive))</option>
345- }612+ for dest in destinations.iter() {
346- </select>613+ if dest.0 != folder.id {
347- <button class="quiet" type="submit">(t(language, Key::Move))</button>614+ <option value=(dest.0.clone())>(dest.1.clone())</option>
348- </form>615+ }
349- <form class="detail-delete-form" method="post" action="/api/folder/delete">616+ }
350- <input type="hidden" name="id" value=(folder.id.clone())>617+ </select>
351- <button class="quiet" type="submit">(t(language, Key::Delete))</button>618+ <button class="quiet" type="submit">(t(language, Key::Move))</button>
352- </form>619+ </div>
620+ </form>
621+ <form class="user-menu-item-form" method="post" action="/api/folder/delete">
622+ <input type="hidden" name="id" value=(folder.id.clone())>
623+ <button class="user-menu-item quiet quiet-danger" type="submit">(t(language, Key::Delete))</button>
624+ </form>
625+ </div>
626+ </details>
353 }627 }
354 </div>628 </div>
355 }629 }
356 for file in listing.files.iter() {630 for file in listing.files.iter() {
357 <div class="dep-row">631 <div class="dep-row">
358- if file.thumb_state == ThumbState::Ready {632+ (crate::files::entry_chip(cx, file).await?)
359- <img class="file-chip" src=(format!("/thumb/{}", file.id)) alt="">
360- } else {
361- <span class="file-chip" aria-hidden="true">"▦"</span>
362- }
363 if edit_id.as_deref() == Some(file.id.as_str()) {633 if edit_id.as_deref() == Some(file.id.as_str()) {
364- <form class="pop-row-form" method="post" action="/api/file/rename">634+ <form class="dep-edit-form" method="post" action="/api/file/rename">
365 <input type="hidden" name="id" value=(file.id.clone())>635 <input type="hidden" name="id" value=(file.id.clone())>
366 <input class="field-input" type="text" name="name" maxlength="255"636 <input class="field-input" type="text" name="name" maxlength="255"
367 value=(file.name.clone()) required="" data-edit-focus=""637 value=(file.name.clone()) required="" data-edit-focus=""
368 aria-label=(t(language, Key::RenameFile))>638 aria-label=(t(language, Key::RenameFile))>
639+ <div class="spacer"></div>
369 <button class="quiet" type="submit">(t(language, Key::Rename))</button>640 <button class="quiet" type="submit">(t(language, Key::Rename))</button>
370 <a class="quiet" href=(here.clone())>(t(language, Key::Cancel))</a>641 <a class="quiet" href=(here.clone())>(t(language, Key::Cancel))</a>
371 </form>642 </form>
372 } else {643 } else {
373- <a class="dep-link" href=(format!("/file/{}", file.id))>(file.name.clone())</a>644+ <a class="dep-link" href=(format!("/view/{}", file.id))>
374- }645+ <span class="dep-title">(file.name.clone())</span>
646+ </a>
375 <span class="file-chip-size">(human_size(file.size_bytes))</span>647 <span class="file-chip-size">(human_size(file.size_bytes))</span>
648+ <span class="file-chip-note">(t(language, Key::UploadedLabel))" "(file.created_at.date().to_string())</span>
649+ <span class="file-chip-note">(t(language, Key::DownloadsLabel))" "(file.download_count.to_string())</span>
376 <div class="spacer"></div>650 <div class="spacer"></div>
377- if edit_id.as_deref() != Some(file.id.as_str()) {651+ <details class="user-menu entry-options">
378- <a class="quiet" href=(format!("{here}{edit_sep}edit={}", file.id))652+ <summary class="quiet entry-options-trigger">(t(language, Key::Options))" ▾"</summary>
379- aria-label=(t(language, Key::RenameFile))>(t(language, Key::Rename))</a>653+ <div class="user-menu-panel">
380- <form class="pop-row-form" method="post" action="/api/file/move">654+ <a class="user-menu-item"
381- <input type="hidden" name="id" value=(file.id.clone())>655+ href=(format!("{here}{edit_sep}edit={}", file.id))>(t(language, Key::Rename))</a>
382- <select class="field-input" name="folder_id" aria-label=(t(language, Key::MoveFile))>656+ <form class="user-menu-item-form" method="post" action="/api/file/move">
383- <option value="">(t(language, Key::Drive))</option>657+ <input type="hidden" name="id" value=(file.id.clone())>
384- for dest in destinations.iter() {658+ <div class="user-menu-item-move">
385- <option value=(dest.0.clone())>(dest.1.clone())</option>659+ <select class="field-input" name="folder_id" aria-label=(t(language, Key::MoveFile))>
386- }660+ <option value="">(t(language, Key::Drive))</option>
387- </select>661+ for dest in destinations.iter() {
388- <button class="quiet" type="submit">(t(language, Key::Move))</button>662+ <option value=(dest.0.clone())>(dest.1.clone())</option>
389- </form>663+ }
390- <form class="detail-delete-form" method="post" action="/api/file/delete">664+ </select>
391- <input type="hidden" name="id" value=(file.id.clone())>665+ <button class="quiet" type="submit">(t(language, Key::Move))</button>
392- <button class="quiet" type="submit">(t(language, Key::Delete))</button>666+ </div>
393- </form>667+ </form>
668+ <form class="user-menu-item-form" method="post" action="/api/file/delete">
669+ <input type="hidden" name="id" value=(file.id.clone())>
670+ <button class="user-menu-item quiet quiet-danger" type="submit">(t(language, Key::Delete))</button>
671+ </form>
672+ </div>
673+ </details>
394 }674 }
395 </div>675 </div>
396 }676 }
@@ -400,6 +680,7 @@ async fn drive(cx: &Cx) -> Result {
400 </main>680 </main>
401 (crate::dropdown::dropdown_script(cx).await?)681 (crate::dropdown::dropdown_script(cx).await?)
402 (upload_script(cx).await?)682 (upload_script(cx).await?)
683+ (status_script(cx).await?)
403 }684 }
404 }685 }
405 686
@@ -431,19 +712,35 @@ fn query_value(query: &str, key: &str) -> Option<String> {
431 })712 })
432 }713 }
433 714
434-/// The upload control's client half: files under 8 MiB ride the form's own715+/// The upload control's client half: files under 8 MiB ride one multipart
435-/// multipart post; files at or over it are split into the chunked protocol's716+/// post, files at or over it are split into the chunked protocol's calls —
436-/// calls with a progress bar.717+/// and every upload, small or big, draws the same live progress row (name,
718+/// bar, percent) into `#upload-progress-list`.
437 ///719 ///
438 /// The form wears `data-hard` so the soft-nav's multipart replay leaves it720 /// The form wears `data-hard` so the soft-nav's multipart replay leaves it
439 /// alone — two uploaders racing the same bytes would double-insert, and the721 /// alone — two uploaders racing the same bytes would double-insert, and the
440 /// progress the soft-nav draws knows nothing of chunks. Without script the722 /// progress the soft-nav draws knows nothing of chunks. Without script the
441 /// form posts plainly and the 303 lands back on the folder.723 /// form posts plainly and the 303 lands back on the folder.
442 ///724 ///
725+/// Failures never append inline notes anymore: they go through
726+/// `window.__inNotify` into the persistent stack ([`status_script`]), which
727+/// survives the swaps that used to wipe them. Completions announce there
728+/// too, then the page navigates to the landing the post answered.
729+///
443 /// The same block carries the `?edit=` row's focus: the rename input the730 /// The same block carries the `?edit=` row's focus: the rename input the
444 /// server renders open gets focused with its name selected on arrival, so a731 /// server renders open gets focused with its name selected on arrival, so a
445 /// quick-created folder is ready to name. Guarded lookups — most visits732 /// quick-created folder is ready to name. Guarded lookups — most visits
446 /// render no such input.733 /// render no such input.
734+///
735+/// And the page-wide drop: dragging files anywhere over a drive view raises
736+/// the `#drop-overlay` affordance (a dragenter/dragleave counter, hidden on
737+/// drop or on leaving), and dropping feeds the upload input, whose change
738+/// the soft-nav's listener turns into the submit below. The overlay wears
739+/// `pointer-events: none` so it never blocks the drop itself.
740+///
741+/// The Rust `\`-continuations strip newlines, so the emitted script is one
742+/// long line: only `/* */` comments survive inside it — a `//` would eat
743+/// the rest of the script and kill every handler silently.
447 async fn upload_script(cx: &Cx) -> Result {744 async fn upload_script(cx: &Cx) -> Result {
448 use topcoat::view::Unescaped;745 use topcoat::view::Unescaped;
449 const JS: &str = "\746 const JS: &str = "\
@@ -451,21 +748,39 @@ async fn upload_script(cx: &Cx) -> Result {
451 if (window.__inUpload) { return; } \748 if (window.__inUpload) { return; } \
452 window.__inUpload = true; \749 window.__inUpload = true; \
453 var LIMIT = 8388608; \750 var LIMIT = 8388608; \
454- function bar(box, label) { \751+ function progressList() { return document.getElementById('upload-progress-list'); } \
455- var wrap = document.createElement('div'); \752+ function bar(label) { \
456- wrap.className = 'upload-progress'; \753+ var row = document.createElement('div'); \
754+ row.className = 'upload-progress-row'; \
755+ var name = document.createElement('span'); \
756+ name.className = 'upload-progress-name'; \
757+ name.textContent = label || ''; \
758+ var track = document.createElement('div'); \
759+ track.className = 'upload-progress'; \
457 var fill = document.createElement('div'); \760 var fill = document.createElement('div'); \
458 fill.className = 'upload-progress-fill'; \761 fill.className = 'upload-progress-fill'; \
459- wrap.appendChild(fill); \762+ track.appendChild(fill); \
460- box.appendChild(window.__inAdded(wrap)); \763+ var pct = document.createElement('span'); \
461- if (label) { wrap.setAttribute('aria-label', label); } \764+ pct.className = 'upload-progress-pct'; \
462- return fill; \765+ pct.textContent = '0%'; \
766+ row.appendChild(name); \
767+ row.appendChild(track); \
768+ row.appendChild(pct); \
769+ if (label) { row.setAttribute('aria-label', label); } \
770+ var list = progressList(); \
771+ if (list) { list.appendChild(window.__inAdded(row)); } \
772+ return { row: row, fill: fill, pct: pct }; \
773+ } \
774+ function setProgress(ui, frac) { \
775+ var text = Math.min(100, Math.round(frac * 100)) + '%'; \
776+ ui.fill.style.width = text; \
777+ ui.pct.textContent = text; \
778+ } \
779+ function dropRow(ui) { \
780+ if (ui.row.parentNode) { ui.row.parentNode.removeChild(ui.row); } \
463 } \781 } \
464- function fail(box, message) { \782+ function notify(kind, message) { \
465- var note = document.createElement('p'); \783+ if (window.__inNotify) { window.__inNotify(kind, message); } \
466- note.className = 'field-error'; \
467- note.textContent = message; \
468- box.appendChild(window.__inAdded(note)); \
469 } \784 } \
470 async function startChunked(folder, name, size) { \785 async function startChunked(folder, name, size) { \
471 var r = await fetch('/api/upload/start', { \786 var r = await fetch('/api/upload/start', { \
@@ -477,8 +792,9 @@ async fn upload_script(cx: &Cx) -> Result {
477 if (!answer.ok) { throw new Error(answer.err || 'start'); } \792 if (!answer.ok) { throw new Error(answer.err || 'start'); } \
478 return answer.ok; \793 return answer.ok; \
479 } \794 } \
480- async function sendBig(file, folder, fill) { \795+ async function sendBig(file, folder, onProgress) { \
481 var session = await startChunked(folder, file.name, file.size); \796 var session = await startChunked(folder, file.name, file.size); \
797+ var total = Math.max(1, file.size); \
482 var index = 0; \798 var index = 0; \
483 for (var off = 0; off < file.size; off += LIMIT, index++) { \799 for (var off = 0; off < file.size; off += LIMIT, index++) { \
484 var piece = file.slice(off, Math.min(file.size, off + LIMIT)); \800 var piece = file.slice(off, Math.min(file.size, off + LIMIT)); \
@@ -488,18 +804,38 @@ async fn upload_script(cx: &Cx) -> Result {
488 body: piece \804 body: piece \
489 }); \805 }); \
490 if (!r.ok) { throw new Error('chunk'); } \806 if (!r.ok) { throw new Error('chunk'); } \
491- fill.style.width = Math.round(((off + piece.size) / file.size) * 100) + '%'; \807+ onProgress((off + piece.size) / total); \
492 } \808 } \
493 var done = await fetch('/api/upload/' + session.id + '/finish', { method: 'POST' }); \809 var done = await fetch('/api/upload/' + session.id + '/finish', { method: 'POST' }); \
494 var fin = await done.json(); \810 var fin = await done.json(); \
495 if (!fin.ok) { throw new Error((fin.err) || 'finish'); } \811 if (!fin.ok) { throw new Error((fin.err) || 'finish'); } \
812+ onProgress(1); \
813+ } \
814+ function sendSmall(action, folder, files, onProgress) { \
815+ return new Promise(function (resolve, reject) { \
816+ var data = new FormData(); \
817+ data.append('folder_id', folder); \
818+ files.forEach(function (f) { data.append('file', f, f.name); }); \
819+ var x = new XMLHttpRequest(); \
820+ x.open('POST', action); \
821+ x.setRequestHeader('accept', 'text/html'); \
822+ x.upload.onprogress = function (ev) { \
823+ if (ev.lengthComputable && ev.total > 0) { onProgress(ev.loaded / ev.total); } \
824+ }; \
825+ x.onload = function () { \
826+ onProgress(1); \
827+ if (x.status >= 200 && x.status < 300) { resolve(x.responseURL || ''); } \
828+ else { reject(new Error('small')); } \
829+ }; \
830+ x.onerror = function () { reject(new Error('small')); }; \
831+ x.send(data); \
832+ }); \
496 } \833 } \
497 document.addEventListener('submit', function (e) { \834 document.addEventListener('submit', function (e) { \
498 var form = e.target; \835 var form = e.target; \
499 if (!form || form.id !== 'upload-form') { return; } \836 if (!form || form.id !== 'upload-form') { return; } \
500 e.preventDefault(); \837 e.preventDefault(); \
501 var input = form.querySelector('.file-upload-input'); \838 var input = form.querySelector('.file-upload-input'); \
502- var box = form.querySelector('.file-upload-box') || form; \
503 var folder = form.querySelector('input[name=folder_id]').value; \839 var folder = form.querySelector('input[name=folder_id]').value; \
504 var files = input && input.files ? Array.prototype.slice.call(input.files) : []; \840 var files = input && input.files ? Array.prototype.slice.call(input.files) : []; \
505 if (!files.length) { return; } \841 if (!files.length) { return; } \
@@ -509,29 +845,41 @@ async fn upload_script(cx: &Cx) -> Result {
509 var small = files.filter(function (f) { return f.size < LIMIT; }); \845 var small = files.filter(function (f) { return f.size < LIMIT; }); \
510 var big = files.filter(function (f) { return f.size >= LIMIT; }); \846 var big = files.filter(function (f) { return f.size >= LIMIT; }); \
511 var failLabel = form.getAttribute('data-failed-label') || 'upload failed'; \847 var failLabel = form.getAttribute('data-failed-label') || 'upload failed'; \
848+ var doneLabel = form.getAttribute('data-complete-label') || ''; \
512 var landing = window.location.href; \849 var landing = window.location.href; \
850+ function settle() { \
851+ input.value = ''; \
852+ form.__inBusy = false; \
853+ if (input) { input.disabled = false; } \
854+ } \
513 (async function () { \855 (async function () { \
856+ var rows = []; \
514 try { \857 try { \
515 if (small.length) { \858 if (small.length) { \
516- var data = new FormData(); \859+ var title = small.length === 1 ? small[0].name : (small.length + ' files'); \
517- data.append('folder_id', folder); \860+ var ui = bar(title); \
518- small.forEach(function (f) { data.append('file', f, f.name); }); \861+ rows.push(ui); \
519- var fill = bar(box); \862+ var url = await sendSmall(form.getAttribute('action'), folder, small, function (frac) { setProgress(ui, frac); }); \
520- var r = await fetch(form.getAttribute('action'), { \863+ if (url) { landing = url; } \
521- method: 'POST', headers: { accept: 'text/html' }, body: data \
522- }); \
523- fill.style.width = '100%'; \
524- landing = r.url || landing; \
525- if (!r.ok) { fail(box, failLabel); } \
526 } \864 } \
527 for (var i = 0; i < big.length; i++) { \865 for (var i = 0; i < big.length; i++) { \
528- var fill2 = bar(box, big[i].name); \866+ await (function (file) { \
529- await sendBig(big[i], folder, fill2); \867+ var ui2 = bar(file.name); \
868+ rows.push(ui2); \
869+ return sendBig(file, folder, function (frac) { setProgress(ui2, frac); }); \
870+ })(big[i]); \
530 } \871 } \
531- } catch (err) { fail(box, failLabel); } \872+ } catch (err) { \
532- input.value = ''; \873+ rows.forEach(dropRow); \
533- form.__inBusy = false; \874+ var why = err && err.message ? err.message : String(err); \
534- if (input) { input.disabled = false; } \875+ notify('error', failLabel + ' (' + why + ')'); \
876+ settle(); \
877+ return; \
878+ } \
879+ rows.forEach(dropRow); \
880+ /* 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. */ \
881+ if (doneLabel && !/[?&]refusal=/.test(landing)) { notify('ok', doneLabel); } \
882+ settle(); \
535 if (window.__inGo) { window.__inGo(landing); } \883 if (window.__inGo) { window.__inGo(landing); } \
536 else { window.location.href = landing; } \884 else { window.location.href = landing; } \
537 })(); \885 })(); \
@@ -549,11 +897,33 @@ async fn upload_script(cx: &Cx) -> Result {
549 (function () { \897 (function () { \
550 if (window.__inDrop) { return; } \898 if (window.__inDrop) { return; } \
551 window.__inDrop = true; \899 window.__inDrop = true; \
900+ var depth = 0; \
552 function uploadForm() { return document.getElementById('upload-form'); } \901 function uploadForm() { return document.getElementById('upload-form'); } \
902+ function overlay() { return document.getElementById('drop-overlay'); } \
903+ function hasFiles(e) { \
904+ return !!(e.dataTransfer && e.dataTransfer.types && Array.prototype.indexOf.call(e.dataTransfer.types, 'Files') !== -1); \
905+ } \
906+ function show(on) { \
907+ var ov = overlay(); \
908+ if (ov) { ov.classList.toggle('drop-overlay-show', !!on); } \
909+ } \
910+ document.addEventListener('dragenter', function (e) { \
911+ if (!uploadForm() || !hasFiles(e)) { return; } \
912+ e.preventDefault(); \
913+ depth++; \
914+ show(true); \
915+ }); \
553 document.addEventListener('dragover', function (e) { \916 document.addEventListener('dragover', function (e) { \
554- if (uploadForm() && e.dataTransfer && e.dataTransfer.types && Array.prototype.indexOf.call(e.dataTransfer.types, 'Files') !== -1) { e.preventDefault(); } \917+ if (uploadForm() && hasFiles(e)) { e.preventDefault(); } \
918+ }); \
919+ document.addEventListener('dragleave', function (e) { \
920+ if (!uploadForm()) { return; } \
921+ depth = Math.max(0, depth - 1); \
922+ if (depth === 0) { show(false); } \
555 }); \923 }); \
556 document.addEventListener('drop', function (e) { \924 document.addEventListener('drop', function (e) { \
925+ depth = 0; \
926+ show(false); \
557 var form = uploadForm(); \927 var form = uploadForm(); \
558 if (!form || !e.dataTransfer || !e.dataTransfer.files || !e.dataTransfer.files.length) { return; } \928 if (!form || !e.dataTransfer || !e.dataTransfer.files || !e.dataTransfer.files.length) { return; } \
559 e.preventDefault(); \929 e.preventDefault(); \
@@ -567,6 +937,73 @@ async fn upload_script(cx: &Cx) -> Result {
567 view! { cx => <script>(Unescaped::new_unchecked(JS))</script> }937 view! { cx => <script>(Unescaped::new_unchecked(JS))</script> }
568 }938 }
569 939
940+/// The persistent notice stack's client half: upload errors and completions
941+/// that must stay until dismissed.
942+///
943+/// How the cards survive the swaps: every card is registered through
944+/// `__inAdded`, so the live path's morph — which pairs only server-rendered
945+/// nodes and leaves client-made ones alone — keeps them where they are. The
946+/// full-replace path (navigations, form posts) rebuilds the body and would
947+/// drop them, so every notice is also mirrored in `window.__inNotices`,
948+/// which lives on the document's `window` and outlives any one body; the
949+/// `in:wire` pass `swap()` runs after every paint re-renders the stack from
950+/// that array. Dismissing (the ✕, labelled from the stack's
951+/// `data-dismiss-label`) drops the notice from both. Nothing here
952+/// auto-times out.
953+///
954+/// The server-rendered `?refusal` banner needs no such route: it rides the
955+/// redirect URL the swap just painted, so both paths re-render it from the
956+/// server's own bytes.
957+async fn status_script(cx: &Cx) -> Result {
958+ use topcoat::view::Unescaped;
959+ const JS: &str = "\
960+ (function () { \
961+ if (window.__inStatus) { return; } \
962+ window.__inStatus = true; \
963+ if (!window.__inNotices) { window.__inNotices = []; } \
964+ var seq = 0; \
965+ window.__inNotices.forEach(function (n) { if (n.id > seq) { seq = n.id; } }); \
966+ function box() { return document.getElementById('in-status'); } \
967+ function dismissLabel() { \
968+ var b = box(); \
969+ return (b && b.getAttribute('data-dismiss-label')) || 'dismiss'; \
970+ } \
971+ window.__inNotify = function (kind, text) { \
972+ seq++; \
973+ window.__inNotices.push({ id: seq, kind: kind, text: text }); \
974+ render(); \
975+ }; \
976+ function render() { \
977+ var target = box(); \
978+ if (!target) { return; } \
979+ target.querySelectorAll('[data-notice]').forEach(function (old) { old.remove(); }); \
980+ window.__inNotices.forEach(function (n) { \
981+ var card = document.createElement('div'); \
982+ card.className = 'in-status-card in-status-' + n.kind; \
983+ card.setAttribute('data-notice', String(n.id)); \
984+ var text = document.createElement('span'); \
985+ text.className = 'in-status-text'; \
986+ text.textContent = n.text; \
987+ var shut = document.createElement('button'); \
988+ shut.type = 'button'; \
989+ shut.className = 'in-status-dismiss'; \
990+ shut.textContent = '✕'; \
991+ shut.setAttribute('aria-label', dismissLabel()); \
992+ shut.addEventListener('click', function () { \
993+ window.__inNotices = window.__inNotices.filter(function (x) { return x.id !== n.id; }); \
994+ card.remove(); \
995+ }); \
996+ card.appendChild(text); \
997+ card.appendChild(shut); \
998+ target.appendChild(window.__inAdded(card)); \
999+ }); \
1000+ } \
1001+ document.addEventListener('in:wire', render); \
1002+ render(); \
1003+ })();";
1004+ view! { cx => <script>(Unescaped::new_unchecked(JS))</script> }
1005+}
1006+
570 #[derive(serde::Deserialize)]1007 #[derive(serde::Deserialize)]
571 struct CreateFolderForm {1008 struct CreateFolderForm {
572 #[serde(default)]1009 #[serde(default)]
crates/in-web/src/files.rsmodified+223 -13
@@ -1,25 +1,32 @@
1-//! File bytes and small uploads.1+//! File bytes, the viewer page, and small uploads.
2 //!2 //!
3 //! `GET /file/{id}` streams one file its owner may see — or a grantee may,3 //! `GET /file/{id}` streams one file its owner may see — or a grantee may,
4 //! when the grant says so — honoring `?dl=1` (download disposition) and4 //! when the grant says so — honoring `?dl=1` (download disposition) and
5 //! `Range` (206 partial content), stamped `Cache-Control: private,5 //! `Range` (206 partial content), stamped `Cache-Control: private,
6 //! immutable`. `GET /thumb/{id}` serves the webp thumbnail under the same6 //! immutable`. `GET /thumb/{id}` serves the webp thumbnail under the same
7-//! visibility. `POST /files` (multipart, 64 MiB cap) takes files under 87+//! visibility. `GET /view/{id}` renders the viewer page: the inline viewer
8-//! MiB through the same pipeline the chunked protocol uses — the store8+//! for the file's kind (`viewer_kind`), a download link while the reader
9-//! sanitises the name, sniffs the mime, checks the quota and attempts the9+//! may download, and its details. `POST /files` (multipart) takes files
10-//! thumbnail — and `POST /api/file/rename|move|delete` mutate the row.10+//! through the same pipeline the chunked protocol uses — each part capped
11-//! Bytes for another owner's file answer 404, not 403.11+//! at the instance upload ceiling first — the store sanitises the name,
12-12+//! sniffs the mime, checks the quota
13-use in_core::store::{ShareKind, Store, StoreError};13+//! and attempts the thumbnail — and `POST /api/file/rename|move|delete`
14+//! mutate the row. Bytes for another owner's file answer 404, not 403.
15+
16+use in_core::store::{File, ShareKind, Store, StoreError, ThumbState};
14 use topcoat::Result;17 use topcoat::Result;
15 use topcoat::context::Cx;18 use topcoat::context::Cx;
16 use topcoat::router::content::multipart::Multipart;19 use topcoat::router::content::multipart::Multipart;
17 use topcoat::router::content::{Form, Json};20 use topcoat::router::content::{Form, Json};
21+use topcoat::router::error::not_found as page_not_found;
18 use topcoat::router::request::headers as request_headers;22 use topcoat::router::request::headers as request_headers;
19 use topcoat::router::{23 use topcoat::router::{
20- HeaderMap, HeaderName, HeaderValue, StatusCode, header, path_param, query_params, route,24+ HeaderMap, HeaderName, HeaderValue, StatusCode, header, page, path_param, query_params, route,
21 };25 };
26+use topcoat::view::view;
22 27
28+use crate::i18n::{Key, lang, t};
29+use crate::layout::{NavPage, topbar};
23 use crate::server::{Refusal, app, back_to, require_user};30 use crate::server::{Refusal, app, back_to, require_user};
24 31
25 path_param!(id);32 path_param!(id);
@@ -261,6 +268,11 @@ async fn download(cx: &Cx) -> topcoat::Result<(StatusCode, HeaderMap, Vec<u8>)>
261 .and_then(|value| value.to_str().ok());268 .and_then(|value| value.to_str().ok());
262 match range.and_then(|range| parse_range(range, total)) {269 match range.and_then(|range| parse_range(range, total)) {
263 Some(Ok((start, end))) => {270 Some(Ok((start, end))) => {
271+ // A play counts once, on its first chunk; later seeks are the
272+ // same view going on, not a new one.
273+ if start == 0 {
274+ let _ = store.record_download(id).await;
275+ }
264 let slice = bytes[start as usize..=end as usize].to_vec();276 let slice = bytes[start as usize..=end as usize].to_vec();
265 headers.insert(277 headers.insert(
266 header::CONTENT_RANGE,278 header::CONTENT_RANGE,
@@ -275,7 +287,10 @@ async fn download(cx: &Cx) -> topcoat::Result<(StatusCode, HeaderMap, Vec<u8>)>
275 );287 );
276 Ok((StatusCode::RANGE_NOT_SATISFIABLE, headers, Vec::new()))288 Ok((StatusCode::RANGE_NOT_SATISFIABLE, headers, Vec::new()))
277 }289 }
278- None => Ok((StatusCode::OK, headers, bytes)),290+ None => {
291+ let _ = store.record_download(id).await;
292+ Ok((StatusCode::OK, headers, bytes))
293+ }
279 }294 }
280 }295 }
281 296
@@ -324,10 +339,197 @@ async fn thumb(cx: &Cx) -> topcoat::Result<(StatusCode, HeaderMap, Vec<u8>)> {
324 Ok((StatusCode::OK, headers, bytes))339 Ok((StatusCode::OK, headers, bytes))
325 }340 }
326 341
342+/// What the viewer page shows inline: images, video and audio through their
343+/// native elements, PDFs through the browser's reader, plain text through a
344+/// sandboxed frame. Anything else — archives, office documents, unknown
345+/// bytes — is download-only.
346+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
347+pub(crate) enum ViewerKind {
348+ Image,
349+ Video,
350+ Audio,
351+ Pdf,
352+ Text,
353+}
354+
355+/// The inline viewer for one stored mime, if it has one. Trusts the stored
356+/// mime alone, the way [`renders_inline`] does; `image/heic` stays
357+/// download-only because no engine decodes it, and only `text/plain` opens
358+/// as text — anything juicier stays a download, the way [`inline_ok`]
359+/// keeps it off this origin.
360+pub(crate) fn viewer_kind(mime: &str) -> Option<ViewerKind> {
361+ if mime == "image/heic" {
362+ None
363+ } else if mime.starts_with("image/") {
364+ Some(ViewerKind::Image)
365+ } else if mime.starts_with("video/") {
366+ Some(ViewerKind::Video)
367+ } else if mime.starts_with("audio/") {
368+ Some(ViewerKind::Audio)
369+ } else if mime == "application/pdf" {
370+ Some(ViewerKind::Pdf)
371+ } else if mime == "text/plain" {
372+ Some(ViewerKind::Text)
373+ } else {
374+ None
375+ }
376+}
377+
378+/// One file's list icon: the webp thumbnail where one is ready, else a
379+/// mime-class glyph. The glyphs are decorative — the file's name beside
380+/// them carries the meaning — so they hide from assistive technology.
381+///
382+/// Lists embed this beside the name: `(crate::files::entry_chip(cx,
383+/// file).await?)`.
384+pub(crate) async fn entry_chip(cx: &Cx, file: &File) -> Result {
385+ if file.thumb_state == ThumbState::Ready {
386+ return view! {
387+ cx =>
388+ <img class="file-chip" src=(format!("/thumb/{}", file.id)) alt="">
389+ };
390+ }
391+ let (class, glyph) = chip_mark(&file.mime);
392+ view! {
393+ cx =>
394+ <span class=(format!("file-chip file-chip-{class}")) aria-hidden="true">(glyph)</span>
395+ }
396+}
397+
398+/// The chip's modifier class and its glyph, by stored mime: one distinct
399+/// mark per class — image, video, audio, pdf, text, archive, generic.
400+fn chip_mark(mime: &str) -> (&'static str, &'static str) {
401+ if mime.starts_with("image/") {
402+ ("image", "◫")
403+ } else if mime.starts_with("video/") {
404+ ("video", "▶")
405+ } else if mime.starts_with("audio/") {
406+ ("audio", "♫")
407+ } else if mime == "application/pdf" {
408+ ("pdf", "☰")
409+ } else if mime.starts_with("text/") {
410+ ("text", "¶")
411+ } else if is_archive_mime(mime) {
412+ ("archive", "⊞")
413+ } else {
414+ ("generic", "▦")
415+ }
416+}
417+
418+/// The stored mimes that are bundles of other files: plain zips, the OOXML
419+/// and OpenDocument documents (all zips underneath), gzip blobs and the
420+/// legacy OLE container.
421+fn is_archive_mime(mime: &str) -> bool {
422+ mime == "application/zip"
423+ || mime == "application/gzip"
424+ || mime == "application/x-ole-storage"
425+ || mime == "application/vnd.ms-excel"
426+ || mime.contains("openxml")
427+ || mime.contains("opendocument")
428+}
429+
430+/// `GET /view/{id}`: one file's viewer page — its name, the inline viewer
431+/// for its kind, a download link and its details. Authorization mirrors
432+/// trashed files open for nobody. A view-only grant opens the page but not
433+/// the bytes: the download link shows only while the reader may download,
434+/// and the inline viewer gives way to the unavailable note, since every
435+/// viewer element reads the same gated bytes. Bytes for another owner's
436+/// file answer 404, not 403.
437+#[page("/view/{id}")]
438+async fn view_file(cx: &Cx) -> Result {
439+ let id: &str = path_param::<Id>(cx);
440+
441+ let user = match require_user(cx).await {
442+ Ok(user) => user,
443+ Err(_) => {
444+ let location = (header::LOCATION, HeaderValue::from_static("/"));
445+ return view! {
446+ cx =>
447+ (StatusCode::SEE_OTHER)
448+ (location)
449+ };
450+ }
451+ };
452+ let language = lang(cx).await;
453+
454+ let store = app(cx).store.clone();
455+ let Some(file) = visible_file(store.as_ref(), &user.id, id).await else {
456+ return Err(page_not_found().into());
457+ };
458+ let may_download = file.owner_id == user.id
459+ || store
460+ .can_download(ShareKind::File, &file.id, &user.id)
461+ .await
462+ .unwrap_or(false);
463+
464+ let src = format!("/file/{}", file.id);
465+ let download_href = format!("/file/{}?dl=1", file.id);
466+ let meta = format!(
467+ "{} · {}",
468+ file.mime,
469+ crate::settings::human_bytes(file.size_bytes)
470+ );
471+ let uploaded = file.created_at.date().to_string();
472+ view! {
473+ cx =>
474+ (topbar(cx, NavPage::Drive, &user, language).await?)
475+ <main class="settings-stage">
476+ <p><a class="quiet" href="/drive">(t(language, Key::BackToDrive))</a></p>
477+ <h1 class="settings-title">(entry_chip(cx, &file).await?) (file.name.clone())</h1>
478+ <p class="field-note">(meta)</p>
479+ <div class="viewer-stage">
480+ if may_download {
481+ match viewer_kind(&file.mime) {
482+ Some(ViewerKind::Image) => <img class="viewer-media" src=(src.clone()) alt=(file.name.clone())>,
483+ Some(ViewerKind::Video) => <video class="viewer-media" src=(src.clone()) controls="" preload="metadata"></video>,
484+ Some(ViewerKind::Audio) => <audio class="viewer-audio" src=(src.clone()) controls="" preload="metadata"></audio>,
485+ Some(ViewerKind::Pdf) => <object class="viewer-media viewer-pdf" data=(src.clone()) type="application/pdf">
486+ <p class="field-note">(t(language, Key::PreviewUnavailable))</p>
487+ </object>,
488+ Some(ViewerKind::Text) => <iframe class="viewer-media viewer-text" src=(src.clone()) sandbox="" title=(file.name.clone())></iframe>,
489+ None => <div class="viewer-fallback">
490+ <p class="field-note">(t(language, Key::PreviewUnavailable))</p>
491+ </div>
492+ }
493+ } else {
494+ // A view-only grant opens the page but not the bytes, so
495+ // the viewer elements — every one reads /file/{id} —
496+ // would only frame a 404. The note instead.
497+ <div class="viewer-fallback">
498+ <p class="field-note">(t(language, Key::PreviewUnavailable))</p>
499+ </div>
500+ }
501+ </div>
502+ if may_download {
503+ <p><a class="primary" href=(download_href)>(t(language, Key::Download))</a></p>
504+ }
505+ <section class="panel">
506+ <div class="panel-head">
507+ <h2 class="panel-title">(t(language, Key::FileDetails))</h2>
508+ </div>
509+ <div class="panel-body">
510+ <div class="field">
511+ <span class="field-label">(t(language, Key::SizeColumn))</span>
512+ <span class="field-static">(crate::settings::human_bytes(file.size_bytes))</span>
513+ </div>
514+ <div class="field">
515+ <span class="field-label">(t(language, Key::UploadedLabel))</span>
516+ <span class="field-static">(uploaded)</span>
517+ </div>
518+ <div class="field">
519+ <span class="field-label">(t(language, Key::DownloadsLabel))</span>
520+ <span class="field-static">(file.download_count.to_string())</span>
521+ </div>
522+ </div>
523+ </section>
524+ </main>
525+ }
526+}
527+
327 /// Takes the files the drive's upload form carries — one per `file` part,528 /// Takes the files the drive's upload form carries — one per `file` part,
328-/// and a `multiple` picker posts several. The route already caps the whole529+/// and a `multiple` picker posts several. The route's body guard sits at 2
329-/// request body at 64 MiB (`main.rs`); each part is buffered whole because530+/// GiB (`main.rs`); each part is buffered whole because the store writes
330-/// the store writes it in one go. Fields arrive in request order:531+/// it in one go, capped at the instance upload ceiling before it gets
532+/// there. Fields arrive in request order:
331 /// `folder_id` before the `file` parts, so the destination is known before533 /// `folder_id` before the `file` parts, so the destination is known before
332 /// a byte of any file is kept.534 /// a byte of any file is kept.
333 #[route(POST "/files")]535 #[route(POST "/files")]
@@ -397,8 +599,16 @@ async fn upload(
397 return Ok(back_to_folder(folder_id.as_deref(), None));599 return Ok(back_to_folder(folder_id.as_deref(), None));
398 }600 }
399 601
602+ let limit = crate::server::effective_upload_limit(cx).await;
603+
400 let mut refusal: Option<Refusal> = None;604 let mut refusal: Option<Refusal> = None;
401 for (name, bytes) in files {605 for (name, bytes) in files {
606+ // One file may not pass the instance ceiling; oversize files never
607+ // reach the store.
608+ if bytes.len() as u64 > limit {
609+ refusal = Some(Refusal::UploadTooLarge);
610+ break;
611+ }
402 // The store sanitises the label, sniffs the mime off the bytes,612 // The store sanitises the label, sniffs the mime off the bytes,
403 // checks the quota, writes the file and attempts the thumbnail.613 // checks the quota, writes the file and attempts the thumbnail.
404 if let Err(error) = store614 if let Err(error) = store
crates/in-web/src/i18n.rsmodified+61 -0
@@ -178,6 +178,29 @@ pub enum Key {
178 DarkOption,178 DarkOption,
179 LanguageLabel,179 LanguageLabel,
180 Saved,180 Saved,
181+ // File viewer.
182+ UploadedLabel,
183+ DownloadsLabel,
184+ // Wave-1 upload limits.
185+ UploadLimits,
186+ CurrentUploadLimit,
187+ MaxUploadBytes,
188+ // Wave-2 drive additions (DriveBuild owns this block).
189+ Options,
190+ DropFilesToUpload,
191+ Dismiss,
192+ Sort,
193+ SortName,
194+ SortUploaded,
195+ SortSize,
196+ SortDownloads,
197+ Kind,
198+ KindAll,
199+ KindFolders,
200+ KindFiles,
201+ // Wave-2 trash/share extras (TrashShareBuild owns this block).
202+ SortDeleted,
203+ SortOwner,
181 }204 }
182 205
183 pub fn t(lang: Lang, key: Key) -> &'static str {206 pub fn t(lang: Lang, key: Key) -> &'static str {
@@ -283,6 +306,25 @@ pub fn t(lang: Lang, key: Key) -> &'static str {
283 DarkOption => "Dark",306 DarkOption => "Dark",
284 LanguageLabel => "LANGUAGE",307 LanguageLabel => "LANGUAGE",
285 Saved => "Saved.",308 Saved => "Saved.",
309+ UploadedLabel => "Uploaded",
310+ DownloadsLabel => "Downloads",
311+ UploadLimits => "Upload limits",
312+ CurrentUploadLimit => "Current limit",
313+ MaxUploadBytes => "Limit in bytes",
314+ Options => "Options",
315+ DropFilesToUpload => "Drop files to upload",
316+ Dismiss => "Dismiss",
317+ Sort => "Sort",
318+ SortName => "Name",
319+ SortUploaded => "Uploaded",
320+ SortSize => "Size",
321+ SortDownloads => "Downloads",
322+ Kind => "Kind",
323+ KindAll => "All",
324+ KindFolders => "Folders",
325+ KindFiles => "Files",
326+ SortDeleted => "Deleted",
327+ SortOwner => "Owner",
286 },328 },
287 Lang::Tr => match key {329 Lang::Tr => match key {
288 Cancel => "Vazgeç",330 Cancel => "Vazgeç",
@@ -384,6 +426,25 @@ pub fn t(lang: Lang, key: Key) -> &'static str {
384 DarkOption => "Koyu",426 DarkOption => "Koyu",
385 LanguageLabel => "DİL",427 LanguageLabel => "DİL",
386 Saved => "Kaydedildi.",428 Saved => "Kaydedildi.",
429+ UploadedLabel => "Yüklendi",
430+ DownloadsLabel => "İndirme",
431+ UploadLimits => "Yükleme sınırları",
432+ CurrentUploadLimit => "Geçerli sınır",
433+ MaxUploadBytes => "Bayt olarak sınır",
434+ Options => "Seçenekler",
435+ DropFilesToUpload => "Yüklemek için dosyaları bırakın",
436+ Dismiss => "Kapat",
437+ Sort => "Sırala",
438+ SortName => "Ad",
439+ SortUploaded => "Yüklenme",
440+ SortSize => "Boyut",
441+ SortDownloads => "İndirme",
442+ Kind => "Tür",
443+ KindAll => "Tümü",
444+ KindFolders => "Klasörler",
445+ KindFiles => "Dosyalar",
446+ SortDeleted => "Silindi",
447+ SortOwner => "Sahibi",
387 },448 },
388 }449 }
389 }450 }
crates/in-web/src/main.rsmodified+7 -2
@@ -150,8 +150,13 @@ async fn main() {
150 let router = in_client::mount(150 let router = in_client::mount(
151 Router::builder()151 Router::builder()
152 .discover()152 .discover()
153- .layer(BodyLimit::max(16 * 1024 * 1024).at("/api/upload"))153+ // BodyLimit is only a memory guard here, not the upload policy: the
154- .layer(BodyLimit::max(64 * 1024 * 1024).at("/files"))154+ // real per-file ceiling is the admin-controlled limit enforced in
155+ // the handlers (`effective_upload_limit`). `/files` takes whole
156+ // multipart bodies, so its guard sits at a hard 2 GiB; `/api/upload`
157+ // carries single 8 MiB chunks, so 32 MiB leaves ample headroom.
158+ .layer(BodyLimit::max(32 * 1024 * 1024).at("/api/upload"))
159+ .layer(BodyLimit::max(2usize * 1024 * 1024 * 1024).at("/files"))
155 .cookies()160 .cookies()
156 .assets(bundle),161 .assets(bundle),
157 oidc,162 oidc,
crates/in-web/src/server.rsmodified+39 -0
@@ -218,6 +218,11 @@ pub enum Refusal {
218 BadTheme,218 BadTheme,
219 /// The language field was not one of the values the form offers.219 /// The language field was not one of the values the form offers.
220 BadLanguage,220 BadLanguage,
221+ /// One file carries more bytes than the instance upload ceiling allows.
222+ UploadTooLarge,
223+ /// The admin's upload-limit form named zero, which would refuse every upload.
224+ /// (The form speaks bytes, so nothing can overflow; zero is the only refusal.)
225+ BadLimit,
221 }226 }
222 227
223 impl Refusal {228 impl Refusal {
@@ -241,6 +246,8 @@ impl Refusal {
241 Refusal::BadUi => "That interface choice is not offered.".to_string(),246 Refusal::BadUi => "That interface choice is not offered.".to_string(),
242 Refusal::BadTheme => "That is not a theme.".to_string(),247 Refusal::BadTheme => "That is not a theme.".to_string(),
243 Refusal::BadLanguage => "That is not a language.".to_string(),248 Refusal::BadLanguage => "That is not a language.".to_string(),
249+ Refusal::UploadTooLarge => "That file is larger than the upload limit.".to_string(),
250+ Refusal::BadLimit => "That limit is not usable.".to_string(),
244 }251 }
245 }252 }
246 253
@@ -266,6 +273,8 @@ impl Refusal {
266 Refusal::BadUi => "Bu arayüz seçeneği sunulmuyor.".to_string(),273 Refusal::BadUi => "Bu arayüz seçeneği sunulmuyor.".to_string(),
267 Refusal::BadTheme => "Bu bir tema değil.".to_string(),274 Refusal::BadTheme => "Bu bir tema değil.".to_string(),
268 Refusal::BadLanguage => "Bu bir dil değil.".to_string(),275 Refusal::BadLanguage => "Bu bir dil değil.".to_string(),
276+ Refusal::UploadTooLarge => "Bu dosya yükleme sınırından büyük.".to_string(),
277+ Refusal::BadLimit => "Bu sınır kullanılamaz.".to_string(),
269 }278 }
270 }279 }
271 280
@@ -289,6 +298,8 @@ impl Refusal {
289 "bad-ui" => Refusal::BadUi,298 "bad-ui" => Refusal::BadUi,
290 "bad-theme" => Refusal::BadTheme,299 "bad-theme" => Refusal::BadTheme,
291 "bad-language" => Refusal::BadLanguage,300 "bad-language" => Refusal::BadLanguage,
301+ "upload-too-large" => Refusal::UploadTooLarge,
302+ "bad-limit" => Refusal::BadLimit,
292 _ => return None,303 _ => return None,
293 })304 })
294 }305 }
@@ -316,10 +327,38 @@ impl Refusal {
316 Refusal::BadUi => "bad-ui",327 Refusal::BadUi => "bad-ui",
317 Refusal::BadTheme => "bad-theme",328 Refusal::BadTheme => "bad-theme",
318 Refusal::BadLanguage => "bad-language",329 Refusal::BadLanguage => "bad-language",
330+ Refusal::UploadTooLarge => "upload-too-large",
331+ Refusal::BadLimit => "bad-limit",
319 }332 }
320 }333 }
321 }334 }
322 335
336+/// The instance setting holding the per-file upload ceiling, in bytes.
337+/// Written by the admin's upload-limit form; read here.
338+pub(crate) const MAX_UPLOAD_SETTING: &str = "max_upload_bytes";
339+
340+/// The per-file upload ceiling in force for this request: the
341+/// [`MAX_UPLOAD_SETTING`] instance setting first, then the
342+/// `max_upload_bytes` key from `config/in.toml`, then 1 GiB when neither
343+/// names one.
344+///
345+/// A setting that is missing, unreadable, unparseable or zero falls through
346+/// to the config default — the save form only ever writes positive integers,
347+/// so anything else is a hand-edited row, not a choice. Quota is untouched:
348+/// this caps one file's size, quota caps an account's total.
349+pub(crate) async fn effective_upload_limit(cx: &Cx) -> u64 {
350+ let ctx = app(cx);
351+ match ctx.store.get_setting(MAX_UPLOAD_SETTING).await {
352+ Ok(Some(raw)) => raw
353+ .trim()
354+ .parse::<u64>()
355+ .ok()
356+ .filter(|limit| *limit > 0)
357+ .unwrap_or(ctx.config.max_upload_bytes),
358+ Ok(None) | Err(_) => ctx.config.max_upload_bytes,
359+ }
360+}
361+
323 /// Which call a carried refusal belongs to. Two forms on one page must not both362 /// Which call a carried refusal belongs to. Two forms on one page must not both
324 /// claim the same sentence, so the redirect names the call and this is the name:363 /// claim the same sentence, so the redirect names the call and this is the name:
325 /// the last piece of the server function's path, with anything that is not a364 /// the last piece of the server function's path, with anything that is not a
crates/in-web/src/settings.rsmodified+53 -1
@@ -84,6 +84,37 @@ async fn set_quota(cx: &Cx, Form(input): Form<QuotaForm>) -> Redirect {
84 }84 }
85 }85 }
86 86
87+#[derive(Deserialize)]
88+struct UploadLimitForm {
89+ max_upload_bytes: u64,
90+}
91+
92+/// Sets the instance-wide per-file upload ceiling, in bytes — the same unit
93+/// the `max_upload_bytes` instance setting stores, so the round trip is
94+/// exact: what the panel shows is what a save writes back. The bytes already
95+/// held are untouched — a ceiling lowered under an existing file refuses new
96+/// uploads past it, rather than deleting anything.
97+#[route(POST "/api/settings/upload-limit")]
98+async fn set_upload_limit(cx: &Cx, Form(input): Form<UploadLimitForm>) -> Redirect {
99+ if let Err(refusal) = require_admin(cx).await {
100+ return redirect_back(cx, "upload-limit", Some(refusal));
101+ }
102+ if input.max_upload_bytes == 0 {
103+ return redirect_back(cx, "upload-limit", Some(Refusal::BadLimit));
104+ }
105+ match app(cx)
106+ .store
107+ .set_setting(
108+ crate::server::MAX_UPLOAD_SETTING,
109+ &input.max_upload_bytes.to_string(),
110+ )
111+ .await
112+ {
113+ Ok(()) => redirect_back(cx, "upload-limit", None),
114+ Err(error) => redirect_back(cx, "upload-limit", Some(refusal_of(error))),
115+ }
116+}
117+
87 #[derive(Deserialize)]118 #[derive(Deserialize)]
88 struct DisableForm {119 struct DisableForm {
89 user_id: String,120 user_id: String,
@@ -200,6 +231,13 @@ async fn settings(cx: &Cx) -> Result {
200 } else {231 } else {
201 Vec::new()232 Vec::new()
202 };233 };
234+ // The live per-file ceiling, read once for the admin panel below. Only
235+ // admins see it, so only they pay the extra setting read.
236+ let upload_limit = if fresh.admin {
237+ Some(crate::server::effective_upload_limit(cx).await)
238+ } else {
239+ None
240+ };
203 let created = created_token(uri(cx).query().unwrap_or(""));241 let created = created_token(uri(cx).query().unwrap_or(""));
204 let origin = app(cx).config.listen_url();242 let origin = app(cx).config.listen_url();
205 view! {243 view! {
@@ -208,7 +246,7 @@ async fn settings(cx: &Cx) -> Result {
208 <div class="settings-shell">246 <div class="settings-shell">
209 <main class="settings-stage">247 <main class="settings-stage">
210 <h1 class="settings-title">(t(language, Key::Settings))</h1>248 <h1 class="settings-title">(t(language, Key::Settings))</h1>
211- (refusal_banner(cx, language, &["create", "revoke", "add", "remove", "quota", "disable", "preferences"]).await?)249+ (refusal_banner(cx, language, &["create", "revoke", "add", "remove", "quota", "disable", "preferences", "upload-limit"]).await?)
212 if let Some(token) = created {250 if let Some(token) = created {
213 <section class="panel">251 <section class="panel">
214 <div class="panel-head">252 <div class="panel-head">
@@ -290,6 +328,20 @@ async fn settings(cx: &Cx) -> Result {
290 </div>328 </div>
291 </section>329 </section>
292 if fresh.admin {330 if fresh.admin {
331+ if let Some(limit) = upload_limit {
332+ <section class="panel">
333+ <div class="panel-head">
334+ <h2 class="panel-title">(t(language, Key::UploadLimits))</h2>
335+ </div>
336+ <div class="panel-body">
337+ <p class="field-note">(format!("{}: {}", t(language, Key::CurrentUploadLimit), human_bytes(limit)))</p>
338+ <form class="pop-row-form" method="post" action="/api/settings/upload-limit">
339+ <input class="field-input" type="number" name="max_upload_bytes" min="1" value=(limit.to_string()) aria-label=(t(language, Key::MaxUploadBytes))>
340+ <button class="quiet" type="submit">(t(language, Key::Save))</button>
341+ </form>
342+ </div>
343+ </section>
344+ }
293 <section class="panel">345 <section class="panel">
294 <div class="panel-head">346 <div class="panel-head">
295 <h2 class="panel-title">(t(language, Key::AdminPanel))</h2>347 <h2 class="panel-title">(t(language, Key::AdminPanel))</h2>
crates/in-web/src/share.rsmodified+320 -73
@@ -17,7 +17,7 @@
17 //! render the copy-once banner off that pair.17 //! render the copy-once banner off that pair.
18 18
19 use in_core::hash_share_token;19 use in_core::hash_share_token;
20-use in_core::store::{ShareKind, Store, StoreError, User};20+use in_core::store::{ShareKind, Store, StoreError, ThumbState, User};
21 use serde::Deserialize;21 use serde::Deserialize;
22 use time::OffsetDateTime;22 use time::OffsetDateTime;
23 use topcoat::Result;23 use topcoat::Result;
@@ -25,10 +25,11 @@ use topcoat::context::Cx;
25 use topcoat::router::content::Form;25 use topcoat::router::content::Form;
26 use topcoat::router::request::{headers as request_headers, uri};26 use topcoat::router::request::{headers as request_headers, uri};
27 use topcoat::router::response::IntoResponse;27 use topcoat::router::response::IntoResponse;
28-use topcoat::router::{HeaderName, StatusCode, header, page, path_param, route};28+use topcoat::router::{HeaderName, StatusCode, header, page, path_param, query_params, route};
29 use topcoat::view::view;29 use topcoat::view::view;
30 30
31 use crate::i18n::{Key, Lang, lang, t};31 use crate::i18n::{Key, Lang, lang, t};
32+use crate::files::entry_chip;
32 use crate::layout::{NavPage, topbar, wordmark};33 use crate::layout::{NavPage, topbar, wordmark};
33 use crate::server::{Refusal, app, back_to, require_user};34 use crate::server::{Refusal, app, back_to, require_user};
34 35
@@ -526,6 +527,19 @@ async fn download_bytes(
526 let Ok(Some(bytes)) = bytes else {527 let Ok(Some(bytes)) = bytes else {
527 return dead_link(cx).await.into_response(cx);528 return dead_link(cx).await.into_response(cx);
528 };529 };
530+ // A fetch counts once: a full fetch, or a range resuming from byte 0.
531+ // A mid-file chunk is the same view going on, not a new one — the way
532+ // the signed-in download route counts its first chunk only.
533+ let range = request_headers(cx)
534+ .get(header::RANGE)
535+ .and_then(|value| value.to_str().ok());
536+ let counts = match range {
537+ None => true,
538+ Some(header) => range_starts_at_zero(header),
539+ };
540+ if counts {
541+ let _ = store.record_download(file_id).await;
542+ }
529 let mut headers = HeaderMap::new();543 let mut headers = HeaderMap::new();
530 if let Ok(value) = HeaderValue::from_str(mime) {544 if let Ok(value) = HeaderValue::from_str(mime) {
531 headers.insert(header::CONTENT_TYPE, value);545 headers.insert(header::CONTENT_TYPE, value);
@@ -541,6 +555,22 @@ async fn download_bytes(
541 Ok((StatusCode::OK, headers, bytes).into_response(cx)?)555 Ok((StatusCode::OK, headers, bytes).into_response(cx)?)
542 }556 }
543 557
558+/// Whether a `Range` header starts at byte 0: only those ranges (and the
559+/// header's absence) count a download. Anything else — a mid-file resume,
560+/// a suffix probe, several ranges, garbage — does not.
561+fn range_starts_at_zero(header: &str) -> bool {
562+ let Some(spec) = header.strip_prefix("bytes=") else {
563+ return false;
564+ };
565+ if spec.contains(',') {
566+ return false;
567+ }
568+ match spec.split_once('-') {
569+ Some(("0", _)) => true,
570+ _ => false,
571+ }
572+}
573+
544 /// The stored webp preview behind a public link. Unlike the bytes, the574 /// The stored webp preview behind a public link. Unlike the bytes, the
545 /// preview is what a view-only link grants, so this answers regardless of575 /// preview is what a view-only link grants, so this answers regardless of
546 /// `can_download` — and anything unservable is the dead card, like every576 /// `can_download` — and anything unservable is the dead card, like every
@@ -623,8 +653,53 @@ async fn file_card(
623 .into_response(cx)653 .into_response(cx)
624 }654 }
625 655
626-/// A shared folder's listing: subfolders then files, downloads gated on the656+/// One file's chip on the public card: the link's own thumbnail where one
627-/// link's flag. Subfolders browse in place under the same token.657+/// is ready, else the same mime-class glyph the signed-in lists wear.
658+/// `/thumb/{id}` needs a session, so this points at the public `?thumb=1`
659+/// route behind the same token instead.
660+async fn public_chip(cx: &Cx, thumb_src: &str, file: &in_core::store::File) -> Result {
661+ if file.thumb_state == ThumbState::Ready {
662+ return view! {
663+ cx =>
664+ <img class="file-chip" src=(thumb_src.to_string()) alt="">
665+ };
666+ }
667+ entry_chip(cx, file).await
668+}
669+
670+/// One shared file's chip: the thumbnail image while the target is live,
671+/// the mime-class glyph once it is trashed — `/thumb/{id}` 404s trashed
672+/// rows, so a Ready image would render broken if the target went into the
673+/// trash after the grant. The clone only clears the thumbnail flag for the
674+/// render.
675+async fn shared_chip(cx: &Cx, file: &in_core::store::File) -> Result {
676+ if file.deleted_at.is_some() {
677+ let mut unthumb = file.clone();
678+ unthumb.thumb_state = ThumbState::None;
679+ return entry_chip(cx, &unthumb).await;
680+ }
681+ entry_chip(cx, file).await
682+}
683+
684+/// One row of the public folder listing, folder or file, for the unified
685+/// list.
686+enum PublicEntry<'a> {
687+ Folder(&'a in_core::store::Folder),
688+ File(&'a in_core::store::File),
689+}
690+
691+impl PublicEntry<'_> {
692+ fn name(&self) -> &str {
693+ match self {
694+ PublicEntry::Folder(folder) => &folder.name,
695+ PublicEntry::File(file) => &file.name,
696+ }
697+ }
698+}
699+
700+/// A shared folder's listing: folders and files in one list, downloads
701+/// gated on the link's flag. Subfolders browse in place under the same
702+/// token.
628 async fn folder_card(703 async fn folder_card(
629 cx: &Cx,704 cx: &Cx,
630 store: &dyn Store,705 store: &dyn Store,
@@ -644,44 +719,38 @@ async fn folder_card(
644 .list_children(&root.owner_id, Some(at))719 .list_children(&root.owner_id, Some(at))
645 .await?;720 .await?;
646 let base = format!("/s/{token}");721 let base = format!("/s/{token}");
722+ let mut rows: Vec<PublicEntry> = Vec::new();
723+ rows.extend(listing.folders.iter().map(PublicEntry::Folder));
724+ rows.extend(listing.files.iter().map(PublicEntry::File));
725+ rows.sort_by(|a, b| a.name().to_lowercase().cmp(&b.name().to_lowercase()));
647 view! {726 view! {
648 cx =>727 cx =>
649 (wordmark(cx).await?)728 (wordmark(cx).await?)
650 <main class="settings-stage">729 <main class="settings-stage">
651 <h1 class="settings-title">(here.name.clone())</h1>730 <h1 class="settings-title">(here.name.clone())</h1>
652 <section class="panel">731 <section class="panel">
653- <div class="panel-head">
654- <h2 class="panel-title">(t(language, Key::FoldersHeading))</h2>
655- <span class="chip">(format!("{}", listing.folders.len()))</span>
656- </div>
657- <div class="panel-body">
658- if listing.folders.is_empty() {
659- <p class="field-note">(t(language, Key::EmptyFolder))</p>
660- }
661- for folder in &listing.folders {
662- <p><a href=(format!("{base}?folder={}", folder.id))>(folder.name.clone())</a></p>
663- }
664- </div>
665- </section>
666- <section class="panel">
667- <div class="panel-head">
668- <h2 class="panel-title">(t(language, Key::FilesHeading))</h2>
669- <span class="chip">(format!("{}", listing.files.len()))</span>
670- </div>
671 <div class="panel-body">732 <div class="panel-body">
672- if listing.files.is_empty() {733+ if rows.is_empty() {
673 <p class="field-note">(t(language, Key::EmptyFolder))</p>734 <p class="field-note">(t(language, Key::EmptyFolder))</p>
674 }735 }
675- for file in &listing.files {736+ for row in &rows {
676- <p>737+ match row {
677- <span>(file.name.clone())</span>738+ PublicEntry::Folder(folder) => <div class="dep-row">
678- (format!(" · {}", crate::settings::human_bytes(file.size_bytes)))739+ <span class="file-chip file-chip-folder" aria-hidden="true">"▤"</span>
679- if link.can_download {740+ <a class="dep-link" href=(format!("{base}?folder={}", folder.id))>(folder.name.clone())</a>
680- <a href=(format!("{base}?folder={at}&file={}&dl=1", file.id))>(t(language, Key::Download))</a>741+ </div>,
681- } else {742+ PublicEntry::File(file) => <div class="dep-row">
682- <span class="field-note">(t(language, Key::ViewOnly))</span>743+ (public_chip(cx, &format!("{base}?folder={at}&file={}&thumb=1", file.id), file).await?)
683- }744+ <span class="member-name">(file.name.clone())</span>
684- </p>745+ <span class="field-note">(crate::settings::human_bytes(file.size_bytes))</span>
746+ <div class="spacer"></div>
747+ if link.can_download {
748+ <a class="quiet" href=(format!("{base}?folder={at}&file={}&dl=1", file.id))>(t(language, Key::Download))</a>
749+ } else {
750+ <span class="field-note">(t(language, Key::ViewOnly))</span>
751+ }
752+ </div>,
753+ }
685 }754 }
686 </div>755 </div>
687 </section>756 </section>
@@ -697,8 +766,86 @@ fn current_path(cx: &Cx) -> String {
697 if path.is_empty() { "/".to_string() } else { path.to_string() }766 if path.is_empty() { "/".to_string() } else { path.to_string() }
698 }767 }
699 768
700-/// Everything others shared with the reader, files and folders in their own769+#[query_params]
701-/// groups, newest grant first. The reader's own library never appears here.770+struct SharedPageQuery {
771+ sort: Option<String>,
772+ kind: Option<String>,
773+ q: Option<String>,
774+}
775+
776+/// The shared list's sort, off the query: name, uploaded, size or owner.
777+/// Anything else is the default — by name.
778+fn valid_shared_sort(raw: Option<&str>) -> &'static str {
779+ match raw {
780+ Some("name") => "name",
781+ Some("uploaded") => "uploaded",
782+ Some("size") => "size",
783+ Some("owner") => "owner",
784+ _ => "name",
785+ }
786+}
787+
788+/// The kind filter, off the query: all, folders or files. Anything else
789+/// shows everything.
790+fn valid_shared_kind(raw: Option<&str>) -> &'static str {
791+ match raw {
792+ Some("folders") => "folders",
793+ Some("files") => "files",
794+ _ => "all",
795+ }
796+}
797+
798+/// One grant with the target's own dates and counters, for the unified
799+/// list. The file row stays aboard for the list chip; folders carry none.
800+struct SharedRow {
801+ item: in_core::store::SharedItem,
802+ owner_name: String,
803+ file: Option<in_core::store::File>,
804+ uploaded: OffsetDateTime,
805+}
806+
807+impl SharedRow {
808+ fn size(&self) -> u64 {
809+ self.file.as_ref().map(|file| file.size_bytes).unwrap_or(0)
810+ }
811+
812+ fn downloads(&self) -> u64 {
813+ self.file
814+ .as_ref()
815+ .map(|file| file.download_count)
816+ .unwrap_or(0)
817+ }
818+}
819+
820+/// The muted line at each shared row's right edge: what the grant opens,
821+/// who opened it, when the target went up — and the size and download
822+/// count for files.
823+fn shared_details(language: Lang, row: &SharedRow) -> String {
824+ let owner = if row.owner_name.is_empty() {
825+ String::new()
826+ } else {
827+ format!(" · {}", row.owner_name)
828+ };
829+ let mut out = format!(
830+ "{}{} · {} {}",
831+ access_chip(language, row.item.can_download),
832+ owner,
833+ t(language, Key::UploadedLabel),
834+ row.uploaded.date()
835+ );
836+ if row.item.kind == ShareKind::File {
837+ out.push_str(&format!(
838+ " · {} · {} {}",
839+ crate::settings::human_bytes(row.size()),
840+ row.downloads(),
841+ t(language, Key::DownloadsLabel)
842+ ));
843+ }
844+ out
845+}
846+
847+/// Everything others shared with the reader, folders and files in one
848+/// list. The reader's own library never appears here.
702 #[page("/shared")]849 #[page("/shared")]
703 async fn shared(cx: &Cx) -> Result {850 async fn shared(cx: &Cx) -> Result {
704 let user = match require_user(cx).await {851 let user = match require_user(cx).await {
@@ -715,6 +862,15 @@ async fn shared(cx: &Cx) -> Result {
715 }862 }
716 };863 };
717 let language = lang(cx).await;864 let language = lang(cx).await;
865+ let params = query_params::<SharedPageQuery>(cx).ok();
866+ let sort = valid_shared_sort(params.as_ref().and_then(|query| query.sort.as_deref()));
867+ let kind = valid_shared_kind(params.as_ref().and_then(|query| query.kind.as_deref()));
868+ let asked = params
869+ .as_ref()
870+ .and_then(|query| query.q.clone())
871+ .map(|query| query.trim().to_string())
872+ .filter(|query| !query.is_empty());
873+ let box_text = asked.clone().unwrap_or_default();
718 let store = app(cx).store;874 let store = app(cx).store;
719 let items = store875 let items = store
720 .shares_for_user(&user.id)876 .shares_for_user(&user.id)
@@ -732,43 +888,145 @@ async fn shared(cx: &Cx) -> Result {
732 owners.insert(item.owner_id.clone(), name);888 owners.insert(item.owner_id.clone(), name);
733 }889 }
734 }890 }
735- let folder_count = items.iter().filter(|item| item.kind == ShareKind::Folder).count();891+ let mut rows: Vec<SharedRow> = Vec::new();
736- let file_count = items.iter().filter(|item| item.kind == ShareKind::File).count();892+ for item in items {
893+ if kind == "folders" && item.kind != ShareKind::Folder {
894+ continue;
895+ }
896+ if kind == "files" && item.kind != ShareKind::File {
897+ continue;
898+ }
899+ if let Some(needle) = asked.as_deref() {
900+ if !item.name.to_lowercase().contains(&needle.to_lowercase()) {
901+ continue;
902+ }
903+ }
904+ let owner_name = owners.get(&item.owner_id).cloned().unwrap_or_default();
905+ // The grant carries no dates or counters of its own: the file row
906+ // brings the upload date, size and downloads, the folder row its
907+ // upload date. A target that went missing since the grant keeps
908+ // its row on the grant's own date.
909+ let (file, uploaded) = match item.kind {
910+ ShareKind::File => match store.file(&item.target_id).await.ok().flatten() {
911+ Some(file) => {
912+ let uploaded = file.created_at;
913+ (Some(file), uploaded)
914+ }
915+ None => (None, item.created_at),
916+ },
917+ ShareKind::Folder => {
918+ let uploaded = store
919+ .folder(&item.target_id)
920+ .await
921+ .ok()
922+ .flatten()
923+ .map(|folder| folder.created_at)
924+ .unwrap_or(item.created_at);
925+ (None, uploaded)
926+ }
927+ };
928+ rows.push(SharedRow {
929+ item,
930+ owner_name,
931+ file,
932+ uploaded,
933+ });
934+ }
935+ let nothing_shared = rows.is_empty() && asked.is_none() && kind == "all";
936+ match sort {
937+ "uploaded" => rows.sort_by(|a, b| {
938+ b.uploaded
939+ .cmp(&a.uploaded)
940+ .then_with(|| a.item.name.to_lowercase().cmp(&b.item.name.to_lowercase()))
941+ }),
942+ "size" => rows.sort_by(|a, b| {
943+ b.size()
944+ .cmp(&a.size())
945+ .then_with(|| a.item.name.to_lowercase().cmp(&b.item.name.to_lowercase()))
946+ }),
947+ "owner" => rows.sort_by(|a, b| {
948+ a.owner_name
949+ .to_lowercase()
950+ .cmp(&b.owner_name.to_lowercase())
951+ .then_with(|| a.item.name.to_lowercase().cmp(&b.item.name.to_lowercase()))
952+ }),
953+ _ => rows.sort_by(|a, b| {
954+ a.item
955+ .name
956+ .to_lowercase()
957+ .cmp(&b.item.name.to_lowercase())
958+ .then_with(|| a.item.target_id.cmp(&b.item.target_id))
959+ }),
960+ }
737 view! {961 view! {
738 cx =>962 cx =>
739 (topbar(cx, NavPage::Shared, &user, language).await?)963 (topbar(cx, NavPage::Shared, &user, language).await?)
740 <main class="settings-stage">964 <main class="settings-stage">
741 <h1 class="settings-title">(t(language, Key::SharedWithMe))</h1>965 <h1 class="settings-title">(t(language, Key::SharedWithMe))</h1>
742- if items.is_empty() {966+ <div class="filterbar">
743- <p class="field-note">(t(language, Key::NoSharedItems))</p>967+ <form class="field-box field-box-sort" method="get" action="/shared">
744- }968+ <span class="field-text">(t(language, Key::Sort))</span>
969+ <select class="status-select" name="sort" data-autosubmit="" aria-label=(t(language, Key::Sort))>
970+ <option value="name" selected=(sort == "name")>(t(language, Key::SortName))</option>
971+ <option value="uploaded" selected=(sort == "uploaded")>(t(language, Key::SortUploaded))</option>
972+ <option value="size" selected=(sort == "size")>(t(language, Key::SortSize))</option>
973+ <option value="owner" selected=(sort == "owner")>(t(language, Key::SortOwner))</option>
974+ </select>
975+ <input type="hidden" name="kind" value=(kind.to_string())>
976+ <input type="hidden" name="q" value=(box_text.clone())>
977+ </form>
978+ <form class="field-box field-box-sort" method="get" action="/shared">
979+ <span class="field-text">(t(language, Key::Kind))</span>
980+ <select class="status-select" name="kind" data-autosubmit="" aria-label=(t(language, Key::Kind))>
981+ <option value="all" selected=(kind == "all")>(t(language, Key::KindAll))</option>
982+ <option value="folders" selected=(kind == "folders")>(t(language, Key::KindFolders))</option>
983+ <option value="files" selected=(kind == "files")>(t(language, Key::KindFiles))</option>
984+ </select>
985+ <input type="hidden" name="sort" value=(sort.to_string())>
986+ <input type="hidden" name="q" value=(box_text.clone())>
987+ </form>
988+ <form class="field-box field-box-search" method="get" action="/shared">
989+ <span class="field-text">(t(language, Key::NavSearch))</span>
990+ <input
991+ class="dd-search"
992+ type="search"
993+ name="q"
994+ value=(box_text.clone())
995+ placeholder=(t(language, Key::SearchPlaceholder))
996+ aria-label=(t(language, Key::SearchPlaceholder))
997+ >
998+ <input type="hidden" name="sort" value=(sort.to_string())>
999+ <input type="hidden" name="kind" value=(kind.to_string())>
1000+ </form>
1001+ </div>
745 <section class="panel">1002 <section class="panel">
746 <div class="panel-head">1003 <div class="panel-head">
747- <h2 class="panel-title">(t(language, Key::FoldersHeading))</h2>1004+ <h2 class="panel-title">(t(language, Key::SharedWithMe))</h2>
748- <span class="chip">(format!("{folder_count}"))</span>1005+ <span class="chip">(rows.len().to_string())</span>
749 </div>1006 </div>
750 <div class="panel-body">1007 <div class="panel-body">
751- for item in items.iter().filter(|item| item.kind == ShareKind::Folder) {1008+ if rows.is_empty() {
752- <p>1009+ if nothing_shared {
753- <a href=(format!("/drive?folder={}", item.target_id))>(item.name.clone())</a>1010+ <p class="field-note">(t(language, Key::NoSharedItems))</p>
754- (owner_chip(item, &owners))1011+ } else {
755- (access_chip(language, item.can_download))1012+ <p class="field-note">(t(language, Key::NoResults))</p>
756- </p>1013+ }
757 }1014 }
758- </div>1015+ for row in &rows {
759- </section>1016+ <div class="dep-row">
760- <section class="panel">1017+ if row.item.kind == ShareKind::Folder {
761- <div class="panel-head">1018+ <span class="file-chip file-chip-folder" aria-hidden="true">"▤"</span>
762- <h2 class="panel-title">(t(language, Key::FilesHeading))</h2>1019+ <a class="dep-link" href=(format!("/drive?folder={}", row.item.target_id))>(row.item.name.clone())</a>
763- <span class="chip">(format!("{file_count}"))</span>1020+ } else {
764- </div>1021+ match &row.file {
765- <div class="panel-body">1022+ Some(file) => (shared_chip(cx, file).await?),
766- for item in items.iter().filter(|item| item.kind == ShareKind::File) {1023+ None => <span class="file-chip file-chip-generic" aria-hidden="true">"▦"</span>,
767- <p>1024+ }
768- <a href=(format!("/file/{}", item.target_id))>(item.name.clone())</a>1025+ <a class="dep-link" href=(format!("/view/{}", row.item.target_id))>(row.item.name.clone())</a>
769- (owner_chip(item, &owners))1026+ }
770- (access_chip(language, item.can_download))1027+ <div class="spacer"></div>
771- </p>1028+ <span class="field-note">(shared_details(language, row))</span>
1029+ </div>
772 }1030 }
773 </div>1031 </div>
774 </section>1032 </section>
@@ -776,17 +1034,6 @@ async fn shared(cx: &Cx) -> Result {
776 }1034 }
777 }1035 }
778 1036
779-/// `by <name>`, when the owner's name is known.
780-fn owner_chip(
781- item: &in_core::store::SharedItem,
782- owners: &std::collections::HashMap<String, String>,
783-) -> String {
784- match owners.get(&item.owner_id) {
785- Some(name) if !name.is_empty() => format!(" · {name}"),
786- _ => String::new(),
787- }
788-}
789-
790 /// What the grant opens: the download, or the view alone.1037 /// What the grant opens: the download, or the view alone.
791 fn access_chip(language: Lang, can_download: bool) -> &'static str {1038 fn access_chip(language: Lang, can_download: bool) -> &'static str {
792 if can_download {1039 if can_download {
crates/in-web/src/trash.rsmodified+221 -42
@@ -9,15 +9,17 @@
9 //! the filesystem. Folder purge has no store method yet (hubbed to Main via9 //! the filesystem. Folder purge has no store method yet (hubbed to Main via
10 //! the orchestrator) and is refused until it lands.10 //! the orchestrator) and is refused until it lands.
11 11
12-use in_core::store::{ShareKind, Store, User};12+use in_core::store::{File, Folder, ShareKind, Store, ThumbState, User};
13 use serde::Deserialize;13 use serde::Deserialize;
14+use time::OffsetDateTime;
14 use topcoat::Result;15 use topcoat::Result;
15 use topcoat::context::Cx;16 use topcoat::context::Cx;
16 use topcoat::router::content::Form;17 use topcoat::router::content::Form;
17-use topcoat::router::{HeaderName, StatusCode, header, page, route};18+use topcoat::router::{HeaderName, StatusCode, header, page, query_params, route};
18 use topcoat::view::view;19 use topcoat::view::view;
19 20
20-use crate::i18n::{Key, lang, t};21+use crate::files::entry_chip;
22+use crate::i18n::{Key, Lang, lang, t};
21 use crate::layout::{NavPage, topbar};23 use crate::layout::{NavPage, topbar};
22 use crate::server::{Refusal, app, back_to, require_user};24 use crate::server::{Refusal, app, back_to, require_user};
23 use crate::share::{refusal_banner, refusal_of};25 use crate::share::{refusal_banner, refusal_of};
@@ -135,9 +137,109 @@ async fn empty(cx: &Cx) -> Redirect {
135 }137 }
136 }138 }
137 139
138-/// The reader's trash: every trashed folder and file, newest trash first,140+/// A trashed file's chip: always the mime-class glyph, never the thumbnail
139-/// each row carrying its way back and its way gone, plus the button that141+/// image — `/thumb/{id}` 404s trashed rows, so a Ready row would render a
140-/// destroys them all.142+/// broken image. The clone only clears the thumbnail flag for the render.
143+async fn trash_chip(cx: &Cx, file: &File) -> Result {
144+ let mut unthumb = file.clone();
145+ unthumb.thumb_state = ThumbState::None;
146+ entry_chip(cx, &unthumb).await
147+}
148+
149+#[query_params]
150+struct TrashQuery {
151+ sort: Option<String>,
152+ kind: Option<String>,
153+ q: Option<String>,
154+}
155+
156+/// The trash's sort, off the query: name, deleted, uploaded or size.
157+/// Anything else is the default — newest trash first.
158+fn valid_trash_sort(raw: Option<&str>) -> &'static str {
159+ match raw {
160+ Some("name") => "name",
161+ Some("deleted") => "deleted",
162+ Some("uploaded") => "uploaded",
163+ Some("size") => "size",
164+ _ => "deleted",
165+ }
166+}
167+
168+/// The kind filter, off the query: all, folders or files. Anything else
169+/// shows everything.
170+fn valid_kind(raw: Option<&str>) -> &'static str {
171+ match raw {
172+ Some("folders") => "folders",
173+ Some("files") => "files",
174+ _ => "all",
175+ }
176+}
177+
178+/// One trashed row, folder or file, for the unified list.
179+enum TrashEntry<'a> {
180+ Folder(&'a Folder),
181+ File(&'a File),
182+}
183+
184+impl TrashEntry<'_> {
185+ fn id(&self) -> &str {
186+ match self {
187+ TrashEntry::Folder(folder) => &folder.id,
188+ TrashEntry::File(file) => &file.id,
189+ }
190+ }
191+
192+ fn name(&self) -> &str {
193+ match self {
194+ TrashEntry::Folder(folder) => &folder.name,
195+ TrashEntry::File(file) => &file.name,
196+ }
197+ }
198+
199+ fn uploaded(&self) -> OffsetDateTime {
200+ match self {
201+ TrashEntry::Folder(folder) => folder.created_at,
202+ TrashEntry::File(file) => file.created_at,
203+ }
204+ }
205+
206+ /// The trash timestamp. Always present on trashed rows; the upload
207+ /// date covers a row that lost it.
208+ fn deleted(&self) -> OffsetDateTime {
209+ let stamped = match self {
210+ TrashEntry::Folder(folder) => folder.deleted_at,
211+ TrashEntry::File(file) => file.deleted_at,
212+ };
213+ stamped.unwrap_or_else(|| self.uploaded())
214+ }
215+
216+ /// Folders carry no size of their own and sort as zero.
217+ fn size(&self) -> u64 {
218+ match self {
219+ TrashEntry::Folder(_) => 0,
220+ TrashEntry::File(file) => file.size_bytes,
221+ }
222+ }
223+}
224+
225+/// The muted line under each trashed name: the trash date, the upload date,
226+/// and the size for files.
227+fn trash_details(language: Lang, row: &TrashEntry) -> String {
228+ let mut out = format!(
229+ "{} {} · {} {}",
230+ t(language, Key::SortDeleted),
231+ row.deleted().date(),
232+ t(language, Key::UploadedLabel),
233+ row.uploaded().date()
234+ );
235+ if let TrashEntry::File(file) = row {
236+ out.push_str(&format!(" · {}", crate::settings::human_bytes(file.size_bytes)));
237+ }
238+ out
239+}
240+
241+/// The reader's trash: folders and files in one list, each row carrying its
242+/// way back and its way gone, plus the button that destroys them all.
141 #[page("/trash")]243 #[page("/trash")]
142 async fn trash(cx: &Cx) -> Result {244 async fn trash(cx: &Cx) -> Result {
143 let user = match require_user(cx).await {245 let user = match require_user(cx).await {
@@ -154,75 +256,152 @@ async fn trash(cx: &Cx) -> Result {
154 }256 }
155 };257 };
156 let language = lang(cx).await;258 let language = lang(cx).await;
259+ let params = query_params::<TrashQuery>(cx).ok();
260+ let sort = valid_trash_sort(params.as_ref().and_then(|query| query.sort.as_deref()));
261+ let kind = valid_kind(params.as_ref().and_then(|query| query.kind.as_deref()));
262+ let asked = params
263+ .as_ref()
264+ .and_then(|query| query.q.clone())
265+ .map(|query| query.trim().to_string())
266+ .filter(|query| !query.is_empty());
267+ let box_text = asked.clone().unwrap_or_default();
157 let listing = app(cx)268 let listing = app(cx)
158 .store269 .store
159 .list_trash(&user.id)270 .list_trash(&user.id)
160 .await?;271 .await?;
272+ let nothing_trashed = listing.folders.is_empty() && listing.files.is_empty();
273+ let mut rows: Vec<TrashEntry> = Vec::new();
274+ if kind == "all" || kind == "folders" {
275+ rows.extend(listing.folders.iter().map(TrashEntry::Folder));
276+ }
277+ if kind == "all" || kind == "files" {
278+ rows.extend(listing.files.iter().map(TrashEntry::File));
279+ }
280+ if let Some(needle) = asked.as_deref() {
281+ let needle = needle.to_lowercase();
282+ rows.retain(|row| row.name().to_lowercase().contains(&needle));
283+ }
284+ match sort {
285+ "name" => rows.sort_by(|a, b| {
286+ a.name()
287+ .to_lowercase()
288+ .cmp(&b.name().to_lowercase())
289+ .then_with(|| a.id().cmp(b.id()))
290+ }),
291+ "uploaded" => rows.sort_by(|a, b| {
292+ b.uploaded()
293+ .cmp(&a.uploaded())
294+ .then_with(|| a.name().to_lowercase().cmp(&b.name().to_lowercase()))
295+ }),
296+ "size" => rows.sort_by(|a, b| {
297+ b.size()
298+ .cmp(&a.size())
299+ .then_with(|| a.name().to_lowercase().cmp(&b.name().to_lowercase()))
300+ }),
301+ _ => rows.sort_by(|a, b| {
302+ b.deleted()
303+ .cmp(&a.deleted())
304+ .then_with(|| a.name().to_lowercase().cmp(&b.name().to_lowercase()))
305+ }),
306+ }
161 view! {307 view! {
162 cx =>308 cx =>
163 (topbar(cx, NavPage::Trash, &user, language).await?)309 (topbar(cx, NavPage::Trash, &user, language).await?)
164 <main class="settings-stage">310 <main class="settings-stage">
165 <h1 class="settings-title">(t(language, Key::Trash))</h1>311 <h1 class="settings-title">(t(language, Key::Trash))</h1>
312+ <div class="filterbar">
313+ <form class="field-box field-box-sort" method="get" action="/trash">
314+ <span class="field-text">(t(language, Key::Sort))</span>
315+ <select class="status-select" name="sort" data-autosubmit="" aria-label=(t(language, Key::Sort))>
316+ <option value="deleted" selected=(sort == "deleted")>(t(language, Key::SortDeleted))</option>
317+ <option value="name" selected=(sort == "name")>(t(language, Key::SortName))</option>
318+ <option value="uploaded" selected=(sort == "uploaded")>(t(language, Key::SortUploaded))</option>
319+ <option value="size" selected=(sort == "size")>(t(language, Key::SortSize))</option>
320+ </select>
321+ <input type="hidden" name="kind" value=(kind.to_string())>
322+ <input type="hidden" name="q" value=(box_text.clone())>
323+ </form>
324+ <form class="field-box field-box-sort" method="get" action="/trash">
325+ <span class="field-text">(t(language, Key::Kind))</span>
326+ <select class="status-select" name="kind" data-autosubmit="" aria-label=(t(language, Key::Kind))>
327+ <option value="all" selected=(kind == "all")>(t(language, Key::KindAll))</option>
328+ <option value="folders" selected=(kind == "folders")>(t(language, Key::KindFolders))</option>
329+ <option value="files" selected=(kind == "files")>(t(language, Key::KindFiles))</option>
330+ </select>
331+ <input type="hidden" name="sort" value=(sort.to_string())>
332+ <input type="hidden" name="q" value=(box_text.clone())>
333+ </form>
334+ <form class="field-box field-box-search" method="get" action="/trash">
335+ <span class="field-text">(t(language, Key::NavSearch))</span>
336+ <input
337+ class="dd-search"
338+ type="search"
339+ name="q"
340+ value=(box_text.clone())
341+ placeholder=(t(language, Key::SearchPlaceholder))
342+ aria-label=(t(language, Key::SearchPlaceholder))
343+ >
344+ <input type="hidden" name="sort" value=(sort.to_string())>
345+ <input type="hidden" name="kind" value=(kind.to_string())>
346+ </form>
347+ </div>
166 (refusal_banner(cx, language, &["restore", "purge", "empty"]).await?)348 (refusal_banner(cx, language, &["restore", "purge", "empty"]).await?)
167- if listing.folders.is_empty() && listing.files.is_empty() {349+ if !nothing_trashed {
168- <p class="field-note">(t(language, Key::TrashEmpty))</p>
169- }
170- if !listing.folders.is_empty() || !listing.files.is_empty() {
171 <form method="post" action="/api/trash/empty">350 <form method="post" action="/api/trash/empty">
172 <button class="quiet-danger" type="submit">(t(language, Key::EmptyTrash))</button>351 <button class="quiet-danger" type="submit">(t(language, Key::EmptyTrash))</button>
173 </form>352 </form>
174 }353 }
175- if !listing.folders.is_empty() {354+ <section class="panel">
176- <section class="panel">355+ <div class="panel-head">
177- <div class="panel-head">356+ <h2 class="panel-title">(t(language, Key::Trash))</h2>
178- <h2 class="panel-title">(t(language, Key::FoldersHeading))</h2>357+ <span class="chip">(rows.len().to_string())</span>
179- <span class="chip">(format!("{}", listing.folders.len()))</span>358+ </div>
180- </div>359+ <div class="panel-body">
181- <div class="panel-body">360+ if rows.is_empty() {
182- for folder in &listing.folders {361+ if nothing_trashed {
183- <div class="member-row">362+ <p class="field-note">(t(language, Key::TrashEmpty))</p>
363+ } else {
364+ <p class="field-note">(t(language, Key::NoResults))</p>
365+ }
366+ }
367+ for row in &rows {
368+ match row {
369+ TrashEntry::Folder(folder) => <div class="dep-row">
370+ <span class="file-chip file-chip-folder" aria-hidden="true">"▤"</span>
184 <span class="member-name">(folder.name.clone())</span>371 <span class="member-name">(folder.name.clone())</span>
372+ <span class="field-note">(trash_details(language, row))</span>
373+ <div class="spacer"></div>
185 <form class="pop-row-form" method="post" action="/api/trash/restore">374 <form class="pop-row-form" method="post" action="/api/trash/restore">
186 <input type="hidden" name="kind" value="folder">375 <input type="hidden" name="kind" value="folder">
187 <input type="hidden" name="id" value=(folder.id.clone())>376 <input type="hidden" name="id" value=(folder.id.clone())>
188- <button type="submit">(t(language, Key::Restore))</button>377+ <button class="quiet" type="submit">(t(language, Key::Restore))</button>
189 </form>378 </form>
190 <form class="pop-row-form" method="post" action="/api/trash/purge">379 <form class="pop-row-form" method="post" action="/api/trash/purge">
191 <input type="hidden" name="kind" value="folder">380 <input type="hidden" name="kind" value="folder">
192 <input type="hidden" name="id" value=(folder.id.clone())>381 <input type="hidden" name="id" value=(folder.id.clone())>
193- <button class="quiet-danger" type="submit">(t(language, Key::DeleteForever))</button>382+ <button class="quiet quiet-danger" type="submit">(t(language, Key::DeleteForever))</button>
194 </form>383 </form>
195- </div>384+ </div>,
196- }385+ TrashEntry::File(file) => <div class="dep-row">
197- </div>386+ (trash_chip(cx, file).await?)
198- </section>
199- }
200- if !listing.files.is_empty() {
201- <section class="panel">
202- <div class="panel-head">
203- <h2 class="panel-title">(t(language, Key::FilesHeading))</h2>
204- <span class="chip">(format!("{}", listing.files.len()))</span>
205- </div>
206- <div class="panel-body">
207- for file in &listing.files {
208- <div class="member-row">
209 <span class="member-name">(file.name.clone())</span>387 <span class="member-name">(file.name.clone())</span>
210- <span class="field-note">(crate::settings::human_bytes(file.size_bytes))</span>388+ <span class="field-note">(trash_details(language, row))</span>
389+ <div class="spacer"></div>
211 <form class="pop-row-form" method="post" action="/api/trash/restore">390 <form class="pop-row-form" method="post" action="/api/trash/restore">
212 <input type="hidden" name="kind" value="file">391 <input type="hidden" name="kind" value="file">
213 <input type="hidden" name="id" value=(file.id.clone())>392 <input type="hidden" name="id" value=(file.id.clone())>
214- <button type="submit">(t(language, Key::Restore))</button>393+ <button class="quiet" type="submit">(t(language, Key::Restore))</button>
215 </form>394 </form>
216 <form class="pop-row-form" method="post" action="/api/trash/purge">395 <form class="pop-row-form" method="post" action="/api/trash/purge">
217 <input type="hidden" name="kind" value="file">396 <input type="hidden" name="kind" value="file">
218 <input type="hidden" name="id" value=(file.id.clone())>397 <input type="hidden" name="id" value=(file.id.clone())>
219- <button class="quiet-danger" type="submit">(t(language, Key::DeleteForever))</button>398+ <button class="quiet quiet-danger" type="submit">(t(language, Key::DeleteForever))</button>
220 </form>399 </form>
221- </div>400+ </div>,
222 }401 }
223- </div>402+ }
224- </section>403+ </div>
225- }404+ </section>
226 </main>405 </main>
227 }406 }
228 }407 }
crates/in-web/src/upload.rsmodified+53 -20
@@ -3,8 +3,10 @@
3 //! Four owner-only JSON calls, all UTF-8: `POST /api/upload/start`3 //! Four owner-only JSON calls, all UTF-8: `POST /api/upload/start`
4 //! `{folder_id, name, size_bytes}` answers `{id, chunk_size}` with the4 //! `{folder_id, name, size_bytes}` answers `{id, chunk_size}` with the
5 //! server-fixed 8 MiB chunk size (`Refusal::QuotaExceeded` when the quota5 //! server-fixed 8 MiB chunk size (`Refusal::QuotaExceeded` when the quota
6-//! says no); `PUT /api/upload/{id}/{index}` takes one raw chunk (16 MiB6+//! says no, `Refusal::UploadTooLarge` past the instance upload ceiling);
7-//! cap, layered in `main.rs`); `POST /api/upload/{id}/finish` assembles the7+//! `PUT /api/upload/{id}/{index}` takes one raw chunk (32 MiB cap, layered
8+//! in `main.rs` — the real per-file ceiling lives in the start handler);
9+//! `POST /api/upload/{id}/finish` assembles the
8 //! staged chunks, sniffs the mime, moves the bytes to `files/<new file id>`10 //! staged chunks, sniffs the mime, moves the bytes to `files/<new file id>`
9 //! and answers with the created file id; `POST /api/upload/{id}/abort`11 //! and answers with the created file id; `POST /api/upload/{id}/abort`
10 //! drops the session and its staged bytes. Quota is enforced at start *and*12 //! drops the session and its staged bytes. Quota is enforced at start *and*
@@ -27,8 +29,28 @@ use crate::server::{Refusal, app, require_user};
27 path_param!(id);29 path_param!(id);
28 30
29 /// What the script side reads: the value, or the refusal it failed with.31 /// What the script side reads: the value, or the refusal it failed with.
30-/// Serialises as `{"ok":...}` / `{"err":...}`.32+/// Serialises as `{"ok":...}` / `{"err":...}` — a hand-rolled enum because
31-type Answer<T> = std::result::Result<T, Refusal>;33+/// serde's own `Result` would say `Ok`/`Err`, which the UI script does not
34+/// read.
35+enum Answer<T> {
36+ Ok(T),
37+ Err(Refusal),
38+}
39+
40+impl<T: serde::Serialize> serde::Serialize for Answer<T> {
41+ fn serialize<S: serde::Serializer>(
42+ &self,
43+ serializer: S,
44+ ) -> std::result::Result<S::Ok, S::Error> {
45+ use serde::ser::SerializeMap;
46+ let mut map = serializer.serialize_map(Some(1))?;
47+ match self {
48+ Answer::Ok(value) => map.serialize_entry("ok", value)?,
49+ Answer::Err(refusal) => map.serialize_entry("err", refusal)?,
50+ }
51+ map.end()
52+ }
53+}
32 54
33 /// A [`StoreError`] in the upload's own words. Another owner's session id55 /// A [`StoreError`] in the upload's own words. Another owner's session id
34 /// answers [`Refusal::NotFound`]: the id space is not theirs to probe.56 /// answers [`Refusal::NotFound`]: the id space is not theirs to probe.
@@ -78,26 +100,32 @@ struct StartOut {
78 async fn start(cx: &Cx, Json(input): Json<StartIn>) -> Result<Json<Answer<StartOut>>> {100 async fn start(cx: &Cx, Json(input): Json<StartIn>) -> Result<Json<Answer<StartOut>>> {
79 let user = match require_user(cx).await {101 let user = match require_user(cx).await {
80 Ok(user) => user,102 Ok(user) => user,
81- Err(refusal) => return Ok(Json(Err(refusal))),103+ Err(refusal) => return Ok(Json(Answer::Err(refusal))),
82 };104 };
83 let store = app(cx).store.clone();105 let store = app(cx).store.clone();
84 let folder = input.folder_id.as_deref().filter(|id| !id.is_empty());106 let folder = input.folder_id.as_deref().filter(|id| !id.is_empty());
85 if let Some(id) = folder {107 if let Some(id) = folder {
86 match store.folder(id).await {108 match store.folder(id).await {
87 Ok(Some(row)) if row.owner_id == user.id && row.deleted_at.is_none() => {}109 Ok(Some(row)) if row.owner_id == user.id && row.deleted_at.is_none() => {}
88- Ok(_) => return Ok(Json(Err(Refusal::NotFound))),110+ Ok(_) => return Ok(Json(Answer::Err(Refusal::NotFound))),
89- Err(_) => return Ok(Json(Err(Refusal::Unavailable))),111+ Err(_) => return Ok(Json(Answer::Err(Refusal::Unavailable))),
90 }112 }
91 }113 }
114+ // The instance ceiling is checked against the declared total before a
115+ // single chunk is sent: chunks can never add past the declared total
116+ // (the store refuses that), so this one check caps the whole session.
117+ if input.size_bytes > crate::server::effective_upload_limit(cx).await {
118+ return Ok(Json(Answer::Err(Refusal::UploadTooLarge)));
119+ }
92 match store120 match store
93 .create_upload_session(&user.id, folder, &input.name, input.size_bytes)121 .create_upload_session(&user.id, folder, &input.name, input.size_bytes)
94 .await122 .await
95 {123 {
96- Ok(session) => Ok(Json(Ok(StartOut {124+ Ok(session) => Ok(Json(Answer::Ok(StartOut {
97 id: session.id,125 id: session.id,
98 chunk_size: session.chunk_size,126 chunk_size: session.chunk_size,
99 }))),127 }))),
100- Err(error) => Ok(Json(Err(store_refusal(error)))),128+ Err(error) => Ok(Json(Answer::Err(store_refusal(error)))),
101 }129 }
102 }130 }
103 131
@@ -113,21 +141,26 @@ struct ChunkOut {
113 #[route(PUT "/api/upload/{id}/{index}")]141 #[route(PUT "/api/upload/{id}/{index}")]
114 async fn chunk(cx: &Cx, body: Bytes) -> Result<Json<Answer<ChunkOut>>> {142 async fn chunk(cx: &Cx, body: Bytes) -> Result<Json<Answer<ChunkOut>>> {
115 let id: &str = path_param::<Id>(cx);143 let id: &str = path_param::<Id>(cx);
116- let index: u64 = match uri(cx).path().rsplit('/').next().and_then(|raw| raw.parse().ok()) {144+ let index: u64 = match uri(cx)
145+ .path()
146+ .rsplit('/')
147+ .next()
148+ .and_then(|raw| raw.parse().ok())
149+ {
117 Some(index) => index,150 Some(index) => index,
118- None => return Ok(Json(Err(Refusal::BadChunk))),151+ None => return Ok(Json(Answer::Err(Refusal::BadChunk))),
119 };152 };
120 let session = match owned_session(cx, id).await {153 let session = match owned_session(cx, id).await {
121 Ok(session) => session,154 Ok(session) => session,
122- Err(refusal) => return Ok(Json(Err(refusal))),155+ Err(refusal) => return Ok(Json(Answer::Err(refusal))),
123 };156 };
124 let store = app(cx).store.clone();157 let store = app(cx).store.clone();
125 match store.record_chunk(&session.id, index, &body).await {158 match store.record_chunk(&session.id, index, &body).await {
126- Ok(session) => Ok(Json(Ok(ChunkOut {159+ Ok(session) => Ok(Json(Answer::Ok(ChunkOut {
127 received_bytes: session.received_bytes,160 received_bytes: session.received_bytes,
128 size_bytes: session.size_bytes,161 size_bytes: session.size_bytes,
129 }))),162 }))),
130- Err(error) => Ok(Json(Err(store_refusal(error)))),163+ Err(error) => Ok(Json(Answer::Err(store_refusal(error)))),
131 }164 }
132 }165 }
133 166
@@ -139,12 +172,12 @@ async fn finish(cx: &Cx) -> Result<Json<Answer<String>>> {
139 let id: &str = path_param::<Id>(cx);172 let id: &str = path_param::<Id>(cx);
140 let session = match owned_session(cx, id).await {173 let session = match owned_session(cx, id).await {
141 Ok(session) => session,174 Ok(session) => session,
142- Err(refusal) => return Ok(Json(Err(refusal))),175+ Err(refusal) => return Ok(Json(Answer::Err(refusal))),
143 };176 };
144 let store = app(cx).store.clone();177 let store = app(cx).store.clone();
145 match store.finish_upload(&session.id).await {178 match store.finish_upload(&session.id).await {
146- Ok(file) => Ok(Json(Ok(file.id))),179+ Ok(file) => Ok(Json(Answer::Ok(file.id))),
147- Err(error) => Ok(Json(Err(store_refusal(error)))),180+ Err(error) => Ok(Json(Answer::Err(store_refusal(error)))),
148 }181 }
149 }182 }
150 183
@@ -155,11 +188,11 @@ async fn abort(cx: &Cx) -> Result<Json<Answer<()>>> {
155 let id: &str = path_param::<Id>(cx);188 let id: &str = path_param::<Id>(cx);
156 let session = match owned_session(cx, id).await {189 let session = match owned_session(cx, id).await {
157 Ok(session) => session,190 Ok(session) => session,
158- Err(refusal) => return Ok(Json(Err(refusal))),191+ Err(refusal) => return Ok(Json(Answer::Err(refusal))),
159 };192 };
160 let store = app(cx).store.clone();193 let store = app(cx).store.clone();
161 match store.abort_upload(&session.id).await {194 match store.abort_upload(&session.id).await {
162- Ok(_) => Ok(Json(Ok(()))),195+ Ok(_) => Ok(Json(Answer::Ok(()))),
163- Err(error) => Ok(Json(Err(store_refusal(error)))),196+ Err(error) => Ok(Json(Answer::Err(store_refusal(error)))),
164 }197 }
165 }198 }
crates/in-web/tests/http.rsmodified+528 -165
@@ -97,20 +97,21 @@ impl FakeIm {
97 let len = content_length(&head);97 let len = content_length(&head);
98 let body: Vec<u8> = req[body_start..body_start + len].to_vec();98 let body: Vec<u8> = req[body_start..body_start + len].to_vec();
99 req.drain(..body_start + len);99 req.drain(..body_start + len);
100- let (status, content_type, payload) = match photo_answer(&pmap, &head, &first) {100+ let (status, content_type, payload) =
101- Some(photo) => photo,101+ match photo_answer(&pmap, &head, &first) {
102- None => match answer_for(&map, &first, &body) {102+ Some(photo) => photo,
103- Some(answer) => (103+ None => match answer_for(&map, &first, &body) {
104- "200 OK",104+ Some(answer) => (
105- "application/json".to_string(),105+ "200 OK",
106- serde_json::to_vec(&answer).unwrap(),106+ "application/json".to_string(),
107- ),107+ serde_json::to_vec(&answer).unwrap(),
108- // Anything but the introspection route is108+ ),
109- // nothing at all, the way the real im 404s109+ // Anything but the introspection route is
110- // unknown paths rather than answering them.110+ // nothing at all, the way the real im 404s
111- None => ("404 Not Found", "text/plain".to_string(), Vec::new()),111+ // unknown paths rather than answering them.
112- },112+ None => ("404 Not Found", "text/plain".to_string(), Vec::new()),
113- };113+ },
114+ };
114 let response = format!(115 let response = format!(
115 "HTTP/1.1 {status}\r\ncontent-type: {content_type}\r\ncontent-length: {}\r\n\r\n",116 "HTTP/1.1 {status}\r\ncontent-type: {content_type}\r\ncontent-length: {}\r\n\r\n",
116 payload.len()117 payload.len()
@@ -125,7 +126,11 @@ impl FakeIm {
125 });126 });
126 }127 }
127 });128 });
128- Self { addr, tokens, photos }129+ Self {
130+ addr,
131+ tokens,
132+ photos,
133+ }
129 }134 }
130 135
131 fn url(&self) -> String {136 fn url(&self) -> String {
@@ -158,7 +163,10 @@ fn photo_answer(
158 return None;163 return None;
159 }164 }
160 let target = parts.next().unwrap_or("");165 let target = parts.next().unwrap_or("");
161- let path = target.split_once('?').map(|(path, _)| path).unwrap_or(target);166+ let path = target
167+ .split_once('?')
168+ .map(|(path, _)| path)
169+ .unwrap_or(target);
162 let id = path.strip_prefix("/photo/")?;170 let id = path.strip_prefix("/photo/")?;
163 if id.is_empty() || id.contains('/') {171 if id.is_empty() || id.contains('/') {
164 return None;172 return None;
@@ -218,7 +226,8 @@ fn answer_for(
218 body: &[u8],226 body: &[u8],
219 ) -> Option<serde_json::Value> {227 ) -> Option<serde_json::Value> {
220 let mut head = request_line.split_whitespace();228 let mut head = request_line.split_whitespace();
221- let is_introspect = head.next() == Some("POST") && head.next() == Some(in_client::introspect_path());229+ let is_introspect =
230+ head.next() == Some("POST") && head.next() == Some(in_client::introspect_path());
222 if !is_introspect {231 if !is_introspect {
223 return None;232 return None;
224 }233 }
@@ -273,6 +282,7 @@ impl TestApp {
273 live_seconds: 300,282 live_seconds: 300,
274 purge_after_days: 30,283 purge_after_days: 30,
275 default_quota_bytes: 10 * 1024 * 1024 * 1024,284 default_quota_bytes: 10 * 1024 * 1024 * 1024,
285+ max_upload_bytes: 1024 * 1024 * 1024,
276 oidc: OidcConfig {286 oidc: OidcConfig {
277 issuer: fake.url(),287 issuer: fake.url(),
278 client_id: "in-test".to_string(),288 client_id: "in-test".to_string(),
@@ -286,8 +296,8 @@ impl TestApp {
286 let router = in_client::mount(296 let router = in_client::mount(
287 Router::builder()297 Router::builder()
288 .discover()298 .discover()
289- .layer(BodyLimit::max(16 * 1024 * 1024).at("/api/upload"))299+ .layer(BodyLimit::max(32 * 1024 * 1024).at("/api/upload"))
290- .layer(BodyLimit::max(64 * 1024 * 1024).at("/files"))300+ .layer(BodyLimit::max(2usize * 1024 * 1024 * 1024).at("/files"))
291 .cookies()301 .cookies()
292 .assets(302 .assets(
293 AssetBundle::load_dir(asset_dir())303 AssetBundle::load_dir(asset_dir())
@@ -547,12 +557,10 @@ impl Answer {
547 557
548 fn refused(&self, code: &str, call: &str) -> bool {558 fn refused(&self, code: &str, call: &str) -> bool {
549 self.status == StatusCode::SEE_OTHER559 self.status == StatusCode::SEE_OTHER
550- && self560+ && self.location.as_deref().is_some_and(|location| {
551- .location561+ location.contains(&format!("refusal={code}"))
552- .as_deref()562+ && location.contains(&format!("on={call}"))
553- .is_some_and(|location| {563+ })
554- location.contains(&format!("refusal={code}")) && location.contains(&format!("on={call}"))
555- })
556 }564 }
557 565
558 fn accepted(&self) -> bool {566 fn accepted(&self) -> bool {
@@ -601,11 +609,11 @@ fn encode(raw: &str) -> String {
601 /// The 1x1 transparent PNG: the smallest thing the thumbnailer must accept.609 /// The 1x1 transparent PNG: the smallest thing the thumbnailer must accept.
602 fn tiny_png() -> Vec<u8> {610 fn tiny_png() -> Vec<u8> {
603 vec![611 vec![
604- 0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A, 0x00, 0x00, 0x00, 0x0D, 0x49, 0x48,612+ 0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A, 0x00, 0x00, 0x00, 0x0D, 0x49, 0x48, 0x44,
605- 0x44, 0x52, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x08, 0x06, 0x00, 0x00,613+ 0x52, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x08, 0x06, 0x00, 0x00, 0x00, 0x1F,
606- 0x00, 0x1F, 0x15, 0xC4, 0x89, 0x00, 0x00, 0x00, 0x0A, 0x49, 0x44, 0x41, 0x54, 0x78,614+ 0x15, 0xC4, 0x89, 0x00, 0x00, 0x00, 0x0A, 0x49, 0x44, 0x41, 0x54, 0x78, 0x9C, 0x63, 0x00,
607- 0x9C, 0x63, 0x00, 0x01, 0x00, 0x00, 0x05, 0x00, 0x01, 0x0D, 0x0A, 0x2D, 0xB4, 0x00,615+ 0x01, 0x00, 0x00, 0x05, 0x00, 0x01, 0x0D, 0x0A, 0x2D, 0xB4, 0x00, 0x00, 0x00, 0x00, 0x49,
608- 0x00, 0x00, 0x00, 0x49, 0x45, 0x4E, 0x44, 0xAE, 0x42, 0x60, 0x82,616+ 0x45, 0x4E, 0x44, 0xAE, 0x42, 0x60, 0x82,
609 ]617 ]
610 }618 }
611 619
@@ -625,7 +633,10 @@ async fn folder_id(app: &TestApp, owner: &str, parent: Option<&str>, name: &str)
625 }633 }
626 /// The token off a creation redirect's `?created=` pair.634 /// The token off a creation redirect's `?created=` pair.
627 fn created_token(location: &str) -> String {635 fn created_token(location: &str) -> String {
628- let query = location.split_once('?').map(|(_, query)| query).unwrap_or("");636+ let query = location
637+ .split_once('?')
638+ .map(|(_, query)| query)
639+ .unwrap_or("");
629 query640 query
630 .split('&')641 .split('&')
631 .filter_map(|pair| pair.split_once('='))642 .filter_map(|pair| pair.split_once('='))
@@ -670,7 +681,11 @@ async fn folder_crud_and_cycle_is_refused() {
670 .unwrap();681 .unwrap();
671 682
672 let answer = app683 let answer = app
673- .post("/api/folder/create", Some(&cookie), &[("parent_id", ""), ("name", "projects")])684+ .post(
685+ "/api/folder/create",
686+ Some(&cookie),
687+ &[("parent_id", ""), ("name", "projects")],
688+ )
674 .await;689 .await;
675 assert_eq!(answer.status, StatusCode::SEE_OTHER, "{}", answer.body);690 assert_eq!(answer.status, StatusCode::SEE_OTHER, "{}", answer.body);
676 assert_eq!(answer.body, "null", "creating was refused");691 assert_eq!(answer.body, "null", "creating was refused");
@@ -703,7 +718,11 @@ async fn folder_crud_and_cycle_is_refused() {
703 718
704 // A legal move, a rename and a delete all land clean.719 // A legal move, a rename and a delete all land clean.
705 let answer = app720 let answer = app
706- .post("/api/folder/move", Some(&cookie), &[("id", &sub), ("parent_id", "")])721+ .post(
722+ "/api/folder/move",
723+ Some(&cookie),
724+ &[("id", &sub), ("parent_id", "")],
725+ )
707 .await;726 .await;
708 assert_eq!(answer.body, "null", "moving was refused: {}", answer.body);727 assert_eq!(answer.body, "null", "moving was refused: {}", answer.body);
709 let answer = app728 let answer = app
@@ -745,9 +764,18 @@ async fn small_upload_round_trip() {
745 &[("hello.txt", "text/plain", bytes)],764 &[("hello.txt", "text/plain", bytes)],
746 )765 )
747 .await;766 .await;
748- assert_eq!(answer.status, StatusCode::SEE_OTHER, "{}", answer.location.unwrap_or_default());767+ assert_eq!(
768+ answer.status,
769+ StatusCode::SEE_OTHER,
770+ "{}",
771+ answer.location.unwrap_or_default()
772+ );
749 assert!(773 assert!(
750- !answer.location.as_deref().unwrap_or("").contains("refusal="),774+ !answer
775+ .location
776+ .as_deref()
777+ .unwrap_or("")
778+ .contains("refusal="),
751 "upload was refused: {}",779 "upload was refused: {}",
752 answer.location.unwrap_or_default()780 answer.location.unwrap_or_default()
753 );781 );
@@ -768,7 +796,10 @@ async fn small_upload_round_trip() {
768 assert_eq!(got.bytes, bytes);796 assert_eq!(got.bytes, bytes);
769 assert_eq!(got.accept_ranges.as_deref(), Some("bytes"));797 assert_eq!(got.accept_ranges.as_deref(), Some("bytes"));
770 assert!(798 assert!(
771- got.cache_control.as_deref().unwrap_or("").contains("immutable"),799+ got.cache_control
800+ .as_deref()
801+ .unwrap_or("")
802+ .contains("immutable"),
772 "missing immutable cache directive"803 "missing immutable cache directive"
773 );804 );
774 }805 }
@@ -801,8 +832,11 @@ async fn chunked_upload_round_trip() {
801 .await;832 .await;
802 assert_eq!(answer.status, StatusCode::OK, "{}", answer.body);833 assert_eq!(answer.status, StatusCode::OK, "{}", answer.body);
803 let started = answer.json();834 let started = answer.json();
804- let session = started["Ok"]["id"].as_str().expect("start was refused").to_string();835+ let session = started["ok"]["id"]
805- assert_eq!(started["Ok"]["chunk_size"].as_u64(), Some(8 * 1024 * 1024));836+ .as_str()
837+ .expect("start was refused")
838+ .to_string();
839+ assert_eq!(started["ok"]["chunk_size"].as_u64(), Some(8 * 1024 * 1024));
806 840
807 let answer = app841 let answer = app
808 .put_bytes(842 .put_bytes(
@@ -812,13 +846,23 @@ async fn chunked_upload_round_trip() {
812 )846 )
813 .await;847 .await;
814 assert_eq!(answer.status, StatusCode::OK, "{}", answer.body);848 assert_eq!(answer.status, StatusCode::OK, "{}", answer.body);
815- assert_eq!(answer.json()["Ok"]["received_bytes"].as_u64(), Some(8 * 1024 * 1024));849+ assert_eq!(
850+ answer.json()["ok"]["received_bytes"].as_u64(),
851+ Some(8 * 1024 * 1024)
852+ );
816 853
817 let answer = app854 let answer = app
818- .put_bytes(&format!("/api/upload/{session}/1"), Some(&cookie), &bytes[8 * 1024 * 1024..])855+ .put_bytes(
856+ &format!("/api/upload/{session}/1"),
857+ Some(&cookie),
858+ &bytes[8 * 1024 * 1024..],
859+ )
819 .await;860 .await;
820 assert_eq!(answer.status, StatusCode::OK, "{}", answer.body);861 assert_eq!(answer.status, StatusCode::OK, "{}", answer.body);
821- assert_eq!(answer.json()["Ok"]["received_bytes"].as_u64(), Some(total as u64));862+ assert_eq!(
863+ answer.json()["ok"]["received_bytes"].as_u64(),
864+ Some(total as u64)
865+ );
822 866
823 let answer = app867 let answer = app
824 .post_json(868 .post_json(
@@ -828,7 +872,10 @@ async fn chunked_upload_round_trip() {
828 )872 )
829 .await;873 .await;
830 assert_eq!(answer.status, StatusCode::OK, "{}", answer.body);874 assert_eq!(answer.status, StatusCode::OK, "{}", answer.body);
831- let file_id = answer.json()["Ok"].as_str().expect("finish was refused").to_string();875+ let file_id = answer.json()["ok"]
876+ .as_str()
877+ .expect("finish was refused")
878+ .to_string();
832 879
833 let got = app.get(&format!("/file/{file_id}"), Some(&cookie)).await;880 let got = app.get(&format!("/file/{file_id}"), Some(&cookie)).await;
834 assert_eq!(got.status, StatusCode::OK);881 assert_eq!(got.status, StatusCode::OK);
@@ -901,7 +948,7 @@ async fn quota_is_refused_before_and_during_upload() {
901 .await;948 .await;
902 assert_eq!(answer.status, StatusCode::OK, "{}", answer.body);949 assert_eq!(answer.status, StatusCode::OK, "{}", answer.body);
903 assert_eq!(950 assert_eq!(
904- answer.json()["Err"].as_str(),951+ answer.json()["err"].as_str(),
905 Some("QuotaExceeded"),952 Some("QuotaExceeded"),
906 "start was not refused: {}",953 "start was not refused: {}",
907 answer.body954 answer.body
@@ -944,7 +991,11 @@ async fn thumbnail_is_served_after_image_upload() {
944 )991 )
945 .await;992 .await;
946 assert!(993 assert!(
947- !answer.location.as_deref().unwrap_or("").contains("refusal="),994+ !answer
995+ .location
996+ .as_deref()
997+ .unwrap_or("")
998+ .contains("refusal="),
948 "image upload was refused: {}",999 "image upload was refused: {}",
949 answer.location.unwrap_or_default()1000 answer.location.unwrap_or_default()
950 );1001 );
@@ -976,11 +1027,20 @@ async fn thumbnail_is_served_after_image_upload() {
976 async fn cross_owner_answers_not_found() {1027 async fn cross_owner_answers_not_found() {
977 let app = TestApp::build().await;1028 let app = TestApp::build().await;
978 let alice = app.sign_in("sub-alice", "alice@in.test", "Alice").await;1029 let alice = app.sign_in("sub-alice", "alice@in.test", "Alice").await;
979- let alice_user = app.store.user_by_oidc_sub("sub-alice").await.unwrap().unwrap();1030+ let alice_user = app
1031+ .store
1032+ .user_by_oidc_sub("sub-alice")
1033+ .await
1034+ .unwrap()
1035+ .unwrap();
980 let bob = app.sign_in("sub-bob", "bob@in.test", "Bob").await;1036 let bob = app.sign_in("sub-bob", "bob@in.test", "Bob").await;
981 1037
982- app.post("/api/folder/create", Some(&alice), &[("parent_id", ""), ("name", "hers")])1038+ app.post(
983- .await;1039+ "/api/folder/create",
1040+ Some(&alice),
1041+ &[("parent_id", ""), ("name", "hers")],
1042+ )
1043+ .await;
984 let hers = folder_id(&app, &alice_user.id, None, "hers").await;1044 let hers = folder_id(&app, &alice_user.id, None, "hers").await;
985 app.post_multipart(1045 app.post_multipart(
986 "/files",1046 "/files",
@@ -1007,7 +1067,11 @@ async fn cross_owner_answers_not_found() {
1007 assert_eq!(page.status, StatusCode::NOT_FOUND);1067 assert_eq!(page.status, StatusCode::NOT_FOUND);
1008 1068
1009 let answer = app1069 let answer = app
1010- .post("/api/folder/rename", Some(&bob), &[("id", &hers), ("name", "theirs")])1070+ .post(
1071+ "/api/folder/rename",
1072+ Some(&bob),
1073+ &[("id", &hers), ("name", "theirs")],
1074+ )
1011 .await;1075 .await;
1012 assert!(1076 assert!(
1013 answer.body.contains("NotFound"),1077 answer.body.contains("NotFound"),
@@ -1028,10 +1092,19 @@ async fn cross_owner_answers_not_found() {
1028 async fn file_rename_move_and_delete() {1092 async fn file_rename_move_and_delete() {
1029 let app = TestApp::build().await;1093 let app = TestApp::build().await;
1030 let cookie = app.sign_in("sub-fops", "fops@in.test", "Fops").await;1094 let cookie = app.sign_in("sub-fops", "fops@in.test", "Fops").await;
1031- let user = app.store.user_by_oidc_sub("sub-fops").await.unwrap().unwrap();1095+ let user = app
1096+ .store
1097+ .user_by_oidc_sub("sub-fops")
1098+ .await
1099+ .unwrap()
1100+ .unwrap();
1032 1101
1033- app.post("/api/folder/create", Some(&cookie), &[("parent_id", ""), ("name", "box")])1102+ app.post(
1034- .await;1103+ "/api/folder/create",
1104+ Some(&cookie),
1105+ &[("parent_id", ""), ("name", "box")],
1106+ )
1107+ .await;
1035 let boxed = folder_id(&app, &user.id, None, "box").await;1108 let boxed = folder_id(&app, &user.id, None, "box").await;
1036 app.post_multipart(1109 app.post_multipart(
1037 "/files",1110 "/files",
@@ -1051,21 +1124,34 @@ async fn file_rename_move_and_delete() {
1051 .unwrap();1124 .unwrap();
1052 1125
1053 let answer = app1126 let answer = app
1054- .post("/api/file/rename", Some(&cookie), &[("id", &file.id), ("name", "renamed.txt")])1127+ .post(
1128+ "/api/file/rename",
1129+ Some(&cookie),
1130+ &[("id", &file.id), ("name", "renamed.txt")],
1131+ )
1055 .await;1132 .await;
1056 assert_eq!(answer.body, "null", "renaming was refused: {}", answer.body);1133 assert_eq!(answer.body, "null", "renaming was refused: {}", answer.body);
1057 let answer = app1134 let answer = app
1058- .post("/api/file/move", Some(&cookie), &[("id", &file.id), ("folder_id", &boxed)])1135+ .post(
1136+ "/api/file/move",
1137+ Some(&cookie),
1138+ &[("id", &file.id), ("folder_id", &boxed)],
1139+ )
1059 .await;1140 .await;
1060 assert_eq!(answer.body, "null", "moving was refused: {}", answer.body);1141 assert_eq!(answer.body, "null", "moving was refused: {}", answer.body);
1061 let moved = app.store.file(&file.id).await.unwrap().unwrap();1142 let moved = app.store.file(&file.id).await.unwrap().unwrap();
1062 assert_eq!(moved.name, "renamed.txt");1143 assert_eq!(moved.name, "renamed.txt");
1063 assert_eq!(moved.folder_id.as_deref(), Some(boxed.as_str()));1144 assert_eq!(moved.folder_id.as_deref(), Some(boxed.as_str()));
1064 1145
1065- let answer = app.post("/api/file/delete", Some(&cookie), &[("id", &file.id)]).await;1146+ let answer = app
1147+ .post("/api/file/delete", Some(&cookie), &[("id", &file.id)])
1148+ .await;
1066 assert_eq!(answer.body, "null", "deleting was refused: {}", answer.body);1149 assert_eq!(answer.body, "null", "deleting was refused: {}", answer.body);
1067 let trashed = app.store.file(&file.id).await.unwrap().unwrap();1150 let trashed = app.store.file(&file.id).await.unwrap().unwrap();
1068- assert!(trashed.deleted_at.is_some(), "delete did not trash the file");1151+ assert!(
1152+ trashed.deleted_at.is_some(),
1153+ "delete did not trash the file"
1154+ );
1069 // And the bytes answer 404 once trashed.1155 // And the bytes answer 404 once trashed.
1070 let gone = app.get(&format!("/file/{}", file.id), Some(&cookie)).await;1156 let gone = app.get(&format!("/file/{}", file.id), Some(&cookie)).await;
1071 assert_eq!(gone.status, StatusCode::NOT_FOUND);1157 assert_eq!(gone.status, StatusCode::NOT_FOUND);
@@ -1083,29 +1169,44 @@ async fn upload_abort_and_bad_chunk() {
1083 serde_json::json!({"folder_id": null, "name": "never.bin", "size_bytes": 100}),1169 serde_json::json!({"folder_id": null, "name": "never.bin", "size_bytes": 100}),
1084 )1170 )
1085 .await;1171 .await;
1086- let session = answer.json()["Ok"]["id"].as_str().unwrap().to_string();1172+ let session = answer.json()["ok"]["id"].as_str().unwrap().to_string();
1087 1173
1088 // A short piece is a bad chunk, not a short file.1174 // A short piece is a bad chunk, not a short file.
1089- let answer = app.put_bytes(&format!("/api/upload/{session}/0"), Some(&cookie), b"short").await;1175+ let answer = app
1176+ .put_bytes(&format!("/api/upload/{session}/0"), Some(&cookie), b"short")
1177+ .await;
1090 assert_eq!(1178 assert_eq!(
1091- answer.json()["Err"].as_str(),1179+ answer.json()["err"].as_str(),
1092 Some("BadChunk"),1180 Some("BadChunk"),
1093 "short chunk was not refused: {}",1181 "short chunk was not refused: {}",
1094 answer.body1182 answer.body
1095 );1183 );
1096 1184
1097 let answer = app1185 let answer = app
1098- .post_json(&format!("/api/upload/{session}/abort"), Some(&cookie), serde_json::json!({}))1186+ .post_json(
1187+ &format!("/api/upload/{session}/abort"),
1188+ Some(&cookie),
1189+ serde_json::json!({}),
1190+ )
1099 .await;1191 .await;
1100- assert_eq!(answer.json()["Ok"], serde_json::Value::Null, "{}", answer.body);1192+ assert_eq!(
1193+ answer.json()["ok"],
1194+ serde_json::Value::Null,
1195+ "{}",
1196+ answer.body
1197+ );
1101 1198
1102 // The finish after the abort finds an expired session, with the chunks1199 // The finish after the abort finds an expired session, with the chunks
1103 // still staged for nothing.1200 // still staged for nothing.
1104 let answer = app1201 let answer = app
1105- .post_json(&format!("/api/upload/{session}/finish"), Some(&cookie), serde_json::json!({}))1202+ .post_json(
1203+ &format!("/api/upload/{session}/finish"),
1204+ Some(&cookie),
1205+ serde_json::json!({}),
1206+ )
1106 .await;1207 .await;
1107 assert_eq!(1208 assert_eq!(
1108- answer.json()["Err"].as_str(),1209+ answer.json()["err"].as_str(),
1109 Some("UploadExpired"),1210 Some("UploadExpired"),
1110 "finish after abort was not refused: {}",1211 "finish after abort was not refused: {}",
1111 answer.body1212 answer.body
@@ -1137,14 +1238,24 @@ async fn forced_download_is_attachment() {
1137 1238
1138 let inline = app.get(&format!("/file/{}", file.id), Some(&cookie)).await;1239 let inline = app.get(&format!("/file/{}", file.id), Some(&cookie)).await;
1139 assert!(1240 assert!(
1140- inline.disposition.as_deref().unwrap_or("").starts_with("inline"),1241+ inline
1242+ .disposition
1243+ .as_deref()
1244+ .unwrap_or("")
1245+ .starts_with("inline"),
1141 "text should render inline: {:?}",1246 "text should render inline: {:?}",
1142 inline.disposition1247 inline.disposition
1143 );1248 );
1144- let forced = app.get(&format!("/file/{}?dl=1", file.id), Some(&cookie)).await;1249+ let forced = app
1250+ .get(&format!("/file/{}?dl=1", file.id), Some(&cookie))
1251+ .await;
1145 assert_eq!(forced.status, StatusCode::OK);1252 assert_eq!(forced.status, StatusCode::OK);
1146 assert!(1253 assert!(
1147- forced.disposition.as_deref().unwrap_or("").starts_with("attachment"),1254+ forced
1255+ .disposition
1256+ .as_deref()
1257+ .unwrap_or("")
1258+ .starts_with("attachment"),
1148 "?dl=1 did not force attachment: {:?}",1259 "?dl=1 did not force attachment: {:?}",
1149 forced.disposition1260 forced.disposition
1150 );1261 );
@@ -1316,10 +1427,18 @@ async fn cross_owner_link_create_is_not_found() {
1316 .post(1427 .post(
1317 "/api/share/link/create",1428 "/api/share/link/create",
1318 Some(&admin),1429 Some(&admin),
1319- &[("kind", "file"), ("target_id", &file), ("can_download", "1")],1430+ &[
1431+ ("kind", "file"),
1432+ ("target_id", &file),
1433+ ("can_download", "1"),
1434+ ],
1320 )1435 )
1321 .await;1436 .await;
1322- assert!(answer.refused("not-found", "create"), "{:?}", answer.location);1437+ assert!(
1438+ answer.refused("not-found", "create"),
1439+ "{:?}",
1440+ answer.location
1441+ );
1323 }1442 }
1324 1443
1325 // -- per-user shares --------------------------------------------------------1444 // -- per-user shares --------------------------------------------------------
@@ -1406,16 +1525,30 @@ async fn trash_restore_purge_empty_flows() {
1406 1525
1407 // Restore one: it leaves the trash and keeps its bytes.1526 // Restore one: it leaves the trash and keeps its bytes.
1408 let answer = app1527 let answer = app
1409- .post("/api/trash/restore", Some(&admin), &[("kind", "file"), ("id", &one)])1528+ .post(
1529+ "/api/trash/restore",
1530+ Some(&admin),
1531+ &[("kind", "file"), ("id", &one)],
1532+ )
1410 .await;1533 .await;
1411 assert!(answer.accepted(), "restore refused: {:?}", answer.location);1534 assert!(answer.accepted(), "restore refused: {:?}", answer.location);
1412 assert!(1535 assert!(
1413- app.store.file(&one).await.unwrap().unwrap().deleted_at.is_none()1536+ app.store
1537+ .file(&one)
1538+ .await
1539+ .unwrap()
1540+ .unwrap()
1541+ .deleted_at
1542+ .is_none()
1414 );1543 );
1415 1544
1416 // Purge the other: the row and its bytes go.1545 // Purge the other: the row and its bytes go.
1417 let answer = app1546 let answer = app
1418- .post("/api/trash/purge", Some(&admin), &[("kind", "file"), ("id", &two)])1547+ .post(
1548+ "/api/trash/purge",
1549+ Some(&admin),
1550+ &[("kind", "file"), ("id", &two)],
1551+ )
1419 .await;1552 .await;
1420 assert!(answer.accepted(), "purge refused: {:?}", answer.location);1553 assert!(answer.accepted(), "purge refused: {:?}", answer.location);
1421 assert!(app.store.file(&two).await.unwrap().is_none());1554 assert!(app.store.file(&two).await.unwrap().is_none());
@@ -1425,14 +1558,7 @@ async fn trash_restore_purge_empty_flows() {
1425 app.store.delete_file(&three).await.unwrap();1558 app.store.delete_file(&three).await.unwrap();
1426 let answer = app.post("/api/trash/empty", Some(&admin), &[]).await;1559 let answer = app.post("/api/trash/empty", Some(&admin), &[]).await;
1427 assert!(answer.accepted(), "empty refused: {:?}", answer.location);1560 assert!(answer.accepted(), "empty refused: {:?}", answer.location);
1428- assert!(1561+ assert!(app.store.list_trash(&owner).await.unwrap().files.is_empty());
1429- app.store
1430- .list_trash(&owner)
1431- .await
1432- .unwrap()
1433- .files
1434- .is_empty()
1435- );
1436 }1562 }
1437 1563
1438 #[tokio::test]1564 #[tokio::test]
@@ -1440,11 +1566,7 @@ async fn restore_under_trashed_ancestor_is_refused() {
1440 let app = TestApp::build().await;1566 let app = TestApp::build().await;
1441 let admin = app.sign_in("sub-admin", "ada@in.test", "Ada").await;1567 let admin = app.sign_in("sub-admin", "ada@in.test", "Ada").await;
1442 let owner = owner_of(&app, "sub-admin").await;1568 let owner = owner_of(&app, "sub-admin").await;
1443- let folder = app1569+ let folder = app.store.create_folder(&owner, None, "box").await.unwrap();
1444- .store
1445- .create_folder(&owner, None, "box")
1446- .await
1447- .unwrap();
1448 let file = app1570 let file = app
1449 .store1571 .store
1450 .insert_file(&owner, Some(&folder.id), "inbox.txt", b"in")1572 .insert_file(&owner, Some(&folder.id), "inbox.txt", b"in")
@@ -1523,25 +1645,51 @@ async fn search_scopes_to_owner_and_hides_trashed() {
1523 // name: the upload control renders, no results caption does.1645 // name: the upload control renders, no results caption does.
1524 let page = app.get("/drive", Some(&admin)).await;1646 let page = app.get("/drive", Some(&admin)).await;
1525 assert_eq!(page.status, StatusCode::OK, "{}", page.text());1647 assert_eq!(page.status, StatusCode::OK, "{}", page.text());
1526- assert!(page.text().contains("id=\"upload-form\""), "{}", page.text());1648+ assert!(
1649+ page.text().contains("id=\"upload-form\""),
1650+ "{}",
1651+ page.text()
1652+ );
1527 assert!(!page.text().contains("Search results"), "{}", page.text());1653 assert!(!page.text().contains("Search results"), "{}", page.text());
1528 1654
1529 let page = app.get("/drive?q=quarterly", Some(&admin)).await;1655 let page = app.get("/drive?q=quarterly", Some(&admin)).await;
1530 assert_eq!(page.status, StatusCode::OK, "{}", page.text());1656 assert_eq!(page.status, StatusCode::OK, "{}", page.text());
1531- assert!(page.text().contains("quarterly report.txt"), "{}", page.text());1657+ assert!(
1532- assert!(!page.text().contains("quarterly notes.txt"), "{}", page.text());1658+ page.text().contains("quarterly report.txt"),
1533- assert!(!page.text().contains("quarterly draft.txt"), "{}", page.text());1659+ "{}",
1660+ page.text()
1661+ );
1662+ assert!(
1663+ !page.text().contains("quarterly notes.txt"),
1664+ "{}",
1665+ page.text()
1666+ );
1667+ assert!(
1668+ !page.text().contains("quarterly draft.txt"),
1669+ "{}",
1670+ page.text()
1671+ );
1534 assert!(app.store.file(&mine).await.unwrap().is_some());1672 assert!(app.store.file(&mine).await.unwrap().is_some());
1535 1673
1536 let page = app.get("/drive?q=quarterly", Some(&bob)).await;1674 let page = app.get("/drive?q=quarterly", Some(&bob)).await;
1537- assert!(page.text().contains("quarterly notes.txt"), "{}", page.text());1675+ assert!(
1538- assert!(!page.text().contains("quarterly report.txt"), "{}", page.text());1676+ page.text().contains("quarterly notes.txt"),
1677+ "{}",
1678+ page.text()
1679+ );
1680+ assert!(
1681+ !page.text().contains("quarterly report.txt"),
1682+ "{}",
1683+ page.text()
1684+ );
1539 }1685 }
1540 1686
1541 #[tokio::test]1687 #[tokio::test]
1542 async fn drive_search_results_merge_into_one_panel() {1688 async fn drive_search_results_merge_into_one_panel() {
1543 let app = TestApp::build().await;1689 let app = TestApp::build().await;
1544- let cookie = app.sign_in("sub-search-in-place", "inplace@in.test", "InPlace").await;1690+ let cookie = app
1691+ .sign_in("sub-search-in-place", "inplace@in.test", "InPlace")
1692+ .await;
1545 let owner = owner_of(&app, "sub-search-in-place").await;1693 let owner = owner_of(&app, "sub-search-in-place").await;
1546 let answer = app1694 let answer = app
1547 .post(1695 .post(
@@ -1561,12 +1709,16 @@ async fn drive_search_results_merge_into_one_panel() {
1561 assert!(body.contains("holiday photos"), "{body}");1709 assert!(body.contains("holiday photos"), "{body}");
1562 assert!(body.contains("holiday report.txt"), "{body}");1710 assert!(body.contains("holiday report.txt"), "{body}");
1563 assert!(body.contains(&format!("/drive?folder={folder}")), "{body}");1711 assert!(body.contains(&format!("/drive?folder={folder}")), "{body}");
1564- assert!(body.contains(&format!("/file/{file}")), "{body}");1712+ assert!(body.contains(&format!("/view/{file}")), "{body}");
1565 let folder_at = body.find("holiday photos").expect("no folder hit");1713 let folder_at = body.find("holiday photos").expect("no folder hit");
1566 let file_at = body.find("holiday report.txt").expect("no file hit");1714 let file_at = body.find("holiday report.txt").expect("no file hit");
1567 assert!(folder_at < file_at, "file hit precedes folder hit: {body}");1715 assert!(folder_at < file_at, "file hit precedes folder hit: {body}");
1568 // One panel, no heads or chips.1716 // One panel, no heads or chips.
1569- assert_eq!(body.matches("<section class=\"panel\">").count(), 1, "{body}");1717+ assert_eq!(
1718+ body.matches("<section class=\"panel\">").count(),
1719+ 1,
1720+ "{body}"
1721+ );
1570 assert!(!body.contains("panel-head"), "{body}");1722 assert!(!body.contains("panel-head"), "{body}");
1571 assert!(!body.contains("class=\"chip\""), "{body}");1723 assert!(!body.contains("class=\"chip\""), "{body}");
1572 assert!(!body.contains(">Folders</h2>"), "{body}");1724 assert!(!body.contains(">Folders</h2>"), "{body}");
@@ -1619,7 +1771,9 @@ async fn drive_search_never_shows_other_owners_hits() {
1619 #[tokio::test]1771 #[tokio::test]
1620 async fn drive_search_empty_query_is_the_folder_view() {1772 async fn drive_search_empty_query_is_the_folder_view() {
1621 let app = TestApp::build().await;1773 let app = TestApp::build().await;
1622- let cookie = app.sign_in("sub-search-empty", "empty@in.test", "Empty").await;1774+ let cookie = app
1775+ .sign_in("sub-search-empty", "empty@in.test", "Empty")
1776+ .await;
1623 let owner = owner_of(&app, "sub-search-empty").await;1777 let owner = owner_of(&app, "sub-search-empty").await;
1624 let _ = file_id(&app, &owner, "plain.txt", b"p").await;1778 let _ = file_id(&app, &owner, "plain.txt", b"p").await;
1625 1779
@@ -1673,7 +1827,10 @@ async fn topbar_nav_has_no_search_link() {
1673 assert!(nav.contains("href=\"/drive\""), "{nav}");1827 assert!(nav.contains("href=\"/drive\""), "{nav}");
1674 assert!(nav.contains("href=\"/shared\""), "{nav}");1828 assert!(nav.contains("href=\"/shared\""), "{nav}");
1675 assert!(nav.contains("href=\"/trash\""), "{nav}");1829 assert!(nav.contains("href=\"/trash\""), "{nav}");
1676- assert!(!nav.contains("/search"), "search leaked into the nav: {nav}");1830+ assert!(
1831+ !nav.contains("/search"),
1832+ "search leaked into the nav: {nav}"
1833+ );
1677 assert!(!nav.contains("Search"), "search leaked into the nav: {nav}");1834 assert!(!nav.contains("Search"), "search leaked into the nav: {nav}");
1678 }1835 }
1679 1836
@@ -1700,7 +1857,10 @@ async fn settings_quota_and_disable_guards() {
1700 )1857 )
1701 .await;1858 .await;
1702 assert!(answer.accepted(), "quota refused: {:?}", answer.location);1859 assert!(answer.accepted(), "quota refused: {:?}", answer.location);
1703- assert_eq!(app.store.user(&bob_id).await.unwrap().unwrap().quota_bytes, 123456);1860+ assert_eq!(
1861+ app.store.user(&bob_id).await.unwrap().unwrap().quota_bytes,
1862+ 123456
1863+ );
1704 1864
1705 // A non-admin is refused the same call.1865 // A non-admin is refused the same call.
1706 let answer = app1866 let answer = app
@@ -1710,7 +1870,11 @@ async fn settings_quota_and_disable_guards() {
1710 &[("user_id", &bob_id), ("quota_bytes", "999")],1870 &[("user_id", &bob_id), ("quota_bytes", "999")],
1711 )1871 )
1712 .await;1872 .await;
1713- assert!(answer.refused("forbidden", "quota"), "{:?}", answer.location);1873+ assert!(
1874+ answer.refused("forbidden", "quota"),
1875+ "{:?}",
1876+ answer.location
1877+ );
1714 1878
1715 // Disabling yourself is refused; disabling Bob signs him out.1879 // Disabling yourself is refused; disabling Bob signs him out.
1716 let answer = app1880 let answer = app
@@ -1720,7 +1884,11 @@ async fn settings_quota_and_disable_guards() {
1720 &[("user_id", &admin_id), ("disabled", "1")],1884 &[("user_id", &admin_id), ("disabled", "1")],
1721 )1885 )
1722 .await;1886 .await;
1723- assert!(answer.refused("forbidden", "disable"), "{:?}", answer.location);1887+ assert!(
1888+ answer.refused("forbidden", "disable"),
1889+ "{:?}",
1890+ answer.location
1891+ );
1724 1892
1725 let answer = app1893 let answer = app
1726 .post(1894 .post(
@@ -1798,9 +1966,18 @@ async fn empty_file_upload_round_trip() {
1798 &[("empty.txt", "text/plain", &[])],1966 &[("empty.txt", "text/plain", &[])],
1799 )1967 )
1800 .await;1968 .await;
1801- assert_eq!(answer.status, StatusCode::SEE_OTHER, "{}", answer.location.clone().unwrap_or_default());1969+ assert_eq!(
1970+ answer.status,
1971+ StatusCode::SEE_OTHER,
1972+ "{}",
1973+ answer.location.clone().unwrap_or_default()
1974+ );
1802 assert!(1975 assert!(
1803- !answer.location.as_deref().unwrap_or("").contains("refusal="),1976+ !answer
1977+ .location
1978+ .as_deref()
1979+ .unwrap_or("")
1980+ .contains("refusal="),
1804 "empty upload was refused: {}",1981 "empty upload was refused: {}",
1805 answer.location.clone().unwrap_or_default()1982 answer.location.clone().unwrap_or_default()
1806 );1983 );
@@ -1818,7 +1995,11 @@ async fn empty_file_upload_round_trip() {
1818 1995
1819 let got = app.get(&format!("/file/{}", file.id), Some(&cookie)).await;1996 let got = app.get(&format!("/file/{}", file.id), Some(&cookie)).await;
1820 assert_eq!(got.status, StatusCode::OK);1997 assert_eq!(got.status, StatusCode::OK);
1821- assert!(got.bytes.is_empty(), "expected 0 bytes, got {}", got.bytes.len());1998+ assert!(
1999+ got.bytes.is_empty(),
2000+ "expected 0 bytes, got {}",
2001+ got.bytes.len()
2002+ );
1822 }2003 }
1823 2004
1824 // -- share review regressions (FullSilkworm) ------------------------------------2005 // -- share review regressions (FullSilkworm) ------------------------------------
@@ -1906,7 +2087,11 @@ async fn malformed_expiry_is_forbidden() {
1906 ],2087 ],
1907 )2088 )
1908 .await;2089 .await;
1909- assert!(answer.accepted(), "good expiry refused: {:?}", answer.location);2090+ assert!(
2091+ answer.accepted(),
2092+ "good expiry refused: {:?}",
2093+ answer.location
2094+ );
1910 let links = app.store.share_links(&owner).await.unwrap();2095 let links = app.store.share_links(&owner).await.unwrap();
1911 assert_eq!(links.len(), 1);2096 assert_eq!(links.len(), 1);
1912 assert!(2097 assert!(
@@ -1925,7 +2110,11 @@ async fn malformed_expiry_is_forbidden() {
1925 ],2110 ],
1926 )2111 )
1927 .await;2112 .await;
1928- assert!(answer.accepted(), "empty expiry refused: {:?}", answer.location);2113+ assert!(
2114+ answer.accepted(),
2115+ "empty expiry refused: {:?}",
2116+ answer.location
2117+ );
1929 let links = app.store.share_links(&owner).await.unwrap();2118 let links = app.store.share_links(&owner).await.unwrap();
1930 assert_eq!(links.len(), 2);2119 assert_eq!(links.len(), 2);
1931 assert!(2120 assert!(
@@ -1963,7 +2152,11 @@ async fn unshare_trashed_target_still_revokes() {
1963 .post(2152 .post(
1964 "/api/share/user/remove",2153 "/api/share/user/remove",
1965 Some(&admin),2154 Some(&admin),
1966- &[("kind", "file"), ("target_id", &file), ("email", "bob@in.test")],2155+ &[
2156+ ("kind", "file"),
2157+ ("target_id", &file),
2158+ ("email", "bob@in.test"),
2159+ ],
1967 )2160 )
1968 .await;2161 .await;
1969 assert!(answer.accepted(), "remove refused: {:?}", answer.location);2162 assert!(answer.accepted(), "remove refused: {:?}", answer.location);
@@ -1989,7 +2182,11 @@ async fn view_only_public_thumb_serves_webp() {
1989 )2182 )
1990 .await;2183 .await;
1991 assert!(2184 assert!(
1992- !answer.location.as_deref().unwrap_or("").contains("refusal="),2185+ !answer
2186+ .location
2187+ .as_deref()
2188+ .unwrap_or("")
2189+ .contains("refusal="),
1993 "image upload was refused: {}",2190 "image upload was refused: {}",
1994 answer.location.unwrap_or_default()2191 answer.location.unwrap_or_default()
1995 );2192 );
@@ -2115,8 +2312,16 @@ async fn settings_preferences_round_trip() {
2115 assert_eq!(user.language, "en");2312 assert_eq!(user.language, "en");
2116 let page = app.get("/settings", Some(&cookie)).await;2313 let page = app.get("/settings", Some(&cookie)).await;
2117 assert_eq!(page.status, StatusCode::OK, "{}", page.text());2314 assert_eq!(page.status, StatusCode::OK, "{}", page.text());
2118- assert!(page.text().contains("data-ui=\"instrument\""), "{}", page.text());2315+ assert!(
2119- assert!(page.text().contains("data-theme=\"dark\""), "{}", page.text());2316+ page.text().contains("data-ui=\"instrument\""),
2317+ "{}",
2318+ page.text()
2319+ );
2320+ assert!(
2321+ page.text().contains("data-theme=\"dark\""),
2322+ "{}",
2323+ page.text()
2324+ );
2120 assert!(page.text().contains("lang=\"en\""), "{}", page.text());2325 assert!(page.text().contains("lang=\"en\""), "{}", page.text());
2121 2326
2122 // Saving all three writes the row and re-renders the chrome — away from2327 // Saving all three writes the row and re-renders the chrome — away from
@@ -2181,7 +2386,9 @@ async fn settings_preferences_round_trip() {
2181 #[tokio::test]2386 #[tokio::test]
2182 async fn settings_preferences_rejects_unknown_values() {2387 async fn settings_preferences_rejects_unknown_values() {
2183 let app = TestApp::build().await;2388 let app = TestApp::build().await;
2184- let cookie = app.sign_in("sub-prefs-bad", "prefsbad@in.test", "PrefsBad").await;2389+ let cookie = app
2390+ .sign_in("sub-prefs-bad", "prefsbad@in.test", "PrefsBad")
2391+ .await;
2185 let me = owner_of(&app, "sub-prefs-bad").await;2392 let me = owner_of(&app, "sub-prefs-bad").await;
2186 2393
2187 // Each field is refused with its own code, and the row keeps the last2394 // 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() {
2193 &[("ui", "mosaic"), ("theme", "light"), ("language", "en")],2400 &[("ui", "mosaic"), ("theme", "light"), ("language", "en")],
2194 )2401 )
2195 .await;2402 .await;
2196- assert!(answer.refused("bad-ui", "preferences"), "{:?}", answer.location);2403+ assert!(
2404+ answer.refused("bad-ui", "preferences"),
2405+ "{:?}",
2406+ answer.location
2407+ );
2197 let answer = app2408 let answer = app
2198 .post(2409 .post(
2199 "/api/settings/preferences",2410 "/api/settings/preferences",
@@ -2289,8 +2500,16 @@ async fn signed_out_settings_falls_back_to_accept_language() {
2289 let page = app.get("/settings", None).await;2500 let page = app.get("/settings", None).await;
2290 assert_eq!(page.status, StatusCode::OK, "{}", page.text());2501 assert_eq!(page.status, StatusCode::OK, "{}", page.text());
2291 assert!(page.text().contains("lang=\"en\""), "{}", page.text());2502 assert!(page.text().contains("lang=\"en\""), "{}", page.text());
2292- assert!(page.text().contains("data-theme=\"dark\""), "{}", page.text());2503+ assert!(
2293- assert!(page.text().contains("data-ui=\"instrument\""), "{}", page.text());2504+ page.text().contains("data-theme=\"dark\""),
2505+ "{}",
2506+ page.text()
2507+ );
2508+ assert!(
2509+ page.text().contains("data-ui=\"instrument\""),
2510+ "{}",
2511+ page.text()
2512+ );
2294 assert!(page.text().contains("Sign in first."), "{}", page.text());2513 assert!(page.text().contains("Sign in first."), "{}", page.text());
2295 // A Turkish browser is answered in Turkish.2514 // A Turkish browser is answered in Turkish.
2296 let page = app2515 let page = app
@@ -2343,8 +2562,12 @@ fn assert_stage_nests(body: &str, markers: &[&str]) {
2343 #[tokio::test]2562 #[tokio::test]
2344 async fn shared_lists_nest_inside_the_stage() {2563 async fn shared_lists_nest_inside_the_stage() {
2345 let app = TestApp::build().await;2564 let app = TestApp::build().await;
2346- let admin = app.sign_in("sub-stage-sharer", "sharer@in.test", "Sharer").await;2565+ let admin = app
2347- let bob = app.sign_in("sub-stage-bob", "stagebob@in.test", "StageBob").await;2566+ .sign_in("sub-stage-sharer", "sharer@in.test", "Sharer")
2567+ .await;
2568+ let bob = app
2569+ .sign_in("sub-stage-bob", "stagebob@in.test", "StageBob")
2570+ .await;
2348 let owner = owner_of(&app, "sub-stage-sharer").await;2571 let owner = owner_of(&app, "sub-stage-sharer").await;
2349 let file = file_id(&app, &owner, "staged.txt", b"staged").await;2572 let file = file_id(&app, &owner, "staged.txt", b"staged").await;
2350 let answer = app2573 let answer = app
@@ -2371,7 +2594,9 @@ async fn shared_lists_nest_inside_the_stage() {
2371 #[tokio::test]2594 #[tokio::test]
2372 async fn trash_panels_nest_inside_the_stage() {2595 async fn trash_panels_nest_inside_the_stage() {
2373 let app = TestApp::build().await;2596 let app = TestApp::build().await;
2374- let admin = app.sign_in("sub-stage-trash", "stagetrash@in.test", "StageTrash").await;2597+ let admin = app
2598+ .sign_in("sub-stage-trash", "stagetrash@in.test", "StageTrash")
2599+ .await;
2375 let owner = owner_of(&app, "sub-stage-trash").await;2600 let owner = owner_of(&app, "sub-stage-trash").await;
2376 let one = file_id(&app, &owner, "staged-trash.txt", b"staged").await;2601 let one = file_id(&app, &owner, "staged-trash.txt", b"staged").await;
2377 app.store.delete_file(&one).await.unwrap();2602 app.store.delete_file(&one).await.unwrap();
@@ -2391,7 +2616,9 @@ async fn trash_panels_nest_inside_the_stage() {
2391 #[tokio::test]2616 #[tokio::test]
2392 async fn drive_search_panel_nests_inside_the_stage() {2617 async fn drive_search_panel_nests_inside_the_stage() {
2393 let app = TestApp::build().await;2618 let app = TestApp::build().await;
2394- let admin = app.sign_in("sub-stage-search", "stagesearch@in.test", "StageSearch").await;2619+ let admin = app
2620+ .sign_in("sub-stage-search", "stagesearch@in.test", "StageSearch")
2621+ .await;
2395 let owner = owner_of(&app, "sub-stage-search").await;2622 let owner = owner_of(&app, "sub-stage-search").await;
2396 file_id(&app, &owner, "staged-report.txt", b"staged").await;2623 file_id(&app, &owner, "staged-report.txt", b"staged").await;
2397 let page = app.get("/drive?q=staged-report", Some(&admin)).await;2624 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() {
2427 assert_eq!(page.status, StatusCode::OK, "{}", page.text());2654 assert_eq!(page.status, StatusCode::OK, "{}", page.text());
2428 assert!(!page.text().contains("detail-crumbs"), "{}", page.text());2655 assert!(!page.text().contains("detail-crumbs"), "{}", page.text());
2429 // The filterbar itself stays, holding the search box and the create form.2656 // The filterbar itself stays, holding the search box and the create form.
2430- assert!(page.text().contains("class=\"filterbar\""), "{}", page.text());2657+ assert!(
2658+ page.text().contains("class=\"filterbar\""),
2659+ "{}",
2660+ page.text()
2661+ );
2431 assert!(page.text().contains("name=\"q\""), "{}", page.text());2662 assert!(page.text().contains("name=\"q\""), "{}", page.text());
2432 assert!(2663 assert!(
2433 page.text().contains("action=\"/api/folder/create\""),2664 page.text().contains("action=\"/api/folder/create\""),
@@ -2437,7 +2668,11 @@ async fn drive_root_hides_crumbs_while_a_subfolder_shows_them() {
2437 2668
2438 // Inside a folder the way back renders.2669 // Inside a folder the way back renders.
2439 let answer = app2670 let answer = app
2440- .post("/api/folder/create", Some(&cookie), &[("parent_id", ""), ("name", "inside")])2671+ .post(
2672+ "/api/folder/create",
2673+ Some(&cookie),
2674+ &[("parent_id", ""), ("name", "inside")],
2675+ )
2441 .await;2676 .await;
2442 assert_eq!(answer.status, StatusCode::SEE_OTHER, "{}", answer.body);2677 assert_eq!(answer.status, StatusCode::SEE_OTHER, "{}", answer.body);
2443 let folder = folder_id(&app, &owner, None, "inside").await;2678 let folder = folder_id(&app, &owner, None, "inside").await;
@@ -2452,7 +2687,9 @@ async fn drive_root_hides_crumbs_while_a_subfolder_shows_them() {
2452 #[tokio::test]2687 #[tokio::test]
2453 async fn settings_quota_button_wears_the_quiet_class() {2688 async fn settings_quota_button_wears_the_quiet_class() {
2454 let app = TestApp::build().await;2689 let app = TestApp::build().await;
2455- let admin = app.sign_in("sub-quota-btn", "quotabtn@in.test", "QuotaBtn").await;2690+ let admin = app
2691+ .sign_in("sub-quota-btn", "quotabtn@in.test", "QuotaBtn")
2692+ .await;
2456 let page = app.get("/settings", Some(&admin)).await;2693 let page = app.get("/settings", Some(&admin)).await;
2457 assert_eq!(page.status, StatusCode::OK, "{}", page.text());2694 assert_eq!(page.status, StatusCode::OK, "{}", page.text());
2458 let body = page.text();2695 let body = page.text();
@@ -2462,12 +2699,19 @@ async fn settings_quota_button_wears_the_quiet_class() {
2462 body.contains("<form class=\"pop-row-form member-quota\""),2699 body.contains("<form class=\"pop-row-form member-quota\""),
2463 "{body}"2700 "{body}"
2464 );2701 );
2465- let quota_at = body.find("action=\"/api/settings/quota\"").expect("no quota form");2702+ let quota_at = body
2703+ .find("action=\"/api/settings/quota\"")
2704+ .expect("no quota form");
2466 let button_at = body[quota_at..]2705 let button_at = body[quota_at..]
2467 .find("<button class=\"quiet\" type=\"submit\">")2706 .find("<button class=\"quiet\" type=\"submit\">")
2468 .expect("quota submit is not quiet");2707 .expect("quota submit is not quiet");
2469- let form_end = body[quota_at..].find("</form>").expect("quota form never closes");2708+ let form_end = body[quota_at..]
2470- assert!(button_at < form_end, "quiet button escapes the quota form: {body}");2709+ .find("</form>")
2710+ .expect("quota form never closes");
2711+ assert!(
2712+ button_at < form_end,
2713+ "quiet button escapes the quota form: {body}"
2714+ );
2471 }2715 }
2472 2716
2473 #[tokio::test]2717 #[tokio::test]
@@ -2482,14 +2726,20 @@ async fn settings_lives_in_the_user_menu_not_the_topbar() {
2482 let nav_start = body.find("topbar-nav-links").expect("no nav");2726 let nav_start = body.find("topbar-nav-links").expect("no nav");
2483 let nav_end = body[nav_start..].find("</nav>").expect("nav never closes");2727 let nav_end = body[nav_start..].find("</nav>").expect("nav never closes");
2484 let nav = &body[nav_start..nav_start + nav_end];2728 let nav = &body[nav_start..nav_start + nav_end];
2485- assert!(!nav.contains("/settings"), "settings leaked into the nav: {nav}");2729+ assert!(
2730+ !nav.contains("/settings"),
2731+ "settings leaked into the nav: {nav}"
2732+ );
2486 2733
2487 // …the user menu carries it, plus the profile link out to im.2734 // …the user menu carries it, plus the profile link out to im.
2488 let menu_start = body.find("user-menu-panel").expect("no user menu");2735 let menu_start = body.find("user-menu-panel").expect("no user menu");
2489 let menu = &body[menu_start..];2736 let menu = &body[menu_start..];
2490 assert!(menu.contains("href=\"/settings\""), "{menu}");2737 assert!(menu.contains("href=\"/settings\""), "{menu}");
2491 let issuer = format!("href=\"{}/\"", app.config.oidc.issuer);2738 let issuer = format!("href=\"{}/\"", app.config.oidc.issuer);
2492- assert!(menu.contains(&issuer), "no profile link to the issuer: {menu}");2739+ assert!(
2740+ menu.contains(&issuer),
2741+ "no profile link to the issuer: {menu}"
2742+ );
2493 }2743 }
2494 2744
2495 #[tokio::test]2745 #[tokio::test]
@@ -2523,7 +2773,10 @@ async fn avatar_serves_own_photo_with_etag() {
2523 body.contains(&format!("src=\"/avatar/{me}\"")),2773 body.contains(&format!("src=\"/avatar/{me}\"")),
2524 "menu wears no photo img"2774 "menu wears no photo img"
2525 );2775 );
2526- assert!(body.contains("avatar-stack"), "no initials stack under the photo");2776+ assert!(
2777+ body.contains("avatar-stack"),
2778+ "no initials stack under the photo"
2779+ );
2527 assert!(body.contains("__inAvatar"), "no avatar fallback script");2780 assert!(body.contains("__inAvatar"), "no avatar fallback script");
2528 }2781 }
2529 2782
@@ -2541,7 +2794,9 @@ async fn avatar_without_photo_is_not_found() {
2541 #[tokio::test]2794 #[tokio::test]
2542 async fn avatar_for_someone_else_is_not_found() {2795 async fn avatar_for_someone_else_is_not_found() {
2543 let app = TestApp::build().await;2796 let app = TestApp::build().await;
2544- let alice = app.sign_in("sub-alice-face", "alice@in.test", "Alice").await;2797+ let alice = app
2798+ .sign_in("sub-alice-face", "alice@in.test", "Alice")
2799+ .await;
2545 let bob = app.sign_in("sub-bob-face", "bob@in.test", "Bob").await;2800 let bob = app.sign_in("sub-bob-face", "bob@in.test", "Bob").await;
2546 let bob_id = owner_of(&app, "sub-bob-face").await;2801 let bob_id = owner_of(&app, "sub-bob-face").await;
2547 app.fake.set_photo("sub-bob-face", tiny_png(), "image/png");2802 app.fake.set_photo("sub-bob-face", tiny_png(), "image/png");
@@ -2590,32 +2845,54 @@ async fn avatar_resolves_local_id_to_oidc_sub() {
2590 #[tokio::test]2845 #[tokio::test]
2591 async fn drive_add_menu_has_two_items() {2846 async fn drive_add_menu_has_two_items() {
2592 let app = TestApp::build().await;2847 let app = TestApp::build().await;
2593- let cookie = app.sign_in("sub-addmenu", "addmenu@in.test", "AddMenu").await;2848+ let cookie = app
2849+ .sign_in("sub-addmenu", "addmenu@in.test", "AddMenu")
2850+ .await;
2594 2851
2595 let page = app.get("/drive", Some(&cookie)).await;2852 let page = app.get("/drive", Some(&cookie)).await;
2596 assert_eq!(page.status, StatusCode::OK);2853 assert_eq!(page.status, StatusCode::OK);
2597 let body = page.text();2854 let body = page.text();
2598 2855
2599 // The filterbar carries one + menu, not the old confirm modal.2856 // The filterbar carries one + menu, not the old confirm modal.
2600- assert!(!body.contains("confirm-details"), "confirm modal still rendered");2857+ assert!(
2601- assert!(!body.contains("new-folder-form"), "modal form still rendered");2858+ !body.contains("confirm-details"),
2859+ "confirm modal still rendered"
2860+ );
2861+ assert!(
2862+ !body.contains("new-folder-form"),
2863+ "modal form still rendered"
2864+ );
2602 let details_at = body.find("drive-add").expect("no + menu on the drive");2865 let details_at = body.find("drive-add").expect("no + menu on the drive");
2603- let details_end = body[details_at..].find("</details>").expect("menu never closes");2866+ let details_end = body[details_at..]
2867+ .find("</details>")
2868+ .expect("menu never closes");
2604 let details = &body[details_at..details_at + details_end];2869 let details = &body[details_at..details_at + details_end];
2605 // New folder: a button-only quick form posting just the parent.2870 // New folder: a button-only quick form posting just the parent.
2606 assert!(2871 assert!(
2607 details.contains("action=\"/api/folder/create\""),2872 details.contains("action=\"/api/folder/create\""),
2608 "quick form escapes the menu: {details}"2873 "quick form escapes the menu: {details}"
2609 );2874 );
2610- assert!(details.contains("name=\"parent_id\""), "no parent field: {details}");2875+ assert!(
2611- assert!(!details.contains("name=\"name\""), "quick form asks for a name: {details}");2876+ details.contains("name=\"parent_id\""),
2612- assert!(details.contains("New folder"), "no New folder item: {details}");2877+ "no parent field: {details}"
2878+ );
2879+ assert!(
2880+ !details.contains("name=\"name\""),
2881+ "quick form asks for a name: {details}"
2882+ );
2883+ assert!(
2884+ details.contains("New folder"),
2885+ "no New folder item: {details}"
2886+ );
2613 // Upload files: a label for the panel's own picker, no script needed.2887 // Upload files: a label for the panel's own picker, no script needed.
2614 assert!(2888 assert!(
2615 details.contains("for=\"drive-upload-input\""),2889 details.contains("for=\"drive-upload-input\""),
2616 "no upload label in the menu: {details}"2890 "no upload label in the menu: {details}"
2617 );2891 );
2618- assert!(details.contains("Upload files"), "no Upload files item: {details}");2892+ assert!(
2893+ details.contains("Upload files"),
2894+ "no Upload files item: {details}"
2895+ );
2619 assert!(2896 assert!(
2620 body.contains("id=\"drive-upload-input\""),2897 body.contains("id=\"drive-upload-input\""),
2621 "upload input carries no id for the label"2898 "upload input carries no id for the label"
@@ -2629,11 +2906,22 @@ async fn drive_quick_create_names_and_edits() {
2629 let me = owner_of(&app, "sub-quick").await;2906 let me = owner_of(&app, "sub-quick").await;
2630 2907
2631 // The + menu posts no name: generic name, 303 into that row's edit mode.2908 // The + menu posts no name: generic name, 303 into that row's edit mode.
2632- let answer = app.post("/api/folder/create", Some(&cookie), &[("parent_id", "")]).await;2909+ let answer = app
2910+ .post("/api/folder/create", Some(&cookie), &[("parent_id", "")])
2911+ .await;
2633 assert_eq!(answer.status, StatusCode::SEE_OTHER);2912 assert_eq!(answer.status, StatusCode::SEE_OTHER);
2634- let location = answer.location.clone().expect("quick create redirects nowhere");2913+ let location = answer
2635- assert!(location.starts_with("/drive?"), "quick create leaves the drive: {location}");2914+ .location
2636- assert!(location.contains("edit="), "quick create skips edit mode: {location}");2915+ .clone()
2916+ .expect("quick create redirects nowhere");
2917+ assert!(
2918+ location.starts_with("/drive?"),
2919+ "quick create leaves the drive: {location}"
2920+ );
2921+ assert!(
2922+ location.contains("edit="),
2923+ "quick create skips edit mode: {location}"
2924+ );
2637 let edit = location2925 let edit = location
2638 .split("edit=")2926 .split("edit=")
2639 .nth(1)2927 .nth(1)
@@ -2643,62 +2931,113 @@ async fn drive_quick_create_names_and_edits() {
2643 .unwrap();2931 .unwrap();
2644 assert_eq!(folder_id(&app, &me, None, "New folder").await, edit);2932 assert_eq!(folder_id(&app, &me, None, "New folder").await, edit);
2645 2933
2646- // A second quick create collision-suffixes instead of colliding.2934+ // Duplicate folder names are allowed: a second quick create takes the
2647- let answer = app.post("/api/folder/create", Some(&cookie), &[("parent_id", "")]).await;2935+ // same generic name on a new row instead of suffixing.
2648- let location = answer.location.clone().expect("second quick create redirects nowhere");2936+ let answer = app
2649- let edit = location2937+ .post("/api/folder/create", Some(&cookie), &[("parent_id", "")])
2938+ .await;
2939+ let location = answer
2940+ .location
2941+ .clone()
2942+ .expect("second quick create redirects nowhere");
2943+ let edit2 = location
2650 .split("edit=")2944 .split("edit=")
2651 .nth(1)2945 .nth(1)
2652 .expect("no edit id")2946 .expect("no edit id")
2653 .split('&')2947 .split('&')
2654 .next()2948 .next()
2655 .unwrap();2949 .unwrap();
2656- assert_eq!(folder_id(&app, &me, None, "New folder 2").await, edit);2950+ assert_ne!(edit, edit2, "second quick create reused the row");
2951+ let root = app.store.list_children(&me, None).await.unwrap();
2952+ assert_eq!(
2953+ root.folders
2954+ .iter()
2955+ .filter(|folder| folder.name == "New folder")
2956+ .count(),
2957+ 2,
2958+ "second quick create did not repeat the generic name"
2959+ );
2657 2960
2658 // A typed name keeps the old answer: back to the page, no edit mode.2961 // A typed name keeps the old answer: back to the page, no edit mode.
2659 let answer = app2962 let answer = app
2660- .post("/api/folder/create", Some(&cookie), &[("parent_id", ""), ("name", "typed")])2963+ .post(
2964+ "/api/folder/create",
2965+ Some(&cookie),
2966+ &[("parent_id", ""), ("name", "typed")],
2967+ )
2661 .await;2968 .await;
2662- assert!(answer.accepted(), "typed create refused: {:?}", answer.location);
2663 assert!(2969 assert!(
2664- answer.location.as_deref().is_some_and(|location| !location.contains("edit=")),2970+ answer.accepted(),
2971+ "typed create refused: {:?}",
2972+ answer.location
2973+ );
2974+ assert!(
2975+ answer
2976+ .location
2977+ .as_deref()
2978+ .is_some_and(|location| !location.contains("edit=")),
2665 "typed create enters edit mode: {:?}",2979 "typed create enters edit mode: {:?}",
2666 answer.location2980 answer.location
2667 );2981 );
2668 folder_id(&app, &me, None, "typed").await;2982 folder_id(&app, &me, None, "typed").await;
2669 2983
2670- // A refused typed create surfaces on the page line, once.2984+ // A typed duplicate is accepted too — folders share names now.
2671 let answer = app2985 let answer = app
2672- .post("/api/folder/create", Some(&cookie), &[("parent_id", ""), ("name", "typed")])2986+ .post(
2987+ "/api/folder/create",
2988+ Some(&cookie),
2989+ &[("parent_id", ""), ("name", "typed")],
2990+ )
2673 .await;2991 .await;
2674- assert_eq!(answer.status, StatusCode::SEE_OTHER);2992+ assert!(
2675- assert!(answer.body.contains("NameTaken"), "dupe was not refused: {}", answer.body);2993+ answer.accepted(),
2676- let page = app.get("/drive?refusal=name-taken&on=create", Some(&cookie)).await;2994+ "typed dupe refused: {:?}",
2677- assert_eq!(page.status, StatusCode::OK);2995+ answer.location
2996+ );
2997+ let root = app.store.list_children(&me, None).await.unwrap();
2678 assert_eq!(2998 assert_eq!(
2679- page.text().matches("<p class=\"field-error\"").count(),2999+ root.folders
2680- 1,3000+ .iter()
2681- "create refusal shows twice — or nowhere"3001+ .filter(|folder| folder.name == "typed")
3002+ .count(),
3003+ 2,
3004+ "typed dupe did not land beside the first"
2682 );3005 );
2683 }3006 }
2684 3007
2685 #[tokio::test]3008 #[tokio::test]
2686 async fn drive_edit_row_renders_the_rename_form() {3009 async fn drive_edit_row_renders_the_rename_form() {
2687 let app = TestApp::build().await;3010 let app = TestApp::build().await;
2688- let cookie = app.sign_in("sub-editrow", "editrow@in.test", "EditRow").await;3011+ let cookie = app
3012+ .sign_in("sub-editrow", "editrow@in.test", "EditRow")
3013+ .await;
2689 let me = owner_of(&app, "sub-editrow").await;3014 let me = owner_of(&app, "sub-editrow").await;
2690 3015
2691 let answer = app3016 let answer = app
2692- .post("/api/folder/create", Some(&cookie), &[("parent_id", ""), ("name", "plans")])3017+ .post(
3018+ "/api/folder/create",
3019+ Some(&cookie),
3020+ &[("parent_id", ""), ("name", "plans")],
3021+ )
2693 .await;3022 .await;
2694- assert!(answer.accepted(), "setup create refused: {:?}", answer.location);3023+ assert!(
3024+ answer.accepted(),
3025+ "setup create refused: {:?}",
3026+ answer.location
3027+ );
2695 let id = folder_id(&app, &me, None, "plans").await;3028 let id = folder_id(&app, &me, None, "plans").await;
2696 3029
2697 // Plain view: the row is a link with an edit entry, no rename input.3030 // Plain view: the row is a link with an edit entry, no rename input.
2698 let page = app.get("/drive", Some(&cookie)).await;3031 let page = app.get("/drive", Some(&cookie)).await;
2699 let body = page.text();3032 let body = page.text();
2700- assert!(body.contains(&format!("/drive?folder={id}")), "row links nowhere");3033+ assert!(
2701- assert!(body.contains(&format!("/drive?edit={id}")), "row has no edit entry");3034+ body.contains(&format!("/drive?folder={id}")),
3035+ "row links nowhere"
3036+ );
3037+ assert!(
3038+ body.contains(&format!("/drive?edit={id}")),
3039+ "row has no edit entry"
3040+ );
2702 3041
2703 // Edit view: that row — and only that row — is the rename form, pre-filled.3042 // Edit view: that row — and only that row — is the rename form, pre-filled.
2704 let page = app.get(&format!("/drive?edit={id}"), Some(&cookie)).await;3043 let page = app.get(&format!("/drive?edit={id}"), Some(&cookie)).await;
@@ -2708,8 +3047,14 @@ async fn drive_edit_row_renders_the_rename_form() {
2708 body.contains("action=\"/api/folder/rename\""),3047 body.contains("action=\"/api/folder/rename\""),
2709 "edit view renders no rename form"3048 "edit view renders no rename form"
2710 );3049 );
2711- assert!(body.contains("data-edit-focus"), "rename input carries no focus hook");3050+ assert!(
2712- assert!(body.contains("value=\"plans\""), "rename input is not pre-filled");3051+ body.contains("data-edit-focus"),
3052+ "rename input carries no focus hook"
3053+ );
3054+ assert!(
3055+ body.contains("value=\"plans\""),
3056+ "rename input is not pre-filled"
3057+ );
2713 assert!(body.contains("__inEditFocus"), "no edit focus script");3058 assert!(body.contains("__inEditFocus"), "no edit focus script");
2714 }3059 }
2715 3060
@@ -2721,15 +3066,27 @@ async fn drive_lists_folders_before_files_in_one_panel() {
2721 // The file's name sorts first alphabetically, so order proves folders lead.3066 // The file's name sorts first alphabetically, so order proves folders lead.
2722 let file_id = file_id(&app, &owner, "aaa file.txt", b"a").await;3067 let file_id = file_id(&app, &owner, "aaa file.txt", b"a").await;
2723 let answer = app3068 let answer = app
2724- .post("/api/folder/create", Some(&cookie), &[("parent_id", ""), ("name", "mmm folder")])3069+ .post(
3070+ "/api/folder/create",
3071+ Some(&cookie),
3072+ &[("parent_id", ""), ("name", "mmm folder")],
3073+ )
2725 .await;3074 .await;
2726- assert!(answer.accepted(), "setup create refused: {:?}", answer.location);3075+ assert!(
3076+ answer.accepted(),
3077+ "setup create refused: {:?}",
3078+ answer.location
3079+ );
2727 3080
2728 let page = app.get("/drive", Some(&cookie)).await;3081 let page = app.get("/drive", Some(&cookie)).await;
2729 assert_eq!(page.status, StatusCode::OK, "{}", page.text());3082 assert_eq!(page.status, StatusCode::OK, "{}", page.text());
2730 let body = page.text();3083 let body = page.text();
2731 // One panel, no heads or chips — just the merged list.3084 // One panel, no heads or chips — just the merged list.
2732- assert_eq!(body.matches("<section class=\"panel\">").count(), 1, "{body}");3085+ assert_eq!(
3086+ body.matches("<section class=\"panel\">").count(),
3087+ 1,
3088+ "{body}"
3089+ );
2733 assert!(!body.contains("panel-head"), "{body}");3090 assert!(!body.contains("panel-head"), "{body}");
2734 assert!(!body.contains("class=\"chip\""), "{body}");3091 assert!(!body.contains("class=\"chip\""), "{body}");
2735 assert!(!body.contains(">Folders</h2>"), "{body}");3092 assert!(!body.contains(">Folders</h2>"), "{body}");
@@ -2766,10 +3123,16 @@ async fn an_empty_folder_says_how_to_fill_it() {
2766 let body = page.text();3123 let body = page.text();
2767 // The single empty state names both ways to fill the folder.3124 // The single empty state names both ways to fill the folder.
2768 assert!(3125 assert!(
2769- body.contains("This folder is empty. Press + to create or upload, or drop files on this page."),3126+ body.contains(
3127+ "This folder is empty. Press + to create or upload, or drop files on this page."
3128+ ),
2770 "no empty-state hint: {body}"3129 "no empty-state hint: {body}"
2771 );3130 );
2772- assert_eq!(body.matches("<section class=\"panel\">").count(), 1, "{body}");3131+ assert_eq!(
3132+ body.matches("<section class=\"panel\">").count(),
3133+ 1,
3134+ "{body}"
3135+ );
2773 assert!(!body.contains("panel-head"), "{body}");3136 assert!(!body.contains("panel-head"), "{body}");
2774 // And the upload control plus the drop handler the hint promises are on the page.3137 // And the upload control plus the drop handler the hint promises are on the page.
2775 assert!(body.contains("id=\"upload-form\""), "{body}");3138 assert!(body.contains("id=\"upload-form\""), "{body}");
style/main.scssmodified+245 -0
@@ -4354,3 +4354,248 @@ input[type="radio"] {
4354 4354
4355 .auth-stage { padding: 0 16px 24px; }4355 .auth-stage { padding: 0 16px 24px; }
4356 }4356 }
4357+
4358+// -- file viewer page ------------------------------------------------------------
4359+// GET /view/{id}: the preview on its own page. The media elements reuse the
4360+// in-app viewer classes (.viewer-media, .viewer-pdf); the stage centers
4361+// them, the audio element takes a readable width, and the text frame wears
4362+// the pdf box's shape.
4363+.viewer-stage {
4364+ display: flex;
4365+ justify-content: center;
4366+ margin: 16px 0;
4367+}
4368+
4369+.viewer-audio { width: min(480px, 100%); }
4370+
4371+.viewer-text {
4372+ width: 100%;
4373+ height: 70vh;
4374+ border: 1px solid var(--border);
4375+ border-radius: var(--radius-md);
4376+ background: var(--surface);
4377+}
4378+
4379+.viewer-fallback {
4380+ display: flex;
4381+ flex-direction: column;
4382+ align-items: center;
4383+ gap: 8px;
4384+ padding: 24px 0;
4385+}
4386+
4387+// -- file chips ------------------------------------------------------------------
4388+// entry_chip's mime-class marks: one glyph each, decorative beside the name.
4389+// The shared rule keeps every glyph chip the same footprint next to a
4390+// thumbnail; the tints reuse the semantic tokens, quiet enough to sit in a
4391+// row.
4392+.file-chip-image,
4393+.file-chip-video,
4394+.file-chip-audio,
4395+.file-chip-pdf,
4396+.file-chip-text,
4397+.file-chip-archive,
4398+.file-chip-generic {
4399+ justify-content: center;
4400+ min-width: 40px;
4401+ font-size: 13px;
4402+}
4403+
4404+.file-chip-video { color: var(--accent-ink); }
4405+.file-chip-audio { color: var(--violet-ink); }
4406+.file-chip-pdf { color: var(--danger); }
4407+.file-chip-text { color: var(--positive-ink); }
4408+.file-chip-archive { color: var(--warn-ink); }
4409+
4410+// -- trash/share unified rows (TrashShareBuild) --------------------------------------
4411+// The folder chip beside trashed, shared and publicly-shared names: the same
4412+// footprint as entry_chip's mime glyphs, the accent tint because folders are
4413+// the rows' way in.
4414+.file-chip-folder {
4415+ justify-content: center;
4416+ min-width: 40px;
4417+ font-size: 13px;
4418+ color: var(--accent-ink);
4419+}
4420+
4421+// -- drive wave-2 (DriveBuild) -------------------------------------------------------
4422+// Options menus, rename rows, progress rows, the drop overlay and the
4423+// persistent notice stack. One contiguous section; the house panel, chip and
4424+// quiet rules above do the rest.
4425+
4426+// The row's Options menu wears the house user-menu panel; the summary hides
4427+// its disclosure marker the way the drive-add trigger does.
4428+.entry-options-trigger {
4429+ list-style: none;
4430+ white-space: nowrap;
4431+
4432+ &::marker, &::-webkit-details-marker { display: none; }
4433+}
4434+
4435+// The move form inside the menu: picker and submit side by side, padded like
4436+// the link items around them.
4437+.user-menu-item-move {
4438+ display: flex;
4439+ align-items: center;
4440+ gap: 8px;
4441+ padding: 4px 14px;
4442+
4443+ .field-input {
4444+ flex: 1;
4445+ min-width: 0;
4446+ }
4447+}
4448+
4449+// The rename row: the form itself fills the row so the input takes the
4450+// middle and Rename/Cancel sit at the right edge, exactly where the Options
4451+// trigger sits in the plain row.
4452+.dep-edit-form {
4453+ display: flex;
4454+ flex: 1;
4455+ align-items: center;
4456+ gap: 10px;
4457+ min-width: 0;
4458+
4459+ .field-input {
4460+ flex: 1;
4461+ min-width: 0;
4462+ }
4463+}
4464+
4465+// Row details keep the chip-note voice: muted, small, single line. The
4466+// dep-note never wraps mid-row; the name's ellipsis absorbs the pressure.
4467+.dep-row > .dep-note {
4468+ white-space: nowrap;
4469+}
4470+
4471+// Upload progress rows under the filterbar: name, bar, percent. The track is
4472+// the house upload-progress rule freed of its upload-box geometry (it was
4473+// absolutely positioned into a box the drive form never renders) — here it
4474+// flexes beside the name it belongs to.
4475+.upload-progress-list {
4476+ display: flex;
4477+ flex-direction: column;
4478+ gap: 8px;
4479+ margin-top: 10px;
4480+
4481+ &:empty { display: none; }
4482+}
4483+
4484+.upload-progress-row {
4485+ display: flex;
4486+ align-items: center;
4487+ gap: 10px;
4488+}
4489+
4490+.upload-progress-name {
4491+ flex: 1;
4492+ min-width: 0;
4493+ overflow: hidden;
4494+ text-overflow: ellipsis;
4495+ white-space: nowrap;
4496+ font-size: 12px;
4497+ color: var(--muted);
4498+}
4499+
4500+.upload-progress-list .upload-progress {
4501+ position: relative;
4502+ flex: 1;
4503+ left: auto;
4504+ right: auto;
4505+ bottom: auto;
4506+ min-width: 80px;
4507+ height: 4px;
4508+}
4509+
4510+.upload-progress-pct {
4511+ flex: none;
4512+ font-family: var(--font-mono);
4513+ font-size: 11px;
4514+ color: var(--muted-soft);
4515+}
4516+
4517+// The full-page drop affordance: a fixed veil with the invitation centred,
4518+// pointer-transparent so it never blocks the drop it announces.
4519+.drop-overlay {
4520+ position: fixed;
4521+ inset: 0;
4522+ z-index: 90;
4523+ display: flex;
4524+ align-items: center;
4525+ justify-content: center;
4526+ background: var(--accent-tint, rgba(70, 85, 123, 0.12));
4527+ border: 2px dashed var(--accent);
4528+ opacity: 0;
4529+ visibility: hidden;
4530+ pointer-events: none;
4531+ transition: opacity var(--dur-fast) var(--ease), visibility var(--dur-fast) var(--ease);
4532+}
4533+
4534+.drop-overlay-show {
4535+ opacity: 1;
4536+ visibility: visible;
4537+}
4538+
4539+.drop-overlay-text {
4540+ padding: 12px 20px;
4541+ background: var(--surface);
4542+ border: 1px solid var(--border-strong);
4543+ border-radius: var(--radius-lg);
4544+ box-shadow: var(--shadow-2);
4545+ font-size: 14px;
4546+ color: var(--ink);
4547+}
4548+
4549+// The persistent notice stack: fixed corner cards for upload errors and
4550+// completions, dismissed only by their ✕ — never by a swap, never by time.
4551+.in-status-stack {
4552+ position: fixed;
4553+ right: 16px;
4554+ bottom: 16px;
4555+ z-index: 100;
4556+ display: flex;
4557+ flex-direction: column;
4558+ gap: 8px;
4559+ max-width: min(360px, 90vw);
4560+
4561+ &:empty { display: none; }
4562+}
4563+
4564+.in-status-card {
4565+ display: flex;
4566+ align-items: center;
4567+ gap: 10px;
4568+ padding: 10px 12px;
4569+ background: var(--surface);
4570+ border: 1px solid var(--border-strong);
4571+ border-radius: var(--radius-md);
4572+ box-shadow: var(--shadow-2);
4573+ font-size: 13px;
4574+ color: var(--ink);
4575+}
4576+
4577+.in-status-error {
4578+ border-color: var(--danger-border);
4579+}
4580+
4581+.in-status-text {
4582+ flex: 1;
4583+ min-width: 0;
4584+}
4585+
4586+.in-status-dismiss {
4587+ flex: none;
4588+ display: inline-flex;
4589+ align-items: center;
4590+ justify-content: center;
4591+ width: 24px;
4592+ height: 24px;
4593+ padding: 0;
4594+ border: none;
4595+ border-radius: var(--radius-sm);
4596+ background: transparent;
4597+ color: var(--muted-soft);
4598+ cursor: pointer;
4599+
4600+ &:hover { color: var(--danger); }
4601+}