paperless-api 0.2.1

Async Paperless ngx API client
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
419
420
421
422
423
424
425
426
427
428
429
//! Types for working with Paperless documents.
//!
//! Document mutations are applied locally first.
//! Methods such as [`set_title`](Document::set_title),
//! [`set_content`](Document::set_content),
//! [`add_tag`](Document::add_tag), etc..
//! only update the in-memory [`Document`] value and mark it as changed.
//! The changes are only sent to the Paperless server when
//! [`patch`](Document::patch) is called.

use std::{fmt::Display, io, path::Path, sync::Arc};

use enumflags2::{BitFlags, bitflags};
use futures_util::TryStreamExt;
use reqwest::Method;
use serde::{Deserialize, Serialize};
use tokio_util::io::StreamReader;

use crate::{
    DocumentCustomField, Error, Result, client::PaperlessClient, correspondent::CorrespondentId,
    custom_field::CustomFieldId, document_type::DocumentTypeId, tag::TagId, user::UserId,
};

#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Deserialize, Serialize)]
#[repr(transparent)]
pub struct DocumentId(pub i32);

/// Represents a document.
///
/// Changes made through mutating methods such as
/// [`set_title`](Document::set_title),
/// [`set_content`](Document::set_content),
/// [`add_tag`](Document::add_tag), and
/// [`set_custom_field`](Document::set_custom_field)
/// are only tracked locally at first.
///
/// They are not sent to the Paperless server until
/// [`patch`](Document::patch) is called.
#[derive(Debug, Clone)]
pub struct Document {
    data: DocumentData,
    client: Arc<PaperlessClient>,
    content_is_truncated: bool,
    changed_values: BitFlags<ChangedAttributes>,
}

#[derive(Debug, Clone, Deserialize, Serialize)]
pub(crate) struct DocumentData {
    id: DocumentId,
    original_file_name: String,
    page_count: u32,
    title: String,
    content: String,
    tags: Vec<TagId>,
    owner: Option<UserId>,
    correspondent: Option<CorrespondentId>,
    custom_fields: Vec<DocumentCustomField>,
    document_type: Option<DocumentTypeId>,
}

#[bitflags]
#[repr(u8)]
#[derive(Copy, Clone, Debug, PartialEq)]
enum ChangedAttributes {
    Title,
    Content,
    Tags,
    CustomFields,
    Correspondent,
    DocumentType,
}

/// The content (OCR) of a document, either full or truncated.
#[derive(Debug, Clone)]
pub enum Content<'a> {
    /// Full content of the document.
    Full(&'a str),

    /// Truncated content of the document.
    Truncated(&'a str),
}

#[derive(Debug, Serialize)]
struct PatchRequest {
    #[serde(skip_serializing_if = "Option::is_none")]
    title: Option<String>,

    #[serde(skip_serializing_if = "Option::is_none")]
    content: Option<String>,

    #[serde(skip_serializing_if = "Option::is_none")]
    tags: Option<Vec<TagId>>,

    #[serde(skip_serializing_if = "Option::is_none")]
    custom_fields: Option<Vec<DocumentCustomField>>,

    #[serde(skip_serializing_if = "Option::is_none")]
    correspondent: Option<CorrespondentId>,

    #[serde(skip_serializing_if = "Option::is_none")]
    document_type: Option<DocumentTypeId>,
}

impl std::fmt::Display for DocumentId {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}", self.0)
    }
}

impl Document {
    pub(crate) fn new(
        data: DocumentData,
        client: Arc<PaperlessClient>,
        content_is_truncated: bool,
    ) -> Self {
        Self {
            data,
            client,
            content_is_truncated,
            changed_values: BitFlags::default(),
        }
    }

    /// Get the id of the document
    #[inline]
    #[must_use]
    pub fn id(&self) -> DocumentId {
        self.data.id
    }

    /// Get the title of the document.
    #[inline]
    #[must_use]
    pub fn title(&self) -> &str {
        &self.data.title
    }

    /// Get the original file name of the document.
    #[inline]
    #[must_use]
    pub fn original_file_name(&self) -> &str {
        &self.data.original_file_name
    }

    /// Get the correspondent id of the document.
    #[inline]
    #[must_use]
    pub fn correspondent(&self) -> Option<CorrespondentId> {
        self.data.correspondent
    }

    /// Get the owner id of the document.
    #[inline]
    #[must_use]
    pub fn owner(&self) -> Option<UserId> {
        self.data.owner
    }

    /// Get the document type id of the document.
    #[inline]
    #[must_use]
    pub fn document_type(&self) -> Option<DocumentTypeId> {
        self.data.document_type
    }

    /// Get the number of pages in the document.
    #[inline]
    #[must_use]
    pub fn page_count(&self) -> u32 {
        self.data.page_count
    }

    /// Get all tag-ids for the document.
    #[inline]
    #[must_use]
    pub fn tags(&self) -> &[TagId] {
        &self.data.tags
    }

    /// Get all custom fields for the document.
    #[inline]
    #[must_use]
    pub fn custom_fields(&self) -> &[DocumentCustomField] {
        &self.data.custom_fields
    }

    /// Get the content of the document.
    #[inline]
    #[must_use]
    pub fn content(&self) -> Content<'_> {
        if self.content_is_truncated {
            Content::Truncated(&self.data.content)
        } else {
            Content::Full(&self.data.content)
        }
    }

    /// Add a tag to the document.
    pub fn add_tag(&mut self, tag_id: TagId) {
        if !self.data.tags.contains(&tag_id) {
            self.data.tags.push(tag_id);
            self.changed_values |= ChangedAttributes::Tags;
        }
    }

    pub fn remove_tag(&mut self, tag_id: TagId) {
        if let Some(index) = self.data.tags.iter().position(|id| *id == tag_id) {
            self.data.tags.remove(index);
            self.changed_values |= ChangedAttributes::Tags;
        }
    }

    /// Set the title of the document.
    pub fn set_title(&mut self, title: &str) {
        self.data.title = title.to_string();
        self.changed_values |= ChangedAttributes::Title;
    }

    /// Set the content of the document.
    pub fn set_content(&mut self, content: &str) {
        self.data.content = content.to_string();
        self.content_is_truncated = false;
        self.changed_values |= ChangedAttributes::Content;
    }

    /// Set a custom field for the document.
    pub fn set_custom_field(&mut self, field: CustomFieldId, value: &str) {
        for custom_field in &mut self.data.custom_fields {
            if custom_field.field == field {
                custom_field.value = value.to_string();
                self.changed_values |= ChangedAttributes::CustomFields;
                return;
            }
        }

        self.data.custom_fields.push(DocumentCustomField {
            field,
            value: value.to_string(),
        });
        self.changed_values |= ChangedAttributes::CustomFields;
    }

    /// Remove a custom field from the document.
    pub fn remove_custom_field(&mut self, field: CustomFieldId) {
        if let Some(index) = self
            .data
            .custom_fields
            .iter()
            .position(|custom_field| custom_field.field == field)
        {
            self.data.custom_fields.remove(index);
            self.changed_values |= ChangedAttributes::CustomFields;
        }
    }

    /// Returns `true` if the document has unsaved changes.
    #[inline]
    #[must_use]
    pub fn is_dirty(&self) -> bool {
        !self.changed_values.is_empty()
    }

    /// Refresh the document from the server.
    ///
    /// This will discard any local changes and replace them with the server's state.
    pub async fn reload(&mut self) -> Result<()> {
        let document_data = self
            .client
            .as_ref()
            .get_document_data_by_id(self.data.id)
            .await?;

        self.data = document_data;

        self.changed_values = BitFlags::empty();
        self.content_is_truncated = false;
        Ok(())
    }

    /// Update the document on the server.
    ///
    /// This applies the currently tracked local changes to the remote Paperless document.
    pub async fn patch(&mut self) -> Result<()> {
        if !self.is_dirty() {
            return Ok(());
        }

        let patch = PatchRequest {
            title: self
                .changed_values
                .contains(ChangedAttributes::Title)
                .then_some(self.data.title.clone()),

            content: self
                .changed_values
                .contains(ChangedAttributes::Content)
                .then_some(self.data.content.clone()),

            tags: self
                .changed_values
                .contains(ChangedAttributes::Tags)
                .then_some(self.data.tags.clone()),

            custom_fields: self
                .changed_values
                .contains(ChangedAttributes::CustomFields)
                .then_some(
                    self.data
                        .custom_fields
                        .iter()
                        .map(|field| DocumentCustomField {
                            field: field.field,
                            value: field.value.clone(),
                        })
                        .collect(),
                ),
            correspondent: self
                .changed_values
                .contains(ChangedAttributes::Correspondent)
                .then_some(self.data.correspondent)
                .flatten(),

            document_type: self
                .changed_values
                .contains(ChangedAttributes::DocumentType)
                .then_some(self.data.document_type)
                .flatten(),
        };

        self.client
            .request(
                Method::PATCH,
                &format!("/api/documents/{}/", self.data.id),
                Some(&serde_json::to_value(patch).expect("Patch request")),
            )
            .await?;

        self.changed_values = BitFlags::empty();
        Ok(())
    }

    /// Get the full content of the document, replacing any truncated content.
    pub async fn get_full_content(&mut self) -> Result<()> {
        if !self.content_is_truncated {
            return Ok(());
        }

        let doc = self.client.get_document_data_by_id(self.data.id).await?;
        self.data.content = doc.content;
        self.content_is_truncated = false;
        Ok(())
    }

    /// Download the document to a file.
    pub async fn download_to_file(&self, path: &Path) -> Result<()> {
        let resp = self
            .client
            .request(
                Method::GET,
                &format!("/api/documents/{}/download/", self.data.id),
                None,
            )
            .await?;

        if !resp.status().is_success() {
            return Err(Error::Other(format!(
                "Failed to download document: {}",
                resp.status()
            )));
        }

        let mut stream = StreamReader::new(
            resp.bytes_stream()
                .map_err(|e| io::Error::other(format!("Failed to read response body: {e}"))),
        );

        let mut file = tokio::fs::File::create(path)
            .await
            .map_err(|e| Error::Other(format!("Failed to create file: {e}")))?;

        tokio::io::copy(&mut stream, &mut file)
            .await
            .map_err(|e| Error::Other(format!("Failed to write file: {e}")))?;

        Ok(())
    }

    /// Download the document to a buffer.
    pub async fn download_to_buffer(&self) -> Result<Vec<u8>> {
        let resp = self
            .client
            .request(
                Method::GET,
                &format!("/api/documents/{}/download/", self.data.id),
                None,
            )
            .await?;

        if resp.status().is_success() {
            let bytes = resp
                .bytes()
                .await
                .map_err(|e| Error::Other(format!("Failed to read response body: {e}")))?;
            Ok(bytes.to_vec())
        } else {
            Err(Error::Other(format!(
                "Failed to download document: {}",
                resp.status()
            )))
        }
    }
}

impl Display for Content<'_> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Content::Full(text) => write!(f, "{text}"),
            Content::Truncated(text) => write!(f, "{text}..."),
        }
    }
}

impl AsRef<str> for Content<'_> {
    fn as_ref(&self) -> &str {
        match self {
            Content::Full(text) | Content::Truncated(text) => text,
        }
    }
}