api.rs
⎇
Raw
1//! Typed HTTP client for the filebrowser-ng API.
2//!
3//! Endpoint paths, query params and wire types all come from the shared
4//! `api_types` crate (the same one the server's route table and handlers
5//! use), so the two sides cannot drift apart.
6
7use serde::Serialize;
8use serde::de::DeserializeOwned;
9use wasm_bindgen::JsCast;
10use wasm_bindgen::JsValue;
11use wasm_bindgen_futures::JsFuture;
12
13use api_types::{
14 ACTION_CONTENT, ACTION_CREATE_FILE, ACTION_DOWNLOAD, ACTION_MKDIR, ACTION_PREVIEW,
15 ADMIN_SETTINGS, ADMIN_USERS, AUTH_LOGIN, AUTH_LOGOUT, AUTH_ME, AUTH_SETUP, CreateShare,
16 CreateUser, Credentials, FILES, Mutation, P_ACTION, P_FORMAT, P_OVERWRITE, P_SHARE, Root,
17 SHARE, SHARES, Settings, UpdateUser,
18};
19pub use api_types::{
20 AdminUser, Entry, FilesResp, Me, Mode, OkResp, Op, RootInfo, SaveResp, ShareInfo, UserInfo,
21};
22
23#[derive(Debug, thiserror::Error)]
24pub enum ApiError {
25 /// Non-2xx response. `skipped` carries the server's conflict file list
26 /// when present (upload conflicts).
27 #[error("{message}")]
28 Http {
29 #[allow(dead_code)]
30 status: u16,
31 message: String,
32 skipped: Option<Vec<String>>,
33 },
34 /// The file changed on disk since it was read (save conflict, HTTP 409).
35 #[error("the file was changed on disk")]
36 Conflict,
37 #[error("network error: {0}")]
38 Net(String),
39}
40
41impl ApiError {
42 pub fn skipped(&self) -> Option<&[String]> {
43 match self {
44 ApiError::Http {
45 skipped: Some(s), ..
46 } => Some(s),
47 _ => None,
48 }
49 }
50
51 /// The HTTP status code, when this was an HTTP (non-2xx) error.
52 pub fn status(&self) -> Option<u16> {
53 match self {
54 ApiError::Http { status, .. } => Some(*status),
55 _ => None,
56 }
57 }
58}
59
60/// Server error body: `{"error": "...", "code": "..."?, "skipped": [...]?}`.
61/// The message is already localized in [`fetch_checked`]; `code` carries the
62/// machine-readable identifier the server sends for known failures.
63#[derive(serde::Deserialize, Default)]
64struct ErrBody {
65 #[serde(default)]
66 error: Option<String>,
67 #[serde(default)]
68 code: Option<String>,
69 #[serde(default)]
70 skipped: Option<Vec<String>>,
71}
72
73// ---------------------------------------------------------------------------
74// Auth
75// ---------------------------------------------------------------------------
76
77pub fn me() -> impl std::future::Future<Output = Result<Me, ApiError>> {
78 request("GET", AUTH_ME.to_string(), None::<()>)
79}
80
81/// PUT /api/auth/me — update the signed-in user's profile settings.
82/// Omitted fields are left unchanged; `language: Some(None)` means "follow
83/// the browser".
84#[derive(Serialize, Default)]
85struct ProfilePatch {
86 #[serde(skip_serializing_if = "Option::is_none")]
87 single_click_open: Option<bool>,
88 #[serde(skip_serializing_if = "Option::is_none")]
89 language: Option<Option<String>>,
90}
91
92pub fn update_profile(
93 single_click_open: Option<bool>,
94 language: Option<Option<String>>,
95) -> impl std::future::Future<Output = Result<Me, ApiError>> {
96 request(
97 "PUT",
98 AUTH_ME.to_string(),
99 Some(ProfilePatch {
100 single_click_open,
101 language,
102 }),
103 )
104}
105
106pub fn login(
107 name: String,
108 password: String,
109) -> impl std::future::Future<Output = Result<OkResp, ApiError>> {
110 request(
111 "POST",
112 AUTH_LOGIN.to_string(),
113 Some(Credentials { name, password }),
114 )
115}
116
117pub fn setup(
118 name: String,
119 password: String,
120) -> impl std::future::Future<Output = Result<OkResp, ApiError>> {
121 request(
122 "POST",
123 AUTH_SETUP.to_string(),
124 Some(Credentials { name, password }),
125 )
126}
127
128pub fn logout() -> impl std::future::Future<Output = Result<OkResp, ApiError>> {
129 request("POST", AUTH_LOGOUT.to_string(), Some(()))
130}
131
132// ---------------------------------------------------------------------------
133// Files
134// ---------------------------------------------------------------------------
135
136/// The public share token while the app is showing a share page. Every file
137/// API call appends `?share=<token>` (or `&share=<token>`). Only one share is
138/// shown per page, so a plain static suffices (wasm is single-threaded).
139use std::sync::Mutex;
140static SHARE_TOKEN: Mutex<Option<String>> = Mutex::new(None);
141
142/// Set (or clear, with `None`) the share token used by file API calls.
143pub fn set_share_token(token: Option<&str>) {
144 *SHARE_TOKEN.lock().unwrap() = token.map(|s| s.to_string());
145}
146
147fn share_suffix() -> String {
148 SHARE_TOKEN
149 .lock()
150 .unwrap()
151 .as_deref()
152 .map(|t| format!("?{P_SHARE}={t}"))
153 .unwrap_or_default()
154}
155
156/// Append `key=value` to a URL, using `&` when a query string already exists.
157fn append_query(url: &str, kv: &str) -> String {
158 if url.contains('?') {
159 format!("{url}&{kv}")
160 } else {
161 format!("{url}?{kv}")
162 }
163}
164
165fn files_url(root_id: i64, path: &str) -> String {
166 let base = if path.is_empty() {
167 format!("{FILES}/{root_id}")
168 } else {
169 let encoded: Vec<String> = path
170 .split('/')
171 .map(|s| js_sys::encode_uri_component(s).into())
172 .collect();
173 format!("{FILES}/{root_id}/{}", encoded.join("/"))
174 };
175 format!("{base}{}", share_suffix())
176}
177
178pub fn list_files(
179 root_id: i64,
180 path: &str,
181) -> impl std::future::Future<Output = Result<FilesResp, ApiError>> {
182 request("GET", files_url(root_id, path), None::<()>)
183}
184
185/// Create an empty file. `path` is relative to the root (may contain
186/// subfolders); the file must not exist yet.
187pub fn create_file(
188 root_id: i64,
189 path: &str,
190) -> impl std::future::Future<Output = Result<OkResp, ApiError>> {
191 let url = append_query(
192 &files_url(root_id, path),
193 &format!("{P_ACTION}={ACTION_CREATE_FILE}"),
194 );
195 request("POST", url, None::<()>)
196}
197
198/// Create a folder. `path` is relative to the root (may contain subfolders).
199pub fn mkdir(
200 root_id: i64,
201 path: &str,
202) -> impl std::future::Future<Output = Result<OkResp, ApiError>> {
203 let url = append_query(
204 &files_url(root_id, path),
205 &format!("{P_ACTION}={ACTION_MKDIR}"),
206 );
207 request("POST", url, None::<()>)
208}
209
210pub fn rename_item(
211 root_id: i64,
212 path: &str,
213 new_name: String,
214 overwrite: bool,
215) -> impl std::future::Future<Output = Result<OkResp, ApiError>> {
216 request(
217 "POST",
218 files_url(root_id, path),
219 Some(Mutation {
220 op: Op::Rename,
221 new_name: Some(new_name),
222 dst_root_id: None,
223 dst: None,
224 overwrite,
225 }),
226 )
227}
228
229pub fn move_item(
230 root_id: i64,
231 path: &str,
232 dst_root_id: i64,
233 dst: &str,
234 overwrite: bool,
235) -> impl std::future::Future<Output = Result<OkResp, ApiError>> {
236 mutation(root_id, path, Op::Move, dst_root_id, dst, overwrite)
237}
238
239pub fn copy_item(
240 root_id: i64,
241 path: &str,
242 dst_root_id: i64,
243 dst: &str,
244 overwrite: bool,
245) -> impl std::future::Future<Output = Result<OkResp, ApiError>> {
246 mutation(root_id, path, Op::Copy, dst_root_id, dst, overwrite)
247}
248
249fn mutation(
250 root_id: i64,
251 path: &str,
252 op: Op,
253 dst_root_id: i64,
254 dst: &str,
255 overwrite: bool,
256) -> impl std::future::Future<Output = Result<OkResp, ApiError>> {
257 request(
258 "POST",
259 files_url(root_id, path),
260 Some(Mutation {
261 op,
262 new_name: None,
263 dst_root_id: Some(dst_root_id),
264 dst: Some(dst.to_string()),
265 overwrite,
266 }),
267 )
268}
269
270pub fn delete_item(
271 root_id: i64,
272 path: &str,
273) -> impl std::future::Future<Output = Result<OkResp, ApiError>> {
274 request("DELETE", files_url(root_id, path), None::<()>)
275}
276
277// ---------------------------------------------------------------------------
278// Download / preview / content (milestone 4)
279// ---------------------------------------------------------------------------
280
281/// `...?action=download` — a single file as-is, or a folder as `format`.
282pub fn download_url(root_id: i64, path: &str, format: Option<&str>) -> String {
283 let mut base = append_query(
284 &files_url(root_id, path),
285 &format!("{P_ACTION}={ACTION_DOWNLOAD}"),
286 );
287 if let Some(f) = format {
288 base = append_query(&base, &format!("{P_FORMAT}={f}"));
289 }
290 base
291}
292
293/// `...?action=preview` — a single file, inline (native media).
294pub fn preview_url(root_id: i64, path: &str) -> String {
295 append_query(
296 &files_url(root_id, path),
297 &format!("{P_ACTION}={ACTION_PREVIEW}"),
298 )
299}
300
301/// `...?action=content` — raw file bytes for the text preview/editor.
302pub fn content_url(root_id: i64, path: &str) -> String {
303 append_query(
304 &files_url(root_id, path),
305 &format!("{P_ACTION}={ACTION_CONTENT}"),
306 )
307}
308
309/// Fetch a file's raw text content plus its mtime (unix seconds), for the
310/// preview and the editor. The mtime anchors the save-time conflict check.
311pub async fn fetch_content_meta(
312 root_id: i64,
313 path: &str,
314) -> Result<(String, Option<i64>), ApiError> {
315 let opts = web_sys::RequestInit::new();
316 opts.set_method("GET");
317 opts.set_mode(web_sys::RequestMode::SameOrigin);
318 let resp = fetch_checked(&content_url(root_id, path), &opts, "could not read file").await?;
319 let mtime: Option<i64> = resp
320 .headers()
321 .get("x-file-mtime")
322 .ok()
323 .flatten()
324 .and_then(|s| s.parse::<i64>().ok());
325 let tp = resp.text().map_err(|e| ApiError::Net(format!("{e:?}")))?;
326 let js = JsFuture::from(tp)
327 .await
328 .map_err(|e| ApiError::Net(format!("{e:?}")))?;
329 let text = js
330 .as_string()
331 .ok_or_else(|| ApiError::Net("content is not a string".to_string()))?;
332 Ok((text, mtime))
333}
334
335/// Save a file's text content (the editor's write path).
336///
337/// When `force` is false, `expected_mtime` is sent and the server rejects the
338/// save with [`ApiError::Conflict`] if the file changed on disk since it was
339/// read. When `force` is true the check is skipped (overwrite). Returns the
340/// file's new mtime (unix seconds) to anchor the next check.
341pub async fn save_content(
342 root_id: i64,
343 path: &str,
344 text: &str,
345 expected_mtime: Option<i64>,
346 force: bool,
347) -> Result<i64, ApiError> {
348 let url = content_url(root_id, path);
349 let opts = web_sys::RequestInit::new();
350 opts.set_method("PUT");
351 opts.set_mode(web_sys::RequestMode::SameOrigin);
352 opts.set_body_opt_str(Some(text));
353 let headers = web_sys::Headers::new()
354 .map_err(|e| ApiError::Net(format!("could not create headers: {e:?}")))?;
355 headers
356 .set("Content-Type", "text/plain; charset=utf-8")
357 .map_err(|e| ApiError::Net(format!("could not set header: {e:?}")))?;
358 if !force && let Some(m) = expected_mtime {
359 headers
360 .set("X-Expected-Mtime", &m.to_string())
361 .map_err(|e| ApiError::Net(format!("could not set header: {e:?}")))?;
362 }
363 opts.set_headers_headers(&headers);
364 // 409 is the server's "changed on disk" answer, not a generic HTTP error.
365 let resp = match fetch_checked(&url, &opts, "could not save file").await {
366 Ok(resp) => resp,
367 Err(e) if e.status() == Some(409) => return Err(ApiError::Conflict),
368 Err(e) => return Err(e),
369 };
370 let save: SaveResp = read_json(&resp).await?;
371 Ok(save.mtime)
372}
373
374/// Open a URL in a new tab.
375///
376/// `noopener` severs the `window.opener` link, so the opened page cannot
377/// script this one. That matters here because the target is a *user file*:
378/// HTML and SVG render as real documents (under the server's sandbox CSP, see
379/// `FILE_CSP`), and this is the browser-side half of the same isolation.
380pub fn open_in_new_tab(url: &str) {
381 if let Some(w) = web_sys::window() {
382 let _ = w.open_with_url_and_target_and_features(url, "_blank", "noopener");
383 }
384}
385
386/// Trigger a browser download of a same-origin URL via a temporary anchor.
387/// No data is pulled into JS memory — the browser streams it.
388pub fn trigger_download(url: &str, filename: &str) {
389 let Some(doc) = web_sys::window().and_then(|w| w.document()) else {
390 return;
391 };
392 let Ok(el) = doc.create_element("a") else {
393 return;
394 };
395 let Ok(a) = el.dyn_into::<web_sys::HtmlAnchorElement>() else {
396 return;
397 };
398 a.set_href(url);
399 a.set_download(filename);
400 if let Some(body) = doc.body() {
401 let _ = body.append_child(&a);
402 }
403 a.click();
404 a.remove();
405}
406
407/// Upload files into a directory. Each part is `(relative_path, file)`;
408/// the relative path may contain subfolders (created on the server).
409///
410/// The multipart body is assembled by hand into a `Blob` (instead of using
411/// `FormData` directly as the fetch body): a FormData body makes Chrome send
412/// the request as a *streaming* body, which forces the HTTP/2-cleartext
413/// (h2c/ALPN) path and fails against an HTTP/1.1-only server with
414/// `ERR_ALPN_NEGOTIATION_FAILED`. A pre-assembled Blob has a known size, so
415/// it goes out as a regular length-prefixed HTTP/1.1 request.
416pub async fn upload(
417 root_id: i64,
418 dir: &str,
419 overwrite: bool,
420 parts: Vec<(String, web_sys::File)>,
421) -> Result<(), ApiError> {
422 let boundary = format!("----fbng{}", random_boundary_suffix());
423 let segments = js_sys::Array::new();
424 for (name, file) in &parts {
425 let basename = name.rsplit('/').next().unwrap_or(name);
426 segments.push(&JsValue::from_str(&format!(
427 "--{boundary}\r\n\
428 Content-Disposition: form-data; name=\"{name}\"; filename=\"{basename}\"\r\n\
429 Content-Type: application/octet-stream\r\n\r\n"
430 )));
431 let f: JsValue = file.clone().unchecked_into();
432 segments.push(&f);
433 segments.push(&JsValue::from_str("\r\n"));
434 }
435 segments.push(&JsValue::from_str(&format!("--{boundary}--\r\n")));
436 let body = web_sys::Blob::new_with_buffer_source_sequence(&segments)
437 .map_err(|e| ApiError::Net(format!("could not build upload body: {e:?}")))?;
438
439 let url = append_query(
440 &files_url(root_id, dir),
441 &format!("{P_OVERWRITE}={}", if overwrite { "true" } else { "false" }),
442 );
443
444 let headers = web_sys::Headers::new()
445 .map_err(|e| ApiError::Net(format!("could not create headers: {e:?}")))?;
446 headers
447 .set(
448 "Content-Type",
449 &format!("multipart/form-data; boundary={boundary}"),
450 )
451 .map_err(|e| ApiError::Net(format!("could not set content-type: {e:?}")))?;
452
453 let opts = web_sys::RequestInit::new();
454 opts.set_method("POST");
455 opts.set_mode(web_sys::RequestMode::SameOrigin);
456 opts.set_headers_headers(&headers);
457 opts.set_body_opt_blob(Some(&body));
458
459 // The error carries the server's `skipped` list on an upload conflict.
460 fetch_checked(&url, &opts, "upload failed").await?;
461 Ok(())
462}
463
464// ---------------------------------------------------------------------------
465// Shares (milestone 6)
466// ---------------------------------------------------------------------------
467
468pub fn list_shares() -> impl std::future::Future<Output = Result<Vec<ShareInfo>, ApiError>> {
469 request("GET", SHARES.to_string(), None::<()>)
470}
471
472pub fn create_share(
473 root_id: i64,
474 path: &str,
475 writable: bool,
476 expires_at: Option<&str>,
477) -> impl std::future::Future<Output = Result<ShareInfo, ApiError>> {
478 request(
479 "POST",
480 SHARES.to_string(),
481 Some(CreateShare {
482 root_id,
483 path: path.to_string(),
484 writable,
485 expires_at: expires_at.map(|s| s.to_string()),
486 }),
487 )
488}
489
490pub fn delete_share(id: i64) -> impl std::future::Future<Output = Result<OkResp, ApiError>> {
491 request("DELETE", format!("{SHARES}/{id}"), None::<()>)
492}
493
494/// Public: resolve a share (no session required).
495pub fn resolve_share(
496 token: &str,
497) -> impl std::future::Future<Output = Result<ShareInfo, ApiError>> {
498 request("GET", format!("{SHARE}/{token}"), None::<()>)
499}
500
501// ---------------------------------------------------------------------------
502// Admin (milestone 7): user management + settings
503// ---------------------------------------------------------------------------
504
505fn roots_to_bodies(roots: &[(String, Mode)]) -> Vec<Root> {
506 roots
507 .iter()
508 .map(|(path, mode)| Root {
509 path: path.clone(),
510 mode: *mode,
511 })
512 .collect()
513}
514
515pub fn list_admin_users() -> impl std::future::Future<Output = Result<Vec<AdminUser>, ApiError>> {
516 request("GET", ADMIN_USERS.to_string(), None::<()>)
517}
518
519pub fn create_admin_user(
520 name: &str,
521 password: &str,
522 is_admin: bool,
523 roots: &[(String, Mode)],
524) -> impl std::future::Future<Output = Result<AdminUser, ApiError>> {
525 request(
526 "POST",
527 ADMIN_USERS.to_string(),
528 Some(CreateUser {
529 name: name.to_string(),
530 password: password.to_string(),
531 is_admin,
532 roots: roots_to_bodies(roots),
533 }),
534 )
535}
536
537pub fn update_admin_user(
538 id: i64,
539 password: Option<String>,
540 is_admin: Option<bool>,
541 active: Option<bool>,
542 roots: Option<Vec<(String, Mode)>>,
543) -> impl std::future::Future<Output = Result<AdminUser, ApiError>> {
544 request(
545 "PUT",
546 format!("{ADMIN_USERS}/{id}"),
547 Some(UpdateUser {
548 password,
549 is_admin,
550 active,
551 roots: roots.map(|r| roots_to_bodies(&r)),
552 }),
553 )
554}
555
556pub fn delete_admin_user(id: i64) -> impl std::future::Future<Output = Result<OkResp, ApiError>> {
557 request("DELETE", format!("{ADMIN_USERS}/{id}"), None::<()>)
558}
559
560pub fn get_admin_settings() -> impl std::future::Future<Output = Result<Settings, ApiError>> {
561 request("GET", ADMIN_SETTINGS.to_string(), None::<()>)
562}
563
564pub fn update_admin_settings(
565 allow_writable_shares: bool,
566) -> impl std::future::Future<Output = Result<Settings, ApiError>> {
567 request(
568 "PUT",
569 ADMIN_SETTINGS.to_string(),
570 Some(Settings {
571 allow_writable_shares,
572 }),
573 )
574}
575
576// ---------------------------------------------------------------------------
577// File picker (imperative, one at a time)
578// ---------------------------------------------------------------------------
579
580fn random_boundary_suffix() -> String {
581 let mut s = String::with_capacity(16);
582 for _ in 0..16 {
583 let n = (js_sys::Math::random() * 36.0) as u32;
584 s.push(char::from_digit(n, 36).unwrap_or('a'));
585 }
586 s
587}
588
589use wasm_bindgen::closure::Closure;
590
591/// Open the native file dialog and run `on_files` with the picked files once
592/// the user confirms. `directory` uses webkitdirectory (folder upload).
593fn webkit_relative_path(file: &web_sys::File) -> String {
594 let js: JsValue = file.into();
595 js_sys::Reflect::get(&js, &JsValue::from_str("webkitRelativePath"))
596 .ok()
597 .and_then(|v| v.as_string())
598 .filter(|s| !s.is_empty())
599 .unwrap_or_default()
600}
601
602pub fn pick_files(
603 multiple: bool,
604 directory: bool,
605 on_files: impl Fn(Vec<(String, web_sys::File)>) + 'static,
606) {
607 let Some(doc) = web_sys::window().and_then(|w| w.document()) else {
608 return;
609 };
610 let Ok(el) = doc.create_element("input") else {
611 return;
612 };
613 let Ok(input) = el.dyn_into::<web_sys::HtmlInputElement>() else {
614 return;
615 };
616 input.set_type("file");
617 if multiple {
618 input.set_multiple(true);
619 }
620 if directory {
621 let _ = input.set_attribute("webkitdirectory", "");
622 }
623
624 // Known small leak, deliberate: the input holds the listener, the
625 // listener holds this closure, and the closure captures the input — a
626 // cycle that nothing frees. `forget()` detaches the Rust side, so the
627 // element + JS function + closure (~1 KB) survive until reload even
628 // when the dialog is used (not only when cancelled). Dropping the
629 // closure from Rust while the JS listener still references it would
630 // leave a dangling callback, and a closure cannot drop itself; a clean
631 // fix needs the caller to own it (e.g. a `StoredValue` released in
632 // `on_cleanup`), which is not worth it at this size.
633 let input2 = input.clone();
634 let closure = Closure::<dyn FnMut()>::new(move || {
635 let mut files: Vec<(String, web_sys::File)> = Vec::new();
636 if let Some(list) = input.files() {
637 for i in 0..list.length() {
638 if let Some(f) = list.get(i) {
639 let rel = webkit_relative_path(&f);
640 let name = if rel.is_empty() { f.name() } else { rel };
641 files.push((name, f));
642 }
643 }
644 }
645 input.remove();
646 if !files.is_empty() {
647 on_files(files);
648 }
649 });
650 let listener: &js_sys::Function = closure.as_js_value().unchecked_ref();
651 let _ = input2.add_event_listener_with_callback("change", listener);
652 closure.forget();
653 if let Some(body) = doc.body() {
654 let _ = body.append_child(&input2);
655 }
656 input2.click();
657}
658
659// ---------------------------------------------------------------------------
660// Low-level request helpers
661// ---------------------------------------------------------------------------
662
663async fn request<T: DeserializeOwned>(
664 method: &str,
665 url: String,
666 body: Option<impl Serialize>,
667) -> Result<T, ApiError> {
668 let opts = web_sys::RequestInit::new();
669 opts.set_method(method);
670 opts.set_mode(web_sys::RequestMode::SameOrigin);
671 if let Some(body) = body {
672 let json = serde_json::to_string(&body).map_err(|e| ApiError::Net(e.to_string()))?;
673 opts.set_body_opt_str(Some(&json));
674 let headers = web_sys::Headers::new().expect("Headers constructor failed");
675 let _ = headers.set("Content-Type", "application/json");
676 opts.set_headers_headers(&headers);
677 }
678
679 do_fetch(&url, &opts).await
680}
681
682/// Run one fetch and return the response, turning any non-2xx status into
683/// [`ApiError::Http`]. `fallback_msg` is used when the error body has no
684/// message. Callers that need the raw response (text, a header, or nothing at
685/// all) use this directly; JSON callers go through [`do_fetch`].
686async fn fetch_checked(
687 url: &str,
688 opts: &web_sys::RequestInit,
689 fallback_msg: &str,
690) -> Result<web_sys::Response, ApiError> {
691 let window =
692 web_sys::window().ok_or_else(|| ApiError::Net("no window available".to_string()))?;
693 let req = web_sys::Request::new_with_str_and_init(url, opts)
694 .map_err(|e| ApiError::Net(format!("{e:?}")))?;
695
696 let promise = window.fetch_with_request(&req);
697 let resp_val = JsFuture::from(promise)
698 .await
699 .map_err(|e| ApiError::Net(format!("{e:?}")))?;
700 let resp: web_sys::Response = resp_val
701 .dyn_into()
702 .map_err(|_| ApiError::Net("fetch did not return a Response".to_string()))?;
703
704 let status = resp.status();
705 if !(200..300).contains(&status) {
706 let body = parse_error_body(&resp).await;
707 let fallback = body
708 .error
709 .clone()
710 .unwrap_or_else(|| fallback_msg.to_string());
711 return Err(ApiError::Http {
712 status,
713 // Known server errors carry a code the client maps to a
714 // localized message; unknown ones fall back to the raw text.
715 message: crate::i18n::error_text(body.code.as_deref(), &fallback),
716 skipped: body.skipped,
717 });
718 }
719 Ok(resp)
720}
721
722async fn do_fetch<T: DeserializeOwned>(
723 url: &str,
724 opts: &web_sys::RequestInit,
725) -> Result<T, ApiError> {
726 let resp = fetch_checked(url, opts, "request failed").await?;
727 read_json(&resp).await
728}
729
730/// Read a response body as text and parse it with serde_json.
731///
732/// Going through text rather than `Response::json()` keeps one JSON
733/// implementation in play. It also keeps the server's 64-bit integers exact:
734/// a detour through a JS value would round file sizes through an f64.
735async fn read_json<T: DeserializeOwned>(resp: &web_sys::Response) -> Result<T, ApiError> {
736 let text = response_text(resp)
737 .await
738 .ok_or_else(|| ApiError::Net("could not read the response body".to_string()))?;
739 serde_json::from_str(&text).map_err(|e| ApiError::Net(format!("response is not JSON: {e}")))
740}
741
742async fn response_text(resp: &web_sys::Response) -> Option<String> {
743 JsFuture::from(resp.text().ok()?).await.ok()?.as_string()
744}
745
746/// Parse the server's error JSON (message + optional conflict list).
747/// An unparseable body yields the default, and the caller's fallback message.
748async fn parse_error_body(resp: &web_sys::Response) -> ErrBody {
749 response_text(resp)
750 .await
751 .and_then(|t| serde_json::from_str(&t).ok())
752 .unwrap_or_default()
753}
754
755/// Read a form input's value by element id.
756pub fn input_value(id: &str) -> String {
757 web_sys::window()
758 .and_then(|w| w.document())
759 .and_then(|d| {
760 d.get_element_by_id(id)
761 .and_then(|el| el.dyn_into::<web_sys::HtmlInputElement>().ok())
762 })
763 .map(|i| i.value())
764 .unwrap_or_default()
765}
766