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
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}
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 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 pub async fn current_tokens(&self) -> TokenSet {
95 self.tokens.lock().await.clone()
96 }
97
98 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 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 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 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 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 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 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 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 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 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 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 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 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 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 response.error_for_status_or_json_error().await?;
387 Ok(None)
388 }
389
390 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 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 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 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 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 pub async fn delete_account_url(&self) -> Result<String, ScribeError> {
522 self.browser_entry_url(DELETE_ACCOUNT_PATH).await
523 }
524
525 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 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 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 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 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 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 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 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 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 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 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 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 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 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 pub fn voice_sample_url(&self, short_name: &str) -> Result<String, ScribeError> {
733 Ok(self.voice_sample_location(short_name)?.into())
734 }
735
736 pub async fn voice_sample(&self, short_name: &str) -> Result<Vec<u8>, ScribeError> {
745 let url = self.voice_sample_location(short_name)?;
746 let response = self.http.get(url).send().await?;
747 if response.status() == reqwest::StatusCode::NOT_FOUND {
748 return Err(no_sample(short_name));
749 }
750 let response = response.error_for_status_or_json_error().await?;
751 Ok(response.bytes().await?.to_vec())
752 }
753
754 fn voice_sample_location(&self, short_name: &str) -> Result<Url, ScribeError> {
755 let is_name = !short_name.is_empty()
756 && short_name
757 .chars()
758 .all(|c| c.is_ascii_alphanumeric() || c == '-');
759 if !is_name {
760 return Err(no_sample(short_name));
761 }
762 let mut url = self.base_url.clone();
763 url.set_path(&format!("/sounds/tts-samples/{short_name}.mp3"));
764 url.set_query(None);
765 Ok(url)
766 }
767
768 async fn with_auth_retry_raw<F>(&self, build: F) -> Result<reqwest::Response, ScribeError>
772 where
773 F: Fn(&str) -> reqwest::RequestBuilder,
774 {
775 let token = self.access_token().await?;
776 let response = build(&token).send().await?;
777 let response = if response.status() == reqwest::StatusCode::UNAUTHORIZED {
778 let token = self.force_refresh().await?;
779 build(&token).send().await?
780 } else {
781 response
782 };
783 response.error_for_status_or_json_error().await
784 }
785
786 async fn with_auth_retry<T, F>(&self, build: F) -> Result<T, ScribeError>
788 where
789 T: serde::de::DeserializeOwned,
790 F: Fn(&str) -> reqwest::RequestBuilder,
791 {
792 self.with_auth_retry_raw(build)
793 .await?
794 .json()
795 .await
796 .map_err(Into::into)
797 }
798}
799
800fn no_sample(short_name: &str) -> ScribeError {
801 ScribeError::NotFound {
802 message: format!("There's no sample of the voice {short_name:?}."),
803 }
804}
805
806fn response_total_bytes(response: &reqwest::Response) -> Option<u64> {
813 response.content_length().or_else(|| {
814 response
815 .headers()
816 .get("x-scribe-content-length")
817 .and_then(|value| value.to_str().ok())
818 .and_then(|value| value.trim().parse().ok())
819 })
820}
821
822fn content_disposition_file_name(header: &str) -> Option<String> {
827 let mut fallback = None;
828 let mut extended = None;
829 for param in header.split(';').map(str::trim) {
830 if let Some(value) = param.strip_prefix("filename*=") {
831 let mut parts = value.splitn(3, '\'');
835 if let (Some(charset), Some(_), Some(encoded)) =
836 (parts.next(), parts.next(), parts.next())
837 {
838 if charset.eq_ignore_ascii_case("utf-8") {
839 extended = percent_encoding::percent_decode_str(encoded)
840 .decode_utf8()
841 .ok()
842 .map(|name| name.into_owned());
843 }
844 }
845 } else if let Some(value) = param.strip_prefix("filename=") {
846 fallback = Some(value.trim_matches('"').to_string());
847 }
848 }
849 extended
850 .or(fallback)
851 .and_then(|name| name.rsplit(['/', '\\']).next().map(str::to_string))
852 .filter(|name| !name.is_empty())
853}
854
855trait ResponseExt {
856 async fn error_for_status_or_json_error(self) -> Result<reqwest::Response, ScribeError>;
857}
858
859impl ResponseExt for reqwest::Response {
860 async fn error_for_status_or_json_error(self) -> Result<reqwest::Response, ScribeError> {
861 let status = self.status();
862 if status.is_success() {
863 return Ok(self);
864 }
865 let text = self.text().await.unwrap_or_default();
866 let Ok(body) = serde_json::from_str::<ApiErrorResponse>(&text) else {
870 return Err(ScribeError::Api {
871 status: status.as_u16(),
872 code: "server_error".to_string(),
873 message: "Something went wrong. Please try again.".to_string(),
874 });
875 };
876 let message = body
877 .error
878 .message
879 .unwrap_or_else(|| "Something went wrong. Please try again.".to_string());
880 Err(match body.error.code.as_str() {
881 "not_found" => ScribeError::NotFound { message },
882 "forbidden" => ScribeError::Forbidden { message },
883 "not_trashed" => ScribeError::NotTrashed { message },
884 "conversion_not_complete" => ScribeError::ConversionNotComplete { message },
885 _ => ScribeError::Api {
886 status: status.as_u16(),
887 code: body.error.code,
888 message,
889 },
890 })
891 }
892}