scribe-client 0.1.0__tar.gz → 0.2.0__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.
Files changed (36) hide show
  1. {scribe_client-0.1.0 → scribe_client-0.2.0}/Cargo.lock +3 -3
  2. {scribe_client-0.1.0 → scribe_client-0.2.0}/Cargo.toml +1 -1
  3. {scribe_client-0.1.0 → scribe_client-0.2.0}/PKG-INFO +32 -7
  4. {scribe_client-0.1.0/crates/scribe-client-py → scribe_client-0.2.0}/README.md +31 -6
  5. {scribe_client-0.1.0 → scribe_client-0.2.0}/crates/scribe-client/Cargo.toml +2 -2
  6. {scribe_client-0.1.0 → scribe_client-0.2.0}/crates/scribe-client/README.md +1 -1
  7. {scribe_client-0.1.0 → scribe_client-0.2.0}/crates/scribe-client/src/channel.rs +70 -20
  8. {scribe_client-0.1.0 → scribe_client-0.2.0}/crates/scribe-client/src/client.rs +53 -5
  9. {scribe_client-0.1.0 → scribe_client-0.2.0}/crates/scribe-client/src/lib.rs +4 -3
  10. {scribe_client-0.1.0 → scribe_client-0.2.0}/crates/scribe-client/src/model.rs +46 -0
  11. {scribe_client-0.1.0 → scribe_client-0.2.0}/crates/scribe-client/tests/channel_test.rs +119 -1
  12. {scribe_client-0.1.0 → scribe_client-0.2.0}/crates/scribe-client/tests/client_test.rs +153 -0
  13. {scribe_client-0.1.0 → scribe_client-0.2.0/crates/scribe-client-py}/README.md +31 -6
  14. scribe_client-0.2.0/crates/scribe-client-py/examples/pkce_flow.py +245 -0
  15. {scribe_client-0.1.0 → scribe_client-0.2.0}/crates/scribe-client-py/src/channel.rs +8 -3
  16. {scribe_client-0.1.0 → scribe_client-0.2.0}/crates/scribe-client-py/tests/test_channel.py +53 -0
  17. {scribe_client-0.1.0 → scribe_client-0.2.0}/crates/scribe-client-py/uv.lock +1 -1
  18. scribe_client-0.1.0/crates/scribe-client-py/examples/pkce_flow.py +0 -127
  19. {scribe_client-0.1.0 → scribe_client-0.2.0}/crates/scribe-client/examples/pkce_flow.rs +0 -0
  20. {scribe_client-0.1.0 → scribe_client-0.2.0}/crates/scribe-client/src/auth.rs +0 -0
  21. {scribe_client-0.1.0 → scribe_client-0.2.0}/crates/scribe-client/src/error.rs +0 -0
  22. {scribe_client-0.1.0 → scribe_client-0.2.0}/crates/scribe-client/tests/auth_test.rs +0 -0
  23. {scribe_client-0.1.0 → scribe_client-0.2.0}/crates/scribe-client/tests/settings_test.rs +0 -0
  24. {scribe_client-0.1.0 → scribe_client-0.2.0}/crates/scribe-client-py/Cargo.toml +0 -0
  25. {scribe_client-0.1.0 → scribe_client-0.2.0}/crates/scribe-client-py/build.rs +0 -0
  26. {scribe_client-0.1.0 → scribe_client-0.2.0}/crates/scribe-client-py/src/auth.rs +0 -0
  27. {scribe_client-0.1.0 → scribe_client-0.2.0}/crates/scribe-client-py/src/client.rs +0 -0
  28. {scribe_client-0.1.0 → scribe_client-0.2.0}/crates/scribe-client-py/src/error.rs +0 -0
  29. {scribe_client-0.1.0 → scribe_client-0.2.0}/crates/scribe-client-py/src/lib.rs +0 -0
  30. {scribe_client-0.1.0 → scribe_client-0.2.0}/crates/scribe-client-py/src/model.rs +0 -0
  31. {scribe_client-0.1.0 → scribe_client-0.2.0}/crates/scribe-client-py/tests/conftest.py +0 -0
  32. {scribe_client-0.1.0 → scribe_client-0.2.0}/crates/scribe-client-py/tests/test_auth.py +0 -0
  33. {scribe_client-0.1.0 → scribe_client-0.2.0}/crates/scribe-client-py/tests/test_client.py +0 -0
  34. {scribe_client-0.1.0 → scribe_client-0.2.0}/crates/scribe-client-py/tests/test_pkce_and_tokens.py +0 -0
  35. {scribe_client-0.1.0 → scribe_client-0.2.0}/crates/scribe-client-py/tests/test_settings.py +0 -0
  36. {scribe_client-0.1.0 → scribe_client-0.2.0}/pyproject.toml +0 -0
@@ -1678,7 +1678,7 @@ dependencies = [
1678
1678
 
1679
1679
  [[package]]
1680
1680
  name = "scribe-client"
1681
- version = "0.1.0"
1681
+ version = "0.2.0"
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.1.0"
1701
+ version = "0.2.0"
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.1.0"
1717
+ version = "0.2.0"
1718
1718
  dependencies = [
1719
1719
  "pyo3",
1720
1720
  "pyo3-build-config",
@@ -3,7 +3,7 @@ resolver = "2"
3
3
  members = ["crates/scribe-client", "crates/scribe-client-py"]
4
4
 
5
5
  [workspace.package]
6
- version = "0.1.0"
6
+ version = "0.2.0"
7
7
  edition = "2021"
8
8
  license = "MIT OR Apache-2.0"
9
9
  repository = "https://github.com/PneumaSolutions/scribe-api-client"
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: scribe-client
3
- Version: 0.1.0
3
+ Version: 0.2.0
4
4
  Classifier: Development Status :: 4 - Beta
5
5
  Classifier: Intended Audience :: Developers
6
6
  Classifier: License :: OSI Approved :: MIT License
@@ -67,7 +67,19 @@ client = ScribeClient(base_url, client_id, tokens)
67
67
 
68
68
  `tokens.access_token`, `tokens.refresh_token`, and `tokens.expires_at` (Unix seconds, or `None`) are readable if you want to persist them between runs — reconstruct a `TokenSet` later with `TokenSet(access_token, refresh_token, expires_at)`.
69
69
 
70
- See `examples/pkce_flow.py` for a runnable end-to-end version of this, including creating a document and converting it.
70
+ `AuthClient` doesn't open a browser or listen for the redirect; getting the `code` back is up to your application. The server never shows the code on a page — it only ever redirects to `redirect_uri` — so something has to be listening there. For a desktop app or script, register a loopback URI with a fixed port, such as `http://127.0.0.1:8765/callback`, and run a small HTTP server on that address while the user signs in. See the [top-level README](../../README.md#choosing-a-redirect-uri) for other kinds of app.
71
+
72
+ See `examples/pkce_flow.py` for a runnable end-to-end version of this, including creating a document and converting it. Given a loopback `SCRIBE_REDIRECT_URI`, it opens the browser and catches the redirect itself:
73
+
74
+ ```bash
75
+ export SCRIBE_BASE_URL=https://scribeit.io
76
+ export SCRIBE_CLIENT_ID=your-client-id
77
+ export SCRIBE_REDIRECT_URI=http://127.0.0.1:8765/callback # as registered for your app
78
+ export SCRIBE_DOCUMENT_PATH=report.docx
79
+ uv run --project crates/scribe-client-py crates/scribe-client-py/examples/pkce_flow.py
80
+ ```
81
+
82
+ With any other redirect URI, the browser ends up on a page that fails to load after you approve access. That's expected: copy the `code` parameter from the address bar and paste it into the script. A code works only once and expires after a few minutes.
71
83
 
72
84
  ## Documents
73
85
 
@@ -106,12 +118,24 @@ client.update_settings(document_id, {"large_print": True})
106
118
 
107
119
  ## Converting to another format
108
120
 
109
- Creating a document only starts the `html_stream` preview. 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.
121
+ 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.
122
+
123
+ The server runs one conversion of a document at a time, and `start_conversion` raises `ConversionInProgressError` while another is running. That includes the `html_stream` conversion that creating the document started, unless it turned out to be a preview, so a call straight after creating a document will normally raise it. Wait for that conversion's `"conversion_complete"` event, then call `start_conversion` again:
110
124
 
111
125
  ```python
112
126
  channel = client.open_document_channel(document_id)
113
127
  try:
114
- output_id = channel.start_conversion("pdf")
128
+ while True:
129
+ try:
130
+ output_id = channel.start_conversion("pdf")
131
+ break
132
+ except ConversionInProgressError:
133
+ while True:
134
+ event = channel.next_event()
135
+ if event["type"] == "conversion_complete":
136
+ break
137
+ if event["type"] == "error":
138
+ raise RuntimeError(event["reason"])
115
139
 
116
140
  while True:
117
141
  event = channel.next_event()
@@ -127,9 +151,10 @@ finally:
127
151
  channel.close()
128
152
  ```
129
153
 
130
- `start_conversion` is idempotent — calling it again for a format that's already converting or complete just returns that output's existing id without starting a duplicate conversion.
154
+ Calling `start_conversion` for a format that's already complete just returns that output's existing id without converting it again. Calling it for a format that's still converting raises `ConversionInProgressError`, like any other running conversion.
155
+
156
+ `next_event()` blocks until the next event arrives and returns it as a dict tagged by `event["type"]`. It sends heartbeats while it waits, which is what keeps the connection open during a long conversion, so keep calling it rather than doing other long work between calls. The server closes a connection it hasn't heard from for about a minute. The connection can still be lost, for example to a network failure, which raises `ScribeApiError`. The conversion carries on without it: open a new channel on the same document, and don't upload it again.
131
157
 
132
- `next_event()` blocks until the next event arrives and returns it as a dict tagged by `event["type"]`:
133
158
 
134
159
  | `type` | other keys | meaning |
135
160
  | ---------------------- | --------------------------------- | ------------------------------------------- |
@@ -169,7 +194,7 @@ All exceptions are subclasses of `ScribeApiError`:
169
194
  | `NotFoundError` | the document (or channel) doesn't exist |
170
195
  | `ForbiddenError` | the document exists but isn't owned by the current user |
171
196
  | `ConversionNotCompleteError` | `download_output` was called before that format finished converting |
172
- | `ConversionInProgressError` | `start_conversion` was called while a different conversion is already running |
197
+ | `ConversionInProgressError` | `start_conversion` was called while a conversion of the document is running |
173
198
  | `RateLimitedError` | `start_conversion` was called too many times too quickly |
174
199
  | `PasswordRequiredError` | the document is a protected file and no password has been supplied |
175
200
  | `NeedsPurchaseError` | the account doesn't have enough page credits for the requested conversion |
@@ -46,7 +46,19 @@ client = ScribeClient(base_url, client_id, tokens)
46
46
 
47
47
  `tokens.access_token`, `tokens.refresh_token`, and `tokens.expires_at` (Unix seconds, or `None`) are readable if you want to persist them between runs — reconstruct a `TokenSet` later with `TokenSet(access_token, refresh_token, expires_at)`.
48
48
 
49
- See `examples/pkce_flow.py` for a runnable end-to-end version of this, including creating a document and converting it.
49
+ `AuthClient` doesn't open a browser or listen for the redirect; getting the `code` back is up to your application. The server never shows the code on a page — it only ever redirects to `redirect_uri` — so something has to be listening there. For a desktop app or script, register a loopback URI with a fixed port, such as `http://127.0.0.1:8765/callback`, and run a small HTTP server on that address while the user signs in. See the [top-level README](../../README.md#choosing-a-redirect-uri) for other kinds of app.
50
+
51
+ See `examples/pkce_flow.py` for a runnable end-to-end version of this, including creating a document and converting it. Given a loopback `SCRIBE_REDIRECT_URI`, it opens the browser and catches the redirect itself:
52
+
53
+ ```bash
54
+ export SCRIBE_BASE_URL=https://scribeit.io
55
+ export SCRIBE_CLIENT_ID=your-client-id
56
+ export SCRIBE_REDIRECT_URI=http://127.0.0.1:8765/callback # as registered for your app
57
+ export SCRIBE_DOCUMENT_PATH=report.docx
58
+ uv run --project crates/scribe-client-py crates/scribe-client-py/examples/pkce_flow.py
59
+ ```
60
+
61
+ With any other redirect URI, the browser ends up on a page that fails to load after you approve access. That's expected: copy the `code` parameter from the address bar and paste it into the script. A code works only once and expires after a few minutes.
50
62
 
51
63
  ## Documents
52
64
 
@@ -85,12 +97,24 @@ client.update_settings(document_id, {"large_print": True})
85
97
 
86
98
  ## Converting to another format
87
99
 
88
- Creating a document only starts the `html_stream` preview. 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.
100
+ 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.
101
+
102
+ The server runs one conversion of a document at a time, and `start_conversion` raises `ConversionInProgressError` while another is running. That includes the `html_stream` conversion that creating the document started, unless it turned out to be a preview, so a call straight after creating a document will normally raise it. Wait for that conversion's `"conversion_complete"` event, then call `start_conversion` again:
89
103
 
90
104
  ```python
91
105
  channel = client.open_document_channel(document_id)
92
106
  try:
93
- output_id = channel.start_conversion("pdf")
107
+ while True:
108
+ try:
109
+ output_id = channel.start_conversion("pdf")
110
+ break
111
+ except ConversionInProgressError:
112
+ while True:
113
+ event = channel.next_event()
114
+ if event["type"] == "conversion_complete":
115
+ break
116
+ if event["type"] == "error":
117
+ raise RuntimeError(event["reason"])
94
118
 
95
119
  while True:
96
120
  event = channel.next_event()
@@ -106,9 +130,10 @@ finally:
106
130
  channel.close()
107
131
  ```
108
132
 
109
- `start_conversion` is idempotent — calling it again for a format that's already converting or complete just returns that output's existing id without starting a duplicate conversion.
133
+ Calling `start_conversion` for a format that's already complete just returns that output's existing id without converting it again. Calling it for a format that's still converting raises `ConversionInProgressError`, like any other running conversion.
134
+
135
+ `next_event()` blocks until the next event arrives and returns it as a dict tagged by `event["type"]`. It sends heartbeats while it waits, which is what keeps the connection open during a long conversion, so keep calling it rather than doing other long work between calls. The server closes a connection it hasn't heard from for about a minute. The connection can still be lost, for example to a network failure, which raises `ScribeApiError`. The conversion carries on without it: open a new channel on the same document, and don't upload it again.
110
136
 
111
- `next_event()` blocks until the next event arrives and returns it as a dict tagged by `event["type"]`:
112
137
 
113
138
  | `type` | other keys | meaning |
114
139
  | ---------------------- | --------------------------------- | ------------------------------------------- |
@@ -148,7 +173,7 @@ All exceptions are subclasses of `ScribeApiError`:
148
173
  | `NotFoundError` | the document (or channel) doesn't exist |
149
174
  | `ForbiddenError` | the document exists but isn't owned by the current user |
150
175
  | `ConversionNotCompleteError` | `download_output` was called before that format finished converting |
151
- | `ConversionInProgressError` | `start_conversion` was called while a different conversion is already running |
176
+ | `ConversionInProgressError` | `start_conversion` was called while a conversion of the document is running |
152
177
  | `RateLimitedError` | `start_conversion` was called too many times too quickly |
153
178
  | `PasswordRequiredError` | the document is a protected file and no password has been supplied |
154
179
  | `NeedsPurchaseError` | the account doesn't have enough page credits for the requested conversion |
@@ -34,10 +34,10 @@ serde_json = "1.0.150"
34
34
  sha2 = "0.11.0"
35
35
  thiserror = "2.0.18"
36
36
  time = { version = "0.3.53", features = ["serde", "parsing", "formatting"] }
37
- tokio = { version = "1.52.3", features = ["rt", "macros", "sync"] }
37
+ tokio = { version = "1.52.3", features = ["rt", "macros", "sync", "time"] }
38
38
  tokio-tungstenite = "0.29.0"
39
39
  url = "2.5.8"
40
40
 
41
41
  [dev-dependencies]
42
- tokio = { version = "1.52.3", features = ["rt-multi-thread", "macros", "net"] }
42
+ tokio = { version = "1.52.3", features = ["rt-multi-thread", "macros", "net", "test-util"] }
43
43
  wiremock = "0.6.5"
@@ -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.1", default-features = false, features = ["native-tls"] }
45
+ scribe-client = { version = "0.2", default-features = false, features = ["native-tls"] }
46
46
  ```
47
47
 
48
48
  ## License
@@ -1,12 +1,15 @@
1
1
  //! The real-time document channel (`documents:<id>` over `/socket`).
2
2
 
3
- use std::collections::VecDeque;
3
+ use std::{collections::VecDeque, time::Duration};
4
4
 
5
5
  use futures_util::{SinkExt, StreamExt};
6
6
  use serde::{Deserialize, Serialize};
7
7
  use serde_json::Value;
8
- use tokio::net::TcpStream;
9
- use tokio_tungstenite::{tungstenite::Message, MaybeTlsStream, WebSocketStream};
8
+ use tokio::{net::TcpStream, time::Instant};
9
+ use tokio_tungstenite::{
10
+ tungstenite::{error::ProtocolError, Error as WsError, Message},
11
+ MaybeTlsStream, WebSocketStream,
12
+ };
10
13
 
11
14
  use crate::{
12
15
  error::ScribeError,
@@ -18,6 +21,11 @@ type WsStream = WebSocketStream<MaybeTlsStream<TcpStream>>;
18
21
  /// A Phoenix channel wire-protocol frame: `[join_ref, ref, topic, event, payload]`.
19
22
  type RawFrame = (Option<String>, Option<String>, String, String, Value);
20
23
 
24
+ /// How often to send a heartbeat while waiting for a frame. The server closes
25
+ /// a connection it has heard nothing from for about 66 seconds, however much
26
+ /// it's sending; 30 seconds is what Phoenix's own client uses.
27
+ const HEARTBEAT_INTERVAL: Duration = Duration::from_secs(30);
28
+
21
29
  /// An event pushed asynchronously over a [`DocumentChannel`], outside of a
22
30
  /// direct reply to something we sent.
23
31
  #[derive(Debug, Clone, PartialEq, Serialize)]
@@ -67,12 +75,19 @@ struct ErrorReason {
67
75
  /// Progress on formats that were already converting (or complete) when the
68
76
  /// channel was joined arrives as [`ChannelEvent`]s from [`Self::next_event`]
69
77
  /// just like anything started with [`Self::start_conversion`] after joining.
78
+ ///
79
+ /// Heartbeats keep the connection open only while a call on this channel is
80
+ /// waiting, so keep calling [`Self::next_event`] during a conversion. The
81
+ /// connection can still be lost, for example to a network failure or a server
82
+ /// restart. A conversion carries on without it: open a new channel on the same
83
+ /// document, and don't upload it again.
70
84
  pub struct DocumentChannel {
71
85
  ws: WsStream,
72
86
  topic: String,
73
87
  join_ref: String,
74
88
  next_ref: u64,
75
89
  pending: VecDeque<ChannelEvent>,
90
+ next_heartbeat: Instant,
76
91
  }
77
92
 
78
93
  impl DocumentChannel {
@@ -81,7 +96,7 @@ impl DocumentChannel {
81
96
  let join_ref = "1".to_string();
82
97
  send_frame(
83
98
  &mut ws,
84
- &join_ref,
99
+ Some(&join_ref),
85
100
  &join_ref,
86
101
  &topic,
87
102
  "phx_join",
@@ -94,24 +109,28 @@ impl DocumentChannel {
94
109
  join_ref: join_ref.clone(),
95
110
  next_ref: 2,
96
111
  pending: VecDeque::new(),
112
+ next_heartbeat: Instant::now() + HEARTBEAT_INTERVAL,
97
113
  };
98
114
  channel.await_reply(&join_ref).await?;
99
115
  Ok(channel)
100
116
  }
101
117
 
102
118
  /// Starts converting the joined document to `format`, using its current
103
- /// settings. Idempotent: if that format is already converting or
104
- /// complete, the server returns its existing output id instead of
105
- /// starting a new conversion. Returns immediately with the output id;
106
- /// progress arrives via subsequent [`Self::next_event`] calls.
119
+ /// settings. If that format is already complete, the server returns its
120
+ /// existing output id instead of starting a new conversion. Returns
121
+ /// immediately with the output id; progress arrives via subsequent
122
+ /// [`Self::next_event`] calls.
107
123
  ///
108
124
  /// # Errors
109
125
  ///
110
126
  /// Returns [`ScribeError::NotFound`]/[`ScribeError::Forbidden`] if the
111
127
  /// document doesn't exist or isn't owned by the caller,
112
- /// [`ScribeError::ConversionInProgress`] if a different non-preview
113
- /// conversion is already running, [`ScribeError::RateLimited`] if too
114
- /// many conversions were started too quickly,
128
+ /// [`ScribeError::ConversionInProgress`] if any non-preview conversion
129
+ /// of the document is running, including that format and the
130
+ /// `html_stream` that creating the document started (wait for its
131
+ /// [`ChannelEvent::ConversionComplete`], then call this again),
132
+ /// [`ScribeError::RateLimited`] if too many conversions were started too
133
+ /// quickly,
115
134
  /// [`ScribeError::NeedsPurchase`] if the account is out of page
116
135
  /// credits, or [`ScribeError::PasswordRequired`] if the document is a
117
136
  /// protected file and `password` was `None` or wrong.
@@ -134,7 +153,7 @@ impl DocumentChannel {
134
153
  }
135
154
  send_frame(
136
155
  &mut self.ws,
137
- &self.join_ref,
156
+ Some(&self.join_ref),
138
157
  &ref_,
139
158
  &self.topic,
140
159
  "start_conversion",
@@ -169,14 +188,24 @@ impl DocumentChannel {
169
188
  }
170
189
  }
171
190
 
191
+ /// Closes the connection. One that's already closed or lost is fine, since
192
+ /// that's what this is for.
193
+ ///
172
194
  /// # Errors
173
195
  ///
174
- /// Returns [`ScribeError::WebSocket`] if sending the close frame fails.
196
+ /// Returns [`ScribeError::WebSocket`] if closing the connection fails with
197
+ /// it still open.
175
198
  pub async fn close(mut self) -> Result<(), ScribeError> {
176
- self.ws
177
- .close(None)
178
- .await
179
- .map_err(|e| ScribeError::WebSocket(Box::new(e)))
199
+ match self.ws.close(None).await {
200
+ Ok(())
201
+ | Err(
202
+ WsError::ConnectionClosed
203
+ | WsError::AlreadyClosed
204
+ | WsError::Protocol(ProtocolError::SendAfterClosing)
205
+ | WsError::Io(_),
206
+ ) => Ok(()),
207
+ Err(e) => Err(ScribeError::WebSocket(Box::new(e))),
208
+ }
180
209
  }
181
210
 
182
211
  fn take_ref(&mut self) -> String {
@@ -185,9 +214,30 @@ impl DocumentChannel {
185
214
  r
186
215
  }
187
216
 
217
+ async fn send_heartbeat(&mut self) -> Result<(), ScribeError> {
218
+ let ref_ = self.take_ref();
219
+ self.next_heartbeat = Instant::now() + HEARTBEAT_INTERVAL;
220
+ send_frame(
221
+ &mut self.ws,
222
+ None,
223
+ &ref_,
224
+ "phoenix",
225
+ "heartbeat",
226
+ Value::Object(serde_json::Map::new()),
227
+ )
228
+ .await
229
+ }
230
+
188
231
  async fn recv_frame(&mut self) -> Result<RawFrame, ScribeError> {
189
232
  loop {
190
- return match self.ws.next().await {
233
+ if Instant::now() >= self.next_heartbeat {
234
+ self.send_heartbeat().await?;
235
+ }
236
+ let Ok(message) = tokio::time::timeout_at(self.next_heartbeat, self.ws.next()).await
237
+ else {
238
+ continue;
239
+ };
240
+ return match message {
191
241
  Some(Ok(Message::Text(text))) => {
192
242
  Ok(serde_json::from_str::<RawFrame>(text.as_str())?)
193
243
  }
@@ -224,14 +274,14 @@ impl DocumentChannel {
224
274
 
225
275
  async fn send_frame(
226
276
  ws: &mut WsStream,
227
- join_ref: &str,
277
+ join_ref: Option<&str>,
228
278
  ref_: &str,
229
279
  topic: &str,
230
280
  event: &str,
231
281
  payload: Value,
232
282
  ) -> Result<(), ScribeError> {
233
283
  let frame: RawFrame = (
234
- Some(join_ref.to_string()),
284
+ join_ref.map(str::to_string),
235
285
  Some(ref_.to_string()),
236
286
  topic.to_string(),
237
287
  event.to_string(),
@@ -10,11 +10,11 @@ use crate::{
10
10
  channel::DocumentChannel,
11
11
  error::ScribeError,
12
12
  model::{
13
- AccountInfo, BrailleTable, BrailleTablesResponse, CreatedDocument, Dialect,
14
- DialectsResponse, DocumentList, DocumentListResponse, DocumentSummary, Download, Language,
15
- LanguagesResponse, NotificationSettings, OutputFormat, OutputList, OutputListResponse,
16
- Settings, SettingsUpdate, TrashedDocument, TrashedDocumentListResponse, Voice,
17
- VoicesResponse,
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
18
  },
19
19
  };
20
20
 
@@ -169,6 +169,7 @@ impl ScribeClient {
169
169
  Ok(DocumentList {
170
170
  documents: response.documents,
171
171
  pages_remaining: response.pages_remaining,
172
+ suggest_buying_pages: response.suggest_buying_pages,
172
173
  })
173
174
  }
174
175
 
@@ -623,6 +624,53 @@ impl ScribeClient {
623
624
  .await
624
625
  }
625
626
 
627
+ /// The pages the account has left and its active subscription, if any.
628
+ ///
629
+ /// # Errors
630
+ ///
631
+ /// Returns [`ScribeError::Http`]/[`ScribeError::Api`] on request failure.
632
+ pub async fn billing(&self) -> Result<BillingStatus, ScribeError> {
633
+ let mut url = self.base_url.clone();
634
+ url.set_path("/api/billing");
635
+ self.with_auth_retry(|token| self.http.get(url.clone()).bearer_auth(token))
636
+ .await
637
+ }
638
+
639
+ /// Lists the App Store products on sale, in the order to show them.
640
+ ///
641
+ /// # Errors
642
+ ///
643
+ /// Returns [`ScribeError::Http`]/[`ScribeError::Api`] on request failure.
644
+ pub async fn app_store_products(&self) -> Result<Vec<AppStoreProduct>, ScribeError> {
645
+ let mut url = self.base_url.clone();
646
+ url.set_path("/api/app_store/products");
647
+ let response: AppStoreProductsResponse = self
648
+ .with_auth_retry(|token| self.http.get(url.clone()).bearer_auth(token))
649
+ .await?;
650
+ Ok(response.products)
651
+ }
652
+
653
+ /// Credits a completed App Store purchase to the account. `signed_transaction`
654
+ /// is `Transaction.jwsRepresentation` from `StoreKit` 2. Reporting the same
655
+ /// transaction again is harmless, so finish the transaction in `StoreKit`
656
+ /// only once this succeeds. Returns the billing status afterwards.
657
+ ///
658
+ /// # Errors
659
+ ///
660
+ /// Returns [`ScribeError::Api`] with code `other_account` if the purchase
661
+ /// was made while signed in to a different Scribe account, or
662
+ /// `invalid_transaction` if the server couldn't verify it.
663
+ pub async fn submit_app_store_transaction(
664
+ &self,
665
+ signed_transaction: &str,
666
+ ) -> Result<BillingStatus, ScribeError> {
667
+ let mut url = self.base_url.clone();
668
+ url.set_path("/api/app_store/transactions");
669
+ let body = serde_json::json!({ "signed_transaction": signed_transaction });
670
+ self.with_auth_retry(|token| self.http.post(url.clone()).bearer_auth(token).json(&body))
671
+ .await
672
+ }
673
+
626
674
  /// # Errors
627
675
  ///
628
676
  /// Returns [`ScribeError::Http`]/[`ScribeError::Api`] on request failure.
@@ -18,7 +18,8 @@ pub use channel::{ChannelEvent, DocumentChannel};
18
18
  pub use client::{DocumentSource, ScribeClient, DELETE_ACCOUNT_PATH};
19
19
  pub use error::ScribeError;
20
20
  pub use model::{
21
- AccountInfo, BrailleTable, CreatedDocument, Dialect, DocumentList, DocumentSummary, Download,
22
- Language, NotificationSettings, Output, OutputFormat, OutputList, Settings, SettingsUpdate,
23
- Stage, TrashedDocument, Voice,
21
+ AccountInfo, AppStoreProduct, BillingStatus, BillingSubscription, BrailleTable,
22
+ CreatedDocument, Dialect, DocumentList, DocumentSummary, Download, Language,
23
+ NotificationSettings, Output, OutputFormat, OutputList, Settings, SettingsUpdate, Stage,
24
+ TrashedDocument, Voice,
24
25
  };
@@ -156,12 +156,19 @@ pub struct DocumentSummary {
156
156
  pub struct DocumentList {
157
157
  pub documents: Vec<DocumentSummary>,
158
158
  pub pages_remaining: Option<i64>,
159
+ /// Whether to put buying pages in front of the user, such as on the home
160
+ /// screen. The server decides: it is true for an individual account with
161
+ /// only trial pages or few pages left. False from a server that predates
162
+ /// it.
163
+ pub suggest_buying_pages: bool,
159
164
  }
160
165
 
161
166
  #[derive(Debug, Deserialize)]
162
167
  pub(crate) struct DocumentListResponse {
163
168
  pub documents: Vec<DocumentSummary>,
164
169
  pub pages_remaining: Option<i64>,
170
+ #[serde(default)]
171
+ pub suggest_buying_pages: bool,
165
172
  }
166
173
 
167
174
  /// One row from `GET /api/documents/trash`.
@@ -253,6 +260,45 @@ pub struct AccountInfo {
253
260
  pub organization_name: Option<String>,
254
261
  }
255
262
 
263
+ /// What the account can spend and what it pays for, from `GET /api/billing`.
264
+ #[derive(Debug, Clone, Serialize, Deserialize)]
265
+ pub struct BillingStatus {
266
+ pub pages_remaining: i64,
267
+ /// The active subscription, or `None` if the account has none.
268
+ pub subscription: Option<BillingSubscription>,
269
+ /// The UUID to set as the `appAccountToken` of every App Store purchase,
270
+ /// so the server credits it to this account and no other.
271
+ pub app_account_token: String,
272
+ }
273
+
274
+ #[derive(Debug, Clone, Serialize, Deserialize)]
275
+ pub struct BillingSubscription {
276
+ /// `"app_store"` for a subscription bought in the App Store, `"web"` for
277
+ /// one bought any other way, which the App Store must not be offered to
278
+ /// replace.
279
+ pub store: String,
280
+ /// ISO 8601 UTC timestamp of the next renewal, if the server knows it.
281
+ pub renews_at: Option<String>,
282
+ }
283
+
284
+ /// A product on sale in the App Store, from `GET /api/app_store/products`.
285
+ /// The server decides what is on sale, so a special can be offered without a
286
+ /// new app; `StoreKit` supplies the name and price.
287
+ #[derive(Debug, Clone, Serialize, Deserialize)]
288
+ pub struct AppStoreProduct {
289
+ /// The App Store product ID to ask `StoreKit` for.
290
+ pub id: String,
291
+ /// `"page_pack"` or `"subscription"`. Skip any other kind.
292
+ pub kind: String,
293
+ /// The pages a page pack adds, or a subscription adds each billing period.
294
+ pub pages: i64,
295
+ }
296
+
297
+ #[derive(Debug, Deserialize)]
298
+ pub(crate) struct AppStoreProductsResponse {
299
+ pub products: Vec<AppStoreProduct>,
300
+ }
301
+
256
302
  /// A `(display_name, language_code)` pair from `GET /api/settings/languages`.
257
303
  #[derive(Debug, Clone, Deserialize)]
258
304
  pub struct Language(pub String, pub String);