-
Notifications
You must be signed in to change notification settings - Fork 2
/
mailing_list_controller.rs
101 lines (89 loc) · 2.46 KB
/
mailing_list_controller.rs
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
use lettre::message::Mailbox;
use rocket::response::{Redirect, Responder};
use std::fmt::Debug;
use crate::config::Config;
use crate::controllers::users_controller::rocket_uri_macro_show_confirm_unsubscribe;
use crate::ephemeral::from_api::Api;
use crate::ephemeral::session::{AdminSession, UserSession};
use crate::errors::{InternalError, Result};
use crate::mailer::Mailer;
use crate::models::mail::*;
use crate::models::user::User;
use crate::views::accepter::Accepter;
use crate::DbConn;
use askama::Template;
use rocket::serde::json::Json;
use rocket::State;
/// Show an overview of all mails, sorted by send date
#[get("/mails")]
pub async fn list_mails<'r>(
session: UserSession,
db: DbConn,
) -> Result<impl Responder<'r, 'static>> {
let mails = Mail::all(&db).await?;
Ok(Accepter {
html: template! {
"maillist/index.html";
current_user: User = session.user,
mails: Vec<Mail> = mails.clone(),
},
json: Json(mails),
})
}
/// Send a new mail and archive it
#[post("/mails", data = "<new_mail>")]
pub async fn send_mail<'r>(
_session: AdminSession,
new_mail: Api<NewMail>,
db: DbConn,
conf: &'r State<Config>,
mailer: &'r State<Mailer>,
) -> Result<impl Responder<'r, 'static>> {
let mail = new_mail.into_inner().save(&db).await?;
let subscribed_users = User::find_subscribed(&db).await?;
for user in &subscribed_users {
let receiver = Mailbox::try_from(user)?;
let token = user.unsubscribe_token.to_string();
let unsubscribe_url =
uri!(conf.base_url(), show_confirm_unsubscribe(token));
let body = template!(
"mails/mailinglist_mail.txt";
body: String = mail.body.clone(),
unsubscribe_url: String = unsubscribe_url.to_string(),
)
.render()
.map_err(InternalError::from)?;
mailer.create_for_mailinglist(receiver, mail.subject.clone(), body)?;
}
Ok(Accepter {
html: Redirect::to(uri!(show_mail(mail.id))),
json: Json(mail),
})
}
/// Show the new_mail page
#[get("/mails/new")]
pub async fn show_create_mail_page<'r>(
session: AdminSession,
) -> Result<impl Responder<'r, 'static>> {
Ok(template! {
"maillist/new_mail.html";
current_user: User = session.admin,
})
}
/// Show a specific mail
#[get("/mails/<id>")]
pub async fn show_mail<'r>(
session: UserSession,
db: DbConn,
id: i32,
) -> Result<impl Responder<'r, 'static>> {
let mail = Mail::get_by_id(id, &db).await?;
Ok(Accepter {
html: template! {
"maillist/show_mail.html";
current_user: User = session.user,
mail: Mail = mail.clone(),
},
json: Json(mail),
})
}