use std::fmt;
use std::str::FromStr;
use bytes::Bytes;
use jiff::Timestamp;
use mime::Mime;
use crate::error::{Error, Result};
use crate::model::DataBoxId;
#[derive(Clone, Eq, Hash, Ord, PartialEq, PartialOrd)]
pub struct MessageId(String);
impl MessageId {
pub fn new(value: impl Into<String>) -> Result<Self> {
let value = value.into();
if value.is_empty() || value.chars().count() > 20 {
return Err(Error::invalid_input(
"message_id",
"message ID must contain between 1 and 20 characters",
));
}
Ok(Self(value))
}
pub fn as_str(&self) -> &str {
&self.0
}
}
impl AsRef<str> for MessageId {
fn as_ref(&self) -> &str {
self.as_str()
}
}
impl fmt::Display for MessageId {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter.write_str(self.as_str())
}
}
impl fmt::Debug for MessageId {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt::Display::fmt(self, formatter)
}
}
impl FromStr for MessageId {
type Err = Error;
fn from_str(value: &str) -> Result<Self> {
Self::new(value)
}
}
impl TryFrom<&str> for MessageId {
type Error = Error;
fn try_from(value: &str) -> Result<Self> {
Self::new(value)
}
}
impl TryFrom<String> for MessageId {
type Error = Error;
fn try_from(value: String) -> Result<Self> {
Self::new(value)
}
}
impl From<MessageId> for String {
fn from(id: MessageId) -> Self {
id.0
}
}
#[cfg(feature = "serde")]
impl serde::Serialize for MessageId {
fn serialize<S>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error>
where
S: serde::Serializer,
{
serializer.serialize_str(self.as_str())
}
}
#[cfg(feature = "serde")]
impl<'de> serde::Deserialize<'de> for MessageId {
fn deserialize<D>(deserializer: D) -> std::result::Result<Self, D::Error>
where
D: serde::Deserializer<'de>,
{
let value = <String as serde::Deserialize>::deserialize(deserializer)?;
Self::new(value).map_err(serde::de::Error::custom)
}
}
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
#[non_exhaustive]
pub enum MessageMode {
Standard,
Large,
}
#[derive(Clone, Debug, Eq, Hash, PartialEq)]
#[non_exhaustive]
pub enum AttachmentType {
Main,
Enclosure,
Signature,
Meta,
Other(String),
}
impl AttachmentType {
pub fn as_str(&self) -> &str {
match self {
Self::Main => "main",
Self::Enclosure => "enclosure",
Self::Signature => "signature",
Self::Meta => "meta",
Self::Other(value) => value,
}
}
pub(crate) fn from_raw(value: &str) -> Self {
match value {
"main" => Self::Main,
"enclosure" => Self::Enclosure,
"signature" => Self::Signature,
"meta" => Self::Meta,
value => Self::Other(value.to_owned()),
}
}
}
#[derive(Clone)]
pub struct Attachment {
description: String,
mime_type: Mime,
content: Bytes,
xml_element: bool,
meta_type: AttachmentType,
guid: Option<String>,
up_file_guid: Option<String>,
format: Option<String>,
}
impl Attachment {
pub fn new(description: impl Into<String>, mime_type: Mime, content: impl Into<Bytes>) -> Self {
Self {
description: description.into(),
mime_type,
content: content.into(),
xml_element: false,
meta_type: AttachmentType::Enclosure,
guid: None,
up_file_guid: None,
format: None,
}
}
pub fn xml(description: impl Into<String>, mime_type: Mime, xml: impl Into<String>) -> Self {
let mut attachment = Self::new(description, mime_type, Bytes::from(xml.into()));
attachment.xml_element = true;
attachment
}
pub fn main(
description: impl Into<String>,
mime_type: Mime,
content: impl Into<Bytes>,
) -> Self {
Self::new(description, mime_type, content).with_meta_type(AttachmentType::Main)
}
pub fn with_meta_type(mut self, meta_type: AttachmentType) -> Self {
self.meta_type = meta_type;
self
}
pub fn with_guid(mut self, guid: impl Into<String>) -> Self {
self.guid = Some(guid.into());
self
}
pub fn with_up_file_guid(mut self, guid: impl Into<String>) -> Self {
self.up_file_guid = Some(guid.into());
self
}
pub fn with_format(mut self, format: impl Into<String>) -> Self {
self.format = Some(format.into());
self
}
pub fn description(&self) -> &str {
&self.description
}
pub fn mime_type(&self) -> &Mime {
&self.mime_type
}
pub fn content(&self) -> &Bytes {
&self.content
}
pub fn xml_content(&self) -> Option<&str> {
if self.xml_element {
std::str::from_utf8(&self.content).ok()
} else {
None
}
}
pub fn meta_type(&self) -> &AttachmentType {
&self.meta_type
}
pub fn guid(&self) -> Option<&str> {
self.guid.as_deref()
}
pub fn up_file_guid(&self) -> Option<&str> {
self.up_file_guid.as_deref()
}
pub fn format(&self) -> Option<&str> {
self.format.as_deref()
}
}
impl fmt::Debug for Attachment {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter
.debug_struct("Attachment")
.field("description", &self.description)
.field("mime_type", &self.mime_type)
.field("content_length", &self.content.len())
.field("xml_element", &self.xml_element)
.field("meta_type", &self.meta_type)
.field("guid", &self.guid)
.field("up_file_guid", &self.up_file_guid)
.field("format", &self.format)
.finish()
}
}
#[derive(Clone, Debug, Default, Eq, PartialEq)]
pub struct MessageMetadata {
pub sender_org_unit: Option<String>,
pub sender_org_unit_number: Option<i64>,
pub recipient_org_unit: Option<String>,
pub recipient_org_unit_number: Option<i64>,
pub to_hands: Option<String>,
pub recipient_reference_number: Option<String>,
pub sender_reference_number: Option<String>,
pub recipient_identification: Option<String>,
pub sender_identification: Option<String>,
pub legal_title_law: Option<i64>,
pub legal_title_year: Option<i64>,
pub legal_title_section: Option<String>,
pub legal_title_paragraph: Option<String>,
pub legal_title_point: Option<String>,
pub personal_delivery: Option<bool>,
pub allow_substitute_delivery: Option<bool>,
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct PublishOwnId {
pub enabled: bool,
pub identification_level: Option<i64>,
}
#[derive(Clone, Debug)]
pub struct OutgoingMessage {
pub recipient: DataBoxId,
pub annotation: String,
pub metadata: MessageMetadata,
pub public_authority_mode: Option<bool>,
pub publish_own_id: Option<PublishOwnId>,
pub message_type: Option<String>,
pub attachments: Vec<Attachment>,
}
impl OutgoingMessage {
pub fn new(recipient: DataBoxId, annotation: impl Into<String>) -> Self {
Self {
recipient,
annotation: annotation.into(),
metadata: MessageMetadata::default(),
public_authority_mode: None,
publish_own_id: None,
message_type: None,
attachments: Vec::new(),
}
}
pub fn with_attachment(mut self, attachment: Attachment) -> Self {
self.attachments.push(attachment);
self
}
pub fn add_attachment(&mut self, attachment: Attachment) {
self.attachments.push(attachment);
}
}
#[derive(Clone, Debug, Eq, PartialEq)]
#[non_exhaustive]
pub struct SentMessage {
pub id: MessageId,
}
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
#[non_exhaustive]
pub enum MessageState {
Submitted,
SubmissionTimestamped,
AntivirusRejected,
PlacedInRecipientBox,
DeliveredByFiction,
DeliveredByLogin,
Read,
Undeliverable,
Erased,
InDataVault,
Unknown(i32),
}
impl MessageState {
pub fn code(self) -> i32 {
match self {
Self::Submitted => 1,
Self::SubmissionTimestamped => 2,
Self::AntivirusRejected => 3,
Self::PlacedInRecipientBox => 4,
Self::DeliveredByFiction => 5,
Self::DeliveredByLogin => 6,
Self::Read => 7,
Self::Undeliverable => 8,
Self::Erased => 9,
Self::InDataVault => 10,
Self::Unknown(code) => code,
}
}
pub(crate) fn from_code(code: i32) -> Self {
match code {
1 => Self::Submitted,
2 => Self::SubmissionTimestamped,
3 => Self::AntivirusRejected,
4 => Self::PlacedInRecipientBox,
5 => Self::DeliveredByFiction,
6 => Self::DeliveredByLogin,
7 => Self::Read,
8 => Self::Undeliverable,
9 => Self::Erased,
10 => Self::InDataVault,
code => Self::Unknown(code),
}
}
}
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct MessageListQuery {
pub from: Option<Timestamp>,
pub to: Option<Timestamp>,
pub organization_unit_number: Option<i64>,
pub states: Option<Vec<MessageState>>,
pub offset: u64,
pub limit: u64,
}
impl Default for MessageListQuery {
fn default() -> Self {
Self {
from: None,
to: None,
organization_unit_number: None,
states: None,
offset: 1,
limit: 1000,
}
}
}
#[derive(Clone, Debug, Eq, PartialEq)]
#[non_exhaustive]
pub struct MessageEnvelope {
pub id: MessageId,
pub sender_id: Option<DataBoxId>,
pub sender: Option<String>,
pub sender_address: Option<String>,
pub sender_type: i32,
pub recipient: Option<String>,
pub recipient_address: Option<String>,
pub ambiguous_recipient: Option<bool>,
pub recipient_id: Option<DataBoxId>,
pub annotation: Option<String>,
pub metadata: MessageMetadata,
}
#[derive(Clone, Debug, Eq, PartialEq)]
#[non_exhaustive]
pub struct MessageRecord {
pub ordinal: u32,
pub envelope: MessageEnvelope,
pub state: MessageState,
pub attachment_size: Option<i64>,
pub delivery_time: Option<Timestamp>,
pub acceptance_time: Option<Timestamp>,
pub message_type: Option<String>,
pub mode: Option<MessageMode>,
pub special_message_flag: Option<i64>,
}
#[derive(Clone, Debug, Eq, PartialEq)]
#[non_exhaustive]
pub struct MessagePage {
pub records: Vec<MessageRecord>,
pub offset: u64,
pub limit: u64,
}
#[derive(Clone, Eq, PartialEq)]
#[non_exhaustive]
pub struct MessageHash {
pub bytes: Bytes,
pub algorithm: Option<String>,
}
impl fmt::Debug for MessageHash {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter
.debug_struct("MessageHash")
.field("length", &self.bytes.len())
.field("algorithm", &self.algorithm)
.finish()
}
}
#[derive(Clone, Debug)]
#[non_exhaustive]
pub struct Message {
pub envelope: MessageEnvelope,
pub attachments: Vec<Attachment>,
pub hash: MessageHash,
pub qualified_timestamp: Option<Bytes>,
pub delivery_time: Option<Timestamp>,
pub acceptance_time: Option<Timestamp>,
pub state: MessageState,
pub attachment_size: Option<i64>,
pub message_type: Option<String>,
pub special_message_flag: Option<i64>,
pub mode: Option<MessageMode>,
pub attachment_count: Option<u32>,
}
#[derive(Clone, Debug)]
#[non_exhaustive]
pub struct MessageEnvelopeDetails {
pub envelope: MessageEnvelope,
pub hash: MessageHash,
pub qualified_timestamp: Bytes,
pub delivery_time: Option<Timestamp>,
pub acceptance_time: Option<Timestamp>,
pub state: MessageState,
pub attachment_size: Option<i64>,
pub message_type: Option<String>,
pub mode: Option<MessageMode>,
pub attachment_count: Option<u32>,
pub special_message_flag: Option<i64>,
}
#[derive(Clone, Debug, Eq, PartialEq)]
#[non_exhaustive]
pub struct DeliveryEvent {
pub time: Option<Timestamp>,
pub description: Option<String>,
}
#[derive(Clone, Debug)]
#[non_exhaustive]
pub struct DeliveryInfo {
pub envelope: MessageEnvelope,
pub hash: MessageHash,
pub qualified_timestamp: Bytes,
pub delivery_time: Option<Timestamp>,
pub acceptance_time: Option<Timestamp>,
pub state: MessageState,
pub events: Vec<DeliveryEvent>,
}