//! Settings: the reader's profile and quota, plus the admin's user panel. //! //! `GET /settings` renders one rail section at a time (`?section=`, the //! profile when the pair is missing or unknown): the profile with the quota //! usage bar; the reader's own live share links with their revoke buttons — //! including the copy-once banner after a creation (`?created=` on //! the query, rendered once and never stored); and, for an admin, the //! Everyone panel of every account with its quota and disabled flag, plus //! the server address the public links carry. `POST //! /api/settings/quota|disable|base_url` are admin-only: the first sets a //! user's byte quota, the second disables or re-enables them (a disabled //! account reads as signed-out everywhere, the im session untouched, and //! disabling yourself is refused), the third stores the origin share links //! are built from. use crate::i18n::{Key, lang, t}; use crate::layout::{NavPage, topbar}; use crate::server::{ Refusal, app, back_to, require_admin, require_user, share_link_url, share_origin, }; use crate::service::mintable_services; use crate::share::{refusal_banner, refusal_of, share_copy_script}; use in_core::store::{ShareKind, User}; use serde::Deserialize; use topcoat::Result; use topcoat::context::Cx; use topcoat::router::content::Form; use topcoat::router::request::uri; use topcoat::router::{HeaderName, StatusCode, header, page, route}; use topcoat::view::{View, ViewExt, view}; /// Bytes in human units: `512 B`, `1.5 KiB`, `2.0 GiB`. One decimal past /// bytes so a quota line reads at a glance. pub fn human_bytes(bytes: u64) -> String { const UNITS: [&str; 5] = ["B", "KiB", "MiB", "GiB", "TiB"]; let mut value = bytes as f64; let mut unit = 0; while value >= 1024.0 && unit + 1 < UNITS.len() { value /= 1024.0; unit += 1; } if unit == 0 { format!("{bytes} {}", UNITS[unit]) } else { format!("{value:.1} {}", UNITS[unit]) } } /// An age in whole seconds as the card prints it — a short number with /// its unit, the same shape in every language: `45s`, `2m`, `3h`. Empty /// before the first occurrence; the caller sentences it. fn age_text(age: Option) -> String { match age { Some(secs) if secs >= 3600 => format!("{}h", secs / 3600), Some(secs) if secs >= 60 => format!("{}m", secs / 60), Some(secs) => format!("{secs}s"), None => String::new(), } } /// The share of the quota already held, for the usage bar's width. fn quota_percent(user: &User) -> u8 { if user.quota_bytes == 0 { return 100; } (user.used_bytes.saturating_mul(100) / user.quota_bytes).min(100) as u8 } /// One mebibyte / gibibyte in bytes: the only two units the limit forms speak. /// Raw bytes never reach the browser — the panel shows `human_bytes` and the /// forms post a decimal amount plus one of these units, converted back here. const MIB_BYTES: f64 = 1_048_576.0; const GIB_BYTES: f64 = 1_073_741_824.0; /// The `(amount, unit)` pair a human-unit form field defaults to: gibibytes /// once the value reaches one, mebiBytes below it, so `2 GiB` edits as `2` /// GiB rather than `2048` MiB, while a small `512 MiB` cap stays addressable. fn bytes_as_unit(bytes: u64) -> (String, &'static str) { if bytes >= GIB_BYTES as u64 { (trim_amount(bytes as f64 / GIB_BYTES), "GiB") } else { (trim_amount(bytes as f64 / MIB_BYTES), "MiB") } } /// A form amount for a number input: two decimals at most, trailing zeros /// (and a bare point) trimmed, so the field reads `2` and `2.5`, never /// `2.00` or `2.5000000001`. fn trim_amount(value: f64) -> String { let rounded = (value * 100.0).round() / 100.0; let text = format!("{rounded:.2}"); text.trim_end_matches('0').trim_end_matches('.').to_string() } /// The bytes an `(amount, unit)` pair names, or `None` when the pair is not /// a usable quota: an unknown unit, or an amount that is not a finite /// positive number. fn unit_bytes(amount: &str, unit: &str) -> Option { let per = match unit { "MiB" => MIB_BYTES, "GiB" => GIB_BYTES, _ => return None, }; let value: f64 = amount.trim().parse().ok()?; if !value.is_finite() || value < 0.0 { return None; } Some((value * per).round() as u64) } type Redirect = Result<(StatusCode, [(HeaderName, String); 1])>; /// Back to the posting page's section, the refusal (if any) on the query — /// or `saved=` when there was nothing to refuse, the way iz's /// `saved_or_refused` marks a save the page should chip. `nowhere` names /// the section the call is answered on, for a post that arrives without a /// `Referer` to go back to. fn redirect_back(cx: &Cx, nowhere: &str, call: &str, refusal: Option) -> Redirect { let back = back_to(cx, nowhere); let separator = if back.contains('?') { '&' } else { '?' }; let location = match refusal { Some(refusal) => format!("{back}{separator}refusal={}&on={call}", refusal.code()), None => format!("{back}{separator}saved={call}"), }; Ok((StatusCode::SEE_OTHER, [(header::LOCATION, location)])) } #[derive(Deserialize)] struct QuotaForm { user_id: String, #[serde(default)] quota: String, #[serde(default)] quota_unit: String, } /// Sets one account's byte ceiling from a human-unit pair (`quota` amount in /// `quota_unit` MiB/GiB), converted to bytes for the store. The bytes already /// held are untouched — a quota lowered under current usage refuses new /// uploads until the person frees space, rather than deleting anything. #[route(POST "/api/settings/quota")] async fn set_quota(cx: &Cx, Form(input): Form) -> Redirect { if let Err(refusal) = require_admin(cx).await { return redirect_back(cx, "/settings?section=everyone", "quota", Some(refusal)); } // A service account's ceiling is im's to set: the family beat carries // it here. The Everyone row keeps its form so the panel reads // uniformly, but the write refuses — the server-side gate is the one // that holds. let service_target = app(cx) .store .list_service_accounts() .await .map(|accounts| { accounts .iter() .any(|account| account.user_id == input.user_id) }) .unwrap_or(false); if service_target { return redirect_back( cx, "/settings?section=everyone", "quota", Some(Refusal::ServiceQuota), ); } match unit_bytes(&input.quota, &input.quota_unit) { Some(quota_bytes) => match app(cx) .store .set_user_quota(&input.user_id, quota_bytes) .await { Ok(()) => redirect_back(cx, "/settings?section=everyone", "quota", None), Err(error) => redirect_back( cx, "/settings?section=everyone", "quota", Some(refusal_of(error)), ), }, None => redirect_back( cx, "/settings?section=everyone", "quota", Some(Refusal::BadLimit), ), } } #[derive(Deserialize)] struct DisableForm { user_id: String, #[serde(default)] disabled: Option, } /// Disables or re-enables one account. Disabling yourself is refused — the /// install must never be left with no way back in through its only admin. #[route(POST "/api/settings/disable")] async fn set_disabled(cx: &Cx, Form(input): Form) -> Redirect { let admin = match require_admin(cx).await { Ok(admin) => admin, Err(refusal) => { return redirect_back(cx, "/settings?section=everyone", "disable", Some(refusal)); } }; if input.user_id == admin.id { return redirect_back( cx, "/settings?section=everyone", "disable", Some(Refusal::Forbidden), ); } let disabled = match input.disabled.as_deref() { None => true, Some(value) => !matches!( value.trim().to_lowercase().as_str(), "" | "0" | "false" | "no" | "off" ), }; match app(cx) .store .set_user_disabled(&input.user_id, disabled) .await { Ok(()) => redirect_back(cx, "/settings?section=everyone", "disable", None), Err(error) => redirect_back( cx, "/settings?section=everyone", "disable", Some(refusal_of(error)), ), } } #[derive(Deserialize)] struct PreferencesForm { ui: String, theme: String, language: String, } /// The values the interface field offers. const UI_OPTIONS: [&str; 2] = ["instrument", "ledger"]; /// The values the theme field offers. const THEME_OPTIONS: [&str; 2] = ["light", "dark"]; /// The values the language field offers. const LANGUAGE_OPTIONS: [&str; 2] = ["en", "tr"]; /// Writes the reader's own display preferences: interface, theme, language. /// Each field is checked against what its dropdown offers — another value is /// a hand-built post, not a typo, and is refused with the field's own /// refusal, the way iz's `save_profile` answers its preferences block. #[route(POST "/api/settings/preferences")] async fn set_preferences(cx: &Cx, Form(input): Form) -> Redirect { let user = match require_user(cx).await { Ok(user) => user, Err(refusal) => { return redirect_back( cx, "/settings?section=profile", "preferences", Some(refusal), ); } }; if !UI_OPTIONS.contains(&input.ui.as_str()) { return redirect_back( cx, "/settings?section=profile", "preferences", Some(Refusal::BadUi), ); } if !THEME_OPTIONS.contains(&input.theme.as_str()) { return redirect_back( cx, "/settings?section=profile", "preferences", Some(Refusal::BadTheme), ); } if !LANGUAGE_OPTIONS.contains(&input.language.as_str()) { return redirect_back( cx, "/settings?section=profile", "preferences", Some(Refusal::BadLanguage), ); } match app(cx) .store .set_preferences(&user.id, &input.theme, &input.language, &input.ui) .await { Ok(()) => redirect_back(cx, "/settings?section=profile", "preferences", None), Err(error) => redirect_back( cx, "/settings?section=profile", "preferences", Some(refusal_of(error)), ), } } #[derive(Deserialize)] struct BaseUrlForm { #[serde(default)] base_url: String, } /// Stores the origin the public links are built from, in the instance /// `setting` store under `base_url`. While a non-empty value sits there it /// is what [`crate::server::share_origin`] hands every link builder; /// saving empty clears it, and the origin falls back to the config chain. /// A value the boot would refuse is refused here for the same reason — /// [`in_core::Config::validate_base_url`], the very check `parse` runs — /// and the stored setting is left untouched. #[route(POST "/api/settings/base_url")] async fn set_base_url(cx: &Cx, Form(input): Form) -> Redirect { if let Err(refusal) = require_admin(cx).await { return redirect_back(cx, "/settings?section=server", "base_url", Some(refusal)); } let trimmed = input.base_url.trim().to_string(); if !trimmed.is_empty() && in_core::Config::validate_base_url(&trimmed).is_err() { return redirect_back( cx, "/settings?section=server", "base_url", Some(Refusal::BadBaseUrl), ); } match app(cx).store.set_setting("base_url", &trimmed).await { Ok(()) => redirect_back(cx, "/settings?section=server", "base_url", None), Err(error) => redirect_back( cx, "/settings?section=server", "base_url", Some(refusal_of(error)), ), } } #[derive(Deserialize)] struct ServiceAddForm { service: String, name: String, } #[derive(Deserialize)] struct ServiceAction { service: String, } /// Back from a Service keys post, the fresh key's claim ticket on the query. /// The ticket is all the URL ever carries; the shelf holds the key itself. fn redirect_shown(cx: &Cx, ticket: &str) -> Redirect { let back = back_to(cx, "/settings?section=service"); let separator = if back.contains('?') { '&' } else { '?' }; Ok(( StatusCode::SEE_OTHER, [(header::LOCATION, format!("{back}{separator}shown={ticket}"))], )) } /// Mints one service account and its key. The service must be one the /// family mirror names and no key yet covers; the name is what the panel /// prints. The minted key is shown once. #[route(POST "/api/settings/service_add")] async fn service_add(cx: &Cx, Form(input): Form) -> Redirect { if let Err(refusal) = require_admin(cx).await { return redirect_back( cx, "/settings?section=service", "service_add", Some(refusal), ); } let service = input.service.trim(); let name = input.name.trim(); if name.is_empty() { return redirect_back( cx, "/settings?section=service", "service_add", Some(Refusal::BadServiceKey), ); } let mintable = match mintable_services(cx).await { Ok(mintable) => mintable, Err(refusal) => { return redirect_back( cx, "/settings?section=service", "service_add", Some(refusal), ); } }; if !mintable.iter().any(|row| row.key == service) { return redirect_back( cx, "/settings?section=service", "service_add", Some(Refusal::BadServiceKey), ); } let default_quota_bytes = app(cx).config.default_quota_bytes; match app(cx) .store .create_service_account(service, name, default_quota_bytes) .await { Ok(token) => redirect_shown(cx, &crate::server::stash_shown_secret(token)), Err(_) => redirect_back( cx, "/settings?section=service", "service_add", Some(Refusal::Unavailable), ), } } /// Replaces one service's key. The account and its files stay; the fresh /// key is shown once. #[route(POST "/api/settings/service_rotate")] async fn service_rotate(cx: &Cx, Form(input): Form) -> Redirect { if let Err(refusal) = require_admin(cx).await { return redirect_back( cx, "/settings?section=service", "service_rotate", Some(refusal), ); } match app(cx).store.rotate_service_key(&input.service).await { Ok(Some(token)) => redirect_shown(cx, &crate::server::stash_shown_secret(token)), Ok(None) => redirect_back( cx, "/settings?section=service", "service_rotate", Some(Refusal::BadServiceKey), ), Err(_) => redirect_back( cx, "/settings?section=service", "service_rotate", Some(Refusal::Unavailable), ), } } /// Deletes one service's key. The account and its files remain — its usage /// reads in the Everyone panel like any other account's. #[route(POST "/api/settings/service_revoke")] async fn service_revoke(cx: &Cx, Form(input): Form) -> Redirect { if let Err(refusal) = require_admin(cx).await { return redirect_back( cx, "/settings?section=service", "service_revoke", Some(refusal), ); } match app(cx).store.revoke_service_key(&input.service).await { Ok(true) => redirect_back(cx, "/settings?section=service", "service_revoke", None), Ok(false) => redirect_back( cx, "/settings?section=service", "service_revoke", Some(Refusal::BadServiceKey), ), Err(_) => redirect_back( cx, "/settings?section=service", "service_revoke", Some(Refusal::Unavailable), ), } } /// Which rail section the page renders. Only one is drawn at a time; an /// admin-only value asked for by anyone else falls back to `Profile`, same /// as a section name it does not recognize at all. #[derive(Clone, Copy, PartialEq, Eq)] enum Section { Profile, Links, Everyone, Server, Service, } /// The class a rail link wears: `active` on the section it points to when /// that is the one showing, plain otherwise. fn rail_class(current: Section, target: Section) -> &'static str { if current == target { "settings-section-link active" } else { "settings-section-link" } } /// The value of one query pair, if present. fn query_value(query: &str, key: &str) -> Option { query.split('&').find_map(|pair| { let (name, value) = pair.split_once('=')?; (name == key).then(|| value.to_string()) }) } /// The settings screen, one rail section at a time: the reader's profile /// and quota, their live share links, and — for an admin — every account /// with its quota and kill switch, plus the server address the public /// links are built from. An admin section asked for by anyone else renders /// the profile, the way an unknown section name does. #[page("/settings")] async fn settings(cx: &Cx) -> Result { let user = match require_user(cx).await { Ok(user) => user, Err(refusal) => { let language = lang(cx).await; return Ok(view! { cx =>

(refusal.message_in(language))

(t(language, Key::BackToDrive))

} .boxed()); } }; let language = lang(cx).await; let app = app(cx); let store = app.store; let connected = app.health.stream_connected(); let last_event = app.health.last_event_age_secs(); let last_pass = app.health.last_pass_age_secs(); // Both ages share one sentence shape: the humanized age and `ago`, // or the `never` wording before the first occurrence — a card that // went silent and a card that never spoke read differently. let age_line = |age: Option| { let text = age_text(age); if text.is_empty() { t(language, Key::Never).to_string() } else { format!("{text} {}", t(language, Key::AgoSuffix)) } }; let event_line = age_line(last_event); let pass_line = age_line(last_pass); // The Connection card reads only what the config already carries and // the sync task's own atomics — the client secret is never touched on // any path that reaches this render. // Re-read the row so the quota bar never shows a stale number. let fresh = store.user(&user.id).await?.unwrap_or_else(|| user.clone()); let administers = fresh.admin; let query = uri(cx).query().unwrap_or(""); let section = match query_value(query, "section").as_deref() { Some("links") => Section::Links, Some("everyone") if administers => Section::Everyone, Some("server") if administers => Section::Server, Some("service") if administers => Section::Service, _ => Section::Profile, }; // Only the section on show pays for its rows: the links panel names // each live link's target, Everyone lists the accounts, and the server // panel needs the origin — nothing else reads them. let mut link_names: Vec<(in_core::store::ShareLink, String, Option)> = Vec::new(); let links = if section == Section::Links { store.share_links(&user.id).await? } else { Vec::new() }; if section == Section::Links { // The display name per live link's target: the row carries only // the id. A missing or trashed target keeps its id — the grant row // outlives the trash, and the panel still revokes it. Enrichment // never fails the page: an unreadable target reads as its id, the // way the shared list degrades per row. for link in links.iter().filter(|link| link.revoked_at.is_none()) { let name = match link.kind { ShareKind::File => store .file(&link.target_id) .await .ok() .flatten() .map(|file| file.name), ShareKind::Folder => store .folder(&link.target_id) .await .ok() .flatten() .map(|folder| folder.name), } .unwrap_or_else(|| link.target_id.clone()); // The full address, re-derived from the token the creation // sealed away; `None` keeps the row masked with the note. let url = share_link_url(cx, link).await; link_names.push((link.clone(), name, url)); } } let users = if administers && section == Section::Everyone { store.users().await? } else { Vec::new() }; // The origin the copy-once banner and the server panel show: the // stored setting when an admin set one, the config chain otherwise. let origin = if matches!(section, Section::Links | Section::Server) { share_origin(cx).await } else { String::new() }; // What the server form's field holds: the stored setting alone. An // empty field is not an invented value — the effective line above it // shows what an empty save falls back to. let stored_base_url = if section == Section::Server { store .get_setting("base_url") .await? .filter(|value| !value.trim().is_empty()) .unwrap_or_default() } else { String::new() }; // The Service keys panel's two reads: the keyed accounts, and the // family rows no key covers yet — the mint dropdown's options. Both are // admin-only reads on an admin-only section. let (accounts, mintable) = if administers && section == Section::Service { let accounts = store.list_service_accounts().await?; let mintable = mintable_services(cx).await.unwrap_or_default(); (accounts, mintable) } else { (Vec::new(), Vec::new()) }; // The one read that takes a stashed key off the shelf — and only on the // section that shows it, so a lost section never eats a live ticket. let created = created_token(query); let shown = if section == Section::Service { query_value(query, "shown") .as_deref() .and_then(crate::server::take_shown_secret) } else { None }; Ok(view! { cx => (topcoat::view::Child::new(topbar(cx, NavPage::Settings, &fresh, language).await?))

(t(language, Key::Settings))

(topcoat::view::Child::new(refusal_banner(cx, language, &["create", "revoke", "add", "remove", "quota", "disable", "preferences", "base_url", "service_add", "service_rotate", "service_revoke"]).await?)) if section == Section::Profile {

(t(language, Key::Profile))

(t(language, Key::QuotaUsage)) (format!("{} {} {}", human_bytes(fresh.used_bytes), t(language, Key::QuotaOf), human_bytes(fresh.quota_bytes)))
// The Connection card: who this app talks to, and whether // the live feed is up right now. Read-only, every // signed-in reader — nothing here is per-user data.

(t(language, Key::Connection))

(t(language, Key::ConnectionIssuer))
(app.config.oidc.issuer.clone())
(t(language, Key::ConnectionClientId))
(app.config.oidc.client_id.clone())
(t(language, Key::ConnectionStream))
if connected { (t(language, Key::ConnectionConnected)) } else { (t(language, Key::ConnectionReconnecting)) }
(t(language, Key::ConnectionLastEvent))
(event_line)
(t(language, Key::ConnectionLastPass))
(pass_line)
} if section == Section::Links { if let Some(token) = created {

(t(language, Key::LinkCreated))

(t(language, Key::CopyLinkOnce))

}

(t(language, Key::ManageLinks))

if link_names.is_empty() {

(t(language, Key::NoLinks))

} if link_names.iter().any(|(link, _, _)| !link.can_download) {

(t(language, Key::ViewOnlyNote))

} for (link, target_name, url) in &link_names {
(format!("{} · {}", t(language, if link.kind == ShareKind::Folder { Key::KindFolder } else { Key::KindFile }), target_name.clone())) (expiry_line(language, link.expires_at))
(if link.can_download { t(language, Key::CanDownload) } else { t(language, Key::ViewOnly) })
// The same affordance the modal's live row // carries: the full address with its copy // button, or the one-click mint plus the // carry-forward note for a link from before // the sealing. if url.is_none() { } }
// One delegated listener serves every row's copy button // above; the script is idempotent across re-renders. (topcoat::view::Child::new(share_copy_script(cx).await?)) } if section == Section::Everyone {

(t(language, Key::AdminPanel))

for listed in &users { }
(t(language, Key::NameColumn)) (t(language, Key::EmailAddress)) (t(language, Key::QuotaBytes))
(listed.display_name.clone()) if listed.admin { (t(language, Key::AdminBadge)) } if listed.disabled { (t(language, Key::DisabledBadge)) } (listed.email.clone())
if listed.id != fresh.id {
if listed.disabled { } else { }
}
} if section == Section::Server {

(t(language, Key::ServerAddress))

(t(language, Key::BaseUrlNote))

} if section == Section::Service { if let Some(key) = shown { // The show-once banner: the shelf behind it has // already handed the key over, so this is the only // render that will ever hold it. The value is // selectable text, so the copy works without script.

(t(language, Key::ServiceKeysTitle))

(t(language, Key::ServiceKeyShown))

}

(t(language, Key::ServiceKeysTitle))

for account in &accounts { }
(t(language, Key::ServiceKeyName)) (t(language, Key::ServiceKeyService)) (t(language, Key::ServiceKeyCreated))
(account.name.clone()) (account.service.clone())
(account.created_at.date().to_string())
(t(language, Key::ServiceKeyRotate))
(t(language, Key::ServiceKeyRotateTitle))

(t(language, Key::ServiceKeyRotateCost))

(t(language, Key::ServiceKeyRevoke))
(t(language, Key::ServiceKeyRevokeTitle))

(t(language, Key::ServiceKeyRevokeCost))

// The banner's copy button above; one delegated listener // serves every row, idempotent across re-renders. (topcoat::view::Child::new(share_copy_script(cx).await?)) }
(topcoat::view::Child::new(crate::dropdown::dropdown_script(cx).await?)) }.boxed()) } /// The just-minted token off the redirect's `?created=` pair, if present. fn created_token(query: &str) -> Option { query_value(query, "created").filter(|value| !value.is_empty()) } /// When the link stops opening, or never on its own. fn expiry_line(language: crate::i18n::Lang, expires_at: Option) -> String { match expires_at { Some(at) => format!( "{} {}", t(language, Key::ExpiresLabel), at.format(&time::format_description::well_known::Rfc3339) .unwrap_or_else(|_| "?".to_string()) ), None => t(language, Key::NeverExpires).to_string(), } }