//! Share creation dialog and the "Your shares" management panel (milestone 6). use leptos::prelude::*; use wasm_bindgen::JsCast; use wasm_bindgen_futures::spawn_local; use std::collections::{BTreeMap, HashMap}; use std::sync::Arc; use crate::api::{self, AdminPimLink, AdminShare, Me, ShareInfo, UserInfo}; use crate::components::icon::icon_svg; use crate::components::modal::Modal; use crate::components::toast::{ToastMsg, show, show_error}; use crate::i18n; use crate::icons::IconName; use crate::router::{dav_share_url, share_url}; use crate::util::copy_to_clipboard; use crate::util::format_date; use crate::views::dialogs::ConfirmDialog; // --------------------------------------------------------------------------- // Expiry helpers (compute the RFC 3339 expiry client-side) // --------------------------------------------------------------------------- /// Format a millisecond timestamp as an RFC 3339 UTC string (ISO 8601). fn ms_to_rfc3339(ms: f64) -> Option { if ms.is_nan() { return None; } Some( js_sys::Date::new(&wasm_bindgen::JsValue::from_f64(ms)) .to_iso_string() .into(), ) } /// Convert the user's expiry choice into an RFC 3339 timestamp, or `None` for /// "never". Presets are computed from "now"; "custom" parses the /// datetime-local value as the browser's local time. pub(crate) fn expiry_to_rfc3339(choice: &str, custom: &str) -> Option { let now = js_sys::Date::now(); let h = 60.0 * 60.0 * 1000.0; let target_ms: Option = match choice { "never" => return None, "1h" => Some(now + h), "1d" => Some(now + 24.0 * h), "1w" => Some(now + 7.0 * 24.0 * h), "1mo" => Some(now + 30.0 * 24.0 * h), "custom" => { if custom.is_empty() { None } else { // `Date.parse` treats a bare datetime as local time, so the // result is already the correct UTC instant. Some(js_sys::Date::parse(custom)) } } _ => return None, }; target_ms.and_then(ms_to_rfc3339) } // --------------------------------------------------------------------------- // Share creation dialog (two-phase: form -> link) // --------------------------------------------------------------------------- #[component] pub fn ShareDialog( name: String, root_id: i64, path: String, allow_writable: bool, root_writable: bool, close: Callback<()>, ) -> impl IntoView { let toast = use_context::().expect("toast context"); let (writable, set_writable) = signal(false); let (choice, set_choice) = signal("never".to_string()); let (custom, set_custom) = signal(String::new()); let (password, set_password) = signal(String::new()); let (created, set_created) = signal(Option::::None); let (busy, set_busy) = signal(false); let name_msg = name.clone(); let do_create = move |_| { if busy.get() { return; } set_busy.set(true); let exp = expiry_to_rfc3339(&choice.get(), &custom.get()); let wr = writable.get(); let rid = root_id; let p = path.clone(); // An empty field means "no password", not a password of "". let pw = password.get().trim().to_string(); let pw = (!pw.is_empty()).then_some(pw); spawn_local(async move { match api::create_share(rid, &p, wr, exp.as_deref(), pw.as_deref()).await { Ok(info) => set_created.set(Some(info)), Err(e) => { show( toast, i18n::t_fmt(i18n::k::SHARE_CREATE_ERR, &e.to_string()), ); set_busy.set(false); } } }); }; view! { } } // --------------------------------------------------------------------------- // Share management view // // A plain user sees their own links. An admin sees every link on the server, // one collapsible section per account. A share outlives the account that made // it (README "Shares"), so without this view nobody could end those links. // --------------------------------------------------------------------------- // Both endpoints load into `AdminShare`, so grouping and rows never branch on // which one answered. The own list has no creator, so the viewer fills it in. /// One collapsible section: an account and its links. struct Group { id: i64, name: String, active: bool, /// The viewer's own links: rendered first, and open by default. mine: bool, shares: Vec, } /// Bucket rows by creator. The map key sorts the sections: the viewer's own /// first, the rest by account name. Non-admins only ever get their own group. /// Rows are pushed in the order the server sent them, so newest stays first. fn group_rows(rows: &[AdminShare], my_id: i64) -> Vec { let mut groups: BTreeMap<(bool, String, i64), Group> = BTreeMap::new(); for r in rows { let mine = r.creator_id == my_id; groups .entry((!mine, r.creator_name.to_lowercase(), r.creator_id)) .or_insert_with(|| Group { id: r.creator_id, name: r.creator_name.clone(), active: r.creator_active, mine, shares: Vec::new(), }) .shares .push(r.share.clone()); } groups.into_values().collect() } /// A bulk deletion that is waiting for the answer to the confirmation dialog. #[derive(Clone, PartialEq)] struct Pending { ids: Vec, /// The account the question names; `None` asks about everything listed. who: Option, } /// End one link. Only the admin route can end a link the viewer does not own, /// so an admin always takes it and everyone else always takes the user route. async fn end_share(is_admin: bool, id: i64) -> bool { if is_admin { api::admin_delete_share(id).await } else { api::delete_share(id).await } .is_ok() } /// One share row: name, meta line, copy buttons, delete. Every section renders /// its rows through this, so an admin sees exactly what the owner sees. fn share_row(s: &ShareInfo, toast: ToastMsg, del: Callback) -> AnyView { let link = share_url(&s.token); let dav_link = dav_share_url(&s.token); let is_file = s.is_file; let glyph = if is_file { IconName::File } else { IconName::Folder }; let mut meta = format!( "{} · {}", s.target, if s.writable { i18n::t(i18n::k::MODE_RW) } else { i18n::t(i18n::k::MODE_RO) } ); if let Some(e) = &s.expires_at { meta.push_str(&format!( " · {}", i18n::t_fmt(i18n::k::META_EXPIRES, &format_date(e)) )); } meta.push_str(&format!( " · {}", i18n::t_fmt(i18n::k::META_CREATED, &format_date(&s.created_at)) )); if s.has_password { meta.push_str(&format!(" · {}", i18n::t(i18n::k::SHARE_PROTECTED))); } let name = s.name.clone(); let id = s.id; view! { } .into_any() } #[component] pub fn SharesView(me: ReadSignal>) -> impl IntoView { let toast = use_context::().expect("toast context"); // One extraction of the signed-in user; everything below reads a field. // The shell renders this view only behind a signed-in `me`. let user: Memo = Memo::new(move |_| { me.with(|m| m.as_ref().and_then(|m| m.user.clone())) .expect("SharesView needs a signed-in user") }); let admin = move || user.with(|u| u.is_admin); let my_id = move || user.with(|u| u.id); // None until the first load answers, so "loading" and "no shares" stay // distinguishable. let (rows, set_rows) = signal(Option::>::None); // Set when the list could not be loaded; the error card offers a retry. let (load_err, set_load_err) = signal(Option::::None); let (confirm, set_confirm) = signal(None::); let (busy, set_busy) = signal(false); // Which sections are open, by account. Kept out of the DOM: the listing is // rebuilt on every delete, and a section must not snap shut under the user. let (open, set_open) = signal(HashMap::::new()); let load = move || { set_load_err.set(None); // `try_get`, not `get`: a bulk delete calls this after its awaits, when // the view may be gone. Reading a disposed memo panics and kills the app. let Some(u) = user.try_get() else { return; }; // The own list does not name a creator, so the viewer's own id and name // fill that in. `me` is loaded before this view renders. let is_admin = u.is_admin; let own_id = u.id; let own_name = u.name; spawn_local(async move { let got = if is_admin { api::list_all_shares().await } else { api::list_shares().await.map(|own| { own.into_iter() .map(|share| AdminShare { share, creator_id: own_id, creator_name: own_name.clone(), creator_active: true, }) .collect() }) }; match got { Ok(rs) => set_rows.set(Some(rs)), Err(e) => set_load_err.set(Some(e.to_string())), } }); }; load(); let delete_one = Callback::new(move |id: i64| { let is_admin = admin(); let toast2 = toast; spawn_local(async move { if end_share(is_admin, id).await { set_rows.update(|rs| { if let Some(list) = rs { list.retain(|r| r.share.id != id); } }); show(toast2, i18n::t(i18n::k::SHARE_DELETED).to_string()); } else { show_error(toast2, i18n::t(i18n::k::SHARE_DELETE_ERR).to_string()); } }); }); // Bulk delete: no server-side bulk endpoint, so this walks the ids one by one. let delete_all = Callback::new(move |_| { let Some(p) = confirm.get() else { return }; set_confirm.set(None); if p.ids.is_empty() || busy.get() { return; } set_busy.set(true); let total = p.ids.len(); let is_admin = admin(); spawn_local(async move { let mut failed = 0usize; for id in &p.ids { if !end_share(is_admin, *id).await { failed += 1; } } if failed == 0 { show( toast, i18n::t_fmt(i18n::k::DELETED_N_SHARES, &total.to_string()), ); } else if failed < total { show( toast, i18n::t_fmt2( i18n::k::DELETE_PARTIAL, &failed.to_string(), &total.to_string(), ), ); } else { show_error(toast, i18n::t(i18n::k::SHARES_DELETE_ERR).to_string()); } // Re-read: after a partial failure, editing the list by hand is // not trustworthy. load(); set_busy.set(false); }); }); view! {

{move || { if admin() { i18n::t(i18n::k::ALL_SHARES).to_string() } else { i18n::t(i18n::k::YOUR_SHARES).to_string() } }}

{move || { let n = rows.get().map(|r| r.len()).unwrap_or(0); (n > 0) .then(|| { view! { } }) .into_any() }}

{move || { if admin() { i18n::t(i18n::k::ALL_SHARES_HINT).to_string() } else { i18n::t(i18n::k::SHARES_VIEW_HINT).to_string() } }}

{move || match rows.get() { None => match load_err.get() { Some(msg) => view! {
{msg}
} .into_any(), None => view! {

{i18n::tr(i18n::k::LOADING)}

} .into_any(), }, Some(ref list) if list.is_empty() => view! {
{icon_svg(IconName::Share, "empty-glyph")}

{i18n::tr(i18n::k::NO_SHARES)}

{i18n::tr(i18n::k::SHARES_EMPTY_HINT)}

} .into_any(), Some(ref list) => { let is_admin = admin(); let mine = my_id(); let sections = group_rows(list, mine) .into_iter() .map(|g| { let own = g.mine; // One copy, shared by the section title and the // delete-all question: both name the account. let name: Arc = g.name.into(); let items = g.shares .iter() .map(|s| share_row(s, toast, delete_one)) .collect::>(); let ids: Vec = g.shares.iter().map(|s| s.id).collect(); let n = g.shares.len(); let gid = g.id; let inactive = !g.active; view! { // Own links open, everyone else's collapsed: an // admin lands on their own links, not on a wall // of other people's tokens. } }) .collect::>(); view! { } .into_any() } }} {move || admin().then(|| view! { })} // Delete-all confirmation, for one account or for everything. {move || { let p = confirm.get()?; // Name the account: the links being deleted are not the // viewer's. let msg = match &p.who { Some(name) => i18n::t_fmt(i18n::k::DELETE_ALL_USER_MSG, name), None => i18n::t_fmt(i18n::k::DELETE_ALL_MSG, &p.ids.len().to_string()), }; Some(view! { }) }}
} } /// Admin only: every public calendar and address book feed on the server. /// Owners manage their own in the calendar and contact views. #[component] fn AdminFeeds() -> impl IntoView { let toast = use_context::().expect("toast context"); let (feeds, set_feeds) = signal(Option::>::None); let load = move || { spawn_local(async move { match api::admin_pim_links().await { Ok(v) => set_feeds.set(Some(v)), Err(e) => show_error(toast, e.to_string()), } }); }; load(); let row = move |f: AdminPimLink| { let url = crate::router::server_url(&f.link.path); let copy = url.clone(); let id = f.link.id; let mut meta = vec![f.owner_name.clone()]; // Address book feeds have no detail level. if f.kind == api_types::PimCollectionKind::Calendar { meta.push(if f.link.busy_only { i18n::t(i18n::k::PIM_LINK_BUSY).to_string() } else { i18n::t(i18n::k::PIM_LINK_FULL).to_string() }); } if let Some(e) = &f.link.expires_at { meta.push(i18n::t_fmt(i18n::k::META_EXPIRES, &format_date(e))); } meta.push(i18n::t_fmt( i18n::k::META_CREATED, &format_date(&f.link.created_at), )); if f.link.has_password { meta.push(i18n::t(i18n::k::SHARE_PROTECTED).to_string()); } if !f.owner_active { meta.push(i18n::t(i18n::k::SHARE_OWNER_DISABLED).to_string()); } let glyph = match f.kind { api::PimCollectionKind::Calendar => IconName::Calendar, api::PimCollectionKind::Addressbook => IconName::Contacts, }; view! { } }; view! {

{i18n::tr(i18n::k::PIM_FEEDS)}

{i18n::tr(i18n::k::PIM_FEEDS_HINT)}

{move || match feeds.get() { None => view! {

{i18n::tr(i18n::k::LOADING)}

}.into_any(), Some(list) if list.is_empty() => { view! {

{i18n::tr(i18n::k::PIM_NO_FEEDS)}

}.into_any() } Some(list) => view! { } .into_any(), }} } }