Skip to main content

scribe_client/
client.rs

1use std::{collections::HashMap, sync::Arc, time::Duration};
2
3use reqwest::multipart;
4use serde::Deserialize;
5use tokio::sync::Mutex;
6use url::Url;
7
8use crate::{
9    auth::{AuthClient, TokenSet},
10    channel::DocumentChannel,
11    error::ScribeError,
12    model::{
13        AccountInfo, BrailleTable, BrailleTablesResponse, CreatedDocument, Dialect,
14        DialectsResponse, DocumentList, DocumentListResponse, DocumentSummary, Download, Language,
15        LanguagesResponse, NotificationSettings, OutputFormat, OutputList, OutputListResponse,
16        Settings, SettingsUpdate, TrashedDocument, TrashedDocumentListResponse, Voice,
17        VoicesResponse,
18    },
19};
20
21/// How early to proactively refresh a token before it actually expires.
22/// 5 minutes gives enough headroom for slow mobile networks and cold starts.
23const REFRESH_SKEW: Duration = Duration::from_secs(300);
24
25/// What to create a document from.
26pub enum DocumentSource {
27    /// Upload file bytes directly.
28    File { file_name: String, bytes: Vec<u8> },
29    /// Have the server fetch the document from a URL.
30    Url(String),
31}
32
33#[derive(Debug, Deserialize)]
34struct ApiErrorResponse {
35    error: ApiErrorBody,
36}
37
38#[derive(Debug, Deserialize)]
39struct ApiErrorBody {
40    code: String,
41    #[serde(default)]
42    message: Option<String>,
43}
44
45/// A client for the document-conversion endpoints
46/// (`/api/documents*`). Holds a [`TokenSet`] and refreshes it
47/// automatically as needed, so construct one [`AuthClient`]/[`ScribeClient`]
48/// pair per authenticated user session and reuse it across requests.
49/// Path of the web page where a user requests, or cancels, deletion of their own
50/// account.
51///
52/// It is under `/settings`, not at a top-level `/delete_account`. Reach it through [`ScribeClient::delete_account_url`] so the
53/// browser arrives already signed in. The same page starts a deletion and cancels
54/// a pending one, so one path serves both.
55pub const DELETE_ACCOUNT_PATH: &str = "/settings/delete_account";
56
57pub struct ScribeClient {
58    http: reqwest::Client,
59    base_url: Url,
60    auth: AuthClient,
61    tokens: Arc<Mutex<TokenSet>>,
62}
63
64impl ScribeClient {
65    pub fn new(
66        http: reqwest::Client,
67        base_url: Url,
68        client_id: impl Into<String>,
69        tokens: TokenSet,
70    ) -> Self {
71        let auth = AuthClient::new(http.clone(), base_url.clone(), client_id);
72        ScribeClient {
73            http,
74            base_url,
75            auth,
76            tokens: Arc::new(Mutex::new(tokens)),
77        }
78    }
79
80    /// The current access token, refreshing first if it's missing or about
81    /// to expire and a refresh token is available.
82    async fn access_token(&self) -> Result<String, ScribeError> {
83        let mut tokens = self.tokens.lock().await;
84        if tokens.needs_refresh(REFRESH_SKEW) {
85            if let Some(refresh_token) = tokens.refresh_token.clone() {
86                *tokens = self.auth.refresh(&refresh_token).await?;
87            }
88        }
89        Ok(tokens.access_token.clone())
90    }
91
92    /// Returns a snapshot of the current token set. Useful for persisting
93    /// the session after the client has auto-refreshed it.
94    pub async fn current_tokens(&self) -> TokenSet {
95        self.tokens.lock().await.clone()
96    }
97
98    /// Force-refreshes and replaces the current token set. Also used after
99    /// a request unexpectedly comes back `401` even though our local
100    /// expiry tracking thought the token was still good.
101    async fn force_refresh(&self) -> Result<String, ScribeError> {
102        let mut tokens = self.tokens.lock().await;
103        let refresh_token =
104            tokens
105                .refresh_token
106                .clone()
107                .ok_or_else(|| ScribeError::InvalidGrant {
108                    message: "Your session has expired. Please sign in again.".to_string(),
109                })?;
110        *tokens = self.auth.refresh(&refresh_token).await?;
111        Ok(tokens.access_token.clone())
112    }
113
114    /// Creates a document from `source`.
115    ///
116    /// # Errors
117    ///
118    /// Returns [`ScribeError::Http`]/[`ScribeError::Api`] if the request
119    /// fails or the server rejects it.
120    /// `password` unlocks a password-protected source file. Supplying it up
121    /// front saves a round trip when the caller already knows the document
122    /// is protected; otherwise leave it `None` and handle the
123    /// `password_required` signal on the document channel.
124    pub async fn create_document(
125        &self,
126        source: DocumentSource,
127        password: Option<&str>,
128    ) -> Result<CreatedDocument, ScribeError> {
129        let mut url = self.base_url.clone();
130        url.set_path("/api/documents");
131        self.with_auth_retry(|token| {
132            let form = match &source {
133                DocumentSource::File { file_name, bytes } => multipart::Form::new().part(
134                    "document[file]",
135                    multipart::Part::bytes(bytes.clone()).file_name(file_name.clone()),
136                ),
137                DocumentSource::Url(source_url) => {
138                    multipart::Form::new().text("document[url]", source_url.clone())
139                }
140            };
141            let form = match password {
142                Some(password) => form.text("document[password]", password.to_string()),
143                None => form,
144            };
145            self.http
146                .post(url.clone())
147                .bearer_auth(token)
148                .multipart(form)
149        })
150        .await
151    }
152
153    /// Lists every document owned by the current user, each with its
154    /// outputs embedded (so this alone is enough to show a document list
155    /// with per-document conversion status, no follow-up `list_outputs`
156    /// calls needed).
157    ///
158    /// # Errors
159    ///
160    /// Returns [`ScribeError::Http`]/[`ScribeError::Api`] on request failure.
161    pub async fn list_documents(&self) -> Result<DocumentList, ScribeError> {
162        let mut url = self.base_url.clone();
163        url.set_path("/api/documents");
164
165        let response: DocumentListResponse = self
166            .with_auth_retry(|token| self.http.get(url.clone()).bearer_auth(token))
167            .await?;
168
169        Ok(DocumentList {
170            documents: response.documents,
171            pages_remaining: response.pages_remaining,
172        })
173    }
174
175    /// Moves a document to the trash. It's permanently deleted 7 days later,
176    /// or sooner per the owner's org retention policy, unless recovered
177    /// first with [`recover_document`](Self::recover_document).
178    ///
179    /// # Errors
180    ///
181    /// Returns [`ScribeError::NotFound`]/[`ScribeError::Forbidden`] if the
182    /// document doesn't exist or isn't owned by the caller, or
183    /// [`ScribeError::Http`]/[`ScribeError::Api`] on other request failures.
184    pub async fn trash_document(&self, document_id: &str) -> Result<(), ScribeError> {
185        let mut url = self.base_url.clone();
186        url.set_path(&format!("/api/documents/{document_id}/trash"));
187        self.with_auth_retry_raw(|token| self.http.post(url.clone()).bearer_auth(token))
188            .await?;
189        Ok(())
190    }
191
192    /// Permanently deletes a document and all of its outputs. The document
193    /// must already be in the trash (see
194    /// [`trash_document`](Self::trash_document)).
195    ///
196    /// # Errors
197    ///
198    /// Returns [`ScribeError::NotFound`]/[`ScribeError::Forbidden`] if the
199    /// document doesn't exist or isn't owned by the caller,
200    /// [`ScribeError::NotTrashed`] if it hasn't been moved to the trash yet,
201    /// or [`ScribeError::Http`]/[`ScribeError::Api`] on other request
202    /// failures.
203    pub async fn delete_document_permanently(&self, document_id: &str) -> Result<(), ScribeError> {
204        let mut url = self.base_url.clone();
205        url.set_path(&format!("/api/documents/{document_id}"));
206        self.with_auth_retry_raw(|token| self.http.delete(url.clone()).bearer_auth(token))
207            .await?;
208        Ok(())
209    }
210
211    /// Restores a trashed document, clearing its trash state.
212    ///
213    /// # Errors
214    ///
215    /// Returns [`ScribeError::NotFound`]/[`ScribeError::Forbidden`] if the
216    /// document doesn't exist or isn't owned by the caller, or
217    /// [`ScribeError::Http`]/[`ScribeError::Api`] on other request failures.
218    pub async fn recover_document(&self, document_id: &str) -> Result<(), ScribeError> {
219        let mut url = self.base_url.clone();
220        url.set_path(&format!("/api/documents/{document_id}/recover"));
221        self.with_auth_retry_raw(|token| self.http.post(url.clone()).bearer_auth(token))
222            .await?;
223        Ok(())
224    }
225
226    /// Lists the caller's trashed documents, most recently trashed first.
227    ///
228    /// # Errors
229    ///
230    /// Returns [`ScribeError::Http`]/[`ScribeError::Api`] on request failure.
231    pub async fn list_trashed_documents(&self) -> Result<Vec<TrashedDocument>, ScribeError> {
232        let mut url = self.base_url.clone();
233        url.set_path("/api/documents/trash");
234        let response: TrashedDocumentListResponse = self
235            .with_auth_retry(|token| self.http.get(url.clone()).bearer_auth(token))
236            .await?;
237        Ok(response.documents)
238    }
239
240    /// Submits a document for human review, attaching `comment` as the
241    /// reason / description of the problem.
242    pub async fn submit_document_feedback(
243        &self,
244        document_id: &str,
245        comment: &str,
246    ) -> Result<(), ScribeError> {
247        let mut url = self.base_url.clone();
248        url.set_path(&format!("/api/documents/{document_id}/feedback"));
249        let body = serde_json::json!({ "comment": comment });
250        self.with_auth_retry_raw(|token| {
251            self.http.post(url.clone()).bearer_auth(token).json(&body)
252        })
253        .await?;
254        Ok(())
255    }
256
257    /// Opens a real-time channel for `document_id`, subscribing to
258    /// progress on whatever formats are already in progress (or their
259    /// incomplete parent formats) and allowing new conversions to be
260    /// started with [`DocumentChannel::start_conversion`]. This is the
261    /// only way to start a conversion for a format other than the
262    /// `html_stream` preview `create_document` already starts — it's no
263    /// longer possible over plain REST, so the server can guarantee it's
264    /// subscribed to whatever it just started converting.
265    ///
266    /// # Errors
267    ///
268    /// Returns [`ScribeError::NotFound`]/[`ScribeError::Forbidden`] if the
269    /// document doesn't exist or isn't owned by the caller, or
270    /// [`ScribeError::WebSocket`] if the connection fails.
271    pub async fn open_document_channel(
272        &self,
273        document_id: &str,
274    ) -> Result<DocumentChannel, ScribeError> {
275        let token = self.access_token().await?;
276        match self.connect_ws_channel(document_id, &token).await {
277            // WebSocket handshake failure likely means the token was rejected
278            // (the server answers 403 when it refuses the token).
279            // Retry once with a force-refreshed token before giving up.
280            Err(ScribeError::WebSocket(_)) => {
281                let token = self.force_refresh().await?;
282                self.connect_ws_channel(document_id, &token).await
283            }
284            other => other,
285        }
286    }
287
288    async fn connect_ws_channel(
289        &self,
290        document_id: &str,
291        token: &str,
292    ) -> Result<DocumentChannel, ScribeError> {
293        let mut url = self.base_url.clone();
294        let ws_scheme = if url.scheme() == "https" { "wss" } else { "ws" };
295        url.set_scheme(ws_scheme)
296            .map_err(|()| ScribeError::Channel {
297                message: "Something went wrong. Please try again.".to_string(),
298            })?;
299        url.set_path("/socket/websocket");
300        url.query_pairs_mut()
301            .append_pair("vsn", "2.0.0")
302            .append_pair("token", token);
303        let (ws, _response) = tokio_tungstenite::connect_async(url.as_str())
304            .await
305            .map_err(|e| ScribeError::WebSocket(Box::new(e)))?;
306        DocumentChannel::join(ws, document_id).await
307    }
308
309    /// # Errors
310    ///
311    /// Returns [`ScribeError::NotFound`]/[`ScribeError::Forbidden`] if the
312    /// document doesn't exist or isn't owned by the caller, or
313    /// [`ScribeError::Http`]/[`ScribeError::Api`] on other request failures.
314    pub async fn list_outputs(&self, document_id: &str) -> Result<OutputList, ScribeError> {
315        let mut url = self.base_url.clone();
316        url.set_path(&format!("/api/documents/{document_id}/outputs"));
317        let response: OutputListResponse = self
318            .with_auth_retry(|token| self.http.get(url.clone()).bearer_auth(token))
319            .await?;
320        Ok(OutputList {
321            outputs: response.outputs,
322            is_password_needed: response.is_password_needed,
323        })
324    }
325
326    /// # Errors
327    ///
328    /// Returns [`ScribeError::ConversionNotComplete`] if that format hasn't
329    /// finished converting yet, [`ScribeError::NotFound`]/[`ScribeError::Forbidden`]
330    /// if the document doesn't exist or isn't owned by the caller, or
331    /// [`ScribeError::Http`]/[`ScribeError::Api`] on other request failures.
332    pub async fn download_output(
333        &self,
334        document_id: &str,
335        format: OutputFormat,
336    ) -> Result<Download, ScribeError> {
337        self.download_output_with_progress(document_id, format, |_, _| {})
338            .await
339    }
340
341    /// Where the file can be fetched from directly, when the server answers
342    /// with a redirect rather than the bytes.
343    ///
344    /// The API redirects to storage by default, and that URL carries a real
345    /// `Content-Length` and accepts range requests, which is what a media
346    /// player needs to start before the whole file has arrived and to seek
347    /// afterwards. `None` means this server sends the file itself, so the
348    /// caller has to download it first.
349    ///
350    /// # Errors
351    ///
352    /// The same as [`download_output`](Self::download_output).
353    pub async fn download_url(
354        &self,
355        document_id: &str,
356        format: OutputFormat,
357    ) -> Result<Option<String>, ScribeError> {
358        let mut url = self.base_url.clone();
359        url.set_path(&format!(
360            "/api/documents/{document_id}/outputs/{}/download",
361            format.as_str()
362        ));
363        // Its own client: the shared one follows redirects, which would fetch
364        // the whole file here instead of reporting where it lives.
365        let client = reqwest::Client::builder()
366            .redirect(reqwest::redirect::Policy::none())
367            .build()?;
368
369        let token = self.access_token().await?;
370        let mut response = client.get(url.clone()).bearer_auth(&token).send().await?;
371        if response.status() == reqwest::StatusCode::UNAUTHORIZED {
372            let token = self.force_refresh().await?;
373            response = client.get(url.clone()).bearer_auth(&token).send().await?;
374        }
375
376        if response.status().is_redirection() {
377            return Ok(response
378                .headers()
379                .get(reqwest::header::LOCATION)
380                .and_then(|value| value.to_str().ok())
381                .map(str::to_string));
382        }
383        // Not a redirect: either this server streams the file itself, or
384        // something is wrong and the body says what.
385        response.error_for_status_or_json_error().await?;
386        Ok(None)
387    }
388
389    /// As [`download_output`](Self::download_output), reporting bytes received
390    /// as they arrive: `(downloaded, total)`, where `total` is `None` when the
391    /// server doesn't say how big the file is.
392    ///
393    /// Audio of a long document is tens of megabytes, and the whole download
394    /// used to be one silent wait.
395    ///
396    /// # Errors
397    ///
398    /// The same as [`download_output`](Self::download_output).
399    pub async fn download_output_with_progress<F>(
400        &self,
401        document_id: &str,
402        format: OutputFormat,
403        mut on_progress: F,
404    ) -> Result<Download, ScribeError>
405    where
406        F: FnMut(u64, Option<u64>) + Send,
407    {
408        let mut url = self.base_url.clone();
409        url.set_path(&format!(
410            "/api/documents/{document_id}/outputs/{}/download",
411            format.as_str()
412        ));
413        let mut response = self
414            .with_auth_retry_raw(|token| self.http.get(url.clone()).bearer_auth(token))
415            .await?;
416        let file_name = response
417            .headers()
418            .get(reqwest::header::CONTENT_DISPOSITION)
419            .and_then(|value| value.to_str().ok())
420            .and_then(content_disposition_file_name);
421        let total = response_total_bytes(&response);
422
423        let mut data: Vec<u8> = Vec::with_capacity(total.unwrap_or(0) as usize);
424        on_progress(0, total);
425        while let Some(chunk) = response.chunk().await? {
426            data.extend_from_slice(&chunk);
427            on_progress(data.len() as u64, total);
428        }
429        Ok(Download { data, file_name })
430    }
431
432    /// # Errors
433    ///
434    /// Returns [`ScribeError::NotFound`]/[`ScribeError::Forbidden`] if the
435    /// document doesn't exist or isn't owned by the caller, or
436    /// [`ScribeError::Http`]/[`ScribeError::Api`] on other request failures.
437    pub async fn get_settings(&self, document_id: &str) -> Result<Settings, ScribeError> {
438        let mut url = self.base_url.clone();
439        url.set_path(&format!("/api/documents/{document_id}/settings"));
440        self.with_auth_retry(|token| self.http.get(url.clone()).bearer_auth(token))
441            .await
442    }
443
444    /// # Errors
445    ///
446    /// Returns [`ScribeError::NotFound`]/[`ScribeError::Forbidden`] if the
447    /// document doesn't exist or isn't owned by the caller, or
448    /// [`ScribeError::Http`]/[`ScribeError::Api`] on other request failures
449    /// (including validation errors on the settings themselves).
450    pub async fn update_settings(
451        &self,
452        document_id: &str,
453        update: &SettingsUpdate,
454    ) -> Result<Settings, ScribeError> {
455        let mut url = self.base_url.clone();
456        url.set_path(&format!("/api/documents/{document_id}/settings"));
457        let body = serde_json::json!({ "settings": update });
458        self.with_auth_retry(|token| self.http.patch(url.clone()).bearer_auth(token).json(&body))
459            .await
460    }
461
462    /// Changes a document's title.
463    ///
464    /// Titles start life as the uploaded file name, which for a photo or a
465    /// share-sheet import is something like "IMG_6746783276432", so this is how
466    /// a caller fixes one after the fact. Returns the document as the list
467    /// endpoint describes it, so a caller can refresh its row from the result.
468    ///
469    /// # Errors
470    ///
471    /// Returns [`ScribeError::NotFound`]/[`ScribeError::Forbidden`] if the
472    /// document doesn't exist or isn't owned by the caller, or
473    /// [`ScribeError::Api`] if the title is rejected (it may not be blank and
474    /// is capped at 255 characters).
475    pub async fn rename_document(
476        &self,
477        document_id: &str,
478        title: &str,
479    ) -> Result<DocumentSummary, ScribeError> {
480        let mut url = self.base_url.clone();
481        url.set_path(&format!("/api/documents/{document_id}"));
482        let body = serde_json::json!({ "document": { "title": title } });
483        self.with_auth_retry(|token| self.http.patch(url.clone()).bearer_auth(token).json(&body))
484            .await
485    }
486
487    /// A URL that signs the system browser in as this client's user, then lands
488    /// on `return_to_path`.
489    ///
490    /// The app and the browser do not share a session, so a bare link to a
491    /// settings page would greet the user with a login form. This hands the
492    /// app's access token to `/auth/browser_from_oauth`, which trades it for a
493    /// browser session and redirects.
494    ///
495    /// Refreshes the token first when it is near expiry. The server rejects a
496    /// stale one with a "Failed to log in" page, and that is the page the user
497    /// would land on.
498    ///
499    /// # Errors
500    ///
501    /// Returns [`ScribeError::InvalidGrant`] if the token has expired and cannot
502    /// be refreshed, or [`ScribeError::Http`] if the refresh request fails.
503    pub async fn browser_entry_url(&self, return_to_path: &str) -> Result<String, ScribeError> {
504        let token = self.access_token().await?;
505        let state = serde_json::json!({ "return_to": return_to_path }).to_string();
506        let mut url = self.base_url.clone();
507        url.set_path("/auth/browser_from_oauth");
508        url.query_pairs_mut()
509            .append_pair("token", &token)
510            .append_pair("state", &state);
511        Ok(url.into())
512    }
513
514    /// The account-deletion page, signed in, for an app that lets users
515    /// start deleting their account from inside it.
516    ///
517    /// # Errors
518    ///
519    /// As for [`ScribeClient::browser_entry_url`].
520    pub async fn delete_account_url(&self) -> Result<String, ScribeError> {
521        self.browser_entry_url(DELETE_ACCOUNT_PATH).await
522    }
523
524    /// The caller's default conversion settings, which every new document's
525    /// settings are seeded from.
526    ///
527    /// Account-scoped, so there is no id: a user has exactly one set, and the
528    /// server creates it on first read rather than returning a 404.
529    ///
530    /// # Errors
531    ///
532    /// Returns [`ScribeError::Http`]/[`ScribeError::Api`] on request failure.
533    pub async fn default_settings(&self) -> Result<Settings, ScribeError> {
534        let mut url = self.base_url.clone();
535        url.set_path("/api/document_settings");
536        self.with_auth_retry(|token| self.http.get(url.clone()).bearer_auth(token))
537            .await
538    }
539
540    /// Updates the caller's default conversion settings. Partial: fields left
541    /// `None` on `update` are not sent, so they keep their current value.
542    ///
543    /// Changing these does not touch documents that already exist.
544    ///
545    /// # Errors
546    ///
547    /// Returns [`ScribeError::Http`]/[`ScribeError::Api`] on request failure,
548    /// including validation errors on the settings themselves.
549    pub async fn update_default_settings(
550        &self,
551        update: &SettingsUpdate,
552    ) -> Result<Settings, ScribeError> {
553        let mut url = self.base_url.clone();
554        url.set_path("/api/document_settings");
555        let body = serde_json::json!({ "settings": update });
556        self.with_auth_retry(|token| self.http.patch(url.clone()).bearer_auth(token).json(&body))
557            .await
558    }
559
560    /// Registers `token` (the hex-encoded APNs device token) so the server
561    /// can send this device push notifications. Registration is an upsert —
562    /// re-registering the same token re-points it at the current user (e.g.
563    /// after signing out and into a different account on the same device).
564    ///
565    /// # Errors
566    ///
567    /// Returns [`ScribeError::Http`]/[`ScribeError::Api`] on request failure.
568    pub async fn register_device(&self, token: &str, platform: &str) -> Result<(), ScribeError> {
569        let mut url = self.base_url.clone();
570        url.set_path("/api/devices");
571        let body = serde_json::json!({ "token": token, "platform": platform });
572        self.with_auth_retry_raw(|token| {
573            self.http.post(url.clone()).bearer_auth(token).json(&body)
574        })
575        .await?;
576        Ok(())
577    }
578
579    /// Unregisters `token`, e.g. on sign-out, so this device stops receiving push.
580    ///
581    /// # Errors
582    ///
583    /// Returns [`ScribeError::Http`]/[`ScribeError::Api`] on request failure.
584    pub async fn unregister_device(&self, token: &str) -> Result<(), ScribeError> {
585        let mut url = self.base_url.clone();
586        url.set_path(&format!("/api/devices/{token}"));
587        self.with_auth_retry_raw(|t| self.http.delete(url.clone()).bearer_auth(t))
588            .await?;
589        Ok(())
590    }
591
592    /// # Errors
593    ///
594    /// Returns [`ScribeError::Http`]/[`ScribeError::Api`] on request failure.
595    pub async fn get_notification_settings(&self) -> Result<NotificationSettings, ScribeError> {
596        let mut url = self.base_url.clone();
597        url.set_path("/api/notification_settings");
598        self.with_auth_retry(|token| self.http.get(url.clone()).bearer_auth(token))
599            .await
600    }
601
602    /// # Errors
603    ///
604    /// Returns [`ScribeError::Http`]/[`ScribeError::Api`] on request failure.
605    pub async fn update_notification_settings(
606        &self,
607        push_notify_when_complete: bool,
608    ) -> Result<NotificationSettings, ScribeError> {
609        let mut url = self.base_url.clone();
610        url.set_path("/api/notification_settings");
611        let body = serde_json::json!({ "push_notify_when_complete": push_notify_when_complete });
612        self.with_auth_retry(|token| self.http.patch(url.clone()).bearer_auth(token).json(&body))
613            .await
614    }
615
616    /// # Errors
617    ///
618    /// Returns [`ScribeError::Http`]/[`ScribeError::Api`] on request failure.
619    pub async fn get_account_info(&self) -> Result<AccountInfo, ScribeError> {
620        let mut url = self.base_url.clone();
621        url.set_path("/api/account_info");
622        self.with_auth_retry(|token| self.http.get(url.clone()).bearer_auth(token))
623            .await
624    }
625
626    /// # Errors
627    ///
628    /// Returns [`ScribeError::Http`]/[`ScribeError::Api`] on request failure.
629    pub async fn languages(&self) -> Result<Vec<Language>, ScribeError> {
630        let mut url = self.base_url.clone();
631        url.set_path("/api/settings/languages");
632        let response: LanguagesResponse = self
633            .with_auth_retry(|token| self.http.get(url.clone()).bearer_auth(token))
634            .await?;
635        Ok(response.languages)
636    }
637
638    /// # Errors
639    ///
640    /// Returns [`ScribeError::Http`]/[`ScribeError::Api`] on request failure.
641    pub async fn dialects(&self) -> Result<HashMap<String, Vec<Dialect>>, ScribeError> {
642        let mut url = self.base_url.clone();
643        url.set_path("/api/settings/dialects");
644        let response: DialectsResponse = self
645            .with_auth_retry(|token| self.http.get(url.clone()).bearer_auth(token))
646            .await?;
647        Ok(response.dialects)
648    }
649
650    /// # Errors
651    ///
652    /// Returns [`ScribeError::Http`]/[`ScribeError::Api`] on request failure.
653    pub async fn braille_tables(&self) -> Result<Vec<BrailleTable>, ScribeError> {
654        let mut url = self.base_url.clone();
655        url.set_path("/api/settings/braille_tables");
656        let response: BrailleTablesResponse = self
657            .with_auth_retry(|token| self.http.get(url.clone()).bearer_auth(token))
658            .await?;
659        Ok(response.braille_tables)
660    }
661
662    /// # Errors
663    ///
664    /// Returns [`ScribeError::Http`]/[`ScribeError::Api`] on request failure.
665    pub async fn voices(&self) -> Result<HashMap<String, Vec<Voice>>, ScribeError> {
666        let mut url = self.base_url.clone();
667        url.set_path("/api/settings/voices");
668        let response: VoicesResponse = self
669            .with_auth_retry(|token| self.http.get(url.clone()).bearer_auth(token))
670            .await?;
671        Ok(response.voices)
672    }
673
674    /// Sends a request built by `build`, retrying once with a
675    /// force-refreshed token if the server returns `401`. Returns the
676    /// validated response for callers that need to read the body themselves.
677    async fn with_auth_retry_raw<F>(&self, build: F) -> Result<reqwest::Response, ScribeError>
678    where
679        F: Fn(&str) -> reqwest::RequestBuilder,
680    {
681        let token = self.access_token().await?;
682        let response = build(&token).send().await?;
683        let response = if response.status() == reqwest::StatusCode::UNAUTHORIZED {
684            let token = self.force_refresh().await?;
685            build(&token).send().await?
686        } else {
687            response
688        };
689        response.error_for_status_or_json_error().await
690    }
691
692    /// Like [`with_auth_retry_raw`] but deserializes the response body as JSON.
693    async fn with_auth_retry<T, F>(&self, build: F) -> Result<T, ScribeError>
694    where
695        T: serde::de::DeserializeOwned,
696        F: Fn(&str) -> reqwest::RequestBuilder,
697    {
698        self.with_auth_retry_raw(build)
699            .await?
700            .json()
701            .await
702            .map_err(Into::into)
703    }
704}
705
706/// Small helper trait so response-status handling reads the same way at every call site.
707/// How many bytes the body will be, if the server says.
708///
709/// A download streamed from object storage goes out chunked, which has no
710/// `Content-Length`, so the API repeats the size it already knows in a header
711/// of its own. Without either, the caller only learns the total at the end.
712fn response_total_bytes(response: &reqwest::Response) -> Option<u64> {
713    response.content_length().or_else(|| {
714        response
715            .headers()
716            .get("x-scribe-content-length")
717            .and_then(|value| value.to_str().ok())
718            .and_then(|value| value.trim().parse().ok())
719    })
720}
721
722/// The file name in a `Content-Disposition` header. Prefers the UTF-8
723/// `filename*` (RFC 6266) over the ASCII-only `filename` fallback, and keeps
724/// only the last path component so a name can never point outside the folder
725/// it is saved in.
726fn content_disposition_file_name(header: &str) -> Option<String> {
727    let mut fallback = None;
728    let mut extended = None;
729    for param in header.split(';').map(str::trim) {
730        if let Some(value) = param.strip_prefix("filename*=") {
731            // `charset'language'value`. The server always sends UTF-8, and
732            // its value keeps a literal "+", so this must not be decoded as a
733            // form, which would turn it into a space.
734            let mut parts = value.splitn(3, '\'');
735            if let (Some(charset), Some(_), Some(encoded)) =
736                (parts.next(), parts.next(), parts.next())
737            {
738                if charset.eq_ignore_ascii_case("utf-8") {
739                    extended = percent_encoding::percent_decode_str(encoded)
740                        .decode_utf8()
741                        .ok()
742                        .map(|name| name.into_owned());
743                }
744            }
745        } else if let Some(value) = param.strip_prefix("filename=") {
746            fallback = Some(value.trim_matches('"').to_string());
747        }
748    }
749    extended
750        .or(fallback)
751        .and_then(|name| name.rsplit(['/', '\\']).next().map(str::to_string))
752        .filter(|name| !name.is_empty())
753}
754
755trait ResponseExt {
756    async fn error_for_status_or_json_error(self) -> Result<reqwest::Response, ScribeError>;
757}
758
759impl ResponseExt for reqwest::Response {
760    async fn error_for_status_or_json_error(self) -> Result<reqwest::Response, ScribeError> {
761        let status = self.status();
762        if status.is_success() {
763            return Ok(self);
764        }
765        let text = self.text().await.unwrap_or_default();
766        // A parse failure here means the body wasn't our JSON envelope at
767        // all (an HTML error page, a proxy's plain-text response, etc.) —
768        // never surface that raw text, fall back to a generic message.
769        let Ok(body) = serde_json::from_str::<ApiErrorResponse>(&text) else {
770            return Err(ScribeError::Api {
771                status: status.as_u16(),
772                code: "server_error".to_string(),
773                message: "Something went wrong. Please try again.".to_string(),
774            });
775        };
776        let message = body
777            .error
778            .message
779            .unwrap_or_else(|| "Something went wrong. Please try again.".to_string());
780        Err(match body.error.code.as_str() {
781            "not_found" => ScribeError::NotFound { message },
782            "forbidden" => ScribeError::Forbidden { message },
783            "not_trashed" => ScribeError::NotTrashed { message },
784            "conversion_not_complete" => ScribeError::ConversionNotComplete { message },
785            _ => ScribeError::Api {
786                status: status.as_u16(),
787                code: body.error.code,
788                message,
789            },
790        })
791    }
792}