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