-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathMailBox.java
More file actions
206 lines (184 loc) · 9.13 KB
/
MailBox.java
File metadata and controls
206 lines (184 loc) · 9.13 KB
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
package invite.mail;
import invite.cron.IdPMetaDataResolver;
import invite.cron.IdentityProvider;
import invite.model.*;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.mustachejava.DefaultMustacheFactory;
import com.github.mustachejava.MustacheFactory;
import jakarta.mail.MessagingException;
import jakarta.mail.internet.MimeMessage;
import lombok.SneakyThrows;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.core.io.ClassPathResource;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import java.io.IOException;
import java.io.StringWriter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;
@SuppressWarnings("unchecked")
public class MailBox {
private final JavaMailSender mailSender;
private final String clientUrl;
private final String welcomeUrl;
private final String emailFrom;
private final String contactEmail;
private final String environment;
private final Map<String, Map<String, String>> subjects;
private final MustacheFactory mustacheFactory = new DefaultMustacheFactory("templates");
private final IdPMetaDataResolver idPMetaDataResolver;
public MailBox(ObjectMapper objectMapper,
IdPMetaDataResolver idPMetaDataResolver,
JavaMailSender mailSender,
String emailFrom,
String contactEmail,
String clientUrl,
String welcomeUrl,
String environment) throws IOException {
this.mailSender = mailSender;
this.idPMetaDataResolver = idPMetaDataResolver;
this.emailFrom = emailFrom;
this.contactEmail = contactEmail;
this.clientUrl = clientUrl;
this.welcomeUrl = welcomeUrl;
this.environment = environment;
this.subjects = objectMapper.readValue(new ClassPathResource("/templates/subjects.json").getInputStream(), new TypeReference<>() {
});
}
@SneakyThrows
public void sendInviteMail(Provisionable provisionable, Invitation invitation,
List<GroupedProviders> groupedProviders, Language language,
Optional<String> optionalIdpName) {
Authority intendedAuthority = invitation.getIntendedAuthority();
String title = String.format(subjects.get(language.name()).get("newInvitation"),
invitation.getRoles().stream().map(role -> role.getRole().getName()).collect(Collectors.joining(", ")));
Map<String, Object> variables = new HashMap<>();
variables.put("groupedProviders", groupedProviders);
variables.put("title", title);
if (provisionable instanceof User user) {
Optional<IdentityProvider> identityProvider = idPMetaDataResolver
.getIdentityProvider(user.getSchacHomeOrganization());
variables.put("institutionName", identityProvider
.map(idp -> idp.getName())
.orElse(user.getSchacHomeOrganization()));
variables.put("institutionLogoUrl", identityProvider
.map(idp -> idp.getLogoUrl())
.orElse(null));
} else {
variables.put("institutionName", "SURF");
variables.put("isInstitutionSurf", true);
}
optionalIdpName.ifPresent(idpName -> variables.put("idpName", idpName));
variables.put("roles", splitListSemantically(invitation.getRoles().stream()
.map(invitationRole -> invitationRole.getRole().getName()).toList()));
if (invitation.getRoles().stream()
.anyMatch(invitationRole -> StringUtils.hasText(invitationRole.getRole().getInviterDisplayName()))) {
variables.put("displaySenderName", splitListSemantically(invitation.getRoles().stream()
.map(invitationRole -> invitationRole.getRole().getInviterDisplayName()).toList()));
} else {
variables.put("displaySenderName", provisionable.getName());
}
if (StringUtils.hasText(invitation.getMessage())) {
variables.put("message", invitation.getMessage().replaceAll("\n", "<br/>"));
}
variables.put("invitation", invitation);
variables.put("intendedAuthority", invitation.getIntendedAuthority().translate(language.name()));
variables.put("user", provisionable);
if (!environment.equalsIgnoreCase("prod")) {
variables.put("environment", environment);
}
String url = intendedAuthority.equals(Authority.GUEST) ? welcomeUrl : clientUrl;
variables.put("url", String.format("%s/invitation/accept?hash=%s", url, invitation.getHash()));
variables.put("useEduID", invitation.isEduIDOnly() && invitation.getIntendedAuthority().equals(Authority.GUEST));
sendMail(String.format("invitation_%s", language.name()),
title,
variables,
invitation.getEmail());
}
@SneakyThrows
public String inviteMailURL(Invitation invitation) {
Authority intendedAuthority = invitation.getIntendedAuthority();
String url = intendedAuthority.equals(Authority.GUEST) ? welcomeUrl : clientUrl;
return String.format("%s/invitation/accept?hash=%s", url, invitation.getHash());
}
@SneakyThrows
public String sendUserRoleExpirationNotificationMail(UserRole userRole,
GroupedProviders groupedProvider,
int nbrOfDays) {
String lang = preferredLanguage().toLowerCase();
String title = String.format(subjects.get(lang).get("roleExpirationNotification"),
userRole.getAuthority().translate(lang),
userRole.getRole().getName());
Map<String, Object> variables = new HashMap<>();
variables.put("title", title);
variables.put("userRole", userRole);
if (groupedProvider != null) {
variables.put("groupedProvider", groupedProvider);
}
variables.put("nbrOfDays", nbrOfDays);
variables.put("contactEmail", contactEmail);
variables.put("authority", userRole.getAuthority().translate(lang));
if (!environment.equalsIgnoreCase("prod")) {
variables.put("environment", environment);
}
return sendMail(String.format("role_expiration_%s", lang),
title,
variables,
userRole.getUser().getEmail());
}
private String preferredLanguage() {
return LocaleContextHolder.getLocale().getLanguage();
}
private String sendMail(String templateName, String subject, Map<String, Object> variables, String... to) throws MessagingException, IOException {
String htmlText = this.mailTemplate(templateName + ".html", variables);
String plainText = this.mailTemplate(templateName + ".txt", variables);
MimeMessage message = mailSender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(message, true);
helper.setSubject(subject);
setText(plainText, htmlText, helper);
helper.setTo(to);
helper.setFrom(emailFrom);
// //Add logo, if there
// if (variables.containsKey("groupedProviders")) {
// List<GroupedProviders> groupedProviders = (List<GroupedProviders>) variables.get("groupedProviders");
// groupedProviders.stream()
// .filter(groupedProvider -> StringUtils.hasText(groupedProvider.getLogo()))
// .forEach(groupedProvider -> {
// try {
// helper.addInline(groupedProvider.logoName(), new UrlResource(new URI(groupedProvider.getLogo())));
// } catch (Exception e) {
// //Can't be helped
// }
// });
// }
doSendMail(message);
return htmlText;
}
protected void setText(String plainText, String htmlText, MimeMessageHelper helper) throws MessagingException, IOException {
helper.setText(plainText, htmlText);
}
protected void doSendMail(MimeMessage message) {
new Thread(() -> mailSender.send(message)).start();
}
private String mailTemplate(String templateName, Map<String, Object> context) {
return mustacheFactory.compile(templateName).execute(new StringWriter(), context).toString();
}
private String splitListSemantically(List<String> values) {
if (CollectionUtils.isEmpty(values)) {
return "";
}
if (values.size() == 1) {
return values.get(0);
}
String separator = preferredLanguage().toLowerCase().equals("en") ? " and " : " en ";
return values.subList(0, values.size() - 1).stream()
.collect(Collectors.joining(", ")) + separator +
values.get(values.size() - 1);
}
}