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, 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}
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            suggest_buying_pages: response.suggest_buying_pages,
173        })
174    }
175
176    /// Moves a document to the trash. It's permanently deleted 7 days later,
177    /// or sooner per the owner's org retention policy, unless recovered
178    /// first with [`recover_document`](Self::recover_document).
179    ///
180    /// # Errors
181    ///
182    /// Returns [`ScribeError::NotFound`]/[`ScribeError::Forbidden`] if the
183    /// document doesn't exist or isn't owned by the caller, or
184    /// [`ScribeError::Http`]/[`ScribeError::Api`] on other request failures.
185    pub async fn trash_document(&self, document_id: &str) -> Result<(), ScribeError> {
186        let mut url = self.base_url.clone();
187        url.set_path(&format!("/api/documents/{document_id}/trash"));
188        self.with_auth_retry_raw(|token| self.http.post(url.clone()).bearer_auth(token))
189            .await?;
190        Ok(())
191    }
192
193    /// Permanently deletes a document and all of its outputs. The document
194    /// must already be in the trash (see
195    /// [`trash_document`](Self::trash_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,
201    /// [`ScribeError::NotTrashed`] if it hasn't been moved to the trash yet,
202    /// or [`ScribeError::Http`]/[`ScribeError::Api`] on other request
203    /// failures.
204    pub async fn delete_document_permanently(&self, document_id: &str) -> Result<(), ScribeError> {
205        let mut url = self.base_url.clone();
206        url.set_path(&format!("/api/documents/{document_id}"));
207        self.with_auth_retry_raw(|token| self.http.delete(url.clone()).bearer_auth(token))
208            .await?;
209        Ok(())
210    }
211
212    /// Restores a trashed document, clearing its trash state.
213    ///
214    /// # Errors
215    ///
216    /// Returns [`ScribeError::NotFound`]/[`ScribeError::Forbidden`] if the
217    /// document doesn't exist or isn't owned by the caller, or
218    /// [`ScribeError::Http`]/[`ScribeError::Api`] on other request failures.
219    pub async fn recover_document(&self, document_id: &str) -> Result<(), ScribeError> {
220        let mut url = self.base_url.clone();
221        url.set_path(&format!("/api/documents/{document_id}/recover"));
222        self.with_auth_retry_raw(|token| self.http.post(url.clone()).bearer_auth(token))
223            .await?;
224        Ok(())
225    }
226
227    /// Lists the caller's trashed documents, most recently trashed first.
228    ///
229    /// # Errors
230    ///
231    /// Returns [`ScribeError::Http`]/[`ScribeError::Api`] on request failure.
232    pub async fn list_trashed_documents(&self) -> Result<Vec<TrashedDocument>, ScribeError> {
233        let mut url = self.base_url.clone();
234        url.set_path("/api/documents/trash");
235        let response: TrashedDocumentListResponse = self
236            .with_auth_retry(|token| self.http.get(url.clone()).bearer_auth(token))
237            .await?;
238        Ok(response.documents)
239    }
240
241    /// Submits a document for human review, attaching `comment` as the
242    /// reason / description of the problem.
243    pub async fn submit_document_feedback(
244        &self,
245        document_id: &str,
246        comment: &str,
247    ) -> Result<(), ScribeError> {
248        let mut url = self.base_url.clone();
249        url.set_path(&format!("/api/documents/{document_id}/feedback"));
250        let body = serde_json::json!({ "comment": comment });
251        self.with_auth_retry_raw(|token| {
252            self.http.post(url.clone()).bearer_auth(token).json(&body)
253        })
254        .await?;
255        Ok(())
256    }
257
258    /// Opens a real-time channel for `document_id`, subscribing to
259    /// progress on whatever formats are already in progress (or their
260    /// incomplete parent formats) and allowing new conversions to be
261    /// started with [`DocumentChannel::start_conversion`]. This is the
262    /// only way to start a conversion for a format other than the
263    /// `html_stream` preview `create_document` already starts — it's no
264    /// longer possible over plain REST, so the server can guarantee it's
265    /// subscribed to whatever it just started converting.
266    ///
267    /// # Errors
268    ///
269    /// Returns [`ScribeError::NotFound`]/[`ScribeError::Forbidden`] if the
270    /// document doesn't exist or isn't owned by the caller, or
271    /// [`ScribeError::WebSocket`] if the connection fails.
272    pub async fn open_document_channel(
273        &self,
274        document_id: &str,
275    ) -> Result<DocumentChannel, ScribeError> {
276        let token = self.access_token().await?;
277        match self.connect_ws_channel(document_id, &token).await {
278            // WebSocket handshake failure likely means the token was rejected
279            // (the server answers 403 when it refuses the token).
280            // Retry once with a force-refreshed token before giving up.
281            Err(ScribeError::WebSocket(_)) => {
282                let token = self.force_refresh().await?;
283                self.connect_ws_channel(document_id, &token).await
284            }
285            other => other,
286        }
287    }
288
289    async fn connect_ws_channel(
290        &self,
291        document_id: &str,
292        token: &str,
293    ) -> Result<DocumentChannel, ScribeError> {
294        let mut url = self.base_url.clone();
295        let ws_scheme = if url.scheme() == "https" { "wss" } else { "ws" };
296        url.set_scheme(ws_scheme)
297            .map_err(|()| ScribeError::Channel {
298                message: "Something went wrong. Please try again.".to_string(),
299            })?;
300        url.set_path("/socket/websocket");
301        url.query_pairs_mut()
302            .append_pair("vsn", "2.0.0")
303            .append_pair("token", token);
304        let (ws, _response) = tokio_tungstenite::connect_async(url.as_str())
305            .await
306            .map_err(|e| ScribeError::WebSocket(Box::new(e)))?;
307        DocumentChannel::join(ws, document_id).await
308    }
309
310    /// # Errors
311    ///
312    /// Returns [`ScribeError::NotFound`]/[`ScribeError::Forbidden`] if the
313    /// document doesn't exist or isn't owned by the caller, or
314    /// [`ScribeError::Http`]/[`ScribeError::Api`] on other request failures.
315    pub async fn list_outputs(&self, document_id: &str) -> Result<OutputList, ScribeError> {
316        let mut url = self.base_url.clone();
317        url.set_path(&format!("/api/documents/{document_id}/outputs"));
318        let response: OutputListResponse = self
319            .with_auth_retry(|token| self.http.get(url.clone()).bearer_auth(token))
320            .await?;
321        Ok(OutputList {
322            outputs: response.outputs,
323            is_password_needed: response.is_password_needed,
324        })
325    }
326
327    /// # Errors
328    ///
329    /// Returns [`ScribeError::ConversionNotComplete`] if that format hasn't
330    /// finished converting yet, [`ScribeError::NotFound`]/[`ScribeError::Forbidden`]
331    /// if the document doesn't exist or isn't owned by the caller, or
332    /// [`ScribeError::Http`]/[`ScribeError::Api`] on other request failures.
333    pub async fn download_output(
334        &self,
335        document_id: &str,
336        format: OutputFormat,
337    ) -> Result<Download, ScribeError> {
338        self.download_output_with_progress(document_id, format, |_, _| {})
339            .await
340    }
341
342    /// Where the file can be fetched from directly, when the server answers
343    /// with a redirect rather than the bytes.
344    ///
345    /// The API redirects to storage by default, and that URL carries a real
346    /// `Content-Length` and accepts range requests, which is what a media
347    /// player needs to start before the whole file has arrived and to seek
348    /// afterwards. `None` means this server sends the file itself, so the
349    /// caller has to download it first.
350    ///
351    /// # Errors
352    ///
353    /// The same as [`download_output`](Self::download_output).
354    pub async fn download_url(
355        &self,
356        document_id: &str,
357        format: OutputFormat,
358    ) -> Result<Option<String>, ScribeError> {
359        let mut url = self.base_url.clone();
360        url.set_path(&format!(
361            "/api/documents/{document_id}/outputs/{}/download",
362            format.as_str()
363        ));
364        // Its own client: the shared one follows redirects, which would fetch
365        // the whole file here instead of reporting where it lives.
366        let client = reqwest::Client::builder()
367            .redirect(reqwest::redirect::Policy::none())
368            .build()?;
369
370        let token = self.access_token().await?;
371        let mut response = client.get(url.clone()).bearer_auth(&token).send().await?;
372        if response.status() == reqwest::StatusCode::UNAUTHORIZED {
373            let token = self.force_refresh().await?;
374            response = client.get(url.clone()).bearer_auth(&token).send().await?;
375        }
376
377        if response.status().is_redirection() {
378            return Ok(response
379                .headers()
380                .get(reqwest::header::LOCATION)
381                .and_then(|value| value.to_str().ok())
382                .map(str::to_string));
383        }
384        // Not a redirect: either this server streams the file itself, or
385        // something is wrong and the body says what.
386        response.error_for_status_or_json_error().await?;
387        Ok(None)
388    }
389
390    /// As [`download_output`](Self::download_output), reporting bytes received
391    /// as they arrive: `(downloaded, total)`, where `total` is `None` when the
392    /// server doesn't say how big the file is.
393    ///
394    /// Audio of a long document is tens of megabytes, and the whole download
395    /// used to be one silent wait.
396    ///
397    /// # Errors
398    ///
399    /// The same as [`download_output`](Self::download_output).
400    pub async fn download_output_with_progress<F>(
401        &self,
402        document_id: &str,
403        format: OutputFormat,
404        mut on_progress: F,
405    ) -> Result<Download, ScribeError>
406    where
407        F: FnMut(u64, Option<u64>) + Send,
408    {
409        let mut url = self.base_url.clone();
410        url.set_path(&format!(
411            "/api/documents/{document_id}/outputs/{}/download",
412            format.as_str()
413        ));
414        let mut response = self
415            .with_auth_retry_raw(|token| self.http.get(url.clone()).bearer_auth(token))
416            .await?;
417        let file_name = response
418            .headers()
419            .get(reqwest::header::CONTENT_DISPOSITION)
420            .and_then(|value| value.to_str().ok())
421            .and_then(content_disposition_file_name);
422        let total = response_total_bytes(&response);
423
424        let mut data: Vec<u8> = Vec::with_capacity(total.unwrap_or(0) as usize);
425        on_progress(0, total);
426        while let Some(chunk) = response.chunk().await? {
427            data.extend_from_slice(&chunk);
428            on_progress(data.len() as u64, total);
429        }
430        Ok(Download { data, file_name })
431    }
432
433    /// # Errors
434    ///
435    /// Returns [`ScribeError::NotFound`]/[`ScribeError::Forbidden`] if the
436    /// document doesn't exist or isn't owned by the caller, or
437    /// [`ScribeError::Http`]/[`ScribeError::Api`] on other request failures.
438    pub async fn get_settings(&self, document_id: &str) -> Result<Settings, ScribeError> {
439        let mut url = self.base_url.clone();
440        url.set_path(&format!("/api/documents/{document_id}/settings"));
441        self.with_auth_retry(|token| self.http.get(url.clone()).bearer_auth(token))
442            .await
443    }
444
445    /// # Errors
446    ///
447    /// Returns [`ScribeError::NotFound`]/[`ScribeError::Forbidden`] if the
448    /// document doesn't exist or isn't owned by the caller, or
449    /// [`ScribeError::Http`]/[`ScribeError::Api`] on other request failures
450    /// (including validation errors on the settings themselves).
451    pub async fn update_settings(
452        &self,
453        document_id: &str,
454        update: &SettingsUpdate,
455    ) -> Result<Settings, ScribeError> {
456        let mut url = self.base_url.clone();
457        url.set_path(&format!("/api/documents/{document_id}/settings"));
458        let body = serde_json::json!({ "settings": update });
459        self.with_auth_retry(|token| self.http.patch(url.clone()).bearer_auth(token).json(&body))
460            .await
461    }
462
463    /// Changes a document's title.
464    ///
465    /// Titles start life as the uploaded file name, which for a photo or a
466    /// share-sheet import is something like "IMG_6746783276432", so this is how
467    /// a caller fixes one after the fact. Returns the document as the list
468    /// endpoint describes it, so a caller can refresh its row from the result.
469    ///
470    /// # Errors
471    ///
472    /// Returns [`ScribeError::NotFound`]/[`ScribeError::Forbidden`] if the
473    /// document doesn't exist or isn't owned by the caller, or
474    /// [`ScribeError::Api`] if the title is rejected (it may not be blank and
475    /// is capped at 255 characters).
476    pub async fn rename_document(
477        &self,
478        document_id: &str,
479        title: &str,
480    ) -> Result<DocumentSummary, ScribeError> {
481        let mut url = self.base_url.clone();
482        url.set_path(&format!("/api/documents/{document_id}"));
483        let body = serde_json::json!({ "document": { "title": title } });
484        self.with_auth_retry(|token| self.http.patch(url.clone()).bearer_auth(token).json(&body))
485            .await
486    }
487
488    /// A URL that signs the system browser in as this client's user, then lands
489    /// on `return_to_path`.
490    ///
491    /// The app and the browser do not share a session, so a bare link to a
492    /// settings page would greet the user with a login form. This hands the
493    /// app's access token to `/auth/browser_from_oauth`, which trades it for a
494    /// browser session and redirects.
495    ///
496    /// Refreshes the token first when it is near expiry. The server rejects a
497    /// stale one with a "Failed to log in" page, and that is the page the user
498    /// would land on.
499    ///
500    /// # Errors
501    ///
502    /// Returns [`ScribeError::InvalidGrant`] if the token has expired and cannot
503    /// be refreshed, or [`ScribeError::Http`] if the refresh request fails.
504    pub async fn browser_entry_url(&self, return_to_path: &str) -> Result<String, ScribeError> {
505        let token = self.access_token().await?;
506        let state = serde_json::json!({ "return_to": return_to_path }).to_string();
507        let mut url = self.base_url.clone();
508        url.set_path("/auth/browser_from_oauth");
509        url.query_pairs_mut()
510            .append_pair("token", &token)
511            .append_pair("state", &state);
512        Ok(url.into())
513    }
514
515    /// The account-deletion page, signed in, for an app that lets users
516    /// start deleting their account from inside it.
517    ///
518    /// # Errors
519    ///
520    /// As for [`ScribeClient::browser_entry_url`].
521    pub async fn delete_account_url(&self) -> Result<String, ScribeError> {
522        self.browser_entry_url(DELETE_ACCOUNT_PATH).await
523    }
524
525    /// The caller's default conversion settings, which every new document's
526    /// settings are seeded from.
527    ///
528    /// Account-scoped, so there is no id: a user has exactly one set, and the
529    /// server creates it on first read rather than returning a 404.
530    ///
531    /// # Errors
532    ///
533    /// Returns [`ScribeError::Http`]/[`ScribeError::Api`] on request failure.
534    pub async fn default_settings(&self) -> Result<Settings, ScribeError> {
535        let mut url = self.base_url.clone();
536        url.set_path("/api/document_settings");
537        self.with_auth_retry(|token| self.http.get(url.clone()).bearer_auth(token))
538            .await
539    }
540
541    /// Updates the caller's default conversion settings. Partial: fields left
542    /// `None` on `update` are not sent, so they keep their current value.
543    ///
544    /// Changing these does not touch documents that already exist.
545    ///
546    /// # Errors
547    ///
548    /// Returns [`ScribeError::Http`]/[`ScribeError::Api`] on request failure,
549    /// including validation errors on the settings themselves.
550    pub async fn update_default_settings(
551        &self,
552        update: &SettingsUpdate,
553    ) -> Result<Settings, ScribeError> {
554        let mut url = self.base_url.clone();
555        url.set_path("/api/document_settings");
556        let body = serde_json::json!({ "settings": update });
557        self.with_auth_retry(|token| self.http.patch(url.clone()).bearer_auth(token).json(&body))
558            .await
559    }
560
561    /// Registers `token` (the hex-encoded APNs device token) so the server
562    /// can send this device push notifications. Registration is an upsert —
563    /// re-registering the same token re-points it at the current user (e.g.
564    /// after signing out and into a different account on the same device).
565    ///
566    /// # Errors
567    ///
568    /// Returns [`ScribeError::Http`]/[`ScribeError::Api`] on request failure.
569    pub async fn register_device(&self, token: &str, platform: &str) -> Result<(), ScribeError> {
570        let mut url = self.base_url.clone();
571        url.set_path("/api/devices");
572        let body = serde_json::json!({ "token": token, "platform": platform });
573        self.with_auth_retry_raw(|token| {
574            self.http.post(url.clone()).bearer_auth(token).json(&body)
575        })
576        .await?;
577        Ok(())
578    }
579
580    /// Unregisters `token`, e.g. on sign-out, so this device stops receiving push.
581    ///
582    /// # Errors
583    ///
584    /// Returns [`ScribeError::Http`]/[`ScribeError::Api`] on request failure.
585    pub async fn unregister_device(&self, token: &str) -> Result<(), ScribeError> {
586        let mut url = self.base_url.clone();
587        url.set_path(&format!("/api/devices/{token}"));
588        self.with_auth_retry_raw(|t| self.http.delete(url.clone()).bearer_auth(t))
589            .await?;
590        Ok(())
591    }
592
593    /// # Errors
594    ///
595    /// Returns [`ScribeError::Http`]/[`ScribeError::Api`] on request failure.
596    pub async fn get_notification_settings(&self) -> Result<NotificationSettings, ScribeError> {
597        let mut url = self.base_url.clone();
598        url.set_path("/api/notification_settings");
599        self.with_auth_retry(|token| self.http.get(url.clone()).bearer_auth(token))
600            .await
601    }
602
603    /// # Errors
604    ///
605    /// Returns [`ScribeError::Http`]/[`ScribeError::Api`] on request failure.
606    pub async fn update_notification_settings(
607        &self,
608        push_notify_when_complete: bool,
609    ) -> Result<NotificationSettings, ScribeError> {
610        let mut url = self.base_url.clone();
611        url.set_path("/api/notification_settings");
612        let body = serde_json::json!({ "push_notify_when_complete": push_notify_when_complete });
613        self.with_auth_retry(|token| self.http.patch(url.clone()).bearer_auth(token).json(&body))
614            .await
615    }
616
617    /// # Errors
618    ///
619    /// Returns [`ScribeError::Http`]/[`ScribeError::Api`] on request failure.
620    pub async fn get_account_info(&self) -> Result<AccountInfo, ScribeError> {
621        let mut url = self.base_url.clone();
622        url.set_path("/api/account_info");
623        self.with_auth_retry(|token| self.http.get(url.clone()).bearer_auth(token))
624            .await
625    }
626
627    /// The pages the account has left and its active subscription, if any.
628    ///
629    /// # Errors
630    ///
631    /// Returns [`ScribeError::Http`]/[`ScribeError::Api`] on request failure.
632    pub async fn billing(&self) -> Result<BillingStatus, ScribeError> {
633        let mut url = self.base_url.clone();
634        url.set_path("/api/billing");
635        self.with_auth_retry(|token| self.http.get(url.clone()).bearer_auth(token))
636            .await
637    }
638
639    /// Lists the App Store products on sale, in the order to show them.
640    ///
641    /// # Errors
642    ///
643    /// Returns [`ScribeError::Http`]/[`ScribeError::Api`] on request failure.
644    pub async fn app_store_products(&self) -> Result<Vec<AppStoreProduct>, ScribeError> {
645        let mut url = self.base_url.clone();
646        url.set_path("/api/app_store/products");
647        let response: AppStoreProductsResponse = self
648            .with_auth_retry(|token| self.http.get(url.clone()).bearer_auth(token))
649            .await?;
650        Ok(response.products)
651    }
652
653    /// Credits a completed App Store purchase to the account. `signed_transaction`
654    /// is `Transaction.jwsRepresentation` from `StoreKit` 2. Reporting the same
655    /// transaction again is harmless, so finish the transaction in `StoreKit`
656    /// only once this succeeds. Returns the billing status afterwards.
657    ///
658    /// # Errors
659    ///
660    /// Returns [`ScribeError::Api`] with code `other_account` if the purchase
661    /// was made while signed in to a different Scribe account, or
662    /// `invalid_transaction` if the server couldn't verify it.
663    pub async fn submit_app_store_transaction(
664        &self,
665        signed_transaction: &str,
666    ) -> Result<BillingStatus, ScribeError> {
667        let mut url = self.base_url.clone();
668        url.set_path("/api/app_store/transactions");
669        let body = serde_json::json!({ "signed_transaction": signed_transaction });
670        self.with_auth_retry(|token| self.http.post(url.clone()).bearer_auth(token).json(&body))
671            .await
672    }
673
674    /// # Errors
675    ///
676    /// Returns [`ScribeError::Http`]/[`ScribeError::Api`] on request failure.
677    pub async fn languages(&self) -> Result<Vec<Language>, ScribeError> {
678        let mut url = self.base_url.clone();
679        url.set_path("/api/settings/languages");
680        let response: LanguagesResponse = self
681            .with_auth_retry(|token| self.http.get(url.clone()).bearer_auth(token))
682            .await?;
683        Ok(response.languages)
684    }
685
686    /// # Errors
687    ///
688    /// Returns [`ScribeError::Http`]/[`ScribeError::Api`] on request failure.
689    pub async fn dialects(&self) -> Result<HashMap<String, Vec<Dialect>>, ScribeError> {
690        let mut url = self.base_url.clone();
691        url.set_path("/api/settings/dialects");
692        let response: DialectsResponse = self
693            .with_auth_retry(|token| self.http.get(url.clone()).bearer_auth(token))
694            .await?;
695        Ok(response.dialects)
696    }
697
698    /// # Errors
699    ///
700    /// Returns [`ScribeError::Http`]/[`ScribeError::Api`] on request failure.
701    pub async fn braille_tables(&self) -> Result<Vec<BrailleTable>, ScribeError> {
702        let mut url = self.base_url.clone();
703        url.set_path("/api/settings/braille_tables");
704        let response: BrailleTablesResponse = self
705            .with_auth_retry(|token| self.http.get(url.clone()).bearer_auth(token))
706            .await?;
707        Ok(response.braille_tables)
708    }
709
710    /// # Errors
711    ///
712    /// Returns [`ScribeError::Http`]/[`ScribeError::Api`] on request failure.
713    pub async fn voices(&self) -> Result<HashMap<String, Vec<Voice>>, ScribeError> {
714        let mut url = self.base_url.clone();
715        url.set_path("/api/settings/voices");
716        let response: VoicesResponse = self
717            .with_auth_retry(|token| self.http.get(url.clone()).bearer_auth(token))
718            .await?;
719        Ok(response.voices)
720    }
721
722    /// Sends a request built by `build`, retrying once with a
723    /// force-refreshed token if the server returns `401`. Returns the
724    /// validated response for callers that need to read the body themselves.
725    async fn with_auth_retry_raw<F>(&self, build: F) -> Result<reqwest::Response, ScribeError>
726    where
727        F: Fn(&str) -> reqwest::RequestBuilder,
728    {
729        let token = self.access_token().await?;
730        let response = build(&token).send().await?;
731        let response = if response.status() == reqwest::StatusCode::UNAUTHORIZED {
732            let token = self.force_refresh().await?;
733            build(&token).send().await?
734        } else {
735            response
736        };
737        response.error_for_status_or_json_error().await
738    }
739
740    /// Like [`with_auth_retry_raw`] but deserializes the response body as JSON.
741    async fn with_auth_retry<T, F>(&self, build: F) -> Result<T, ScribeError>
742    where
743        T: serde::de::DeserializeOwned,
744        F: Fn(&str) -> reqwest::RequestBuilder,
745    {
746        self.with_auth_retry_raw(build)
747            .await?
748            .json()
749            .await
750            .map_err(Into::into)
751    }
752}
753
754/// Small helper trait so response-status handling reads the same way at every call site.
755/// How many bytes the body will be, if the server says.
756///
757/// A download streamed from object storage goes out chunked, which has no
758/// `Content-Length`, so the API repeats the size it already knows in a header
759/// of its own. Without either, the caller only learns the total at the end.
760fn response_total_bytes(response: &reqwest::Response) -> Option<u64> {
761    response.content_length().or_else(|| {
762        response
763            .headers()
764            .get("x-scribe-content-length")
765            .and_then(|value| value.to_str().ok())
766            .and_then(|value| value.trim().parse().ok())
767    })
768}
769
770/// The file name in a `Content-Disposition` header. Prefers the UTF-8
771/// `filename*` (RFC 6266) over the ASCII-only `filename` fallback, and keeps
772/// only the last path component so a name can never point outside the folder
773/// it is saved in.
774fn content_disposition_file_name(header: &str) -> Option<String> {
775    let mut fallback = None;
776    let mut extended = None;
777    for param in header.split(';').map(str::trim) {
778        if let Some(value) = param.strip_prefix("filename*=") {
779            // `charset'language'value`. The server always sends UTF-8, and
780            // its value keeps a literal "+", so this must not be decoded as a
781            // form, which would turn it into a space.
782            let mut parts = value.splitn(3, '\'');
783            if let (Some(charset), Some(_), Some(encoded)) =
784                (parts.next(), parts.next(), parts.next())
785            {
786                if charset.eq_ignore_ascii_case("utf-8") {
787                    extended = percent_encoding::percent_decode_str(encoded)
788                        .decode_utf8()
789                        .ok()
790                        .map(|name| name.into_owned());
791                }
792            }
793        } else if let Some(value) = param.strip_prefix("filename=") {
794            fallback = Some(value.trim_matches('"').to_string());
795        }
796    }
797    extended
798        .or(fallback)
799        .and_then(|name| name.rsplit(['/', '\\']).next().map(str::to_string))
800        .filter(|name| !name.is_empty())
801}
802
803trait ResponseExt {
804    async fn error_for_status_or_json_error(self) -> Result<reqwest::Response, ScribeError>;
805}
806
807impl ResponseExt for reqwest::Response {
808    async fn error_for_status_or_json_error(self) -> Result<reqwest::Response, ScribeError> {
809        let status = self.status();
810        if status.is_success() {
811            return Ok(self);
812        }
813        let text = self.text().await.unwrap_or_default();
814        // A parse failure here means the body wasn't our JSON envelope at
815        // all (an HTML error page, a proxy's plain-text response, etc.) —
816        // never surface that raw text, fall back to a generic message.
817        let Ok(body) = serde_json::from_str::<ApiErrorResponse>(&text) else {
818            return Err(ScribeError::Api {
819                status: status.as_u16(),
820                code: "server_error".to_string(),
821                message: "Something went wrong. Please try again.".to_string(),
822            });
823        };
824        let message = body
825            .error
826            .message
827            .unwrap_or_else(|| "Something went wrong. Please try again.".to_string());
828        Err(match body.error.code.as_str() {
829            "not_found" => ScribeError::NotFound { message },
830            "forbidden" => ScribeError::Forbidden { message },
831            "not_trashed" => ScribeError::NotTrashed { message },
832            "conversion_not_complete" => ScribeError::ConversionNotComplete { message },
833            _ => ScribeError::Api {
834                status: status.as_u16(),
835                code: body.error.code,
836                message,
837            },
838        })
839    }
840}