scribe-client 0.3.1

Rust client for the Scribe document conversion API
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
use std::collections::HashMap;

use serde::{Deserialize, Serialize};

/// A document conversion output format.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum OutputFormat {
    Html,
    Pdf,
    Epub,
    Daisy,
    Docx,
    Brf,
    Mp3,
    OfflineHtml,
    Mobi,
    HtmlStream,
}

impl OutputFormat {
    #[must_use]
    pub fn as_str(&self) -> &'static str {
        match self {
            OutputFormat::Html => "html",
            OutputFormat::Pdf => "pdf",
            OutputFormat::Epub => "epub",
            OutputFormat::Daisy => "daisy",
            OutputFormat::Docx => "docx",
            OutputFormat::Brf => "brf",
            OutputFormat::Mp3 => "mp3",
            OutputFormat::OfflineHtml => "offline_html",
            OutputFormat::Mobi => "mobi",
            OutputFormat::HtmlStream => "html_stream",
        }
    }

    #[must_use]
    pub fn parse(s: &str) -> Option<Self> {
        Some(match s {
            "html" => OutputFormat::Html,
            "pdf" => OutputFormat::Pdf,
            "epub" => OutputFormat::Epub,
            "daisy" => OutputFormat::Daisy,
            "docx" => OutputFormat::Docx,
            "brf" => OutputFormat::Brf,
            "mp3" => OutputFormat::Mp3,
            "offline_html" => OutputFormat::OfflineHtml,
            "mobi" => OutputFormat::Mobi,
            "html_stream" => OutputFormat::HtmlStream,
            _ => return None,
        })
    }
}

/// The current stage of a document conversion.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum Stage {
    Queue,
    Start,
    Convert,
    AddImageDescriptions,
    Complete,
}

impl Stage {
    #[must_use]
    pub fn is_complete(&self) -> bool {
        matches!(self, Stage::Complete)
    }

    #[must_use]
    pub fn as_str(&self) -> &'static str {
        match self {
            Stage::Queue => "queue",
            Stage::Start => "start",
            Stage::Convert => "convert",
            Stage::AddImageDescriptions => "add_image_descriptions",
            Stage::Complete => "complete",
        }
    }
}

/// One row from `GET /api/documents/:id/outputs`.
#[derive(Debug, Clone, Deserialize)]
pub struct Output {
    pub format: OutputFormat,
    pub stage: Stage,
    pub progress: f64,
    pub estimated_time_remaining: Option<i64>,
    pub is_preview: bool,
    /// Whether the server offers this output as a download. The in-app HTML
    /// preview formats are not. Defaults to true for a server that predates
    /// the field.
    #[serde(default = "default_true")]
    pub downloadable: bool,
}

fn default_true() -> bool {
    true
}

/// A downloaded output, with the name the server says to save it under.
#[derive(Debug, Clone)]
pub struct Download {
    pub data: Vec<u8>,
    /// From the response's `Content-Disposition`, or `None` if it had no
    /// usable file name.
    pub file_name: Option<String>,
}

/// Response body of `POST /api/documents`.
#[derive(Debug, Clone, Deserialize)]
pub struct CreatedDocument {
    pub document_id: String,
}

/// The result of `GET /api/documents/:id/outputs`.
#[derive(Debug, Clone, Deserialize)]
pub struct OutputList {
    pub outputs: Vec<Output>,
    /// The document is a password-protected file that hasn't been unlocked
    /// yet. It has no outputs at all while this is true, so an empty
    /// `outputs` alone doesn't distinguish "locked" from "not started".
    #[serde(default)]
    pub is_password_needed: bool,
}

#[derive(Debug, Deserialize)]
pub(crate) struct OutputListResponse {
    pub outputs: Vec<Output>,
    #[serde(default)]
    pub is_password_needed: bool,
}

/// One row from `GET /api/documents`.
#[derive(Debug, Clone, Deserialize)]
pub struct DocumentSummary {
    pub id: String,
    /// `None` if the document hasn't been titled yet (e.g. a URL-sourced
    /// document before the converter has determined one).
    pub title: Option<String>,
    pub page_count: Option<i64>,
    /// ISO 8601 UTC timestamp of when the document was created.
    pub inserted_at: String,
    /// The document is a password-protected file that hasn't been unlocked
    /// yet, so it has no outputs and nothing can be downloaded from it.
    #[serde(default)]
    pub is_password_needed: bool,
    pub outputs: Vec<Output>,
}

/// The result of `GET /api/documents`.
#[derive(Debug, Clone, Deserialize)]
pub struct DocumentList {
    pub documents: Vec<DocumentSummary>,
    pub pages_remaining: Option<i64>,
    /// Whether to put buying pages in front of the user, such as on the home
    /// screen. The server decides: it is true for an individual account with
    /// only trial pages or few pages left. False from a server that predates
    /// it.
    pub suggest_buying_pages: bool,
}

#[derive(Debug, Deserialize)]
pub(crate) struct DocumentListResponse {
    pub documents: Vec<DocumentSummary>,
    pub pages_remaining: Option<i64>,
    #[serde(default)]
    pub suggest_buying_pages: bool,
}

/// One row from `GET /api/documents/trash`.
#[derive(Debug, Clone, Deserialize)]
pub struct TrashedDocument {
    pub id: String,
    pub title: Option<String>,
    pub page_count: Option<i64>,
    /// ISO 8601 UTC timestamp of when the document was created.
    pub inserted_at: String,
    /// ISO 8601 UTC timestamp of when the document was moved to the trash.
    pub trashed_at: String,
    /// ISO 8601 UTC timestamp of when the document will be permanently
    /// deleted if it isn't recovered first.
    pub permanently_delete_at: String,
}

#[derive(Debug, Deserialize)]
pub(crate) struct TrashedDocumentListResponse {
    pub documents: Vec<TrashedDocument>,
}

/// A document's current conversion settings
#[allow(clippy::struct_excessive_bools)] // mirrors the server's flat settings shape
#[derive(Debug, Clone, Deserialize)]
pub struct Settings {
    pub language: Option<String>,
    pub dialects: serde_json::Value,
    pub voices: serde_json::Value,
    pub tts_gender: Option<String>,
    pub tts_rate: f64,
    pub braille_translation_table: String,
    pub braille_cells_per_line: i64,
    pub braille_split_into_pages: bool,
    pub braille_lines_per_page: i64,
    pub large_print: bool,
    pub add_image_descriptions: bool,
    pub math: bool,
    pub notify_when_complete: bool,
}

/// The server takes `dialects` and `voices` as strings holding JSON, though
/// it gives them back decoded, so an object written back as it was read is
/// sent as its JSON. A string is sent as it is.
#[allow(clippy::ref_option, reason = "serde's serialize_with signature")]
fn as_json_string<S: serde::Serializer>(
    value: &Option<serde_json::Value>,
    serializer: S,
) -> Result<S::Ok, S::Error> {
    match value {
        Some(serde_json::Value::String(text)) => serializer.serialize_str(text),
        Some(other) => serializer.serialize_str(&other.to_string()),
        None => serializer.serialize_none(),
    }
}

/// A partial update to a document's conversion settings
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct SettingsUpdate {
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub language: Option<String>,
    /// Language code to dialect locale. An object is sent as the string of
    /// JSON the server takes.
    #[serde(
        default,
        skip_serializing_if = "Option::is_none",
        serialize_with = "as_json_string"
    )]
    pub dialects: Option<serde_json::Value>,
    /// Dialect locale to voice short name, sent as `dialects` is.
    #[serde(
        default,
        skip_serializing_if = "Option::is_none",
        serialize_with = "as_json_string"
    )]
    pub voices: Option<serde_json::Value>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub tts_gender: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub tts_rate: Option<f64>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub braille_translation_table: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub braille_cells_per_line: Option<i64>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub braille_split_into_pages: Option<bool>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub braille_lines_per_page: Option<i64>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub large_print: Option<bool>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub add_image_descriptions: Option<bool>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub math: Option<bool>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub notify_when_complete: Option<bool>,
}

/// A user's push-notification preference. One flag today, on purpose —
/// device tokens are per-device, so this is user-scoped, not per-document.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct NotificationSettings {
    pub push_notify_when_complete: bool,
}

/// The authenticated user's name, email, phone number, and (if the account
/// belongs to a real organization rather than an individual) organization
/// name, for read-only display in the app's Account screen.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AccountInfo {
    pub first_name: Option<String>,
    pub last_name: Option<String>,
    pub email: Option<String>,
    pub phone_number: Option<String>,
    pub organization_name: Option<String>,
}

/// What the account can spend and what it pays for, from `GET /api/billing`.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct BillingStatus {
    pub pages_remaining: i64,
    /// The active subscription, or `None` if the account has none.
    pub subscription: Option<BillingSubscription>,
    /// The UUID to set as the `appAccountToken` of every App Store purchase,
    /// so the server credits it to this account and no other.
    pub app_account_token: String,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct BillingSubscription {
    /// `"app_store"` for a subscription bought in the App Store, `"web"` for
    /// one bought any other way, which the App Store must not be offered to
    /// replace.
    pub store: String,
    /// ISO 8601 UTC timestamp of the next renewal, if the server knows it.
    pub renews_at: Option<String>,
}

/// A product on sale in the App Store, from `GET /api/app_store/products`.
/// The server decides what is on sale, so a special can be offered without a
/// new app; `StoreKit` supplies the name and price.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AppStoreProduct {
    /// The App Store product ID to ask `StoreKit` for.
    pub id: String,
    /// `"page_pack"` or `"subscription"`. Skip any other kind.
    pub kind: String,
    /// The pages a page pack adds, or a subscription adds each billing period.
    pub pages: i64,
}

#[derive(Debug, Deserialize)]
pub(crate) struct AppStoreProductsResponse {
    pub products: Vec<AppStoreProduct>,
}

/// A `(display_name, language_code)` pair from `GET /api/settings/languages`.
#[derive(Debug, Clone, Deserialize)]
pub struct Language(pub String, pub String);

/// A `(display_name, locale)` pair from `GET /api/settings/dialects`.
#[derive(Debug, Clone, Deserialize)]
pub struct Dialect(pub String, pub String);

/// A `(display_name, table_id)` pair from `GET /api/settings/braille_tables`.
#[derive(Debug, Clone, Deserialize)]
pub struct BrailleTable(pub String, pub String);

/// A `(display_name, voice_short_name, has_sample)` triple from
/// `GET /api/settings/voices`.
#[derive(Debug, Clone, Deserialize)]
pub struct Voice(pub String, pub String, pub bool);

#[derive(Debug, Deserialize)]
pub(crate) struct LanguagesResponse {
    pub languages: Vec<Language>,
}

#[derive(Debug, Deserialize)]
pub(crate) struct DialectsResponse {
    pub dialects: HashMap<String, Vec<Dialect>>,
}

#[derive(Debug, Deserialize)]
pub(crate) struct BrailleTablesResponse {
    pub braille_tables: Vec<BrailleTable>,
}

#[derive(Debug, Deserialize)]
pub(crate) struct VoicesResponse {
    pub voices: HashMap<String, Vec<Voice>>,
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn output_format_as_str_and_parse_round_trip() {
        let all = [
            OutputFormat::Html,
            OutputFormat::Pdf,
            OutputFormat::Epub,
            OutputFormat::Daisy,
            OutputFormat::Docx,
            OutputFormat::Brf,
            OutputFormat::Mp3,
            OutputFormat::OfflineHtml,
            OutputFormat::Mobi,
            OutputFormat::HtmlStream,
        ];
        for format in all {
            assert_eq!(OutputFormat::parse(format.as_str()), Some(format));
        }
        assert_eq!(OutputFormat::parse("not_a_format"), None);
    }

    #[test]
    fn only_the_complete_stage_reports_is_complete() {
        let all = [
            Stage::Queue,
            Stage::Start,
            Stage::Convert,
            Stage::AddImageDescriptions,
            Stage::Complete,
        ];
        for stage in all {
            assert_eq!(stage.is_complete(), stage == Stage::Complete);
        }
    }

    #[test]
    fn stage_as_str_round_trips_through_json() {
        let all = [
            (Stage::Queue, "queue"),
            (Stage::Start, "start"),
            (Stage::Convert, "convert"),
            (Stage::AddImageDescriptions, "add_image_descriptions"),
            (Stage::Complete, "complete"),
        ];
        for (stage, expected) in all {
            assert_eq!(stage.as_str(), expected);
            let deserialized: Stage = serde_json::from_str(&format!("{expected:?}")).unwrap();
            assert_eq!(deserialized, stage);
        }
    }
}