scribe-client 0.3.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.3.0 → scribe_client-0.3.1}/Cargo.lock +3 -3
- {scribe_client-0.3.0 → scribe_client-0.3.1}/Cargo.toml +1 -1
- {scribe_client-0.3.0 → scribe_client-0.3.1}/PKG-INFO +1 -1
- {scribe_client-0.3.0 → scribe_client-0.3.1}/crates/scribe-client/README.md +1 -1
- {scribe_client-0.3.0 → scribe_client-0.3.1}/crates/scribe-client/src/auth.rs +41 -2
- {scribe_client-0.3.0 → scribe_client-0.3.1}/crates/scribe-client/src/channel.rs +26 -15
- {scribe_client-0.3.0 → scribe_client-0.3.1}/crates/scribe-client/src/client.rs +32 -5
- {scribe_client-0.3.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.3.0 → scribe_client-0.3.1}/crates/scribe-client-py/src/auth.rs +9 -4
- {scribe_client-0.3.0 → scribe_client-0.3.1}/crates/scribe-client-py/src/client.rs +15 -4
- {scribe_client-0.3.0 → scribe_client-0.3.1}/crates/scribe-client-py/tests/test_client.py +22 -0
- {scribe_client-0.3.0 → scribe_client-0.3.1}/crates/scribe-client-py/uv.lock +1 -1
- {scribe_client-0.3.0 → scribe_client-0.3.1}/README.md +0 -0
- {scribe_client-0.3.0 → scribe_client-0.3.1}/crates/scribe-client/Cargo.toml +0 -0
- {scribe_client-0.3.0 → scribe_client-0.3.1}/crates/scribe-client/examples/pkce_flow.rs +0 -0
- {scribe_client-0.3.0 → scribe_client-0.3.1}/crates/scribe-client/src/error.rs +0 -0
- {scribe_client-0.3.0 → scribe_client-0.3.1}/crates/scribe-client/src/lib.rs +0 -0
- {scribe_client-0.3.0 → scribe_client-0.3.1}/crates/scribe-client/src/model.rs +0 -0
- {scribe_client-0.3.0 → scribe_client-0.3.1}/crates/scribe-client/tests/auth_test.rs +0 -0
- {scribe_client-0.3.0 → scribe_client-0.3.1}/crates/scribe-client/tests/client_test.rs +0 -0
- {scribe_client-0.3.0 → scribe_client-0.3.1}/crates/scribe-client/tests/settings_test.rs +0 -0
- {scribe_client-0.3.0 → scribe_client-0.3.1}/crates/scribe-client-py/Cargo.toml +0 -0
- {scribe_client-0.3.0 → scribe_client-0.3.1}/crates/scribe-client-py/README.md +0 -0
- {scribe_client-0.3.0 → scribe_client-0.3.1}/crates/scribe-client-py/build.rs +0 -0
- {scribe_client-0.3.0 → scribe_client-0.3.1}/crates/scribe-client-py/examples/pkce_flow.py +0 -0
- {scribe_client-0.3.0 → scribe_client-0.3.1}/crates/scribe-client-py/src/channel.rs +0 -0
- {scribe_client-0.3.0 → scribe_client-0.3.1}/crates/scribe-client-py/src/error.rs +0 -0
- {scribe_client-0.3.0 → scribe_client-0.3.1}/crates/scribe-client-py/src/lib.rs +0 -0
- {scribe_client-0.3.0 → scribe_client-0.3.1}/crates/scribe-client-py/src/model.rs +0 -0
- {scribe_client-0.3.0 → scribe_client-0.3.1}/crates/scribe-client-py/tests/conftest.py +0 -0
- {scribe_client-0.3.0 → scribe_client-0.3.1}/crates/scribe-client-py/tests/test_auth.py +0 -0
- {scribe_client-0.3.0 → scribe_client-0.3.1}/crates/scribe-client-py/tests/test_channel.py +0 -0
- {scribe_client-0.3.0 → scribe_client-0.3.1}/crates/scribe-client-py/tests/test_pkce_and_tokens.py +0 -0
- {scribe_client-0.3.0 → scribe_client-0.3.1}/crates/scribe-client-py/tests/test_settings.py +0 -0
- {scribe_client-0.3.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.3.
|
|
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.3.
|
|
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.3.
|
|
1717
|
+
version = "0.3.1"
|
|
1718
1718
|
dependencies = [
|
|
1719
1719
|
"pyo3",
|
|
1720
1720
|
"pyo3-build-config",
|
|
@@ -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
|
|
|
@@ -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() {
|
|
@@ -773,16 +796,20 @@ impl ScribeClient {
|
|
|
773
796
|
F: Fn(&str) -> reqwest::RequestBuilder,
|
|
774
797
|
{
|
|
775
798
|
let token = self.access_token().await?;
|
|
776
|
-
let response = build(&token).send().await?;
|
|
799
|
+
let response = self.localized(build(&token)).send().await?;
|
|
777
800
|
let response = if response.status() == reqwest::StatusCode::UNAUTHORIZED {
|
|
778
801
|
let token = self.force_refresh().await?;
|
|
779
|
-
build(&token).send().await?
|
|
802
|
+
self.localized(build(&token)).send().await?
|
|
780
803
|
} else {
|
|
781
804
|
response
|
|
782
805
|
};
|
|
783
806
|
response.error_for_status_or_json_error().await
|
|
784
807
|
}
|
|
785
808
|
|
|
809
|
+
fn localized(&self, request: reqwest::RequestBuilder) -> reqwest::RequestBuilder {
|
|
810
|
+
accept_language(request, self.locale.as_deref())
|
|
811
|
+
}
|
|
812
|
+
|
|
786
813
|
/// Like [`with_auth_retry_raw`] but deserializes the response body as JSON.
|
|
787
814
|
async fn with_auth_retry<T, F>(&self, build: F) -> Result<T, ScribeError>
|
|
788
815
|
where
|
|
@@ -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
|
+
}
|
|
@@ -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
|
|
@@ -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"]
|
|
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
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
{scribe_client-0.3.0 → scribe_client-0.3.1}/crates/scribe-client-py/tests/test_pkce_and_tokens.py
RENAMED
|
File without changes
|
|
File without changes
|
|
File without changes
|