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
// FIXME:(depricated) This here to keep backwards compat with apps that need the email logic here, USE apostle_client instead
// TODO Drop this whole file in 6.0.0
use colored::Colorize;
use dusa_collection_utils::{
core::errors::{
ErrorArrayItem, Errors,
},
core::logger::LogLevel,
core::types::stringy::Stringy,
log,
};
#[cfg(target_os = "linux")]
use serde::{Deserialize, Serialize};
#[cfg(target_os = "linux")]
use simple_comms::{
network::send_receive::{establish_connection_initiator, send_message}, protocol::{flags::ConnectionParams, message::ConnectionCtx, proto::Proto},
};
use std::fmt;
use tokio::net::TcpStream;
/// Default mail server address. Used if no custom address is provided in [`Email::send`].
const MAIL_ADDRESS: [&str; 2] = ["172.237.134.238:1827", "172.234.222.191:1827"];
// it can't get more pinned than this
const MAIL_SERVER_PUB: [u8; 32] =
[4, 174, 4, 246, 179, 162, 129, 67, 40, 38, 19, 206, 110, 212, 181, 156, 135, 163, 139, 211, 132, 147, 103, 80, 141, 7, 41, 46, 32, 80, 190, 84];
/// Represents an email message containing a subject and a body.
///
/// # Overview
///
/// - **Subject** (`Stringy`): The headline or topic of the email.
/// - **Body** (`Stringy`): The main content of the email.
///
/// This struct provides methods for creating, validating, converting to/from JSON,
/// and sending the email over a TCP stream to a mail server.
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct Email {
pub destination: Stringy,
/// The subject of the email message.
pub subject: Stringy,
/// The body content of the email message.
pub body: Stringy,
}
impl fmt::Display for Email {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(
f,
"To: {}, Subject: {}, Body: {}",
self.destination.bold().green(),
self.subject.bold().blue(),
self.body.bold().blue()
)
}
}
#[cfg(target_os = "linux")]
impl Email {
/// Creates a new `Email` instance with the provided subject and body.
///
/// # Arguments
///
/// * `subject` - A [`Stringy`] value representing the email's subject line.
/// * `body` - A [`Stringy`] value representing the email's main content.
///
/// # Example
/// ```rust
/// # use dusa_collection_utils::core::types::stringy::Stringy;
/// # use artisan_middleware::notifications::Email;
/// let destination = Stringy::from("dwhitfield@artisanhosting.net");
/// let subject = Stringy::from("Greetings");
/// let body = Stringy::from("Hello, how are you?");
/// let email = Email::new(destination, subject, body);
/// ```
pub fn new(destination: Stringy, subject: Stringy, body: Stringy) -> Self {
Email {
destination,
subject,
body,
}
}
/// Checks if the `Email` fields are valid (i.e., not empty).
///
/// # Returns
///
/// * `true` if both `subject` and `body` are non-empty.
/// * `false` otherwise.
///
/// # Example
/// ```rust
/// # use artisan_middleware::notifications::Email;
/// let email = Email::new("dwhitfield@artisanhosting.net".into(), "Subject".into(), "Body".into());
/// assert!(email.is_valid());
/// ```
pub fn is_valid(&self) -> bool {
!self.subject.is_empty() && !self.body.is_empty() && !self.destination.is_empty()
}
/// Converts this `Email` instance to a JSON string.
///
/// # Errors
///
/// Returns an [`ErrorArrayItem`] if the serialization fails.
///
/// # Example
/// ```rust
/// # use artisan_middleware::notifications::Email;
/// let email = Email::new("dwhitfield@artisanhosting.net".into(), "Subject".into(), "Body".into());
/// match email.to_json() {
/// Ok(json_str) => println!("JSON: {}", json_str),
/// Err(err) => eprintln!("Could not serialize email: {}", err),
/// }
/// ```
pub fn to_json(&self) -> Result<String, ErrorArrayItem> {
serde_json::to_string(self).map_err(ErrorArrayItem::from)
}
/// Creates an `Email` instance from a JSON string.
///
/// # Arguments
///
/// * `json_data` - The JSON representation of an `Email`.
///
/// # Errors
///
/// Returns an [`ErrorArrayItem`] if deserialization fails.
///
/// # Example
/// ```rust
/// # use artisan_middleware::notifications::Email;
/// let json_data = r#"{"destination":"dwhitfield@artisanhosting.net","subject":"Hello","body":"World"}"#;
/// match Email::from_json(json_data) {
/// Ok(email) => println!("Email Subject: {}", email.subject),
/// Err(err) => eprintln!("Could not deserialize email: {}", err),
/// }
/// ```
pub fn from_json(json_data: &str) -> Result<Self, ErrorArrayItem> {
serde_json::from_str(json_data).map_err(ErrorArrayItem::from)
}
/// Sends this `Email` over a TCP stream to the specified address, or to the default
/// [`MAIL_ADDRESS`] if `addr` is `None`.
///
/// # Arguments
///
/// * `addr` - An optional address in the format `host:port`. If `None`,
/// defaults to `MAIL_ADDRESS`.
///
/// # Return
///
/// Returns a [`UnifiedResult`] containing an [`OkWarning<()>`] on success,
/// or an [`ErrorArrayItem`] if the connection fails, the email data is invalid,
/// or the server indicates an error.
///
/// # Errors
///
/// - **`Errors::GeneralError`** if `subject` or `body` is empty.
/// - **`Errors::Network`** for network-related issues.
/// - **Other** potential errors based on serialization or internal server response codes.
///
/// # Example
/// ```rust
/// # use tokio::runtime::Runtime;
/// # use dusa_collection_utils::core::types::stringy::Stringy;
/// # use artisan_middleware::notifications::Email;
/// # let rt = Runtime::new().unwrap();
/// # rt.block_on(async {
/// let email = Email::new(Stringy::from("dwhitfield@artisanhosting.net"), Stringy::from("Test Subject"), Stringy::from("Test Body"));
/// let result = email.send(None).await; // uses MAIL_ADDRESS by default
/// match result {
/// Ok(_) => println!("Email sent successfully!"),
/// Err(err) => eprintln!("Failed to send email: {}", err),
/// }
/// # });
/// ```
#[rustfmt::skip]
pub async fn send(&self, addr: Option<&str>) -> Result<(), ErrorArrayItem> {
// Validate email fields
if !self.is_valid() {
return Err(ErrorArrayItem::new(
Errors::GeneralError,
"Invalid Email Data".to_owned(),
));
}
let mailserver_addr: &str = if let Some(addr) = addr {
addr
} else {
// TODO figure out how to randomise this
MAIL_ADDRESS[0]
};
let mut stream: TcpStream = match TcpStream::connect(mailserver_addr).await {
Ok(res) => {
log!{LogLevel::Trace, "Connected to: {:#?}", res.peer_addr()?};
Ok(res)
},
Err(e) => Err(ErrorArrayItem::new(Errors::ConnectionError,
format!("Failed to connect to mailserver: {}. {}", mailserver_addr, e))),
}?;
let mut conn: ConnectionCtx = establish_connection_initiator(&mut stream, &MAIL_SERVER_PUB, ConnectionParams::OPTIMIZED).await?;
let email_data: String = self.to_json()?;
let _: () = send_message(&mut stream, email_data, Proto::TCP, &mut conn).await?;
Ok(())
}
}