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/// A partial update to a document's conversion settings
214#[derive(Debug, Clone, Default, Serialize, Deserialize)]
215pub struct SettingsUpdate {
216    #[serde(default, skip_serializing_if = "Option::is_none")]
217    pub language: Option<String>,
218    #[serde(default, skip_serializing_if = "Option::is_none")]
219    pub dialects: Option<serde_json::Value>,
220    #[serde(default, skip_serializing_if = "Option::is_none")]
221    pub voices: Option<serde_json::Value>,
222    #[serde(default, skip_serializing_if = "Option::is_none")]
223    pub tts_gender: Option<String>,
224    #[serde(default, skip_serializing_if = "Option::is_none")]
225    pub tts_rate: Option<f64>,
226    #[serde(default, skip_serializing_if = "Option::is_none")]
227    pub braille_translation_table: Option<String>,
228    #[serde(default, skip_serializing_if = "Option::is_none")]
229    pub braille_cells_per_line: Option<i64>,
230    #[serde(default, skip_serializing_if = "Option::is_none")]
231    pub braille_split_into_pages: Option<bool>,
232    #[serde(default, skip_serializing_if = "Option::is_none")]
233    pub braille_lines_per_page: Option<i64>,
234    #[serde(default, skip_serializing_if = "Option::is_none")]
235    pub large_print: Option<bool>,
236    #[serde(default, skip_serializing_if = "Option::is_none")]
237    pub add_image_descriptions: Option<bool>,
238    #[serde(default, skip_serializing_if = "Option::is_none")]
239    pub math: Option<bool>,
240    #[serde(default, skip_serializing_if = "Option::is_none")]
241    pub notify_when_complete: Option<bool>,
242}
243
244/// A user's push-notification preference. One flag today, on purpose —
245/// device tokens are per-device, so this is user-scoped, not per-document.
246#[derive(Debug, Clone, Serialize, Deserialize)]
247pub struct NotificationSettings {
248    pub push_notify_when_complete: bool,
249}
250
251/// The authenticated user's name, email, phone number, and (if the account
252/// belongs to a real organization rather than an individual) organization
253/// name, for read-only display in the app's Account screen.
254#[derive(Debug, Clone, Serialize, Deserialize)]
255pub struct AccountInfo {
256    pub first_name: Option<String>,
257    pub last_name: Option<String>,
258    pub email: Option<String>,
259    pub phone_number: Option<String>,
260    pub organization_name: Option<String>,
261}
262
263/// What the account can spend and what it pays for, from `GET /api/billing`.
264#[derive(Debug, Clone, Serialize, Deserialize)]
265pub 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)]
275pub 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)]
288pub 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)]
298pub(crate) struct AppStoreProductsResponse {
299    pub products: Vec<AppStoreProduct>,
300}
301
302/// A `(display_name, language_code)` pair from `GET /api/settings/languages`.
303#[derive(Debug, Clone, Deserialize)]
304pub struct Language(pub String, pub String);
305
306/// A `(display_name, locale)` pair from `GET /api/settings/dialects`.
307#[derive(Debug, Clone, Deserialize)]
308pub struct Dialect(pub String, pub String);
309
310/// A `(display_name, table_id)` pair from `GET /api/settings/braille_tables`.
311#[derive(Debug, Clone, Deserialize)]
312pub struct BrailleTable(pub String, pub String);
313
314/// A `(display_name, voice_short_name, has_sample)` triple from
315/// `GET /api/settings/voices`.
316#[derive(Debug, Clone, Deserialize)]
317pub struct Voice(pub String, pub String, pub bool);
318
319#[derive(Debug, Deserialize)]
320pub(crate) struct LanguagesResponse {
321    pub languages: Vec<Language>,
322}
323
324#[derive(Debug, Deserialize)]
325pub(crate) struct DialectsResponse {
326    pub dialects: HashMap<String, Vec<Dialect>>,
327}
328
329#[derive(Debug, Deserialize)]
330pub(crate) struct BrailleTablesResponse {
331    pub braille_tables: Vec<BrailleTable>,
332}
333
334#[derive(Debug, Deserialize)]
335pub(crate) struct VoicesResponse {
336    pub voices: HashMap<String, Vec<Voice>>,
337}
338
339#[cfg(test)]
340mod tests {
341    use super::*;
342
343    #[test]
344    fn output_format_as_str_and_parse_round_trip() {
345        let all = [
346            OutputFormat::Html,
347            OutputFormat::Pdf,
348            OutputFormat::Epub,
349            OutputFormat::Daisy,
350            OutputFormat::Docx,
351            OutputFormat::Brf,
352            OutputFormat::Mp3,
353            OutputFormat::OfflineHtml,
354            OutputFormat::Mobi,
355            OutputFormat::HtmlStream,
356        ];
357        for format in all {
358            assert_eq!(OutputFormat::parse(format.as_str()), Some(format));
359        }
360        assert_eq!(OutputFormat::parse("not_a_format"), None);
361    }
362
363    #[test]
364    fn only_the_complete_stage_reports_is_complete() {
365        let all = [
366            Stage::Queue,
367            Stage::Start,
368            Stage::Convert,
369            Stage::AddImageDescriptions,
370            Stage::Complete,
371        ];
372        for stage in all {
373            assert_eq!(stage.is_complete(), stage == Stage::Complete);
374        }
375    }
376
377    #[test]
378    fn stage_as_str_round_trips_through_json() {
379        let all = [
380            (Stage::Queue, "queue"),
381            (Stage::Start, "start"),
382            (Stage::Convert, "convert"),
383            (Stage::AddImageDescriptions, "add_image_descriptions"),
384            (Stage::Complete, "complete"),
385        ];
386        for (stage, expected) in all {
387            assert_eq!(stage.as_str(), expected);
388            let deserialized: Stage = serde_json::from_str(&format!("{expected:?}")).unwrap();
389            assert_eq!(deserialized, stage);
390        }
391    }
392}