Struct mailpot::models::MailingList
source · pub struct MailingList {
pub pk: i64,
pub name: String,
pub id: String,
pub address: String,
pub topics: Vec<String>,
pub description: Option<String>,
pub archive_url: Option<String>,
}
Expand description
A mailing list entry.
Fields§
§pk: i64
Database primary key.
name: String
Mailing list name.
id: String
Mailing list ID (what appears in the subject tag, e.g. [mailing-list] New post!
).
address: String
Mailing list e-mail address.
topics: Vec<String>
Discussion topics.
description: Option<String>
Mailing list description.
archive_url: Option<String>
Mailing list archive URL.
Implementations§
source§impl MailingList
impl MailingList
sourcepub fn display_name(&self) -> String
pub fn display_name(&self) -> String
Mailing list display name.
Example
assert_eq!(
&list.display_name(),
"\"foobar chat\" <foo-chat@example.com>"
);
Examples found in repository?
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
fn inner_post(&self, env: &Envelope, raw: &[u8], _dry_run: bool) -> Result<()> {
trace!("Received envelope to post: {:#?}", &env);
let tos = env.to().to_vec();
if tos.is_empty() {
return Err("Envelope To: field is empty!".into());
}
if env.from().is_empty() {
return Err("Envelope From: field is empty!".into());
}
let mut lists = self.lists()?;
if lists.is_empty() {
return Err("No active mailing lists found.".into());
}
let prev_list_len = lists.len();
for t in &tos {
if let Some((addr, subaddr)) = t.subaddress("+") {
lists.retain(|list| {
if !addr.contains_address(&list.address()) {
return true;
}
if let Err(err) = ListRequest::try_from((subaddr.as_str(), env))
.and_then(|req| self.request(list, req, env, raw))
{
info!("Processing request returned error: {}", err);
}
false
});
if lists.len() != prev_list_len {
// Was request, handled above.
return Ok(());
}
}
}
lists.retain(|list| {
trace!(
"Is post related to list {}? {}",
&list,
tos.iter().any(|a| a.contains_address(&list.address()))
);
tos.iter().any(|a| a.contains_address(&list.address()))
});
if lists.is_empty() {
return Err(format!(
"No relevant mailing list found for these addresses: {:?}",
tos
)
.into());
}
trace!("Configuration is {:#?}", &self.conf);
for mut list in lists {
trace!("Examining list {}", list.display_name());
let filters = self.list_filters(&list);
let subscriptions = self.list_subscriptions(list.pk)?;
let owners = self.list_owners(list.pk)?;
trace!("List subscriptions {:#?}", &subscriptions);
let mut list_ctx = ListContext {
post_policy: self.list_post_policy(list.pk)?,
subscription_policy: self.list_subscription_policy(list.pk)?,
list_owners: &owners,
subscriptions: &subscriptions,
scheduled_jobs: vec![],
filter_settings: self.get_settings(list.pk)?,
list: &mut list,
};
let mut post = PostEntry {
message_id: env.message_id().clone(),
from: env.from()[0].clone(),
bytes: raw.to_vec(),
to: env.to().to_vec(),
action: PostAction::Hold,
};
let result = filters
.into_iter()
.fold(Ok((&mut post, &mut list_ctx)), |p, f| {
p.and_then(|(p, c)| f.feed(p, c))
});
trace!("result {:#?}", result);
let PostEntry { bytes, action, .. } = post;
trace!("Action is {:#?}", action);
let post_env = melib::Envelope::from_bytes(&bytes, None)?;
match action {
PostAction::Accept => {
let _post_pk = self.insert_post(list_ctx.list.pk, &bytes, &post_env)?;
trace!("post_pk is {:#?}", _post_pk);
for job in list_ctx.scheduled_jobs.iter() {
trace!("job is {:#?}", &job);
if let crate::mail::MailJob::Send { recipients } = job {
trace!("recipients: {:?}", &recipients);
if recipients.is_empty() {
trace!("list has no recipients");
}
for recipient in recipients {
let mut env = post_env.clone();
env.set_to(melib::smallvec::smallvec![recipient.clone()]);
self.insert_to_queue(QueueEntry::new(
Queue::Out,
Some(list.pk),
Some(Cow::Owned(env)),
&bytes,
None,
)?)?;
}
}
}
}
PostAction::Reject { reason } => {
log::info!("PostAction::Reject {{ reason: {} }}", reason);
for f in env.from() {
/* send error notice to e-mail sender */
self.send_reply_with_list_template(
TemplateRenderContext {
template: Template::GENERIC_FAILURE,
default_fn: Some(Template::default_generic_failure),
list: &list,
context: minijinja::context! {
list => &list,
subject => format!("Your post to {} was rejected.", list.id),
details => &reason,
},
queue: Queue::Out,
comment: format!("PostAction::Reject {{ reason: {} }}", reason)
.into(),
},
std::iter::once(Cow::Borrowed(f)),
)?;
}
/* error handled by notifying submitter */
return Ok(());
}
PostAction::Defer { reason } => {
trace!("PostAction::Defer {{ reason: {} }}", reason);
for f in env.from() {
/* send error notice to e-mail sender */
self.send_reply_with_list_template(
TemplateRenderContext {
template: Template::GENERIC_FAILURE,
default_fn: Some(Template::default_generic_failure),
list: &list,
context: minijinja::context! {
list => &list,
subject => format!("Your post to {} was deferred.", list.id),
details => &reason,
},
queue: Queue::Out,
comment: format!("PostAction::Defer {{ reason: {} }}", reason)
.into(),
},
std::iter::once(Cow::Borrowed(f)),
)?;
}
self.insert_to_queue(QueueEntry::new(
Queue::Deferred,
Some(list.pk),
Some(Cow::Borrowed(&post_env)),
&bytes,
Some(format!("PostAction::Defer {{ reason: {} }}", reason)),
)?)?;
return Ok(());
}
PostAction::Hold => {
trace!("PostAction::Hold");
self.insert_to_queue(QueueEntry::new(
Queue::Hold,
Some(list.pk),
Some(Cow::Borrowed(&post_env)),
&bytes,
Some("PostAction::Hold".to_string()),
)?)?;
return Ok(());
}
}
}
Ok(())
}
sourcepub fn request_subaddr(&self) -> String
pub fn request_subaddr(&self) -> String
Examples found in repository?
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 430
pub fn help_header(&self) -> Option<String> {
Some(format!("<mailto:{}?subject=help>", self.request_subaddr()))
}
/// Value of `List-Post` header.
///
/// See RFC2369 Section 3.4: <https://www.rfc-editor.org/rfc/rfc2369#section-3.4>
///
/// # Example
///
/// ```rust
/// # fn main() -> mailpot::Result<()> {
#[doc = include_str!("./doctests/db_setup.rs.inc")]
/// assert_eq!(&list.post_header(None).unwrap(), "NO");
/// assert_eq!(
/// &list.post_header(Some(&post_policy)).unwrap(),
/// "<mailto:foo-chat@example.com>"
/// );
/// # Ok(())
/// # }
pub fn post_header(&self, policy: Option<&PostPolicy>) -> Option<String> {
Some(policy.map_or_else(
|| "NO".to_string(),
|p| {
if p.announce_only {
"NO".to_string()
} else {
format!("<mailto:{}>", self.address)
}
},
))
}
/// Value of `List-Unsubscribe` header.
///
/// See RFC2369 Section 3.2: <https://www.rfc-editor.org/rfc/rfc2369#section-3.2>
///
/// # Example
///
/// ```rust
/// # fn main() -> mailpot::Result<()> {
#[doc = include_str!("./doctests/db_setup.rs.inc")]
/// assert_eq!(
/// &list.unsubscribe_header(Some(&sub_policy)).unwrap(),
/// "<mailto:foo-chat+request@example.com?subject=unsubscribe>"
/// );
/// # Ok(())
/// # }
pub fn unsubscribe_header(&self, policy: Option<&SubscriptionPolicy>) -> Option<String> {
policy.map_or_else(
|| None,
|_| {
Some(format!(
"<mailto:{}?subject=unsubscribe>",
self.request_subaddr()
))
},
)
}
/// Value of `List-Subscribe` header.
///
/// See RFC2369 Section 3.3: <https://www.rfc-editor.org/rfc/rfc2369#section-3.3>
///
/// # Example
///
/// ```rust
/// # fn main() -> mailpot::Result<()> {
#[doc = include_str!("./doctests/db_setup.rs.inc")]
/// assert_eq!(
/// &list.subscribe_header(Some(&sub_policy)).unwrap(),
/// "<mailto:foo-chat+request@example.com?subject=subscribe>",
/// );
/// # Ok(())
/// # }
/// ```
pub fn subscribe_header(&self, policy: Option<&SubscriptionPolicy>) -> Option<String> {
policy.map_or_else(
|| None,
|_| {
Some(format!(
"<mailto:{}?subject=subscribe>",
self.request_subaddr()
))
},
)
}
/// Value of `List-Archive` header.
///
/// See RFC2369 Section 3.6: <https://www.rfc-editor.org/rfc/rfc2369#section-3.6>
///
/// # Example
///
/// ```rust
/// # fn main() -> mailpot::Result<()> {
#[doc = include_str!("./doctests/db_setup.rs.inc")]
/// assert_eq!(
/// &list.archive_header().unwrap(),
/// "<https://lists.example.com>"
/// );
/// # Ok(())
/// # }
/// ```
pub fn archive_header(&self) -> Option<String> {
self.archive_url.as_ref().map(|url| format!("<{}>", url))
}
/// List address as a [`melib::Address`]
pub fn address(&self) -> Address {
Address::new(Some(self.name.clone()), self.address.clone())
}
/// List unsubscribe action as a [`MailtoAddress`](super::MailtoAddress).
pub fn unsubscription_mailto(&self) -> MailtoAddress {
MailtoAddress {
address: self.request_subaddr(),
subject: Some("unsubscribe".to_string()),
}
}
/// List subscribe action as a [`MailtoAddress`](super::MailtoAddress).
pub fn subscription_mailto(&self) -> MailtoAddress {
MailtoAddress {
address: self.request_subaddr(),
subject: Some("subscribe".to_string()),
}
}
/// List owner as a [`MailtoAddress`](super::MailtoAddress).
pub fn owner_mailto(&self) -> MailtoAddress {
let p = self.address.split('@').collect::<Vec<&str>>();
MailtoAddress {
address: format!("{}+owner@{}", p[0], p[1]),
subject: None,
}
}
/// List archive url value.
pub fn archive_url(&self) -> Option<&str> {
self.archive_url.as_deref()
}
/// Insert all available list headers.
pub fn insert_headers(
&self,
draft: &mut melib::Draft,
post_policy: Option<&PostPolicy>,
subscription_policy: Option<&SubscriptionPolicy>,
) {
for (hdr, val) in [
("List-Id", Some(self.id_header())),
("List-Help", self.help_header()),
("List-Post", self.post_header(post_policy)),
(
"List-Unsubscribe",
self.unsubscribe_header(subscription_policy),
),
("List-Subscribe", self.subscribe_header(subscription_policy)),
("List-Archive", self.archive_header()),
] {
if let Some(val) = val {
draft
.headers
.insert(melib::HeaderName::new_unchecked(hdr), val);
}
}
}
/// Generate help e-mail body containing information on how to subscribe,
/// unsubscribe, post and how to contact the list owners.
pub fn generate_help_email(
&self,
post_policy: Option<&PostPolicy>,
subscription_policy: Option<&SubscriptionPolicy>,
) -> String {
format!(
"Help for {list_name}\n\n{subscribe}\n\n{post}\n\nTo contact the list owners, send an \
e-mail to {contact}\n",
list_name = self.name,
subscribe = subscription_policy.map_or(
Cow::Borrowed("This list is not open to subscriptions."),
|p| if p.open {
Cow::Owned(format!(
"Anyone can subscribe without restrictions. Send an e-mail to {} with the \
subject `subscribe`.",
self.request_subaddr(),
))
} else if p.manual {
Cow::Borrowed(
"The list owners must manually add you to the list of subscriptions.",
)
} else if p.request {
Cow::Owned(format!(
"Anyone can request to subscribe. Send an e-mail to {} with the subject \
`subscribe` and a confirmation will be sent to you when your request is \
approved.",
self.request_subaddr(),
))
} else {
Cow::Borrowed("Please contact the list owners for details on how to subscribe.")
}
),
post = post_policy.map_or(Cow::Borrowed("This list does not allow posting."), |p| {
if p.announce_only {
Cow::Borrowed(
"This list is announce only, which means that you can only receive posts \
from the list owners.",
)
} else if p.subscription_only {
Cow::Owned(format!(
"Only list subscriptions can post to this list. Send your post to {}",
self.address
))
} else if p.approval_needed {
Cow::Owned(format!(
"Anyone can post, but approval from list owners is required if they are \
not subscribed. Send your post to {}",
self.address
))
} else {
Cow::Borrowed("This list does not allow posting.")
}
}),
contact = self.owner_mailto().address,
)
}
More examples
719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768
pub fn send_reply_with_list_template<'ctx, F: Fn() -> Template>(
&self,
render_context: TemplateRenderContext<'ctx, F>,
recipients: impl Iterator<Item = Cow<'ctx, melib::Address>>,
) -> Result<()> {
let TemplateRenderContext {
template,
default_fn,
list,
context,
queue,
comment,
} = render_context;
let post_policy = self.list_post_policy(list.pk)?;
let subscription_policy = self.list_subscription_policy(list.pk)?;
let templ = self
.fetch_template(template, Some(list.pk))?
.map(DbVal::into_inner)
.or_else(|| default_fn.map(|f| f()))
.ok_or_else(|| -> crate::Error {
format!("Template with name {template:?} was not found.").into()
})?;
let mut draft = templ.render(context)?;
draft.headers.insert(
melib::HeaderName::new_unchecked("From"),
list.request_subaddr(),
);
for addr in recipients {
let mut draft = draft.clone();
draft
.headers
.insert(melib::HeaderName::new_unchecked("To"), addr.to_string());
list.insert_headers(
&mut draft,
post_policy.as_deref(),
subscription_policy.as_deref(),
);
self.insert_to_queue(QueueEntry::new(
queue,
Some(list.pk),
None,
draft.finalise()?.as_bytes(),
Some(comment.to_string()),
)?)?;
}
Ok(())
}
sourcepub fn id_header(&self) -> String
pub fn id_header(&self) -> String
Value of List-Id
header.
See RFC2919 Section 3: https://www.rfc-editor.org/rfc/rfc2919
Example
assert_eq!(
&list.id_header(),
"Hello world, from foo-chat list <foo-chat.example.com>");
Examples found in repository?
348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371
pub fn insert_headers(
&self,
draft: &mut melib::Draft,
post_policy: Option<&PostPolicy>,
subscription_policy: Option<&SubscriptionPolicy>,
) {
for (hdr, val) in [
("List-Id", Some(self.id_header())),
("List-Help", self.help_header()),
("List-Post", self.post_header(post_policy)),
(
"List-Unsubscribe",
self.unsubscribe_header(subscription_policy),
),
("List-Subscribe", self.subscribe_header(subscription_policy)),
("List-Archive", self.archive_header()),
] {
if let Some(val) = val {
draft
.headers
.insert(melib::HeaderName::new_unchecked(hdr), val);
}
}
}
More examples
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
fn feed<'p, 'list>(
self: Box<Self>,
post: &'p mut PostEntry,
ctx: &'p mut ListContext<'list>,
) -> std::result::Result<(&'p mut PostEntry, &'p mut ListContext<'list>), ()> {
trace!("Running AddListHeaders filter");
let (mut headers, body) = melib::email::parser::mail(&post.bytes).unwrap();
let sender = format!("<{}>", ctx.list.address);
headers.push((&b"Sender"[..], sender.as_bytes()));
let list_id = Some(ctx.list.id_header());
let list_help = ctx.list.help_header();
let list_post = ctx.list.post_header(ctx.post_policy.as_deref());
let list_unsubscribe = ctx
.list
.unsubscribe_header(ctx.subscription_policy.as_deref());
let list_subscribe = ctx
.list
.subscribe_header(ctx.subscription_policy.as_deref());
let list_archive = ctx.list.archive_header();
for (hdr, val) in [
(b"List-Id".as_slice(), &list_id),
(b"List-Help".as_slice(), &list_help),
(b"List-Post".as_slice(), &list_post),
(b"List-Unsubscribe".as_slice(), &list_unsubscribe),
(b"List-Subscribe".as_slice(), &list_subscribe),
(b"List-Archive".as_slice(), &list_archive),
] {
if let Some(val) = val {
headers.push((hdr, val.as_bytes()));
}
}
let mut new_vec = Vec::with_capacity(
headers
.iter()
.map(|(h, v)| h.len() + v.len() + ": \r\n".len())
.sum::<usize>()
+ "\r\n\r\n".len()
+ body.len(),
);
for (h, v) in headers {
new_vec.extend_from_slice(h);
new_vec.extend_from_slice(b": ");
new_vec.extend_from_slice(v);
new_vec.extend_from_slice(b"\r\n");
}
new_vec.extend_from_slice(b"\r\n\r\n");
new_vec.extend_from_slice(body);
post.bytes = new_vec;
Ok((post, ctx))
}
sourcepub fn help_header(&self) -> Option<String>
pub fn help_header(&self) -> Option<String>
Value of List-Help
header.
See RFC2369 Section 3.1: https://www.rfc-editor.org/rfc/rfc2369#section-3.1
Example
assert_eq!(
&list.help_header().unwrap(),
"<mailto:foo-chat+request@example.com?subject=help>"
);
Examples found in repository?
348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371
pub fn insert_headers(
&self,
draft: &mut melib::Draft,
post_policy: Option<&PostPolicy>,
subscription_policy: Option<&SubscriptionPolicy>,
) {
for (hdr, val) in [
("List-Id", Some(self.id_header())),
("List-Help", self.help_header()),
("List-Post", self.post_header(post_policy)),
(
"List-Unsubscribe",
self.unsubscribe_header(subscription_policy),
),
("List-Subscribe", self.subscribe_header(subscription_policy)),
("List-Archive", self.archive_header()),
] {
if let Some(val) = val {
draft
.headers
.insert(melib::HeaderName::new_unchecked(hdr), val);
}
}
}
More examples
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
fn feed<'p, 'list>(
self: Box<Self>,
post: &'p mut PostEntry,
ctx: &'p mut ListContext<'list>,
) -> std::result::Result<(&'p mut PostEntry, &'p mut ListContext<'list>), ()> {
trace!("Running AddListHeaders filter");
let (mut headers, body) = melib::email::parser::mail(&post.bytes).unwrap();
let sender = format!("<{}>", ctx.list.address);
headers.push((&b"Sender"[..], sender.as_bytes()));
let list_id = Some(ctx.list.id_header());
let list_help = ctx.list.help_header();
let list_post = ctx.list.post_header(ctx.post_policy.as_deref());
let list_unsubscribe = ctx
.list
.unsubscribe_header(ctx.subscription_policy.as_deref());
let list_subscribe = ctx
.list
.subscribe_header(ctx.subscription_policy.as_deref());
let list_archive = ctx.list.archive_header();
for (hdr, val) in [
(b"List-Id".as_slice(), &list_id),
(b"List-Help".as_slice(), &list_help),
(b"List-Post".as_slice(), &list_post),
(b"List-Unsubscribe".as_slice(), &list_unsubscribe),
(b"List-Subscribe".as_slice(), &list_subscribe),
(b"List-Archive".as_slice(), &list_archive),
] {
if let Some(val) = val {
headers.push((hdr, val.as_bytes()));
}
}
let mut new_vec = Vec::with_capacity(
headers
.iter()
.map(|(h, v)| h.len() + v.len() + ": \r\n".len())
.sum::<usize>()
+ "\r\n\r\n".len()
+ body.len(),
);
for (h, v) in headers {
new_vec.extend_from_slice(h);
new_vec.extend_from_slice(b": ");
new_vec.extend_from_slice(v);
new_vec.extend_from_slice(b"\r\n");
}
new_vec.extend_from_slice(b"\r\n\r\n");
new_vec.extend_from_slice(body);
post.bytes = new_vec;
Ok((post, ctx))
}
sourcepub fn post_header(&self, policy: Option<&PostPolicy>) -> Option<String>
pub fn post_header(&self, policy: Option<&PostPolicy>) -> Option<String>
Value of List-Post
header.
See RFC2369 Section 3.4: https://www.rfc-editor.org/rfc/rfc2369#section-3.4
Example
assert_eq!(&list.post_header(None).unwrap(), "NO");
assert_eq!(
&list.post_header(Some(&post_policy)).unwrap(),
"<mailto:foo-chat@example.com>"
);
Examples found in repository?
348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371
pub fn insert_headers(
&self,
draft: &mut melib::Draft,
post_policy: Option<&PostPolicy>,
subscription_policy: Option<&SubscriptionPolicy>,
) {
for (hdr, val) in [
("List-Id", Some(self.id_header())),
("List-Help", self.help_header()),
("List-Post", self.post_header(post_policy)),
(
"List-Unsubscribe",
self.unsubscribe_header(subscription_policy),
),
("List-Subscribe", self.subscribe_header(subscription_policy)),
("List-Archive", self.archive_header()),
] {
if let Some(val) = val {
draft
.headers
.insert(melib::HeaderName::new_unchecked(hdr), val);
}
}
}
More examples
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
fn feed<'p, 'list>(
self: Box<Self>,
post: &'p mut PostEntry,
ctx: &'p mut ListContext<'list>,
) -> std::result::Result<(&'p mut PostEntry, &'p mut ListContext<'list>), ()> {
trace!("Running AddListHeaders filter");
let (mut headers, body) = melib::email::parser::mail(&post.bytes).unwrap();
let sender = format!("<{}>", ctx.list.address);
headers.push((&b"Sender"[..], sender.as_bytes()));
let list_id = Some(ctx.list.id_header());
let list_help = ctx.list.help_header();
let list_post = ctx.list.post_header(ctx.post_policy.as_deref());
let list_unsubscribe = ctx
.list
.unsubscribe_header(ctx.subscription_policy.as_deref());
let list_subscribe = ctx
.list
.subscribe_header(ctx.subscription_policy.as_deref());
let list_archive = ctx.list.archive_header();
for (hdr, val) in [
(b"List-Id".as_slice(), &list_id),
(b"List-Help".as_slice(), &list_help),
(b"List-Post".as_slice(), &list_post),
(b"List-Unsubscribe".as_slice(), &list_unsubscribe),
(b"List-Subscribe".as_slice(), &list_subscribe),
(b"List-Archive".as_slice(), &list_archive),
] {
if let Some(val) = val {
headers.push((hdr, val.as_bytes()));
}
}
let mut new_vec = Vec::with_capacity(
headers
.iter()
.map(|(h, v)| h.len() + v.len() + ": \r\n".len())
.sum::<usize>()
+ "\r\n\r\n".len()
+ body.len(),
);
for (h, v) in headers {
new_vec.extend_from_slice(h);
new_vec.extend_from_slice(b": ");
new_vec.extend_from_slice(v);
new_vec.extend_from_slice(b"\r\n");
}
new_vec.extend_from_slice(b"\r\n\r\n");
new_vec.extend_from_slice(body);
post.bytes = new_vec;
Ok((post, ctx))
}
sourcepub fn unsubscribe_header(
&self,
policy: Option<&SubscriptionPolicy>
) -> Option<String>
pub fn unsubscribe_header( &self, policy: Option<&SubscriptionPolicy> ) -> Option<String>
Value of List-Unsubscribe
header.
See RFC2369 Section 3.2: https://www.rfc-editor.org/rfc/rfc2369#section-3.2
Example
assert_eq!(
&list.unsubscribe_header(Some(&sub_policy)).unwrap(),
"<mailto:foo-chat+request@example.com?subject=unsubscribe>"
);
Examples found in repository?
348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371
pub fn insert_headers(
&self,
draft: &mut melib::Draft,
post_policy: Option<&PostPolicy>,
subscription_policy: Option<&SubscriptionPolicy>,
) {
for (hdr, val) in [
("List-Id", Some(self.id_header())),
("List-Help", self.help_header()),
("List-Post", self.post_header(post_policy)),
(
"List-Unsubscribe",
self.unsubscribe_header(subscription_policy),
),
("List-Subscribe", self.subscribe_header(subscription_policy)),
("List-Archive", self.archive_header()),
] {
if let Some(val) = val {
draft
.headers
.insert(melib::HeaderName::new_unchecked(hdr), val);
}
}
}
More examples
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
fn feed<'p, 'list>(
self: Box<Self>,
post: &'p mut PostEntry,
ctx: &'p mut ListContext<'list>,
) -> std::result::Result<(&'p mut PostEntry, &'p mut ListContext<'list>), ()> {
trace!("Running AddListHeaders filter");
let (mut headers, body) = melib::email::parser::mail(&post.bytes).unwrap();
let sender = format!("<{}>", ctx.list.address);
headers.push((&b"Sender"[..], sender.as_bytes()));
let list_id = Some(ctx.list.id_header());
let list_help = ctx.list.help_header();
let list_post = ctx.list.post_header(ctx.post_policy.as_deref());
let list_unsubscribe = ctx
.list
.unsubscribe_header(ctx.subscription_policy.as_deref());
let list_subscribe = ctx
.list
.subscribe_header(ctx.subscription_policy.as_deref());
let list_archive = ctx.list.archive_header();
for (hdr, val) in [
(b"List-Id".as_slice(), &list_id),
(b"List-Help".as_slice(), &list_help),
(b"List-Post".as_slice(), &list_post),
(b"List-Unsubscribe".as_slice(), &list_unsubscribe),
(b"List-Subscribe".as_slice(), &list_subscribe),
(b"List-Archive".as_slice(), &list_archive),
] {
if let Some(val) = val {
headers.push((hdr, val.as_bytes()));
}
}
let mut new_vec = Vec::with_capacity(
headers
.iter()
.map(|(h, v)| h.len() + v.len() + ": \r\n".len())
.sum::<usize>()
+ "\r\n\r\n".len()
+ body.len(),
);
for (h, v) in headers {
new_vec.extend_from_slice(h);
new_vec.extend_from_slice(b": ");
new_vec.extend_from_slice(v);
new_vec.extend_from_slice(b"\r\n");
}
new_vec.extend_from_slice(b"\r\n\r\n");
new_vec.extend_from_slice(body);
post.bytes = new_vec;
Ok((post, ctx))
}
sourcepub fn subscribe_header(
&self,
policy: Option<&SubscriptionPolicy>
) -> Option<String>
pub fn subscribe_header( &self, policy: Option<&SubscriptionPolicy> ) -> Option<String>
Value of List-Subscribe
header.
See RFC2369 Section 3.3: https://www.rfc-editor.org/rfc/rfc2369#section-3.3
Example
assert_eq!(
&list.subscribe_header(Some(&sub_policy)).unwrap(),
"<mailto:foo-chat+request@example.com?subject=subscribe>",
);
Examples found in repository?
348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371
pub fn insert_headers(
&self,
draft: &mut melib::Draft,
post_policy: Option<&PostPolicy>,
subscription_policy: Option<&SubscriptionPolicy>,
) {
for (hdr, val) in [
("List-Id", Some(self.id_header())),
("List-Help", self.help_header()),
("List-Post", self.post_header(post_policy)),
(
"List-Unsubscribe",
self.unsubscribe_header(subscription_policy),
),
("List-Subscribe", self.subscribe_header(subscription_policy)),
("List-Archive", self.archive_header()),
] {
if let Some(val) = val {
draft
.headers
.insert(melib::HeaderName::new_unchecked(hdr), val);
}
}
}
More examples
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
fn feed<'p, 'list>(
self: Box<Self>,
post: &'p mut PostEntry,
ctx: &'p mut ListContext<'list>,
) -> std::result::Result<(&'p mut PostEntry, &'p mut ListContext<'list>), ()> {
trace!("Running AddListHeaders filter");
let (mut headers, body) = melib::email::parser::mail(&post.bytes).unwrap();
let sender = format!("<{}>", ctx.list.address);
headers.push((&b"Sender"[..], sender.as_bytes()));
let list_id = Some(ctx.list.id_header());
let list_help = ctx.list.help_header();
let list_post = ctx.list.post_header(ctx.post_policy.as_deref());
let list_unsubscribe = ctx
.list
.unsubscribe_header(ctx.subscription_policy.as_deref());
let list_subscribe = ctx
.list
.subscribe_header(ctx.subscription_policy.as_deref());
let list_archive = ctx.list.archive_header();
for (hdr, val) in [
(b"List-Id".as_slice(), &list_id),
(b"List-Help".as_slice(), &list_help),
(b"List-Post".as_slice(), &list_post),
(b"List-Unsubscribe".as_slice(), &list_unsubscribe),
(b"List-Subscribe".as_slice(), &list_subscribe),
(b"List-Archive".as_slice(), &list_archive),
] {
if let Some(val) = val {
headers.push((hdr, val.as_bytes()));
}
}
let mut new_vec = Vec::with_capacity(
headers
.iter()
.map(|(h, v)| h.len() + v.len() + ": \r\n".len())
.sum::<usize>()
+ "\r\n\r\n".len()
+ body.len(),
);
for (h, v) in headers {
new_vec.extend_from_slice(h);
new_vec.extend_from_slice(b": ");
new_vec.extend_from_slice(v);
new_vec.extend_from_slice(b"\r\n");
}
new_vec.extend_from_slice(b"\r\n\r\n");
new_vec.extend_from_slice(body);
post.bytes = new_vec;
Ok((post, ctx))
}
sourcepub fn archive_header(&self) -> Option<String>
pub fn archive_header(&self) -> Option<String>
Value of List-Archive
header.
See RFC2369 Section 3.6: https://www.rfc-editor.org/rfc/rfc2369#section-3.6
Example
assert_eq!(
&list.archive_header().unwrap(),
"<https://lists.example.com>"
);
Examples found in repository?
348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371
pub fn insert_headers(
&self,
draft: &mut melib::Draft,
post_policy: Option<&PostPolicy>,
subscription_policy: Option<&SubscriptionPolicy>,
) {
for (hdr, val) in [
("List-Id", Some(self.id_header())),
("List-Help", self.help_header()),
("List-Post", self.post_header(post_policy)),
(
"List-Unsubscribe",
self.unsubscribe_header(subscription_policy),
),
("List-Subscribe", self.subscribe_header(subscription_policy)),
("List-Archive", self.archive_header()),
] {
if let Some(val) = val {
draft
.headers
.insert(melib::HeaderName::new_unchecked(hdr), val);
}
}
}
More examples
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
fn feed<'p, 'list>(
self: Box<Self>,
post: &'p mut PostEntry,
ctx: &'p mut ListContext<'list>,
) -> std::result::Result<(&'p mut PostEntry, &'p mut ListContext<'list>), ()> {
trace!("Running AddListHeaders filter");
let (mut headers, body) = melib::email::parser::mail(&post.bytes).unwrap();
let sender = format!("<{}>", ctx.list.address);
headers.push((&b"Sender"[..], sender.as_bytes()));
let list_id = Some(ctx.list.id_header());
let list_help = ctx.list.help_header();
let list_post = ctx.list.post_header(ctx.post_policy.as_deref());
let list_unsubscribe = ctx
.list
.unsubscribe_header(ctx.subscription_policy.as_deref());
let list_subscribe = ctx
.list
.subscribe_header(ctx.subscription_policy.as_deref());
let list_archive = ctx.list.archive_header();
for (hdr, val) in [
(b"List-Id".as_slice(), &list_id),
(b"List-Help".as_slice(), &list_help),
(b"List-Post".as_slice(), &list_post),
(b"List-Unsubscribe".as_slice(), &list_unsubscribe),
(b"List-Subscribe".as_slice(), &list_subscribe),
(b"List-Archive".as_slice(), &list_archive),
] {
if let Some(val) = val {
headers.push((hdr, val.as_bytes()));
}
}
let mut new_vec = Vec::with_capacity(
headers
.iter()
.map(|(h, v)| h.len() + v.len() + ": \r\n".len())
.sum::<usize>()
+ "\r\n\r\n".len()
+ body.len(),
);
for (h, v) in headers {
new_vec.extend_from_slice(h);
new_vec.extend_from_slice(b": ");
new_vec.extend_from_slice(v);
new_vec.extend_from_slice(b"\r\n");
}
new_vec.extend_from_slice(b"\r\n\r\n");
new_vec.extend_from_slice(body);
post.bytes = new_vec;
Ok((post, ctx))
}
sourcepub fn address(&self) -> Address
pub fn address(&self) -> Address
List address as a [melib::Address
]
Examples found in repository?
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
fn inner_post(&self, env: &Envelope, raw: &[u8], _dry_run: bool) -> Result<()> {
trace!("Received envelope to post: {:#?}", &env);
let tos = env.to().to_vec();
if tos.is_empty() {
return Err("Envelope To: field is empty!".into());
}
if env.from().is_empty() {
return Err("Envelope From: field is empty!".into());
}
let mut lists = self.lists()?;
if lists.is_empty() {
return Err("No active mailing lists found.".into());
}
let prev_list_len = lists.len();
for t in &tos {
if let Some((addr, subaddr)) = t.subaddress("+") {
lists.retain(|list| {
if !addr.contains_address(&list.address()) {
return true;
}
if let Err(err) = ListRequest::try_from((subaddr.as_str(), env))
.and_then(|req| self.request(list, req, env, raw))
{
info!("Processing request returned error: {}", err);
}
false
});
if lists.len() != prev_list_len {
// Was request, handled above.
return Ok(());
}
}
}
lists.retain(|list| {
trace!(
"Is post related to list {}? {}",
&list,
tos.iter().any(|a| a.contains_address(&list.address()))
);
tos.iter().any(|a| a.contains_address(&list.address()))
});
if lists.is_empty() {
return Err(format!(
"No relevant mailing list found for these addresses: {:?}",
tos
)
.into());
}
trace!("Configuration is {:#?}", &self.conf);
for mut list in lists {
trace!("Examining list {}", list.display_name());
let filters = self.list_filters(&list);
let subscriptions = self.list_subscriptions(list.pk)?;
let owners = self.list_owners(list.pk)?;
trace!("List subscriptions {:#?}", &subscriptions);
let mut list_ctx = ListContext {
post_policy: self.list_post_policy(list.pk)?,
subscription_policy: self.list_subscription_policy(list.pk)?,
list_owners: &owners,
subscriptions: &subscriptions,
scheduled_jobs: vec![],
filter_settings: self.get_settings(list.pk)?,
list: &mut list,
};
let mut post = PostEntry {
message_id: env.message_id().clone(),
from: env.from()[0].clone(),
bytes: raw.to_vec(),
to: env.to().to_vec(),
action: PostAction::Hold,
};
let result = filters
.into_iter()
.fold(Ok((&mut post, &mut list_ctx)), |p, f| {
p.and_then(|(p, c)| f.feed(p, c))
});
trace!("result {:#?}", result);
let PostEntry { bytes, action, .. } = post;
trace!("Action is {:#?}", action);
let post_env = melib::Envelope::from_bytes(&bytes, None)?;
match action {
PostAction::Accept => {
let _post_pk = self.insert_post(list_ctx.list.pk, &bytes, &post_env)?;
trace!("post_pk is {:#?}", _post_pk);
for job in list_ctx.scheduled_jobs.iter() {
trace!("job is {:#?}", &job);
if let crate::mail::MailJob::Send { recipients } = job {
trace!("recipients: {:?}", &recipients);
if recipients.is_empty() {
trace!("list has no recipients");
}
for recipient in recipients {
let mut env = post_env.clone();
env.set_to(melib::smallvec::smallvec![recipient.clone()]);
self.insert_to_queue(QueueEntry::new(
Queue::Out,
Some(list.pk),
Some(Cow::Owned(env)),
&bytes,
None,
)?)?;
}
}
}
}
PostAction::Reject { reason } => {
log::info!("PostAction::Reject {{ reason: {} }}", reason);
for f in env.from() {
/* send error notice to e-mail sender */
self.send_reply_with_list_template(
TemplateRenderContext {
template: Template::GENERIC_FAILURE,
default_fn: Some(Template::default_generic_failure),
list: &list,
context: minijinja::context! {
list => &list,
subject => format!("Your post to {} was rejected.", list.id),
details => &reason,
},
queue: Queue::Out,
comment: format!("PostAction::Reject {{ reason: {} }}", reason)
.into(),
},
std::iter::once(Cow::Borrowed(f)),
)?;
}
/* error handled by notifying submitter */
return Ok(());
}
PostAction::Defer { reason } => {
trace!("PostAction::Defer {{ reason: {} }}", reason);
for f in env.from() {
/* send error notice to e-mail sender */
self.send_reply_with_list_template(
TemplateRenderContext {
template: Template::GENERIC_FAILURE,
default_fn: Some(Template::default_generic_failure),
list: &list,
context: minijinja::context! {
list => &list,
subject => format!("Your post to {} was deferred.", list.id),
details => &reason,
},
queue: Queue::Out,
comment: format!("PostAction::Defer {{ reason: {} }}", reason)
.into(),
},
std::iter::once(Cow::Borrowed(f)),
)?;
}
self.insert_to_queue(QueueEntry::new(
Queue::Deferred,
Some(list.pk),
Some(Cow::Borrowed(&post_env)),
&bytes,
Some(format!("PostAction::Defer {{ reason: {} }}", reason)),
)?)?;
return Ok(());
}
PostAction::Hold => {
trace!("PostAction::Hold");
self.insert_to_queue(QueueEntry::new(
Queue::Hold,
Some(list.pk),
Some(Cow::Borrowed(&post_env)),
&bytes,
Some("PostAction::Hold".to_string()),
)?)?;
return Ok(());
}
}
}
Ok(())
}
sourcepub fn unsubscription_mailto(&self) -> MailtoAddress
pub fn unsubscription_mailto(&self) -> MailtoAddress
List unsubscribe action as a MailtoAddress
.
sourcepub fn subscription_mailto(&self) -> MailtoAddress
pub fn subscription_mailto(&self) -> MailtoAddress
List subscribe action as a MailtoAddress
.
Examples found in repository?
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
pub fn generate_maps(
&self,
lists: &[(DbVal<MailingList>, Option<DbVal<PostPolicy>>)],
) -> String {
let transport_name = self.transport_name.as_deref().unwrap_or("mailpot");
let mut ret = String::new();
ret.push_str("# Automatically generated by mailpot.\n");
ret.push_str(
"# Upon its creation and every time it is modified, postmap(1) must be called for the \
changes to take effect:\n",
);
ret.push_str("# postmap /path/to/map_file\n\n");
// [ref:TODO]: add custom addresses if PostPolicy is custom
let calc_width = |list: &MailingList, policy: Option<&PostPolicy>| -> usize {
let addr = list.address.len();
match policy {
None => 0,
Some(PostPolicy { .. }) => addr + "+request".len(),
}
};
let Some(width): Option<usize> = lists.iter().map(|(l, p)| calc_width(l, p.as_deref())).max() else {
return ret;
};
for (list, policy) in lists {
macro_rules! push_addr {
($addr:expr) => {{
let addr = &$addr;
ret.push_str(addr);
for _ in 0..(width - addr.len() + 5) {
ret.push(' ');
}
ret.push_str(transport_name);
ret.push_str(":\n");
}};
}
match policy.as_deref() {
None => log::debug!(
"Not generating postfix map entry for list {} because it has no post_policy \
set.",
list.id
),
Some(PostPolicy { open: true, .. }) => {
push_addr!(list.address);
ret.push('\n');
}
Some(PostPolicy { .. }) => {
push_addr!(list.address);
push_addr!(list.subscription_mailto().address);
push_addr!(list.owner_mailto().address);
ret.push('\n');
}
}
}
// pop second of the last two newlines
ret.pop();
ret
}
sourcepub fn owner_mailto(&self) -> MailtoAddress
pub fn owner_mailto(&self) -> MailtoAddress
List owner as a MailtoAddress
.
Examples found in repository?
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
pub fn generate_maps(
&self,
lists: &[(DbVal<MailingList>, Option<DbVal<PostPolicy>>)],
) -> String {
let transport_name = self.transport_name.as_deref().unwrap_or("mailpot");
let mut ret = String::new();
ret.push_str("# Automatically generated by mailpot.\n");
ret.push_str(
"# Upon its creation and every time it is modified, postmap(1) must be called for the \
changes to take effect:\n",
);
ret.push_str("# postmap /path/to/map_file\n\n");
// [ref:TODO]: add custom addresses if PostPolicy is custom
let calc_width = |list: &MailingList, policy: Option<&PostPolicy>| -> usize {
let addr = list.address.len();
match policy {
None => 0,
Some(PostPolicy { .. }) => addr + "+request".len(),
}
};
let Some(width): Option<usize> = lists.iter().map(|(l, p)| calc_width(l, p.as_deref())).max() else {
return ret;
};
for (list, policy) in lists {
macro_rules! push_addr {
($addr:expr) => {{
let addr = &$addr;
ret.push_str(addr);
for _ in 0..(width - addr.len() + 5) {
ret.push(' ');
}
ret.push_str(transport_name);
ret.push_str(":\n");
}};
}
match policy.as_deref() {
None => log::debug!(
"Not generating postfix map entry for list {} because it has no post_policy \
set.",
list.id
),
Some(PostPolicy { open: true, .. }) => {
push_addr!(list.address);
ret.push('\n');
}
Some(PostPolicy { .. }) => {
push_addr!(list.address);
push_addr!(list.subscription_mailto().address);
push_addr!(list.owner_mailto().address);
ret.push('\n');
}
}
}
// pop second of the last two newlines
ret.pop();
ret
}
More examples
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 430
pub fn generate_help_email(
&self,
post_policy: Option<&PostPolicy>,
subscription_policy: Option<&SubscriptionPolicy>,
) -> String {
format!(
"Help for {list_name}\n\n{subscribe}\n\n{post}\n\nTo contact the list owners, send an \
e-mail to {contact}\n",
list_name = self.name,
subscribe = subscription_policy.map_or(
Cow::Borrowed("This list is not open to subscriptions."),
|p| if p.open {
Cow::Owned(format!(
"Anyone can subscribe without restrictions. Send an e-mail to {} with the \
subject `subscribe`.",
self.request_subaddr(),
))
} else if p.manual {
Cow::Borrowed(
"The list owners must manually add you to the list of subscriptions.",
)
} else if p.request {
Cow::Owned(format!(
"Anyone can request to subscribe. Send an e-mail to {} with the subject \
`subscribe` and a confirmation will be sent to you when your request is \
approved.",
self.request_subaddr(),
))
} else {
Cow::Borrowed("Please contact the list owners for details on how to subscribe.")
}
),
post = post_policy.map_or(Cow::Borrowed("This list does not allow posting."), |p| {
if p.announce_only {
Cow::Borrowed(
"This list is announce only, which means that you can only receive posts \
from the list owners.",
)
} else if p.subscription_only {
Cow::Owned(format!(
"Only list subscriptions can post to this list. Send your post to {}",
self.address
))
} else if p.approval_needed {
Cow::Owned(format!(
"Anyone can post, but approval from list owners is required if they are \
not subscribed. Send your post to {}",
self.address
))
} else {
Cow::Borrowed("This list does not allow posting.")
}
}),
contact = self.owner_mailto().address,
)
}
sourcepub fn archive_url(&self) -> Option<&str>
pub fn archive_url(&self) -> Option<&str>
List archive url value.
sourcepub fn insert_headers(
&self,
draft: &mut Draft,
post_policy: Option<&PostPolicy>,
subscription_policy: Option<&SubscriptionPolicy>
)
pub fn insert_headers( &self, draft: &mut Draft, post_policy: Option<&PostPolicy>, subscription_policy: Option<&SubscriptionPolicy> )
Insert all available list headers.
Examples found in repository?
719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768
pub fn send_reply_with_list_template<'ctx, F: Fn() -> Template>(
&self,
render_context: TemplateRenderContext<'ctx, F>,
recipients: impl Iterator<Item = Cow<'ctx, melib::Address>>,
) -> Result<()> {
let TemplateRenderContext {
template,
default_fn,
list,
context,
queue,
comment,
} = render_context;
let post_policy = self.list_post_policy(list.pk)?;
let subscription_policy = self.list_subscription_policy(list.pk)?;
let templ = self
.fetch_template(template, Some(list.pk))?
.map(DbVal::into_inner)
.or_else(|| default_fn.map(|f| f()))
.ok_or_else(|| -> crate::Error {
format!("Template with name {template:?} was not found.").into()
})?;
let mut draft = templ.render(context)?;
draft.headers.insert(
melib::HeaderName::new_unchecked("From"),
list.request_subaddr(),
);
for addr in recipients {
let mut draft = draft.clone();
draft
.headers
.insert(melib::HeaderName::new_unchecked("To"), addr.to_string());
list.insert_headers(
&mut draft,
post_policy.as_deref(),
subscription_policy.as_deref(),
);
self.insert_to_queue(QueueEntry::new(
queue,
Some(list.pk),
None,
draft.finalise()?.as_bytes(),
Some(comment.to_string()),
)?)?;
}
Ok(())
}
sourcepub fn generate_help_email(
&self,
post_policy: Option<&PostPolicy>,
subscription_policy: Option<&SubscriptionPolicy>
) -> String
pub fn generate_help_email( &self, post_policy: Option<&PostPolicy>, subscription_policy: Option<&SubscriptionPolicy> ) -> String
Generate help e-mail body containing information on how to subscribe, unsubscribe, post and how to contact the list owners.
Examples found in repository?
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 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663
pub fn request(
&self,
list: &DbVal<MailingList>,
request: ListRequest,
env: &Envelope,
raw: &[u8],
) -> Result<()> {
let post_policy = self.list_post_policy(list.pk)?;
match request {
ListRequest::Help => {
trace!(
"help action for addresses {:?} in list {}",
env.from(),
list
);
let subscription_policy = self.list_subscription_policy(list.pk)?;
let subject = format!("Help for {}", list.name);
let details = list
.generate_help_email(post_policy.as_deref(), subscription_policy.as_deref());
for f in env.from() {
self.send_reply_with_list_template(
TemplateRenderContext {
template: Template::GENERIC_HELP,
default_fn: Some(Template::default_generic_help),
list,
context: minijinja::context! {
list => &list,
subject => &subject,
details => &details,
},
queue: Queue::Out,
comment: "Help request".into(),
},
std::iter::once(Cow::Borrowed(f)),
)?;
}
}
ListRequest::Subscribe => {
trace!(
"subscribe action for addresses {:?} in list {}",
env.from(),
list
);
let approval_needed = post_policy
.as_ref()
.map(|p| p.approval_needed)
.unwrap_or(false);
for f in env.from() {
let email_from = f.get_email();
if self
.list_subscription_by_address(list.pk, &email_from)
.is_ok()
{
/* send error notice to e-mail sender */
self.send_reply_with_list_template(
TemplateRenderContext {
template: Template::GENERIC_FAILURE,
default_fn: Some(Template::default_generic_failure),
list,
context: minijinja::context! {
list => &list,
subject => format!("You are already subscribed to {}.", list.id),
details => "No action has been taken since you are already subscribed to the list.",
},
queue: Queue::Out,
comment: format!("Address {} is already subscribed to list {}", f, list.id).into(),
},
std::iter::once(Cow::Borrowed(f)),
)?;
continue;
}
let subscription = ListSubscription {
pk: 0,
list: list.pk,
address: f.get_email(),
account: None,
name: f.get_display_name(),
digest: false,
hide_address: false,
receive_duplicates: true,
receive_own_posts: false,
receive_confirmation: true,
enabled: !approval_needed,
verified: true,
};
if approval_needed {
match self.add_candidate_subscription(list.pk, subscription) {
Ok(v) => {
let list_owners = self.list_owners(list.pk)?;
self.send_reply_with_list_template(
TemplateRenderContext {
template: Template::SUBSCRIPTION_REQUEST_NOTICE_OWNER,
default_fn: Some(
Template::default_subscription_request_owner,
),
list,
context: minijinja::context! {
list => &list,
candidate => &v,
},
queue: Queue::Out,
comment: Template::SUBSCRIPTION_REQUEST_NOTICE_OWNER.into(),
},
list_owners.iter().map(|owner| Cow::Owned(owner.address())),
)?;
}
Err(err) => {
log::error!(
"Could not create candidate subscription for {f:?}: {err}"
);
/* send error notice to e-mail sender */
self.send_reply_with_list_template(
TemplateRenderContext {
template: Template::GENERIC_FAILURE,
default_fn: Some(Template::default_generic_failure),
list,
context: minijinja::context! {
list => &list,
},
queue: Queue::Out,
comment: format!(
"Could not create candidate subscription for {f:?}: \
{err}"
)
.into(),
},
std::iter::once(Cow::Borrowed(f)),
)?;
/* send error details to list owners */
let list_owners = self.list_owners(list.pk)?;
self.send_reply_with_list_template(
TemplateRenderContext {
template: Template::ADMIN_NOTICE,
default_fn: Some(Template::default_admin_notice),
list,
context: minijinja::context! {
list => &list,
details => err.to_string(),
},
queue: Queue::Out,
comment: format!(
"Could not create candidate subscription for {f:?}: \
{err}"
)
.into(),
},
list_owners.iter().map(|owner| Cow::Owned(owner.address())),
)?;
}
}
} else if let Err(err) = self.add_subscription(list.pk, subscription) {
log::error!("Could not create subscription for {f:?}: {err}");
/* send error notice to e-mail sender */
self.send_reply_with_list_template(
TemplateRenderContext {
template: Template::GENERIC_FAILURE,
default_fn: Some(Template::default_generic_failure),
list,
context: minijinja::context! {
list => &list,
},
queue: Queue::Out,
comment: format!("Could not create subscription for {f:?}: {err}")
.into(),
},
std::iter::once(Cow::Borrowed(f)),
)?;
/* send error details to list owners */
let list_owners = self.list_owners(list.pk)?;
self.send_reply_with_list_template(
TemplateRenderContext {
template: Template::ADMIN_NOTICE,
default_fn: Some(Template::default_admin_notice),
list,
context: minijinja::context! {
list => &list,
details => err.to_string(),
},
queue: Queue::Out,
comment: format!("Could not create subscription for {f:?}: {err}")
.into(),
},
list_owners.iter().map(|owner| Cow::Owned(owner.address())),
)?;
} else {
log::trace!(
"Added subscription to list {list:?} for address {f:?}, sending \
confirmation."
);
self.send_reply_with_list_template(
TemplateRenderContext {
template: Template::SUBSCRIPTION_CONFIRMATION,
default_fn: Some(Template::default_subscription_confirmation),
list,
context: minijinja::context! {
list => &list,
},
queue: Queue::Out,
comment: Template::SUBSCRIPTION_CONFIRMATION.into(),
},
std::iter::once(Cow::Borrowed(f)),
)?;
}
}
}
ListRequest::Unsubscribe => {
trace!(
"unsubscribe action for addresses {:?} in list {}",
env.from(),
list
);
for f in env.from() {
if let Err(err) = self.remove_subscription(list.pk, &f.get_email()) {
log::error!("Could not unsubscribe {f:?}: {err}");
/* send error notice to e-mail sender */
self.send_reply_with_list_template(
TemplateRenderContext {
template: Template::GENERIC_FAILURE,
default_fn: Some(Template::default_generic_failure),
list,
context: minijinja::context! {
list => &list,
},
queue: Queue::Out,
comment: format!("Could not unsubscribe {f:?}: {err}").into(),
},
std::iter::once(Cow::Borrowed(f)),
)?;
/* send error details to list owners */
let list_owners = self.list_owners(list.pk)?;
self.send_reply_with_list_template(
TemplateRenderContext {
template: Template::ADMIN_NOTICE,
default_fn: Some(Template::default_admin_notice),
list,
context: minijinja::context! {
list => &list,
details => err.to_string(),
},
queue: Queue::Out,
comment: format!("Could not unsubscribe {f:?}: {err}").into(),
},
list_owners.iter().map(|owner| Cow::Owned(owner.address())),
)?;
} else {
self.send_reply_with_list_template(
TemplateRenderContext {
template: Template::UNSUBSCRIPTION_CONFIRMATION,
default_fn: Some(Template::default_unsubscription_confirmation),
list,
context: minijinja::context! {
list => &list,
},
queue: Queue::Out,
comment: Template::UNSUBSCRIPTION_CONFIRMATION.into(),
},
std::iter::once(Cow::Borrowed(f)),
)?;
}
}
}
ListRequest::Other(ref req) if req == "owner" => {
trace!(
"list-owner mail action for addresses {:?} in list {}",
env.from(),
list
);
return Err("list-owner emails are not implemented yet.".into());
//FIXME: mail to list-owner
/*
for _owner in self.list_owners(list.pk)? {
self.insert_to_queue(
Queue::Out,
Some(list.pk),
None,
draft.finalise()?.as_bytes(),
"list-owner-forward".to_string(),
)?;
}
*/
}
ListRequest::Other(ref req) if req.trim().eq_ignore_ascii_case("password") => {
trace!(
"list-request password set action for addresses {:?} in list {list}",
env.from(),
);
let body = env.body_bytes(raw);
let password = body.text();
// TODO: validate SSH public key with `ssh-keygen`.
for f in env.from() {
let email_from = f.get_email();
if let Ok(sub) = self.list_subscription_by_address(list.pk, &email_from) {
match self.account_by_address(&email_from)? {
Some(_acc) => {
let changeset = AccountChangeset {
address: email_from.clone(),
name: None,
public_key: None,
password: Some(password.clone()),
enabled: None,
};
self.update_account(changeset)?;
}
None => {
// Create new account.
self.add_account(Account {
pk: 0,
name: sub.name.clone(),
address: sub.address.clone(),
public_key: None,
password: password.clone(),
enabled: sub.enabled,
})?;
}
}
}
}
}
ListRequest::RetrieveMessages(ref message_ids) => {
trace!(
"retrieve messages {message_ids:?} action for addresses {:?} in list {list}",
env.from(),
);
return Err("message retrievals are not implemented yet.".into());
}
ListRequest::RetrieveArchive(ref from, ref to) => {
trace!(
"retrieve archive action from {from:?} to {to:?} for addresses {:?} in list \
{list}",
env.from(),
);
return Err("message retrievals are not implemented yet.".into());
}
ListRequest::ChangeSetting(ref setting, ref toggle) => {
trace!(
"change setting {setting}, request with value {toggle:?} for addresses {:?} \
in list {list}",
env.from(),
);
return Err("setting digest options via e-mail is not implemented yet.".into());
}
ListRequest::Other(ref req) => {
trace!(
"unknown request action {req} for addresses {:?} in list {list}",
env.from(),
);
return Err(format!("Unknown request {req}.").into());
}
}
Ok(())
}
sourcepub fn topics_from_json_value(v: Value) -> Result<Vec<String>, Error>
pub fn topics_from_json_value(v: Value) -> Result<Vec<String>, Error>
Utility function to get a Vec<String>
-which is the expected type of
the topics
field- from a serde_json::Value
, which is the value
stored in the topics
column in sqlite3
.
Example
use serde_json::Value;
let value: Value = serde_json::from_str(r#"["fruits","vegetables"]"#)?;
assert_eq!(
MailingList::topics_from_json_value(value),
Ok(vec!["fruits".to_string(), "vegetables".to_string()])
);
let value: Value = serde_json::from_str(r#"{"invalid":"value"}"#)?;
assert!(MailingList::topics_from_json_value(value).is_err());
Examples found in repository?
422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542
pub fn lists(&self) -> Result<Vec<DbVal<MailingList>>> {
let mut stmt = self.connection.prepare("SELECT * FROM list;")?;
let list_iter = stmt.query_map([], |row| {
let pk = row.get("pk")?;
let topics: serde_json::Value = row.get("topics")?;
let topics = MailingList::topics_from_json_value(topics)?;
Ok(DbVal(
MailingList {
pk,
name: row.get("name")?,
id: row.get("id")?,
address: row.get("address")?,
description: row.get("description")?,
topics,
archive_url: row.get("archive_url")?,
},
pk,
))
})?;
let mut ret = vec![];
for list in list_iter {
let list = list?;
ret.push(list);
}
Ok(ret)
}
/// Fetch a mailing list by primary key.
pub fn list(&self, pk: i64) -> Result<Option<DbVal<MailingList>>> {
let mut stmt = self
.connection
.prepare("SELECT * FROM list WHERE pk = ?;")?;
let ret = stmt
.query_row([&pk], |row| {
let pk = row.get("pk")?;
let topics: serde_json::Value = row.get("topics")?;
let topics = MailingList::topics_from_json_value(topics)?;
Ok(DbVal(
MailingList {
pk,
name: row.get("name")?,
id: row.get("id")?,
address: row.get("address")?,
description: row.get("description")?,
topics,
archive_url: row.get("archive_url")?,
},
pk,
))
})
.optional()?;
Ok(ret)
}
/// Fetch a mailing list by id.
pub fn list_by_id<S: AsRef<str>>(&self, id: S) -> Result<Option<DbVal<MailingList>>> {
let id = id.as_ref();
let mut stmt = self
.connection
.prepare("SELECT * FROM list WHERE id = ?;")?;
let ret = stmt
.query_row([&id], |row| {
let pk = row.get("pk")?;
let topics: serde_json::Value = row.get("topics")?;
let topics = MailingList::topics_from_json_value(topics)?;
Ok(DbVal(
MailingList {
pk,
name: row.get("name")?,
id: row.get("id")?,
address: row.get("address")?,
description: row.get("description")?,
topics,
archive_url: row.get("archive_url")?,
},
pk,
))
})
.optional()?;
Ok(ret)
}
/// Create a new list.
pub fn create_list(&self, new_val: MailingList) -> Result<DbVal<MailingList>> {
let mut stmt = self.connection.prepare(
"INSERT INTO list(name, id, address, description, archive_url, topics) VALUES(?, ?, \
?, ?, ?, ?) RETURNING *;",
)?;
let ret = stmt.query_row(
rusqlite::params![
&new_val.name,
&new_val.id,
&new_val.address,
new_val.description.as_ref(),
new_val.archive_url.as_ref(),
serde_json::json!(new_val.topics.as_slice()),
],
|row| {
let pk = row.get("pk")?;
let topics: serde_json::Value = row.get("topics")?;
let topics = MailingList::topics_from_json_value(topics)?;
Ok(DbVal(
MailingList {
pk,
name: row.get("name")?,
id: row.get("id")?,
address: row.get("address")?,
description: row.get("description")?,
topics,
archive_url: row.get("archive_url")?,
},
pk,
))
},
)?;
trace!("create_list {:?}.", &ret);
Ok(ret)
}
Trait Implementations§
source§impl Clone for MailingList
impl Clone for MailingList
source§fn clone(&self) -> MailingList
fn clone(&self) -> MailingList
1.0.0 · source§fn clone_from(&mut self, source: &Self)
fn clone_from(&mut self, source: &Self)
source
. Read moresource§impl Debug for MailingList
impl Debug for MailingList
source§impl<'de> Deserialize<'de> for MailingList
impl<'de> Deserialize<'de> for MailingList
source§fn deserialize<__D>(__deserializer: __D) -> Result<Self, __D::Error>where
__D: Deserializer<'de>,
fn deserialize<__D>(__deserializer: __D) -> Result<Self, __D::Error>where __D: Deserializer<'de>,
source§impl Display for MailingList
impl Display for MailingList
source§impl PartialEq<MailingList> for MailingList
impl PartialEq<MailingList> for MailingList
source§fn eq(&self, other: &MailingList) -> bool
fn eq(&self, other: &MailingList) -> bool
self
and other
values to be equal, and is used
by ==
.source§impl Serialize for MailingList
impl Serialize for MailingList
impl Eq for MailingList
impl StructuralEq for MailingList
impl StructuralPartialEq for MailingList
Auto Trait Implementations§
impl RefUnwindSafe for MailingList
impl Send for MailingList
impl Sync for MailingList
impl Unpin for MailingList
impl UnwindSafe for MailingList
Blanket Implementations§
source§impl<T> BorrowMut<T> for Twhere
T: ?Sized,
impl<T> BorrowMut<T> for Twhere T: ?Sized,
source§fn borrow_mut(&mut self) -> &mut T
fn borrow_mut(&mut self) -> &mut T
source§impl<Q, K> Equivalent<K> for Qwhere
Q: Eq + ?Sized,
K: Borrow<Q> + ?Sized,
impl<Q, K> Equivalent<K> for Qwhere Q: Eq + ?Sized, K: Borrow<Q> + ?Sized,
source§fn equivalent(&self, key: &K) -> bool
fn equivalent(&self, key: &K) -> bool
key
and return true
if they are equal.