-
Notifications
You must be signed in to change notification settings - Fork 7.3k
/
notification_email.go
353 lines (307 loc) · 13 KB
/
notification_email.go
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
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
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved.
// See LICENSE.txt for license information.
package app
import (
"fmt"
"html"
"html/template"
"net/url"
"path/filepath"
"strings"
"time"
"github.com/mattermost/mattermost-server/v5/model"
"github.com/mattermost/mattermost-server/v5/shared/i18n"
"github.com/mattermost/mattermost-server/v5/shared/mlog"
"github.com/pkg/errors"
)
func (a *App) sendNotificationEmail(notification *PostNotification, user *model.User, team *model.Team) error {
channel := notification.Channel
post := notification.Post
if channel.IsGroupOrDirect() {
teams, err := a.Srv().Store.Team().GetTeamsByUserId(user.Id)
if err != nil {
return errors.Wrap(err, "unable to get user teams")
}
// if the recipient isn't in the current user's team, just pick one
found := false
for i := range teams {
if teams[i].Id == team.Id {
found = true
break
}
}
if !found && len(teams) > 0 {
team = teams[0]
} else {
// in case the user hasn't joined any teams we send them to the select_team page
team = &model.Team{Name: "select_team", DisplayName: *a.Config().TeamSettings.SiteName}
}
}
if *a.Config().EmailSettings.EnableEmailBatching {
var sendBatched bool
if data, err := a.Srv().Store.Preference().Get(user.Id, model.PREFERENCE_CATEGORY_NOTIFICATIONS, model.PREFERENCE_NAME_EMAIL_INTERVAL); err != nil {
// if the call fails, assume that the interval has not been explicitly set and batch the notifications
sendBatched = true
} else {
// if the user has chosen to receive notifications immediately, don't batch them
sendBatched = data.Value != model.PREFERENCE_EMAIL_INTERVAL_NO_BATCHING_SECONDS
}
if sendBatched {
if err := a.Srv().EmailService.AddNotificationEmailToBatch(user, post, team); err == nil {
return nil
}
}
// fall back to sending a single email if we can't batch it for some reason
}
translateFunc := i18n.GetUserTranslations(user.Locale)
var useMilitaryTime bool
if data, err := a.Srv().Store.Preference().Get(user.Id, model.PREFERENCE_CATEGORY_DISPLAY_SETTINGS, model.PREFERENCE_NAME_USE_MILITARY_TIME); err != nil {
useMilitaryTime = true
} else {
useMilitaryTime = data.Value == "true"
}
nameFormat := a.GetNotificationNameFormat(user)
channelName := notification.GetChannelName(nameFormat, "")
senderName := notification.GetSenderName(nameFormat, *a.Config().ServiceSettings.EnablePostUsernameOverride)
emailNotificationContentsType := model.EMAIL_NOTIFICATION_CONTENTS_FULL
if license := a.Srv().License(); license != nil && *license.Features.EmailNotificationContents {
emailNotificationContentsType = *a.Config().EmailSettings.EmailNotificationContentsType
}
var subjectText string
if channel.Type == model.CHANNEL_DIRECT {
subjectText = getDirectMessageNotificationEmailSubject(user, post, translateFunc, *a.Config().TeamSettings.SiteName, senderName, useMilitaryTime)
} else if channel.Type == model.CHANNEL_GROUP {
subjectText = getGroupMessageNotificationEmailSubject(user, post, translateFunc, *a.Config().TeamSettings.SiteName, channelName, emailNotificationContentsType, useMilitaryTime)
} else if *a.Config().EmailSettings.UseChannelInEmailNotifications {
subjectText = getNotificationEmailSubject(user, post, translateFunc, *a.Config().TeamSettings.SiteName, team.DisplayName+" ("+channelName+")", useMilitaryTime)
} else {
subjectText = getNotificationEmailSubject(user, post, translateFunc, *a.Config().TeamSettings.SiteName, team.DisplayName, useMilitaryTime)
}
landingURL := a.GetSiteURL() + "/landing#/" + team.Name
var bodyText, err = a.getNotificationEmailBody(user, post, channel, channelName, senderName, team.Name, landingURL, emailNotificationContentsType, useMilitaryTime, translateFunc)
if err != nil {
return errors.Wrap(err, "unable to render the email notification template")
}
a.Srv().Go(func() {
if nErr := a.Srv().EmailService.sendNotificationMail(user.Email, html.UnescapeString(subjectText), bodyText); nErr != nil {
mlog.Error("Error while sending the email", mlog.String("user_email", user.Email), mlog.Err(nErr))
}
})
if a.Metrics() != nil {
a.Metrics().IncrementPostSentEmail()
}
return nil
}
/**
* Computes the subject line for direct notification email messages
*/
func getDirectMessageNotificationEmailSubject(user *model.User, post *model.Post, translateFunc i18n.TranslateFunc, siteName string, senderName string, useMilitaryTime bool) string {
t := getFormattedPostTime(user, post, useMilitaryTime, translateFunc)
var subjectParameters = map[string]interface{}{
"SiteName": siteName,
"SenderDisplayName": senderName,
"Month": t.Month,
"Day": t.Day,
"Year": t.Year,
}
return translateFunc("app.notification.subject.direct.full", subjectParameters)
}
/**
* Computes the subject line for group, public, and private email messages
*/
func getNotificationEmailSubject(user *model.User, post *model.Post, translateFunc i18n.TranslateFunc, siteName string, teamName string, useMilitaryTime bool) string {
t := getFormattedPostTime(user, post, useMilitaryTime, translateFunc)
var subjectParameters = map[string]interface{}{
"SiteName": siteName,
"TeamName": teamName,
"Month": t.Month,
"Day": t.Day,
"Year": t.Year,
}
return translateFunc("app.notification.subject.notification.full", subjectParameters)
}
/**
* Computes the subject line for group email messages
*/
func getGroupMessageNotificationEmailSubject(user *model.User, post *model.Post, translateFunc i18n.TranslateFunc, siteName string, channelName string, emailNotificationContentsType string, useMilitaryTime bool) string {
t := getFormattedPostTime(user, post, useMilitaryTime, translateFunc)
var subjectParameters = map[string]interface{}{
"SiteName": siteName,
"Month": t.Month,
"Day": t.Day,
"Year": t.Year,
}
if emailNotificationContentsType == model.EMAIL_NOTIFICATION_CONTENTS_FULL {
subjectParameters["ChannelName"] = channelName
return translateFunc("app.notification.subject.group_message.full", subjectParameters)
}
return translateFunc("app.notification.subject.group_message.generic", subjectParameters)
}
/**
* Computes the email body for notification messages
*/
func (a *App) getNotificationEmailBody(recipient *model.User, post *model.Post, channel *model.Channel, channelName string, senderName string, teamName string, landingURL string, emailNotificationContentsType string, useMilitaryTime bool, translateFunc i18n.TranslateFunc) (string, error) {
// only include message contents in notification email if email notification contents type is set to full
var templateName = "post_body_generic"
data := a.Srv().EmailService.newEmailTemplateData(recipient.Locale)
if emailNotificationContentsType == model.EMAIL_NOTIFICATION_CONTENTS_FULL {
templateName = "post_body_full"
postMessage := a.GetMessageForNotification(post, translateFunc)
postMessage = html.EscapeString(postMessage)
normalizedPostMessage, err := a.generateHyperlinkForChannels(postMessage, teamName, landingURL)
if err != nil {
mlog.Warn("Encountered error while generating hyperlink for channels", mlog.String("team_name", teamName), mlog.Err(err))
normalizedPostMessage = postMessage
}
data.Props["PostMessage"] = template.HTML(normalizedPostMessage)
}
data.Props["SiteURL"] = a.GetSiteURL()
if teamName != "select_team" {
data.Props["TeamLink"] = landingURL + "/pl/" + post.Id
} else {
data.Props["TeamLink"] = landingURL
}
t := getFormattedPostTime(recipient, post, useMilitaryTime, translateFunc)
info := map[string]interface{}{
"Hour": t.Hour,
"Minute": t.Minute,
"TimeZone": t.TimeZone,
"Month": t.Month,
"Day": t.Day,
}
if channel.Type == model.CHANNEL_DIRECT {
if emailNotificationContentsType == model.EMAIL_NOTIFICATION_CONTENTS_FULL {
data.Props["BodyText"] = translateFunc("app.notification.body.intro.direct.full")
data.Props["Info1"] = ""
info["SenderName"] = senderName
data.Props["Info2"] = translateFunc("app.notification.body.text.direct.full", info)
} else {
data.Props["BodyText"] = translateFunc("app.notification.body.intro.direct.generic", map[string]interface{}{
"SenderName": senderName,
})
data.Props["Info"] = translateFunc("app.notification.body.text.direct.generic", info)
}
} else if channel.Type == model.CHANNEL_GROUP {
if emailNotificationContentsType == model.EMAIL_NOTIFICATION_CONTENTS_FULL {
data.Props["BodyText"] = translateFunc("app.notification.body.intro.group_message.full")
data.Props["Info1"] = translateFunc("app.notification.body.text.group_message.full",
map[string]interface{}{
"ChannelName": channelName,
})
info["SenderName"] = senderName
data.Props["Info2"] = translateFunc("app.notification.body.text.group_message.full2", info)
} else {
data.Props["BodyText"] = translateFunc("app.notification.body.intro.group_message.generic", map[string]interface{}{
"SenderName": senderName,
})
data.Props["Info"] = translateFunc("app.notification.body.text.group_message.generic", info)
}
} else {
if emailNotificationContentsType == model.EMAIL_NOTIFICATION_CONTENTS_FULL {
data.Props["BodyText"] = translateFunc("app.notification.body.intro.notification.full")
data.Props["Info1"] = translateFunc("app.notification.body.text.notification.full",
map[string]interface{}{
"ChannelName": channelName,
})
info["SenderName"] = senderName
data.Props["Info2"] = translateFunc("app.notification.body.text.notification.full2", info)
} else {
data.Props["BodyText"] = translateFunc("app.notification.body.intro.notification.generic", map[string]interface{}{
"SenderName": senderName,
})
data.Props["Info"] = translateFunc("app.notification.body.text.notification.generic", info)
}
}
data.Props["Button"] = translateFunc("api.templates.post_body.button")
return a.Srv().TemplatesContainer().RenderToString(templateName, data)
}
type formattedPostTime struct {
Time time.Time
Year string
Month string
Day string
Hour string
Minute string
TimeZone string
}
func getFormattedPostTime(user *model.User, post *model.Post, useMilitaryTime bool, translateFunc i18n.TranslateFunc) formattedPostTime {
preferredTimezone := user.GetPreferredTimezone()
postTime := time.Unix(post.CreateAt/1000, 0)
zone, _ := postTime.Zone()
localTime := postTime
if preferredTimezone != "" {
loc, _ := time.LoadLocation(preferredTimezone)
if loc != nil {
localTime = postTime.In(loc)
zone, _ = localTime.Zone()
}
}
hour := localTime.Format("15")
period := ""
if !useMilitaryTime {
hour = localTime.Format("3")
period = " " + localTime.Format("PM")
}
return formattedPostTime{
Time: localTime,
Year: fmt.Sprintf("%d", localTime.Year()),
Month: translateFunc(localTime.Month().String()),
Day: fmt.Sprintf("%d", localTime.Day()),
Hour: hour,
Minute: fmt.Sprintf("%02d"+period, localTime.Minute()),
TimeZone: zone,
}
}
func (a *App) generateHyperlinkForChannels(postMessage, teamName, teamURL string) (string, *model.AppError) {
team, err := a.GetTeamByName(teamName)
if err != nil {
return "", err
}
channelNames := model.ChannelMentions(postMessage)
if len(channelNames) == 0 {
return postMessage, nil
}
channels, err := a.GetChannelsByNames(channelNames, team.Id)
if err != nil {
return "", err
}
visited := make(map[string]bool)
for _, ch := range channels {
if !visited[ch.Id] && ch.Type == model.CHANNEL_OPEN {
channelURL := teamURL + "/channels/" + ch.Name
channelHyperLink := fmt.Sprintf("<a href='%s'>%s</a>", channelURL, "~"+ch.Name)
postMessage = strings.Replace(postMessage, "~"+ch.Name, channelHyperLink, -1)
visited[ch.Id] = true
}
}
return postMessage, nil
}
func (s *Server) GetMessageForNotification(post *model.Post, translateFunc i18n.TranslateFunc) string {
if strings.TrimSpace(post.Message) != "" || len(post.FileIds) == 0 {
return post.Message
}
// extract the filenames from their paths and determine what type of files are attached
infos, err := s.Store.FileInfo().GetForPost(post.Id, true, false, true)
if err != nil {
mlog.Warn("Encountered error when getting files for notification message", mlog.String("post_id", post.Id), mlog.Err(err))
}
filenames := make([]string, len(infos))
onlyImages := true
for i, info := range infos {
if escaped, err := url.QueryUnescape(filepath.Base(info.Name)); err != nil {
// this should never error since filepath was escaped using url.QueryEscape
filenames[i] = escaped
} else {
filenames[i] = info.Name
}
onlyImages = onlyImages && info.IsImage()
}
props := map[string]interface{}{"Filenames": strings.Join(filenames, ", ")}
if onlyImages {
return translateFunc("api.post.get_message_for_notification.images_sent", len(filenames), props)
}
return translateFunc("api.post.get_message_for_notification.files_sent", len(filenames), props)
}
func (a *App) GetMessageForNotification(post *model.Post, translateFunc i18n.TranslateFunc) string {
return a.Srv().GetMessageForNotification(post, translateFunc)
}