scribe-client 0.2.0__tar.gz → 0.3.1__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- {scribe_client-0.2.0 → scribe_client-0.3.1}/Cargo.lock +3 -3
- {scribe_client-0.2.0 → scribe_client-0.3.1}/Cargo.toml +1 -1
- {scribe_client-0.2.0 → scribe_client-0.3.1}/PKG-INFO +13 -1
- {scribe_client-0.2.0/crates/scribe-client-py → scribe_client-0.3.1}/README.md +12 -0
- {scribe_client-0.2.0 → scribe_client-0.3.1}/crates/scribe-client/README.md +2 -2
- {scribe_client-0.2.0 → scribe_client-0.3.1}/crates/scribe-client/src/auth.rs +41 -2
- {scribe_client-0.2.0 → scribe_client-0.3.1}/crates/scribe-client/src/channel.rs +26 -15
- {scribe_client-0.2.0 → scribe_client-0.3.1}/crates/scribe-client/src/client.rs +84 -5
- {scribe_client-0.2.0 → scribe_client-0.3.1}/crates/scribe-client/src/model.rs +28 -2
- {scribe_client-0.2.0 → scribe_client-0.3.1}/crates/scribe-client/tests/channel_test.rs +97 -0
- scribe_client-0.3.1/crates/scribe-client/tests/locale_test.rs +179 -0
- {scribe_client-0.2.0 → scribe_client-0.3.1}/crates/scribe-client/tests/settings_test.rs +64 -0
- {scribe_client-0.2.0 → scribe_client-0.3.1/crates/scribe-client-py}/README.md +12 -0
- {scribe_client-0.2.0 → scribe_client-0.3.1}/crates/scribe-client-py/src/auth.rs +9 -4
- {scribe_client-0.2.0 → scribe_client-0.3.1}/crates/scribe-client-py/src/client.rs +34 -4
- {scribe_client-0.2.0 → scribe_client-0.3.1}/crates/scribe-client-py/tests/test_client.py +22 -0
- {scribe_client-0.2.0 → scribe_client-0.3.1}/crates/scribe-client-py/tests/test_settings.py +37 -0
- {scribe_client-0.2.0 → scribe_client-0.3.1}/crates/scribe-client-py/uv.lock +1 -1
- {scribe_client-0.2.0 → scribe_client-0.3.1}/crates/scribe-client/Cargo.toml +0 -0
- {scribe_client-0.2.0 → scribe_client-0.3.1}/crates/scribe-client/examples/pkce_flow.rs +0 -0
- {scribe_client-0.2.0 → scribe_client-0.3.1}/crates/scribe-client/src/error.rs +0 -0
- {scribe_client-0.2.0 → scribe_client-0.3.1}/crates/scribe-client/src/lib.rs +0 -0
- {scribe_client-0.2.0 → scribe_client-0.3.1}/crates/scribe-client/tests/auth_test.rs +0 -0
- {scribe_client-0.2.0 → scribe_client-0.3.1}/crates/scribe-client/tests/client_test.rs +0 -0
- {scribe_client-0.2.0 → scribe_client-0.3.1}/crates/scribe-client-py/Cargo.toml +0 -0
- {scribe_client-0.2.0 → scribe_client-0.3.1}/crates/scribe-client-py/build.rs +0 -0
- {scribe_client-0.2.0 → scribe_client-0.3.1}/crates/scribe-client-py/examples/pkce_flow.py +0 -0
- {scribe_client-0.2.0 → scribe_client-0.3.1}/crates/scribe-client-py/src/channel.rs +0 -0
- {scribe_client-0.2.0 → scribe_client-0.3.1}/crates/scribe-client-py/src/error.rs +0 -0
- {scribe_client-0.2.0 → scribe_client-0.3.1}/crates/scribe-client-py/src/lib.rs +0 -0
- {scribe_client-0.2.0 → scribe_client-0.3.1}/crates/scribe-client-py/src/model.rs +0 -0
- {scribe_client-0.2.0 → scribe_client-0.3.1}/crates/scribe-client-py/tests/conftest.py +0 -0
- {scribe_client-0.2.0 → scribe_client-0.3.1}/crates/scribe-client-py/tests/test_auth.py +0 -0
- {scribe_client-0.2.0 → scribe_client-0.3.1}/crates/scribe-client-py/tests/test_channel.py +0 -0
- {scribe_client-0.2.0 → scribe_client-0.3.1}/crates/scribe-client-py/tests/test_pkce_and_tokens.py +0 -0
- {scribe_client-0.2.0 → scribe_client-0.3.1}/pyproject.toml +0 -0
|
@@ -1678,7 +1678,7 @@ dependencies = [
|
|
|
1678
1678
|
|
|
1679
1679
|
[[package]]
|
|
1680
1680
|
name = "scribe-client"
|
|
1681
|
-
version = "0.
|
|
1681
|
+
version = "0.3.1"
|
|
1682
1682
|
dependencies = [
|
|
1683
1683
|
"base64 0.22.1",
|
|
1684
1684
|
"futures-util",
|
|
@@ -1698,7 +1698,7 @@ dependencies = [
|
|
|
1698
1698
|
|
|
1699
1699
|
[[package]]
|
|
1700
1700
|
name = "scribe-client-ffi"
|
|
1701
|
-
version = "0.
|
|
1701
|
+
version = "0.3.1"
|
|
1702
1702
|
dependencies = [
|
|
1703
1703
|
"futures-util",
|
|
1704
1704
|
"reqwest",
|
|
@@ -1714,7 +1714,7 @@ dependencies = [
|
|
|
1714
1714
|
|
|
1715
1715
|
[[package]]
|
|
1716
1716
|
name = "scribe-client-py"
|
|
1717
|
-
version = "0.
|
|
1717
|
+
version = "0.3.1"
|
|
1718
1718
|
dependencies = [
|
|
1719
1719
|
"pyo3",
|
|
1720
1720
|
"pyo3-build-config",
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: scribe-client
|
|
3
|
-
Version: 0.
|
|
3
|
+
Version: 0.3.1
|
|
4
4
|
Classifier: Development Status :: 4 - Beta
|
|
5
5
|
Classifier: Intended Audience :: Developers
|
|
6
6
|
Classifier: License :: OSI Approved :: MIT License
|
|
@@ -116,6 +116,18 @@ client.update_settings(document_id, {"large_print": True})
|
|
|
116
116
|
|
|
117
117
|
`update_settings` takes a plain dict; only the keys you pass are changed server-side.
|
|
118
118
|
|
|
119
|
+
## Voices and their samples
|
|
120
|
+
|
|
121
|
+
`voices()` lists the text-to-speech voices by dialect, each as a `(name, short_name, has_sample)` triple. A voice whose `has_sample` is true has a short MP3 the user can listen to before choosing it, as the Scribe app lets them. `voice_sample_url(short_name)` gives its URL, which needs no token, so you can hand it straight to a media player to stream. `voice_sample(short_name)` downloads the MP3 bytes instead. Both raise `NotFoundError` when there's no sample.
|
|
122
|
+
|
|
123
|
+
```python
|
|
124
|
+
voices = client.voices()
|
|
125
|
+
name, short_name, has_sample = voices["en-US"][0]
|
|
126
|
+
if has_sample:
|
|
127
|
+
play(client.voice_sample_url(short_name)) # or: data = client.voice_sample(short_name)
|
|
128
|
+
client.update_settings(document_id, {"voices": {"en-US": short_name}})
|
|
129
|
+
```
|
|
130
|
+
|
|
119
131
|
## Converting to another format
|
|
120
132
|
|
|
121
133
|
Creating a document starts only the `html_stream` conversion. Converting to any other format — `pdf`, `epub`, `daisy`, `docx`, `brf`, `mp3`, `offline_html`, `mobi` — happens over a **real-time channel**, not a REST call, so the server can guarantee it's subscribed to progress on whatever it just started converting.
|
|
@@ -95,6 +95,18 @@ client.update_settings(document_id, {"large_print": True})
|
|
|
95
95
|
|
|
96
96
|
`update_settings` takes a plain dict; only the keys you pass are changed server-side.
|
|
97
97
|
|
|
98
|
+
## Voices and their samples
|
|
99
|
+
|
|
100
|
+
`voices()` lists the text-to-speech voices by dialect, each as a `(name, short_name, has_sample)` triple. A voice whose `has_sample` is true has a short MP3 the user can listen to before choosing it, as the Scribe app lets them. `voice_sample_url(short_name)` gives its URL, which needs no token, so you can hand it straight to a media player to stream. `voice_sample(short_name)` downloads the MP3 bytes instead. Both raise `NotFoundError` when there's no sample.
|
|
101
|
+
|
|
102
|
+
```python
|
|
103
|
+
voices = client.voices()
|
|
104
|
+
name, short_name, has_sample = voices["en-US"][0]
|
|
105
|
+
if has_sample:
|
|
106
|
+
play(client.voice_sample_url(short_name)) # or: data = client.voice_sample(short_name)
|
|
107
|
+
client.update_settings(document_id, {"voices": {"en-US": short_name}})
|
|
108
|
+
```
|
|
109
|
+
|
|
98
110
|
## Converting to another format
|
|
99
111
|
|
|
100
112
|
Creating a document starts only the `html_stream` conversion. Converting to any other format — `pdf`, `epub`, `daisy`, `docx`, `brf`, `mp3`, `offline_html`, `mobi` — happens over a **real-time channel**, not a REST call, so the server can guarantee it's subscribed to progress on whatever it just started converting.
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
# scribe-client
|
|
2
2
|
|
|
3
|
-
A Rust client for the [Scribe for Documents](https://scribeit.io) API by Pneuma Solutions, which converts documents into accessible formats: HTML,
|
|
3
|
+
A Rust client for the [Scribe for Documents](https://scribeit.io) API by Pneuma Solutions, which converts documents into accessible formats: HTML, streaming HTML, offline HTML, tagged PDF, Word (DOCX), EPUB, MOBI, DAISY, MP3 audio, and Braille (BRF).
|
|
4
4
|
|
|
5
5
|
It covers signing in (OAuth 2.0 with PKCE), uploading documents, converting them, following a conversion live over a WebSocket channel, downloading the results, and the account and settings around them. The [`scribe-client`](https://pypi.org/project/scribe-client/) Python package is built on it.
|
|
6
6
|
|
|
@@ -42,7 +42,7 @@ async fn main() -> Result<(), scribe_client::ScribeError> {
|
|
|
42
42
|
By default TLS is done by [rustls](https://crates.io/crates/rustls), with no system library to link against. To use the platform's own TLS library instead (Security.framework on Apple platforms, SChannel on Windows, OpenSSL elsewhere), turn off the default features and turn on `native-tls`:
|
|
43
43
|
|
|
44
44
|
```toml
|
|
45
|
-
scribe-client = { version = "0.
|
|
45
|
+
scribe-client = { version = "0.3", default-features = false, features = ["native-tls"] }
|
|
46
46
|
```
|
|
47
47
|
|
|
48
48
|
## License
|
|
@@ -113,6 +113,7 @@ pub struct AuthClient {
|
|
|
113
113
|
http: reqwest::Client,
|
|
114
114
|
base_url: Url,
|
|
115
115
|
client_id: String,
|
|
116
|
+
locale: Option<String>,
|
|
116
117
|
}
|
|
117
118
|
|
|
118
119
|
impl AuthClient {
|
|
@@ -121,9 +122,24 @@ impl AuthClient {
|
|
|
121
122
|
http,
|
|
122
123
|
base_url,
|
|
123
124
|
client_id: client_id.into(),
|
|
125
|
+
locale: None,
|
|
124
126
|
}
|
|
125
127
|
}
|
|
126
128
|
|
|
129
|
+
/// Asks the server for its messages in `locale`, a language tag such as
|
|
130
|
+
/// `de` or `pt-BR`, usually the language the app's own interface is in.
|
|
131
|
+
/// The sign-in page from [`Self::authorization_url`] opens in it too.
|
|
132
|
+
/// Without one, the server uses the account's language, or English.
|
|
133
|
+
#[must_use]
|
|
134
|
+
pub fn with_locale(mut self, locale: impl Into<String>) -> Self {
|
|
135
|
+
self.locale = Some(locale.into());
|
|
136
|
+
self
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
pub(crate) fn locale(&self) -> Option<&str> {
|
|
140
|
+
self.locale.as_deref()
|
|
141
|
+
}
|
|
142
|
+
|
|
127
143
|
/// Builds the URL the user's browser should be sent to. `redirect_uri`
|
|
128
144
|
/// must match one registered for `client_id` server-side.
|
|
129
145
|
///
|
|
@@ -174,6 +190,11 @@ impl AuthClient {
|
|
|
174
190
|
let mut url = self.base_url.clone();
|
|
175
191
|
url.set_path("/auth/logout");
|
|
176
192
|
url.query_pairs_mut().append_pair("next", &next);
|
|
193
|
+
// The website keeps `locale` in a cookie that logging out leaves
|
|
194
|
+
// alone, so the sign-in page the redirects end on is in it too.
|
|
195
|
+
if let Some(locale) = &self.locale {
|
|
196
|
+
url.query_pairs_mut().append_pair("locale", locale);
|
|
197
|
+
}
|
|
177
198
|
url
|
|
178
199
|
}
|
|
179
200
|
|
|
@@ -243,7 +264,10 @@ impl AuthClient {
|
|
|
243
264
|
let mut url = self.base_url.clone();
|
|
244
265
|
url.set_path("/oauth/revoke");
|
|
245
266
|
let body = [("client_id", self.client_id.as_str()), ("token", token)];
|
|
246
|
-
let response = self.http.post(url).
|
|
267
|
+
let response = accept_language(self.http.post(url), self.locale())
|
|
268
|
+
.form(&body)
|
|
269
|
+
.send()
|
|
270
|
+
.await?;
|
|
247
271
|
let status = response.status();
|
|
248
272
|
if status.is_success() {
|
|
249
273
|
return Ok(());
|
|
@@ -267,7 +291,10 @@ impl AuthClient {
|
|
|
267
291
|
url: Url,
|
|
268
292
|
body: &[(&str, &str)],
|
|
269
293
|
) -> Result<TokenSet, ScribeError> {
|
|
270
|
-
let response = self.http.post(url).
|
|
294
|
+
let response = accept_language(self.http.post(url), self.locale())
|
|
295
|
+
.form(body)
|
|
296
|
+
.send()
|
|
297
|
+
.await?;
|
|
271
298
|
let status = response.status();
|
|
272
299
|
if status.is_success() {
|
|
273
300
|
let parsed: TokenResponse = response.json().await?;
|
|
@@ -297,6 +324,18 @@ impl AuthClient {
|
|
|
297
324
|
}
|
|
298
325
|
}
|
|
299
326
|
|
|
327
|
+
/// Adds `Accept-Language` for `locale`, which is how the server picks the
|
|
328
|
+
/// language of what it says in a response.
|
|
329
|
+
pub(crate) fn accept_language(
|
|
330
|
+
request: reqwest::RequestBuilder,
|
|
331
|
+
locale: Option<&str>,
|
|
332
|
+
) -> reqwest::RequestBuilder {
|
|
333
|
+
match locale {
|
|
334
|
+
Some(locale) => request.header(reqwest::header::ACCEPT_LANGUAGE, locale),
|
|
335
|
+
None => request,
|
|
336
|
+
}
|
|
337
|
+
}
|
|
338
|
+
|
|
300
339
|
#[cfg(test)]
|
|
301
340
|
mod tests {
|
|
302
341
|
use super::*;
|
|
@@ -47,7 +47,12 @@ pub enum ChannelEvent {
|
|
|
47
47
|
},
|
|
48
48
|
/// The server reported an error unrelated to a specific request we
|
|
49
49
|
/// made (e.g. a conversion failed after it had already started).
|
|
50
|
-
|
|
50
|
+
/// `message` is a sentence to show for it, in the client's language,
|
|
51
|
+
/// from servers that send one.
|
|
52
|
+
Error {
|
|
53
|
+
reason: String,
|
|
54
|
+
message: Option<String>,
|
|
55
|
+
},
|
|
51
56
|
/// The document is password-protected and hasn't been unlocked yet.
|
|
52
57
|
/// Pushed on join, since a locked document has no outputs and would
|
|
53
58
|
/// otherwise look like a silent channel. Prompt for the password and
|
|
@@ -66,6 +71,8 @@ struct ReplyPayload {
|
|
|
66
71
|
struct ErrorReason {
|
|
67
72
|
reason: String,
|
|
68
73
|
#[serde(default)]
|
|
74
|
+
message: Option<String>,
|
|
75
|
+
#[serde(default)]
|
|
69
76
|
purchase_url: Option<String>,
|
|
70
77
|
}
|
|
71
78
|
|
|
@@ -315,6 +322,10 @@ fn parse_event(event: &str, payload: &Value) -> Option<ChannelEvent> {
|
|
|
315
322
|
}),
|
|
316
323
|
"error" => Some(ChannelEvent::Error {
|
|
317
324
|
reason: payload.get("reason")?.as_str()?.to_string(),
|
|
325
|
+
message: payload
|
|
326
|
+
.get("message")
|
|
327
|
+
.and_then(Value::as_str)
|
|
328
|
+
.map(str::to_string),
|
|
318
329
|
}),
|
|
319
330
|
"password_required" => Some(ChannelEvent::PasswordRequired),
|
|
320
331
|
_ => None,
|
|
@@ -325,34 +336,34 @@ fn map_channel_error(payload: Value) -> ScribeError {
|
|
|
325
336
|
let Ok(err) = serde_json::from_value::<ErrorReason>(payload) else {
|
|
326
337
|
return ScribeError::ChannelClosed;
|
|
327
338
|
};
|
|
328
|
-
//
|
|
329
|
-
// server
|
|
330
|
-
//
|
|
331
|
-
|
|
332
|
-
// token errors) uses that instead; see error_for_status_or_json_error.
|
|
339
|
+
// The server's own message is in the language the client asked for.
|
|
340
|
+
// A server too old to send one gets the English these codes have always
|
|
341
|
+
// shown.
|
|
342
|
+
let message = |english: &str| err.message.clone().unwrap_or_else(|| english.to_string());
|
|
333
343
|
match err.reason.as_str() {
|
|
334
344
|
"not_found" => ScribeError::NotFound {
|
|
335
|
-
message: "We couldn't find that document."
|
|
345
|
+
message: message("We couldn't find that document."),
|
|
336
346
|
},
|
|
337
347
|
"forbidden" => ScribeError::Forbidden {
|
|
338
|
-
message: "You don't have permission to access that document."
|
|
348
|
+
message: message("You don't have permission to access that document."),
|
|
339
349
|
},
|
|
340
350
|
"conversion_in_progress" => ScribeError::ConversionInProgress {
|
|
341
|
-
message: "A conversion is already in progress for this document."
|
|
351
|
+
message: message("A conversion is already in progress for this document."),
|
|
342
352
|
},
|
|
343
353
|
"rate_limited" => ScribeError::RateLimited {
|
|
344
|
-
message: "Rate limited, try again shortly."
|
|
354
|
+
message: message("Rate limited, try again shortly."),
|
|
345
355
|
},
|
|
346
356
|
"password_required" => ScribeError::PasswordRequired {
|
|
347
|
-
message:
|
|
348
|
-
.
|
|
357
|
+
message: message(
|
|
358
|
+
"This document is password-protected. Enter its password to continue.",
|
|
359
|
+
),
|
|
349
360
|
},
|
|
350
361
|
"needs_purchase" => ScribeError::NeedsPurchase {
|
|
351
|
-
message: "You need to purchase more pages to do that."
|
|
352
|
-
purchase_url: err.purchase_url.unwrap_or_default(),
|
|
362
|
+
message: message("You need to purchase more pages to do that."),
|
|
363
|
+
purchase_url: err.purchase_url.clone().unwrap_or_default(),
|
|
353
364
|
},
|
|
354
365
|
_ => ScribeError::Channel {
|
|
355
|
-
message: "Something went wrong. Please try again."
|
|
366
|
+
message: message("Something went wrong. Please try again."),
|
|
356
367
|
},
|
|
357
368
|
}
|
|
358
369
|
}
|
|
@@ -6,7 +6,7 @@ use tokio::sync::Mutex;
|
|
|
6
6
|
use url::Url;
|
|
7
7
|
|
|
8
8
|
use crate::{
|
|
9
|
-
auth::{AuthClient, TokenSet},
|
|
9
|
+
auth::{accept_language, AuthClient, TokenSet},
|
|
10
10
|
channel::DocumentChannel,
|
|
11
11
|
error::ScribeError,
|
|
12
12
|
model::{
|
|
@@ -59,6 +59,7 @@ pub struct ScribeClient {
|
|
|
59
59
|
base_url: Url,
|
|
60
60
|
auth: AuthClient,
|
|
61
61
|
tokens: Arc<Mutex<TokenSet>>,
|
|
62
|
+
locale: Option<String>,
|
|
62
63
|
}
|
|
63
64
|
|
|
64
65
|
impl ScribeClient {
|
|
@@ -74,9 +75,25 @@ impl ScribeClient {
|
|
|
74
75
|
base_url,
|
|
75
76
|
auth,
|
|
76
77
|
tokens: Arc::new(Mutex::new(tokens)),
|
|
78
|
+
locale: None,
|
|
77
79
|
}
|
|
78
80
|
}
|
|
79
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
|
+
|
|
80
97
|
/// The current access token, refreshing first if it's missing or about
|
|
81
98
|
/// to expire and a refresh token is available.
|
|
82
99
|
async fn access_token(&self) -> Result<String, ScribeError> {
|
|
@@ -301,6 +318,11 @@ impl ScribeClient {
|
|
|
301
318
|
url.query_pairs_mut()
|
|
302
319
|
.append_pair("vsn", "2.0.0")
|
|
303
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
|
+
}
|
|
304
326
|
let (ws, _response) = tokio_tungstenite::connect_async(url.as_str())
|
|
305
327
|
.await
|
|
306
328
|
.map_err(|e| ScribeError::WebSocket(Box::new(e)))?;
|
|
@@ -367,11 +389,12 @@ impl ScribeClient {
|
|
|
367
389
|
.redirect(reqwest::redirect::Policy::none())
|
|
368
390
|
.build()?;
|
|
369
391
|
|
|
392
|
+
let request = |token: &str| self.localized(client.get(url.clone()).bearer_auth(token));
|
|
370
393
|
let token = self.access_token().await?;
|
|
371
|
-
let mut response =
|
|
394
|
+
let mut response = request(&token).send().await?;
|
|
372
395
|
if response.status() == reqwest::StatusCode::UNAUTHORIZED {
|
|
373
396
|
let token = self.force_refresh().await?;
|
|
374
|
-
response =
|
|
397
|
+
response = request(&token).send().await?;
|
|
375
398
|
}
|
|
376
399
|
|
|
377
400
|
if response.status().is_redirection() {
|
|
@@ -719,6 +742,52 @@ impl ScribeClient {
|
|
|
719
742
|
Ok(response.voices)
|
|
720
743
|
}
|
|
721
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
|
+
|
|
722
791
|
/// Sends a request built by `build`, retrying once with a
|
|
723
792
|
/// force-refreshed token if the server returns `401`. Returns the
|
|
724
793
|
/// validated response for callers that need to read the body themselves.
|
|
@@ -727,16 +796,20 @@ impl ScribeClient {
|
|
|
727
796
|
F: Fn(&str) -> reqwest::RequestBuilder,
|
|
728
797
|
{
|
|
729
798
|
let token = self.access_token().await?;
|
|
730
|
-
let response = build(&token).send().await?;
|
|
799
|
+
let response = self.localized(build(&token)).send().await?;
|
|
731
800
|
let response = if response.status() == reqwest::StatusCode::UNAUTHORIZED {
|
|
732
801
|
let token = self.force_refresh().await?;
|
|
733
|
-
build(&token).send().await?
|
|
802
|
+
self.localized(build(&token)).send().await?
|
|
734
803
|
} else {
|
|
735
804
|
response
|
|
736
805
|
};
|
|
737
806
|
response.error_for_status_or_json_error().await
|
|
738
807
|
}
|
|
739
808
|
|
|
809
|
+
fn localized(&self, request: reqwest::RequestBuilder) -> reqwest::RequestBuilder {
|
|
810
|
+
accept_language(request, self.locale.as_deref())
|
|
811
|
+
}
|
|
812
|
+
|
|
740
813
|
/// Like [`with_auth_retry_raw`] but deserializes the response body as JSON.
|
|
741
814
|
async fn with_auth_retry<T, F>(&self, build: F) -> Result<T, ScribeError>
|
|
742
815
|
where
|
|
@@ -751,6 +824,12 @@ impl ScribeClient {
|
|
|
751
824
|
}
|
|
752
825
|
}
|
|
753
826
|
|
|
827
|
+
fn no_sample(short_name: &str) -> ScribeError {
|
|
828
|
+
ScribeError::NotFound {
|
|
829
|
+
message: format!("There's no sample of the voice {short_name:?}."),
|
|
830
|
+
}
|
|
831
|
+
}
|
|
832
|
+
|
|
754
833
|
/// Small helper trait so response-status handling reads the same way at every call site.
|
|
755
834
|
/// How many bytes the body will be, if the server says.
|
|
756
835
|
///
|
|
@@ -210,14 +210,40 @@ pub struct Settings {
|
|
|
210
210
|
pub notify_when_complete: bool,
|
|
211
211
|
}
|
|
212
212
|
|
|
213
|
+
/// The server takes `dialects` and `voices` as strings holding JSON, though
|
|
214
|
+
/// it gives them back decoded, so an object written back as it was read is
|
|
215
|
+
/// sent as its JSON. A string is sent as it is.
|
|
216
|
+
#[allow(clippy::ref_option, reason = "serde's serialize_with signature")]
|
|
217
|
+
fn as_json_string<S: serde::Serializer>(
|
|
218
|
+
value: &Option<serde_json::Value>,
|
|
219
|
+
serializer: S,
|
|
220
|
+
) -> Result<S::Ok, S::Error> {
|
|
221
|
+
match value {
|
|
222
|
+
Some(serde_json::Value::String(text)) => serializer.serialize_str(text),
|
|
223
|
+
Some(other) => serializer.serialize_str(&other.to_string()),
|
|
224
|
+
None => serializer.serialize_none(),
|
|
225
|
+
}
|
|
226
|
+
}
|
|
227
|
+
|
|
213
228
|
/// A partial update to a document's conversion settings
|
|
214
229
|
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
|
|
215
230
|
pub struct SettingsUpdate {
|
|
216
231
|
#[serde(default, skip_serializing_if = "Option::is_none")]
|
|
217
232
|
pub language: Option<String>,
|
|
218
|
-
|
|
233
|
+
/// Language code to dialect locale. An object is sent as the string of
|
|
234
|
+
/// JSON the server takes.
|
|
235
|
+
#[serde(
|
|
236
|
+
default,
|
|
237
|
+
skip_serializing_if = "Option::is_none",
|
|
238
|
+
serialize_with = "as_json_string"
|
|
239
|
+
)]
|
|
219
240
|
pub dialects: Option<serde_json::Value>,
|
|
220
|
-
|
|
241
|
+
/// Dialect locale to voice short name, sent as `dialects` is.
|
|
242
|
+
#[serde(
|
|
243
|
+
default,
|
|
244
|
+
skip_serializing_if = "Option::is_none",
|
|
245
|
+
serialize_with = "as_json_string"
|
|
246
|
+
)]
|
|
221
247
|
pub voices: Option<serde_json::Value>,
|
|
222
248
|
#[serde(default, skip_serializing_if = "Option::is_none")]
|
|
223
249
|
pub tts_gender: Option<String>,
|
|
@@ -494,3 +494,100 @@ async fn close_succeeds_after_the_connection_was_lost() {
|
|
|
494
494
|
assert!(channel.next_event().await.is_err());
|
|
495
495
|
channel.close().await.unwrap();
|
|
496
496
|
}
|
|
497
|
+
|
|
498
|
+
/// Answers the join with `reply`, then pushes each of `pushes` as an event.
|
|
499
|
+
async fn serve_join(reply: Value, pushes: Vec<(&'static str, Value)>) -> Url {
|
|
500
|
+
start_fake_server(move |mut ws| {
|
|
501
|
+
Box::pin(async move {
|
|
502
|
+
let (join_ref, ref_, topic, _event, _payload) = recv(&mut ws).await;
|
|
503
|
+
let join_ref = join_ref.unwrap();
|
|
504
|
+
send(
|
|
505
|
+
&mut ws,
|
|
506
|
+
&join_ref,
|
|
507
|
+
Some(&ref_.unwrap()),
|
|
508
|
+
&topic,
|
|
509
|
+
"phx_reply",
|
|
510
|
+
reply,
|
|
511
|
+
)
|
|
512
|
+
.await;
|
|
513
|
+
for (event, payload) in pushes {
|
|
514
|
+
send(&mut ws, &join_ref, None, &topic, event, payload).await;
|
|
515
|
+
}
|
|
516
|
+
})
|
|
517
|
+
})
|
|
518
|
+
.await
|
|
519
|
+
}
|
|
520
|
+
|
|
521
|
+
#[tokio::test]
|
|
522
|
+
async fn a_join_error_shows_the_servers_message() {
|
|
523
|
+
let base_url = serve_join(
|
|
524
|
+
serde_json::json!({"status": "error", "response": {
|
|
525
|
+
"reason": "forbidden",
|
|
526
|
+
"message": "Sie haben keine Berechtigung, auf dieses Dokument zuzugreifen."
|
|
527
|
+
}}),
|
|
528
|
+
vec![],
|
|
529
|
+
)
|
|
530
|
+
.await;
|
|
531
|
+
match client_for(base_url).open_document_channel("doc-1").await {
|
|
532
|
+
Err(ScribeError::Forbidden { message }) => {
|
|
533
|
+
assert_eq!(
|
|
534
|
+
message,
|
|
535
|
+
"Sie haben keine Berechtigung, auf dieses Dokument zuzugreifen."
|
|
536
|
+
);
|
|
537
|
+
}
|
|
538
|
+
Err(other) => panic!("expected Forbidden, got {other:?}"),
|
|
539
|
+
Ok(_) => panic!("expected Forbidden, got a channel"),
|
|
540
|
+
}
|
|
541
|
+
}
|
|
542
|
+
|
|
543
|
+
#[tokio::test]
|
|
544
|
+
async fn a_join_error_without_a_message_falls_back_to_english() {
|
|
545
|
+
let base_url = serve_join(
|
|
546
|
+
serde_json::json!({"status": "error", "response": {"reason": "not_found"}}),
|
|
547
|
+
vec![],
|
|
548
|
+
)
|
|
549
|
+
.await;
|
|
550
|
+
match client_for(base_url).open_document_channel("doc-1").await {
|
|
551
|
+
Err(ScribeError::NotFound { message }) => {
|
|
552
|
+
assert_eq!(message, "We couldn't find that document.");
|
|
553
|
+
}
|
|
554
|
+
Err(other) => panic!("expected NotFound, got {other:?}"),
|
|
555
|
+
Ok(_) => panic!("expected NotFound, got a channel"),
|
|
556
|
+
}
|
|
557
|
+
}
|
|
558
|
+
|
|
559
|
+
#[tokio::test]
|
|
560
|
+
async fn an_error_event_carries_the_servers_message_when_there_is_one() {
|
|
561
|
+
let base_url = serve_join(
|
|
562
|
+
serde_json::json!({"status": "ok", "response": {}}),
|
|
563
|
+
vec![
|
|
564
|
+
(
|
|
565
|
+
"error",
|
|
566
|
+
serde_json::json!({
|
|
567
|
+
"reason": "invalid_password",
|
|
568
|
+
"message": "Ce mot de passe n'a pas fonctionné."
|
|
569
|
+
}),
|
|
570
|
+
),
|
|
571
|
+
("error", serde_json::json!({"reason": "conversion_failed"})),
|
|
572
|
+
],
|
|
573
|
+
)
|
|
574
|
+
.await;
|
|
575
|
+
let mut channel = client_for(base_url)
|
|
576
|
+
.open_document_channel("doc-1")
|
|
577
|
+
.await
|
|
578
|
+
.unwrap();
|
|
579
|
+
assert_eq!(
|
|
580
|
+
channel.next_event().await.unwrap(),
|
|
581
|
+
ChannelEvent::Error {
|
|
582
|
+
reason: "invalid_password".into(),
|
|
583
|
+
message: Some("Ce mot de passe n'a pas fonctionné.".into()),
|
|
584
|
+
}
|
|
585
|
+
);
|
|
586
|
+
assert_eq!(
|
|
587
|
+
channel.next_event().await.unwrap(),
|
|
588
|
+
ChannelEvent::Error {
|
|
589
|
+
reason: "conversion_failed".into(),
|
|
590
|
+
message: None,
|
|
591
|
+
}
|
|
592
|
+
);
|
|
593
|
+
}
|
|
@@ -0,0 +1,179 @@
|
|
|
1
|
+
//! The client's locale reaches the server on every path it can: `Accept-Language` on API and OAuth requests, `locale` on the socket and on the sign-in page.
|
|
2
|
+
|
|
3
|
+
use std::sync::{Arc, Mutex};
|
|
4
|
+
|
|
5
|
+
use scribe_client::{AuthClient, PkceChallenge, ScribeClient, TokenSet};
|
|
6
|
+
use time::OffsetDateTime;
|
|
7
|
+
use tokio::net::TcpListener;
|
|
8
|
+
use tokio_tungstenite::tungstenite::handshake::server::{Request, Response};
|
|
9
|
+
use url::Url;
|
|
10
|
+
use wiremock::{
|
|
11
|
+
matchers::{header, method, path},
|
|
12
|
+
Mock, MockServer, ResponseTemplate,
|
|
13
|
+
};
|
|
14
|
+
|
|
15
|
+
fn tokens(expires_in: time::Duration) -> TokenSet {
|
|
16
|
+
TokenSet {
|
|
17
|
+
access_token: "at-valid".into(),
|
|
18
|
+
refresh_token: Some("rt-valid".into()),
|
|
19
|
+
expires_at: Some(OffsetDateTime::now_utc() + expires_in),
|
|
20
|
+
}
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
fn client(base_url: &str, tokens: TokenSet) -> ScribeClient {
|
|
24
|
+
ScribeClient::new(
|
|
25
|
+
reqwest::Client::new(),
|
|
26
|
+
Url::parse(base_url).unwrap(),
|
|
27
|
+
"test-client-id",
|
|
28
|
+
tokens,
|
|
29
|
+
)
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
async fn mount_languages(server: &MockServer) {
|
|
33
|
+
Mock::given(method("GET"))
|
|
34
|
+
.and(path("/api/settings/languages"))
|
|
35
|
+
.respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
|
|
36
|
+
"languages": [["Englisch", "en"]]
|
|
37
|
+
})))
|
|
38
|
+
.mount(server)
|
|
39
|
+
.await;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
#[tokio::test]
|
|
43
|
+
async fn api_requests_carry_the_locale_as_accept_language() {
|
|
44
|
+
let server = MockServer::start().await;
|
|
45
|
+
mount_languages(&server).await;
|
|
46
|
+
let client = client(&server.uri(), tokens(time::Duration::hours(1))).with_locale("de");
|
|
47
|
+
|
|
48
|
+
client.languages().await.unwrap();
|
|
49
|
+
|
|
50
|
+
let requests = server.received_requests().await.unwrap();
|
|
51
|
+
assert_eq!(requests.len(), 1);
|
|
52
|
+
assert_eq!(requests[0].headers.get("accept-language").unwrap(), "de");
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
#[tokio::test]
|
|
56
|
+
async fn without_a_locale_no_accept_language_is_sent() {
|
|
57
|
+
let server = MockServer::start().await;
|
|
58
|
+
mount_languages(&server).await;
|
|
59
|
+
let client = client(&server.uri(), tokens(time::Duration::hours(1)));
|
|
60
|
+
|
|
61
|
+
client.languages().await.unwrap();
|
|
62
|
+
|
|
63
|
+
let requests = server.received_requests().await.unwrap();
|
|
64
|
+
assert!(requests[0].headers.get("accept-language").is_none());
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
/// A token refresh's errors are shown to the user too ("Your session has
|
|
68
|
+
/// expired"), so the refresh is asked for in the same language.
|
|
69
|
+
#[tokio::test]
|
|
70
|
+
async fn the_token_refresh_a_request_needs_carries_the_locale_too() {
|
|
71
|
+
let server = MockServer::start().await;
|
|
72
|
+
Mock::given(method("POST"))
|
|
73
|
+
.and(path("/oauth/token"))
|
|
74
|
+
.and(header("accept-language", "fr"))
|
|
75
|
+
.respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
|
|
76
|
+
"access_token": "at-new",
|
|
77
|
+
"refresh_token": "rt-new",
|
|
78
|
+
"expires_in": 3600
|
|
79
|
+
})))
|
|
80
|
+
.expect(1)
|
|
81
|
+
.mount(&server)
|
|
82
|
+
.await;
|
|
83
|
+
mount_languages(&server).await;
|
|
84
|
+
let client = client(&server.uri(), tokens(time::Duration::seconds(-1))).with_locale("fr");
|
|
85
|
+
|
|
86
|
+
client.languages().await.unwrap();
|
|
87
|
+
|
|
88
|
+
assert_eq!(client.current_tokens().await.access_token, "at-new");
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
#[tokio::test]
|
|
92
|
+
async fn auth_requests_carry_the_locale() {
|
|
93
|
+
let server = MockServer::start().await;
|
|
94
|
+
Mock::given(method("POST"))
|
|
95
|
+
.and(path("/oauth/revoke"))
|
|
96
|
+
.and(header("accept-language", "ja"))
|
|
97
|
+
.respond_with(ResponseTemplate::new(200))
|
|
98
|
+
.expect(1)
|
|
99
|
+
.mount(&server)
|
|
100
|
+
.await;
|
|
101
|
+
let auth = AuthClient::new(
|
|
102
|
+
reqwest::Client::new(),
|
|
103
|
+
Url::parse(&server.uri()).unwrap(),
|
|
104
|
+
"test-client-id",
|
|
105
|
+
)
|
|
106
|
+
.with_locale("ja");
|
|
107
|
+
|
|
108
|
+
auth.revoke("rt-1").await.unwrap();
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
#[test]
|
|
112
|
+
fn the_sign_in_page_is_asked_for_in_the_locale() {
|
|
113
|
+
let auth = AuthClient::new(
|
|
114
|
+
reqwest::Client::new(),
|
|
115
|
+
Url::parse("https://scribe.example/").unwrap(),
|
|
116
|
+
"test-client-id",
|
|
117
|
+
);
|
|
118
|
+
let pkce = PkceChallenge::generate();
|
|
119
|
+
|
|
120
|
+
let plain = auth.authorization_url("myapp://callback", &pkce);
|
|
121
|
+
assert!(!plain.query_pairs().any(|(key, _)| key == "locale"));
|
|
122
|
+
|
|
123
|
+
let url = auth
|
|
124
|
+
.with_locale("pt-BR")
|
|
125
|
+
.authorization_url("myapp://callback", &pkce);
|
|
126
|
+
let locale = url
|
|
127
|
+
.query_pairs()
|
|
128
|
+
.find(|(key, _)| key == "locale")
|
|
129
|
+
.unwrap()
|
|
130
|
+
.1;
|
|
131
|
+
assert_eq!(locale, "pt-BR");
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
/// Accepts one WebSocket connection and reports the request URI it was made
|
|
135
|
+
/// to, then drops it: the URI is all these tests need.
|
|
136
|
+
async fn socket_uri_for(client: impl FnOnce(Url) -> ScribeClient) -> String {
|
|
137
|
+
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
|
|
138
|
+
let addr = listener.local_addr().unwrap();
|
|
139
|
+
let seen = Arc::new(Mutex::new(String::new()));
|
|
140
|
+
let record = Arc::clone(&seen);
|
|
141
|
+
let server = tokio::spawn(async move {
|
|
142
|
+
let (stream, _) = listener.accept().await.unwrap();
|
|
143
|
+
// Its error type is tungstenite's, an HTTP response, not ours to shrink.
|
|
144
|
+
#[allow(clippy::result_large_err)]
|
|
145
|
+
let callback = move |request: &Request, response: Response| {
|
|
146
|
+
*record.lock().unwrap() = request.uri().to_string();
|
|
147
|
+
Ok(response)
|
|
148
|
+
};
|
|
149
|
+
let _ = tokio_tungstenite::accept_hdr_async(stream, callback).await;
|
|
150
|
+
});
|
|
151
|
+
let client = client(Url::parse(&format!("http://{addr}")).unwrap());
|
|
152
|
+
// The server never answers the join, so this fails; the URI was still seen.
|
|
153
|
+
let _ = tokio::time::timeout(
|
|
154
|
+
std::time::Duration::from_secs(2),
|
|
155
|
+
client.open_document_channel("doc-1"),
|
|
156
|
+
)
|
|
157
|
+
.await;
|
|
158
|
+
server.await.unwrap();
|
|
159
|
+
let uri = seen.lock().unwrap().clone();
|
|
160
|
+
uri
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
#[tokio::test]
|
|
164
|
+
async fn the_socket_is_opened_with_the_locale() {
|
|
165
|
+
let uri = socket_uri_for(|base| {
|
|
166
|
+
client(base.as_str(), tokens(time::Duration::hours(1))).with_locale("sv")
|
|
167
|
+
})
|
|
168
|
+
.await;
|
|
169
|
+
let url = Url::parse(&format!("ws://localhost{uri}")).unwrap();
|
|
170
|
+
let pairs: std::collections::HashMap<_, _> = url.query_pairs().collect();
|
|
171
|
+
assert_eq!(pairs.get("locale").unwrap(), "sv");
|
|
172
|
+
assert_eq!(pairs.get("token").unwrap(), "at-valid");
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
#[tokio::test]
|
|
176
|
+
async fn without_a_locale_the_socket_names_none() {
|
|
177
|
+
let uri = socket_uri_for(|base| client(base.as_str(), tokens(time::Duration::hours(1)))).await;
|
|
178
|
+
assert!(!uri.contains("locale="), "{uri}");
|
|
179
|
+
}
|
|
@@ -277,3 +277,67 @@ async fn update_default_settings_sends_voices_as_a_json_string() {
|
|
|
277
277
|
};
|
|
278
278
|
client.update_default_settings(&update).await.unwrap();
|
|
279
279
|
}
|
|
280
|
+
|
|
281
|
+
#[tokio::test]
|
|
282
|
+
async fn voice_sample_downloads_the_mp3_without_a_token() {
|
|
283
|
+
let server = MockServer::start().await;
|
|
284
|
+
Mock::given(method("GET"))
|
|
285
|
+
.and(path("/sounds/tts-samples/en-US-JennyNeural.mp3"))
|
|
286
|
+
.respond_with(ResponseTemplate::new(200).set_body_bytes(b"ID3mp3".to_vec()))
|
|
287
|
+
.mount(&server)
|
|
288
|
+
.await;
|
|
289
|
+
let client = client_for(&server, valid_tokens());
|
|
290
|
+
let data = client.voice_sample("en-US-JennyNeural").await.unwrap();
|
|
291
|
+
assert_eq!(data, b"ID3mp3");
|
|
292
|
+
let requests = server.received_requests().await.unwrap();
|
|
293
|
+
assert!(requests[0].headers.get("authorization").is_none());
|
|
294
|
+
}
|
|
295
|
+
|
|
296
|
+
#[tokio::test]
|
|
297
|
+
async fn voice_sample_maps_a_missing_sample_to_not_found() {
|
|
298
|
+
let server = MockServer::start().await;
|
|
299
|
+
Mock::given(method("GET"))
|
|
300
|
+
.respond_with(ResponseTemplate::new(404).set_body_string("<html>Not Found</html>"))
|
|
301
|
+
.mount(&server)
|
|
302
|
+
.await;
|
|
303
|
+
let client = client_for(&server, valid_tokens());
|
|
304
|
+
let err = client.voice_sample("xx-XX-NobodyNeural").await.unwrap_err();
|
|
305
|
+
assert!(matches!(err, ScribeError::NotFound { .. }), "{err:?}");
|
|
306
|
+
}
|
|
307
|
+
|
|
308
|
+
#[tokio::test]
|
|
309
|
+
async fn voice_sample_url_names_the_file_and_refuses_other_paths() {
|
|
310
|
+
let server = MockServer::start().await;
|
|
311
|
+
let client = client_for(&server, valid_tokens());
|
|
312
|
+
assert_eq!(
|
|
313
|
+
client.voice_sample_url("en-US-JennyNeural").unwrap(),
|
|
314
|
+
format!("{}/sounds/tts-samples/en-US-JennyNeural.mp3", server.uri())
|
|
315
|
+
);
|
|
316
|
+
for bad in ["", "../secret", "a/b", "a.mp3", "a?b"] {
|
|
317
|
+
assert!(
|
|
318
|
+
matches!(
|
|
319
|
+
client.voice_sample_url(bad),
|
|
320
|
+
Err(ScribeError::NotFound { .. })
|
|
321
|
+
),
|
|
322
|
+
"{bad}"
|
|
323
|
+
);
|
|
324
|
+
assert!(client.voice_sample(bad).await.is_err(), "{bad}");
|
|
325
|
+
}
|
|
326
|
+
assert!(server.received_requests().await.unwrap().is_empty());
|
|
327
|
+
}
|
|
328
|
+
|
|
329
|
+
#[test]
|
|
330
|
+
fn voices_and_dialects_objects_go_out_as_json_strings() {
|
|
331
|
+
let update = SettingsUpdate {
|
|
332
|
+
voices: Some(serde_json::json!({"en-US": "en-US-JennyNeural"})),
|
|
333
|
+
dialects: Some(serde_json::Value::String(r#"{"en":"en-US"}"#.into())),
|
|
334
|
+
..Default::default()
|
|
335
|
+
};
|
|
336
|
+
let body = serde_json::to_value(&update).unwrap();
|
|
337
|
+
assert_eq!(body["voices"], r#"{"en-US":"en-US-JennyNeural"}"#);
|
|
338
|
+
assert_eq!(body["dialects"], r#"{"en":"en-US"}"#);
|
|
339
|
+
assert!(serde_json::to_value(SettingsUpdate::default())
|
|
340
|
+
.unwrap()
|
|
341
|
+
.get("voices")
|
|
342
|
+
.is_none());
|
|
343
|
+
}
|
|
@@ -95,6 +95,18 @@ client.update_settings(document_id, {"large_print": True})
|
|
|
95
95
|
|
|
96
96
|
`update_settings` takes a plain dict; only the keys you pass are changed server-side.
|
|
97
97
|
|
|
98
|
+
## Voices and their samples
|
|
99
|
+
|
|
100
|
+
`voices()` lists the text-to-speech voices by dialect, each as a `(name, short_name, has_sample)` triple. A voice whose `has_sample` is true has a short MP3 the user can listen to before choosing it, as the Scribe app lets them. `voice_sample_url(short_name)` gives its URL, which needs no token, so you can hand it straight to a media player to stream. `voice_sample(short_name)` downloads the MP3 bytes instead. Both raise `NotFoundError` when there's no sample.
|
|
101
|
+
|
|
102
|
+
```python
|
|
103
|
+
voices = client.voices()
|
|
104
|
+
name, short_name, has_sample = voices["en-US"][0]
|
|
105
|
+
if has_sample:
|
|
106
|
+
play(client.voice_sample_url(short_name)) # or: data = client.voice_sample(short_name)
|
|
107
|
+
client.update_settings(document_id, {"voices": {"en-US": short_name}})
|
|
108
|
+
```
|
|
109
|
+
|
|
98
110
|
## Converting to another format
|
|
99
111
|
|
|
100
112
|
Creating a document starts only the `html_stream` conversion. Converting to any other format — `pdf`, `epub`, `daisy`, `docx`, `brf`, `mp3`, `offline_html`, `mobi` — happens over a **real-time channel**, not a REST call, so the server can guarantee it's subscribed to progress on whatever it just started converting.
|
|
@@ -19,13 +19,18 @@ pub(crate) struct PyAuthClient {
|
|
|
19
19
|
|
|
20
20
|
#[pymethods]
|
|
21
21
|
impl PyAuthClient {
|
|
22
|
+
/// `locale` is a language tag such as `de` or `pt-BR`. The sign-in page
|
|
23
|
+
/// and the server's messages are then in it.
|
|
22
24
|
#[new]
|
|
23
|
-
|
|
25
|
+
#[pyo3(signature = (base_url, client_id, locale=None))]
|
|
26
|
+
fn new(base_url: &str, client_id: &str, locale: Option<&str>) -> PyResult<Self> {
|
|
24
27
|
let base_url = parse_url(base_url)?;
|
|
25
28
|
let http = reqwest::Client::new();
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
+
let mut inner = AuthClient::new(http, base_url, client_id.to_string());
|
|
30
|
+
if let Some(locale) = locale {
|
|
31
|
+
inner = inner.with_locale(locale);
|
|
32
|
+
}
|
|
33
|
+
Ok(PyAuthClient { inner })
|
|
29
34
|
}
|
|
30
35
|
|
|
31
36
|
fn authorization_url(&self, redirect_uri: &str, pkce: &PyPkceChallenge) -> String {
|
|
@@ -26,13 +26,24 @@ pub(crate) struct PyScribeClient {
|
|
|
26
26
|
|
|
27
27
|
#[pymethods]
|
|
28
28
|
impl PyScribeClient {
|
|
29
|
+
/// `locale` is a language tag such as `de` or `pt-BR`, which the server
|
|
30
|
+
/// then writes its messages and image descriptions in. Without one, it
|
|
31
|
+
/// uses the account's language, or English.
|
|
29
32
|
#[new]
|
|
30
|
-
|
|
33
|
+
#[pyo3(signature = (base_url, client_id, tokens, locale=None))]
|
|
34
|
+
fn new(
|
|
35
|
+
base_url: &str,
|
|
36
|
+
client_id: &str,
|
|
37
|
+
tokens: PyTokenSet,
|
|
38
|
+
locale: Option<&str>,
|
|
39
|
+
) -> PyResult<Self> {
|
|
31
40
|
let base_url = parse_url(base_url)?;
|
|
32
41
|
let http = reqwest::Client::new();
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
42
|
+
let mut inner = ScribeClient::new(http, base_url, client_id.to_string(), tokens.inner);
|
|
43
|
+
if let Some(locale) = locale {
|
|
44
|
+
inner = inner.with_locale(locale);
|
|
45
|
+
}
|
|
46
|
+
Ok(PyScribeClient { inner })
|
|
36
47
|
}
|
|
37
48
|
|
|
38
49
|
/// Creates a document by uploading file bytes directly. Returns the new
|
|
@@ -208,4 +219,23 @@ impl PyScribeClient {
|
|
|
208
219
|
})
|
|
209
220
|
.map_err(to_py_err)
|
|
210
221
|
}
|
|
222
|
+
|
|
223
|
+
/// Where a voice's sample MP3 can be played from, without a token, so a
|
|
224
|
+
/// media player can stream it. Only voices whose `has_sample` is true
|
|
225
|
+
/// have one. Raises `NotFoundError` for a name that can't be a voice's.
|
|
226
|
+
fn voice_sample_url(&self, short_name: &str) -> PyResult<String> {
|
|
227
|
+
self.inner.voice_sample_url(short_name).map_err(to_py_err)
|
|
228
|
+
}
|
|
229
|
+
|
|
230
|
+
/// A voice's sample, as MP3 bytes. Raises `NotFoundError` if it has none.
|
|
231
|
+
fn voice_sample<'py>(
|
|
232
|
+
&self,
|
|
233
|
+
py: Python<'py>,
|
|
234
|
+
short_name: &str,
|
|
235
|
+
) -> PyResult<Bound<'py, PyBytes>> {
|
|
236
|
+
let data = py
|
|
237
|
+
.detach(|| runtime().block_on(self.inner.voice_sample(short_name)))
|
|
238
|
+
.map_err(to_py_err)?;
|
|
239
|
+
Ok(PyBytes::new(py, &data))
|
|
240
|
+
}
|
|
211
241
|
}
|
|
@@ -330,3 +330,25 @@ def test_create_document_from_file_omits_an_absent_password(mock_server):
|
|
|
330
330
|
client.create_document_from_file("plain.pdf", b"%PDF")
|
|
331
331
|
[request] = mock_server.recorded_requests
|
|
332
332
|
assert b"document[password]" not in request["body"]
|
|
333
|
+
|
|
334
|
+
|
|
335
|
+
def test_a_locale_is_sent_as_accept_language(mock_server):
|
|
336
|
+
mock_server.add_json_route(
|
|
337
|
+
"POST", "/api/documents", 200, {"document_id": "doc-3"}
|
|
338
|
+
)
|
|
339
|
+
client = ScribeClient(
|
|
340
|
+
mock_server.base_url, "test-client-id", valid_tokens(), locale="de"
|
|
341
|
+
)
|
|
342
|
+
client.create_document_from_url("https://example.com/report.pdf")
|
|
343
|
+
[request] = mock_server.recorded_requests
|
|
344
|
+
assert request["headers"]["accept-language"] == "de"
|
|
345
|
+
|
|
346
|
+
|
|
347
|
+
def test_without_a_locale_no_accept_language_is_sent(mock_server):
|
|
348
|
+
mock_server.add_json_route(
|
|
349
|
+
"POST", "/api/documents", 200, {"document_id": "doc-4"}
|
|
350
|
+
)
|
|
351
|
+
client = ScribeClient(mock_server.base_url, "test-client-id", valid_tokens())
|
|
352
|
+
client.create_document_from_url("https://example.com/report.pdf")
|
|
353
|
+
[request] = mock_server.recorded_requests
|
|
354
|
+
assert "accept-language" not in request["headers"]
|
|
@@ -133,3 +133,40 @@ def test_voices_returns_map_of_lists(mock_server):
|
|
|
133
133
|
client = ScribeClient(mock_server.base_url, "test-client-id", valid_tokens())
|
|
134
134
|
voices = client.voices()
|
|
135
135
|
assert voices == {"en-US": [("Jenny (Female)", "en-US-JennyNeural", True)]}
|
|
136
|
+
|
|
137
|
+
|
|
138
|
+
def test_voice_sample_downloads_the_mp3_without_a_token(mock_server):
|
|
139
|
+
mock_server.add_bytes_route(
|
|
140
|
+
"GET", "/sounds/tts-samples/en-US-JennyNeural.mp3", 200, b"ID3mp3", "audio/mpeg"
|
|
141
|
+
)
|
|
142
|
+
client = ScribeClient(mock_server.base_url, "test-client-id", valid_tokens())
|
|
143
|
+
assert client.voice_sample("en-US-JennyNeural") == b"ID3mp3"
|
|
144
|
+
headers = {k.lower() for k in mock_server.recorded_requests[0]["headers"]}
|
|
145
|
+
assert "authorization" not in headers
|
|
146
|
+
|
|
147
|
+
|
|
148
|
+
def test_voice_sample_raises_not_found_without_a_sample(mock_server):
|
|
149
|
+
client = ScribeClient(mock_server.base_url, "test-client-id", valid_tokens())
|
|
150
|
+
with pytest.raises(NotFoundError):
|
|
151
|
+
client.voice_sample("xx-XX-NobodyNeural")
|
|
152
|
+
|
|
153
|
+
|
|
154
|
+
def test_voice_sample_url_names_the_file_and_refuses_other_paths(mock_server):
|
|
155
|
+
client = ScribeClient(mock_server.base_url, "test-client-id", valid_tokens())
|
|
156
|
+
assert (
|
|
157
|
+
client.voice_sample_url("en-US-JennyNeural")
|
|
158
|
+
== f"{mock_server.base_url}/sounds/tts-samples/en-US-JennyNeural.mp3"
|
|
159
|
+
)
|
|
160
|
+
for bad in ["", "../secret", "a/b"]:
|
|
161
|
+
with pytest.raises(NotFoundError):
|
|
162
|
+
client.voice_sample_url(bad)
|
|
163
|
+
|
|
164
|
+
|
|
165
|
+
def test_update_settings_sends_a_voices_dict_as_the_json_string_the_server_takes(mock_server):
|
|
166
|
+
import json
|
|
167
|
+
|
|
168
|
+
mock_server.add_json_route("PATCH", "/api/documents/doc-1/settings", 200, settings_body())
|
|
169
|
+
client = ScribeClient(mock_server.base_url, "test-client-id", valid_tokens())
|
|
170
|
+
client.update_settings("doc-1", {"voices": {"en-US": "en-US-JennyNeural"}})
|
|
171
|
+
body = json.loads(mock_server.recorded_requests[0]["body"])
|
|
172
|
+
assert json.loads(body["settings"]["voices"]) == {"en-US": "en-US-JennyNeural"}
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
{scribe_client-0.2.0 → scribe_client-0.3.1}/crates/scribe-client-py/tests/test_pkce_and_tokens.py
RENAMED
|
File without changes
|
|
File without changes
|