Skip to main content

scribe_client/
model.rs

1use std::collections::HashMap;
2
3use serde::{Deserialize, Serialize};
4
5/// A document conversion output format.
6#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
7#[serde(rename_all = "snake_case")]
8pub enum OutputFormat {
9    Html,
10    Pdf,
11    Epub,
12    Daisy,
13    Docx,
14    Brf,
15    Mp3,
16    OfflineHtml,
17    Mobi,
18    HtmlStream,
19}
20
21impl OutputFormat {
22    #[must_use]
23    pub fn as_str(&self) -> &'static str {
24        match self {
25            OutputFormat::Html => "html",
26            OutputFormat::Pdf => "pdf",
27            OutputFormat::Epub => "epub",
28            OutputFormat::Daisy => "daisy",
29            OutputFormat::Docx => "docx",
30            OutputFormat::Brf => "brf",
31            OutputFormat::Mp3 => "mp3",
32            OutputFormat::OfflineHtml => "offline_html",
33            OutputFormat::Mobi => "mobi",
34            OutputFormat::HtmlStream => "html_stream",
35        }
36    }
37
38    #[must_use]
39    pub fn parse(s: &str) -> Option<Self> {
40        Some(match s {
41            "html" => OutputFormat::Html,
42            "pdf" => OutputFormat::Pdf,
43            "epub" => OutputFormat::Epub,
44            "daisy" => OutputFormat::Daisy,
45            "docx" => OutputFormat::Docx,
46            "brf" => OutputFormat::Brf,
47            "mp3" => OutputFormat::Mp3,
48            "offline_html" => OutputFormat::OfflineHtml,
49            "mobi" => OutputFormat::Mobi,
50            "html_stream" => OutputFormat::HtmlStream,
51            _ => return None,
52        })
53    }
54}
55
56/// The current stage of a document conversion.
57#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
58#[serde(rename_all = "snake_case")]
59pub enum Stage {
60    Queue,
61    Start,
62    Convert,
63    AddImageDescriptions,
64    Complete,
65}
66
67impl Stage {
68    #[must_use]
69    pub fn is_complete(&self) -> bool {
70        matches!(self, Stage::Complete)
71    }
72
73    #[must_use]
74    pub fn as_str(&self) -> &'static str {
75        match self {
76            Stage::Queue => "queue",
77            Stage::Start => "start",
78            Stage::Convert => "convert",
79            Stage::AddImageDescriptions => "add_image_descriptions",
80            Stage::Complete => "complete",
81        }
82    }
83}
84
85/// One row from `GET /api/documents/:id/outputs`.
86#[derive(Debug, Clone, Deserialize)]
87pub struct Output {
88    pub format: OutputFormat,
89    pub stage: Stage,
90    pub progress: f64,
91    pub estimated_time_remaining: Option<i64>,
92    pub is_preview: bool,
93    /// Whether the server offers this output as a download. The in-app HTML
94    /// preview formats are not. Defaults to true for a server that predates
95    /// the field.
96    #[serde(default = "default_true")]
97    pub downloadable: bool,
98}
99
100fn default_true() -> bool {
101    true
102}
103
104/// A downloaded output, with the name the server says to save it under.
105#[derive(Debug, Clone)]
106pub struct Download {
107    pub data: Vec<u8>,
108    /// From the response's `Content-Disposition`, or `None` if it had no
109    /// usable file name.
110    pub file_name: Option<String>,
111}
112
113/// Response body of `POST /api/documents`.
114#[derive(Debug, Clone, Deserialize)]
115pub struct CreatedDocument {
116    pub document_id: String,
117}
118
119/// The result of `GET /api/documents/:id/outputs`.
120#[derive(Debug, Clone, Deserialize)]
121pub struct OutputList {
122    pub outputs: Vec<Output>,
123    /// The document is a password-protected file that hasn't been unlocked
124    /// yet. It has no outputs at all while this is true, so an empty
125    /// `outputs` alone doesn't distinguish "locked" from "not started".
126    #[serde(default)]
127    pub is_password_needed: bool,
128}
129
130#[derive(Debug, Deserialize)]
131pub(crate) struct OutputListResponse {
132    pub outputs: Vec<Output>,
133    #[serde(default)]
134    pub is_password_needed: bool,
135}
136
137/// One row from `GET /api/documents`.
138#[derive(Debug, Clone, Deserialize)]
139pub struct DocumentSummary {
140    pub id: String,
141    /// `None` if the document hasn't been titled yet (e.g. a URL-sourced
142    /// document before the converter has determined one).
143    pub title: Option<String>,
144    pub page_count: Option<i64>,
145    /// ISO 8601 UTC timestamp of when the document was created.
146    pub inserted_at: String,
147    /// The document is a password-protected file that hasn't been unlocked
148    /// yet, so it has no outputs and nothing can be downloaded from it.
149    #[serde(default)]
150    pub is_password_needed: bool,
151    pub outputs: Vec<Output>,
152}
153
154/// The result of `GET /api/documents`.
155#[derive(Debug, Clone, Deserialize)]
156pub struct DocumentList {
157    pub documents: Vec<DocumentSummary>,
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,
164}
165
166#[derive(Debug, Deserialize)]
167pub(crate) struct DocumentListResponse {
168    pub documents: Vec<DocumentSummary>,
169    pub pages_remaining: Option<i64>,
170    #[serde(default)]
171    pub suggest_buying_pages: bool,
172}
173
174/// One row from `GET /api/documents/trash`.
175#[derive(Debug, Clone, Deserialize)]
176pub struct TrashedDocument {
177    pub id: String,
178    pub title: Option<String>,
179    pub page_count: Option<i64>,
180    /// ISO 8601 UTC timestamp of when the document was created.
181    pub inserted_at: String,
182    /// ISO 8601 UTC timestamp of when the document was moved to the trash.
183    pub trashed_at: String,
184    /// ISO 8601 UTC timestamp of when the document will be permanently
185    /// deleted if it isn't recovered first.
186    pub permanently_delete_at: String,
187}
188
189#[derive(Debug, Deserialize)]
190pub(crate) struct TrashedDocumentListResponse {
191    pub documents: Vec<TrashedDocument>,
192}
193
194/// A document's current conversion settings
195#[allow(clippy::struct_excessive_bools)] // mirrors the server's flat settings shape
196#[derive(Debug, Clone, Deserialize)]
197pub struct Settings {
198    pub language: Option<String>,
199    pub dialects: serde_json::Value,
200    pub voices: serde_json::Value,
201    pub tts_gender: Option<String>,
202    pub tts_rate: f64,
203    pub braille_translation_table: String,
204    pub braille_cells_per_line: i64,
205    pub braille_split_into_pages: bool,
206    pub braille_lines_per_page: i64,
207    pub large_print: bool,
208    pub add_image_descriptions: bool,
209    pub math: bool,
210    pub notify_when_complete: bool,
211}
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")]
217fn 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
228/// A partial update to a document's conversion settings
229#[derive(Debug, Clone, Default, Serialize, Deserialize)]
230pub struct SettingsUpdate {
231    #[serde(default, skip_serializing_if = "Option::is_none")]
232    pub language: Option<String>,
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    )]
240    pub dialects: Option<serde_json::Value>,
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    )]
247    pub voices: Option<serde_json::Value>,
248    #[serde(default, skip_serializing_if = "Option::is_none")]
249    pub tts_gender: Option<String>,
250    #[serde(default, skip_serializing_if = "Option::is_none")]
251    pub tts_rate: Option<f64>,
252    #[serde(default, skip_serializing_if = "Option::is_none")]
253    pub braille_translation_table: Option<String>,
254    #[serde(default, skip_serializing_if = "Option::is_none")]
255    pub braille_cells_per_line: Option<i64>,
256    #[serde(default, skip_serializing_if = "Option::is_none")]
257    pub braille_split_into_pages: Option<bool>,
258    #[serde(default, skip_serializing_if = "Option::is_none")]
259    pub braille_lines_per_page: Option<i64>,
260    #[serde(default, skip_serializing_if = "Option::is_none")]
261    pub large_print: Option<bool>,
262    #[serde(default, skip_serializing_if = "Option::is_none")]
263    pub add_image_descriptions: Option<bool>,
264    #[serde(default, skip_serializing_if = "Option::is_none")]
265    pub math: Option<bool>,
266    #[serde(default, skip_serializing_if = "Option::is_none")]
267    pub notify_when_complete: Option<bool>,
268}
269
270/// A user's push-notification preference. One flag today, on purpose —
271/// device tokens are per-device, so this is user-scoped, not per-document.
272#[derive(Debug, Clone, Serialize, Deserialize)]
273pub struct NotificationSettings {
274    pub push_notify_when_complete: bool,
275}
276
277/// The authenticated user's name, email, phone number, and (if the account
278/// belongs to a real organization rather than an individual) organization
279/// name, for read-only display in the app's Account screen.
280#[derive(Debug, Clone, Serialize, Deserialize)]
281pub struct AccountInfo {
282    pub first_name: Option<String>,
283    pub last_name: Option<String>,
284    pub email: Option<String>,
285    pub phone_number: Option<String>,
286    pub organization_name: Option<String>,
287}
288
289/// What the account can spend and what it pays for, from `GET /api/billing`.
290#[derive(Debug, Clone, Serialize, Deserialize)]
291pub struct BillingStatus {
292    pub pages_remaining: i64,
293    /// The active subscription, or `None` if the account has none.
294    pub subscription: Option<BillingSubscription>,
295    /// The UUID to set as the `appAccountToken` of every App Store purchase,
296    /// so the server credits it to this account and no other.
297    pub app_account_token: String,
298}
299
300#[derive(Debug, Clone, Serialize, Deserialize)]
301pub struct BillingSubscription {
302    /// `"app_store"` for a subscription bought in the App Store, `"web"` for
303    /// one bought any other way, which the App Store must not be offered to
304    /// replace.
305    pub store: String,
306    /// ISO 8601 UTC timestamp of the next renewal, if the server knows it.
307    pub renews_at: Option<String>,
308}
309
310/// A product on sale in the App Store, from `GET /api/app_store/products`.
311/// The server decides what is on sale, so a special can be offered without a
312/// new app; `StoreKit` supplies the name and price.
313#[derive(Debug, Clone, Serialize, Deserialize)]
314pub struct AppStoreProduct {
315    /// The App Store product ID to ask `StoreKit` for.
316    pub id: String,
317    /// `"page_pack"` or `"subscription"`. Skip any other kind.
318    pub kind: String,
319    /// The pages a page pack adds, or a subscription adds each billing period.
320    pub pages: i64,
321}
322
323#[derive(Debug, Deserialize)]
324pub(crate) struct AppStoreProductsResponse {
325    pub products: Vec<AppStoreProduct>,
326}
327
328/// A `(display_name, language_code)` pair from `GET /api/settings/languages`.
329#[derive(Debug, Clone, Deserialize)]
330pub struct Language(pub String, pub String);
331
332/// A `(display_name, locale)` pair from `GET /api/settings/dialects`.
333#[derive(Debug, Clone, Deserialize)]
334pub struct Dialect(pub String, pub String);
335
336/// A `(display_name, table_id)` pair from `GET /api/settings/braille_tables`.
337#[derive(Debug, Clone, Deserialize)]
338pub struct BrailleTable(pub String, pub String);
339
340/// A `(display_name, voice_short_name, has_sample)` triple from
341/// `GET /api/settings/voices`.
342#[derive(Debug, Clone, Deserialize)]
343pub struct Voice(pub String, pub String, pub bool);
344
345#[derive(Debug, Deserialize)]
346pub(crate) struct LanguagesResponse {
347    pub languages: Vec<Language>,
348}
349
350#[derive(Debug, Deserialize)]
351pub(crate) struct DialectsResponse {
352    pub dialects: HashMap<String, Vec<Dialect>>,
353}
354
355#[derive(Debug, Deserialize)]
356pub(crate) struct BrailleTablesResponse {
357    pub braille_tables: Vec<BrailleTable>,
358}
359
360#[derive(Debug, Deserialize)]
361pub(crate) struct VoicesResponse {
362    pub voices: HashMap<String, Vec<Voice>>,
363}
364
365#[cfg(test)]
366mod tests {
367    use super::*;
368
369    #[test]
370    fn output_format_as_str_and_parse_round_trip() {
371        let all = [
372            OutputFormat::Html,
373            OutputFormat::Pdf,
374            OutputFormat::Epub,
375            OutputFormat::Daisy,
376            OutputFormat::Docx,
377            OutputFormat::Brf,
378            OutputFormat::Mp3,
379            OutputFormat::OfflineHtml,
380            OutputFormat::Mobi,
381            OutputFormat::HtmlStream,
382        ];
383        for format in all {
384            assert_eq!(OutputFormat::parse(format.as_str()), Some(format));
385        }
386        assert_eq!(OutputFormat::parse("not_a_format"), None);
387    }
388
389    #[test]
390    fn only_the_complete_stage_reports_is_complete() {
391        let all = [
392            Stage::Queue,
393            Stage::Start,
394            Stage::Convert,
395            Stage::AddImageDescriptions,
396            Stage::Complete,
397        ];
398        for stage in all {
399            assert_eq!(stage.is_complete(), stage == Stage::Complete);
400        }
401    }
402
403    #[test]
404    fn stage_as_str_round_trips_through_json() {
405        let all = [
406            (Stage::Queue, "queue"),
407            (Stage::Start, "start"),
408            (Stage::Convert, "convert"),
409            (Stage::AddImageDescriptions, "add_image_descriptions"),
410            (Stage::Complete, "complete"),
411        ];
412        for (stage, expected) in all {
413            assert_eq!(stage.as_str(), expected);
414            let deserialized: Stage = serde_json::from_str(&format!("{expected:?}")).unwrap();
415            assert_eq!(deserialized, stage);
416        }
417    }
418}