forked from mattermost/mattermost
-
Notifications
You must be signed in to change notification settings - Fork 0
/
notification.go
954 lines (812 loc) · 31.6 KB
/
notification.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
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
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
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
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
// Copyright (c) 2016-present Mattermost, Inc. All Rights Reserved.
// See License.txt for license information.
package app
import (
"fmt"
"html"
"html/template"
"io/ioutil"
"net/http"
"net/url"
"path/filepath"
"regexp"
"sort"
"strings"
"time"
"unicode"
l4g "github.com/alecthomas/log4go"
"github.com/mattermost/platform/einterfaces"
"github.com/mattermost/platform/model"
"github.com/mattermost/platform/store"
"github.com/mattermost/platform/utils"
"github.com/nicksnyder/go-i18n/i18n"
)
func SendNotifications(post *model.Post, team *model.Team, channel *model.Channel, sender *model.User) ([]string, *model.AppError) {
pchan := Srv.Store.User().GetAllProfilesInChannel(channel.Id, true)
cmnchan := Srv.Store.Channel().GetAllChannelMembersNotifyPropsForChannel(channel.Id, true)
var fchan store.StoreChannel
if len(post.FileIds) != 0 {
fchan = Srv.Store.FileInfo().GetForPost(post.Id, true, true)
}
var profileMap map[string]*model.User
if result := <-pchan; result.Err != nil {
return nil, result.Err
} else {
profileMap = result.Data.(map[string]*model.User)
}
var channelMemberNotifyPropsMap map[string]model.StringMap
if result := <-cmnchan; result.Err != nil {
return nil, result.Err
} else {
channelMemberNotifyPropsMap = result.Data.(map[string]model.StringMap)
}
mentionedUserIds := make(map[string]bool)
allActivityPushUserIds := []string{}
hereNotification := false
channelNotification := false
allNotification := false
updateMentionChans := []store.StoreChannel{}
if channel.Type == model.CHANNEL_DIRECT {
var otherUserId string
if userIds := strings.Split(channel.Name, "__"); userIds[0] == post.UserId {
otherUserId = userIds[1]
} else {
otherUserId = userIds[0]
}
if _, ok := profileMap[otherUserId]; ok {
mentionedUserIds[otherUserId] = true
}
if post.Props["from_webhook"] == "true" {
mentionedUserIds[post.UserId] = true
}
} else {
keywords := GetMentionKeywordsInChannel(profileMap)
var potentialOtherMentions []string
mentionedUserIds, potentialOtherMentions, hereNotification, channelNotification, allNotification = GetExplicitMentions(post.Message, keywords)
// get users that have comment thread mentions enabled
if len(post.RootId) > 0 {
if result := <-Srv.Store.Post().Get(post.RootId); result.Err != nil {
return nil, result.Err
} else {
list := result.Data.(*model.PostList)
for _, threadPost := range list.Posts {
profile := profileMap[threadPost.UserId]
if profile != nil && (profile.NotifyProps["comments"] == "any" || (profile.NotifyProps["comments"] == "root" && threadPost.Id == list.Order[0])) {
mentionedUserIds[threadPost.UserId] = true
}
}
}
}
// prevent the user from mentioning themselves
if post.Props["from_webhook"] != "true" {
delete(mentionedUserIds, post.UserId)
}
if len(potentialOtherMentions) > 0 {
if result := <-Srv.Store.User().GetProfilesByUsernames(potentialOtherMentions, team.Id); result.Err == nil {
outOfChannelMentions := result.Data.([]*model.User)
if channel.Type != model.CHANNEL_GROUP {
go sendOutOfChannelMentions(sender, post, team.Id, outOfChannelMentions)
}
}
}
// find which users in the channel are set up to always receive mobile notifications
for _, profile := range profileMap {
if (profile.NotifyProps[model.PUSH_NOTIFY_PROP] == model.USER_NOTIFY_ALL ||
channelMemberNotifyPropsMap[profile.Id][model.PUSH_NOTIFY_PROP] == model.CHANNEL_NOTIFY_ALL) &&
(post.UserId != profile.Id || post.Props["from_webhook"] == "true") &&
!post.IsSystemMessage() {
allActivityPushUserIds = append(allActivityPushUserIds, profile.Id)
}
}
}
mentionedUsersList := make([]string, 0, len(mentionedUserIds))
for id := range mentionedUserIds {
mentionedUsersList = append(mentionedUsersList, id)
updateMentionChans = append(updateMentionChans, Srv.Store.Channel().IncrementMentionCount(post.ChannelId, id))
}
senderName := ""
channelName := ""
if post.IsSystemMessage() {
senderName = utils.T("system.message.name")
} else {
if value, ok := post.Props["override_username"]; ok && post.Props["from_webhook"] == "true" {
senderName = value.(string)
} else {
senderName = sender.Username
}
}
if channel.Type == model.CHANNEL_GROUP {
userList := []*model.User{}
for _, u := range profileMap {
if u.Id != sender.Id {
userList = append(userList, u)
}
}
userList = append(userList, sender)
channelName = model.GetGroupDisplayNameFromUsers(userList, false)
} else {
channelName = channel.DisplayName
}
var senderUsername string
if value, ok := post.Props["override_username"]; ok && post.Props["from_webhook"] == "true" {
senderUsername = value.(string)
} else {
senderUsername = sender.Username
}
if utils.Cfg.EmailSettings.SendEmailNotifications {
for _, id := range mentionedUsersList {
userAllowsEmails := profileMap[id].NotifyProps[model.EMAIL_NOTIFY_PROP] != "false"
if channelEmail, ok := channelMemberNotifyPropsMap[id][model.EMAIL_NOTIFY_PROP]; ok {
if channelEmail != model.CHANNEL_NOTIFY_DEFAULT {
userAllowsEmails = channelEmail != "false"
}
}
var status *model.Status
var err *model.AppError
if status, err = GetStatus(id); err != nil {
status = &model.Status{
UserId: id,
Status: model.STATUS_OFFLINE,
Manual: false,
LastActivityAt: 0,
ActiveChannel: "",
}
}
if userAllowsEmails && status.Status != model.STATUS_ONLINE && profileMap[id].DeleteAt == 0 {
sendNotificationEmail(post, profileMap[id], channel, team, senderName, sender)
}
}
}
T := utils.GetUserTranslations(sender.Locale)
// If the channel has more than 1K users then @here is disabled
if hereNotification && int64(len(profileMap)) > *utils.Cfg.TeamSettings.MaxNotificationsPerChannel {
hereNotification = false
SendEphemeralPost(
team.Id,
post.UserId,
&model.Post{
ChannelId: post.ChannelId,
Message: T("api.post.disabled_here", map[string]interface{}{"Users": *utils.Cfg.TeamSettings.MaxNotificationsPerChannel}),
CreateAt: post.CreateAt + 1,
},
)
}
// If the channel has more than 1K users then @channel is disabled
if channelNotification && int64(len(profileMap)) > *utils.Cfg.TeamSettings.MaxNotificationsPerChannel {
SendEphemeralPost(
team.Id,
post.UserId,
&model.Post{
ChannelId: post.ChannelId,
Message: T("api.post.disabled_channel", map[string]interface{}{"Users": *utils.Cfg.TeamSettings.MaxNotificationsPerChannel}),
CreateAt: post.CreateAt + 1,
},
)
}
// If the channel has more than 1K users then @all is disabled
if allNotification && int64(len(profileMap)) > *utils.Cfg.TeamSettings.MaxNotificationsPerChannel {
SendEphemeralPost(
team.Id,
post.UserId,
&model.Post{
ChannelId: post.ChannelId,
Message: T("api.post.disabled_all", map[string]interface{}{"Users": *utils.Cfg.TeamSettings.MaxNotificationsPerChannel}),
CreateAt: post.CreateAt + 1,
},
)
}
// Make sure all mention updates are complete to prevent race
// Probably better to batch these DB updates in the future
// MUST be completed before push notifications send
for _, uchan := range updateMentionChans {
if result := <-uchan; result.Err != nil {
l4g.Warn(utils.T("api.post.update_mention_count_and_forget.update_error"), post.Id, post.ChannelId, result.Err)
}
}
sendPushNotifications := false
if *utils.Cfg.EmailSettings.SendPushNotifications {
pushServer := *utils.Cfg.EmailSettings.PushNotificationServer
if pushServer == model.MHPNS && (!utils.IsLicensed || !*utils.License.Features.MHPNS) {
l4g.Warn(utils.T("api.post.send_notifications_and_forget.push_notification.mhpnsWarn"))
sendPushNotifications = false
} else {
sendPushNotifications = true
}
}
if sendPushNotifications {
for _, id := range mentionedUsersList {
var status *model.Status
var err *model.AppError
if status, err = GetStatus(id); err != nil {
status = &model.Status{UserId: id, Status: model.STATUS_OFFLINE, Manual: false, LastActivityAt: 0, ActiveChannel: ""}
}
if ShouldSendPushNotification(profileMap[id], channelMemberNotifyPropsMap[id], true, status, post) {
sendPushNotification(post, profileMap[id], channel, senderName, channelName, true)
}
}
for _, id := range allActivityPushUserIds {
if _, ok := mentionedUserIds[id]; !ok {
var status *model.Status
var err *model.AppError
if status, err = GetStatus(id); err != nil {
status = &model.Status{UserId: id, Status: model.STATUS_OFFLINE, Manual: false, LastActivityAt: 0, ActiveChannel: ""}
}
if ShouldSendPushNotification(profileMap[id], channelMemberNotifyPropsMap[id], false, status, post) {
sendPushNotification(post, profileMap[id], channel, senderName, channelName, false)
}
}
}
}
message := model.NewWebSocketEvent(model.WEBSOCKET_EVENT_POSTED, "", post.ChannelId, "", nil)
message.Add("post", post.ToJson())
message.Add("channel_type", channel.Type)
message.Add("channel_display_name", channelName)
message.Add("channel_name", channel.Name)
message.Add("sender_name", senderUsername)
message.Add("team_id", team.Id)
if len(post.FileIds) != 0 && fchan != nil {
message.Add("otherFile", "true")
var infos []*model.FileInfo
if result := <-fchan; result.Err != nil {
l4g.Warn(utils.T("api.post.send_notifications.files.error"), post.Id, result.Err)
} else {
infos = result.Data.([]*model.FileInfo)
}
for _, info := range infos {
if info.IsImage() {
message.Add("image", "true")
break
}
}
}
if len(mentionedUsersList) != 0 {
message.Add("mentions", model.ArrayToJson(mentionedUsersList))
}
Publish(message)
return mentionedUsersList, nil
}
func sendNotificationEmail(post *model.Post, user *model.User, channel *model.Channel, team *model.Team, senderName string, sender *model.User) *model.AppError {
if channel.IsGroupOrDirect() {
if result := <-Srv.Store.Team().GetTeamsByUserId(user.Id); result.Err != nil {
return result.Err
} else {
// if the recipient isn't in the current user's team, just pick one
teams := result.Data.([]*model.Team)
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: utils.Cfg.TeamSettings.SiteName}
}
}
}
if *utils.Cfg.EmailSettings.EnableEmailBatching {
var sendBatched bool
if result := <-Srv.Store.Preference().Get(user.Id, model.PREFERENCE_CATEGORY_NOTIFICATIONS, model.PREFERENCE_NAME_EMAIL_INTERVAL); result.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 = result.Data.(model.Preference).Value != model.PREFERENCE_EMAIL_INTERVAL_NO_BATCHING_SECONDS
}
if sendBatched {
if err := 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 := utils.GetUserTranslations(user.Locale)
var subjectText string
if channel.Type == model.CHANNEL_DIRECT {
subjectText = getDirectMessageNotificationEmailSubject(post, translateFunc, utils.Cfg.TeamSettings.SiteName, senderName)
} else {
subjectText = getNotificationEmailSubject(post, translateFunc, utils.Cfg.TeamSettings.SiteName, team.DisplayName)
}
emailNotificationContentsType := model.EMAIL_NOTIFICATION_CONTENTS_FULL
if utils.IsLicensed && *utils.License.Features.EmailNotificationContents {
emailNotificationContentsType = *utils.Cfg.EmailSettings.EmailNotificationContentsType
}
teamURL := utils.GetSiteURL() + "/" + team.Name
var bodyText = getNotificationEmailBody(user, post, channel, senderName, team.Name, teamURL, emailNotificationContentsType, translateFunc)
go func() {
if err := utils.SendMail(user.Email, html.UnescapeString(subjectText), bodyText); err != nil {
l4g.Error(utils.T("api.post.send_notifications_and_forget.send.error"), user.Email, err)
}
}()
if einterfaces.GetMetricsInterface() != nil {
einterfaces.GetMetricsInterface().IncrementPostSentEmail()
}
return nil
}
/**
* Computes the subject line for direct notification email messages
*/
func getDirectMessageNotificationEmailSubject(post *model.Post, translateFunc i18n.TranslateFunc, siteName string, senderName string) string {
t := getFormattedPostTime(post, 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(post *model.Post, translateFunc i18n.TranslateFunc, siteName string, teamName string) string {
t := getFormattedPostTime(post, 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 email body for notification messages
*/
func getNotificationEmailBody(recipient *model.User, post *model.Post, channel *model.Channel, senderName string, teamName string, teamURL string, emailNotificationContentsType string, translateFunc i18n.TranslateFunc) string {
// only include message contents in notification email if email notification contents type is set to full
var bodyPage *utils.HTMLTemplate
if emailNotificationContentsType == model.EMAIL_NOTIFICATION_CONTENTS_FULL {
bodyPage = utils.NewHTMLTemplate("post_body_full", recipient.Locale)
bodyPage.Props["PostMessage"] = GetMessageForNotification(post, translateFunc)
} else {
bodyPage = utils.NewHTMLTemplate("post_body_generic", recipient.Locale)
}
bodyPage.Props["SiteURL"] = utils.GetSiteURL()
if teamName != "select_team" {
bodyPage.Props["TeamLink"] = teamURL + "/pl/" + post.Id
} else {
bodyPage.Props["TeamLink"] = teamURL
}
var channelName = channel.DisplayName
if channel.Type == model.CHANNEL_GROUP {
channelName = translateFunc("api.templates.channel_name.group")
}
t := getFormattedPostTime(post, translateFunc)
var bodyText string
var info string
if channel.Type == model.CHANNEL_DIRECT {
if emailNotificationContentsType == model.EMAIL_NOTIFICATION_CONTENTS_FULL {
bodyText = translateFunc("app.notification.body.intro.direct.full")
info = translateFunc("app.notification.body.text.direct.full",
map[string]interface{}{
"SenderName": senderName,
"Hour": t.Hour,
"Minute": t.Minute,
"TimeZone": t.TimeZone,
"Month": t.Month,
"Day": t.Day,
})
} else {
bodyText = translateFunc("app.notification.body.intro.direct.generic", map[string]interface{}{
"SenderName": senderName,
})
info = translateFunc("app.notification.body.text.direct.generic",
map[string]interface{}{
"Hour": t.Hour,
"Minute": t.Minute,
"TimeZone": t.TimeZone,
"Month": t.Month,
"Day": t.Day,
})
}
} else {
if emailNotificationContentsType == model.EMAIL_NOTIFICATION_CONTENTS_FULL {
bodyText = translateFunc("app.notification.body.intro.notification.full")
info = translateFunc("app.notification.body.text.notification.full",
map[string]interface{}{
"ChannelName": channelName,
"SenderName": senderName,
"Hour": t.Hour,
"Minute": t.Minute,
"TimeZone": t.TimeZone,
"Month": t.Month,
"Day": t.Day,
})
} else {
bodyText = translateFunc("app.notification.body.intro.notification.generic", map[string]interface{}{
"SenderName": senderName,
})
info = translateFunc("app.notification.body.text.notification.generic",
map[string]interface{}{
"Hour": t.Hour,
"Minute": t.Minute,
"TimeZone": t.TimeZone,
"Month": t.Month,
"Day": t.Day,
})
}
}
bodyPage.Props["BodyText"] = bodyText
bodyPage.Html["Info"] = template.HTML(info)
bodyPage.Props["Button"] = translateFunc("api.templates.post_body.button")
return bodyPage.Render()
}
type formattedPostTime struct {
Time time.Time
Year string
Month string
Day string
Hour string
Minute string
TimeZone string
}
func getFormattedPostTime(post *model.Post, translateFunc i18n.TranslateFunc) formattedPostTime {
tm := time.Unix(post.CreateAt/1000, 0)
zone, _ := tm.Zone()
return formattedPostTime{
Time: tm,
Year: fmt.Sprintf("%d", tm.Year()),
Month: translateFunc(tm.Month().String()),
Day: fmt.Sprintf("%d", tm.Day()),
Hour: fmt.Sprintf("%02d", tm.Hour()),
Minute: fmt.Sprintf("%02d", tm.Minute()),
TimeZone: zone,
}
}
func GetMessageForNotification(post *model.Post, translateFunc i18n.TranslateFunc) string {
if len(strings.TrimSpace(post.Message)) != 0 || len(post.FileIds) == 0 {
return post.Message
}
// extract the filenames from their paths and determine what type of files are attached
var infos []*model.FileInfo
if result := <-Srv.Store.FileInfo().GetForPost(post.Id, true, true); result.Err != nil {
l4g.Warn(utils.T("api.post.get_message_for_notification.get_files.error"), post.Id, result.Err)
} else {
infos = result.Data.([]*model.FileInfo)
}
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)
} else {
return translateFunc("api.post.get_message_for_notification.files_sent", len(filenames), props)
}
}
func sendPushNotification(post *model.Post, user *model.User, channel *model.Channel, senderName, channelName string, wasMentioned bool) *model.AppError {
sessions, err := getMobileAppSessions(user.Id)
if err != nil {
return err
}
if channel.Type == model.CHANNEL_DIRECT {
channelName = senderName
}
userLocale := utils.GetUserTranslations(user.Locale)
msg := model.PushNotification{}
if badge := <-Srv.Store.User().GetUnreadCount(user.Id); badge.Err != nil {
msg.Badge = 1
l4g.Error(utils.T("store.sql_user.get_unread_count.app_error"), user.Id, badge.Err)
} else {
msg.Badge = int(badge.Data.(int64))
}
msg.Type = model.PUSH_TYPE_MESSAGE
msg.TeamId = channel.TeamId
msg.ChannelId = channel.Id
msg.ChannelName = channel.Name
msg.SenderId = post.UserId
if ou, ok := post.Props["override_username"]; ok && ou != nil {
msg.OverrideUsername = ou.(string)
}
if oi, ok := post.Props["override_icon_url"]; ok && oi != nil {
msg.OverrideIconUrl = oi.(string)
}
if fw, ok := post.Props["from_webhook"]; ok && fw != nil {
msg.FromWebhook = fw.(string)
}
if *utils.Cfg.EmailSettings.PushNotificationContents == model.FULL_NOTIFICATION {
if channel.Type == model.CHANNEL_DIRECT {
msg.Category = model.CATEGORY_DM
msg.Message = senderName + ": " + model.ClearMentionTags(post.Message)
} else {
msg.Message = senderName + userLocale("api.post.send_notifications_and_forget.push_in") + channelName + ": " + model.ClearMentionTags(post.Message)
}
} else if *utils.Cfg.EmailSettings.PushNotificationContents == model.GENERIC_NO_CHANNEL_NOTIFICATION {
if channel.Type == model.CHANNEL_DIRECT {
msg.Category = model.CATEGORY_DM
msg.Message = senderName + userLocale("api.post.send_notifications_and_forget.push_message")
} else if wasMentioned || channel.Type == model.CHANNEL_GROUP {
msg.Message = senderName + userLocale("api.post.send_notifications_and_forget.push_mention_no_channel")
} else {
msg.Message = senderName + userLocale("api.post.send_notifications_and_forget.push_non_mention_no_channel")
}
} else {
if channel.Type == model.CHANNEL_DIRECT {
msg.Category = model.CATEGORY_DM
msg.Message = senderName + userLocale("api.post.send_notifications_and_forget.push_message")
} else if wasMentioned || channel.Type == model.CHANNEL_GROUP {
msg.Message = senderName + userLocale("api.post.send_notifications_and_forget.push_mention") + channelName
} else {
msg.Message = senderName + userLocale("api.post.send_notifications_and_forget.push_non_mention") + channelName
}
}
// If the post only has images then push an appropriate message
if len(post.Message) == 0 && post.FileIds != nil && len(post.FileIds) > 0 {
if channel.Type == model.CHANNEL_DIRECT {
msg.Message = senderName + userLocale("api.post.send_notifications_and_forget.push_image_only_dm")
} else {
msg.Message = senderName + userLocale("api.post.send_notifications_and_forget.push_image_only") + channelName
}
}
l4g.Debug("Sending push notification for user %v with msg of '%v'", user.Id, msg.Message)
for _, session := range sessions {
tmpMessage := *model.PushNotificationFromJson(strings.NewReader(msg.ToJson()))
tmpMessage.SetDeviceIdAndPlatform(session.DeviceId)
l4g.Debug("Sending push notification to device %v for user %v with msg of '%v'", tmpMessage.DeviceId, user.Id, msg.Message)
go sendToPushProxy(tmpMessage, session)
if einterfaces.GetMetricsInterface() != nil {
einterfaces.GetMetricsInterface().IncrementPostSentPush()
}
}
return nil
}
func ClearPushNotification(userId string, channelId string) *model.AppError {
sessions, err := getMobileAppSessions(userId)
if err != nil {
return err
}
msg := model.PushNotification{}
msg.Type = model.PUSH_TYPE_CLEAR
msg.ChannelId = channelId
msg.ContentAvailable = 0
if badge := <-Srv.Store.User().GetUnreadCount(userId); badge.Err != nil {
msg.Badge = 0
l4g.Error(utils.T("store.sql_user.get_unread_count.app_error"), userId, badge.Err)
} else {
msg.Badge = int(badge.Data.(int64))
}
l4g.Debug(utils.T("api.post.send_notifications_and_forget.clear_push_notification.debug"), msg.DeviceId, msg.ChannelId)
for _, session := range sessions {
tmpMessage := *model.PushNotificationFromJson(strings.NewReader(msg.ToJson()))
tmpMessage.SetDeviceIdAndPlatform(session.DeviceId)
go sendToPushProxy(tmpMessage, session)
}
return nil
}
func sendToPushProxy(msg model.PushNotification, session *model.Session) {
msg.ServerId = utils.CfgDiagnosticId
request, _ := http.NewRequest("POST", *utils.Cfg.EmailSettings.PushNotificationServer+model.API_URL_SUFFIX_V1+"/send_push", strings.NewReader(msg.ToJson()))
if resp, err := utils.HttpClient().Do(request); err != nil {
l4g.Error("Device push reported as error for UserId=%v SessionId=%v message=%v", session.UserId, session.Id, err.Error())
} else {
pushResponse := model.PushResponseFromJson(resp.Body)
if resp.Body != nil {
ioutil.ReadAll(resp.Body)
resp.Body.Close()
}
if pushResponse[model.PUSH_STATUS] == model.PUSH_STATUS_REMOVE {
l4g.Info("Device was reported as removed for UserId=%v SessionId=%v removing push for this session", session.UserId, session.Id)
AttachDeviceId(session.Id, "", session.ExpiresAt)
ClearSessionCacheForUser(session.UserId)
}
if pushResponse[model.PUSH_STATUS] == model.PUSH_STATUS_FAIL {
l4g.Error("Device push reported as error for UserId=%v SessionId=%v message=%v", session.UserId, session.Id, pushResponse[model.PUSH_STATUS_ERROR_MSG])
}
}
}
func getMobileAppSessions(userId string) ([]*model.Session, *model.AppError) {
if result := <-Srv.Store.Session().GetSessionsWithActiveDeviceIds(userId); result.Err != nil {
return nil, result.Err
} else {
return result.Data.([]*model.Session), nil
}
}
func sendOutOfChannelMentions(sender *model.User, post *model.Post, teamId string, users []*model.User) *model.AppError {
if len(users) == 0 {
return nil
}
var usernames []string
for _, user := range users {
usernames = append(usernames, user.Username)
}
sort.Strings(usernames)
T := utils.GetUserTranslations(sender.Locale)
var message string
if len(usernames) == 1 {
message = T("api.post.check_for_out_of_channel_mentions.message.one", map[string]interface{}{
"Username": usernames[0],
})
} else {
message = T("api.post.check_for_out_of_channel_mentions.message.multiple", map[string]interface{}{
"Usernames": strings.Join(usernames[:len(usernames)-1], ", "),
"LastUsername": usernames[len(usernames)-1],
})
}
SendEphemeralPost(
teamId,
post.UserId,
&model.Post{
ChannelId: post.ChannelId,
Message: message,
CreateAt: post.CreateAt + 1,
},
)
return nil
}
// Given a message and a map mapping mention keywords to the users who use them, returns a map of mentioned
// users and a slice of potential mention users not in the channel and whether or not @here was mentioned.
func GetExplicitMentions(message string, keywords map[string][]string) (map[string]bool, []string, bool, bool, bool) {
mentioned := make(map[string]bool)
potentialOthersMentioned := make([]string, 0)
systemMentions := map[string]bool{"@here": true, "@channel": true, "@all": true}
hereMentioned := false
allMentioned := false
channelMentioned := false
addMentionedUsers := func(ids []string) {
for _, id := range ids {
mentioned[id] = true
}
}
message = removeCodeFromMessage(message)
for _, word := range strings.FieldsFunc(message, func(c rune) bool {
// Split on any whitespace or punctuation that can't be part of an at mention
return !(c == '.' || c == '-' || c == '_' || c == '@' || unicode.IsLetter(c) || unicode.IsNumber(c))
}) {
isMention := false
if word == "@here" {
hereMentioned = true
}
if word == "@channel" {
channelMentioned = true
}
if word == "@all" {
allMentioned = true
}
// Non-case-sensitive check for regular keys
if ids, match := keywords[strings.ToLower(word)]; match {
addMentionedUsers(ids)
isMention = true
}
// Case-sensitive check for first name
if ids, match := keywords[word]; match {
addMentionedUsers(ids)
isMention = true
}
if isMention {
continue
}
if strings.ContainsAny(word, ".-") {
// This word contains a character that may be the end of a sentence, so split further
splitWords := strings.FieldsFunc(word, func(c rune) bool {
return c == '.' || c == '-'
})
for _, splitWord := range splitWords {
if splitWord == "@here" {
hereMentioned = true
}
if splitWord == "@all" {
allMentioned = true
}
if splitWord == "@channel" {
channelMentioned = true
}
// Non-case-sensitive check for regular keys
if ids, match := keywords[strings.ToLower(splitWord)]; match {
addMentionedUsers(ids)
}
// Case-sensitive check for first name
if ids, match := keywords[splitWord]; match {
addMentionedUsers(ids)
} else if _, ok := systemMentions[word]; !ok && strings.HasPrefix(word, "@") {
username := word[1:len(splitWord)]
potentialOthersMentioned = append(potentialOthersMentioned, username)
}
}
} else if _, ok := systemMentions[word]; !ok && strings.HasPrefix(word, "@") {
username := word[1:]
potentialOthersMentioned = append(potentialOthersMentioned, username)
}
}
return mentioned, potentialOthersMentioned, hereMentioned, channelMentioned, allMentioned
}
// Matches a line containing only ``` and a potential language definition, any number of lines not containing ```,
// and then either a line containing only ``` or the end of the text
var codeBlockPattern = regexp.MustCompile("(?m)^[^\\S\n]*\\`\\`\\`.*$[\\s\\S]+?(^[^\\S\n]*\\`\\`\\`$|\\z)")
// Matches a backquote, either some text or any number of non-empty lines, and then a final backquote
var inlineCodePattern = regexp.MustCompile("(?m)\\`(?:.+?|.*?\n(.*?\\S.*?\n)*.*?)\\`")
// Strips pre-formatted text and code blocks from a Markdown string by replacing them with whitespace
func removeCodeFromMessage(message string) string {
if strings.Contains(message, "```") {
message = codeBlockPattern.ReplaceAllString(message, "")
}
// Replace with a space to prevent cases like "user`code`name" from turning into "username"
if strings.Contains(message, "`") {
message = inlineCodePattern.ReplaceAllString(message, " ")
}
return message
}
// Given a map of user IDs to profiles, returns a list of mention
// keywords for all users in the channel.
func GetMentionKeywordsInChannel(profiles map[string]*model.User) map[string][]string {
keywords := make(map[string][]string)
for id, profile := range profiles {
userMention := "@" + strings.ToLower(profile.Username)
keywords[userMention] = append(keywords[userMention], id)
if len(profile.NotifyProps["mention_keys"]) > 0 {
// Add all the user's mention keys
splitKeys := strings.Split(profile.NotifyProps["mention_keys"], ",")
for _, k := range splitKeys {
// note that these are made lower case so that we can do a case insensitive check for them
key := strings.ToLower(k)
keywords[key] = append(keywords[key], id)
}
}
// If turned on, add the user's case sensitive first name
if profile.NotifyProps["first_name"] == "true" {
keywords[profile.FirstName] = append(keywords[profile.FirstName], profile.Id)
}
// Add @channel and @all to keywords if user has them turned on
if int64(len(profiles)) < *utils.Cfg.TeamSettings.MaxNotificationsPerChannel && profile.NotifyProps["channel"] == "true" {
keywords["@channel"] = append(keywords["@channel"], profile.Id)
keywords["@all"] = append(keywords["@all"], profile.Id)
status := GetStatusFromCache(profile.Id)
if status != nil && status.Status == model.STATUS_ONLINE {
keywords["@here"] = append(keywords["@here"], profile.Id)
}
}
}
return keywords
}
func ShouldSendPushNotification(user *model.User, channelNotifyProps model.StringMap, wasMentioned bool, status *model.Status, post *model.Post) bool {
return DoesNotifyPropsAllowPushNotification(user, channelNotifyProps, post, wasMentioned) &&
DoesStatusAllowPushNotification(user.NotifyProps, status, post.ChannelId)
}
func DoesNotifyPropsAllowPushNotification(user *model.User, channelNotifyProps model.StringMap, post *model.Post, wasMentioned bool) bool {
userNotifyProps := user.NotifyProps
userNotify := userNotifyProps[model.PUSH_NOTIFY_PROP]
channelNotify, ok := channelNotifyProps[model.PUSH_NOTIFY_PROP]
if post.IsSystemMessage() {
return false
}
if channelNotify == model.USER_NOTIFY_NONE {
return false
}
if channelNotify == model.CHANNEL_NOTIFY_MENTION && !wasMentioned {
return false
}
if userNotify == model.USER_NOTIFY_MENTION && (!ok || channelNotify == model.CHANNEL_NOTIFY_DEFAULT) && !wasMentioned {
return false
}
if (userNotify == model.USER_NOTIFY_ALL || channelNotify == model.CHANNEL_NOTIFY_ALL) &&
(post.UserId != user.Id || post.Props["from_webhook"] == "true") {
return true
}
if userNotify == model.USER_NOTIFY_NONE &&
(!ok || channelNotify == model.CHANNEL_NOTIFY_DEFAULT) {
return false
}
return true
}
func DoesStatusAllowPushNotification(userNotifyProps model.StringMap, status *model.Status, channelId string) bool {
if pushStatus, ok := userNotifyProps["push_status"]; (pushStatus == model.STATUS_ONLINE || !ok) && (status.ActiveChannel != channelId || model.GetMillis()-status.LastActivityAt > model.STATUS_CHANNEL_TIMEOUT) {
return true
} else if pushStatus == model.STATUS_AWAY && (status.Status == model.STATUS_AWAY || status.Status == model.STATUS_OFFLINE) {
return true
} else if pushStatus == model.STATUS_OFFLINE && status.Status == model.STATUS_OFFLINE {
return true
}
return false
}