Skip to main content

isds/model/
message.rs

1use std::fmt;
2use std::str::FromStr;
3
4use bytes::Bytes;
5use jiff::Timestamp;
6use mime::Mime;
7
8use crate::error::{Error, Result};
9use crate::model::DataBoxId;
10
11/// An opaque ISDS message identifier.
12///
13/// Message IDs have no protocol-defined chronological order and must not be
14/// treated as integers. `Ord` is deterministic lexicographic ordering for
15/// container use only; it never represents chronology or pagination. With the
16/// `serde` feature, this serializes as a string and deserialization performs the
17/// same validation as [`MessageId::new`].
18#[derive(Clone, Eq, Hash, Ord, PartialEq, PartialOrd)]
19pub struct MessageId(String);
20
21impl MessageId {
22    /// Creates a non-empty message ID within the schema's 20-character limit.
23    pub fn new(value: impl Into<String>) -> Result<Self> {
24        let value = value.into();
25        if value.is_empty() || value.chars().count() > 20 {
26            return Err(Error::invalid_input(
27                "message_id",
28                "message ID must contain between 1 and 20 characters",
29            ));
30        }
31        Ok(Self(value))
32    }
33
34    /// Returns the identifier without changing its representation.
35    pub fn as_str(&self) -> &str {
36        &self.0
37    }
38}
39
40impl AsRef<str> for MessageId {
41    fn as_ref(&self) -> &str {
42        self.as_str()
43    }
44}
45
46impl fmt::Display for MessageId {
47    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
48        formatter.write_str(self.as_str())
49    }
50}
51
52impl fmt::Debug for MessageId {
53    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
54        fmt::Display::fmt(self, formatter)
55    }
56}
57
58impl FromStr for MessageId {
59    type Err = Error;
60
61    fn from_str(value: &str) -> Result<Self> {
62        Self::new(value)
63    }
64}
65
66impl TryFrom<&str> for MessageId {
67    type Error = Error;
68
69    fn try_from(value: &str) -> Result<Self> {
70        Self::new(value)
71    }
72}
73
74impl TryFrom<String> for MessageId {
75    type Error = Error;
76
77    fn try_from(value: String) -> Result<Self> {
78        Self::new(value)
79    }
80}
81
82impl From<MessageId> for String {
83    fn from(id: MessageId) -> Self {
84        id.0
85    }
86}
87
88#[cfg(feature = "serde")]
89impl serde::Serialize for MessageId {
90    fn serialize<S>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error>
91    where
92        S: serde::Serializer,
93    {
94        serializer.serialize_str(self.as_str())
95    }
96}
97
98#[cfg(feature = "serde")]
99impl<'de> serde::Deserialize<'de> for MessageId {
100    fn deserialize<D>(deserializer: D) -> std::result::Result<Self, D::Error>
101    where
102        D: serde::Deserializer<'de>,
103    {
104        let value = <String as serde::Deserialize>::deserialize(deserializer)?;
105        Self::new(value).map_err(serde::de::Error::custom)
106    }
107}
108
109/// Standard or large-message behavior for sending, downloading, and metadata.
110///
111/// Pass `Some(mode)` to force a mode, or `None` to select it automatically.
112/// Returned messages use the same optional representation when ISDS supplies it.
113#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
114#[non_exhaustive]
115pub enum MessageMode {
116    /// Use ordinary `CreateMessage` or `MessageDownload` operations.
117    Standard,
118    /// Use large-message upload/creation or `BigMessageDownload` operations.
119    Large,
120}
121
122/// ISDS attachment role.
123#[derive(Clone, Debug, Eq, Hash, PartialEq)]
124#[non_exhaustive]
125pub enum AttachmentType {
126    /// Main document (`main`).
127    Main,
128    /// Ordinary enclosure (`enclosure`).
129    Enclosure,
130    /// Signature attachment (`signature`).
131    Signature,
132    /// Metadata attachment (`meta`).
133    Meta,
134    /// A value not known by this version of the crate.
135    Other(String),
136}
137
138impl AttachmentType {
139    /// Returns the exact ISDS attribute value.
140    pub fn as_str(&self) -> &str {
141        match self {
142            Self::Main => "main",
143            Self::Enclosure => "enclosure",
144            Self::Signature => "signature",
145            Self::Meta => "meta",
146            Self::Other(value) => value,
147        }
148    }
149
150    pub(crate) fn from_raw(value: &str) -> Self {
151        match value {
152            "main" => Self::Main,
153            "enclosure" => Self::Enclosure,
154            "signature" => Self::Signature,
155            "meta" => Self::Meta,
156            value => Self::Other(value.to_owned()),
157        }
158    }
159}
160
161/// A fully buffered ordinary or large-volume message attachment.
162///
163/// SOAP base64 encoding increases the encoded size. MTOM/XOP streaming is not
164/// currently supported.
165#[derive(Clone)]
166pub struct Attachment {
167    description: String,
168    mime_type: Mime,
169    content: Bytes,
170    xml_element: bool,
171    meta_type: AttachmentType,
172    guid: Option<String>,
173    up_file_guid: Option<String>,
174    format: Option<String>,
175}
176
177impl Attachment {
178    /// Creates an enclosure with binary content.
179    pub fn new(description: impl Into<String>, mime_type: Mime, content: impl Into<Bytes>) -> Self {
180        Self {
181            description: description.into(),
182            mime_type,
183            content: content.into(),
184            xml_element: false,
185            meta_type: AttachmentType::Enclosure,
186            guid: None,
187            up_file_guid: None,
188            format: None,
189        }
190    }
191
192    /// Creates an attachment from the contents of an ISDS `dmXMLContent` element.
193    ///
194    /// When sent through this crate, the same XML bytes are encoded using the
195    /// schema's equivalent `dmEncodedContent` choice.
196    pub fn xml(description: impl Into<String>, mime_type: Mime, xml: impl Into<String>) -> Self {
197        let mut attachment = Self::new(description, mime_type, Bytes::from(xml.into()));
198        attachment.xml_element = true;
199        attachment
200    }
201
202    /// Creates a main-document attachment with binary content.
203    pub fn main(
204        description: impl Into<String>,
205        mime_type: Mime,
206        content: impl Into<Bytes>,
207    ) -> Self {
208        Self::new(description, mime_type, content).with_meta_type(AttachmentType::Main)
209    }
210
211    /// Changes the ISDS attachment role.
212    pub fn with_meta_type(mut self, meta_type: AttachmentType) -> Self {
213        self.meta_type = meta_type;
214        self
215    }
216
217    /// Sets the optional attachment GUID.
218    pub fn with_guid(mut self, guid: impl Into<String>) -> Self {
219        self.guid = Some(guid.into());
220        self
221    }
222
223    /// Sets the optional parent-signature attachment GUID.
224    pub fn with_up_file_guid(mut self, guid: impl Into<String>) -> Self {
225        self.up_file_guid = Some(guid.into());
226        self
227    }
228
229    /// Sets the optional `dmFormat` value.
230    ///
231    /// The current ISDS schema documents this attribute as unused.
232    pub fn with_format(mut self, format: impl Into<String>) -> Self {
233        self.format = Some(format.into());
234        self
235    }
236
237    /// Returns the attachment description or filename.
238    pub fn description(&self) -> &str {
239        &self.description
240    }
241
242    /// Returns the declared MIME type.
243    pub fn mime_type(&self) -> &Mime {
244        &self.mime_type
245    }
246
247    /// Returns the decoded attachment bytes.
248    pub fn content(&self) -> &Bytes {
249        &self.content
250    }
251
252    /// Returns the XML source when this attachment used `dmXMLContent`.
253    pub fn xml_content(&self) -> Option<&str> {
254        if self.xml_element {
255            std::str::from_utf8(&self.content).ok()
256        } else {
257            None
258        }
259    }
260
261    /// Returns the ISDS attachment role.
262    pub fn meta_type(&self) -> &AttachmentType {
263        &self.meta_type
264    }
265
266    /// Returns the optional attachment GUID.
267    pub fn guid(&self) -> Option<&str> {
268        self.guid.as_deref()
269    }
270
271    /// Returns the optional parent-signature attachment GUID.
272    pub fn up_file_guid(&self) -> Option<&str> {
273        self.up_file_guid.as_deref()
274    }
275
276    /// Returns the optional, currently unused `dmFormat` value.
277    pub fn format(&self) -> Option<&str> {
278        self.format.as_deref()
279    }
280}
281
282impl fmt::Debug for Attachment {
283    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
284        formatter
285            .debug_struct("Attachment")
286            .field("description", &self.description)
287            .field("mime_type", &self.mime_type)
288            .field("content_length", &self.content.len())
289            .field("xml_element", &self.xml_element)
290            .field("meta_type", &self.meta_type)
291            .field("guid", &self.guid)
292            .field("up_file_guid", &self.up_file_guid)
293            .field("format", &self.format)
294            .finish()
295    }
296}
297
298/// Optional metadata shared by outgoing and returned messages.
299#[derive(Clone, Debug, Default, Eq, PartialEq)]
300pub struct MessageMetadata {
301    /// Sender organizational unit name.
302    pub sender_org_unit: Option<String>,
303    /// Sender organizational unit number.
304    pub sender_org_unit_number: Option<i64>,
305    /// Recipient organizational unit name.
306    pub recipient_org_unit: Option<String>,
307    /// Recipient organizational unit number.
308    pub recipient_org_unit_number: Option<i64>,
309    /// Informational name for personal delivery; not the legal personal-delivery flag.
310    pub to_hands: Option<String>,
311    /// Recipient reference number.
312    pub recipient_reference_number: Option<String>,
313    /// Sender reference number.
314    pub sender_reference_number: Option<String>,
315    /// Recipient file identifier.
316    pub recipient_identification: Option<String>,
317    /// Sender file identifier.
318    pub sender_identification: Option<String>,
319    /// Legal-title law number.
320    pub legal_title_law: Option<i64>,
321    /// Legal-title year.
322    pub legal_title_year: Option<i64>,
323    /// Legal-title section.
324    pub legal_title_section: Option<String>,
325    /// Legal-title paragraph.
326    pub legal_title_paragraph: Option<String>,
327    /// Legal-title point.
328    pub legal_title_point: Option<String>,
329    /// Whether delivery is restricted to the recipient personally (`do vlastnĂ­ch rukou`).
330    pub personal_delivery: Option<bool>,
331    /// Whether substitute delivery is allowed.
332    pub allow_substitute_delivery: Option<bool>,
333}
334
335/// Controls whether the sender's databox ID is published to the recipient.
336#[derive(Clone, Copy, Debug, Eq, PartialEq)]
337pub struct PublishOwnId {
338    /// Whether the sender ID may be published.
339    pub enabled: bool,
340    /// Optional ISDS identification level.
341    pub identification_level: Option<i64>,
342}
343
344/// A message ready for automatic ordinary or large-volume sending.
345#[derive(Clone, Debug)]
346pub struct OutgoingMessage {
347    /// Recipient databox ID.
348    pub recipient: DataBoxId,
349    /// Message subject or annotation, at most 255 Unicode characters.
350    pub annotation: String,
351    /// Optional envelope metadata.
352    pub metadata: MessageMetadata,
353    /// Whether to send the message in public-authority mode.
354    pub public_authority_mode: Option<bool>,
355    /// Optional sender-ID publication setting.
356    pub publish_own_id: Option<PublishOwnId>,
357    /// Optional one-character `dmType` attribute.
358    pub message_type: Option<String>,
359    /// Attachments; ISDS requires at least one and permits at most 100.
360    pub attachments: Vec<Attachment>,
361}
362
363impl OutgoingMessage {
364    /// Creates a message with no attachments or optional metadata.
365    pub fn new(recipient: DataBoxId, annotation: impl Into<String>) -> Self {
366        Self {
367            recipient,
368            annotation: annotation.into(),
369            metadata: MessageMetadata::default(),
370            public_authority_mode: None,
371            publish_own_id: None,
372            message_type: None,
373            attachments: Vec::new(),
374        }
375    }
376
377    /// Appends an attachment.
378    pub fn with_attachment(mut self, attachment: Attachment) -> Self {
379        self.attachments.push(attachment);
380        self
381    }
382
383    /// Appends an attachment in place.
384    pub fn add_attachment(&mut self, attachment: Attachment) {
385        self.attachments.push(attachment);
386    }
387}
388
389/// Successful acknowledgement from `CreateMessage` or `CreateBigMessage`.
390///
391/// This confirms acceptance by ISDS, not delivery to the recipient.
392#[derive(Clone, Debug, Eq, PartialEq)]
393#[non_exhaustive]
394pub struct SentMessage {
395    /// ID assigned by ISDS.
396    pub id: MessageId,
397}
398
399/// A message state returned by ISDS.
400#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
401#[non_exhaustive]
402pub enum MessageState {
403    /// Submitted (`1`).
404    Submitted,
405    /// Submission timestamp assigned (`2`).
406    SubmissionTimestamped,
407    /// Rejected by antivirus processing (`3`).
408    AntivirusRejected,
409    /// Placed in the recipient databox but not necessarily legally delivered (`4`).
410    PlacedInRecipientBox,
411    /// Delivered by legal fiction (`5`).
412    DeliveredByFiction,
413    /// Delivered by authorized login (`6`).
414    DeliveredByLogin,
415    /// Marked as read (`7`).
416    Read,
417    /// Undeliverable (`8`).
418    Undeliverable,
419    /// Erased (`9`).
420    Erased,
421    /// Stored in DatovĂ˝ trezor (`10`).
422    InDataVault,
423    /// A state introduced after this crate version.
424    Unknown(i32),
425}
426
427impl MessageState {
428    /// Returns the numeric ISDS state code.
429    pub fn code(self) -> i32 {
430        match self {
431            Self::Submitted => 1,
432            Self::SubmissionTimestamped => 2,
433            Self::AntivirusRejected => 3,
434            Self::PlacedInRecipientBox => 4,
435            Self::DeliveredByFiction => 5,
436            Self::DeliveredByLogin => 6,
437            Self::Read => 7,
438            Self::Undeliverable => 8,
439            Self::Erased => 9,
440            Self::InDataVault => 10,
441            Self::Unknown(code) => code,
442        }
443    }
444
445    pub(crate) fn from_code(code: i32) -> Self {
446        match code {
447            1 => Self::Submitted,
448            2 => Self::SubmissionTimestamped,
449            3 => Self::AntivirusRejected,
450            4 => Self::PlacedInRecipientBox,
451            5 => Self::DeliveredByFiction,
452            6 => Self::DeliveredByLogin,
453            7 => Self::Read,
454            8 => Self::Undeliverable,
455            9 => Self::Erased,
456            10 => Self::InDataVault,
457            code => Self::Unknown(code),
458        }
459    }
460}
461
462/// Query and paging parameters for sent- or received-message lists.
463///
464/// `from` and `to` filter `dmDeliveryTime`, not submission or acceptance time.
465#[derive(Clone, Debug, Eq, PartialEq)]
466pub struct MessageListQuery {
467    /// Optional inclusive lower delivery-time bound.
468    pub from: Option<Timestamp>,
469    /// Optional upper delivery-time bound.
470    pub to: Option<Timestamp>,
471    /// Sender or recipient organizational-unit number, depending on the operation.
472    pub organization_unit_number: Option<i64>,
473    /// States to include; `None` sends the ISDS all-permitted-states value `-1`.
474    pub states: Option<Vec<MessageState>>,
475    /// One-based result offset. The default is `1`.
476    pub offset: u64,
477    /// Maximum number of records requested. The default is `1000`.
478    pub limit: u64,
479}
480
481impl Default for MessageListQuery {
482    fn default() -> Self {
483        Self {
484            from: None,
485            to: None,
486            organization_unit_number: None,
487            states: None,
488            offset: 1,
489            limit: 1000,
490        }
491    }
492}
493
494/// The common envelope returned in lists, downloads, and delivery information.
495#[derive(Clone, Debug, Eq, PartialEq)]
496#[non_exhaustive]
497pub struct MessageEnvelope {
498    /// Opaque message ID.
499    pub id: MessageId,
500    /// Sender databox ID.
501    pub sender_id: Option<DataBoxId>,
502    /// Sender display name.
503    pub sender: Option<String>,
504    /// Sender address.
505    pub sender_address: Option<String>,
506    /// Raw sender type code; newer fine-grained values are preserved.
507    pub sender_type: i32,
508    /// Recipient display name.
509    pub recipient: Option<String>,
510    /// Recipient address.
511    pub recipient_address: Option<String>,
512    /// Whether the recipient was ambiguous.
513    pub ambiguous_recipient: Option<bool>,
514    /// Recipient databox ID.
515    pub recipient_id: Option<DataBoxId>,
516    /// Message annotation.
517    pub annotation: Option<String>,
518    /// Shared optional message metadata.
519    pub metadata: MessageMetadata,
520}
521
522/// One entry in a sent- or received-message page.
523#[derive(Clone, Debug, Eq, PartialEq)]
524#[non_exhaustive]
525pub struct MessageRecord {
526    /// One-based ordinal within the returned result set.
527    pub ordinal: u32,
528    /// Message envelope.
529    pub envelope: MessageEnvelope,
530    /// Current message state.
531    pub state: MessageState,
532    /// Rounded attachment size in kilobytes.
533    pub attachment_size: Option<i64>,
534    /// Time at which the message entered the databox.
535    pub delivery_time: Option<Timestamp>,
536    /// Time of legal acceptance, if applicable.
537    pub acceptance_time: Option<Timestamp>,
538    /// Optional raw `dmType` attribute.
539    pub message_type: Option<String>,
540    /// Standard or large-message mode, if supplied by ISDS.
541    pub mode: Option<MessageMode>,
542    /// Optional raw special-message flag.
543    pub special_message_flag: Option<i64>,
544}
545
546/// One explicitly requested page of message records.
547#[derive(Clone, Debug, Eq, PartialEq)]
548#[non_exhaustive]
549pub struct MessagePage {
550    /// Returned records.
551    pub records: Vec<MessageRecord>,
552    /// One-based offset used for this page.
553    pub offset: u64,
554    /// Limit used for this page.
555    pub limit: u64,
556}
557
558/// Base64-decoded message hash and its optional algorithm identifier.
559#[derive(Clone, Eq, PartialEq)]
560#[non_exhaustive]
561pub struct MessageHash {
562    /// Raw hash bytes.
563    pub bytes: Bytes,
564    /// Hash algorithm name supplied by ISDS.
565    pub algorithm: Option<String>,
566}
567
568impl fmt::Debug for MessageHash {
569    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
570        formatter
571            .debug_struct("MessageHash")
572            .field("length", &self.bytes.len())
573            .field("algorithm", &self.algorithm)
574            .finish()
575    }
576}
577
578/// A downloaded ordinary or large-volume received message.
579#[derive(Clone, Debug)]
580#[non_exhaustive]
581pub struct Message {
582    /// Message envelope.
583    pub envelope: MessageEnvelope,
584    /// Decoded binary or XML attachments.
585    pub attachments: Vec<Attachment>,
586    /// ISDS-computed message hash.
587    pub hash: MessageHash,
588    /// Qualified timestamp token, if present.
589    pub qualified_timestamp: Option<Bytes>,
590    /// Time at which the message entered the databox.
591    pub delivery_time: Option<Timestamp>,
592    /// Time of legal acceptance, if applicable.
593    pub acceptance_time: Option<Timestamp>,
594    /// Current message state.
595    pub state: MessageState,
596    /// Rounded attachment size in kilobytes.
597    pub attachment_size: Option<i64>,
598    /// Optional raw `dmType` attribute.
599    pub message_type: Option<String>,
600    /// Optional raw special-message flag.
601    pub special_message_flag: Option<i64>,
602    /// Standard or large-message mode, if supplied by ISDS.
603    pub mode: Option<MessageMode>,
604    /// Total attachment count supplied for a large-volume message.
605    pub attachment_count: Option<u32>,
606}
607
608/// A standalone received-message envelope returned by `MessageEnvelopeDownload`.
609///
610/// Unlike [`Message`], this result intentionally contains no attachment content.
611#[derive(Clone, Debug)]
612#[non_exhaustive]
613pub struct MessageEnvelopeDetails {
614    /// Message envelope.
615    pub envelope: MessageEnvelope,
616    /// ISDS-computed message hash.
617    pub hash: MessageHash,
618    /// Qualified timestamp token.
619    pub qualified_timestamp: Bytes,
620    /// Time at which the message entered the databox.
621    pub delivery_time: Option<Timestamp>,
622    /// Time of legal acceptance, if applicable.
623    pub acceptance_time: Option<Timestamp>,
624    /// Current message state.
625    pub state: MessageState,
626    /// Rounded attachment size in kilobytes.
627    pub attachment_size: Option<i64>,
628    /// Optional raw `dmType` attribute.
629    pub message_type: Option<String>,
630    /// Standard or large-message mode, if supplied by ISDS.
631    pub mode: Option<MessageMode>,
632    /// Total attachment count supplied for a large-volume message.
633    pub attachment_count: Option<u32>,
634    /// Optional raw special-message flag.
635    pub special_message_flag: Option<i64>,
636}
637
638/// One event in a message's delivery history.
639#[derive(Clone, Debug, Eq, PartialEq)]
640#[non_exhaustive]
641pub struct DeliveryEvent {
642    /// Event timestamp.
643    pub time: Option<Timestamp>,
644    /// Human-readable event description.
645    pub description: Option<String>,
646}
647
648/// Unsigned delivery information for a sent or received message.
649#[derive(Clone, Debug)]
650#[non_exhaustive]
651pub struct DeliveryInfo {
652    /// Message envelope without attachments.
653    pub envelope: MessageEnvelope,
654    /// ISDS-computed message hash.
655    pub hash: MessageHash,
656    /// Qualified timestamp token.
657    pub qualified_timestamp: Bytes,
658    /// Time at which the message entered the databox.
659    pub delivery_time: Option<Timestamp>,
660    /// Time of legal acceptance, if applicable.
661    pub acceptance_time: Option<Timestamp>,
662    /// Current message state.
663    pub state: MessageState,
664    /// Ordered delivery events.
665    pub events: Vec<DeliveryEvent>,
666}