forge
Explore
Log in

Don't you dare go Hollow

in_old

Clone
★ 0

0 watching0 forksRustGPL-3.01.1 MiB218b775Tahinli2 months ago90 commits

share.rs1946 lines, 83.0 KiBHistoryRawDownload
1//! Sharing: public links, per-user grants, and the shared-with-me page.
2//!
3//! `POST /api/share/link/create|revoke|remint` mints, kills, and re-mints
4//! bearer links over a
5//! file or folder (`can_download`, optional expiry in days; only the token
6//! hash is stored). `POST /api/share/user/add|remove` grants and revokes
7//! named users the same way. `GET /s/{token}` is public — no auth —
8//! rendering the viewer page in the document shell, the download only when
9//! `can_download` allows, the stored webp preview on `?thumb=1` regardless
10//! of the flag, and the card's `<video>`/`<audio>` player feed on
11//! `?media=1` for the video and audio kinds; a spent, expired or revoked
12//! token answers the dead card, never a stack.
13//! `GET /shared` lists what others shared with the reader.
14//!
15//! Every mutation answers the way `board.rs` in iz does: a 303 back to the
16//! page the form was posted from, the refusal (if any) on the redirect's
17//! query. The one exception is link creation, whose plaintext token is
18//! sealed with the app key onto the `share_token:{id}` setting row and
19//! shown in the redirect's `?created=<token>` pair, so a browser without
20//! script can copy it; the drive and settings pages render the copy-once
21//! banner off that pair, and re-derive the full address for the live-link
22//! rows from the sealed one.
23
24use in_core::store::{File, ShareKind, Store, StoreError, ThumbState, User};
25use in_core::{hash_link_password, hash_share_token, link_password_matches, link_unlock_proof};
26use serde::de::{IgnoredAny, MapAccess, Visitor};
27use serde::{Deserialize, Deserializer};
28use time::OffsetDateTime;
29use topcoat::Result;
30use topcoat::context::Cx;
31use topcoat::cookie::{Cookies, cookie, cookies};
32use topcoat::router::content::Form;
33use topcoat::router::request::{headers as request_headers, uri};
34use topcoat::router::response::IntoResponse;
35use topcoat::router::{HeaderName, StatusCode, header, page, path_param, query_params, route};
36use topcoat::view::{View, ViewExt, view};
37
38use crate::files::{ViewerKind, entry_chip, media_player, media_player_script, viewer_kind};
39use crate::i18n::{Key, Lang, lang, t};
40use crate::layout::{NavPage, document_shell, topbar, wordmark};
41use crate::server::{Refusal, app, back_to, require_user, share_link_url, share_origin};
42
43path_param!(token);
44path_param!(kind);
45path_param!(id);
46
47/// A refusal surfaced as a banner: the `?refusal=<code>&on=<call>` pair the
48/// mutation redirects carry, rendered only when `on` names one of `calls` —
49/// and the `?saved=<call>` chip a clean save carries, the way iz's
50/// `saved_or_refused` marks one. Shared by the trash and settings pages,
51/// which own no banner of their own.
52pub(crate) async fn refusal_banner<'a>(
53 cx: &'a Cx,
54 language: Lang,
55 calls: &'a [&'a str],
56) -> Result<impl View + 'a> {
57 let query = uri(cx).query().unwrap_or("");
58 let refusal = query_value(query, "refusal").and_then(|code| Refusal::from_code(&code));
59 let on = query_value(query, "on").unwrap_or_default();
60 let saved = query_value(query, "saved").unwrap_or_default();
61 let refused = calls.iter().any(|call| *call == on);
62 let kept = calls.iter().any(|call| *call == saved);
63 Ok(view! {
64 cx =>
65 if refused {
66 if let Some(refusal) = refusal {
67 <p class="field-error" role="alert">(refusal.message_in(language))</p>
68 }
69 }
70 if kept {
71 <p class="field-note" role="status">(t(language, Key::Saved))</p>
72 }
73 }
74 .boxed())
75}
76
77/// The value of one query pair, if present.
78fn query_value(query: &str, key: &str) -> Option<String> {
79 query.split('&').find_map(|pair| {
80 let (name, value) = pair.split_once('=')?;
81 (name == key).then(|| value.to_string())
82 })
83}
84
85type Redirect = Result<(StatusCode, [(HeaderName, String); 1])>;
86
87/// Back to the posting page, the refusal (if any) on the query.
88fn redirect_back(cx: &Cx, nowhere: &str, call: &str, refusal: Option<Refusal>) -> Redirect {
89 let back = back_to(cx, nowhere);
90 let separator = if back.contains('?') { '&' } else { '?' };
91 let location = match refusal {
92 Some(refusal) => format!("{back}{separator}refusal={}&on={call}", refusal.code()),
93 None => back,
94 };
95 Ok((StatusCode::SEE_OTHER, [(header::LOCATION, location)]))
96}
97
98/// The store's failure in the route's words. Cross-owner reads answer as
99/// not-found — a 404, never a 403 — so a stranger cannot probe which ids
100/// exist.
101pub(crate) fn refusal_of(error: StoreError) -> Refusal {
102 match error {
103 StoreError::NotFound | StoreError::CrossOwner => Refusal::NotFound,
104 StoreError::QuotaExceeded => Refusal::QuotaExceeded,
105 StoreError::AncestorTrashed => Refusal::AncestorTrashed,
106 _ => Refusal::Unavailable,
107 }
108}
109
110/// `file` or `folder`, or nothing a route may act on.
111fn parse_kind(raw: &str) -> Option<ShareKind> {
112 match raw {
113 "file" => Some(ShareKind::File),
114 "folder" => Some(ShareKind::Folder),
115 _ => None,
116 }
117}
118
119/// A checkbox-ish flag: absent means the control's default, present is true
120/// unless it reads plainly false.
121fn parse_flag(raw: Option<&str>, when_absent: bool) -> bool {
122 match raw {
123 None => when_absent,
124 Some(value) => !matches!(
125 value.trim().to_lowercase().as_str(),
126 "" | "0" | "false" | "no" | "off"
127 ),
128 }
129}
130/// The link's expiry off `expires_in_days`: absent or empty means no expiry,
131/// anything else must name a positive whole number of days. A mistyped value
132/// silently minting a never-expiring link would be the wrong default, so it
133/// is refused instead.
134fn parse_expiry(raw: Option<&str>) -> std::result::Result<Option<OffsetDateTime>, Refusal> {
135 let Some(raw) = raw.map(str::trim).filter(|raw| !raw.is_empty()) else {
136 return Ok(None);
137 };
138 let days: i64 = raw.parse().map_err(|_| Refusal::Forbidden)?;
139 if days <= 0 {
140 return Err(Refusal::Forbidden);
141 }
142 let seconds = days.checked_mul(86_400).ok_or(Refusal::Forbidden)?;
143 OffsetDateTime::now_utc()
144 .checked_add(time::Duration::seconds(seconds))
145 .map(Some)
146 .ok_or(Refusal::Forbidden)
147}
148
149/// The link password off the form: absent, blank, or all whitespace is no
150/// password — the field is optional, and a blank string nobody typed is
151/// never a secret worth keeping.
152fn form_password(raw: Option<&str>) -> Option<String> {
153 raw.map(str::trim)
154 .filter(|password| !password.is_empty())
155 .map(str::to_string)
156}
157
158/// The target the caller must own: present, untrashed, and theirs. Anything
159/// else is not-found — a stranger learns nothing about whose it is.
160async fn owned_target(
161 store: &dyn Store,
162 user: &User,
163 kind: ShareKind,
164 target_id: &str,
165) -> std::result::Result<(), Refusal> {
166 let owned = match kind {
167 ShareKind::File => store
168 .file(target_id)
169 .await
170 .map_err(|_| Refusal::Unavailable)?
171 .is_some_and(|file| file.owner_id == user.id && file.deleted_at.is_none()),
172 ShareKind::Folder => store
173 .folder(target_id)
174 .await
175 .map_err(|_| Refusal::Unavailable)?
176 .is_some_and(|folder| folder.owner_id == user.id && folder.deleted_at.is_none()),
177 };
178 if owned {
179 Ok(())
180 } else {
181 Err(Refusal::NotFound)
182 }
183}
184/// The target the caller owns, trashed or not: unsharing a trashed target
185/// still revokes the grant, and the grant row outlives the trash either way.
186/// Anything else is not-found — a stranger learns nothing about whose it is.
187async fn owned_target_for_unshare(
188 store: &dyn Store,
189 user: &User,
190 kind: ShareKind,
191 target_id: &str,
192) -> std::result::Result<(), Refusal> {
193 let owned = match kind {
194 ShareKind::File => store
195 .file(target_id)
196 .await
197 .map_err(|_| Refusal::Unavailable)?
198 .is_some_and(|file| file.owner_id == user.id),
199 ShareKind::Folder => store
200 .folder(target_id)
201 .await
202 .map_err(|_| Refusal::Unavailable)?
203 .is_some_and(|folder| folder.owner_id == user.id),
204 };
205 if owned {
206 Ok(())
207 } else {
208 Err(Refusal::NotFound)
209 }
210}
211
212#[derive(Deserialize)]
213struct CreateLinkForm {
214 kind: String,
215 target_id: String,
216 #[serde(default)]
217 can_download: Option<String>,
218 #[serde(default)]
219 expires_in_days: Option<String>,
220 #[serde(default)]
221 password: Option<String>,
222}
223
224/// Mints a bearer link. The token rides the redirect's `?created=` pair —
225/// which the drive and settings pages render as the copy-once banner — and
226/// is sealed with the app key onto the `share_token:{id}` setting row, so
227/// the full address can be re-shown later; the row itself keeps only the
228/// token's hash.
229#[route(POST "/api/share/link/create")]
230async fn create_link(cx: &Cx, Form(input): Form<CreateLinkForm>) -> Redirect {
231 let user = match require_user(cx).await {
232 Ok(user) => user,
233 Err(refusal) => {
234 return redirect_back(cx, "/settings?section=links", "create", Some(refusal));
235 }
236 };
237 let Some(kind) = parse_kind(&input.kind) else {
238 return redirect_back(
239 cx,
240 "/settings?section=links",
241 "create",
242 Some(Refusal::NotFound),
243 );
244 };
245 if let Err(refusal) = owned_target(app(cx).store.as_ref(), &user, kind, &input.target_id).await
246 {
247 return redirect_back(cx, "/settings?section=links", "create", Some(refusal));
248 }
249 let expires_at = match parse_expiry(input.expires_in_days.as_deref()) {
250 Ok(expires_at) => expires_at,
251 Err(refusal) => {
252 return redirect_back(cx, "/settings?section=links", "create", Some(refusal));
253 }
254 };
255 // An optional password on the link: a trimmed empty field is no
256 // password at all. Argon2id is CPU-slow on purpose, so the hash runs
257 // off the async path — a hash this cheap would be a hash worth
258 // guessing.
259 let password_hash = match form_password(input.password.as_deref()) {
260 Some(password) => {
261 match tokio::task::spawn_blocking(move || hash_link_password(&password)).await {
262 Ok(Ok(hash)) => Some(hash),
263 _ => {
264 return redirect_back(
265 cx,
266 "/settings?section=links",
267 "create",
268 Some(Refusal::Unavailable),
269 );
270 }
271 }
272 }
273 None => None,
274 };
275 let created = app(cx)
276 .store
277 .create_share_link(
278 &user.id,
279 kind,
280 &input.target_id,
281 // Absent means the checkbox came unchecked: view-only. A checked
282 // box posts `1`; nothing posted must never mint a download.
283 parse_flag(input.can_download.as_deref(), false),
284 expires_at,
285 password_hash,
286 )
287 .await;
288 match created {
289 Ok(minted) => {
290 // The token is sealed onto its own setting row — the same
291 // `in.key` that seals the session cookies — so the share modal
292 // and the settings panel can re-show the full address later. A
293 // failed seal is lived with, not refused: refusing now would
294 // leave a live link whose token the one-time banner never
295 // showed, the worse half of that bargain.
296 let sealed = in_core::store::secret::seal(&app(cx).link_key, &minted.token);
297 let _ = app(cx)
298 .store
299 .set_setting(&format!("share_token:{}", minted.link.id), &sealed)
300 .await;
301 let back = back_to(cx, "/settings?section=links");
302 let separator = if back.contains('?') { '&' } else { '?' };
303 let location = format!("{back}{separator}created={}", minted.token);
304 Ok((StatusCode::SEE_OTHER, [(header::LOCATION, location)]))
305 }
306 Err(error) => redirect_back(
307 cx,
308 "/settings?section=links",
309 "create",
310 Some(refusal_of(error)),
311 ),
312 }
313}
314
315#[derive(Deserialize)]
316struct RevokeLinkForm {
317 id: String,
318}
319
320/// Kills a bearer link. Only its creator may: anyone else is answered as if
321/// it never existed. Revoking twice is not an error.
322#[route(POST "/api/share/link/revoke")]
323async fn revoke_link(cx: &Cx, Form(input): Form<RevokeLinkForm>) -> Redirect {
324 let user = match require_user(cx).await {
325 Ok(user) => user,
326 Err(refusal) => {
327 return redirect_back(cx, "/settings?section=links", "revoke", Some(refusal));
328 }
329 };
330 let store = app(cx).store;
331 let mine = store
332 .share_links(&user.id)
333 .await
334 .map_err(|_| Refusal::Unavailable);
335 let Ok(links) = mine else {
336 return redirect_back(
337 cx,
338 "/settings?section=links",
339 "revoke",
340 Some(Refusal::Unavailable),
341 );
342 };
343 if !links
344 .iter()
345 .any(|link| link.id == input.id && link.created_by == user.id)
346 {
347 return redirect_back(
348 cx,
349 "/settings?section=links",
350 "revoke",
351 Some(Refusal::NotFound),
352 );
353 }
354 match store.revoke_share_link(&input.id).await {
355 Ok(()) => {
356 // The sealed address dies with the link: deleting the row is
357 // part of revoking, not cleanup after it, so a failed delete
358 // reports the revoke as refused. A retry finishes the job —
359 // revoking twice is not an error.
360 match store
361 .delete_setting(&format!("share_token:{}", input.id))
362 .await
363 {
364 Ok(()) => redirect_back(cx, "/settings?section=links", "revoke", None),
365 Err(error) => redirect_back(
366 cx,
367 "/settings?section=links",
368 "revoke",
369 Some(refusal_of(error)),
370 ),
371 }
372 }
373 Err(error) => redirect_back(
374 cx,
375 "/settings?section=links",
376 "revoke",
377 Some(refusal_of(error)),
378 ),
379 }
380}
381
382/// Carries a legacy link forward: a fresh mint over the same target, with
383/// the old row's `can_download`, its password, and a still-future expiry —
384/// an elapsed one drops, since a minted expiry opens for no one. Only its
385/// creator may; a foreign or unknown link is answered as if it never
386/// existed. The old row and its sealed setting die with the mint, the
387/// revoke path's exact semantics: the address remint replaces was already
388/// unrecoverable.
389#[route(POST "/api/share/link/remint")]
390async fn remint_link(cx: &Cx, Form(input): Form<RevokeLinkForm>) -> Redirect {
391 let user = match require_user(cx).await {
392 Ok(user) => user,
393 Err(refusal) => {
394 return redirect_back(cx, "/settings?section=links", "remint", Some(refusal));
395 }
396 };
397 let store = app(cx).store;
398 let mine = store
399 .share_links(&user.id)
400 .await
401 .map_err(|_| Refusal::Unavailable);
402 let Ok(links) = mine else {
403 return redirect_back(
404 cx,
405 "/settings?section=links",
406 "remint",
407 Some(Refusal::Unavailable),
408 );
409 };
410 let Some(old) = links
411 .iter()
412 .find(|link| link.id == input.id && link.created_by == user.id)
413 else {
414 return redirect_back(
415 cx,
416 "/settings?section=links",
417 "remint",
418 Some(Refusal::NotFound),
419 );
420 };
421 // A still-future expiry carries over; an elapsed one would mint a link
422 // that is dead on arrival.
423 let expires_at = old.expires_at.filter(|at| *at > OffsetDateTime::now_utc());
424 let created = store
425 .create_share_link(
426 &user.id,
427 old.kind,
428 &old.target_id,
429 old.can_download,
430 expires_at,
431 old.password_hash.clone(),
432 )
433 .await;
434 match created {
435 Ok(minted) => match store.revoke_share_link(&input.id).await {
436 Ok(()) => {
437 // The sealed address dies with the link — part of the
438 // remint, not cleanup after it, so a failed delete reports
439 // the remint as refused.
440 match store
441 .delete_setting(&format!("share_token:{}", input.id))
442 .await
443 {
444 Ok(()) => {
445 // The fresh token gets the seal, exactly as a
446 // creation seals its own; a failed seal is lived
447 // with, because the redirect below shows the full
448 // address regardless.
449 let sealed = in_core::store::secret::seal(&app(cx).link_key, &minted.token);
450 let _ = app(cx)
451 .store
452 .set_setting(&format!("share_token:{}", minted.link.id), &sealed)
453 .await;
454 let back = back_to(cx, "/settings?section=links");
455 let separator = if back.contains('?') { '&' } else { '?' };
456 let location = format!("{back}{separator}created={}", minted.token);
457 Ok((StatusCode::SEE_OTHER, [(header::LOCATION, location)]))
458 }
459 Err(error) => redirect_back(
460 cx,
461 "/settings?section=links",
462 "remint",
463 Some(refusal_of(error)),
464 ),
465 }
466 }
467 Err(error) => redirect_back(
468 cx,
469 "/settings?section=links",
470 "remint",
471 Some(refusal_of(error)),
472 ),
473 },
474 Err(error) => redirect_back(
475 cx,
476 "/settings?section=links",
477 "remint",
478 Some(refusal_of(error)),
479 ),
480 }
481}
482
483/// Whether `at` is the link's target or sits under it: every step up must be
484/// live, owned by the link's owner, and end at the target. A break anywhere
485/// means the browse is outside the share.
486async fn under_target(store: &dyn Store, owner_id: &str, target_id: &str, at: &str) -> bool {
487 let mut current = at.to_string();
488 loop {
489 if current == target_id {
490 return true;
491 }
492 let Ok(Some(folder)) = store.folder(&current).await else {
493 return false;
494 };
495 if folder.owner_id != owner_id || folder.deleted_at.is_some() {
496 return false;
497 }
498 match folder.parent_id {
499 Some(parent) if parent != current => current = parent,
500 _ => return false,
501 }
502 }
503}
504/// The share form. The picker posts one `email` field per person, and
505/// serde_urlencoded hands a map visitor one pair at a time — a `Vec` field
506/// cannot see the repeats — so the impl below collects them itself. The
507/// typed-address fallback posts a single `email`, which lands the same way.
508struct ShareUserForm {
509 kind: String,
510 target_id: String,
511 email: Vec<String>,
512 can_download: Option<String>,
513}
514
515impl<'de> Deserialize<'de> for ShareUserForm {
516 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
517 where
518 D: Deserializer<'de>,
519 {
520 struct FormVisitor;
521 impl<'de> Visitor<'de> for FormVisitor {
522 type Value = ShareUserForm;
523
524 fn expecting(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
525 f.write_str("the share form")
526 }
527
528 fn visit_map<A: MapAccess<'de>>(self, mut map: A) -> Result<Self::Value, A::Error> {
529 let mut form = ShareUserForm {
530 kind: String::new(),
531 target_id: String::new(),
532 email: Vec::new(),
533 can_download: None,
534 };
535 while let Some(key) = map.next_key::<String>()? {
536 match key.as_str() {
537 "kind" => form.kind = map.next_value()?,
538 "target_id" => form.target_id = map.next_value()?,
539 // The repeats are the point: every checked row is
540 // one pair, collected in post order.
541 "email" => form.email.push(map.next_value()?),
542 // Absent means the checkbox came unchecked.
543 "can_download" => form.can_download = map.next_value()?,
544 _ => {
545 let _: IgnoredAny = map.next_value()?;
546 }
547 }
548 }
549 Ok(form)
550 }
551 }
552 deserializer.deserialize_map(FormVisitor)
553 }
554}
555
556/// Shares one file or folder with the people the form names: one `email`
557/// field per person, so the picker's multi-select posts them all in one
558/// submit. Each address is folded to lowercase before lookup; an unknown
559/// address is not-found.
560#[route(POST "/api/share/user/add")]
561async fn add_share(cx: &Cx, Form(input): Form<ShareUserForm>) -> Redirect {
562 let user = match require_user(cx).await {
563 Ok(user) => user,
564 Err(refusal) => return redirect_back(cx, "/settings", "add", Some(refusal)),
565 };
566 let Some(kind) = parse_kind(&input.kind) else {
567 return redirect_back(cx, "/settings", "add", Some(Refusal::NotFound));
568 };
569 if let Err(refusal) = owned_target(app(cx).store.as_ref(), &user, kind, &input.target_id).await
570 {
571 return redirect_back(cx, "/settings", "add", Some(refusal));
572 }
573 let store = app(cx).store;
574 // Absent means the checkbox came unchecked: view-only, like the
575 // sibling link creator above. One setting covers the whole submit.
576 let can_download = parse_flag(input.can_download.as_deref(), false);
577 // The picker's filter doubles as the typed-address fallback, so a
578 // checkbox-only submit carries one blank `email` pair beside the checked
579 // rows. Blank names nobody: only real addresses are looked up. Nothing
580 // but blanks is still nobody — refused like nothing checked.
581 let emails: Vec<&str> = input
582 .email
583 .iter()
584 .map(|email| email.trim())
585 .filter(|email| !email.is_empty())
586 .collect();
587 if emails.is_empty() {
588 return redirect_back(cx, "/settings", "add", Some(Refusal::NotFound));
589 }
590 for email in emails {
591 let grantee = store
592 .user_by_email(&email.to_lowercase())
593 .await
594 .map_err(|_| Refusal::Unavailable);
595 let Ok(Some(grantee)) = grantee else {
596 return redirect_back(cx, "/settings", "add", Some(Refusal::NotFound));
597 };
598 // Re-sharing updates the same row — the store upserts — so a name
599 // the list already carries cannot refuse here.
600 if let Err(error) = store
601 .add_share_user(&user.id, kind, &input.target_id, &grantee.id, can_download)
602 .await
603 {
604 return redirect_back(cx, "/settings", "add", Some(refusal_of(error)));
605 }
606 }
607 redirect_back(cx, "/settings", "add", None)
608}
609
610/// Unshares. Removing what was never shared is not an error; only the
611/// target's owner may unshare, trashed or not.
612#[route(POST "/api/share/user/remove")]
613async fn remove_share(cx: &Cx, Form(input): Form<ShareUserForm>) -> Redirect {
614 let user = match require_user(cx).await {
615 Ok(user) => user,
616 Err(refusal) => return redirect_back(cx, "/settings", "remove", Some(refusal)),
617 };
618 let Some(kind) = parse_kind(&input.kind) else {
619 return redirect_back(cx, "/settings", "remove", Some(Refusal::NotFound));
620 };
621 if let Err(refusal) =
622 owned_target_for_unshare(app(cx).store.as_ref(), &user, kind, &input.target_id).await
623 {
624 return redirect_back(cx, "/settings", "remove", Some(refusal));
625 }
626 let store = app(cx).store;
627 // The remove form posts exactly one address.
628 let email = input.email.first().map(String::as_str).unwrap_or("");
629 let grantee = store
630 .user_by_email(&email.trim().to_lowercase())
631 .await
632 .map_err(|_| Refusal::Unavailable);
633 let Ok(Some(grantee)) = grantee else {
634 return redirect_back(cx, "/settings", "remove", Some(Refusal::NotFound));
635 };
636 match store
637 .remove_share_user(kind, &input.target_id, &grantee.id)
638 .await
639 {
640 Ok(()) => redirect_back(cx, "/settings", "remove", None),
641 Err(error) => redirect_back(cx, "/settings", "remove", Some(refusal_of(error))),
642 }
643}
644
645/// The public viewer's query: which folder is browsed, which file is named,
646/// whether the bytes (rather than the card) are wanted, whether the stored
647/// webp preview is wanted — the preview a view-only link grants — and
648/// whether the inline media stream the card's player draws from is wanted.
649struct SharedQuery {
650 folder: Option<String>,
651 file: Option<String>,
652 dl: bool,
653 thumb: bool,
654 media: bool,
655}
656
657/// The query off the request's own URI. Unparseable pairs are ignored —
658/// a hand-edited query browses nothing rather than failing the page.
659fn shared_query(cx: &Cx) -> SharedQuery {
660 let query = uri(cx).query().unwrap_or("");
661 SharedQuery {
662 folder: query_value(query, "folder"),
663 file: query_value(query, "file"),
664 dl: has_flag(query, "dl"),
665 thumb: has_flag(query, "thumb"),
666 media: has_flag(query, "media"),
667 }
668}
669
670/// Whether the query names the bare flag, as `?dl` or `?dl=1`.
671fn has_flag(query: &str, key: &str) -> bool {
672 query
673 .split('&')
674 .any(|pair| pair == key || pair.starts_with(&format!("{key}=")))
675}
676
677/// A public page in the document shell. `#[page]` pairs its layouts at
678/// build time, but this route's query asks for raw bytes (`?dl=1`,
679/// `?thumb=1`, `?media=1`) that a page-shaped answer cannot carry, so the
680/// `/s` surface stays a `#[route]` and wraps its views itself — in
681/// `document_shell`, the same shell every `#[page]` under `/` wears, never
682/// a hand-copied head.
683async fn public_page(
684 cx: &Cx,
685 title: &str,
686 page: impl View,
687) -> Result<topcoat::router::response::Response> {
688 let title = format!("{title} · in");
689 document_shell(cx, topcoat::view::Child::new(page), title)
690 .await?
691 .first()
692 .await?
693 .into_response(cx)
694}
695
696/// The dead card: a spent, expired, revoked or never-real token, a trashed
697/// target, or a download the link may not open. One answer for all of them —
698/// a stranger learns nothing about which tokens exist.
699async fn dead_link(cx: &Cx) -> topcoat::Result<topcoat::router::response::Response> {
700 let language = lang(cx).await;
701 let page = view! {
702 cx =>
703 <main class="scaffold-note">
704 (topcoat::view::Child::new(wordmark(cx).await?))
705 <p>(Refusal::ShareRevoked.message_in(language))</p>
706 <p><a href="/">(t(language, Key::BackToDrive))</a></p>
707 </main>
708 };
709 public_page(cx, t(language, Key::NothingAtThisAddress), page).await
710}
711/// The public viewer. No auth: the token in the path is the whole
712/// credential. A file target renders its card (and its bytes on `?dl=1`
713/// when the link may download); a folder target renders the listing of the
714/// browsed folder, downloads gated per file on the same flag. The card's
715/// player streams `?media=1` regardless of the flag — preview is what a
716/// view-only link grants — for the video and audio kinds the signed-in
717/// viewer plays inline.
718#[route(GET "/s/{token}")]
719async fn shared_link(cx: &Cx) -> topcoat::Result<topcoat::router::response::Response> {
720 let token: &str = path_param::<Token>(cx);
721 let store = app(cx).store;
722 let now = OffsetDateTime::now_utc();
723 let link = store
724 .resolve_share_link(&hash_share_token(token), now)
725 .await
726 .ok()
727 .flatten();
728 let Some(link) = link else {
729 return dead_link(cx).await;
730 };
731 // A password-protected link answers nothing — card, bytes or thumbnail —
732 // until this browser carries the unlock proof. One check up front gates
733 // every branch below, which is the point: a gate the download route
734 // forgot would not be a gate.
735 if let Some(password_hash) = &link.password_hash {
736 let proof = link_unlock_proof(token, password_hash);
737 let presented = cookies(cx)
738 .get(&link_cookie_name(&link.id))
739 .map(|cookie| cookie.value().to_string());
740 if presented.as_deref() != Some(proof.as_str()) {
741 return password_gate(cx).await;
742 }
743 }
744 let query = shared_query(cx);
745 match link.kind {
746 ShareKind::File => {
747 let file = store
748 .file(&link.target_id)
749 .await
750 .map_err(|_| Refusal::Unavailable);
751 let Ok(Some(file)) = file else {
752 return dead_link(cx).await;
753 };
754 if file.deleted_at.is_some() {
755 return dead_link(cx).await;
756 }
757 if query.dl {
758 return download_bytes(
759 cx,
760 store.as_ref(),
761 &file.id,
762 file.size_bytes,
763 &file.name,
764 &file.mime,
765 link.can_download,
766 )
767 .await;
768 }
769 if query.media {
770 return media_bytes(
771 cx,
772 store.as_ref(),
773 &file.id,
774 file.size_bytes,
775 &file.name,
776 &file.mime,
777 )
778 .await;
779 }
780 if query.thumb {
781 return public_thumb(cx, store.as_ref(), &file.id).await;
782 }
783 file_card(cx, &link, &file).await
784 }
785 ShareKind::Folder => {
786 let root = store
787 .folder(&link.target_id)
788 .await
789 .map_err(|_| Refusal::Unavailable);
790 let Ok(Some(root)) = root else {
791 return dead_link(cx).await;
792 };
793 if root.deleted_at.is_some() {
794 return dead_link(cx).await;
795 }
796 let at = query.folder.as_deref().unwrap_or(&root.id).to_string();
797 if !under_target(store.as_ref(), &root.owner_id, &root.id, &at).await {
798 return dead_link(cx).await;
799 }
800 if query.dl {
801 let Some(file_id) = query.file.as_deref() else {
802 return dead_link(cx).await;
803 };
804 let file = store.file(file_id).await.map_err(|_| Refusal::Unavailable);
805 let Ok(Some(file)) = file else {
806 return dead_link(cx).await;
807 };
808 if file.deleted_at.is_some()
809 || file.owner_id != root.owner_id
810 || file.folder_id.as_deref() != Some(at.as_str())
811 {
812 return dead_link(cx).await;
813 }
814 return download_bytes(
815 cx,
816 store.as_ref(),
817 &file.id,
818 file.size_bytes,
819 &file.name,
820 &file.mime,
821 link.can_download,
822 )
823 .await;
824 }
825 if query.media {
826 let Some(file_id) = query.file.as_deref() else {
827 return dead_link(cx).await;
828 };
829 let file = store.file(file_id).await.map_err(|_| Refusal::Unavailable);
830 let Ok(Some(file)) = file else {
831 return dead_link(cx).await;
832 };
833 if file.deleted_at.is_some()
834 || file.owner_id != root.owner_id
835 || file.folder_id.as_deref() != Some(at.as_str())
836 {
837 return dead_link(cx).await;
838 }
839 return media_bytes(
840 cx,
841 store.as_ref(),
842 &file.id,
843 file.size_bytes,
844 &file.name,
845 &file.mime,
846 )
847 .await;
848 }
849 if query.thumb {
850 let Some(file_id) = query.file.as_deref() else {
851 return dead_link(cx).await;
852 };
853 let file = store.file(file_id).await.map_err(|_| Refusal::Unavailable);
854 let Ok(Some(file)) = file else {
855 return dead_link(cx).await;
856 };
857 if file.deleted_at.is_some()
858 || file.owner_id != root.owner_id
859 || file.folder_id.as_deref() != Some(at.as_str())
860 {
861 return dead_link(cx).await;
862 }
863 return public_thumb(cx, store.as_ref(), &file.id).await;
864 }
865 folder_card(cx, store.as_ref(), &link, &root, &at, token).await
866 }
867 }
868}
869
870/// The cookie a unlocked browser carries for one link, named for the link's
871/// own id: two protected links are two gates, not one.
872fn link_cookie_name(link_id: &str) -> String {
873 format!("in_link_{link_id}")
874}
875
876/// The gate a password-protected link shows until the browser carries the
877/// proof. Same public chrome as the cards — no hint of what waits behind
878/// the gate, not even the file's name.
879async fn password_gate(cx: &Cx) -> topcoat::Result<topcoat::router::response::Response> {
880 let language = lang(cx).await;
881 let action = current_path(cx);
882 let wrong = has_flag(uri(cx).query().unwrap_or(""), "wrong");
883 let page = view! {
884 cx =>
885 <main class="scaffold-note">
886 (topcoat::view::Child::new(wordmark(cx).await?))
887 <h1 class="settings-title">(t(language, Key::PasswordProtected))</h1>
888 <p class="field-note">(t(language, Key::PasswordPrompt))</p>
889 if wrong {
890 <p class="field-error" role="alert">(t(language, Key::WrongPassword))</p>
891 }
892 <form class="pop-row-form" method="post" action=(action)>
893 <input class="field-input" type="password" name="password" required="" autocomplete="off" placeholder=(t(language, Key::PasswordLabel)) aria-label=(t(language, Key::PasswordLabel))>
894 <button class="quiet" type="submit">(t(language, Key::Unlock))</button>
895 </form>
896 </main>
897 };
898 public_page(cx, t(language, Key::PasswordProtected), page).await
899}
900
901#[derive(Deserialize)]
902struct UnlockForm {
903 #[serde(default)]
904 password: Option<String>,
905}
906
907/// Unlocks a password-protected link: the right password mints the proof
908/// cookie and the visitor is sent on to the page as if the gate had never
909/// been there; anything else is the gate again, the error riding `?wrong=1`.
910/// The whole surface answers a 303 either way, so the response says nothing
911/// about whether the guess was close.
912#[route(POST "/s/{token}")]
913async fn unlock_link(
914 cx: &Cx,
915 Form(input): Form<UnlockForm>,
916) -> topcoat::Result<topcoat::router::response::Response> {
917 let token: &str = path_param::<Token>(cx);
918 let store = app(cx).store;
919 let now = OffsetDateTime::now_utc();
920 let link = store
921 .resolve_share_link(&hash_share_token(token), now)
922 .await
923 .ok()
924 .flatten();
925 let Some(link) = link else {
926 return dead_link(cx).await;
927 };
928 let Some(password_hash) = link.password_hash else {
929 // Nothing to unlock: the form has no business here. Back to the page.
930 return (
931 StatusCode::SEE_OTHER,
932 [(header::LOCATION, format!("/s/{token}"))],
933 )
934 .into_response(cx);
935 };
936 let candidate = input.password.unwrap_or_default();
937 // The proof needs the hash after the verify, so the verify gets a copy.
938 let hash_for_verify = password_hash.clone();
939 let matches =
940 tokio::task::spawn_blocking(move || link_password_matches(&hash_for_verify, &candidate))
941 .await
942 .unwrap_or(false);
943 if matches {
944 let proof = link_unlock_proof(token, &password_hash);
945 // Secure mirrors the session cookie: on when the identity provider
946 // itself is reached over https, so a plain-http rehearsal stays
947 // plain.
948 let secure = app(cx).config.oidc.issuer.starts_with("https://");
949 let name = link_cookie_name(&link.id);
950 cookies(cx).add(cookie! {
951 name = proof;
952 Path = "/s";
953 HttpOnly;
954 SameSite = Lax;
955 Secure = secure
956 });
957 (
958 StatusCode::SEE_OTHER,
959 [(header::LOCATION, format!("/s/{token}"))],
960 )
961 .into_response(cx)
962 } else {
963 (
964 StatusCode::SEE_OTHER,
965 [(header::LOCATION, format!("/s/{token}?wrong=1"))],
966 )
967 .into_response(cx)
968 }
969}
970
971/// The bytes behind a public link. A view-only link answers the dead card
972/// here — the same answer as a spent token — so the surface never says which
973/// tokens exist. The body streams off disk through
974/// [`crate::files::bytes_response`], the same shape the signed-in route
975/// serves: a range reads only its span, and no fetch buffers the file whole.
976async fn download_bytes(
977 cx: &Cx,
978 store: &dyn Store,
979 file_id: &str,
980 size_bytes: u64,
981 name: &str,
982 mime: &str,
983 can_download: bool,
984) -> topcoat::Result<topcoat::router::response::Response> {
985 use topcoat::router::response::IntoResponse;
986 use topcoat::router::{HeaderMap, HeaderValue};
987 if !can_download {
988 return dead_link(cx).await;
989 }
990 // A fetch counts once: a full fetch, or a range resuming from byte 0.
991 // A mid-file chunk is the same view going on, not a new one — the way
992 // the signed-in download route counts its first chunk only.
993 let range = request_headers(cx)
994 .get(header::RANGE)
995 .and_then(|value| value.to_str().ok());
996 let counts = match range {
997 None => true,
998 Some(header) => range_starts_at_zero(header),
999 };
1000 if counts {
1001 let _ = store.record_download(file_id).await;
1002 }
1003 let mut headers = HeaderMap::new();
1004 if let Ok(value) = HeaderValue::from_str(mime) {
1005 headers.insert(header::CONTENT_TYPE, value);
1006 }
1007 let disposition = format!("attachment; filename=\"{}\"", safe_name(name));
1008 if let Ok(value) = HeaderValue::from_str(&disposition) {
1009 headers.insert(header::CONTENT_DISPOSITION, value);
1010 }
1011 headers.insert(
1012 header::CACHE_CONTROL,
1013 HeaderValue::from_static("private, no-cache"),
1014 );
1015 let Some(parts) =
1016 crate::files::bytes_response(store, file_id, size_bytes, range, headers).await
1017 else {
1018 return dead_link(cx).await;
1019 };
1020 parts.into_response(cx)
1021}
1022
1023/// The inline media stream behind a public link: the bytes the card's
1024/// `<video>`/`<audio>` player draws from, through
1025/// [`crate::files::bytes_response`] — a range reads only its span, the way
1026/// every byte route here serves. Only the kinds the signed-in viewer plays
1027/// through their native elements answer: preview is what a view-only link
1028/// grants, but a document's bytes (pdf, text) would leak through the same
1029/// inline fetch, so anything else — and anything unservable — is the dead
1030/// card, like every other answer on this surface. Never an attachment, and
1031/// never counted as a download: a view is not a download.
1032async fn media_bytes(
1033 cx: &Cx,
1034 store: &dyn Store,
1035 file_id: &str,
1036 size_bytes: u64,
1037 name: &str,
1038 mime: &str,
1039) -> topcoat::Result<topcoat::router::response::Response> {
1040 use topcoat::router::response::IntoResponse;
1041 use topcoat::router::{HeaderMap, HeaderValue};
1042 if !matches!(
1043 viewer_kind(mime),
1044 Some(ViewerKind::Video | ViewerKind::Audio)
1045 ) {
1046 return dead_link(cx).await;
1047 }
1048 let range = request_headers(cx)
1049 .get(header::RANGE)
1050 .and_then(|value| value.to_str().ok());
1051 // The stored bytes under the stored mime: looking is what a view-only
1052 // link grants, and this grants nothing beyond it — there is no download
1053 // shape on this route, and `?dl=1` still answers the original or the
1054 // dead card.
1055 let mut headers = HeaderMap::new();
1056 if let Ok(value) = HeaderValue::from_str(mime) {
1057 headers.insert(header::CONTENT_TYPE, value);
1058 }
1059 let disposition = format!("inline; filename=\"{}\"", safe_name(name));
1060 if let Ok(value) = HeaderValue::from_str(&disposition) {
1061 headers.insert(header::CONTENT_DISPOSITION, value);
1062 }
1063 // Safari refuses to play a media element without a `206` reply to its
1064 // own `Range` probe; the signed-in byte route declares the same.
1065 headers.insert(header::ACCEPT_RANGES, HeaderValue::from_static("bytes"));
1066 headers.insert(
1067 header::CACHE_CONTROL,
1068 HeaderValue::from_static("private, no-cache"),
1069 );
1070 let Some(parts) =
1071 crate::files::bytes_response(store, file_id, size_bytes, range, headers).await
1072 else {
1073 return dead_link(cx).await;
1074 };
1075 parts.into_response(cx)
1076}
1077
1078/// Whether a `Range` header starts at byte 0: only those ranges (and the
1079/// header's absence) count a download. Anything else — a mid-file resume,
1080/// a suffix probe, several ranges, garbage — does not.
1081fn range_starts_at_zero(header: &str) -> bool {
1082 let Some(spec) = header.strip_prefix("bytes=") else {
1083 return false;
1084 };
1085 if spec.contains(',') {
1086 return false;
1087 }
1088 matches!(spec.split_once('-'), Some(("0", _)))
1089}
1090
1091/// The stored webp preview behind a public link. Unlike the bytes, the
1092/// preview is what a view-only link grants, so this answers regardless of
1093/// `can_download` — and anything unservable is the dead card, like every
1094/// other answer on this surface. Headers twin the `files.rs` thumbnail route.
1095async fn public_thumb(
1096 cx: &Cx,
1097 store: &dyn Store,
1098 file_id: &str,
1099) -> topcoat::Result<topcoat::router::response::Response> {
1100 use topcoat::router::response::IntoResponse;
1101 use topcoat::router::{HeaderMap, HeaderValue};
1102 let Ok(Some(bytes)) = store.thumb_bytes(file_id).await else {
1103 return dead_link(cx).await;
1104 };
1105 let etag = format!("\"{:x}\"", crate::files::fnv1a(&bytes));
1106 let mut headers = HeaderMap::new();
1107 headers.insert(
1108 header::ETAG,
1109 HeaderValue::from_str(&etag).unwrap_or(HeaderValue::from_static("\"0\"")),
1110 );
1111 headers.insert(
1112 header::CACHE_CONTROL,
1113 HeaderValue::from_static("private, max-age=31536000, immutable"),
1114 );
1115 headers.insert(header::CONTENT_TYPE, HeaderValue::from_static("image/webp"));
1116 let if_none_match = request_headers(cx)
1117 .get(header::IF_NONE_MATCH)
1118 .and_then(|value| value.to_str().ok());
1119 if if_none_match == Some(etag.as_str()) {
1120 return (StatusCode::NOT_MODIFIED, headers, Vec::new()).into_response(cx);
1121 }
1122 (StatusCode::OK, headers, bytes).into_response(cx)
1123}
1124
1125/// A filename safe for a header: quotes and backslashes stripped, never
1126/// empty.
1127fn safe_name(name: &str) -> String {
1128 let cleaned: String = name
1129 .chars()
1130 .filter(|c| !c.is_control() && *c != '"' && *c != '\\')
1131 .collect();
1132 if cleaned.is_empty() {
1133 "file".to_string()
1134 } else {
1135 cleaned
1136 }
1137}
1138
1139/// A shared file's card: its name, size and type, an image preview off the
1140/// public thumbnail route, the video/audio kinds through the house player
1141/// itself — [`crate::files::media_player`], the one markup + bar + script
1142/// the signed-in viewer renders, its classes (`media-player`, `media-el`,
1143/// `viewer-video`) verbatim, the stream off the public `?media=1` route —
1144/// and the download while the link allows it.
1145async fn file_card(
1146 cx: &Cx,
1147 link: &in_core::store::ShareLink,
1148 file: &in_core::store::File,
1149) -> topcoat::Result<topcoat::router::response::Response> {
1150 let language = lang(cx).await;
1151 let preview = file.mime.starts_with("image/");
1152 let token_path = current_path(cx);
1153 let media = viewer_kind(&file.mime);
1154 let media_src = format!("{token_path}?media=1");
1155 let page = view! {
1156 cx =>
1157 <main class="scaffold-note">
1158 (topcoat::view::Child::new(wordmark(cx).await?))
1159 <h1 class="settings-title">(file.name.clone())</h1>
1160 <p class="field-note">(format!("{} · {}", file.mime.clone(), crate::settings::human_bytes(file.size_bytes)))</p>
1161 if preview {
1162 <img src=(format!("{token_path}?thumb=1")) alt=(file.name.clone())>
1163 } else if matches!(media, Some(ViewerKind::Video)) {
1164 (topcoat::view::Child::new(media_player(cx, language, file.name.clone(), media_src.clone(), true).await?))
1165 } else if matches!(media, Some(ViewerKind::Audio)) {
1166 (topcoat::view::Child::new(media_player(cx, language, file.name.clone(), media_src.clone(), false).await?))
1167 } else {
1168 <p class="field-note">(t(language, Key::PreviewUnavailable))</p>
1169 }
1170 if link.can_download {
1171 <p><a class="primary" href=(format!("{token_path}?dl=1"))>(t(language, Key::Download))</a></p>
1172 } else {
1173 <p class="field-note">(format!("{} · {}", t(language, Key::ViewOnly), t(language, Key::ViewOnlyNote)))</p>
1174 }
1175 </main>
1176 (topcoat::view::Child::new(media_player_script(cx).await?))
1177 };
1178 public_page(cx, &file.name, page).await
1179}
1180
1181/// One file's chip on the public card: the link's own thumbnail where one
1182/// is ready, else the same mime-class glyph the signed-in lists wear.
1183/// `/thumb/{id}` needs a session, so this points at the public `?thumb=1`
1184async fn public_chip<'a>(
1185 cx: &'a Cx,
1186 thumb_src: &str,
1187 file: &in_core::store::File,
1188) -> Result<impl View + 'a> {
1189 if file.thumb_state == ThumbState::Ready {
1190 let src = thumb_src.to_string();
1191 return Ok(view! {
1192 cx =>
1193 <img class="file-chip" src=(src) alt="">
1194 }
1195 .boxed());
1196 }
1197 Ok(entry_chip(cx, file).await?.boxed())
1198}
1199
1200async fn shared_chip<'a>(cx: &'a Cx, file: &in_core::store::File) -> Result<impl View + 'a> {
1201 if file.deleted_at.is_some() {
1202 let mut unthumb = file.clone();
1203 unthumb.thumb_state = ThumbState::None;
1204 return Ok(entry_chip(cx, &unthumb).await?.boxed());
1205 }
1206 Ok(entry_chip(cx, file).await?.boxed())
1207}
1208
1209/// One row of the public folder listing, folder or file, for the unified
1210/// list.
1211enum PublicEntry<'a> {
1212 Folder(&'a in_core::store::Folder),
1213 File(&'a in_core::store::File),
1214}
1215
1216impl PublicEntry<'_> {
1217 fn name(&self) -> &str {
1218 match self {
1219 PublicEntry::Folder(folder) => &folder.name,
1220 PublicEntry::File(file) => &file.name,
1221 }
1222 }
1223}
1224
1225/// A shared folder's listing: folders and files in one list, downloads
1226/// gated on the link's flag. Subfolders browse in place under the same
1227/// token.
1228async fn folder_card(
1229 cx: &Cx,
1230 store: &dyn Store,
1231 link: &in_core::store::ShareLink,
1232 root: &in_core::store::Folder,
1233 at: &str,
1234 token: &str,
1235) -> topcoat::Result<topcoat::router::response::Response> {
1236 let language = lang(cx).await;
1237 let here = store.folder(at).await?;
1238 let Some(here) = here else {
1239 return dead_link(cx).await;
1240 };
1241 let listing = store.list_children(&root.owner_id, Some(at)).await?;
1242 let base = format!("/s/{token}");
1243 let mut rows: Vec<PublicEntry> = Vec::new();
1244 rows.extend(listing.folders.iter().map(PublicEntry::Folder));
1245 rows.extend(listing.files.iter().map(PublicEntry::File));
1246 rows.sort_by_key(|row| row.name().to_lowercase());
1247 let page = view! {
1248 cx =>
1249 (topcoat::view::Child::new(wordmark(cx).await?))
1250 <main class="settings-stage stage-wide">
1251 <h1 class="settings-title">(here.name.clone())</h1>
1252 <section class="panel">
1253 <div class="panel-body">
1254 if !link.can_download {
1255 <p class="field-note">(t(language, Key::ViewOnlyNote))</p>
1256 }
1257 if rows.is_empty() {
1258 <p class="field-note">(t(language, Key::EmptyFolder))</p>
1259 }
1260 for row in &rows {
1261 match row {
1262 PublicEntry::Folder(folder) => <div class="dep-row">
1263 <span class="file-chip file-chip-folder" aria-hidden="true">"▤"</span>
1264 <a class="dep-link" href=(format!("{base}?folder={}", folder.id))><span class="dep-title">(folder.name.clone())</span></a>
1265 </div>,
1266 PublicEntry::File(file) => <div class="dep-row">
1267 (topcoat::view::Child::new(public_chip(cx, &format!("{base}?folder={at}&file={}&thumb=1", file.id), file).await?))
1268 <span class="member-name dep-title">(file.name.clone())</span>
1269 <span class="field-note">(crate::settings::human_bytes(file.size_bytes))</span>
1270 <div class="spacer"></div>
1271 if link.can_download {
1272 <a class="quiet" href=(format!("{base}?folder={at}&file={}&dl=1", file.id))>(t(language, Key::Download))</a>
1273 } else {
1274 <span class="field-note">(t(language, Key::ViewOnly))</span>
1275 }
1276 </div>,
1277 }
1278 }
1279 </div>
1280 </section>
1281 </main>
1282 };
1283 public_page(cx, &root.name, page).await
1284}
1285
1286/// The request's own path, without its query: the download links the public
1287/// cards render point back at the same token.
1288fn current_path(cx: &Cx) -> String {
1289 let path = uri(cx).path();
1290 if path.is_empty() {
1291 "/".to_string()
1292 } else {
1293 path.to_string()
1294 }
1295}
1296
1297#[query_params]
1298struct SharedPageQuery {
1299 sort: Option<String>,
1300 kind: Option<String>,
1301 q: Option<String>,
1302}
1303
1304/// The shared list's sort, off the query as `key:direction` ("owner:desc"):
1305/// name, uploaded, size or owner; name and owner ascend by default, the
1306/// measures descend. Anything else is the default — by name.
1307fn valid_shared_sort(raw: Option<&str>) -> (&'static str, bool) {
1308 let (key, dir) = raw
1309 .unwrap_or("")
1310 .split_once(':')
1311 .unwrap_or((raw.unwrap_or(""), ""));
1312 let key = match key {
1313 "name" => "name",
1314 "uploaded" => "uploaded",
1315 "size" => "size",
1316 "owner" => "owner",
1317 _ => "name",
1318 };
1319 let descending = match dir {
1320 "asc" => false,
1321 "desc" => true,
1322 _ => matches!(key, "uploaded" | "size"),
1323 };
1324 (key, descending)
1325}
1326
1327/// The kind filter, off the query: all, folders or files. Anything else
1328/// shows everything.
1329fn valid_shared_kind(raw: Option<&str>) -> &'static str {
1330 match raw {
1331 Some("folders") => "folders",
1332 Some("files") => "files",
1333 _ => "all",
1334 }
1335}
1336
1337/// One grant with the target's own dates and counters, for the unified
1338/// list. The file row stays aboard for the list chip; folders carry none.
1339struct SharedRow {
1340 item: in_core::store::SharedItem,
1341 owner_name: String,
1342 file: Option<in_core::store::File>,
1343 uploaded: OffsetDateTime,
1344}
1345
1346impl SharedRow {
1347 fn size(&self) -> u64 {
1348 self.file.as_ref().map(|file| file.size_bytes).unwrap_or(0)
1349 }
1350}
1351
1352/// Everything others shared with the reader, folders and files in one
1353/// list. The reader's own library never appears here.
1354#[page("/shared")]
1355async fn shared(cx: &Cx) -> Result<impl View> {
1356 let user = match require_user(cx).await {
1357 Ok(user) => user,
1358 Err(refusal) => {
1359 let language = lang(cx).await;
1360 return Ok(view! {
1361 cx =>
1362 <main class="scaffold-note">
1363 <p>(refusal.message_in(language))</p>
1364 <p><a href="/">(t(language, Key::BackToDrive))</a></p>
1365 </main>
1366 }
1367 .boxed());
1368 }
1369 };
1370 let language = lang(cx).await;
1371 let params = query_params::<SharedPageQuery>(cx).ok();
1372 let sort = valid_shared_sort(params.as_ref().and_then(|query| query.sort.as_deref()));
1373 let kind = valid_shared_kind(params.as_ref().and_then(|query| query.kind.as_deref()));
1374 let asked = params
1375 .as_ref()
1376 .and_then(|query| query.q.clone())
1377 .map(|query| query.trim().to_string())
1378 .filter(|query| !query.is_empty());
1379 let box_text = asked.clone().unwrap_or_default();
1380 let store = app(cx).store;
1381 let items = store.shares_for_user(&user.id).await?;
1382 let mut owners: std::collections::HashMap<String, String> = std::collections::HashMap::new();
1383 for item in &items {
1384 if !owners.contains_key(&item.owner_id) {
1385 let name = store
1386 .user(&item.owner_id)
1387 .await
1388 .ok()
1389 .flatten()
1390 .map(|owner| owner.display_name)
1391 .unwrap_or_default();
1392 owners.insert(item.owner_id.clone(), name);
1393 }
1394 }
1395 let mut rows: Vec<SharedRow> = Vec::new();
1396 for item in items {
1397 if kind == "folders" && item.kind != ShareKind::Folder {
1398 continue;
1399 }
1400 if kind == "files" && item.kind != ShareKind::File {
1401 continue;
1402 }
1403 if let Some(needle) = asked.as_deref()
1404 && !item.name.to_lowercase().contains(&needle.to_lowercase())
1405 {
1406 continue;
1407 }
1408 let owner_name = owners.get(&item.owner_id).cloned().unwrap_or_default();
1409 // The grant carries no dates or counters of its own: the file row
1410 // brings the upload date, size and downloads, the folder row its
1411 // upload date. A target that went missing since the grant keeps
1412 // its row on the grant's own date.
1413 let (file, uploaded) = match item.kind {
1414 ShareKind::File => match store.file(&item.target_id).await.ok().flatten() {
1415 Some(file) => {
1416 let uploaded = file.created_at;
1417 (Some(file), uploaded)
1418 }
1419 None => (None, item.created_at),
1420 },
1421 ShareKind::Folder => {
1422 let uploaded = store
1423 .folder(&item.target_id)
1424 .await
1425 .ok()
1426 .flatten()
1427 .map(|folder| folder.created_at)
1428 .unwrap_or(item.created_at);
1429 (None, uploaded)
1430 }
1431 };
1432 rows.push(SharedRow {
1433 item,
1434 owner_name,
1435 file,
1436 uploaded,
1437 });
1438 }
1439 let nothing_shared = rows.is_empty() && asked.is_none() && kind == "all";
1440 let (sort, descending) = sort;
1441 rows.sort_by(|a, b| {
1442 let order = match sort {
1443 "uploaded" => a
1444 .uploaded
1445 .cmp(&b.uploaded)
1446 .then_with(|| a.item.name.to_lowercase().cmp(&b.item.name.to_lowercase())),
1447 "size" => a
1448 .size()
1449 .cmp(&b.size())
1450 .then_with(|| a.item.name.to_lowercase().cmp(&b.item.name.to_lowercase())),
1451 "owner" => a
1452 .owner_name
1453 .to_lowercase()
1454 .cmp(&b.owner_name.to_lowercase())
1455 .then_with(|| a.item.name.to_lowercase().cmp(&b.item.name.to_lowercase())),
1456 _ => a
1457 .item
1458 .name
1459 .to_lowercase()
1460 .cmp(&b.item.name.to_lowercase())
1461 .then_with(|| a.item.target_id.cmp(&b.item.target_id)),
1462 };
1463 if descending { order.reverse() } else { order }
1464 });
1465 let sort_value = format!("{}:{}", sort, if descending { "desc" } else { "asc" });
1466 Ok(view! {
1467 cx =>
1468 (topcoat::view::Child::new(topbar(cx, NavPage::Shared, &user, language).await?))
1469 <main class="settings-stage stage-wide">
1470 <h1 class="settings-title">(t(language, Key::SharedWithMe))</h1>
1471 <div class="filterbar">
1472 <form class="field-box field-box-search" method="get" action="/shared">
1473 <span class="field-text">(t(language, Key::NavSearch))</span>
1474 <input
1475 class="filter-search"
1476 type="search"
1477 name="q"
1478 value=(box_text.clone())
1479 placeholder=(t(language, Key::SearchPlaceholder))
1480 aria-label=(t(language, Key::SearchPlaceholder))
1481 >
1482 <input type="hidden" name="sort" value=(sort.to_string())>
1483 <input type="hidden" name="kind" value=(kind.to_string())>
1484 </form>
1485 <form class="field-box field-box-sort" method="get" action="/shared">
1486 <span class="field-text">(t(language, Key::Sort))</span>
1487 <select class="status-select" name="sort" data-autosubmit="" aria-label=(t(language, Key::Sort))>
1488 <option value="name:asc" selected=(sort_value == "name:asc")>(t(language, Key::SortNameAZ))</option>
1489 <option value="name:desc" selected=(sort_value == "name:desc")>(t(language, Key::SortNameZA))</option>
1490 <option value="uploaded:desc" selected=(sort_value == "uploaded:desc")>(t(language, Key::SortNewest))</option>
1491 <option value="uploaded:asc" selected=(sort_value == "uploaded:asc")>(t(language, Key::SortOldest))</option>
1492 <option value="size:desc" selected=(sort_value == "size:desc")>(t(language, Key::SortLargest))</option>
1493 <option value="size:asc" selected=(sort_value == "size:asc")>(t(language, Key::SortSmallest))</option>
1494 <option value="owner:asc" selected=(sort_value == "owner:asc")>(t(language, Key::SortOwnerAZ))</option>
1495 <option value="owner:desc" selected=(sort_value == "owner:desc")>(t(language, Key::SortOwnerZA))</option>
1496 </select>
1497 <input type="hidden" name="kind" value=(kind.to_string())>
1498 <input type="hidden" name="q" value=(box_text.clone())>
1499 </form>
1500 <form class="field-box field-box-sort" method="get" action="/shared">
1501 <span class="field-text">(t(language, Key::Kind))</span>
1502 <select class="status-select" name="kind" data-autosubmit="" aria-label=(t(language, Key::Kind))>
1503 <option value="all" selected=(kind == "all")>(t(language, Key::KindAll))</option>
1504 <option value="folders" selected=(kind == "folders")>(t(language, Key::KindFolders))</option>
1505 <option value="files" selected=(kind == "files")>(t(language, Key::KindFiles))</option>
1506 </select>
1507 <input type="hidden" name="sort" value=(sort.to_string())>
1508 <input type="hidden" name="q" value=(box_text.clone())>
1509 </form>
1510 </div>
1511 if rows.iter().any(|row| !row.item.can_download) {
1512 <p class="field-note">(t(language, Key::ViewOnlyNote))</p>
1513 }
1514 <section class="panel drive-panel drive-owner">
1515 if rows.is_empty() {
1516 <div class="drive-empty">
1517 <span class="drive-empty-glyph" aria-hidden="true">"▤"</span>
1518 <p class="drive-empty-text">(t(language, if nothing_shared { Key::NoSharedItems } else { Key::NoResults }))</p>
1519 </div>
1520 } else {
1521 <div class="drive-head">
1522 <span class="drive-cols">
1523 <span class="drive-col-ico" aria-hidden="true"></span>
1524 <span>(t(language, Key::NameColumn))</span>
1525 <span class="drive-col-num drive-col-size">(t(language, Key::SizeColumn))</span>
1526 <span class="drive-col-date">(t(language, Key::ModifiedColumn))</span>
1527 <span class="drive-col-num drive-col-dl">(t(language, Key::OwnerColumn))</span>
1528 </span>
1529 </div>
1530 <div class="drive-list">
1531 for row in &rows {
1532 // The grant's facts ride the whole row: the last cell
1533 // names who opened it and how far the opening goes.
1534 <div class="drive-row">
1535 <a class="drive-open" href=(match row.item.kind {
1536 ShareKind::Folder => format!("/drive?folder={}", row.item.target_id),
1537 ShareKind::File => format!("/view/{}?from=shared", row.item.target_id),
1538 })>
1539 if row.item.kind == ShareKind::Folder {
1540 <span class="file-chip file-chip-folder" aria-hidden="true">"▤"</span>
1541 } else {
1542 match &row.file {
1543 Some(file) => (topcoat::view::Child::new(shared_chip(cx, file).await?)),
1544 None => <span class="file-chip file-chip-generic" aria-hidden="true">"▦"</span>,
1545 }
1546 }
1547 <span class="dep-title">(row.item.name.clone())</span>
1548 if row.item.kind == ShareKind::File {
1549 <span class="drive-meta drive-size">(crate::drive::human_size(row.size()))</span>
1550 } else {
1551 <span class="drive-meta" aria-hidden="true"></span>
1552 }
1553 <span class="drive-meta drive-date">(row.uploaded.date().to_string())</span>
1554 <span class="drive-meta drive-dl">(format!("{} · {}", row.owner_name, access_chip(language, row.item.can_download)))</span>
1555 </a>
1556 </div>
1557 }
1558 </div>
1559 }
1560 </section>
1561 </main>
1562 (topcoat::view::Child::new(crate::dropdown::dropdown_script(cx).await?))
1563 }.boxed())
1564}
1565
1566/// What the grant opens: the download, or the view alone.
1567pub(crate) fn access_chip(language: Lang, can_download: bool) -> &'static str {
1568 if can_download {
1569 t(language, Key::CanDownload)
1570 } else {
1571 t(language, Key::ViewOnly)
1572 }
1573}
1574
1575/// The share modal: the drive row's Share item links to `?share=kind:id`
1576/// and the drive page renders this over itself — the Proton-style dialog
1577/// (add-people row, who-has-access list, public-link section), not a
1578/// separate page. `None` when the target is missing, trashed, or not the
1579/// reader's — a hand-edited `?share=` pair simply opens nothing.
1580///
1581/// Every form inside posts to the existing share routes and comes back
1582/// through `Referer`, so the modal survives them; the minted token's
1583/// copy-once banner rides the `?created=` pair into the modal itself.
1584pub(crate) async fn share_modal<'a>(
1585 cx: &'a Cx,
1586 kind_raw: &str,
1587 target_id: &str,
1588 close_href: &str,
1589 created: Option<String>,
1590) -> Result<Option<impl View + 'a>> {
1591 let Some(kind) = parse_kind(kind_raw) else {
1592 return Ok(None);
1593 };
1594 let user = match require_user(cx).await {
1595 Ok(user) => user,
1596 Err(_) => return Ok(None),
1597 };
1598 let language = lang(cx).await;
1599 // The links this modal shows carry the public origin — the admin-set
1600 // `base_url` setting when one is stored, else the config chain: the
1601 // file's `base_url`, else the bound address.
1602 let origin = share_origin(cx).await;
1603 let store = app(cx).store.clone();
1604 // The owned, live target: present, untrashed, and theirs. Anything else
1605 // opens nothing — a stranger learns not even whose it is.
1606 let (name, file): (String, Option<File>) = match kind {
1607 ShareKind::File => {
1608 let Some(file) = store.file(target_id).await? else {
1609 return Ok(None);
1610 };
1611 if file.owner_id != user.id || file.deleted_at.is_some() {
1612 return Ok(None);
1613 }
1614 (file.name.clone(), Some(file))
1615 }
1616 ShareKind::Folder => {
1617 let Some(folder) = store.folder(target_id).await? else {
1618 return Ok(None);
1619 };
1620 if folder.owner_id != user.id || folder.deleted_at.is_some() {
1621 return Ok(None);
1622 }
1623 (folder.name.clone(), None)
1624 }
1625 };
1626 let links = store.share_links(&user.id).await?;
1627 let live: Vec<_> = links
1628 .into_iter()
1629 .filter(|link| {
1630 // An expired link is as dead as a revoked one for form purposes:
1631 // it must not suppress the create form.
1632 link.kind == kind
1633 && link.target_id == target_id
1634 && link.revoked_at.is_none()
1635 && link
1636 .expires_at
1637 .is_none_or(|at| at > OffsetDateTime::now_utc())
1638 })
1639 .collect();
1640 let grants = match store.shares_for_target(&user.id, kind, target_id).await {
1641 Ok(grants) => grants,
1642 Err(StoreError::NotFound) | Err(StoreError::CrossOwner) => return Ok(None),
1643 Err(error) => return Err(error.into()),
1644 };
1645 let mut people: Vec<(String, String, bool)> = Vec::new();
1646 for grant in &grants {
1647 if let Some(grantee) = store.user(&grant.user_id).await? {
1648 people.push((grantee.display_name, grantee.email, grant.can_download));
1649 }
1650 }
1651 // The shareable people come from im's directory: each entry mirrored
1652 // into a local user row here, so the address the form posts resolves
1653 // the way a typed one would — then the owner, anyone already on the
1654 // list above, and any locally-disabled account are taken back out
1655 // (im's directory not naming someone disabled here must not offer
1656 // them). A directory that does not answer, or answers nobody new,
1657 // leaves the typed-address field in place below.
1658 let default_quota = app(cx).config.default_quota_bytes;
1659 let mut candidates: Vec<User> = Vec::new();
1660 if let Ok(members) = app(cx).directory.directory().await {
1661 for member in members {
1662 let row = store
1663 .provision_user(
1664 &member.sub,
1665 &member.email,
1666 &member.name,
1667 Some(member.admin),
1668 member.photo_version,
1669 default_quota,
1670 )
1671 .await?;
1672 if !row.disabled
1673 && row.id != user.id
1674 && !people.iter().any(|(_, email, _)| *email == row.email)
1675 {
1676 candidates.push(row);
1677 }
1678 }
1679 }
1680 candidates.sort_by(|a, b| a.display_name.cmp(&b.display_name));
1681 let refusal = query_value(uri(cx).query().unwrap_or(""), "refusal")
1682 .and_then(|code| Refusal::from_code(&code));
1683 let target_id = target_id.to_string();
1684 let close_href = close_href.to_string();
1685 Ok(Some(view! {
1686 cx =>
1687 <div class="modal-scrim">
1688 <div class="modal share-modal">
1689 <div class="viewer-head">
1690 <h2 class="settings-title share-modal-title">
1691 if kind == ShareKind::Folder {
1692 <span class="file-chip file-chip-folder" aria-hidden="true">"▤"</span>
1693 }
1694 if let Some(file) = file.as_ref() {
1695 (topcoat::view::Child::new(entry_chip(cx, file).await?))
1696 }
1697 (format!("{} “{}”", t(language, Key::Share), name.clone()))
1698 </h2>
1699 <div class="spacer"></div>
1700 <a class="quiet" href=(close_href.to_string()) aria-label=(t(language, Key::Close))>(t(language, Key::Close))</a>
1701 </div>
1702 if let Some(refusal) = refusal {
1703 <p class="field-error share-modal-note">(refusal.message_in(language))</p>
1704 }
1705 if let Some(token) = created {
1706 <p class="field-note share-modal-note">(t(language, Key::CopyLinkOnce))</p>
1707 <div class="share-link-row">
1708 <p class="member-link-value share-link-url" aria-label=(t(language, Key::ShareLink))>(format!("{origin}/s/{token}"))</p>
1709 <button class="quiet share-copy" type="button" data-copied-label=(t(language, Key::Copied))>(t(language, Key::CopyLink))</button>
1710 </div>
1711 }
1712 <form class="pop-row-form share-add" method="post" action="/api/share/user/add">
1713 <input type="hidden" name="kind" value=(kind.as_str())>
1714 <input type="hidden" name="target_id" value=(target_id.to_string())>
1715 if candidates.is_empty() {
1716 <input class="field-input share-add-email" type="email" name="email" required="" placeholder=(t(language, Key::SharePlaceholder)) aria-label=(t(language, Key::EmailAddress))>
1717 } else {
1718 <div class="share-picker pop-panel" role="group" aria-label=(t(language, Key::SharePickPerson))>
1719 // The filter doubles as the typed-address fallback: it
1720 // carries `name="email"`, so typing an address and
1721 // submitting without script still grants that person.
1722 // With script it only filters — the script half benches
1723 // it on submit whenever rows are checked, and the
1724 // route skips the blank pair a checkbox-only post
1725 // carries beside the checked values.
1726 <input class="field-input share-pick-filter" type="email" name="email" placeholder=(t(language, Key::SharePickPerson)) aria-label=(t(language, Key::SharePickPerson))>
1727 <label class="pop-row share-pick-row share-pick-all">
1728 <input type="checkbox" class="share-all-toggle" aria-label=(t(language, Key::ShareEveryone))>
1729 <svg class="glyph share-pick-glyph" width="12" height="12" viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M2.5 8.5l3.5 3.5 7.5-8"></path></svg>
1730 <span class="pop-row-name">(t(language, Key::ShareEveryone))</span>
1731 </label>
1732 <div class="pop-list pop-list-scroll">
1733 for person in &candidates {
1734 <label class="pop-row share-pick-row">
1735 <input type="checkbox" name="email" value=(person.email.clone())>
1736 <svg class="glyph share-pick-glyph" width="12" height="12" viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M2.5 8.5l3.5 3.5 7.5-8"></path></svg>
1737 <span class="pop-row-name">(person.display_name.clone())</span>
1738 <span class="share-pick-mail">(person.email.clone())</span>
1739 </label>
1740 }
1741 // Ships hidden: only the script ever shows it,
1742 // when the filter matches no row.
1743 <p class="field-note share-pick-none share-pick-off">(t(language, Key::ShareNoMatch))</p>
1744 </div>
1745 </div>
1746 }
1747 <select class="field-input share-add-access" name="can_download" aria-label=(t(language, Key::CanDownload))>
1748 <option value="1">(t(language, Key::CanDownload))</option>
1749 <option value="0">(t(language, Key::ViewOnly))</option>
1750 </select>
1751 <button class="quiet" type="submit">(t(language, Key::Share))</button>
1752 </form>
1753 <p class="field-note share-modal-note">(t(language, Key::ViewOnlyNote))</p>
1754 <p class="share-section">(t(language, Key::WhoHasAccess))</p>
1755 <div class="member-row share-owner">
1756 <span class="member-name">(format!("{} {}", user.display_name.clone(), t(language, Key::YouSuffix)))</span>
1757 <span class="field-note">(user.email.clone())</span>
1758 <div class="spacer"></div>
1759 <span class="field-note">(t(language, Key::OwnerRole))</span>
1760 </div>
1761 for person in &people {
1762 <div class="member-row">
1763 <span class="member-name">(person.0.clone())</span>
1764 <span class="field-note">(person.1.clone())</span>
1765 <div class="spacer"></div>
1766 <span class="field-note">(access_chip(language, person.2))</span>
1767 <form class="pop-row-form" method="post" action="/api/share/user/remove">
1768 <input type="hidden" name="kind" value=(kind.as_str())>
1769 <input type="hidden" name="target_id" value=(target_id.to_string())>
1770 <input type="hidden" name="email" value=(person.1.clone())>
1771 <button class="quiet" type="submit">(t(language, Key::RemoveAccess))</button>
1772 </form>
1773 </div>
1774 }
1775 <p class="share-section">(t(language, Key::PublicLinkLabel))</p>
1776 if live.is_empty() {
1777 <form class="pop-row-form" method="post" action="/api/share/link/create">
1778 <input type="hidden" name="kind" value=(kind.as_str())>
1779 <input type="hidden" name="target_id" value=(target_id.to_string())>
1780 <span class="field-note">(t(language, Key::NotActive))</span>
1781 <div class="spacer"></div>
1782 <select class="field-input" name="can_download" aria-label=(t(language, Key::CanDownload))>
1783 <option value="1">(t(language, Key::CanDownload))</option>
1784 <option value="0">(t(language, Key::ViewOnly))</option>
1785 </select>
1786 <input class="field-input share-expiry" type="number" name="expires_in_days" min="1" step="1" placeholder=(t(language, Key::ExpiresInDays)) aria-label=(t(language, Key::ExpiresInDays))>
1787 <input class="field-input share-expiry" type="password" name="password" autocomplete="new-password" placeholder=(t(language, Key::PasswordOptional)) aria-label=(t(language, Key::PasswordOptional))>
1788 <button class="quiet" type="submit">(t(language, Key::CreateLink))</button>
1789 </form>
1790 <p class="field-note share-modal-note">(t(language, Key::ViewOnlyNote))</p>
1791 }
1792 for link in live.iter().take(1) {
1793 // away. A link from before the sealing — or one whose key is gone —
1794 // has no address to re-show: the row carries the mint action and the
1795 // note below states the fact.
1796 let url = share_link_url(cx, link).await;
1797 let legacy = url.is_none();
1798 <div class="member-row">
1799 <span class="member-name">(t(language, Key::AnyoneWithLink))</span>
1800 <div class="spacer"></div>
1801 <span class="field-note">(expiry_line(language, link.expires_at))</span>
1802 if link.password_hash.is_some() {
1803 <span class="field-note">"▪ "(t(language, Key::PasswordLabel))</span>
1804 }
1805 <span class="field-note">(access_chip(language, link.can_download))</span>
1806 </div>
1807 <div class="share-link-row">
1808 if let Some(url) = url {
1809 <p class="member-link-value share-link-url" aria-label=(t(language, Key::ShareLink))>(url)</p>
1810 <button class="quiet share-copy" type="button" data-copied-label=(t(language, Key::Copied))>(t(language, Key::CopyLink))</button>
1811 } else {
1812 <form class="pop-row-form" method="post" action="/api/share/link/remint">
1813 <input type="hidden" name="id" value=(link.id.clone())>
1814 <button class="quiet" type="submit">(t(language, Key::RemintLink))</button>
1815 </form>
1816 }
1817 <form class="pop-row-form" method="post" action="/api/share/link/revoke">
1818 <input type="hidden" name="id" value=(link.id.clone())>
1819 <button class="quiet quiet-danger" type="submit">(t(language, Key::RevokeLink))</button>
1820 </form>
1821 </div>
1822 if legacy {
1823 <p class="share-link-note">(t(language, Key::LegacyLinkNote))</p>
1824 }
1825 }
1826 </div>
1827 </div>
1828 (topcoat::view::Child::new(share_copy_script(cx).await?))
1829 (topcoat::view::Child::new(share_pick_script(cx).await?))
1830 }.boxed()))
1831}
1832
1833/// The link row's copy client: one delegated listener, idempotent across
1834/// re-renders (`window.__inShareCopy` guards it), so the `in:wire` morph
1835/// needs no per-element re-init. A click on the copy button or on the
1836/// wrapping link text itself copies the full address — and only where a
1837/// copy button is present: the masked legacy rows carry none, so their
1838/// placeholder can never reach a clipboard.
1839pub(crate) async fn share_copy_script<'a>(cx: &'a Cx) -> Result<impl View + 'a> {
1840 use topcoat::view::Unescaped;
1841 const JS: &str = "\
1842 (function () { \
1843 if (window.__inShareCopy) { return; } \
1844 window.__inShareCopy = true; \
1845 document.addEventListener('click', function (e) { \
1846 if (!e.target || !e.target.closest) { return; } \
1847 var hit = e.target.closest('.share-copy, .share-link-url'); \
1848 if (!hit) { return; } \
1849 var row = hit.closest('.share-link-row'); \
1850 if (!row) { return; } \
1851 var b = row.querySelector('.share-copy'); \
1852 var u = row.querySelector('.share-link-url'); \
1853 if (!b || !u) { return; } \
1854 if (document.createRange && window.getSelection) { \
1855 var r = document.createRange(); r.selectNodeContents(u); \
1856 var s = window.getSelection(); s.removeAllRanges(); s.addRange(r); \
1857 } \
1858 var done = function () { b.textContent = b.getAttribute('data-copied-label'); }; \
1859 if (navigator.clipboard && navigator.clipboard.writeText) { navigator.clipboard.writeText(u.textContent).then(done, done); } \
1860 else { try { document.execCommand('copy'); } catch (err) {} done(); } \
1861 }); \
1862 })();";
1863 Ok(view! { cx => <script>(Unescaped::new_unchecked(JS))</script> }.boxed())
1864}
1865
1866/// The people picker's client half. The All row checks and unchecks every
1867/// candidate, and hand-checking rows keeps the All row honest. The filter
1868/// field narrows the rows live — substring, case-insensitive, against name
1869/// and address — and hides itself down to the Everyone row when no filter
1870/// word matches. The same field carries the no-script typed-address post,
1871/// so on submit it is benched whenever rows are checked: its half-typed
1872/// text must not ride beside them. The first keystroke also locks the
1873/// panel at its full, unfiltered height — the rows the filter hides would
1874/// otherwise shrink the modal under it, jumping everything below with
1875/// every letter — and a panel reborn through a morph re-render locks
1876/// anew. Delegated listeners only, idempotent across the modal's
1877/// re-renders (`window.__inSharePick` guards it), so the `in:wire` morph
1878/// needs no per-element re-init.
1879pub(crate) async fn share_pick_script<'a>(cx: &'a Cx) -> Result<impl View + 'a> {
1880 use topcoat::view::Unescaped;
1881 const JS: &str = "\
1882 (function () { \
1883 if (window.__inSharePick) { return; } \
1884 window.__inSharePick = true; \
1885 function rows(box) { return Array.prototype.slice.call(box.querySelectorAll('.pop-list input[type=checkbox]')); } \
1886 function pickRows(box) { return Array.prototype.slice.call(box.querySelectorAll('.pop-list .share-pick-row')); } \
1887 document.addEventListener('submit', function (e) { \
1888 var form = e.target; \
1889 if (!form || !form.classList || !form.classList.contains('share-add')) { return; } \
1890 var box = form.querySelector('.share-picker'); \
1891 if (!box) { return; } \
1892 var filter = box.querySelector('.share-pick-filter'); \
1893 if (filter && box.querySelector('.pop-list input[type=checkbox]:checked')) { \
1894 filter.disabled = true; \
1895 setTimeout(function () { filter.disabled = false; }, 0); \
1896 } \
1897 }); \
1898 document.addEventListener('input', function (e) { \
1899 var t = e.target; \
1900 if (!t || !t.classList || !t.classList.contains('share-pick-filter')) { return; } \
1901 var box = t.closest('.share-picker'); \
1902 if (!box) { return; } \
1903 if (!box.style.minHeight) { box.style.minHeight = box.getBoundingClientRect().height + 'px'; } \
1904 var needle = t.value.trim().toLowerCase(); \
1905 var shown = 0; \
1906 pickRows(box).forEach(function (row) { \
1907 var hit = !needle || row.textContent.toLowerCase().indexOf(needle) !== -1; \
1908 row.classList.toggle('share-pick-off', !hit); \
1909 if (hit) { shown += 1; } \
1910 }); \
1911 var word = needle === '' || needle.indexOf('everyone') !== -1 || needle.indexOf('herkes') !== -1 || needle.indexOf('all') !== -1; \
1912 var all = box.querySelector('.share-pick-all'); \
1913 if (all) { all.classList.toggle('share-pick-off', !word); } \
1914 var none = box.querySelector('.share-pick-none'); \
1915 if (none) { none.classList.toggle('share-pick-off', needle === '' || shown > 0 || word); } \
1916 }); \
1917 document.addEventListener('change', function (e) { \
1918 var t = e.target; \
1919 if (!t || !t.closest) { return; } \
1920 var box = t.closest('.share-picker'); \
1921 if (!box) { return; } \
1922 if (t.classList.contains('share-all-toggle')) { \
1923 rows(box).forEach(function (cb) { cb.checked = t.checked; }); \
1924 } else { \
1925 var all = box.querySelector('.share-all-toggle'); \
1926 var list = rows(box); \
1927 if (all) { all.checked = list.length > 0 && list.every(function (cb) { return cb.checked; }); } \
1928 } \
1929 }); \
1930 })();";
1931 Ok(view! { cx => <script>(Unescaped::new_unchecked(JS))</script> }.boxed())
1932}
1933
1934/// When the link stops opening, or never on its own. Twins the settings
1935/// page's helper; the share page renders the same expiry line.
1936fn expiry_line(language: Lang, expires_at: Option<OffsetDateTime>) -> String {
1937 match expires_at {
1938 Some(at) => format!(
1939 "{} {}",
1940 t(language, Key::ExpiresLabel),
1941 at.format(&time::format_description::well_known::Rfc3339)
1942 .unwrap_or_else(|_| "?".to_string())
1943 ),
1944 None => t(language, Key::NeverExpires).to_string(),
1945 }
1946}