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
21const REFRESH_SKEW: Duration = Duration::from_secs(300);
24
25pub enum DocumentSource {
27 File { file_name: String, bytes: Vec<u8> },
29 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
45pub 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 #[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 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 pub async fn current_tokens(&self) -> TokenSet {
112 self.tokens.lock().await.clone()
113 }
114
115 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 response.error_for_status_or_json_error().await?;
410 Ok(None)
411 }
412
413 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 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 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 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 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 pub async fn delete_account_url(&self) -> Result<String, ScribeError> {
545 self.browser_entry_url(DELETE_ACCOUNT_PATH).await
546 }
547
548 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 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 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 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 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 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 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 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 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 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 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 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 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 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 pub fn voice_sample_url(&self, short_name: &str) -> Result<String, ScribeError> {
756 Ok(self.voice_sample_location(short_name)?.into())
757 }
758
759 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 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 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
833fn 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
849fn 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 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 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}