Chunked upload API, drive.js upload queue, hourly sweeper
Browse files at this commit6e0d0ad66b8e91c8569b8ec11867cc613bf9eed2Parent: a693d7d- feat
- chunked upload API, drive.js upload queue, hourly sweeper
- routes aligned with architecture
24 changed files +2054 -302
- crates/in-core/src/staging.rs +95 -1
- crates/in-core/src/store/files.rs +59 -48
- crates/in-core/src/store/mod.rs +1 -0
- crates/in-core/src/store/uploads.rs +306 -0
- crates/in-web/assets/drive.js +421 -0
- crates/in-web/assets/nav.js +4 -0
- crates/in-web/build.rs +2 -1
- crates/in-web/src/api/mod.rs +4 -0
- crates/in-web/src/api/upload.rs +717 -0
- crates/in-web/src/assets.rs +10 -0
- crates/in-web/src/auth.rs +51 -0
- crates/in-web/src/boot.rs +2 -0
- crates/in-web/src/i18n/drive.rs +24 -12
- crates/in-web/src/main.rs +2 -0
- crates/in-web/src/pages/drive.rs +89 -40
- crates/in-web/src/pages/files.rs +35 -155
- crates/in-web/src/pages/home.rs +20 -35
- crates/in-web/src/pages/mod.rs +1 -0
- crates/in-web/src/pages/trash.rs +4 -2
- crates/in-web/src/pages/view.rs +65 -0
- crates/in-web/src/sweeper.rs +52 -0
- crates/in-web/src/views/drive.rs +5 -5
- crates/in-web/src/views/mod.rs +8 -3
- style/_components.scss +77 -0
crates/in-core/src/staging.rsmodified+95 -1
| @@ -3,6 +3,9 @@ | |||
| 3 | //! | 3 | //! |
| 4 | //! The finished file is handed to a blob store with `BlobStore::put_file`, which moves it into place. | 4 | //! The finished file is handed to a blob store with `BlobStore::put_file`, which moves it into place. |
| 5 | //! A file that is never finished stays in `data_dir/tmp` until the sweeper removes it. | 5 | //! A file that is never finished stays in `data_dir/tmp` until the sweeper removes it. |
| 6 | +//! | ||
| 7 | +//! Chunks of a resumable upload are staged under `data_dir/uploads/<upload id>/<index>` by the same type, | ||
| 8 | +//! and the chunk math (sizes, counts, validated directories) lives here too. | ||
| 6 | 9 | ||
| 7 | use std::fmt::Display; | 10 | use std::fmt::Display; |
| 8 | use std::path::{Path, PathBuf}; | 11 | use std::path::{Path, PathBuf}; |
| @@ -14,9 +17,62 @@ use tokio::io::AsyncWriteExt; | |||
| 14 | 17 | ||
| 15 | use crate::error::{Error, Result}; | 18 | use crate::error::{Error, Result}; |
| 16 | 19 | ||
| 17 | -/// Name of the staging directory inside the data directory. | 20 | +/// Name of the staging directory inside the data directory, for whole-file intake. |
| 18 | pub const TMP_DIR: &str = "tmp"; | 21 | pub const TMP_DIR: &str = "tmp"; |
| 19 | 22 | ||
| 23 | +/// Name of the directory inside the data directory that holds the chunks of resumable uploads. Each | ||
| 24 | +/// upload has `uploads/<upload id>/` with one file per chunk, named by its index. | ||
| 25 | +pub const UPLOADS_DIR: &str = "uploads"; | ||
| 26 | + | ||
| 27 | +/// Size of one chunk of a resumable upload: 8 MiB. Every chunk but the last is exactly this long. | ||
| 28 | +pub const CHUNK_BYTES: u64 = 8 * 1024 * 1024; | ||
| 29 | + | ||
| 30 | +/// Number of chunks a file of `size` bytes is split into. A zero-byte file has none. | ||
| 31 | +pub fn chunk_count(size: u64, chunk: u64) -> u64 { | ||
| 32 | + size.div_ceil(chunk.max(1)) | ||
| 33 | +} | ||
| 34 | + | ||
| 35 | +/// The exact length chunk `index` must have, or `None` when the index is past the last chunk. Every | ||
| 36 | +/// chunk but the last is `chunk` bytes; the last is the remainder, which is `chunk` when the size divides | ||
| 37 | +/// evenly. | ||
| 38 | +pub fn expected_chunk_len(size: u64, chunk: u64, index: u64) -> Option<u64> { | ||
| 39 | + let count = chunk_count(size, chunk); | ||
| 40 | + if index >= count { | ||
| 41 | + return None; | ||
| 42 | + } | ||
| 43 | + if index + 1 == count { | ||
| 44 | + Some(size - index * chunk) | ||
| 45 | + } else { | ||
| 46 | + Some(chunk) | ||
| 47 | + } | ||
| 48 | +} | ||
| 49 | + | ||
| 50 | +/// The staging directory of an upload: `data_dir/uploads/<id>`. The id must be a lower-case ULID, so | ||
| 51 | +/// this path can never leave the uploads directory. Anything else is `Invalid("bad_id")`. | ||
| 52 | +pub fn upload_dir(data_dir: &Path, id: &str) -> Result<PathBuf> { | ||
| 53 | + let well_formed = ulid::Ulid::from_string(id).is_ok() && id == id.to_ascii_lowercase(); | ||
| 54 | + if !well_formed { | ||
| 55 | + return Err(Error::Invalid("bad_id".into())); | ||
| 56 | + } | ||
| 57 | + Ok(data_dir.join(UPLOADS_DIR).join(id)) | ||
| 58 | +} | ||
| 59 | + | ||
| 60 | +/// The file that holds chunk `index` inside an upload's staging directory. | ||
| 61 | +pub fn chunk_path(dir: &Path, index: u64) -> PathBuf { | ||
| 62 | + dir.join(index.to_string()) | ||
| 63 | +} | ||
| 64 | + | ||
| 65 | +/// Removes an upload's staging directory and everything in it. A missing directory is not an error. | ||
| 66 | +/// The path is built by [`upload_dir`], so only a validated upload id is ever removed. | ||
| 67 | +pub async fn remove_upload_dir(data_dir: &Path, id: &str) -> Result<()> { | ||
| 68 | + let dir = upload_dir(data_dir, id)?; | ||
| 69 | + match tokio::fs::remove_dir_all(&dir).await { | ||
| 70 | + Ok(()) => Ok(()), | ||
| 71 | + Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(()), | ||
| 72 | + Err(e) => Err(e.into()), | ||
| 73 | + } | ||
| 74 | +} | ||
| 75 | + | ||
| 20 | /// A file being written. Create it with [`StagedFile::create`], feed it with [`StagedFile::write`] or | 76 | /// A file being written. Create it with [`StagedFile::create`], feed it with [`StagedFile::write`] or |
| 21 | /// [`StagedFile::consume`], then call [`StagedFile::finish`]. | 77 | /// [`StagedFile::consume`], then call [`StagedFile::finish`]. |
| 22 | pub struct StagedFile { | 78 | pub struct StagedFile { |
| @@ -48,6 +104,13 @@ impl StagedFile { | |||
| 48 | .mode(0o700) | 104 | .mode(0o700) |
| 49 | .create(&dir) | 105 | .create(&dir) |
| 50 | .await?; | 106 | .await?; |
| 107 | + Self::create_in(&dir, max_size).await | ||
| 108 | + } | ||
| 109 | + | ||
| 110 | + /// Starts a new staged file inside `dir`, which must exist. The file is created with mode 0600 and | ||
| 111 | + /// a fresh ULID name, so it never replaces anything. The directory is not created: a caller that | ||
| 112 | + /// writes into a removed directory fails instead of recreating it. | ||
| 113 | + pub async fn create_in(dir: &Path, max_size: u64) -> Result<Self> { | ||
| 51 | let path = dir.join(ulid::Ulid::generate().to_string()); | 114 | let path = dir.join(ulid::Ulid::generate().to_string()); |
| 52 | let file = tokio::fs::OpenOptions::new() | 115 | let file = tokio::fs::OpenOptions::new() |
| 53 | .write(true) | 116 | .write(true) |
| @@ -124,6 +187,37 @@ mod tests { | |||
| 124 | use super::*; | 187 | use super::*; |
| 125 | use futures_util::stream; | 188 | use futures_util::stream; |
| 126 | 189 | ||
| 190 | + #[test] | ||
| 191 | + fn chunk_lengths_are_full_then_the_remainder() { | ||
| 192 | + // 10 bytes in 4-byte chunks: 4, 4, 2. Index 3 is past the end. | ||
| 193 | + assert_eq!(chunk_count(10, 4), 3); | ||
| 194 | + assert_eq!(expected_chunk_len(10, 4, 0), Some(4)); | ||
| 195 | + assert_eq!(expected_chunk_len(10, 4, 2), Some(2)); | ||
| 196 | + assert_eq!(expected_chunk_len(10, 4, 3), None); | ||
| 197 | + // An exact multiple has no short last chunk; an empty file has no chunks at all. | ||
| 198 | + assert_eq!(expected_chunk_len(8, 4, 1), Some(4)); | ||
| 199 | + assert_eq!(expected_chunk_len(0, 4, 0), None); | ||
| 200 | + } | ||
| 201 | + | ||
| 202 | + #[test] | ||
| 203 | + fn upload_dirs_only_take_lower_case_ulids() { | ||
| 204 | + let data = Path::new("/data"); | ||
| 205 | + let good = ulid::Ulid::generate().to_string().to_ascii_lowercase(); | ||
| 206 | + assert!( | ||
| 207 | + upload_dir(data, &good) | ||
| 208 | + .unwrap() | ||
| 209 | + .starts_with("/data/uploads") | ||
| 210 | + ); | ||
| 211 | + for bad in [ | ||
| 212 | + "../x", | ||
| 213 | + "", | ||
| 214 | + "01h/../../etc", | ||
| 215 | + &ulid::Ulid::generate().to_string(), | ||
| 216 | + ] { | ||
| 217 | + assert!(upload_dir(data, bad).is_err(), "{bad:?} should be refused"); | ||
| 218 | + } | ||
| 219 | + } | ||
| 220 | + | ||
| 127 | #[tokio::test] | 221 | #[tokio::test] |
| 128 | async fn streams_hash_and_size_and_refuses_oversize() { | 222 | async fn streams_hash_and_size_and_refuses_oversize() { |
| 129 | let dir = tempfile::tempdir().unwrap(); | 223 | let dir = tempfile::tempdir().unwrap(); |
crates/in-core/src/store/files.rsmodified+59 -48
| @@ -144,6 +144,64 @@ fn like_escape(q: &str) -> String { | |||
| 144 | out | 144 | out |
| 145 | } | 145 | } |
| 146 | 146 | ||
| 147 | +/// Inserts a file row inside the caller's transaction: the folder must be a live folder of the owner, the | ||
| 148 | +/// size must fit the headroom left after `new.staged_claims`, the name gets the first free postfix, and | ||
| 149 | +/// `used_bytes` is raised by the size. Shared by [`Store::insert_file`] and [`Store::finish_upload`], so | ||
| 150 | +/// the quota rule is written once. | ||
| 151 | +pub(crate) async fn insert_file_in(conn: &Connection, new: NewFile) -> Result<File> { | ||
| 152 | + let base = names::display_name(&new.name); | ||
| 153 | + let blob_key = files_blob_key(&new.id); | ||
| 154 | + let now = now_stamp(); | ||
| 155 | + if let Some(f) = new.folder.as_deref() { | ||
| 156 | + live_folder(conn, &new.owner, f).await?; | ||
| 157 | + } | ||
| 158 | + let (quota, used) = fetch_opt( | ||
| 159 | + conn, | ||
| 160 | + "SELECT quota_bytes, used_bytes FROM members WHERE sub = ?1", | ||
| 161 | + (new.owner.clone(),), | ||
| 162 | + |row| Ok((col_int(row, 0)?, col_int(row, 1)?)), | ||
| 163 | + ) | ||
| 164 | + .await? | ||
| 165 | + .ok_or(Error::NotFound)?; | ||
| 166 | + let room = quota::headroom(quota, used, new.staged_claims.max(0)); | ||
| 167 | + if !quota::fits(new.size, room) { | ||
| 168 | + return Err(Error::Conflict("quota_exceeded".into())); | ||
| 169 | + } | ||
| 170 | + let name = first_free_name( | ||
| 171 | + conn, | ||
| 172 | + "files", | ||
| 173 | + &new.owner, | ||
| 174 | + new.folder.as_deref(), | ||
| 175 | + &base, | ||
| 176 | + true, | ||
| 177 | + ) | ||
| 178 | + .await?; | ||
| 179 | + conn.execute( | ||
| 180 | + "INSERT INTO files (id, owner, folder_id, name, mime, size, sha256, blob_key, \ | ||
| 181 | + created_at, updated_at) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?9)", | ||
| 182 | + ( | ||
| 183 | + new.id.clone(), | ||
| 184 | + new.owner.clone(), | ||
| 185 | + new.folder.clone(), | ||
| 186 | + name, | ||
| 187 | + new.mime.clone(), | ||
| 188 | + new.size, | ||
| 189 | + new.sha256.clone(), | ||
| 190 | + blob_key, | ||
| 191 | + now.clone(), | ||
| 192 | + ), | ||
| 193 | + ) | ||
| 194 | + .await | ||
| 195 | + .map_err(|e| insert_err(e, "name_taken"))?; | ||
| 196 | + conn.execute( | ||
| 197 | + "UPDATE members SET used_bytes = used_bytes + ?2 WHERE sub = ?1", | ||
| 198 | + (new.owner.clone(), new.size), | ||
| 199 | + ) | ||
| 200 | + .await | ||
| 201 | + .map_err(db_err)?; | ||
| 202 | + file_by_id(conn, &new.id).await?.ok_or(Error::NotFound) | ||
| 203 | +} | ||
| 204 | + | ||
| 147 | impl Store { | 205 | impl Store { |
| 148 | /// The file with this id, whoever owns it. Authorise the result before showing it. | 206 | /// The file with this id, whoever owns it. Authorise the result before showing it. |
| 149 | pub async fn file(&self, id: &str) -> Result<Option<File>> { | 207 | pub async fn file(&self, id: &str) -> Result<Option<File>> { |
| @@ -158,56 +216,9 @@ impl Store { | |||
| 158 | if new.size < 0 { | 216 | if new.size < 0 { |
| 159 | return Err(Error::Invalid("size_negative".into())); | 217 | return Err(Error::Invalid("size_negative".into())); |
| 160 | } | 218 | } |
| 161 | - let base = names::display_name(&new.name); | ||
| 162 | - let blob_key = files_blob_key(&new.id); | ||
| 163 | - let now = now_stamp(); | ||
| 164 | let conn = self.inner.conn.lock().await; | 219 | let conn = self.inner.conn.lock().await; |
| 165 | let tx = conn.unchecked_transaction().await.map_err(db_err)?; | 220 | let tx = conn.unchecked_transaction().await.map_err(db_err)?; |
| 166 | - let outcome: Result<File> = async { | 221 | + let outcome = insert_file_in(&tx, new).await; |
| 167 | - if let Some(f) = new.folder.as_deref() { | ||
| 168 | - live_folder(&tx, &new.owner, f).await?; | ||
| 169 | - } | ||
| 170 | - let (quota, used) = fetch_opt( | ||
| 171 | - &tx, | ||
| 172 | - "SELECT quota_bytes, used_bytes FROM members WHERE sub = ?1", | ||
| 173 | - (new.owner.clone(),), | ||
| 174 | - |row| Ok((col_int(row, 0)?, col_int(row, 1)?)), | ||
| 175 | - ) | ||
| 176 | - .await? | ||
| 177 | - .ok_or(Error::NotFound)?; | ||
| 178 | - let room = quota::headroom(quota, used, new.staged_claims.max(0)); | ||
| 179 | - if !quota::fits(new.size, room) { | ||
| 180 | - return Err(Error::Conflict("quota_exceeded".into())); | ||
| 181 | - } | ||
| 182 | - let name = | ||
| 183 | - first_free_name(&tx, "files", &new.owner, new.folder.as_deref(), &base, true) | ||
| 184 | - .await?; | ||
| 185 | - tx.execute( | ||
| 186 | - "INSERT INTO files (id, owner, folder_id, name, mime, size, sha256, blob_key, \ | ||
| 187 | - created_at, updated_at) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?9)", | ||
| 188 | - ( | ||
| 189 | - new.id.clone(), | ||
| 190 | - new.owner.clone(), | ||
| 191 | - new.folder.clone(), | ||
| 192 | - name, | ||
| 193 | - new.mime.clone(), | ||
| 194 | - new.size, | ||
| 195 | - new.sha256.clone(), | ||
| 196 | - blob_key, | ||
| 197 | - now.clone(), | ||
| 198 | - ), | ||
| 199 | - ) | ||
| 200 | - .await | ||
| 201 | - .map_err(|e| insert_err(e, "name_taken"))?; | ||
| 202 | - tx.execute( | ||
| 203 | - "UPDATE members SET used_bytes = used_bytes + ?2 WHERE sub = ?1", | ||
| 204 | - (new.owner.clone(), new.size), | ||
| 205 | - ) | ||
| 206 | - .await | ||
| 207 | - .map_err(db_err)?; | ||
| 208 | - file_by_id(&tx, &new.id).await?.ok_or(Error::NotFound) | ||
| 209 | - } | ||
| 210 | - .await; | ||
| 211 | finish(tx, outcome).await | 222 | finish(tx, outcome).await |
| 212 | } | 223 | } |
| 213 | 224 | ||
crates/in-core/src/store/mod.rsmodified+1 -0
| @@ -12,6 +12,7 @@ pub mod sessions; | |||
| 12 | pub mod settings; | 12 | pub mod settings; |
| 13 | pub mod snapshot; | 13 | pub mod snapshot; |
| 14 | pub mod trash; | 14 | pub mod trash; |
| 15 | +pub mod uploads; | ||
| 15 | 16 | ||
| 16 | use std::path::Path; | 17 | use std::path::Path; |
| 17 | use std::sync::Arc; | 18 | use std::sync::Arc; |
crates/in-core/src/store/uploads.rsadded+306 -0
| @@ -0,0 +1,306 @@ | |||
| 1 | +//! Resumable uploads: the rows that track an upload from its first request to its finish, and the | ||
| 2 | +//! transactions that decide its fate. | ||
| 3 | +//! | ||
| 4 | +//! The quota is promised, not spent, while an upload is open. Creating an upload checks the headroom | ||
| 5 | +//! inside the write transaction, with the declared sizes of the owner's other live uploads counted | ||
| 6 | +//! against it, so two creates that would together exceed the quota cannot both succeed. Finishing | ||
| 7 | +//! checks again, in the transaction that inserts the file row and marks the upload `done`. Bytes never | ||
| 8 | +//! change here: the chunks live on disk (`staging.rs`), and the blob is put before the finish commits. | ||
| 9 | + | ||
| 10 | +use turso::{Connection, Row}; | ||
| 11 | + | ||
| 12 | +use crate::error::{Error, Result}; | ||
| 13 | +use crate::quota; | ||
| 14 | +use crate::store::files::{File, NewFile, insert_file_in}; | ||
| 15 | +use crate::store::folders::live_folder; | ||
| 16 | +use crate::store::{Store, col_int, col_opt_text, col_text, db_err, fetch_all, fetch_opt, finish}; | ||
| 17 | +use crate::time::now_stamp; | ||
| 18 | + | ||
| 19 | +/// Column list for [`map_upload`]. Keep the two in step. | ||
| 20 | +pub const UPLOAD_COLS: &str = | ||
| 21 | + "id, owner, folder_id, name, size, chunk_size, state, file_id, created_at, expires_at"; | ||
| 22 | + | ||
| 23 | +/// One row of the `uploads` table. | ||
| 24 | +#[derive(Debug, Clone, PartialEq, Eq)] | ||
| 25 | +pub struct Upload { | ||
| 26 | + /// Upload id (a lower-case ULID). It names the staging directory. | ||
| 27 | + pub id: String, | ||
| 28 | + /// The person who started the upload. | ||
| 29 | + pub owner: String, | ||
| 30 | + /// Destination folder, or `None` for the top level. | ||
| 31 | + pub folder_id: Option<String>, | ||
| 32 | + /// The cleaned file name the finished file gets (a postfix is added at finish if it is taken). | ||
| 33 | + pub name: String, | ||
| 34 | + /// Declared size in bytes. Every chunk is checked against it. | ||
| 35 | + pub size: i64, | ||
| 36 | + /// Chunk size in bytes the upload was started with. | ||
| 37 | + pub chunk_size: i64, | ||
| 38 | + /// `active`, `done` or `aborted`. | ||
| 39 | + pub state: String, | ||
| 40 | + /// The file the upload became, once it is `done`. | ||
| 41 | + pub file_id: Option<String>, | ||
| 42 | + /// When the upload was started. | ||
| 43 | + pub created_at: String, | ||
| 44 | + /// When the upload expires: 24 hours after its last chunk. | ||
| 45 | + pub expires_at: String, | ||
| 46 | +} | ||
| 47 | + | ||
| 48 | +impl Upload { | ||
| 49 | + /// Whether the upload may still take chunks or finish at `now`: active and not yet expired. | ||
| 50 | + pub fn is_open(&self, now: &str) -> bool { | ||
| 51 | + self.state == "active" && self.expires_at.as_str() > now | ||
| 52 | + } | ||
| 53 | +} | ||
| 54 | + | ||
| 55 | +/// What a new upload needs. The name is already cleaned by the caller. | ||
| 56 | +#[derive(Debug, Clone, PartialEq, Eq)] | ||
| 57 | +pub struct NewUpload { | ||
| 58 | + /// Id, made by the caller with `store::new_id`, so the staging directory can be named first. | ||
| 59 | + pub id: String, | ||
| 60 | + /// The person who starts the upload. | ||
| 61 | + pub owner: String, | ||
| 62 | + /// Destination folder, or `None` for the top level. | ||
| 63 | + pub folder: Option<String>, | ||
| 64 | + /// The cleaned file name. | ||
| 65 | + pub name: String, | ||
| 66 | + /// Declared size in bytes. | ||
| 67 | + pub size: i64, | ||
| 68 | + /// Chunk size in bytes. | ||
| 69 | + pub chunk_size: i64, | ||
| 70 | + /// Expiry stamp: now plus 24 hours. | ||
| 71 | + pub expires_at: String, | ||
| 72 | +} | ||
| 73 | + | ||
| 74 | +/// Maps a row selected with [`UPLOAD_COLS`]. | ||
| 75 | +pub fn map_upload(row: &Row) -> Result<Upload> { | ||
| 76 | + Ok(Upload { | ||
| 77 | + id: col_text(row, 0)?, | ||
| 78 | + owner: col_text(row, 1)?, | ||
| 79 | + folder_id: col_opt_text(row, 2)?, | ||
| 80 | + name: col_text(row, 3)?, | ||
| 81 | + size: col_int(row, 4)?, | ||
| 82 | + chunk_size: col_int(row, 5)?, | ||
| 83 | + state: col_text(row, 6)?, | ||
| 84 | + file_id: col_opt_text(row, 7)?, | ||
| 85 | + created_at: col_text(row, 8)?, | ||
| 86 | + expires_at: col_text(row, 9)?, | ||
| 87 | + }) | ||
| 88 | +} | ||
| 89 | + | ||
| 90 | +/// An upload of `owner` by id. Foreign ids find nothing, so they look missing. | ||
| 91 | +async fn upload_of(conn: &Connection, owner: &str, id: &str) -> Result<Option<Upload>> { | ||
| 92 | + fetch_opt( | ||
| 93 | + conn, | ||
| 94 | + &format!("SELECT {UPLOAD_COLS} FROM uploads WHERE id = ?1 AND owner = ?2"), | ||
| 95 | + (id.to_string(), owner.to_string()), | ||
| 96 | + map_upload, | ||
| 97 | + ) | ||
| 98 | + .await | ||
| 99 | +} | ||
| 100 | + | ||
| 101 | +/// The bytes the owner's open uploads have declared, except the upload named `except`. Those bytes are | ||
| 102 | +/// promised to be written, so a new upload or a finish cannot take them. | ||
| 103 | +async fn declared_claims(conn: &Connection, owner: &str, now: &str, except: &str) -> Result<i64> { | ||
| 104 | + fetch_opt( | ||
| 105 | + conn, | ||
| 106 | + "SELECT COALESCE(SUM(size), 0) FROM uploads \ | ||
| 107 | + WHERE owner = ?1 AND state = 'active' AND expires_at > ?2 AND id <> ?3", | ||
| 108 | + (owner.to_string(), now.to_string(), except.to_string()), | ||
| 109 | + |row| col_int(row, 0), | ||
| 110 | + ) | ||
| 111 | + .await | ||
| 112 | + .map(|sum| sum.unwrap_or(0)) | ||
| 113 | +} | ||
| 114 | + | ||
| 115 | +impl Store { | ||
| 116 | + /// An upload of `owner` by id, or `None` when there is no such upload for that person. | ||
| 117 | + pub async fn upload(&self, owner: &str, id: &str) -> Result<Option<Upload>> { | ||
| 118 | + let conn = self.read_conn().await; | ||
| 119 | + upload_of(&conn, owner, id).await | ||
| 120 | + } | ||
| 121 | + | ||
| 122 | + /// Starts an upload. In one transaction: the folder must be a live folder of the owner, the size | ||
| 123 | + /// must not be above `max_size`, and it must fit the headroom after the other open uploads' declared | ||
| 124 | + /// sizes. A refusal for size is `Invalid("too_large")`, one for quota is `Conflict("quota_exceeded")`. | ||
| 125 | + pub async fn create_upload(&self, new: NewUpload, max_size: i64) -> Result<Upload> { | ||
| 126 | + if new.size < 0 || new.size > max_size { | ||
| 127 | + return Err(Error::Invalid("too_large".into())); | ||
| 128 | + } | ||
| 129 | + let now = now_stamp(); | ||
| 130 | + let conn = self.inner.conn.lock().await; | ||
| 131 | + let tx = conn.unchecked_transaction().await.map_err(db_err)?; | ||
| 132 | + let outcome: Result<Upload> = async { | ||
| 133 | + if let Some(f) = new.folder.as_deref() { | ||
| 134 | + live_folder(&tx, &new.owner, f).await?; | ||
| 135 | + } | ||
| 136 | + let (quota, used) = fetch_opt( | ||
| 137 | + &tx, | ||
| 138 | + "SELECT quota_bytes, used_bytes FROM members WHERE sub = ?1", | ||
| 139 | + (new.owner.clone(),), | ||
| 140 | + |row| Ok((col_int(row, 0)?, col_int(row, 1)?)), | ||
| 141 | + ) | ||
| 142 | + .await? | ||
| 143 | + .ok_or(Error::NotFound)?; | ||
| 144 | + let claims = declared_claims(&tx, &new.owner, &now, "").await?; | ||
| 145 | + if !quota::fits(new.size, quota::headroom(quota, used, claims)) { | ||
| 146 | + return Err(Error::Conflict("quota_exceeded".into())); | ||
| 147 | + } | ||
| 148 | + tx.execute( | ||
| 149 | + "INSERT INTO uploads (id, owner, folder_id, name, size, chunk_size, state, created_at, \ | ||
| 150 | + expires_at) VALUES (?1, ?2, ?3, ?4, ?5, ?6, 'active', ?7, ?8)", | ||
| 151 | + ( | ||
| 152 | + new.id.clone(), | ||
| 153 | + new.owner.clone(), | ||
| 154 | + new.folder.clone(), | ||
| 155 | + new.name.clone(), | ||
| 156 | + new.size, | ||
| 157 | + new.chunk_size, | ||
| 158 | + now.clone(), | ||
| 159 | + new.expires_at.clone(), | ||
| 160 | + ), | ||
| 161 | + ) | ||
| 162 | + .await | ||
| 163 | + .map_err(db_err)?; | ||
| 164 | + upload_of(&tx, &new.owner, &new.id) | ||
| 165 | + .await? | ||
| 166 | + .ok_or(Error::NotFound) | ||
| 167 | + } | ||
| 168 | + .await; | ||
| 169 | + finish(tx, outcome).await | ||
| 170 | + } | ||
| 171 | + | ||
| 172 | + /// Moves the expiry of an open upload of `owner` to `expires_at`. Returns `false` when the upload is | ||
| 173 | + /// not open for that person any more. | ||
| 174 | + pub async fn touch_upload(&self, owner: &str, id: &str, expires_at: &str) -> Result<bool> { | ||
| 175 | + let conn = self.inner.conn.lock().await; | ||
| 176 | + let changed = conn | ||
| 177 | + .execute( | ||
| 178 | + "UPDATE uploads SET expires_at = ?3 WHERE id = ?1 AND owner = ?2 AND state = 'active'", | ||
| 179 | + (id.to_string(), owner.to_string(), expires_at.to_string()), | ||
| 180 | + ) | ||
| 181 | + .await | ||
| 182 | + .map_err(db_err)?; | ||
| 183 | + Ok(changed == 1) | ||
| 184 | + } | ||
| 185 | + | ||
| 186 | + /// Cancels an open upload of `owner`. Returns `false` when it was not open (already finished, | ||
| 187 | + /// already cancelled, or not theirs). The staging directory is the caller's to remove. | ||
| 188 | + pub async fn abort_upload(&self, owner: &str, id: &str) -> Result<bool> { | ||
| 189 | + let conn = self.inner.conn.lock().await; | ||
| 190 | + let changed = conn | ||
| 191 | + .execute( | ||
| 192 | + "UPDATE uploads SET state = 'aborted' WHERE id = ?1 AND owner = ?2 AND state = 'active'", | ||
| 193 | + (id.to_string(), owner.to_string()), | ||
| 194 | + ) | ||
| 195 | + .await | ||
| 196 | + .map_err(db_err)?; | ||
| 197 | + Ok(changed == 1) | ||
| 198 | + } | ||
| 199 | + | ||
| 200 | + /// Turns an open upload into a file. The blob must already be stored under the key of `file.id`. | ||
| 201 | + /// In one transaction: the upload must still be open, `file.size` must equal the declared size, the | ||
| 202 | + /// quota is checked against the owner's other open uploads, the row is inserted with the upload's own | ||
| 203 | + /// folder and name, and the upload becomes `done`. A refused finish leaves the upload open. | ||
| 204 | + /// `file.folder`, `file.name` and `file.staged_claims` are ignored: the upload row decides them. | ||
| 205 | + pub async fn finish_upload(&self, owner: &str, id: &str, file: NewFile) -> Result<File> { | ||
| 206 | + let now = now_stamp(); | ||
| 207 | + let conn = self.inner.conn.lock().await; | ||
| 208 | + let tx = conn.unchecked_transaction().await.map_err(db_err)?; | ||
| 209 | + let outcome: Result<File> = async { | ||
| 210 | + let upload = upload_of(&tx, owner, id).await?.ok_or(Error::NotFound)?; | ||
| 211 | + if !upload.is_open(&now) { | ||
| 212 | + return Err(Error::Conflict("upload_not_active".into())); | ||
| 213 | + } | ||
| 214 | + if file.size != upload.size { | ||
| 215 | + return Err(Error::Invalid("size_mismatch".into())); | ||
| 216 | + } | ||
| 217 | + let claims = declared_claims(&tx, owner, &now, id).await?; | ||
| 218 | + let row = insert_file_in( | ||
| 219 | + &tx, | ||
| 220 | + NewFile { | ||
| 221 | + folder: upload.folder_id.clone(), | ||
| 222 | + name: upload.name.clone(), | ||
| 223 | + staged_claims: claims, | ||
| 224 | + owner: owner.to_owned(), | ||
| 225 | + ..file | ||
| 226 | + }, | ||
| 227 | + ) | ||
| 228 | + .await?; | ||
| 229 | + tx.execute( | ||
| 230 | + "UPDATE uploads SET state = 'done', file_id = ?2 WHERE id = ?1", | ||
| 231 | + (id.to_string(), row.id.clone()), | ||
| 232 | + ) | ||
| 233 | + .await | ||
| 234 | + .map_err(db_err)?; | ||
| 235 | + Ok(row) | ||
| 236 | + } | ||
| 237 | + .await; | ||
| 238 | + finish(tx, outcome).await | ||
| 239 | + } | ||
| 240 | + | ||
| 241 | + /// Deletes the upload rows that expired at or before `now`, in one transaction, and returns their | ||
| 242 | + /// ids so the caller can remove their staging directories. The rows go in the same transaction that | ||
| 243 | + /// reads the ids, so an upload that was extended in between is not removed. | ||
| 244 | + pub async fn expire_uploads(&self, now: &str) -> Result<Vec<String>> { | ||
| 245 | + let conn = self.inner.conn.lock().await; | ||
| 246 | + let tx = conn.unchecked_transaction().await.map_err(db_err)?; | ||
| 247 | + let outcome: Result<Vec<String>> = async { | ||
| 248 | + let ids = fetch_all( | ||
| 249 | + &tx, | ||
| 250 | + "SELECT id FROM uploads WHERE expires_at <= ?1", | ||
| 251 | + (now.to_string(),), | ||
| 252 | + |row| col_text(row, 0), | ||
| 253 | + ) | ||
| 254 | + .await?; | ||
| 255 | + tx.execute( | ||
| 256 | + "DELETE FROM uploads WHERE expires_at <= ?1", | ||
| 257 | + (now.to_string(),), | ||
| 258 | + ) | ||
| 259 | + .await | ||
| 260 | + .map_err(db_err)?; | ||
| 261 | + Ok(ids) | ||
| 262 | + } | ||
| 263 | + .await; | ||
| 264 | + finish(tx, outcome).await | ||
| 265 | + } | ||
| 266 | +} | ||
| 267 | + | ||
| 268 | +#[cfg(test)] | ||
| 269 | +mod tests { | ||
| 270 | + use super::*; | ||
| 271 | + use crate::store::new_id; | ||
| 272 | + use crate::store::test_support::store_with_member; | ||
| 273 | + use crate::time::stamp_after; | ||
| 274 | + use std::time::Duration; | ||
| 275 | + | ||
| 276 | + fn new_upload(size: i64) -> NewUpload { | ||
| 277 | + NewUpload { | ||
| 278 | + id: new_id(), | ||
| 279 | + owner: "ann".into(), | ||
| 280 | + folder: None, | ||
| 281 | + name: "big.bin".into(), | ||
| 282 | + size, | ||
| 283 | + chunk_size: 8, | ||
| 284 | + expires_at: stamp_after(Duration::from_secs(24 * 3600)), | ||
| 285 | + } | ||
| 286 | + } | ||
| 287 | + | ||
| 288 | + #[tokio::test] | ||
| 289 | + async fn parallel_creates_cannot_together_exceed_the_quota() { | ||
| 290 | + let (_dir, store) = store_with_member("ann").await; | ||
| 291 | + store.set_quota("ann", 100).await.unwrap(); | ||
| 292 | + let (first, second) = tokio::join!( | ||
| 293 | + store.create_upload(new_upload(60), 1000), | ||
| 294 | + store.create_upload(new_upload(60), 1000), | ||
| 295 | + ); | ||
| 296 | + let refused: Vec<&Result<Upload>> = [&first, &second] | ||
| 297 | + .into_iter() | ||
| 298 | + .filter(|outcome| outcome.is_err()) | ||
| 299 | + .collect(); | ||
| 300 | + assert_eq!(refused.len(), 1, "exactly one of the two may be accepted"); | ||
| 301 | + match refused[0] { | ||
| 302 | + Err(Error::Conflict(word)) => assert_eq!(word, "quota_exceeded"), | ||
| 303 | + other => panic!("expected quota_exceeded, got {other:?}"), | ||
| 304 | + } | ||
| 305 | + } | ||
| 306 | +} | ||
crates/in-web/assets/drive.jsadded+421 -0
| @@ -0,0 +1,421 @@ | |||
| 1 | +/* | ||
| 2 | + * drive.js: the upload queue of the drive pages. It is loaded only on those pages, and only does anything | ||
| 3 | + * on a page with a `form[data-upload-form]`. Without it, the upload form posts a whole file the old way. | ||
| 4 | + * | ||
| 5 | + * What it does: | ||
| 6 | + * - Files go to `/api/uploads` in chunks (`api/upload.rs`): create, send each chunk with a PUT, then | ||
| 7 | + * finish. Every request carries the session's CSRF token from the form's `data-csrf`. | ||
| 8 | + * - A chunk that fails with a network error or a server error is retried three times, waiting 0.5 s, | ||
| 9 | + * 1 s and 2 s between tries. A refusal the server gave (a 4xx) is not retried. | ||
| 10 | + * - When a chunk still fails, the upload waits and then asks the server which chunks it has, and sends | ||
| 11 | + * only the missing ones. That is the resume after a network error. It gives up after three rounds. | ||
| 12 | + * - A queue panel shows each file with a progress bar, its state and a cancel button. Cancelling an upload | ||
| 13 | + * that has an id removes it on the server too. | ||
| 14 | + * - Dropping files anywhere on the page offers them to the same queue. | ||
| 15 | + * - When a file finishes, `in:refresh` is dispatched on the document; `nav.js` re-reads the page, so the | ||
| 16 | + * new file appears in the listing. | ||
| 17 | + * | ||
| 18 | + * The labels come from data attributes on the form, so the server translates them. Nothing is inserted as | ||
| 19 | + * HTML: names and messages are set with textContent. The file is one IIFE with no globals. | ||
| 20 | + */ | ||
| 21 | +(function () { | ||
| 22 | + "use strict"; | ||
| 23 | + | ||
| 24 | + if (!window.fetch || !window.FormData || !window.XMLHttpRequest || !window.Blob) { | ||
| 25 | + return; | ||
| 26 | + } | ||
| 27 | + | ||
| 28 | + /** Pauses before the retry of a chunk, in milliseconds. One entry per retry. */ | ||
| 29 | + const BACKOFF_MS = [500, 1000, 2000]; | ||
| 30 | + /** Most rounds of "ask what is there, send what is missing" before an upload gives up. */ | ||
| 31 | + const RESUME_ROUNDS = 3; | ||
| 32 | + /** Pause before a resume round, in milliseconds. */ | ||
| 33 | + const RESUME_PAUSE_MS = 2000; | ||
| 34 | + | ||
| 35 | + /** The uploads waiting for their turn, in the order they were added. */ | ||
| 36 | + const waiting = []; | ||
| 37 | + /** True while one upload runs. Uploads go one at a time, so a slow link is not split between them. */ | ||
| 38 | + let running = false; | ||
| 39 | + /** The queue panel, created on first use and kept outside `<main>`, so a page refresh does not drop it. */ | ||
| 40 | + let panel = null; | ||
| 41 | + /** How many dragged-in events are still open. The overlay goes when it reaches zero. */ | ||
| 42 | + let dragDepth = 0; | ||
| 43 | + /** The drop overlay, created on first use. */ | ||
| 44 | + let overlay = null; | ||
| 45 | + | ||
| 46 | + /** A refusal or failure of an API call. `status` is the HTTP status, `word` the server's fixed word. */ | ||
| 47 | + class ApiError extends Error { | ||
| 48 | + constructor(status, word) { | ||
| 49 | + super(word); | ||
| 50 | + this.status = status; | ||
| 51 | + this.word = word; | ||
| 52 | + } | ||
| 53 | + | ||
| 54 | + /** A 4xx is the server's answer and repeating it will not change it. */ | ||
| 55 | + get retryable() { | ||
| 56 | + return this.status === 0 || this.status >= 500; | ||
| 57 | + } | ||
| 58 | + } | ||
| 59 | + | ||
| 60 | + /** The form the drop and the picker use: the first upload form of the page, if there is one. */ | ||
| 61 | + function uploadForm() { | ||
| 62 | + return document.querySelector("form[data-upload-form]"); | ||
| 63 | + } | ||
| 64 | + | ||
| 65 | + /** Reads the labels, the folder and the CSRF token of a form now, so a later page refresh cannot change them. */ | ||
| 66 | + function settingsOf(form) { | ||
| 67 | + return { | ||
| 68 | + csrf: form.dataset.csrf || "", | ||
| 69 | + folder: form.dataset.folder || "", | ||
| 70 | + labels: { | ||
| 71 | + uploading: form.dataset.labelUploading || "", | ||
| 72 | + done: form.dataset.labelDone || "", | ||
| 73 | + failed: form.dataset.labelFailed || "", | ||
| 74 | + canceled: form.dataset.labelCanceled || "", | ||
| 75 | + cancel: form.dataset.labelCancel || "", | ||
| 76 | + drop: form.dataset.labelDrop || "", | ||
| 77 | + }, | ||
| 78 | + }; | ||
| 79 | + } | ||
| 80 | + | ||
| 81 | + /** Makes a job for one file and puts it in the queue. */ | ||
| 82 | + function enqueue(form, files) { | ||
| 83 | + const settings = settingsOf(form); | ||
| 84 | + for (const file of files) { | ||
| 85 | + const job = { | ||
| 86 | + file, | ||
| 87 | + csrf: settings.csrf, | ||
| 88 | + folder: settings.folder, | ||
| 89 | + labels: settings.labels, | ||
| 90 | + uploadId: "", | ||
| 91 | + state: "waiting", | ||
| 92 | + cancelled: false, | ||
| 93 | + doneBytes: 0, | ||
| 94 | + xhr: null, | ||
| 95 | + row: null, | ||
| 96 | + }; | ||
| 97 | + render(job); | ||
| 98 | + waiting.push(job); | ||
| 99 | + } | ||
| 100 | + pump(); | ||
| 101 | + } | ||
| 102 | + | ||
| 103 | + /** Runs the next waiting upload, then the one after it, until the queue is empty. */ | ||
| 104 | + async function pump() { | ||
| 105 | + if (running) { | ||
| 106 | + return; | ||
| 107 | + } | ||
| 108 | + running = true; | ||
| 109 | + while (waiting.length > 0) { | ||
| 110 | + const job = waiting.shift(); | ||
| 111 | + if (job.state === "waiting") { | ||
| 112 | + await run(job); | ||
| 113 | + } | ||
| 114 | + } | ||
| 115 | + running = false; | ||
| 116 | + } | ||
| 117 | + | ||
| 118 | + /** The whole upload of one file: create, send what is missing, finish. Ends with the job's state set. */ | ||
| 119 | + async function run(job) { | ||
| 120 | + setState(job, "uploading", job.labels.uploading); | ||
| 121 | + try { | ||
| 122 | + const created = await api(job, "POST", "/api/uploads", { | ||
| 123 | + folder_id: job.folder || null, | ||
| 124 | + name: job.file.name, | ||
| 125 | + size: job.file.size, | ||
| 126 | + }); | ||
| 127 | + job.uploadId = created.id; | ||
| 128 | + const chunk = created.chunk_size; | ||
| 129 | + const size = job.file.size; | ||
| 130 | + const count = Math.ceil(size / chunk); | ||
| 131 | + let rounds = 0; | ||
| 132 | + for (;;) { | ||
| 133 | + const status = await api(job, "GET", `/api/uploads/${job.uploadId}`); | ||
| 134 | + const have = new Set(status.received); | ||
| 135 | + job.doneBytes = 0; | ||
| 136 | + const missing = []; | ||
| 137 | + for (let index = 0; index < count; index += 1) { | ||
| 138 | + const length = Math.min(size, (index + 1) * chunk) - index * chunk; | ||
| 139 | + if (have.has(index)) { | ||
| 140 | + job.doneBytes += length; | ||
| 141 | + } else { | ||
| 142 | + missing.push(index); | ||
| 143 | + } | ||
| 144 | + } | ||
| 145 | + setProgress(job, job.doneBytes); | ||
| 146 | + if (missing.length === 0) { | ||
| 147 | + break; | ||
| 148 | + } | ||
| 149 | + rounds += 1; | ||
| 150 | + try { | ||
| 151 | + for (const index of missing) { | ||
| 152 | + await sendChunk(job, index, chunk, size); | ||
| 153 | + } | ||
| 154 | + } catch (error) { | ||
| 155 | + // Only a network error or a server error is worth another round. A refusal of the server is final. | ||
| 156 | + const resumable = | ||
| 157 | + !job.cancelled && | ||
| 158 | + rounds < RESUME_ROUNDS && | ||
| 159 | + (error instanceof TypeError || (error instanceof ApiError && error.retryable)); | ||
| 160 | + if (!resumable) { | ||
| 161 | + throw error; | ||
| 162 | + } | ||
| 163 | + // A network error ends the round. Wait, then ask the server what it has and go on from there. | ||
| 164 | + await delay(RESUME_PAUSE_MS); | ||
| 165 | + } | ||
| 166 | + } | ||
| 167 | + await api(job, "POST", `/api/uploads/${job.uploadId}/finish`); | ||
| 168 | + job.uploadId = ""; | ||
| 169 | + setProgress(job, size); | ||
| 170 | + setState(job, "done", job.labels.done); | ||
| 171 | + job.row.cancel.remove(); | ||
| 172 | + document.dispatchEvent(new CustomEvent("in:refresh")); | ||
| 173 | + } catch (error) { | ||
| 174 | + if (job.cancelled) { | ||
| 175 | + return; | ||
| 176 | + } | ||
| 177 | + const word = error instanceof ApiError ? error.word : "network"; | ||
| 178 | + setState(job, "failed", `${job.labels.failed} (${word})`); | ||
| 179 | + job.row.cancel.remove(); | ||
| 180 | + } | ||
| 181 | + } | ||
| 182 | + | ||
| 183 | + /** Sends one chunk, retrying the retryable failures with the backoff. */ | ||
| 184 | + async function sendChunk(job, index, chunk, size) { | ||
| 185 | + const start = index * chunk; | ||
| 186 | + const blob = job.file.slice(start, Math.min(size, start + chunk)); | ||
| 187 | + for (let attempt = 0; ; attempt += 1) { | ||
| 188 | + try { | ||
| 189 | + await putChunk(job, index, blob); | ||
| 190 | + return; | ||
| 191 | + } catch (error) { | ||
| 192 | + const retryable = | ||
| 193 | + !job.cancelled && (error instanceof TypeError || (error instanceof ApiError && error.retryable)); | ||
| 194 | + if (!retryable || attempt >= BACKOFF_MS.length) { | ||
| 195 | + throw error; | ||
| 196 | + } | ||
| 197 | + await delay(BACKOFF_MS[attempt]); | ||
| 198 | + } | ||
| 199 | + } | ||
| 200 | + } | ||
| 201 | + | ||
| 202 | + /** PUTs one chunk. The progress of the file counts the bytes sent so far, not only whole chunks. */ | ||
| 203 | + function putChunk(job, index, blob) { | ||
| 204 | + return new Promise((resolve, reject) => { | ||
| 205 | + const xhr = new XMLHttpRequest(); | ||
| 206 | + job.xhr = xhr; | ||
| 207 | + xhr.open("PUT", `/api/uploads/${job.uploadId}/${index}`); | ||
| 208 | + xhr.setRequestHeader("X-CSRF-Token", job.csrf); | ||
| 209 | + xhr.setRequestHeader("Content-Type", "application/octet-stream"); | ||
| 210 | + xhr.upload.onprogress = (event) => { | ||
| 211 | + if (event.lengthComputable) { | ||
| 212 | + setProgress(job, job.doneBytes + event.loaded); | ||
| 213 | + } | ||
| 214 | + }; | ||
| 215 | + xhr.onload = () => { | ||
| 216 | + job.xhr = null; | ||
| 217 | + if (xhr.status >= 200 && xhr.status < 300) { | ||
| 218 | + job.doneBytes += blob.size; | ||
| 219 | + setProgress(job, job.doneBytes); | ||
| 220 | + resolve(); | ||
| 221 | + } else { | ||
| 222 | + reject(answerError(xhr.status, xhr.responseText)); | ||
| 223 | + } | ||
| 224 | + }; | ||
| 225 | + xhr.onerror = () => { | ||
| 226 | + job.xhr = null; | ||
| 227 | + reject(new TypeError("network")); | ||
| 228 | + }; | ||
| 229 | + xhr.onabort = () => { | ||
| 230 | + job.xhr = null; | ||
| 231 | + reject(new TypeError("aborted")); | ||
| 232 | + }; | ||
| 233 | + xhr.send(blob); | ||
| 234 | + }); | ||
| 235 | + } | ||
| 236 | + | ||
| 237 | + /** A JSON call to the upload API. A failed status becomes an `ApiError` with the server's word. */ | ||
| 238 | + async function api(job, method, path, body) { | ||
| 239 | + const headers = { "X-CSRF-Token": job.csrf }; | ||
| 240 | + if (body !== undefined) { | ||
| 241 | + headers["Content-Type"] = "application/json"; | ||
| 242 | + } | ||
| 243 | + let response; | ||
| 244 | + try { | ||
| 245 | + response = await fetch(path, { | ||
| 246 | + method, | ||
| 247 | + headers, | ||
| 248 | + body: body === undefined ? undefined : JSON.stringify(body), | ||
| 249 | + credentials: "same-origin", | ||
| 250 | + cache: "no-store", | ||
| 251 | + }); | ||
| 252 | + } catch (error) { | ||
| 253 | + throw new TypeError("network"); | ||
| 254 | + } | ||
| 255 | + const text = await response.text(); | ||
| 256 | + if (!response.ok) { | ||
| 257 | + throw answerError(response.status, text); | ||
| 258 | + } | ||
| 259 | + return text ? JSON.parse(text) : {}; | ||
| 260 | + } | ||
| 261 | + | ||
| 262 | + /** The error of a failed answer: its status and the `error` word of its JSON body. */ | ||
| 263 | + function answerError(status, text) { | ||
| 264 | + let word = "server"; | ||
| 265 | + try { | ||
| 266 | + const data = JSON.parse(text); | ||
| 267 | + if (data && typeof data.error === "string") { | ||
| 268 | + word = data.error; | ||
| 269 | + } | ||
| 270 | + } catch (error) { | ||
| 271 | + // Not JSON: the status alone says what happened. | ||
| 272 | + } | ||
| 273 | + return new ApiError(status, word); | ||
| 274 | + } | ||
| 275 | + | ||
| 276 | + /** Stops an upload. A started upload is also removed on the server. */ | ||
| 277 | + function cancel(job) { | ||
| 278 | + if (job.state === "done" || job.state === "failed" || job.state === "canceled") { | ||
| 279 | + return; | ||
| 280 | + } | ||
| 281 | + job.cancelled = true; | ||
| 282 | + if (job.xhr) { | ||
| 283 | + job.xhr.abort(); | ||
| 284 | + } | ||
| 285 | + if (job.uploadId) { | ||
| 286 | + fetch(`/api/uploads/${job.uploadId}`, { | ||
| 287 | + method: "DELETE", | ||
| 288 | + headers: { "X-CSRF-Token": job.csrf }, | ||
| 289 | + credentials: "same-origin", | ||
| 290 | + }).catch(() => {}); | ||
| 291 | + job.uploadId = ""; | ||
| 292 | + } | ||
| 293 | + setState(job, "canceled", job.labels.canceled); | ||
| 294 | + job.row.cancel.remove(); | ||
| 295 | + } | ||
| 296 | + | ||
| 297 | + /** The queue panel, made on first use and appended to the body. */ | ||
| 298 | + function queuePanel() { | ||
| 299 | + if (!panel) { | ||
| 300 | + panel = document.createElement("section"); | ||
| 301 | + panel.className = "upload-queue"; | ||
| 302 | + panel.setAttribute("aria-live", "polite"); | ||
| 303 | + const list = document.createElement("ul"); | ||
| 304 | + list.className = "upload-list"; | ||
| 305 | + panel.append(list); | ||
| 306 | + document.body.append(panel); | ||
| 307 | + } | ||
| 308 | + return panel.querySelector(".upload-list"); | ||
| 309 | + } | ||
| 310 | + | ||
| 311 | + /** Adds the queue row of a job: name, progress, state and cancel. */ | ||
| 312 | + function render(job) { | ||
| 313 | + const item = document.createElement("li"); | ||
| 314 | + item.className = "upload-item"; | ||
| 315 | + const name = document.createElement("span"); | ||
| 316 | + name.className = "upload-name"; | ||
| 317 | + name.textContent = job.file.name; | ||
| 318 | + const bar = document.createElement("progress"); | ||
| 319 | + bar.max = Math.max(job.file.size, 1); | ||
| 320 | + bar.value = 0; | ||
| 321 | + const status = document.createElement("span"); | ||
| 322 | + status.className = "upload-status"; | ||
| 323 | + status.textContent = job.labels.uploading; | ||
| 324 | + const cancelButton = document.createElement("button"); | ||
| 325 | + cancelButton.type = "button"; | ||
| 326 | + cancelButton.className = "button ghost"; | ||
| 327 | + cancelButton.textContent = job.labels.cancel; | ||
| 328 | + cancelButton.addEventListener("click", () => cancel(job)); | ||
| 329 | + item.append(name, bar, status, cancelButton); | ||
| 330 | + queuePanel().append(item); | ||
| 331 | + job.row = { item, bar, status, cancel: cancelButton }; | ||
| 332 | + } | ||
| 333 | + | ||
| 334 | + /** Sets the state word of a job and the matching `data-state` of its row. */ | ||
| 335 | + function setState(job, state, text) { | ||
| 336 | + job.state = state; | ||
| 337 | + job.row.item.dataset.state = state; | ||
| 338 | + job.row.status.textContent = text; | ||
| 339 | + } | ||
| 340 | + | ||
| 341 | + /** Moves the progress bar of a job. */ | ||
| 342 | + function setProgress(job, bytes) { | ||
| 343 | + job.row.bar.value = Math.min(bytes, job.row.bar.max); | ||
| 344 | + } | ||
| 345 | + | ||
| 346 | + /** Resolves after `ms` milliseconds. */ | ||
| 347 | + function delay(ms) { | ||
| 348 | + return new Promise((resolve) => setTimeout(resolve, ms)); | ||
| 349 | + } | ||
| 350 | + | ||
| 351 | + /** Whether a drag carries files, as opposed to text or a link. */ | ||
| 352 | + function carriesFiles(event) { | ||
| 353 | + const types = event.dataTransfer && event.dataTransfer.types; | ||
| 354 | + return !!types && Array.prototype.indexOf.call(types, "Files") !== -1; | ||
| 355 | + } | ||
| 356 | + | ||
| 357 | + /** Shows or hides the drop overlay. Its text is the form's drop label. */ | ||
| 358 | + function showOverlay(show, form) { | ||
| 359 | + if (!overlay) { | ||
| 360 | + overlay = document.createElement("div"); | ||
| 361 | + overlay.className = "drop-overlay"; | ||
| 362 | + overlay.setAttribute("aria-hidden", "true"); | ||
| 363 | + document.body.append(overlay); | ||
| 364 | + } | ||
| 365 | + if (show && form) { | ||
| 366 | + overlay.textContent = form.dataset.labelDrop || ""; | ||
| 367 | + } | ||
| 368 | + overlay.classList.toggle("drop-overlay-show", show); | ||
| 369 | + } | ||
| 370 | + | ||
| 371 | + document.addEventListener("submit", (event) => { | ||
| 372 | + const form = event.target; | ||
| 373 | + if (!(form instanceof HTMLFormElement) || !form.matches("form[data-upload-form]")) { | ||
| 374 | + return; | ||
| 375 | + } | ||
| 376 | + const input = form.querySelector("input[type=file]"); | ||
| 377 | + const files = input && input.files ? Array.from(input.files) : []; | ||
| 378 | + if (files.length === 0) { | ||
| 379 | + return; | ||
| 380 | + } | ||
| 381 | + event.preventDefault(); | ||
| 382 | + enqueue(form, files); | ||
| 383 | + input.value = ""; | ||
| 384 | + }); | ||
| 385 | + | ||
| 386 | + document.addEventListener("dragenter", (event) => { | ||
| 387 | + if (!uploadForm() || !carriesFiles(event)) { | ||
| 388 | + return; | ||
| 389 | + } | ||
| 390 | + event.preventDefault(); | ||
| 391 | + dragDepth += 1; | ||
| 392 | + showOverlay(true, uploadForm()); | ||
| 393 | + }); | ||
| 394 | + | ||
| 395 | + document.addEventListener("dragover", (event) => { | ||
| 396 | + if (uploadForm() && carriesFiles(event)) { | ||
| 397 | + event.preventDefault(); | ||
| 398 | + } | ||
| 399 | + }); | ||
| 400 | + | ||
| 401 | + document.addEventListener("dragleave", () => { | ||
| 402 | + if (!uploadForm()) { | ||
| 403 | + return; | ||
| 404 | + } | ||
| 405 | + dragDepth = Math.max(0, dragDepth - 1); | ||
| 406 | + if (dragDepth === 0) { | ||
| 407 | + showOverlay(false, null); | ||
| 408 | + } | ||
| 409 | + }); | ||
| 410 | + | ||
| 411 | + document.addEventListener("drop", (event) => { | ||
| 412 | + dragDepth = 0; | ||
| 413 | + showOverlay(false, null); | ||
| 414 | + const form = uploadForm(); | ||
| 415 | + if (!form || !event.dataTransfer || !event.dataTransfer.files || event.dataTransfer.files.length === 0) { | ||
| 416 | + return; | ||
| 417 | + } | ||
| 418 | + event.preventDefault(); | ||
| 419 | + enqueue(form, Array.from(event.dataTransfer.files)); | ||
| 420 | + }); | ||
| 421 | +})(); | ||
crates/in-web/assets/nav.jsmodified+4 -0
| @@ -224,6 +224,10 @@ | |||
| 224 | }, REFRESH_DEBOUNCE_MS); | 224 | }, REFRESH_DEBOUNCE_MS); |
| 225 | } | 225 | } |
| 226 | 226 | ||
| 227 | + // drive.js dispatches `in:refresh` when an upload finishes. The page re-reads itself, as it does on a | ||
| 228 | + // `changed` event from the server, so the new file shows up in the listing. | ||
| 229 | + document.addEventListener("in:refresh", () => scheduleRefresh()); | ||
| 230 | + | ||
| 227 | // --------------------------------------------------------------------------------------------- | 231 | // --------------------------------------------------------------------------------------------- |
| 228 | // Form fields and focus, kept across a live refresh. | 232 | // Form fields and focus, kept across a live refresh. |
| 229 | 233 | ||
crates/in-web/build.rsmodified+2 -1
| @@ -1,6 +1,6 @@ | |||
| 1 | //! Build script of the `in` binary. It compiles `style/main.scss` into `OUT_DIR/main.css`, and it | 1 | //! Build script of the `in` binary. It compiles `style/main.scss` into `OUT_DIR/main.css`, and it |
| 2 | //! emits the build identity and the content hashes that the page links use as cache-busting | 2 | //! emits the build identity and the content hashes that the page links use as cache-busting |
| 3 | -//! queries: `IN_MAIN_CSS_V`, `IN_NAV_JS_V`, `IN_PAGES_JS_V` and `IN_BUILD_SHA`. | 3 | +//! queries: `IN_MAIN_CSS_V`, `IN_NAV_JS_V`, `IN_PAGES_JS_V`, `IN_DRIVE_JS_V` and `IN_BUILD_SHA`. |
| 4 | //! | 4 | //! |
| 5 | //! It does not decide what is served: `src/assets.rs` embeds the files. It does not decide what a | 5 | //! It does not decide what is served: `src/assets.rs` embeds the files. It does not decide what a |
| 6 | //! page links to either: `src/assets.rs` builds the `?v=` URLs from these values. It only compiles | 6 | //! page links to either: `src/assets.rs` builds the `?v=` URLs from these values. It only compiles |
| @@ -45,6 +45,7 @@ fn main() { | |||
| 45 | for (var, file) in [ | 45 | for (var, file) in [ |
| 46 | ("IN_NAV_JS_V", "assets/nav.js"), | 46 | ("IN_NAV_JS_V", "assets/nav.js"), |
| 47 | ("IN_PAGES_JS_V", "assets/pages.js"), | 47 | ("IN_PAGES_JS_V", "assets/pages.js"), |
| 48 | + ("IN_DRIVE_JS_V", "assets/drive.js"), | ||
| 48 | ] { | 49 | ] { |
| 49 | let bytes = fs::read(manifest.join(file)).unwrap_or_else(|e| panic!("reading {file}: {e}")); | 50 | let bytes = fs::read(manifest.join(file)).unwrap_or_else(|e| panic!("reading {file}: {e}")); |
| 50 | println!("cargo:rustc-env={var}={}", content_version(&bytes)); | 51 | println!("cargo:rustc-env={var}={}", content_version(&bytes)); |
crates/in-web/src/api/mod.rsadded+4 -0
| @@ -0,0 +1,4 @@ | |||
| 1 | +//! The JSON APIs of the app: the chunked upload (`upload.rs`, architecture 4.2). The machine object API | ||
| 2 | +//! comes later (contracts.md 5). Every route here answers JSON, including its refusals, and never | ||
| 3 | +//! redirects to sign-in: a script that lost its session gets `401`. | ||
| 4 | +pub mod upload; | ||
crates/in-web/src/api/upload.rsadded+717 -0
| @@ -0,0 +1,717 @@ | |||
| 1 | +//! The chunked upload API (architecture 4.2). A file is sent in chunks of 8 MiB, each to its own URL, and | ||
| 2 | +//! the server joins them when the client finishes. Every route needs the session cookie and the | ||
| 3 | +//! `X-CSRF-Token` header; a missing or wrong token is `403`, a missing session is `401`, both as JSON. | ||
| 4 | +//! | ||
| 5 | +//! The routes: | ||
| 6 | +//! - `POST /api/uploads` `{folder_id?, name, size}` starts an upload → `201 {id, chunk_size}`. The size is | ||
| 7 | +//! reserved against the quota in the same transaction that creates the row, so two creates cannot | ||
| 8 | +//! together promise more than the headroom. | ||
| 9 | +//! - `GET /api/uploads/{id}` → `{id, state, size, chunk_size, received}`, where `received` lists the chunk | ||
| 10 | +//! indexes on disk. A client that lost its connection asks this, then sends only what is missing. | ||
| 11 | +//! - `PUT /api/uploads/{id}/{index}` sends one chunk as the raw body. The index must be a chunk of the | ||
| 12 | +//! upload, and the body must be exactly the length that chunk has: `chunk_size` for every chunk but the | ||
| 13 | +//! last, which is the remainder. A longer body is `413` and a shorter one `400`; the bytes are read with a | ||
| 14 | +//! hard limit, so a client cannot make the server store more than the declared size. Sending a chunk that | ||
| 15 | +//! is already there replaces it with the same bytes. | ||
| 16 | +//! - `POST /api/uploads/{id}/finish` joins the chunks into a blob, inserts the file row and marks the upload | ||
| 17 | +//! done → `{file_id}`. Missing chunks are `409` with their indexes. The quota is checked again in the | ||
| 18 | +//! insert transaction, against the other open uploads. | ||
| 19 | +//! - `DELETE /api/uploads/{id}` cancels an open upload and removes its staging directory. | ||
| 20 | +//! | ||
| 21 | +//! An upload that is not finished within 24 hours of its last chunk expires; the sweeper removes it. | ||
| 22 | +//! Another member's upload id is `404`, the same as a missing one. | ||
| 23 | + | ||
| 24 | +use std::path::Path; | ||
| 25 | + | ||
| 26 | +use futures_util::StreamExt; | ||
| 27 | +use http::header::{CACHE_CONTROL, CONTENT_TYPE}; | ||
| 28 | +use http::{HeaderValue, StatusCode}; | ||
| 29 | +use in_core::error::Error as CoreError; | ||
| 30 | +use in_core::names::upload_name; | ||
| 31 | +use in_core::sniff::sniff; | ||
| 32 | +use in_core::staging::{ | ||
| 33 | + CHUNK_BYTES, Staged, StagedFile, chunk_count, chunk_path, expected_chunk_len, | ||
| 34 | + remove_upload_dir, upload_dir, | ||
| 35 | +}; | ||
| 36 | +use in_core::store::files::{NewFile, files_blob_key}; | ||
| 37 | +use in_core::store::new_id; | ||
| 38 | +use in_core::store::uploads::{NewUpload, Upload}; | ||
| 39 | +use in_core::time::{now_stamp, stamp_after}; | ||
| 40 | +use serde::Deserialize; | ||
| 41 | +use serde_json::{Value, json}; | ||
| 42 | +use tokio::io::AsyncReadExt; | ||
| 43 | +use topcoat::Result; | ||
| 44 | +use topcoat::context::{Cx, app_context}; | ||
| 45 | +use topcoat::router::request::headers; | ||
| 46 | +use topcoat::router::response::Response; | ||
| 47 | +use topcoat::router::{Body, path_param_segment, route, to_bytes}; | ||
| 48 | + | ||
| 49 | +use crate::auth::{Viewer, csrf_matches, current_member}; | ||
| 50 | +use crate::pages::drive::{changed, optional_folder}; | ||
| 51 | +use crate::state::AppState; | ||
| 52 | + | ||
| 53 | +/// The header that carries the session's CSRF token. | ||
| 54 | +const CSRF_HEADER: &str = "x-csrf-token"; | ||
| 55 | + | ||
| 56 | +/// How long an open upload may wait for its next chunk: 24 hours. Every chunk restarts the count. | ||
| 57 | +pub const UPLOAD_TTL: std::time::Duration = std::time::Duration::from_secs(24 * 60 * 60); | ||
| 58 | + | ||
| 59 | +/// The default largest upload: 50 GiB. The `max_upload_bytes` setting overrides it. | ||
| 60 | +pub const DEFAULT_MAX_UPLOAD: u64 = 50 * 1024 * 1024 * 1024; | ||
| 61 | + | ||
| 62 | +/// The settings key of the largest upload, in bytes. | ||
| 63 | +pub const MAX_UPLOAD_SETTING: &str = "max_upload_bytes"; | ||
| 64 | + | ||
| 65 | +/// Largest body the create route reads. Its JSON is a few hundred bytes. | ||
| 66 | +const CREATE_BODY_LIMIT: usize = 4096; | ||
| 67 | + | ||
| 68 | +/// How many bytes a chunk is copied with when the chunks are joined. | ||
| 69 | +const COPY_BUFFER: usize = 64 * 1024; | ||
| 70 | + | ||
| 71 | +/// How many leading bytes of the file the sniffer reads. | ||
| 72 | +const SNIFF_BYTES: usize = 8192; | ||
| 73 | + | ||
| 74 | +/// A refused call: the status and the fixed word the client gets as `{"error": word}`. | ||
| 75 | +#[derive(Debug, Clone, Copy)] | ||
| 76 | +struct Refusal { | ||
| 77 | + status: StatusCode, | ||
| 78 | + word: &'static str, | ||
| 79 | +} | ||
| 80 | + | ||
| 81 | +impl Refusal { | ||
| 82 | + /// The JSON answer of this refusal. | ||
| 83 | + fn answer(self) -> Response { | ||
| 84 | + json_answer(self.status, json!({ "error": self.word })) | ||
| 85 | + } | ||
| 86 | +} | ||
| 87 | + | ||
| 88 | +/// Shorthand for a [`Refusal`]. | ||
| 89 | +const fn refuse(status: StatusCode, word: &'static str) -> Refusal { | ||
| 90 | + Refusal { status, word } | ||
| 91 | +} | ||
| 92 | + | ||
| 93 | +/// A JSON response with the given status. Upload answers are never cached. | ||
| 94 | +fn json_answer(status: StatusCode, value: Value) -> Response { | ||
| 95 | + let body = serde_json::to_vec(&value).unwrap_or_default(); | ||
| 96 | + http::Response::builder() | ||
| 97 | + .status(status) | ||
| 98 | + .header(CONTENT_TYPE, HeaderValue::from_static("application/json")) | ||
| 99 | + .header(CACHE_CONTROL, HeaderValue::from_static("no-store")) | ||
| 100 | + .body(Body::from(body)) | ||
| 101 | + .unwrap_or_else(|_| http::Response::new(Body::empty())) | ||
| 102 | +} | ||
| 103 | + | ||
| 104 | +/// The signed-in viewer, when the request carries the session cookie and a matching CSRF header. The | ||
| 105 | +/// outer `Result` is a server failure; the inner one is the refusal to send. | ||
| 106 | +async fn api_viewer(cx: &Cx) -> Result<std::result::Result<Viewer, Refusal>> { | ||
| 107 | + let Some(viewer) = current_member(cx).await? else { | ||
| 108 | + return Ok(Err(refuse(StatusCode::UNAUTHORIZED, "signed_out"))); | ||
| 109 | + }; | ||
| 110 | + let submitted = headers(cx) | ||
| 111 | + .get(CSRF_HEADER) | ||
| 112 | + .and_then(|value| value.to_str().ok()) | ||
| 113 | + .unwrap_or(""); | ||
| 114 | + if !csrf_matches(&viewer.session, submitted) { | ||
| 115 | + return Ok(Err(refuse(StatusCode::FORBIDDEN, "csrf"))); | ||
| 116 | + } | ||
| 117 | + Ok(Ok(viewer)) | ||
| 118 | +} | ||
| 119 | + | ||
| 120 | +/// The viewer's upload by id, which must still be open. Another member's or a missing id is `404`; an | ||
| 121 | +/// upload that already finished or was cancelled is `409`; one past its expiry is `410`. | ||
| 122 | +async fn open_upload( | ||
| 123 | + state: &AppState, | ||
| 124 | + viewer: &Viewer, | ||
| 125 | + id: &str, | ||
| 126 | +) -> Result<std::result::Result<Upload, Refusal>> { | ||
| 127 | + let Some(upload) = state.store.upload(&viewer.member.sub, id).await? else { | ||
| 128 | + return Ok(Err(refuse(StatusCode::NOT_FOUND, "not_found"))); | ||
| 129 | + }; | ||
| 130 | + if upload.state != "active" { | ||
| 131 | + return Ok(Err(refuse(StatusCode::CONFLICT, "not_active"))); | ||
| 132 | + } | ||
| 133 | + if !upload.is_open(&now_stamp()) { | ||
| 134 | + return Ok(Err(refuse(StatusCode::GONE, "expired"))); | ||
| 135 | + } | ||
| 136 | + Ok(Ok(upload)) | ||
| 137 | +} | ||
| 138 | + | ||
| 139 | +/// The largest upload the settings allow, in bytes. A stored value that is not a number is ignored. | ||
| 140 | +pub async fn max_upload_bytes(state: &AppState) -> Result<i64> { | ||
| 141 | + let limit = state | ||
| 142 | + .store | ||
| 143 | + .get_setting(MAX_UPLOAD_SETTING) | ||
| 144 | + .await? | ||
| 145 | + .and_then(|value| value.trim().parse::<u64>().ok()) | ||
| 146 | + .unwrap_or(DEFAULT_MAX_UPLOAD) | ||
| 147 | + .clamp(1, i64::MAX as u64); | ||
| 148 | + Ok(i64::try_from(limit).unwrap_or(i64::MAX)) | ||
| 149 | +} | ||
| 150 | + | ||
| 151 | +/// The indexes of the chunks that are on disk. A missing directory has none. | ||
| 152 | +async fn received_chunks(dir: &Path) -> Result<Vec<u64>> { | ||
| 153 | + let mut found = Vec::new(); | ||
| 154 | + let mut entries = match tokio::fs::read_dir(dir).await { | ||
| 155 | + Ok(entries) => entries, | ||
| 156 | + Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(found), | ||
| 157 | + Err(error) => return Err(CoreError::from(error).into()), | ||
| 158 | + }; | ||
| 159 | + while let Some(entry) = entries.next_entry().await.map_err(CoreError::from)? { | ||
| 160 | + // Chunk files are named by their index. Temporary files have ULID names, which never parse. | ||
| 161 | + if let Some(index) = entry | ||
| 162 | + .file_name() | ||
| 163 | + .to_str() | ||
| 164 | + .and_then(|n| n.parse::<u64>().ok()) | ||
| 165 | + { | ||
| 166 | + found.push(index); | ||
| 167 | + } | ||
| 168 | + } | ||
| 169 | + found.sort_unstable(); | ||
| 170 | + Ok(found) | ||
| 171 | +} | ||
| 172 | + | ||
| 173 | +/// The body of `POST /api/uploads`. | ||
| 174 | +#[derive(Debug, Deserialize)] | ||
| 175 | +struct CreateRequest { | ||
| 176 | + /// Destination folder, or absent for the top level. | ||
| 177 | + #[serde(default)] | ||
| 178 | + folder_id: Option<String>, | ||
| 179 | + /// The file name as the client has it. It is cleaned, not refused. | ||
| 180 | + name: String, | ||
| 181 | + /// Declared size in bytes. | ||
| 182 | + size: u64, | ||
| 183 | +} | ||
| 184 | + | ||
| 185 | +/// `POST /api/uploads`: starts an upload. | ||
| 186 | +#[route(POST "/api/uploads")] | ||
| 187 | +async fn create_upload(cx: &Cx, body: Body) -> Result<Response> { | ||
| 188 | + let state = app_context::<AppState>(cx); | ||
| 189 | + let viewer = match api_viewer(cx).await? { | ||
| 190 | + Ok(viewer) => viewer, | ||
| 191 | + Err(refusal) => return Ok(refusal.answer()), | ||
| 192 | + }; | ||
| 193 | + let Ok(bytes) = to_bytes(body, CREATE_BODY_LIMIT).await else { | ||
| 194 | + return Ok(refuse(StatusCode::PAYLOAD_TOO_LARGE, "too_large").answer()); | ||
| 195 | + }; | ||
| 196 | + let Ok(request) = serde_json::from_slice::<CreateRequest>(&bytes) else { | ||
| 197 | + return Ok(refuse(StatusCode::BAD_REQUEST, "bad_request").answer()); | ||
| 198 | + }; | ||
| 199 | + let Ok(size) = i64::try_from(request.size) else { | ||
| 200 | + return Ok(refuse(StatusCode::PAYLOAD_TOO_LARGE, "too_large").answer()); | ||
| 201 | + }; | ||
| 202 | + let folder = | ||
| 203 | + optional_folder(state, &viewer, request.folder_id.as_deref().unwrap_or("")).await?; | ||
| 204 | + let max = max_upload_bytes(state).await?; | ||
| 205 | + let id = new_id(); | ||
| 206 | + let new = NewUpload { | ||
| 207 | + id: id.clone(), | ||
| 208 | + owner: viewer.member.sub.clone(), | ||
| 209 | + folder, | ||
| 210 | + name: upload_name(&request.name), | ||
| 211 | + size, | ||
| 212 | + chunk_size: i64::try_from(CHUNK_BYTES).unwrap_or(i64::MAX), | ||
| 213 | + expires_at: stamp_after(UPLOAD_TTL), | ||
| 214 | + }; | ||
| 215 | + let upload = match state.store.create_upload(new, max).await { | ||
| 216 | + Ok(upload) => upload, | ||
| 217 | + Err(CoreError::Invalid(word)) if word == "too_large" => { | ||
| 218 | + return Ok(refuse(StatusCode::PAYLOAD_TOO_LARGE, "too_large").answer()); | ||
| 219 | + } | ||
| 220 | + Err(CoreError::Conflict(word)) if word == "quota_exceeded" => { | ||
| 221 | + return Ok(refuse(StatusCode::PAYLOAD_TOO_LARGE, "quota_exceeded").answer()); | ||
| 222 | + } | ||
| 223 | + Err(error) => return Err(error.into()), | ||
| 224 | + }; | ||
| 225 | + // The directory is made after the row commits. A crash in between leaves a row with no directory, which | ||
| 226 | + // the sweeper expires; the other order could leave a directory no row names. | ||
| 227 | + let dir = upload_dir(&state.config.data_dir, &upload.id)?; | ||
| 228 | + tokio::fs::DirBuilder::new() | ||
| 229 | + .recursive(true) | ||
| 230 | + .mode(0o700) | ||
| 231 | + .create(&dir) | ||
| 232 | + .await | ||
| 233 | + .map_err(CoreError::from)?; | ||
| 234 | + Ok(json_answer( | ||
| 235 | + StatusCode::CREATED, | ||
| 236 | + json!({ "id": upload.id, "chunk_size": CHUNK_BYTES }), | ||
| 237 | + )) | ||
| 238 | +} | ||
| 239 | + | ||
| 240 | +/// `GET /api/uploads/{id}`: the state of an upload and the chunks it has. | ||
| 241 | +#[route(GET "/api/uploads/{id}")] | ||
| 242 | +async fn upload_status(cx: &Cx) -> Result<Response> { | ||
| 243 | + let state = app_context::<AppState>(cx); | ||
| 244 | + let viewer = match api_viewer(cx).await? { | ||
| 245 | + Ok(viewer) => viewer, | ||
| 246 | + Err(refusal) => return Ok(refusal.answer()), | ||
| 247 | + }; | ||
| 248 | + let id = path_param_segment(cx, "id").to_owned(); | ||
| 249 | + let Some(upload) = state.store.upload(&viewer.member.sub, &id).await? else { | ||
| 250 | + return Ok(refuse(StatusCode::NOT_FOUND, "not_found").answer()); | ||
| 251 | + }; | ||
| 252 | + let dir = upload_dir(&state.config.data_dir, &upload.id)?; | ||
| 253 | + let received = received_chunks(&dir).await?; | ||
| 254 | + let word = if upload.state == "active" && !upload.is_open(&now_stamp()) { | ||
| 255 | + "expired" | ||
| 256 | + } else { | ||
| 257 | + upload.state.as_str() | ||
| 258 | + }; | ||
| 259 | + Ok(json_answer( | ||
| 260 | + StatusCode::OK, | ||
| 261 | + json!({ | ||
| 262 | + "id": upload.id, | ||
| 263 | + "state": word, | ||
| 264 | + "size": upload.size, | ||
| 265 | + "chunk_size": upload.chunk_size, | ||
| 266 | + "received": received, | ||
| 267 | + }), | ||
| 268 | + )) | ||
| 269 | +} | ||
| 270 | + | ||
| 271 | +/// `PUT /api/uploads/{id}/{index}`: stores one chunk. | ||
| 272 | +#[route(PUT "/api/uploads/{id}/{index}")] | ||
| 273 | +async fn put_chunk(cx: &Cx, body: Body) -> Result<Response> { | ||
| 274 | + let state = app_context::<AppState>(cx); | ||
| 275 | + let viewer = match api_viewer(cx).await? { | ||
| 276 | + Ok(viewer) => viewer, | ||
| 277 | + Err(refusal) => return Ok(refusal.answer()), | ||
| 278 | + }; | ||
| 279 | + let id = path_param_segment(cx, "id").to_owned(); | ||
| 280 | + let raw_index = path_param_segment(cx, "index").to_owned(); | ||
| 281 | + let upload = match open_upload(state, &viewer, &id).await? { | ||
| 282 | + Ok(upload) => upload, | ||
| 283 | + Err(refusal) => return Ok(refusal.answer()), | ||
| 284 | + }; | ||
| 285 | + let Ok(index) = raw_index.parse::<u64>() else { | ||
| 286 | + return Ok(refuse(StatusCode::BAD_REQUEST, "bad_index").answer()); | ||
| 287 | + }; | ||
| 288 | + let (size, chunk) = (upload.size as u64, upload.chunk_size as u64); | ||
| 289 | + let Some(expected) = expected_chunk_len(size, chunk, index) else { | ||
| 290 | + return Ok(refuse(StatusCode::BAD_REQUEST, "index_out_of_range").answer()); | ||
| 291 | + }; | ||
| 292 | + let dir = upload_dir(&state.config.data_dir, &upload.id)?; | ||
| 293 | + // The bytes go to a temporary file in the staging directory, which is then renamed onto the index. A | ||
| 294 | + // reader sees either the old chunk or the new one, never a partial write. | ||
| 295 | + let mut staged = match StagedFile::create_in(&dir, expected).await { | ||
| 296 | + Ok(staged) => staged, | ||
| 297 | + Err(CoreError::Io(error)) if error.kind() == std::io::ErrorKind::NotFound => { | ||
| 298 | + return Ok(refuse(StatusCode::NOT_FOUND, "not_found").answer()); | ||
| 299 | + } | ||
| 300 | + Err(error) => return Err(error.into()), | ||
| 301 | + }; | ||
| 302 | + let mut frames = body.into_data_stream(); | ||
| 303 | + let mut received: u64 = 0; | ||
| 304 | + while let Some(frame) = frames.next().await { | ||
| 305 | + let Ok(bytes) = frame else { | ||
| 306 | + staged.abort().await; | ||
| 307 | + return Ok(refuse(StatusCode::BAD_REQUEST, "body_read").answer()); | ||
| 308 | + }; | ||
| 309 | + let len = bytes.len() as u64; | ||
| 310 | + if received + len > expected { | ||
| 311 | + staged.abort().await; | ||
| 312 | + return Ok(refuse(StatusCode::PAYLOAD_TOO_LARGE, "chunk_too_large").answer()); | ||
| 313 | + } | ||
| 314 | + if let Err(error) = staged.write(&bytes).await { | ||
| 315 | + staged.abort().await; | ||
| 316 | + return Err(error.into()); | ||
| 317 | + } | ||
| 318 | + received += len; | ||
| 319 | + } | ||
| 320 | + if received != expected { | ||
| 321 | + staged.abort().await; | ||
| 322 | + return Ok(refuse(StatusCode::BAD_REQUEST, "chunk_length").answer()); | ||
| 323 | + } | ||
| 324 | + let Staged { path, .. } = staged.finish().await?; | ||
| 325 | + let target = chunk_path(&dir, index); | ||
| 326 | + if let Err(error) = tokio::fs::rename(&path, &target).await { | ||
| 327 | + let _ = tokio::fs::remove_file(&path).await; | ||
| 328 | + return Err(CoreError::from(error).into()); | ||
| 329 | + } | ||
| 330 | + // The rename is durable only once the directory entry is: fsync the directory, as the blob store does. | ||
| 331 | + tokio::fs::File::open(&dir) | ||
| 332 | + .await | ||
| 333 | + .map_err(CoreError::from)? | ||
| 334 | + .sync_all() | ||
| 335 | + .await | ||
| 336 | + .map_err(CoreError::from)?; | ||
| 337 | + if !state | ||
| 338 | + .store | ||
| 339 | + .touch_upload(&viewer.member.sub, &upload.id, &stamp_after(UPLOAD_TTL)) | ||
| 340 | + .await? | ||
| 341 | + { | ||
| 342 | + // The upload was finished or cancelled after the check above. Its directory is removed by that | ||
| 343 | + // request or by the sweeper, so this chunk does not outlive it. | ||
| 344 | + return Ok(refuse(StatusCode::CONFLICT, "not_active").answer()); | ||
| 345 | + } | ||
| 346 | + Ok(json_answer(StatusCode::OK, json!({ "index": index }))) | ||
| 347 | +} | ||
| 348 | + | ||
| 349 | +/// Joins the chunks of `dir` into `staged`, in index order, and keeps the first bytes for the sniffer. | ||
| 350 | +async fn join_chunks( | ||
| 351 | + dir: &Path, | ||
| 352 | + count: u64, | ||
| 353 | + staged: &mut StagedFile, | ||
| 354 | + prefix: &mut Vec<u8>, | ||
| 355 | +) -> std::result::Result<(), CoreError> { | ||
| 356 | + let mut buffer = vec![0u8; COPY_BUFFER]; | ||
| 357 | + for index in 0..count { | ||
| 358 | + let mut part = tokio::fs::File::open(chunk_path(dir, index)).await?; | ||
| 359 | + loop { | ||
| 360 | + let read = part.read(&mut buffer).await?; | ||
| 361 | + if read == 0 { | ||
| 362 | + break; | ||
| 363 | + } | ||
| 364 | + if prefix.len() < SNIFF_BYTES { | ||
| 365 | + let take = (SNIFF_BYTES - prefix.len()).min(read); | ||
| 366 | + prefix.extend_from_slice(&buffer[..take]); | ||
| 367 | + } | ||
| 368 | + staged.write(&buffer[..read]).await?; | ||
| 369 | + } | ||
| 370 | + } | ||
| 371 | + Ok(()) | ||
| 372 | +} | ||
| 373 | + | ||
| 374 | +/// `POST /api/uploads/{id}/finish`: joins the chunks into the file. | ||
| 375 | +#[route(POST "/api/uploads/{id}/finish")] | ||
| 376 | +async fn finish_upload(cx: &Cx) -> Result<Response> { | ||
| 377 | + let state = app_context::<AppState>(cx); | ||
| 378 | + let viewer = match api_viewer(cx).await? { | ||
| 379 | + Ok(viewer) => viewer, | ||
| 380 | + Err(refusal) => return Ok(refusal.answer()), | ||
| 381 | + }; | ||
| 382 | + let id = path_param_segment(cx, "id").to_owned(); | ||
| 383 | + let upload = match open_upload(state, &viewer, &id).await? { | ||
| 384 | + Ok(upload) => upload, | ||
| 385 | + Err(refusal) => return Ok(refusal.answer()), | ||
| 386 | + }; | ||
| 387 | + let data_dir = state.config.data_dir.clone(); | ||
| 388 | + let dir = upload_dir(&data_dir, &upload.id)?; | ||
| 389 | + let (size, chunk) = (upload.size as u64, upload.chunk_size as u64); | ||
| 390 | + let count = chunk_count(size, chunk); | ||
| 391 | + let received = received_chunks(&dir).await?; | ||
| 392 | + let missing: Vec<u64> = (0..count) | ||
| 393 | + .filter(|index| received.binary_search(index).is_err()) | ||
| 394 | + .collect(); | ||
| 395 | + if !missing.is_empty() { | ||
| 396 | + return Ok(json_answer( | ||
| 397 | + StatusCode::CONFLICT, | ||
| 398 | + json!({ "error": "chunks_missing", "missing": missing }), | ||
| 399 | + )); | ||
| 400 | + } | ||
| 401 | + | ||
| 402 | + let mut staged = StagedFile::create(&data_dir, size).await?; | ||
| 403 | + let mut prefix = Vec::with_capacity(SNIFF_BYTES); | ||
| 404 | + if let Err(error) = join_chunks(&dir, count, &mut staged, &mut prefix).await { | ||
| 405 | + staged.abort().await; | ||
| 406 | + return Err(error.into()); | ||
| 407 | + } | ||
| 408 | + let Staged { path, sha256, .. } = staged.finish().await?; | ||
| 409 | + | ||
| 410 | + // The bytes are durable at their key before the row that names them commits (architecture 3). | ||
| 411 | + let file_id = new_id(); | ||
| 412 | + let key = files_blob_key(&file_id); | ||
| 413 | + if let Err(error) = state.blobs.put_file(&key, &path).await { | ||
| 414 | + let _ = tokio::fs::remove_file(&path).await; | ||
| 415 | + return Err(error.into()); | ||
| 416 | + } | ||
| 417 | + let new = NewFile { | ||
| 418 | + id: file_id, | ||
| 419 | + owner: viewer.member.sub.clone(), | ||
| 420 | + folder: upload.folder_id.clone(), | ||
| 421 | + name: upload.name.clone(), | ||
| 422 | + mime: sniff(&prefix), | ||
| 423 | + size: upload.size, | ||
| 424 | + sha256, | ||
| 425 | + staged_claims: 0, | ||
| 426 | + }; | ||
| 427 | + match state | ||
| 428 | + .store | ||
| 429 | + .finish_upload(&viewer.member.sub, &upload.id, new) | ||
| 430 | + .await | ||
| 431 | + { | ||
| 432 | + Ok(file) => { | ||
| 433 | + if let Err(error) = remove_upload_dir(&data_dir, &upload.id).await { | ||
| 434 | + tracing::warn!(upload = %upload.id, error = %error, "upload: staging directory not removed"); | ||
| 435 | + } | ||
| 436 | + changed(state, &viewer.member.sub); | ||
| 437 | + Ok(json_answer(StatusCode::OK, json!({ "file_id": file.id }))) | ||
| 438 | + } | ||
| 439 | + Err(error) => { | ||
| 440 | + // No row names these bytes now, so they go. | ||
| 441 | + let _ = state.blobs.delete(&key).await; | ||
| 442 | + match error { | ||
| 443 | + CoreError::Conflict(word) if word == "quota_exceeded" => { | ||
| 444 | + Ok(refuse(StatusCode::PAYLOAD_TOO_LARGE, "quota_exceeded").answer()) | ||
| 445 | + } | ||
| 446 | + CoreError::Conflict(word) if word == "upload_not_active" => { | ||
| 447 | + Ok(refuse(StatusCode::CONFLICT, "not_active").answer()) | ||
| 448 | + } | ||
| 449 | + CoreError::Invalid(word) if word == "size_mismatch" => { | ||
| 450 | + Ok(refuse(StatusCode::CONFLICT, "size_mismatch").answer()) | ||
| 451 | + } | ||
| 452 | + CoreError::NotFound => Ok(refuse(StatusCode::NOT_FOUND, "not_found").answer()), | ||
| 453 | + other => Err(other.into()), | ||
| 454 | + } | ||
| 455 | + } | ||
| 456 | + } | ||
| 457 | +} | ||
| 458 | + | ||
| 459 | +/// `DELETE /api/uploads/{id}`: cancels an open upload and removes what it staged. | ||
| 460 | +#[route(DELETE "/api/uploads/{id}")] | ||
| 461 | +async fn cancel_upload(cx: &Cx) -> Result<Response> { | ||
| 462 | + let state = app_context::<AppState>(cx); | ||
| 463 | + let viewer = match api_viewer(cx).await? { | ||
| 464 | + Ok(viewer) => viewer, | ||
| 465 | + Err(refusal) => return Ok(refusal.answer()), | ||
| 466 | + }; | ||
| 467 | + let id = path_param_segment(cx, "id").to_owned(); | ||
| 468 | + let Some(upload) = state.store.upload(&viewer.member.sub, &id).await? else { | ||
| 469 | + return Ok(refuse(StatusCode::NOT_FOUND, "not_found").answer()); | ||
| 470 | + }; | ||
| 471 | + if !state | ||
| 472 | + .store | ||
| 473 | + .abort_upload(&viewer.member.sub, &upload.id) | ||
| 474 | + .await? | ||
| 475 | + { | ||
| 476 | + return Ok(refuse(StatusCode::CONFLICT, "not_active").answer()); | ||
| 477 | + } | ||
| 478 | + if let Err(error) = remove_upload_dir(&state.config.data_dir, &upload.id).await { | ||
| 479 | + tracing::warn!(upload = %upload.id, error = %error, "upload: staging directory not removed"); | ||
| 480 | + } | ||
| 481 | + Ok(json_answer(StatusCode::OK, json!({ "state": "aborted" }))) | ||
| 482 | +} | ||
| 483 | + | ||
| 484 | +#[cfg(test)] | ||
| 485 | +mod tests { | ||
| 486 | + use super::*; | ||
| 487 | + use crate::auth::SESSION_COOKIE; | ||
| 488 | + use crate::auth::test_support::signed_in; | ||
| 489 | + use crate::boot::{router, test_state}; | ||
| 490 | + use http::Request; | ||
| 491 | + use http::header::COOKIE; | ||
| 492 | + use in_core::quota::DEFAULT_MEMBER_QUOTA; | ||
| 493 | + use topcoat::router::{Body, to_bytes}; | ||
| 494 | + | ||
| 495 | + /// One call to the API as the session `token`, with the CSRF header `csrf` when given. Returns the | ||
| 496 | + /// status and the JSON body. | ||
| 497 | + async fn call( | ||
| 498 | + state: &AppState, | ||
| 499 | + method: &str, | ||
| 500 | + path: &str, | ||
| 501 | + token: &str, | ||
| 502 | + csrf: Option<&str>, | ||
| 503 | + body: Vec<u8>, | ||
| 504 | + ) -> (StatusCode, Value) { | ||
| 505 | + let mut request = Request::builder() | ||
| 506 | + .method(method) | ||
| 507 | + .uri(path) | ||
| 508 | + .header(COOKIE, format!("{SESSION_COOKIE}={token}")); | ||
| 509 | + if let Some(csrf) = csrf { | ||
| 510 | + request = request.header(CSRF_HEADER, csrf); | ||
| 511 | + } | ||
| 512 | + let request = request.body(Body::from(body)).expect("request"); | ||
| 513 | + let response = router(state.clone()).handle(request).await; | ||
| 514 | + let status = response.status(); | ||
| 515 | + let bytes = to_bytes(response.into_body(), 64 * 1024) | ||
| 516 | + .await | ||
| 517 | + .expect("body"); | ||
| 518 | + ( | ||
| 519 | + status, | ||
| 520 | + serde_json::from_slice(&bytes).unwrap_or(Value::Null), | ||
| 521 | + ) | ||
| 522 | + } | ||
| 523 | + | ||
| 524 | + /// Starts an upload of `size` bytes as `ann`, and returns its id. | ||
| 525 | + async fn start(state: &AppState, token: &str, size: u64) -> String { | ||
| 526 | + let body = json!({ "name": "clip.bin", "size": size }).to_string(); | ||
| 527 | + let (status, value) = call( | ||
| 528 | + state, | ||
| 529 | + "POST", | ||
| 530 | + "/api/uploads", | ||
| 531 | + token, | ||
| 532 | + Some("csrf-ann"), | ||
| 533 | + body.into_bytes(), | ||
| 534 | + ) | ||
| 535 | + .await; | ||
| 536 | + assert_eq!(status, StatusCode::CREATED); | ||
| 537 | + value["id"].as_str().expect("an id").to_owned() | ||
| 538 | + } | ||
| 539 | + | ||
| 540 | + #[tokio::test] | ||
| 541 | + async fn chunk_bounds_are_enforced() { | ||
| 542 | + let (_dir, state) = test_state().await; | ||
| 543 | + let token = signed_in(&state, "ann", DEFAULT_MEMBER_QUOTA).await; | ||
| 544 | + let id = start(&state, &token, 10).await; | ||
| 545 | + let put = |index: u64| format!("/api/uploads/{id}/{index}"); | ||
| 546 | + | ||
| 547 | + // One chunk of ten bytes: index 1 does not exist. | ||
| 548 | + let (status, value) = call( | ||
| 549 | + &state, | ||
| 550 | + "PUT", | ||
| 551 | + &put(1), | ||
| 552 | + &token, | ||
| 553 | + Some("csrf-ann"), | ||
| 554 | + vec![0; 10], | ||
| 555 | + ) | ||
| 556 | + .await; | ||
| 557 | + assert_eq!(status, StatusCode::BAD_REQUEST); | ||
| 558 | + assert_eq!(value["error"], "index_out_of_range"); | ||
| 559 | + | ||
| 560 | + // The last chunk must be exactly the remainder: longer is refused as too large, shorter as bad. | ||
| 561 | + let (status, value) = call( | ||
| 562 | + &state, | ||
| 563 | + "PUT", | ||
| 564 | + &put(0), | ||
| 565 | + &token, | ||
| 566 | + Some("csrf-ann"), | ||
| 567 | + vec![0; 11], | ||
| 568 | + ) | ||
| 569 | + .await; | ||
| 570 | + assert_eq!(status, StatusCode::PAYLOAD_TOO_LARGE); | ||
| 571 | + assert_eq!(value["error"], "chunk_too_large"); | ||
| 572 | + let (status, value) = | ||
| 573 | + call(&state, "PUT", &put(0), &token, Some("csrf-ann"), vec![0; 9]).await; | ||
| 574 | + assert_eq!(status, StatusCode::BAD_REQUEST); | ||
| 575 | + assert_eq!(value["error"], "chunk_length"); | ||
| 576 | + } | ||
| 577 | + | ||
| 578 | + #[tokio::test] | ||
| 579 | + async fn a_whole_upload_becomes_a_file_that_can_be_downloaded() { | ||
| 580 | + let (_dir, state) = test_state().await; | ||
| 581 | + let token = signed_in(&state, "ann", DEFAULT_MEMBER_QUOTA).await; | ||
| 582 | + let id = start(&state, &token, 10).await; | ||
| 583 | + let (status, _) = call( | ||
| 584 | + &state, | ||
| 585 | + "PUT", | ||
| 586 | + &format!("/api/uploads/{id}/0"), | ||
| 587 | + &token, | ||
| 588 | + Some("csrf-ann"), | ||
| 589 | + b"0123456789".to_vec(), | ||
| 590 | + ) | ||
| 591 | + .await; | ||
| 592 | + assert_eq!(status, StatusCode::OK); | ||
| 593 | + let (status, value) = call( | ||
| 594 | + &state, | ||
| 595 | + "POST", | ||
| 596 | + &format!("/api/uploads/{id}/finish"), | ||
| 597 | + &token, | ||
| 598 | + Some("csrf-ann"), | ||
| 599 | + Vec::new(), | ||
| 600 | + ) | ||
| 601 | + .await; | ||
| 602 | + assert_eq!(status, StatusCode::OK); | ||
| 603 | + let file_id = value["file_id"].as_str().expect("a file id").to_owned(); | ||
| 604 | + | ||
| 605 | + let request = Request::get(format!("/file/{file_id}?dl=1")) | ||
| 606 | + .header(COOKIE, format!("{SESSION_COOKIE}={token}")) | ||
| 607 | + .body(Body::empty()) | ||
| 608 | + .expect("request"); | ||
| 609 | + let response = router(state.clone()).handle(request).await; | ||
| 610 | + assert_eq!(response.status(), StatusCode::OK); | ||
| 611 | + let bytes = to_bytes(response.into_body(), 64 * 1024) | ||
| 612 | + .await | ||
| 613 | + .expect("body"); | ||
| 614 | + assert_eq!(&bytes[..], b"0123456789"); | ||
| 615 | + } | ||
| 616 | + | ||
| 617 | + #[tokio::test] | ||
| 618 | + async fn finishing_with_a_missing_chunk_is_a_conflict() { | ||
| 619 | + let (_dir, state) = test_state().await; | ||
| 620 | + let token = signed_in(&state, "ann", DEFAULT_MEMBER_QUOTA).await; | ||
| 621 | + // Two chunks: the first is 8 MiB, so the test sends only the one-byte last chunk. | ||
| 622 | + let id = start(&state, &token, CHUNK_BYTES + 1).await; | ||
| 623 | + let (status, _) = call( | ||
| 624 | + &state, | ||
| 625 | + "PUT", | ||
| 626 | + &format!("/api/uploads/{id}/1"), | ||
| 627 | + &token, | ||
| 628 | + Some("csrf-ann"), | ||
| 629 | + vec![7], | ||
| 630 | + ) | ||
| 631 | + .await; | ||
| 632 | + assert_eq!(status, StatusCode::OK); | ||
| 633 | + let (status, value) = call( | ||
| 634 | + &state, | ||
| 635 | + "POST", | ||
| 636 | + &format!("/api/uploads/{id}/finish"), | ||
| 637 | + &token, | ||
| 638 | + Some("csrf-ann"), | ||
| 639 | + Vec::new(), | ||
| 640 | + ) | ||
| 641 | + .await; | ||
| 642 | + assert_eq!(status, StatusCode::CONFLICT); | ||
| 643 | + assert_eq!(value["error"], "chunks_missing"); | ||
| 644 | + assert_eq!(value["missing"], json!([0])); | ||
| 645 | + } | ||
| 646 | + | ||
| 647 | + #[tokio::test] | ||
| 648 | + async fn another_members_upload_is_not_found_and_a_bad_csrf_token_is_forbidden() { | ||
| 649 | + let (_dir, state) = test_state().await; | ||
| 650 | + let ann = signed_in(&state, "ann", DEFAULT_MEMBER_QUOTA).await; | ||
| 651 | + let bob = signed_in(&state, "bob", DEFAULT_MEMBER_QUOTA).await; | ||
| 652 | + let id = start(&state, &ann, 10).await; | ||
| 653 | + | ||
| 654 | + let (status, _) = call( | ||
| 655 | + &state, | ||
| 656 | + "GET", | ||
| 657 | + &format!("/api/uploads/{id}"), | ||
| 658 | + &bob, | ||
| 659 | + Some("csrf-bob"), | ||
| 660 | + Vec::new(), | ||
| 661 | + ) | ||
| 662 | + .await; | ||
| 663 | + assert_eq!(status, StatusCode::NOT_FOUND); | ||
| 664 | + let (status, _) = call( | ||
| 665 | + &state, | ||
| 666 | + "PUT", | ||
| 667 | + &format!("/api/uploads/{id}/0"), | ||
| 668 | + &bob, | ||
| 669 | + Some("csrf-bob"), | ||
| 670 | + vec![0; 10], | ||
| 671 | + ) | ||
| 672 | + .await; | ||
| 673 | + assert_eq!(status, StatusCode::NOT_FOUND); | ||
| 674 | + let (status, _) = call( | ||
| 675 | + &state, | ||
| 676 | + "POST", | ||
| 677 | + &format!("/api/uploads/{id}/finish"), | ||
| 678 | + &bob, | ||
| 679 | + Some("csrf-bob"), | ||
| 680 | + Vec::new(), | ||
| 681 | + ) | ||
| 682 | + .await; | ||
| 683 | + assert_eq!(status, StatusCode::NOT_FOUND); | ||
| 684 | + let (status, _) = call( | ||
| 685 | + &state, | ||
| 686 | + "DELETE", | ||
| 687 | + &format!("/api/uploads/{id}"), | ||
| 688 | + &bob, | ||
| 689 | + Some("csrf-bob"), | ||
| 690 | + Vec::new(), | ||
| 691 | + ) | ||
| 692 | + .await; | ||
| 693 | + assert_eq!(status, StatusCode::NOT_FOUND); | ||
| 694 | + | ||
| 695 | + let (status, value) = call( | ||
| 696 | + &state, | ||
| 697 | + "GET", | ||
| 698 | + &format!("/api/uploads/{id}"), | ||
| 699 | + &ann, | ||
| 700 | + Some("csrf-wrong"), | ||
| 701 | + Vec::new(), | ||
| 702 | + ) | ||
| 703 | + .await; | ||
| 704 | + assert_eq!(status, StatusCode::FORBIDDEN); | ||
| 705 | + assert_eq!(value["error"], "csrf"); | ||
| 706 | + let (status, _) = call( | ||
| 707 | + &state, | ||
| 708 | + "GET", | ||
| 709 | + &format!("/api/uploads/{id}"), | ||
| 710 | + &ann, | ||
| 711 | + None, | ||
| 712 | + Vec::new(), | ||
| 713 | + ) | ||
| 714 | + .await; | ||
| 715 | + assert_eq!(status, StatusCode::FORBIDDEN); | ||
| 716 | + } | ||
| 717 | +} | ||
crates/in-web/src/assets.rsmodified+10 -0
| @@ -18,9 +18,13 @@ pub const NAV_JS_HREF: &str = concat!("/assets/nav.js?v=", env!("IN_NAV_JS_V")); | |||
| 18 | /// Link to the script of individual pages. | 18 | /// Link to the script of individual pages. |
| 19 | pub const PAGES_JS_HREF: &str = concat!("/assets/pages.js?v=", env!("IN_PAGES_JS_V")); | 19 | pub const PAGES_JS_HREF: &str = concat!("/assets/pages.js?v=", env!("IN_PAGES_JS_V")); |
| 20 | 20 | ||
| 21 | +/// Link to the upload queue of the drive pages. Only those pages load it. | ||
| 22 | +pub const DRIVE_JS_HREF: &str = concat!("/assets/drive.js?v=", env!("IN_DRIVE_JS_V")); | ||
| 23 | + | ||
| 21 | const MAIN_CSS: &str = include_str!(concat!(env!("OUT_DIR"), "/main.css")); | 24 | const MAIN_CSS: &str = include_str!(concat!(env!("OUT_DIR"), "/main.css")); |
| 22 | const NAV_JS: &str = include_str!("../assets/nav.js"); | 25 | const NAV_JS: &str = include_str!("../assets/nav.js"); |
| 23 | const PAGES_JS: &str = include_str!("../assets/pages.js"); | 26 | const PAGES_JS: &str = include_str!("../assets/pages.js"); |
| 27 | +const DRIVE_JS: &str = include_str!("../assets/drive.js"); | ||
| 24 | const OFFLINE_HTML: &str = include_str!("../assets/offline.html"); | 28 | const OFFLINE_HTML: &str = include_str!("../assets/offline.html"); |
| 25 | const SW_JS: &str = include_str!("../assets/sw.js"); | 29 | const SW_JS: &str = include_str!("../assets/sw.js"); |
| 26 | 30 | ||
| @@ -59,6 +63,12 @@ async fn pages_js() -> Result<Asset> { | |||
| 59 | Ok(asset("text/javascript; charset=utf-8", IMMUTABLE, PAGES_JS)) | 63 | Ok(asset("text/javascript; charset=utf-8", IMMUTABLE, PAGES_JS)) |
| 60 | } | 64 | } |
| 61 | 65 | ||
| 66 | +/// `GET /assets/drive.js`. | ||
| 67 | +#[route(GET "/assets/drive.js")] | ||
| 68 | +async fn drive_js() -> Result<Asset> { | ||
| 69 | + Ok(asset("text/javascript; charset=utf-8", IMMUTABLE, DRIVE_JS)) | ||
| 70 | +} | ||
| 71 | + | ||
| 62 | /// `GET /assets/offline.html`. Also precached by the service worker. | 72 | /// `GET /assets/offline.html`. Also precached by the service worker. |
| 63 | #[route(GET "/assets/offline.html")] | 73 | #[route(GET "/assets/offline.html")] |
| 64 | async fn offline_html() -> Result<Asset> { | 74 | async fn offline_html() -> Result<Asset> { |
crates/in-web/src/auth.rsmodified+51 -0
| @@ -227,3 +227,54 @@ mod tests { | |||
| 227 | assert_eq!(safe_next(&format!("{longest}a")), None); | 227 | assert_eq!(safe_next(&format!("{longest}a")), None); |
| 228 | } | 228 | } |
| 229 | } | 229 | } |
| 230 | + | ||
| 231 | +/// Helpers for the in-process router tests: a member with a live session. | ||
| 232 | +#[cfg(test)] | ||
| 233 | +pub(crate) mod test_support { | ||
| 234 | + use super::*; | ||
| 235 | + use in_core::quota::DEFAULT_MEMBER_QUOTA; | ||
| 236 | + use in_core::store::members::MemberFields; | ||
| 237 | + use in_core::store::new_id; | ||
| 238 | + use in_core::store::sessions::NewSession; | ||
| 239 | + use in_core::time::stamp_after; | ||
| 240 | + use in_core::token::{generate_token, hash_token}; | ||
| 241 | + | ||
| 242 | + /// Makes `sub` a member with `quota` bytes and a live session. Returns the session cookie value; the | ||
| 243 | + /// session's CSRF token is `csrf-<sub>`. | ||
| 244 | + pub async fn signed_in(state: &AppState, sub: &str, quota: i64) -> String { | ||
| 245 | + state | ||
| 246 | + .store | ||
| 247 | + .upsert_member_from_claims( | ||
| 248 | + &MemberFields { | ||
| 249 | + sub: sub.into(), | ||
| 250 | + email: format!("{sub}@example.test"), | ||
| 251 | + name: sub.into(), | ||
| 252 | + is_admin: false, | ||
| 253 | + locale: "en".into(), | ||
| 254 | + zoneinfo: "UTC".into(), | ||
| 255 | + picture_version: 0, | ||
| 256 | + im_updated_at: String::new(), | ||
| 257 | + }, | ||
| 258 | + DEFAULT_MEMBER_QUOTA, | ||
| 259 | + ) | ||
| 260 | + .await | ||
| 261 | + .expect("member"); | ||
| 262 | + state.store.set_quota(sub, quota).await.expect("quota"); | ||
| 263 | + let token = generate_token(); | ||
| 264 | + state | ||
| 265 | + .store | ||
| 266 | + .create_session(NewSession { | ||
| 267 | + sub: sub.into(), | ||
| 268 | + token_hash: hash_token(&token), | ||
| 269 | + csrf_token: format!("csrf-{sub}"), | ||
| 270 | + im_sid: format!("im-{sub}-{}", new_id()), | ||
| 271 | + expires_at: stamp_after(SESSION_TTL), | ||
| 272 | + ip: None, | ||
| 273 | + user_agent: None, | ||
| 274 | + id_token_sealed: None, | ||
| 275 | + }) | ||
| 276 | + .await | ||
| 277 | + .expect("session"); | ||
| 278 | + token | ||
| 279 | + } | ||
| 280 | +} | ||
crates/in-web/src/boot.rsmodified+2 -0
| @@ -30,6 +30,7 @@ use crate::pages::files; | |||
| 30 | use crate::pages::not_found::NotFoundLayer; | 30 | use crate::pages::not_found::NotFoundLayer; |
| 31 | use crate::security::{self, SecurityHeaders}; | 31 | use crate::security::{self, SecurityHeaders}; |
| 32 | use crate::state::AppState; | 32 | use crate::state::AppState; |
| 33 | +use crate::sweeper; | ||
| 33 | 34 | ||
| 34 | /// Name of the instance key file inside the data directory. | 35 | /// Name of the instance key file inside the data directory. |
| 35 | const KEY_FILE: &str = "in.key"; | 36 | const KEY_FILE: &str = "in.key"; |
| @@ -47,6 +48,7 @@ pub async fn serve(config_path: &Path) -> Result<()> { | |||
| 47 | if state.oidc.is_some() { | 48 | if state.oidc.is_some() { |
| 48 | tokio::spawn(directory::run(state.clone(), stop_rx.clone())); | 49 | tokio::spawn(directory::run(state.clone(), stop_rx.clone())); |
| 49 | } | 50 | } |
| 51 | + tokio::spawn(sweeper::run(state.clone(), stop_rx.clone())); | ||
| 50 | 52 | ||
| 51 | let listener = TcpListener::bind(listen).await.map_err(|error| { | 53 | let listener = TcpListener::bind(listen).await.map_err(|error| { |
| 52 | std::io::Error::new(error.kind(), format!("cannot bind {listen}: {error}")) | 54 | std::io::Error::new(error.kind(), format!("cannot bind {listen}: {error}")) |
crates/in-web/src/i18n/drive.rsmodified+24 -12
| @@ -80,14 +80,20 @@ pub enum DK { | |||
| 80 | PickHint, | 80 | PickHint, |
| 81 | /// Cancel a form and go back. | 81 | /// Cancel a form and go back. |
| 82 | Back, | 82 | Back, |
| 83 | - /// Field label: the place the file is in. | ||
| 84 | - Location, | ||
| 85 | /// Field label: the MIME type. | 83 | /// Field label: the MIME type. |
| 86 | MimeType, | 84 | MimeType, |
| 87 | - /// Field label: when it was uploaded. | 85 | + /// Drop overlay text on a drive page. |
| 88 | - Uploaded, | 86 | + UploadDrop, |
| 89 | - /// Field label: how many times it was downloaded. | 87 | + /// Queue row: an upload in progress. |
| 90 | - Downloads, | 88 | + UploadUploading, |
| 89 | + /// Queue row: an upload that finished. | ||
| 90 | + UploadDone, | ||
| 91 | + /// Queue row: an upload that failed. The server's word follows it. | ||
| 92 | + UploadFailed, | ||
| 93 | + /// Queue row: an upload that was cancelled. | ||
| 94 | + UploadCanceled, | ||
| 95 | + /// Queue row: the button that cancels an upload. | ||
| 96 | + UploadCancel, | ||
| 91 | /// Link to view the bytes in the browser. | 97 | /// Link to view the bytes in the browser. |
| 92 | OpenRaw, | 98 | OpenRaw, |
| 93 | /// Accessible name of the breadcrumb trail. | 99 | /// Accessible name of the breadcrumb trail. |
| @@ -213,14 +219,20 @@ pub fn d(lang: Lang, key: DK) -> &'static str { | |||
| 213 | (DK::PickHint, Lang::Tr) => "Taşınacağı klasörü seçin.", | 219 | (DK::PickHint, Lang::Tr) => "Taşınacağı klasörü seçin.", |
| 214 | (DK::Back, Lang::En) => "Back", | 220 | (DK::Back, Lang::En) => "Back", |
| 215 | (DK::Back, Lang::Tr) => "Geri", | 221 | (DK::Back, Lang::Tr) => "Geri", |
| 216 | - (DK::Location, Lang::En) => "Location", | ||
| 217 | - (DK::Location, Lang::Tr) => "Konum", | ||
| 218 | (DK::MimeType, Lang::En) => "Type", | 222 | (DK::MimeType, Lang::En) => "Type", |
| 219 | (DK::MimeType, Lang::Tr) => "Tür", | 223 | (DK::MimeType, Lang::Tr) => "Tür", |
| 220 | - (DK::Uploaded, Lang::En) => "Uploaded", | 224 | + (DK::UploadDrop, Lang::En) => "Drop files anywhere on this page to upload them.", |
| 221 | - (DK::Uploaded, Lang::Tr) => "Yüklendi", | 225 | + (DK::UploadDrop, Lang::Tr) => "Yüklemek için dosyaları bu sayfaya bırakın.", |
| 222 | - (DK::Downloads, Lang::En) => "Downloads", | 226 | + (DK::UploadUploading, Lang::En) => "Uploading", |
| 223 | - (DK::Downloads, Lang::Tr) => "İndirme", | 227 | + (DK::UploadUploading, Lang::Tr) => "Yükleniyor", |
| 228 | + (DK::UploadDone, Lang::En) => "Uploaded", | ||
| 229 | + (DK::UploadDone, Lang::Tr) => "Yüklendi", | ||
| 230 | + (DK::UploadFailed, Lang::En) => "Upload failed", | ||
| 231 | + (DK::UploadFailed, Lang::Tr) => "Yükleme başarısız", | ||
| 232 | + (DK::UploadCanceled, Lang::En) => "Cancelled", | ||
| 233 | + (DK::UploadCanceled, Lang::Tr) => "İptal edildi", | ||
| 234 | + (DK::UploadCancel, Lang::En) => "Cancel", | ||
| 235 | + (DK::UploadCancel, Lang::Tr) => "İptal", | ||
| 224 | (DK::OpenRaw, Lang::En) => "Open in the browser", | 236 | (DK::OpenRaw, Lang::En) => "Open in the browser", |
| 225 | (DK::OpenRaw, Lang::Tr) => "Tarayıcıda aç", | 237 | (DK::OpenRaw, Lang::Tr) => "Tarayıcıda aç", |
| 226 | (DK::Location2, Lang::En) => "Location", | 238 | (DK::Location2, Lang::En) => "Location", |
crates/in-web/src/main.rsmodified+2 -0
| @@ -4,6 +4,7 @@ | |||
| 4 | //! operator command line, which is not built yet. The configuration file is the `--config` path, | 4 | //! operator command line, which is not built yet. The configuration file is the `--config` path, |
| 5 | //! then `IN_CONFIG`, then `config/in.toml`. Exit status 0 is success, 1 a failure, 2 a usage error. | 5 | //! then `IN_CONFIG`, then `config/in.toml`. Exit status 0 is success, 1 a failure, 2 a usage error. |
| 6 | 6 | ||
| 7 | +mod api; | ||
| 7 | mod assets; | 8 | mod assets; |
| 8 | mod auth; | 9 | mod auth; |
| 9 | mod boot; | 10 | mod boot; |
| @@ -16,6 +17,7 @@ mod pages; | |||
| 16 | mod security; | 17 | mod security; |
| 17 | mod serve_bytes; | 18 | mod serve_bytes; |
| 18 | mod state; | 19 | mod state; |
| 20 | +mod sweeper; | ||
| 19 | mod views; | 21 | mod views; |
| 20 | 22 | ||
| 21 | use std::path::{Path, PathBuf}; | 23 | use std::path::{Path, PathBuf}; |
crates/in-web/src/pages/drive.rsmodified+89 -40
| @@ -1,6 +1,7 @@ | |||
| 1 | -//! The drive's listing pages: the root (`/`), a folder (`/f/{id}`), search (`/search`), the live stream | 1 | +//! The drive's listing pages: the root (`/drive`, which also answers search with `?q=`), a folder |
| 2 | -//! that refreshes an open listing, the folder writes (create, rename, move, trash) and the folder move | 2 | +//! (`/drive/{folder_id}`), the live stream that refreshes an open listing, the folder writes (create, |
| 3 | -//! picker. The file pages live in `files.rs`, the trash in `trash.rs`. | 3 | +//! rename, move, trash) and the folder move picker. The file bytes live in `files.rs`, the viewer in |
| 4 | +//! `view.rs`, the trash in `trash.rs`. | ||
| 4 | //! | 5 | //! |
| 5 | //! Authorization: each item is loaded by id and passed to `authz::authorize`. A refusal to see the item | 6 | //! Authorization: each item is loaded by id and passed to `authz::authorize`. A refusal to see the item |
| 6 | //! is `404`, so a foreign or missing id looks the same as no item at all. A refusal to change an item the | 7 | //! is `404`, so a foreign or missing id looks the same as no item at all. A refusal to change an item the |
| @@ -38,6 +39,9 @@ use crate::views::{ViewerInfo, empty_state, shell}; | |||
| 38 | /// How many search hits each kind shows. | 39 | /// How many search hits each kind shows. |
| 39 | const SEARCH_LIMIT: usize = 100; | 40 | const SEARCH_LIMIT: usize = 100; |
| 40 | 41 | ||
| 42 | +/// The drive's root listing. `/` sends a signed-in person here, and forms return here by default. | ||
| 43 | +pub const DRIVE_HOME: &str = "/drive"; | ||
| 44 | + | ||
| 41 | /// The query of a listing page. Every field is optional; unknown ones are ignored. | 45 | /// The query of a listing page. Every field is optional; unknown ones are ignored. |
| 42 | #[derive(Debug, Default, Deserialize)] | 46 | #[derive(Debug, Default, Deserialize)] |
| 43 | #[serde(default)] | 47 | #[serde(default)] |
| @@ -46,7 +50,7 @@ pub struct ListQuery { | |||
| 46 | pub sort: String, | 50 | pub sort: String, |
| 47 | /// `asc` (default) or `desc`. | 51 | /// `asc` (default) or `desc`. |
| 48 | pub dir: String, | 52 | pub dir: String, |
| 49 | - /// The search text, on `/search` only. | 53 | + /// The search text, on `/drive` only. |
| 50 | pub q: String, | 54 | pub q: String, |
| 51 | /// A notice word from a finished action. | 55 | /// A notice word from a finished action. |
| 52 | pub notice: String, | 56 | pub notice: String, |
| @@ -305,11 +309,15 @@ pub async fn folder_board( | |||
| 305 | let descending = query.dir == "desc"; | 309 | let descending = query.dir == "desc"; |
| 306 | sort_listing(&mut listing, sort, descending); | 310 | sort_listing(&mut listing, sort, descending); |
| 307 | let (base, live, back) = match folder.as_deref() { | 311 | let (base, live, back) = match folder.as_deref() { |
| 308 | - None => ("/?".to_owned(), "/live/drive".to_owned(), "/".to_owned()), | 312 | + None => ( |
| 313 | + format!("{DRIVE_HOME}?"), | ||
| 314 | + "/live/drive".to_owned(), | ||
| 315 | + DRIVE_HOME.to_owned(), | ||
| 316 | + ), | ||
| 309 | Some(id) => ( | 317 | Some(id) => ( |
| 310 | - format!("/f/{id}?"), | 318 | + format!("/drive/{id}?"), |
| 311 | format!("/live/drive?folder={id}"), | 319 | format!("/live/drive?folder={id}"), |
| 312 | - format!("/f/{id}"), | 320 | + format!("/drive/{id}"), |
| 313 | ), | 321 | ), |
| 314 | }; | 322 | }; |
| 315 | Ok(Board { | 323 | Ok(Board { |
| @@ -356,24 +364,14 @@ pub async fn search_board( | |||
| 356 | sort, | 364 | sort, |
| 357 | descending, | 365 | descending, |
| 358 | csrf: viewer.session.csrf_token.clone(), | 366 | csrf: viewer.session.csrf_token.clone(), |
| 359 | - back: format!("/search?q={enc}"), | 367 | + back: format!("{DRIVE_HOME}?q={enc}"), |
| 360 | notice: query.notice.clone(), | 368 | notice: query.notice.clone(), |
| 361 | refusal: query.refusal.clone(), | 369 | refusal: query.refusal.clone(), |
| 362 | live: None, | 370 | live: None, |
| 363 | - base: format!("/search?q={enc}&"), | 371 | + base: format!("{DRIVE_HOME}?q={enc}&"), |
| 364 | }) | 372 | }) |
| 365 | } | 373 | } |
| 366 | 374 | ||
| 367 | -/// The drive root's listing for a signed-in viewer. The start page uses it. | ||
| 368 | -pub async fn root_board( | ||
| 369 | - state: &AppState, | ||
| 370 | - viewer: &Viewer, | ||
| 371 | - query: &ListQuery, | ||
| 372 | - lang: Lang, | ||
| 373 | -) -> Result<Board> { | ||
| 374 | - folder_board(state, viewer, None, query, lang).await | ||
| 375 | -} | ||
| 376 | - | ||
| 377 | /// The main content of a listing page: the heading, the trail, the flash line, the forms that create | 375 | /// The main content of a listing page: the heading, the trail, the flash line, the forms that create |
| 378 | /// and upload, and the table. Used by the drive pages and by the start page for a signed-in viewer. | 376 | /// and upload, and the table. Used by the drive pages and by the start page for a signed-in viewer. |
| 379 | #[component] | 377 | #[component] |
| @@ -390,7 +388,7 @@ pub async fn drive_board(lang: Lang, board: &Board) -> Result<impl View> { | |||
| 390 | } | 388 | } |
| 391 | flash(lang: lang, notice: board.notice.as_str(), refusal: board.refusal.as_str()) | 389 | flash(lang: lang, notice: board.notice.as_str(), refusal: board.refusal.as_str()) |
| 392 | <div class="toolbar"> | 390 | <div class="toolbar"> |
| 393 | - <form method="get" action="/search" class="inline-form" role="search"> | 391 | + <form method="get" action="/drive" class="inline-form" role="search"> |
| 394 | <label class="sr-only" for="drive-search">(d(lang, DK::SearchPlaceholder))</label> | 392 | <label class="sr-only" for="drive-search">(d(lang, DK::SearchPlaceholder))</label> |
| 395 | <input id="drive-search" type="search" name="q" value=(search_value.as_str()) placeholder=(d(lang, DK::SearchPlaceholder))> | 393 | <input id="drive-search" type="search" name="q" value=(search_value.as_str()) placeholder=(d(lang, DK::SearchPlaceholder))> |
| 396 | <button class="button" type="submit">(d(lang, DK::Search))</button> | 394 | <button class="button" type="submit">(d(lang, DK::Search))</button> |
| @@ -404,7 +402,11 @@ pub async fn drive_board(lang: Lang, board: &Board) -> Result<impl View> { | |||
| 404 | <input id="new-folder" name="name" maxlength="255" required="" placeholder=(d(lang, DK::NewFolder))> | 402 | <input id="new-folder" name="name" maxlength="255" required="" placeholder=(d(lang, DK::NewFolder))> |
| 405 | <button class="button" type="submit">(d(lang, DK::Create))</button> | 403 | <button class="button" type="submit">(d(lang, DK::Create))</button> |
| 406 | </form> | 404 | </form> |
| 407 | - <form method="post" action="/files" enctype="multipart/form-data" class="inline-form"> | 405 | + <form method="post" action="/files" enctype="multipart/form-data" class="inline-form" |
| 406 | + data-upload-form="" data-hard="" data-csrf=(board.csrf.as_str()) data-folder=(parent.as_str()) | ||
| 407 | + data-label-drop=(d(lang, DK::UploadDrop)) data-label-uploading=(d(lang, DK::UploadUploading)) | ||
| 408 | + data-label-done=(d(lang, DK::UploadDone)) data-label-failed=(d(lang, DK::UploadFailed)) | ||
| 409 | + data-label-canceled=(d(lang, DK::UploadCanceled)) data-label-cancel=(d(lang, DK::UploadCancel))> | ||
| 408 | <input type="hidden" name="csrf" value=(board.csrf.as_str())> | 410 | <input type="hidden" name="csrf" value=(board.csrf.as_str())> |
| 409 | <input type="hidden" name="back" value=(board.back.as_str())> | 411 | <input type="hidden" name="back" value=(board.back.as_str())> |
| 410 | <input type="hidden" name="folder" value=(parent.as_str())> | 412 | <input type="hidden" name="folder" value=(parent.as_str())> |
| @@ -455,37 +457,38 @@ fn fingerprint(listing: &Listing) -> String { | |||
| 455 | text | 457 | text |
| 456 | } | 458 | } |
| 457 | 459 | ||
| 458 | -/// `GET /f/{folder_id}`: one folder's listing. | 460 | +/// `GET /drive`: the drive root. With `?q=` it is the search over the viewer's own items instead. |
| 459 | -#[page("/f/{folder_id}")] | 461 | +#[page("/drive")] |
| 460 | -async fn folder_page(cx: &Cx) -> Result<impl View> { | 462 | +async fn drive_root_page(cx: &Cx) -> Result<impl View> { |
| 461 | let state = app_context::<AppState>(cx); | 463 | let state = app_context::<AppState>(cx); |
| 462 | let viewer = require_member(cx).await?; | 464 | let viewer = require_member(cx).await?; |
| 463 | let lang = viewer_lang(cx, &viewer); | 465 | let lang = viewer_lang(cx, &viewer); |
| 464 | - let folder_id = path_param_segment(cx, "folder_id").to_owned(); | ||
| 465 | let query: ListQuery = parse_query_params(cx).unwrap_or_default(); | 466 | let query: ListQuery = parse_query_params(cx).unwrap_or_default(); |
| 466 | - let board = folder_board(state, &viewer, Some(folder_id), &query, lang).await?; | 467 | + let board = if query.q.trim().is_empty() { |
| 468 | + folder_board(state, &viewer, None, &query, lang).await? | ||
| 469 | + } else { | ||
| 470 | + search_board(state, &viewer, &query, lang).await? | ||
| 471 | + }; | ||
| 467 | let info = ViewerInfo::of(&viewer); | 472 | let info = ViewerInfo::of(&viewer); |
| 468 | Ok(view! { | 473 | Ok(view! { |
| 469 | - shell(title: board.heading.as_str(), lang: lang, viewer: Some(&info), | 474 | + shell(title: board.heading.as_str(), lang: lang, viewer: Some(&info), drive_js: true, |
| 470 | drive_board(lang: lang, board: &board) | 475 | drive_board(lang: lang, board: &board) |
| 471 | ) | 476 | ) |
| 472 | }) | 477 | }) |
| 473 | } | 478 | } |
| 474 | 479 | ||
| 475 | -/// `GET /search?q=`: the viewer's own items whose names contain the text. Blank text goes to the root. | 480 | +/// `GET /drive/{folder_id}`: one folder's listing. |
| 476 | -#[page("/search")] | 481 | +#[page("/drive/{folder_id}")] |
| 477 | -async fn search_page(cx: &Cx) -> Result<impl View> { | 482 | +async fn folder_page(cx: &Cx) -> Result<impl View> { |
| 478 | let state = app_context::<AppState>(cx); | 483 | let state = app_context::<AppState>(cx); |
| 479 | let viewer = require_member(cx).await?; | 484 | let viewer = require_member(cx).await?; |
| 480 | let lang = viewer_lang(cx, &viewer); | 485 | let lang = viewer_lang(cx, &viewer); |
| 486 | + let folder_id = path_param_segment(cx, "folder_id").to_owned(); | ||
| 481 | let query: ListQuery = parse_query_params(cx).unwrap_or_default(); | 487 | let query: ListQuery = parse_query_params(cx).unwrap_or_default(); |
| 482 | - if query.q.trim().is_empty() { | 488 | + let board = folder_board(state, &viewer, Some(folder_id), &query, lang).await?; |
| 483 | - return Err(see_other("/").into()); | ||
| 484 | - } | ||
| 485 | - let board = search_board(state, &viewer, &query, lang).await?; | ||
| 486 | let info = ViewerInfo::of(&viewer); | 489 | let info = ViewerInfo::of(&viewer); |
| 487 | Ok(view! { | 490 | Ok(view! { |
| 488 | - shell(title: board.heading.as_str(), lang: lang, viewer: Some(&info), | 491 | + shell(title: board.heading.as_str(), lang: lang, viewer: Some(&info), drive_js: true, |
| 489 | drive_board(lang: lang, board: &board) | 492 | drive_board(lang: lang, board: &board) |
| 490 | ) | 493 | ) |
| 491 | }) | 494 | }) |
| @@ -540,7 +543,7 @@ struct CreateFolderForm { | |||
| 540 | async fn create_folder(cx: &Cx, Form(form): Form<CreateFolderForm>) -> Result<SeeOther> { | 543 | async fn create_folder(cx: &Cx, Form(form): Form<CreateFolderForm>) -> Result<SeeOther> { |
| 541 | let state = app_context::<AppState>(cx); | 544 | let state = app_context::<AppState>(cx); |
| 542 | let viewer = require_csrf(cx, &form.csrf).await?; | 545 | let viewer = require_csrf(cx, &form.csrf).await?; |
| 543 | - let back = back_or(&form.back, "/"); | 546 | + let back = back_or(&form.back, DRIVE_HOME); |
| 544 | let parent = optional_folder(state, &viewer, &form.parent).await?; | 547 | let parent = optional_folder(state, &viewer, &form.parent).await?; |
| 545 | let name = match validate_name(&form.name) { | 548 | let name = match validate_name(&form.name) { |
| 546 | Ok(name) => name, | 549 | Ok(name) => name, |
| @@ -579,7 +582,7 @@ async fn rename_folder(cx: &Cx, Form(form): Form<ItemForm>) -> Result<SeeOther> | |||
| 579 | let state = app_context::<AppState>(cx); | 582 | let state = app_context::<AppState>(cx); |
| 580 | let viewer = require_csrf(cx, &form.csrf).await?; | 583 | let viewer = require_csrf(cx, &form.csrf).await?; |
| 581 | let id = path_param_segment(cx, "id").to_owned(); | 584 | let id = path_param_segment(cx, "id").to_owned(); |
| 582 | - let back = back_or(&form.back, "/"); | 585 | + let back = back_or(&form.back, DRIVE_HOME); |
| 583 | folder_for(state, &viewer, &id, Action::Write).await?; | 586 | folder_for(state, &viewer, &id, Action::Write).await?; |
| 584 | let name = match validate_name(&form.name) { | 587 | let name = match validate_name(&form.name) { |
| 585 | Ok(name) => name, | 588 | Ok(name) => name, |
| @@ -605,7 +608,7 @@ async fn move_folder(cx: &Cx, Form(form): Form<ItemForm>) -> Result<SeeOther> { | |||
| 605 | let state = app_context::<AppState>(cx); | 608 | let state = app_context::<AppState>(cx); |
| 606 | let viewer = require_csrf(cx, &form.csrf).await?; | 609 | let viewer = require_csrf(cx, &form.csrf).await?; |
| 607 | let id = path_param_segment(cx, "id").to_owned(); | 610 | let id = path_param_segment(cx, "id").to_owned(); |
| 608 | - let back = back_or(&form.back, "/"); | 611 | + let back = back_or(&form.back, DRIVE_HOME); |
| 609 | folder_for(state, &viewer, &id, Action::Write).await?; | 612 | folder_for(state, &viewer, &id, Action::Write).await?; |
| 610 | let parent = optional_folder(state, &viewer, &form.parent).await?; | 613 | let parent = optional_folder(state, &viewer, &form.parent).await?; |
| 611 | match state | 614 | match state |
| @@ -627,7 +630,7 @@ async fn trash_folder(cx: &Cx, Form(form): Form<ItemForm>) -> Result<SeeOther> { | |||
| 627 | let state = app_context::<AppState>(cx); | 630 | let state = app_context::<AppState>(cx); |
| 628 | let viewer = require_csrf(cx, &form.csrf).await?; | 631 | let viewer = require_csrf(cx, &form.csrf).await?; |
| 629 | let id = path_param_segment(cx, "id").to_owned(); | 632 | let id = path_param_segment(cx, "id").to_owned(); |
| 630 | - let back = back_or(&form.back, "/"); | 633 | + let back = back_or(&form.back, DRIVE_HOME); |
| 631 | folder_for(state, &viewer, &id, Action::Write).await?; | 634 | folder_for(state, &viewer, &id, Action::Write).await?; |
| 632 | match state.store.trash_folder(&viewer.member.sub, &id).await { | 635 | match state.store.trash_folder(&viewer.member.sub, &id).await { |
| 633 | Ok(()) => { | 636 | Ok(()) => { |
| @@ -650,7 +653,7 @@ async fn pick_folder(cx: &Cx) -> Result<impl View> { | |||
| 650 | let all = state.store.live_folders(&viewer.member.sub).await?; | 653 | let all = state.store.live_folders(&viewer.member.sub).await?; |
| 651 | let rows = tree_rows(&all, Some(&id)); | 654 | let rows = tree_rows(&all, Some(&id)); |
| 652 | let action = format!("/folders/{id}/move"); | 655 | let action = format!("/folders/{id}/move"); |
| 653 | - let back = format!("/f/{id}"); | 656 | + let back = format!("/drive/{id}"); |
| 654 | let csrf = viewer.session.csrf_token.clone(); | 657 | let csrf = viewer.session.csrf_token.clone(); |
| 655 | let info = ViewerInfo::of(&viewer); | 658 | let info = ViewerInfo::of(&viewer); |
| 656 | let title = d(lang, DK::MoveTo); | 659 | let title = d(lang, DK::MoveTo); |
| @@ -700,3 +703,49 @@ pub async fn pick_body( | |||
| 700 | </section> | 703 | </section> |
| 701 | }) | 704 | }) |
| 702 | } | 705 | } |
| 706 | + | ||
| 707 | +#[cfg(test)] | ||
| 708 | +mod tests { | ||
| 709 | + use crate::auth::SESSION_COOKIE; | ||
| 710 | + use crate::auth::test_support::signed_in; | ||
| 711 | + use crate::boot::{router, test_state}; | ||
| 712 | + use http::Request; | ||
| 713 | + use http::header::{COOKIE, LOCATION}; | ||
| 714 | + use in_core::quota::DEFAULT_MEMBER_QUOTA; | ||
| 715 | + use topcoat::router::{Body, to_bytes}; | ||
| 716 | + | ||
| 717 | + #[tokio::test] | ||
| 718 | + async fn the_start_page_goes_to_the_drive_and_the_drive_lists_its_root() { | ||
| 719 | + let (_dir, state) = test_state().await; | ||
| 720 | + let token = signed_in(&state, "ann", DEFAULT_MEMBER_QUOTA).await; | ||
| 721 | + let get = |path: &str| { | ||
| 722 | + Request::get(path) | ||
| 723 | + .header(COOKIE, format!("{SESSION_COOKIE}={token}")) | ||
| 724 | + .body(Body::empty()) | ||
| 725 | + .expect("request") | ||
| 726 | + }; | ||
| 727 | + | ||
| 728 | + let response = router(state.clone()).handle(get("/")).await; | ||
| 729 | + assert_eq!(response.status(), 303); | ||
| 730 | + assert_eq!(response.headers()[LOCATION], "/drive"); | ||
| 731 | + | ||
| 732 | + let response = router(state.clone()).handle(get("/drive")).await; | ||
| 733 | + assert_eq!(response.status(), 200); | ||
| 734 | + let body = to_bytes(response.into_body(), 1 << 20).await.expect("body"); | ||
| 735 | + let html = String::from_utf8_lossy(&body); | ||
| 736 | + assert!( | ||
| 737 | + html.contains("data-upload-form"), | ||
| 738 | + "the upload form carries the queue hooks" | ||
| 739 | + ); | ||
| 740 | + assert!( | ||
| 741 | + html.contains("/assets/drive.js?v="), | ||
| 742 | + "the upload script is loaded on the drive" | ||
| 743 | + ); | ||
| 744 | + | ||
| 745 | + // A folder id that is not ours looks like no folder at all. | ||
| 746 | + let response = router(state.clone()) | ||
| 747 | + .handle(get("/drive/01h0000000000000000000000z")) | ||
| 748 | + .await; | ||
| 749 | + assert_eq!(response.status(), 404); | ||
| 750 | + } | ||
| 751 | +} | ||
crates/in-web/src/pages/files.rsmodified+35 -155
| @@ -1,6 +1,6 @@ | |||
| 1 | -//! The file pages: the upload (`POST /files`), the file page (`/file/{id}`), its bytes | 1 | +//! The file routes: the small upload (`POST /files`), the bytes of a file (`GET /file/{id}`, through |
| 2 | -//! (`/file/{id}/download` and `/file/{id}/raw`, both through `serve_bytes`), the file writes (rename, | 2 | +//! `serve_bytes`; `?dl=1` forces a download), the file writes (rename, move, trash) and the file move |
| 3 | -//! move, trash) and the file move picker. | 3 | +//! picker. The viewer page of a file is `view.rs`; the chunked upload API is `api/upload.rs`. |
| 4 | //! | 4 | //! |
| 5 | //! An upload streams. Each file part goes to a staging file under `data_dir/tmp` while its SHA-256 and | 5 | //! An upload streams. Each file part goes to a staging file under `data_dir/tmp` while its SHA-256 and |
| 6 | //! its first bytes are taken; the sniffed type decides the MIME type, never the uploader's claim. The quota | 6 | //! its first bytes are taken; the sniffed type decides the MIME type, never the uploader's claim. The quota |
| @@ -15,6 +15,7 @@ use in_core::sniff::sniff; | |||
| 15 | use in_core::staging::{Staged, StagedFile}; | 15 | use in_core::staging::{Staged, StagedFile}; |
| 16 | use in_core::store::files::{File, NewFile, files_blob_key}; | 16 | use in_core::store::files::{File, NewFile, files_blob_key}; |
| 17 | use in_core::store::new_id; | 17 | use in_core::store::new_id; |
| 18 | +use serde::Deserialize; | ||
| 18 | use topcoat::Result; | 19 | use topcoat::Result; |
| 19 | use topcoat::context::{Cx, app_context}; | 20 | use topcoat::context::{Cx, app_context}; |
| 20 | use topcoat::router::content::Form; | 21 | use topcoat::router::content::Form; |
| @@ -23,18 +24,16 @@ use topcoat::router::error::{SeeOther, bad_request, forbidden, not_found, see_ot | |||
| 23 | use topcoat::router::page; | 24 | use topcoat::router::page; |
| 24 | use topcoat::router::request::headers; | 25 | use topcoat::router::request::headers; |
| 25 | use topcoat::router::{parse_query_params, path_param_segment, route}; | 26 | use topcoat::router::{parse_query_params, path_param_segment, route}; |
| 26 | -use topcoat::view::{View, component, view}; | 27 | +use topcoat::view::{View, view}; |
| 27 | 28 | ||
| 28 | use crate::auth::{Viewer, require_csrf, require_member}; | 29 | use crate::auth::{Viewer, require_csrf, require_member}; |
| 29 | -use crate::i18n::Lang; | ||
| 30 | use crate::i18n::drive::{DK, d}; | 30 | use crate::i18n::drive::{DK, d}; |
| 31 | use crate::pages::drive::{ | 31 | use crate::pages::drive::{ |
| 32 | - ItemForm, ListQuery, back_or, changed, check, done, optional_folder, pick_body, refusal_word, | 32 | + DRIVE_HOME, ItemForm, back_or, changed, check, done, optional_folder, pick_body, refusal_word, |
| 33 | refused, tree_rows, viewer_lang, with_param, | 33 | refused, tree_rows, viewer_lang, with_param, |
| 34 | }; | 34 | }; |
| 35 | use crate::serve_bytes::{ByteAnswer, ByteSource, Disposition, counts_as_download, serve_bytes}; | 35 | use crate::serve_bytes::{ByteAnswer, ByteSource, Disposition, counts_as_download, serve_bytes}; |
| 36 | use crate::state::AppState; | 36 | use crate::state::AppState; |
| 37 | -use crate::views::drive::{flash, size_text, stamp_text}; | ||
| 38 | use crate::views::{ViewerInfo, shell}; | 37 | use crate::views::{ViewerInfo, shell}; |
| 39 | 38 | ||
| 40 | /// How many leading bytes of an upload the sniffer reads. Enough for every signature it knows. | 39 | /// How many leading bytes of an upload the sniffer reads. Enough for every signature it knows. |
| @@ -212,9 +211,9 @@ async fn upload(cx: &Cx, mut multipart: Multipart) -> Result<SeeOther> { | |||
| 212 | return Err(forbidden().into()); | 211 | return Err(forbidden().into()); |
| 213 | }; | 212 | }; |
| 214 | let default_back = if folder_raw.trim().is_empty() { | 213 | let default_back = if folder_raw.trim().is_empty() { |
| 215 | - "/".to_owned() | 214 | + DRIVE_HOME.to_owned() |
| 216 | } else { | 215 | } else { |
| 217 | - format!("/f/{}", folder_raw.trim()) | 216 | + format!("/drive/{}", folder_raw.trim()) |
| 218 | }; | 217 | }; |
| 219 | let back = back_or(&back, &default_back); | 218 | let back = back_or(&back, &default_back); |
| 220 | if stored > 0 { | 219 | if stored > 0 { |
| @@ -229,101 +228,31 @@ async fn upload(cx: &Cx, mut multipart: Multipart) -> Result<SeeOther> { | |||
| 229 | Ok(done(&back, "uploaded")) | 228 | Ok(done(&back, "uploaded")) |
| 230 | } | 229 | } |
| 231 | 230 | ||
| 232 | -/// The file page's content: its details, the links to its bytes and, for the owner of a live file, the | 231 | +/// The query of `GET /file/{id}`. `dl=1` asks for the bytes as a download. |
| 233 | -/// actions. | 232 | +#[derive(Debug, Default, Deserialize)] |
| 234 | -#[component] | 233 | +#[serde(default)] |
| 235 | -pub async fn file_body( | 234 | +struct BytesQuery { |
| 236 | - lang: Lang, | 235 | + /// `1` forces an attachment; anything else shows the bytes when their type allows it. |
| 237 | - file: &File, | 236 | + dl: String, |
| 238 | - location: &str, | ||
| 239 | - csrf: &str, | ||
| 240 | - writable: bool, | ||
| 241 | - notice: &str, | ||
| 242 | - refusal: &str, | ||
| 243 | -) -> Result<impl View> { | ||
| 244 | - let back = format!("/file/{}", file.id); | ||
| 245 | - let move_page = format!("/files/{}/pick", file.id); | ||
| 246 | - let rename_action = format!("/files/{}/rename", file.id); | ||
| 247 | - let trash_action = format!("/files/{}/trash", file.id); | ||
| 248 | - let download_url = format!("/file/{}/download", file.id); | ||
| 249 | - let raw_url = format!("/file/{}/raw", file.id); | ||
| 250 | - Ok(view! { | ||
| 251 | - <section class="drive file-page"> | ||
| 252 | - <h1>(file.name.as_str())</h1> | ||
| 253 | - flash(lang: lang, notice: notice, refusal: refusal) | ||
| 254 | - <dl class="details"> | ||
| 255 | - <dt>(d(lang, DK::Location))</dt><dd>(location)</dd> | ||
| 256 | - <dt>(d(lang, DK::Size))</dt><dd>(size_text(file.size))</dd> | ||
| 257 | - <dt>(d(lang, DK::MimeType))</dt><dd>(file.mime.as_str())</dd> | ||
| 258 | - <dt>(d(lang, DK::Uploaded))</dt><dd>(stamp_text(&file.created_at))</dd> | ||
| 259 | - <dt>(d(lang, DK::Downloads))</dt><dd>(file.download_count.to_string())</dd> | ||
| 260 | - </dl> | ||
| 261 | - <p class="actions"> | ||
| 262 | - <a class="button primary" href=(download_url)>(d(lang, DK::Download))</a> | ||
| 263 | - <a class="button" href=(raw_url)>(d(lang, DK::OpenRaw))</a> | ||
| 264 | - </p> | ||
| 265 | - if writable { | ||
| 266 | - <form method="post" action=(rename_action) class="inline-form"> | ||
| 267 | - <input type="hidden" name="csrf" value=(csrf)> | ||
| 268 | - <input type="hidden" name="back" value=(back.as_str())> | ||
| 269 | - <label for="rename-file">(d(lang, DK::Rename))</label> | ||
| 270 | - <input id="rename-file" name="name" value=(file.name.as_str()) maxlength="255" required=""> | ||
| 271 | - <button class="button" type="submit">(d(lang, DK::Save))</button> | ||
| 272 | - </form> | ||
| 273 | - <p class="actions"> | ||
| 274 | - <a class="button" href=(move_page)>(d(lang, DK::Move))</a> | ||
| 275 | - <form method="post" action=(trash_action) class="inline-form"> | ||
| 276 | - <input type="hidden" name="csrf" value=(csrf)> | ||
| 277 | - <input type="hidden" name="back" value="/"> | ||
| 278 | - <button class="button danger" type="submit">(d(lang, DK::TrashItem))</button> | ||
| 279 | - </form> | ||
| 280 | - </p> | ||
| 281 | - } | ||
| 282 | - </section> | ||
| 283 | - }) | ||
| 284 | } | 237 | } |
| 285 | 238 | ||
| 286 | -/// `GET /file/{id}`: the file page. | 239 | +/// `GET /file/{id}`: the bytes of a file. Shown in the page when the type allows it, otherwise (and |
| 287 | -#[page("/file/{id}")] | 240 | +/// always with `?dl=1`) saved as a file. A forced download that starts at byte 0 counts once. |
| 288 | -async fn file_page(cx: &Cx) -> Result<impl View> { | 241 | +#[route(GET "/file/{id}")] |
| 242 | +async fn file_bytes(cx: &Cx) -> Result<ByteAnswer> { | ||
| 289 | let state = app_context::<AppState>(cx); | 243 | let state = app_context::<AppState>(cx); |
| 290 | let viewer = require_member(cx).await?; | 244 | let viewer = require_member(cx).await?; |
| 291 | - let lang = viewer_lang(cx, &viewer); | ||
| 292 | let id = path_param_segment(cx, "id").to_owned(); | 245 | let id = path_param_segment(cx, "id").to_owned(); |
| 293 | - let file = file_for(state, &viewer, &id, Action::View).await?; | 246 | + let query: BytesQuery = parse_query_params(cx).unwrap_or_default(); |
| 294 | - let location = match file.folder_id.as_deref() { | 247 | + let download = query.dl == "1"; |
| 295 | - Some(folder) => match state.store.folder(folder).await? { | 248 | + let action = if download { |
| 296 | - Some(row) if row.trashed_at.is_none() => row.name, | 249 | + Action::Download |
| 297 | - _ => d(lang, DK::Drive).to_owned(), | 250 | + } else { |
| 298 | - }, | 251 | + Action::View |
| 299 | - None => d(lang, DK::Drive).to_owned(), | ||
| 300 | }; | 252 | }; |
| 301 | - let writable = | ||
| 302 | - file.trashed_at.is_none() && check(&viewer, &file.owner, false, Action::Write).is_ok(); | ||
| 303 | - let query: ListQuery = parse_query_params(cx).unwrap_or_default(); | ||
| 304 | - let info = ViewerInfo::of(&viewer); | ||
| 305 | - let csrf = viewer.session.csrf_token.clone(); | ||
| 306 | - let title = file.name.clone(); | ||
| 307 | - Ok(view! { | ||
| 308 | - shell(title: title.as_str(), lang: lang, viewer: Some(&info), | ||
| 309 | - file_body(lang: lang, file: &file, location: location.as_str(), csrf: csrf.as_str(), writable: writable, notice: query.notice.as_str(), refusal: query.refusal.as_str()) | ||
| 310 | - ) | ||
| 311 | - }) | ||
| 312 | -} | ||
| 313 | - | ||
| 314 | -/// Serves the bytes of a file the viewer may act on with `action`. | ||
| 315 | -async fn serve_file( | ||
| 316 | - cx: &Cx, | ||
| 317 | - action: Action, | ||
| 318 | - disposition: Disposition, | ||
| 319 | - count: bool, | ||
| 320 | -) -> Result<ByteAnswer> { | ||
| 321 | - let state = app_context::<AppState>(cx); | ||
| 322 | - let viewer = require_member(cx).await?; | ||
| 323 | - let id = path_param_segment(cx, "id").to_owned(); | ||
| 324 | let file = file_for(state, &viewer, &id, action).await?; | 253 | let file = file_for(state, &viewer, &id, action).await?; |
| 325 | let size = u64::try_from(file.size).unwrap_or(0); | 254 | let size = u64::try_from(file.size).unwrap_or(0); |
| 326 | - if count && counts_as_download(headers(cx), &file.sha256, size) { | 255 | + if download && counts_as_download(headers(cx), &file.sha256, size) { |
| 327 | state.store.record_download(&file.id).await?; | 256 | state.store.record_download(&file.id).await?; |
| 328 | } | 257 | } |
| 329 | let source = ByteSource { | 258 | let source = ByteSource { |
| @@ -333,22 +262,14 @@ async fn serve_file( | |||
| 333 | mime: &file.mime, | 262 | mime: &file.mime, |
| 334 | name: &file.name, | 263 | name: &file.name, |
| 335 | }; | 264 | }; |
| 265 | + let disposition = if download { | ||
| 266 | + Disposition::Attachment | ||
| 267 | + } else { | ||
| 268 | + Disposition::Inline | ||
| 269 | + }; | ||
| 336 | serve_bytes(cx, state.blobs.as_ref(), &source, disposition).await | 270 | serve_bytes(cx, state.blobs.as_ref(), &source, disposition).await |
| 337 | } | 271 | } |
| 338 | 272 | ||
| 339 | -/// `GET /file/{id}/download`: the bytes as a download. Counts one download when it starts at byte 0. | ||
| 340 | -#[route(GET "/file/{id}/download")] | ||
| 341 | -async fn download_bytes(cx: &Cx) -> Result<ByteAnswer> { | ||
| 342 | - serve_file(cx, Action::Download, Disposition::Attachment, true).await | ||
| 343 | -} | ||
| 344 | - | ||
| 345 | -/// `GET /file/{id}/raw`: the bytes to show in the browser. The type decides whether they are shown or | ||
| 346 | -/// saved. | ||
| 347 | -#[route(GET "/file/{id}/raw")] | ||
| 348 | -async fn raw_bytes(cx: &Cx) -> Result<ByteAnswer> { | ||
| 349 | - serve_file(cx, Action::View, Disposition::Inline, false).await | ||
| 350 | -} | ||
| 351 | - | ||
| 352 | /// `POST /files/{id}/rename`. | 273 | /// `POST /files/{id}/rename`. |
| 353 | #[route(POST "/files/{id}/rename")] | 274 | #[route(POST "/files/{id}/rename")] |
| 354 | async fn rename_file(cx: &Cx, Form(form): Form<ItemForm>) -> Result<SeeOther> { | 275 | async fn rename_file(cx: &Cx, Form(form): Form<ItemForm>) -> Result<SeeOther> { |
| @@ -424,7 +345,7 @@ async fn pick_file(cx: &Cx) -> Result<impl View> { | |||
| 424 | let all = state.store.live_folders(&viewer.member.sub).await?; | 345 | let all = state.store.live_folders(&viewer.member.sub).await?; |
| 425 | let rows = tree_rows(&all, None); | 346 | let rows = tree_rows(&all, None); |
| 426 | let action = format!("/files/{id}/move"); | 347 | let action = format!("/files/{id}/move"); |
| 427 | - let back = format!("/file/{id}"); | 348 | + let back = format!("/view/{id}"); |
| 428 | let csrf = viewer.session.csrf_token.clone(); | 349 | let csrf = viewer.session.csrf_token.clone(); |
| 429 | let info = ViewerInfo::of(&viewer); | 350 | let info = ViewerInfo::of(&viewer); |
| 430 | let title = d(lang, DK::MoveTo); | 351 | let title = d(lang, DK::MoveTo); |
| @@ -438,56 +359,15 @@ async fn pick_file(cx: &Cx) -> Result<impl View> { | |||
| 438 | #[cfg(test)] | 359 | #[cfg(test)] |
| 439 | mod tests { | 360 | mod tests { |
| 440 | use super::*; | 361 | use super::*; |
| 441 | - use crate::auth::{SESSION_COOKIE, SESSION_TTL}; | 362 | + use crate::auth::SESSION_COOKIE; |
| 363 | + use crate::auth::test_support::signed_in; | ||
| 442 | use crate::boot::{router, test_state}; | 364 | use crate::boot::{router, test_state}; |
| 443 | use http::Request; | 365 | use http::Request; |
| 444 | use http::header::{CONTENT_TYPE, COOKIE}; | 366 | use http::header::{CONTENT_TYPE, COOKIE}; |
| 445 | use in_core::quota::DEFAULT_MEMBER_QUOTA; | 367 | use in_core::quota::DEFAULT_MEMBER_QUOTA; |
| 446 | - use in_core::store::members::MemberFields; | ||
| 447 | use in_core::store::new_id; | 368 | use in_core::store::new_id; |
| 448 | - use in_core::store::sessions::NewSession; | ||
| 449 | - use in_core::time::stamp_after; | ||
| 450 | - use in_core::token::{generate_token, hash_token}; | ||
| 451 | use topcoat::router::Body; | 369 | use topcoat::router::Body; |
| 452 | 370 | ||
| 453 | - /// A member with a session: returns the session cookie value. | ||
| 454 | - async fn signed_in(state: &AppState, sub: &str, quota: i64) -> String { | ||
| 455 | - state | ||
| 456 | - .store | ||
| 457 | - .upsert_member_from_claims( | ||
| 458 | - &MemberFields { | ||
| 459 | - sub: sub.into(), | ||
| 460 | - email: format!("{sub}@example.test"), | ||
| 461 | - name: sub.into(), | ||
| 462 | - is_admin: false, | ||
| 463 | - locale: "en".into(), | ||
| 464 | - zoneinfo: "UTC".into(), | ||
| 465 | - picture_version: 0, | ||
| 466 | - im_updated_at: String::new(), | ||
| 467 | - }, | ||
| 468 | - DEFAULT_MEMBER_QUOTA, | ||
| 469 | - ) | ||
| 470 | - .await | ||
| 471 | - .expect("member"); | ||
| 472 | - state.store.set_quota(sub, quota).await.expect("quota"); | ||
| 473 | - let token = generate_token(); | ||
| 474 | - state | ||
| 475 | - .store | ||
| 476 | - .create_session(NewSession { | ||
| 477 | - sub: sub.into(), | ||
| 478 | - token_hash: hash_token(&token), | ||
| 479 | - csrf_token: format!("csrf-{sub}"), | ||
| 480 | - im_sid: format!("im-{sub}"), | ||
| 481 | - expires_at: stamp_after(SESSION_TTL), | ||
| 482 | - ip: None, | ||
| 483 | - user_agent: None, | ||
| 484 | - id_token_sealed: None, | ||
| 485 | - }) | ||
| 486 | - .await | ||
| 487 | - .expect("session"); | ||
| 488 | - token | ||
| 489 | - } | ||
| 490 | - | ||
| 491 | /// A file stored the way an upload stores it, owned by `owner`. | 371 | /// A file stored the way an upload stores it, owned by `owner`. |
| 492 | async fn stored_file(state: &AppState, owner: &str, name: &str, bytes: &[u8]) -> File { | 372 | async fn stored_file(state: &AppState, owner: &str, name: &str, bytes: &[u8]) -> File { |
| 493 | let mut staged = StagedFile::create(&state.config.data_dir, 1 << 20) | 373 | let mut staged = StagedFile::create(&state.config.data_dir, 1 << 20) |
| @@ -547,7 +427,7 @@ mod tests { | |||
| 547 | let owner_token = signed_in(&state, "ann", DEFAULT_MEMBER_QUOTA).await; | 427 | let owner_token = signed_in(&state, "ann", DEFAULT_MEMBER_QUOTA).await; |
| 548 | let other_token = signed_in(&state, "bob", DEFAULT_MEMBER_QUOTA).await; | 428 | let other_token = signed_in(&state, "bob", DEFAULT_MEMBER_QUOTA).await; |
| 549 | let file = stored_file(&state, "ann", "notes.txt", b"hello").await; | 429 | let file = stored_file(&state, "ann", "notes.txt", b"hello").await; |
| 550 | - let path = format!("/file/{}/download", file.id); | 430 | + let path = format!("/file/{}?dl=1", file.id); |
| 551 | 431 | ||
| 552 | let as_other = Request::get(&path) | 432 | let as_other = Request::get(&path) |
| 553 | .header(COOKIE, format!("{SESSION_COOKIE}={other_token}")) | 433 | .header(COOKIE, format!("{SESSION_COOKIE}={other_token}")) |
| @@ -580,7 +460,7 @@ mod tests { | |||
| 580 | boundary, | 460 | boundary, |
| 581 | &[ | 461 | &[ |
| 582 | ("csrf", None, b"csrf-ann"), | 462 | ("csrf", None, b"csrf-ann"), |
| 583 | - ("back", None, b"/"), | 463 | + ("back", None, b"/drive"), |
| 584 | ("folder", None, b""), | 464 | ("folder", None, b""), |
| 585 | ("files", Some("../../big.bin"), &[7u8; 100]), | 465 | ("files", Some("../../big.bin"), &[7u8; 100]), |
| 586 | ], | 466 | ], |
crates/in-web/src/pages/home.rsmodified+20 -35
| @@ -1,49 +1,34 @@ | |||
| 1 | -//! The start page (`/`). Signed out, it offers sign-in. Signed in, it is the drive root: the same listing | 1 | +//! The start page (`/`). Signed out, it offers sign-in. Signed in, it sends the person to the drive |
| 2 | -//! as `/f/{id}` for the top level, built by `drive.rs`. | 2 | +//! (`/drive`), which is the one place the listing lives. |
| 3 | 3 | ||
| 4 | use topcoat::Result; | 4 | use topcoat::Result; |
| 5 | -use topcoat::context::{Cx, app_context}; | 5 | +use topcoat::context::Cx; |
| 6 | -use topcoat::router::{page, parse_query_params}; | 6 | +use topcoat::router::error::see_other; |
| 7 | +use topcoat::router::page; | ||
| 7 | use topcoat::view::{View, view}; | 8 | use topcoat::view::{View, view}; |
| 8 | 9 | ||
| 9 | use crate::auth::current_member; | 10 | use crate::auth::current_member; |
| 10 | use crate::i18n::lang; | 11 | use crate::i18n::lang; |
| 11 | use crate::i18n::shell::{K, t}; | 12 | use crate::i18n::shell::{K, t}; |
| 12 | -use crate::pages::drive::{ListQuery, drive_board, root_board, viewer_lang}; | 13 | +use crate::pages::drive::DRIVE_HOME; |
| 13 | -use crate::state::AppState; | 14 | +use crate::views::shell; |
| 14 | -use crate::views::{ViewerInfo, shell}; | ||
| 15 | 15 | ||
| 16 | -/// `GET /`. | 16 | +/// `GET /`: the sign-in card when signed out. A signed-in person is redirected to the drive. |
| 17 | #[page("/")] | 17 | #[page("/")] |
| 18 | async fn home(cx: &Cx) -> Result<impl View> { | 18 | async fn home(cx: &Cx) -> Result<impl View> { |
| 19 | - let state = app_context::<AppState>(cx); | 19 | + if current_member(cx).await?.is_some() { |
| 20 | - let viewer = current_member(cx).await?; | 20 | + return Err(see_other(DRIVE_HOME).into()); |
| 21 | - let query: ListQuery = parse_query_params(cx).unwrap_or_default(); | 21 | + } |
| 22 | - let lang = match &viewer { | 22 | + let lang = lang(cx, None); |
| 23 | - Some(viewer) => viewer_lang(cx, viewer), | 23 | + let heading = t(lang, K::SignedOutTitle).to_owned(); |
| 24 | - None => lang(cx, None), | ||
| 25 | - }; | ||
| 26 | - let info = viewer.as_ref().map(ViewerInfo::of); | ||
| 27 | - let board = match &viewer { | ||
| 28 | - Some(viewer) => Some(root_board(state, viewer, &query, lang).await?), | ||
| 29 | - None => None, | ||
| 30 | - }; | ||
| 31 | - let heading = match &board { | ||
| 32 | - Some(board) => board.heading.clone(), | ||
| 33 | - None => t(lang, K::SignedOutTitle).to_owned(), | ||
| 34 | - }; | ||
| 35 | Ok(view! { | 24 | Ok(view! { |
| 36 | - shell(title: heading.as_str(), lang: lang, viewer: info.as_ref(), | 25 | + shell(title: heading.as_str(), lang: lang, viewer: None, |
| 37 | - if let Some(board) = &board { | 26 | + <section class="card"> |
| 38 | - drive_board(lang: lang, board: board) | 27 | + <p class="kicker">"in"</p> |
| 39 | - } else { | 28 | + <h1>(t(lang, K::SignedOutTitle))</h1> |
| 40 | - <section class="card"> | 29 | + <p>(t(lang, K::SignedOutBody))</p> |
| 41 | - <p class="kicker">"in"</p> | 30 | + <a class="button primary" href="/auth/login">(t(lang, K::SignIn))</a> |
| 42 | - <h1>(t(lang, K::SignedOutTitle))</h1> | 31 | + </section> |
| 43 | - <p>(t(lang, K::SignedOutBody))</p> | ||
| 44 | - <a class="button primary" href="/auth/login">(t(lang, K::SignIn))</a> | ||
| 45 | - </section> | ||
| 46 | - } | ||
| 47 | ) | 32 | ) |
| 48 | }) | 33 | }) |
| 49 | } | 34 | } |
crates/in-web/src/pages/mod.rsmodified+1 -0
| @@ -8,3 +8,4 @@ pub mod not_found; | |||
| 8 | pub mod photo; | 8 | pub mod photo; |
| 9 | pub mod sign_in; | 9 | pub mod sign_in; |
| 10 | pub mod trash; | 10 | pub mod trash; |
| 11 | +pub mod view; | ||
crates/in-web/src/pages/trash.rsmodified+4 -2
| @@ -21,7 +21,9 @@ use topcoat::view::{View, component, view}; | |||
| 21 | use crate::auth::{require_csrf, require_member}; | 21 | use crate::auth::{require_csrf, require_member}; |
| 22 | use crate::i18n::Lang; | 22 | use crate::i18n::Lang; |
| 23 | use crate::i18n::drive::{DK, d}; | 23 | use crate::i18n::drive::{DK, d}; |
| 24 | -use crate::pages::drive::{ListQuery, back_or, changed, done, folder_for, refused, viewer_lang}; | 24 | +use crate::pages::drive::{ |
| 25 | + DRIVE_HOME, ListQuery, back_or, changed, done, folder_for, refused, viewer_lang, | ||
| 26 | +}; | ||
| 25 | use crate::pages::files::file_for; | 27 | use crate::pages::files::file_for; |
| 26 | use crate::state::AppState; | 28 | use crate::state::AppState; |
| 27 | use crate::views::drive::{flash, size_text, stamp_text}; | 29 | use crate::views::drive::{flash, size_text, stamp_text}; |
| @@ -269,7 +271,7 @@ async fn trash_items(cx: &Cx, Form(pairs): Form<Vec<(String, String)>>) -> Resul | |||
| 269 | } | 271 | } |
| 270 | } | 272 | } |
| 271 | let viewer = require_csrf(cx, &csrf).await?; | 273 | let viewer = require_csrf(cx, &csrf).await?; |
| 272 | - let back = back_or(&back, "/"); | 274 | + let back = back_or(&back, DRIVE_HOME); |
| 273 | let mut files = Vec::new(); | 275 | let mut files = Vec::new(); |
| 274 | let mut folders = Vec::new(); | 276 | let mut folders = Vec::new(); |
| 275 | for item in &items { | 277 | for item in &items { |
crates/in-web/src/pages/view.rsadded+65 -0
| @@ -0,0 +1,65 @@ | |||
| 1 | +//! The viewer page of a file (`GET /view/{id}`). This is the minimal version: the name, size, type, the | ||
| 2 | +//! last change, and the links to the bytes (shown, and downloaded). The image, video, audio, PDF and | ||
| 3 | +//! text viewers come with the viewer step, and replace the body of this page. | ||
| 4 | +//! | ||
| 5 | +//! Authorization is the file's `View` check (`files::file_for`): a file the viewer may not see is `404`. | ||
| 6 | + | ||
| 7 | +use in_core::authz::Action; | ||
| 8 | +use in_core::store::files::File; | ||
| 9 | +use topcoat::Result; | ||
| 10 | +use topcoat::context::{Cx, app_context}; | ||
| 11 | +use topcoat::router::page; | ||
| 12 | +use topcoat::router::path_param_segment; | ||
| 13 | +use topcoat::view::{View, component, view}; | ||
| 14 | + | ||
| 15 | +use crate::auth::require_member; | ||
| 16 | +use crate::i18n::Lang; | ||
| 17 | +use crate::i18n::drive::{DK, d}; | ||
| 18 | +use crate::pages::drive::viewer_lang; | ||
| 19 | +use crate::pages::files::file_for; | ||
| 20 | +use crate::state::AppState; | ||
| 21 | +use crate::views::drive::{size_text, stamp_text}; | ||
| 22 | +use crate::views::{ViewerInfo, shell}; | ||
| 23 | + | ||
| 24 | +/// The details of a file and the two links to its bytes. | ||
| 25 | +#[component] | ||
| 26 | +pub async fn file_details( | ||
| 27 | + lang: Lang, | ||
| 28 | + file: &File, | ||
| 29 | + open: &str, | ||
| 30 | + download: &str, | ||
| 31 | +) -> Result<impl View> { | ||
| 32 | + Ok(view! { | ||
| 33 | + <section class="drive file-page"> | ||
| 34 | + <h1>(file.name.as_str())</h1> | ||
| 35 | + <dl class="details"> | ||
| 36 | + <dt>(d(lang, DK::Size))</dt><dd>(size_text(file.size))</dd> | ||
| 37 | + <dt>(d(lang, DK::MimeType))</dt><dd>(file.mime.as_str())</dd> | ||
| 38 | + <dt>(d(lang, DK::Modified))</dt><dd>(stamp_text(&file.updated_at))</dd> | ||
| 39 | + </dl> | ||
| 40 | + <p class="actions"> | ||
| 41 | + <a class="button primary" href=(download)>(d(lang, DK::Download))</a> | ||
| 42 | + <a class="button" href=(open)>(d(lang, DK::OpenRaw))</a> | ||
| 43 | + </p> | ||
| 44 | + </section> | ||
| 45 | + }) | ||
| 46 | +} | ||
| 47 | + | ||
| 48 | +/// `GET /view/{id}`. | ||
| 49 | +#[page("/view/{id}")] | ||
| 50 | +async fn view_page(cx: &Cx) -> Result<impl View> { | ||
| 51 | + let state = app_context::<AppState>(cx); | ||
| 52 | + let viewer = require_member(cx).await?; | ||
| 53 | + let lang = viewer_lang(cx, &viewer); | ||
| 54 | + let id = path_param_segment(cx, "id").to_owned(); | ||
| 55 | + let file = file_for(state, &viewer, &id, Action::View).await?; | ||
| 56 | + let info = ViewerInfo::of(&viewer); | ||
| 57 | + let open = format!("/file/{}", file.id); | ||
| 58 | + let download = format!("/file/{}?dl=1", file.id); | ||
| 59 | + let title = file.name.clone(); | ||
| 60 | + Ok(view! { | ||
| 61 | + shell(title: title.as_str(), lang: lang, viewer: Some(&info), | ||
| 62 | + file_details(lang: lang, file: &file, open: open.as_str(), download: download.as_str()) | ||
| 63 | + ) | ||
| 64 | + }) | ||
| 65 | +} | ||
crates/in-web/src/sweeper.rsadded+52 -0
| @@ -0,0 +1,52 @@ | |||
| 1 | +//! The hourly sweeper. It removes what has expired and nothing else: sessions past their expiry, back-channel | ||
| 2 | +//! logout ids past their expiry (the replay guard only needs them while the token could still arrive), and | ||
| 3 | +//! open uploads that were not finished within 24 hours, with their staging directories. | ||
| 4 | +//! | ||
| 5 | +//! Each pass runs once at boot and then every hour, and stops with the shared stop flag. A failed pass is | ||
| 6 | +//! logged and the next one runs as usual; nothing it does is needed for a request to be served correctly. | ||
| 7 | + | ||
| 8 | +use std::time::Duration; | ||
| 9 | + | ||
| 10 | +use in_core::error::Result; | ||
| 11 | +use in_core::staging::remove_upload_dir; | ||
| 12 | +use in_core::time::now_stamp; | ||
| 13 | +use tokio::sync::watch; | ||
| 14 | + | ||
| 15 | +use crate::state::AppState; | ||
| 16 | + | ||
| 17 | +/// Time between two passes: one hour. | ||
| 18 | +pub const SWEEP_EVERY: Duration = Duration::from_secs(60 * 60); | ||
| 19 | + | ||
| 20 | +/// Runs passes until the stop flag is set. | ||
| 21 | +pub async fn run(state: AppState, mut stop: watch::Receiver<bool>) { | ||
| 22 | + loop { | ||
| 23 | + if let Err(error) = sweep(&state).await { | ||
| 24 | + tracing::warn!(error = %error, "sweeper: pass failed"); | ||
| 25 | + } | ||
| 26 | + tokio::select! { | ||
| 27 | + _ = stop.wait_for(|stopped| *stopped) => return, | ||
| 28 | + () = tokio::time::sleep(SWEEP_EVERY) => {} | ||
| 29 | + } | ||
| 30 | + } | ||
| 31 | +} | ||
| 32 | + | ||
| 33 | +/// One pass. The rows go first, in their own transactions; the staging directories of the expired uploads | ||
| 34 | +/// go after, so a request that races the pass finds no row and writes nothing. | ||
| 35 | +pub async fn sweep(state: &AppState) -> Result<()> { | ||
| 36 | + let now = now_stamp(); | ||
| 37 | + let sessions = state.store.sweep_expired_sessions(&now).await?; | ||
| 38 | + let jtis = state.store.sweep_jti(&now).await?; | ||
| 39 | + let uploads = state.store.expire_uploads(&now).await?; | ||
| 40 | + for id in &uploads { | ||
| 41 | + if let Err(error) = remove_upload_dir(&state.config.data_dir, id).await { | ||
| 42 | + tracing::warn!(upload = %id, error = %error, "sweeper: staging directory not removed"); | ||
| 43 | + } | ||
| 44 | + } | ||
| 45 | + tracing::info!( | ||
| 46 | + sessions, | ||
| 47 | + seen_logout_ids = jtis, | ||
| 48 | + expired_uploads = uploads.len(), | ||
| 49 | + "sweeper: pass done" | ||
| 50 | + ); | ||
| 51 | + Ok(()) | ||
| 52 | +} | ||
crates/in-web/src/views/drive.rsmodified+5 -5
| @@ -68,9 +68,9 @@ pub async fn crumbs(lang: Lang, trail: &[Folder]) -> Result<impl View> { | |||
| 68 | Ok(view! { | 68 | Ok(view! { |
| 69 | <nav class="crumbs" aria-label=(d(lang, DK::Location2))> | 69 | <nav class="crumbs" aria-label=(d(lang, DK::Location2))> |
| 70 | <ol> | 70 | <ol> |
| 71 | - <li><a href="/">(d(lang, DK::Drive))</a></li> | 71 | + <li><a href="/drive">(d(lang, DK::Drive))</a></li> |
| 72 | for folder in trail { | 72 | for folder in trail { |
| 73 | - <li><a href=(format!("/f/{}", folder.id))>(folder.name.as_str())</a></li> | 73 | + <li><a href=(format!("/drive/{}", folder.id))>(folder.name.as_str())</a></li> |
| 74 | } | 74 | } |
| 75 | </ol> | 75 | </ol> |
| 76 | </nav> | 76 | </nav> |
| @@ -180,7 +180,7 @@ pub async fn listing_table( | |||
| 180 | for folder in folders { | 180 | for folder in folders { |
| 181 | <tr> | 181 | <tr> |
| 182 | <td><input type="checkbox" name="item" value=(format!("folder:{}", folder.id)) form="bulk-trash" aria-label=(folder.name.as_str())></td> | 182 | <td><input type="checkbox" name="item" value=(format!("folder:{}", folder.id)) form="bulk-trash" aria-label=(folder.name.as_str())></td> |
| 183 | - <td><a href=(format!("/f/{}", folder.id))>(folder.name.as_str())</a></td> | 183 | + <td><a href=(format!("/drive/{}", folder.id))>(folder.name.as_str())</a></td> |
| 184 | <td class="muted">"\u{2014}"</td> | 184 | <td class="muted">"\u{2014}"</td> |
| 185 | <td class="muted">(stamp_text(&folder.updated_at))</td> | 185 | <td class="muted">(stamp_text(&folder.updated_at))</td> |
| 186 | <td>(d(lang, DK::FolderKind))</td> | 186 | <td>(d(lang, DK::FolderKind))</td> |
| @@ -190,12 +190,12 @@ pub async fn listing_table( | |||
| 190 | for file in files { | 190 | for file in files { |
| 191 | <tr> | 191 | <tr> |
| 192 | <td><input type="checkbox" name="item" value=(format!("file:{}", file.id)) form="bulk-trash" aria-label=(file.name.as_str())></td> | 192 | <td><input type="checkbox" name="item" value=(format!("file:{}", file.id)) form="bulk-trash" aria-label=(file.name.as_str())></td> |
| 193 | - <td><a href=(format!("/file/{}", file.id))>(file.name.as_str())</a></td> | 193 | + <td><a href=(format!("/view/{}", file.id))>(file.name.as_str())</a></td> |
| 194 | <td>(size_text(file.size))</td> | 194 | <td>(size_text(file.size))</td> |
| 195 | <td class="muted">(stamp_text(&file.updated_at))</td> | 195 | <td class="muted">(stamp_text(&file.updated_at))</td> |
| 196 | <td>(d(lang, DK::FileKind))</td> | 196 | <td>(d(lang, DK::FileKind))</td> |
| 197 | <td> | 197 | <td> |
| 198 | - <a class="button ghost" href=(format!("/file/{}/download", file.id))>(d(lang, DK::Download))</a> | 198 | + <a class="button ghost" href=(format!("/file/{}?dl=1", file.id))>(d(lang, DK::Download))</a> |
| 199 | row_menu(lang: lang, csrf: csrf, back: back, kind: "file", id: file.id.as_str(), name: file.name.as_str()) | 199 | row_menu(lang: lang, csrf: csrf, back: back, kind: "file", id: file.id.as_str(), name: file.name.as_str()) |
| 200 | </td> | 200 | </td> |
| 201 | </tr> | 201 | </tr> |
crates/in-web/src/views/mod.rsmodified+8 -3
| @@ -6,7 +6,7 @@ | |||
| 6 | use topcoat::Result; | 6 | use topcoat::Result; |
| 7 | use topcoat::view::{Child, View, component, view}; | 7 | use topcoat::view::{Child, View, component, view}; |
| 8 | 8 | ||
| 9 | -use crate::assets::{MAIN_CSS_HREF, NAV_JS_HREF, PAGES_JS_HREF}; | 9 | +use crate::assets::{DRIVE_JS_HREF, MAIN_CSS_HREF, NAV_JS_HREF, PAGES_JS_HREF}; |
| 10 | use crate::auth::Viewer; | 10 | use crate::auth::Viewer; |
| 11 | use crate::i18n::Lang; | 11 | use crate::i18n::Lang; |
| 12 | use crate::i18n::drive::{DK, d}; | 12 | use crate::i18n::drive::{DK, d}; |
| @@ -44,7 +44,8 @@ impl ViewerInfo { | |||
| 44 | } | 44 | } |
| 45 | 45 | ||
| 46 | /// The HTML document around a page. `title` is the page's own title; the document title adds the | 46 | /// The HTML document around a page. `title` is the page's own title; the document title adds the |
| 47 | -/// app name. `child` is the page, placed in `<main>`. | 47 | +/// app name. `child` is the page, placed in `<main>`. `drive_js` adds the upload script, which only the |
| 48 | +/// drive pages need. | ||
| 48 | /// | 49 | /// |
| 49 | /// The topbar has the wordmark on the left, the service switcher in the middle (empty for now) and | 50 | /// The topbar has the wordmark on the left, the service switcher in the middle (empty for now) and |
| 50 | /// the viewer's user menu on the right. The menu's sign-out form opts out of soft navigation, because | 51 | /// the viewer's user menu on the right. The menu's sign-out form opts out of soft navigation, because |
| @@ -54,6 +55,7 @@ pub async fn shell( | |||
| 54 | title: &str, | 55 | title: &str, |
| 55 | lang: Lang, | 56 | lang: Lang, |
| 56 | viewer: Option<&ViewerInfo>, | 57 | viewer: Option<&ViewerInfo>, |
| 58 | + #[default] drive_js: bool, | ||
| 57 | #[default] child: Child<'_>, | 59 | #[default] child: Child<'_>, |
| 58 | ) -> Result<impl View> { | 60 | ) -> Result<impl View> { |
| 59 | let document_title = format!("{title} \u{b7} in"); | 61 | let document_title = format!("{title} \u{b7} in"); |
| @@ -67,6 +69,9 @@ pub async fn shell( | |||
| 67 | <link rel="stylesheet" href=(MAIN_CSS_HREF)> | 69 | <link rel="stylesheet" href=(MAIN_CSS_HREF)> |
| 68 | <script src=(NAV_JS_HREF) defer=""></script> | 70 | <script src=(NAV_JS_HREF) defer=""></script> |
| 69 | <script src=(PAGES_JS_HREF) defer=""></script> | 71 | <script src=(PAGES_JS_HREF) defer=""></script> |
| 72 | + if drive_js { | ||
| 73 | + <script src=(DRIVE_JS_HREF) defer=""></script> | ||
| 74 | + } | ||
| 70 | </head> | 75 | </head> |
| 71 | <body data-restart-text=(t(lang, K::ServerRestarting))> | 76 | <body data-restart-text=(t(lang, K::ServerRestarting))> |
| 72 | <a class="skip-link" href="#main">(t(lang, K::SkipToContent))</a> | 77 | <a class="skip-link" href="#main">(t(lang, K::SkipToContent))</a> |
| @@ -74,7 +79,7 @@ pub async fn shell( | |||
| 74 | <a class="topbar-brand" href="/">"in"</a> | 79 | <a class="topbar-brand" href="/">"in"</a> |
| 75 | <nav class="switcher" aria-label=(t(lang, K::Services))> | 80 | <nav class="switcher" aria-label=(t(lang, K::Services))> |
| 76 | if viewer.is_some() { | 81 | if viewer.is_some() { |
| 77 | - <a href="/">(d(lang, DK::Drive))</a> | 82 | + <a href="/drive">(d(lang, DK::Drive))</a> |
| 78 | <a href="/trash">(d(lang, DK::Trash))</a> | 83 | <a href="/trash">(d(lang, DK::Trash))</a> |
| 79 | } | 84 | } |
| 80 | </nav> | 85 | </nav> |
style/_components.scssmodified+77 -0
| @@ -426,3 +426,80 @@ textarea::placeholder { | |||
| 426 | .trash .table td form { | 426 | .trash .table td form { |
| 427 | display: inline-flex; | 427 | display: inline-flex; |
| 428 | } | 428 | } |
| 429 | + | ||
| 430 | +// --- Upload queue and drop overlay --------------------------------------------------------------- | ||
| 431 | +// The queue panel sits outside <main>, so a soft refresh of the listing does not drop it. The overlay | ||
| 432 | +// shows while files are dragged over a drive page. | ||
| 433 | + | ||
| 434 | +.upload-queue { | ||
| 435 | + position: fixed; | ||
| 436 | + right: var(--space-4); | ||
| 437 | + bottom: var(--space-4); | ||
| 438 | + z-index: 40; | ||
| 439 | + width: min(24rem, calc(100vw - 2 * var(--space-4))); | ||
| 440 | + max-height: 50vh; | ||
| 441 | + overflow: auto; | ||
| 442 | + padding: var(--space-3); | ||
| 443 | + border: 1px solid var(--border); | ||
| 444 | + border-radius: var(--radius-sm); | ||
| 445 | + background: var(--surface); | ||
| 446 | + box-shadow: var(--shadow); | ||
| 447 | +} | ||
| 448 | + | ||
| 449 | +.upload-list { | ||
| 450 | + display: grid; | ||
| 451 | + gap: var(--space-2); | ||
| 452 | + margin: 0; | ||
| 453 | + padding: 0; | ||
| 454 | + list-style: none; | ||
| 455 | +} | ||
| 456 | + | ||
| 457 | +.upload-item { | ||
| 458 | + display: grid; | ||
| 459 | + grid-template-columns: 1fr auto; | ||
| 460 | + gap: var(--space-1) var(--space-2); | ||
| 461 | + align-items: center; | ||
| 462 | + | ||
| 463 | + progress { | ||
| 464 | + grid-column: 1 / -1; | ||
| 465 | + width: 100%; | ||
| 466 | + } | ||
| 467 | + | ||
| 468 | + &[data-state="failed"] .upload-status { | ||
| 469 | + color: var(--danger); | ||
| 470 | + } | ||
| 471 | + | ||
| 472 | + &[data-state="done"] .upload-status { | ||
| 473 | + color: var(--ok); | ||
| 474 | + } | ||
| 475 | +} | ||
| 476 | + | ||
| 477 | +.upload-name { | ||
| 478 | + overflow: hidden; | ||
| 479 | + white-space: nowrap; | ||
| 480 | + text-overflow: ellipsis; | ||
| 481 | +} | ||
| 482 | + | ||
| 483 | +.upload-status { | ||
| 484 | + color: var(--muted); | ||
| 485 | + font-size: 0.875rem; | ||
| 486 | +} | ||
| 487 | + | ||
| 488 | +.drop-overlay { | ||
| 489 | + position: fixed; | ||
| 490 | + inset: var(--space-3); | ||
| 491 | + z-index: 50; | ||
| 492 | + display: none; | ||
| 493 | + align-items: center; | ||
| 494 | + justify-content: center; | ||
| 495 | + border: 2px dashed var(--accent); | ||
| 496 | + border-radius: var(--radius); | ||
| 497 | + background: var(--accent-soft); | ||
| 498 | + color: var(--accent-strong); | ||
| 499 | + font-weight: 600; | ||
| 500 | + pointer-events: none; | ||
| 501 | +} | ||
| 502 | + | ||
| 503 | +.drop-overlay.drop-overlay-show { | ||
| 504 | + display: flex; | ||
| 505 | +} | ||