github.com/lologarithm/mattermost-server@v5.3.2-0.20181002060438-c82a84ed765b+incompatible/app/notification.go (about) 1 // Copyright (c) 2016-present Mattermost, Inc. All Rights Reserved. 2 // See License.txt for license information. 3 4 package app 5 6 import ( 7 "fmt" 8 "sort" 9 "strings" 10 "unicode" 11 12 "github.com/mattermost/mattermost-server/mlog" 13 "github.com/mattermost/mattermost-server/model" 14 "github.com/mattermost/mattermost-server/store" 15 "github.com/mattermost/mattermost-server/utils" 16 "github.com/mattermost/mattermost-server/utils/markdown" 17 ) 18 19 const ( 20 THREAD_ANY = "any" 21 THREAD_ROOT = "root" 22 ) 23 24 func (a *App) SendNotifications(post *model.Post, team *model.Team, channel *model.Channel, sender *model.User, parentPostList *model.PostList) ([]string, *model.AppError) { 25 // Do not send notifications in archived channels 26 if channel.DeleteAt > 0 { 27 return []string{}, nil 28 } 29 30 pchan := a.Srv.Store.User().GetAllProfilesInChannel(channel.Id, true) 31 cmnchan := a.Srv.Store.Channel().GetAllChannelMembersNotifyPropsForChannel(channel.Id, true) 32 var fchan store.StoreChannel 33 34 if len(post.FileIds) != 0 { 35 fchan = a.Srv.Store.FileInfo().GetForPost(post.Id, true, true) 36 } 37 38 result := <-pchan 39 if result.Err != nil { 40 return nil, result.Err 41 } 42 profileMap := result.Data.(map[string]*model.User) 43 44 result = <-cmnchan 45 if result.Err != nil { 46 return nil, result.Err 47 } 48 channelMemberNotifyPropsMap := result.Data.(map[string]model.StringMap) 49 50 mentionedUserIds := make(map[string]bool) 51 threadMentionedUserIds := make(map[string]string) 52 allActivityPushUserIds := []string{} 53 hereNotification := false 54 channelNotification := false 55 allNotification := false 56 updateMentionChans := []store.StoreChannel{} 57 58 if channel.Type == model.CHANNEL_DIRECT { 59 var otherUserId string 60 61 userIds := strings.Split(channel.Name, "__") 62 63 if userIds[0] != userIds[1] { 64 if userIds[0] == post.UserId { 65 otherUserId = userIds[1] 66 } else { 67 otherUserId = userIds[0] 68 } 69 } 70 71 otherUser, ok := profileMap[otherUserId] 72 if ok { 73 mentionedUserIds[otherUserId] = true 74 } 75 76 if post.Props["from_webhook"] == "true" { 77 mentionedUserIds[post.UserId] = true 78 } 79 80 if post.Type != model.POST_AUTO_RESPONDER { 81 a.Go(func() { 82 rootId := post.Id 83 if post.RootId != "" && post.RootId != post.Id { 84 rootId = post.RootId 85 } 86 a.SendAutoResponse(channel, otherUser, rootId) 87 }) 88 } 89 90 } else { 91 keywords := a.GetMentionKeywordsInChannel(profileMap, post.Type != model.POST_HEADER_CHANGE && post.Type != model.POST_PURPOSE_CHANGE) 92 93 m := GetExplicitMentions(post, keywords) 94 95 // Add an implicit mention when a user is added to a channel 96 // even if the user has set 'username mentions' to false in account settings. 97 if post.Type == model.POST_ADD_TO_CHANNEL { 98 val := post.Props[model.POST_PROPS_ADDED_USER_ID] 99 if val != nil { 100 uid := val.(string) 101 m.MentionedUserIds[uid] = true 102 } 103 } 104 105 mentionedUserIds, hereNotification, channelNotification, allNotification = m.MentionedUserIds, m.HereMentioned, m.ChannelMentioned, m.AllMentioned 106 107 // get users that have comment thread mentions enabled 108 if len(post.RootId) > 0 && parentPostList != nil { 109 for _, threadPost := range parentPostList.Posts { 110 profile := profileMap[threadPost.UserId] 111 if profile != nil && (profile.NotifyProps["comments"] == THREAD_ANY || (profile.NotifyProps["comments"] == THREAD_ROOT && threadPost.Id == parentPostList.Order[0])) { 112 if threadPost.Id == parentPostList.Order[0] { 113 threadMentionedUserIds[threadPost.UserId] = THREAD_ROOT 114 } else { 115 threadMentionedUserIds[threadPost.UserId] = THREAD_ANY 116 } 117 118 if _, ok := mentionedUserIds[threadPost.UserId]; !ok { 119 mentionedUserIds[threadPost.UserId] = false 120 } 121 } 122 } 123 } 124 125 // prevent the user from mentioning themselves 126 if post.Props["from_webhook"] != "true" { 127 delete(mentionedUserIds, post.UserId) 128 } 129 130 if len(m.OtherPotentialMentions) > 0 && !post.IsSystemMessage() { 131 if result := <-a.Srv.Store.User().GetProfilesByUsernames(m.OtherPotentialMentions, team.Id); result.Err == nil { 132 outOfChannelMentions := result.Data.([]*model.User) 133 if channel.Type != model.CHANNEL_GROUP { 134 a.Go(func() { 135 a.sendOutOfChannelMentions(sender, post, outOfChannelMentions) 136 }) 137 } 138 } 139 } 140 141 // find which users in the channel are set up to always receive mobile notifications 142 for _, profile := range profileMap { 143 if (profile.NotifyProps[model.PUSH_NOTIFY_PROP] == model.USER_NOTIFY_ALL || 144 channelMemberNotifyPropsMap[profile.Id][model.PUSH_NOTIFY_PROP] == model.CHANNEL_NOTIFY_ALL) && 145 (post.UserId != profile.Id || post.Props["from_webhook"] == "true") && 146 !post.IsSystemMessage() { 147 allActivityPushUserIds = append(allActivityPushUserIds, profile.Id) 148 } 149 } 150 } 151 152 mentionedUsersList := make([]string, 0, len(mentionedUserIds)) 153 for id := range mentionedUserIds { 154 mentionedUsersList = append(mentionedUsersList, id) 155 updateMentionChans = append(updateMentionChans, a.Srv.Store.Channel().IncrementMentionCount(post.ChannelId, id)) 156 } 157 158 notification := &postNotification{ 159 post: post, 160 channel: channel, 161 profileMap: profileMap, 162 sender: sender, 163 } 164 165 if a.Config().EmailSettings.SendEmailNotifications { 166 for _, id := range mentionedUsersList { 167 if profileMap[id] == nil { 168 continue 169 } 170 171 userAllowsEmails := profileMap[id].NotifyProps[model.EMAIL_NOTIFY_PROP] != "false" 172 if channelEmail, ok := channelMemberNotifyPropsMap[id][model.EMAIL_NOTIFY_PROP]; ok { 173 if channelEmail != model.CHANNEL_NOTIFY_DEFAULT { 174 userAllowsEmails = channelEmail != "false" 175 } 176 } 177 178 // Remove the user as recipient when the user has muted the channel. 179 if channelMuted, ok := channelMemberNotifyPropsMap[id][model.MARK_UNREAD_NOTIFY_PROP]; ok { 180 if channelMuted == model.CHANNEL_MARK_UNREAD_MENTION { 181 mlog.Debug(fmt.Sprintf("Channel muted for user_id %v, channel_mute %v", id, channelMuted)) 182 userAllowsEmails = false 183 } 184 } 185 186 //If email verification is required and user email is not verified don't send email. 187 if a.Config().EmailSettings.RequireEmailVerification && !profileMap[id].EmailVerified { 188 mlog.Error(fmt.Sprintf("Skipped sending notification email to %v, address not verified. [details: user_id=%v]", profileMap[id].Email, id)) 189 continue 190 } 191 192 var status *model.Status 193 var err *model.AppError 194 if status, err = a.GetStatus(id); err != nil { 195 status = &model.Status{ 196 UserId: id, 197 Status: model.STATUS_OFFLINE, 198 Manual: false, 199 LastActivityAt: 0, 200 ActiveChannel: "", 201 } 202 } 203 204 autoResponderRelated := status.Status == model.STATUS_OUT_OF_OFFICE || post.Type == model.POST_AUTO_RESPONDER 205 206 if userAllowsEmails && status.Status != model.STATUS_ONLINE && profileMap[id].DeleteAt == 0 && !autoResponderRelated { 207 a.sendNotificationEmail(notification, profileMap[id], team) 208 } 209 } 210 } 211 212 T := utils.GetUserTranslations(sender.Locale) 213 214 // If the channel has more than 1K users then @here is disabled 215 if hereNotification && int64(len(profileMap)) > *a.Config().TeamSettings.MaxNotificationsPerChannel { 216 hereNotification = false 217 a.SendEphemeralPost( 218 post.UserId, 219 &model.Post{ 220 ChannelId: post.ChannelId, 221 Message: T("api.post.disabled_here", map[string]interface{}{"Users": *a.Config().TeamSettings.MaxNotificationsPerChannel}), 222 CreateAt: post.CreateAt + 1, 223 }, 224 ) 225 } 226 227 // If the channel has more than 1K users then @channel is disabled 228 if channelNotification && int64(len(profileMap)) > *a.Config().TeamSettings.MaxNotificationsPerChannel { 229 a.SendEphemeralPost( 230 post.UserId, 231 &model.Post{ 232 ChannelId: post.ChannelId, 233 Message: T("api.post.disabled_channel", map[string]interface{}{"Users": *a.Config().TeamSettings.MaxNotificationsPerChannel}), 234 CreateAt: post.CreateAt + 1, 235 }, 236 ) 237 } 238 239 // If the channel has more than 1K users then @all is disabled 240 if allNotification && int64(len(profileMap)) > *a.Config().TeamSettings.MaxNotificationsPerChannel { 241 a.SendEphemeralPost( 242 post.UserId, 243 &model.Post{ 244 ChannelId: post.ChannelId, 245 Message: T("api.post.disabled_all", map[string]interface{}{"Users": *a.Config().TeamSettings.MaxNotificationsPerChannel}), 246 CreateAt: post.CreateAt + 1, 247 }, 248 ) 249 } 250 251 // Make sure all mention updates are complete to prevent race 252 // Probably better to batch these DB updates in the future 253 // MUST be completed before push notifications send 254 for _, uchan := range updateMentionChans { 255 if result := <-uchan; result.Err != nil { 256 mlog.Warn(fmt.Sprintf("Failed to update mention count, post_id=%v channel_id=%v err=%v", post.Id, post.ChannelId, result.Err), mlog.String("post_id", post.Id)) 257 } 258 } 259 260 sendPushNotifications := false 261 if *a.Config().EmailSettings.SendPushNotifications { 262 pushServer := *a.Config().EmailSettings.PushNotificationServer 263 if license := a.License(); pushServer == model.MHPNS && (license == nil || !*license.Features.MHPNS) { 264 mlog.Warn("Push notifications are disabled. Go to System Console > Notifications > Mobile Push to enable them.") 265 sendPushNotifications = false 266 } else { 267 sendPushNotifications = true 268 } 269 } 270 271 if sendPushNotifications { 272 for _, id := range mentionedUsersList { 273 if profileMap[id] == nil { 274 continue 275 } 276 277 var status *model.Status 278 var err *model.AppError 279 if status, err = a.GetStatus(id); err != nil { 280 status = &model.Status{UserId: id, Status: model.STATUS_OFFLINE, Manual: false, LastActivityAt: 0, ActiveChannel: ""} 281 } 282 283 if ShouldSendPushNotification(profileMap[id], channelMemberNotifyPropsMap[id], true, status, post) { 284 replyToThreadType := "" 285 if value, ok := threadMentionedUserIds[id]; ok { 286 replyToThreadType = value 287 } 288 289 a.sendPushNotification( 290 notification, 291 profileMap[id], 292 mentionedUserIds[id], 293 (channelNotification || hereNotification || allNotification), 294 replyToThreadType, 295 ) 296 } 297 } 298 299 for _, id := range allActivityPushUserIds { 300 if profileMap[id] == nil { 301 continue 302 } 303 304 if _, ok := mentionedUserIds[id]; !ok { 305 var status *model.Status 306 var err *model.AppError 307 if status, err = a.GetStatus(id); err != nil { 308 status = &model.Status{UserId: id, Status: model.STATUS_OFFLINE, Manual: false, LastActivityAt: 0, ActiveChannel: ""} 309 } 310 311 if ShouldSendPushNotification(profileMap[id], channelMemberNotifyPropsMap[id], false, status, post) { 312 a.sendPushNotification( 313 notification, 314 profileMap[id], 315 false, 316 false, 317 "", 318 ) 319 } 320 } 321 } 322 } 323 324 message := model.NewWebSocketEvent(model.WEBSOCKET_EVENT_POSTED, "", post.ChannelId, "", nil) 325 message.Add("post", a.PostWithProxyAddedToImageURLs(post).ToJson()) 326 message.Add("channel_type", channel.Type) 327 message.Add("channel_display_name", notification.GetChannelName(model.SHOW_USERNAME, "")) 328 message.Add("channel_name", channel.Name) 329 message.Add("sender_name", notification.GetSenderName(model.SHOW_USERNAME, a.Config().ServiceSettings.EnablePostUsernameOverride)) 330 message.Add("team_id", team.Id) 331 332 if len(post.FileIds) != 0 && fchan != nil { 333 message.Add("otherFile", "true") 334 335 var infos []*model.FileInfo 336 if result := <-fchan; result.Err != nil { 337 mlog.Warn(fmt.Sprint("Unable to get fileInfo for push notifications.", post.Id, result.Err), mlog.String("post_id", post.Id)) 338 } else { 339 infos = result.Data.([]*model.FileInfo) 340 } 341 342 for _, info := range infos { 343 if info.IsImage() { 344 message.Add("image", "true") 345 break 346 } 347 } 348 } 349 350 if len(mentionedUsersList) != 0 { 351 message.Add("mentions", model.ArrayToJson(mentionedUsersList)) 352 } 353 354 a.Publish(message) 355 return mentionedUsersList, nil 356 } 357 358 func (a *App) sendOutOfChannelMentions(sender *model.User, post *model.Post, users []*model.User) *model.AppError { 359 if len(users) == 0 { 360 return nil 361 } 362 363 var usernames []string 364 for _, user := range users { 365 usernames = append(usernames, user.Username) 366 } 367 sort.Strings(usernames) 368 369 var userIds []string 370 for _, user := range users { 371 userIds = append(userIds, user.Id) 372 } 373 374 T := utils.GetUserTranslations(sender.Locale) 375 376 ephemeralPostId := model.NewId() 377 var message string 378 if len(users) == 1 { 379 message = T("api.post.check_for_out_of_channel_mentions.message.one", map[string]interface{}{ 380 "Username": usernames[0], 381 }) 382 } else { 383 message = T("api.post.check_for_out_of_channel_mentions.message.multiple", map[string]interface{}{ 384 "Usernames": strings.Join(usernames[:len(usernames)-1], ", @"), 385 "LastUsername": usernames[len(usernames)-1], 386 }) 387 } 388 389 props := model.StringInterface{ 390 model.PROPS_ADD_CHANNEL_MEMBER: model.StringInterface{ 391 "post_id": ephemeralPostId, 392 "usernames": usernames, 393 "user_ids": userIds, 394 }, 395 } 396 397 a.SendEphemeralPost( 398 post.UserId, 399 &model.Post{ 400 Id: ephemeralPostId, 401 RootId: post.RootId, 402 ChannelId: post.ChannelId, 403 Message: message, 404 CreateAt: post.CreateAt + 1, 405 Props: props, 406 }, 407 ) 408 409 return nil 410 } 411 412 type ExplicitMentions struct { 413 // MentionedUserIds contains a key for each user mentioned by keyword. 414 MentionedUserIds map[string]bool 415 416 // OtherPotentialMentions contains a list of strings that looked like mentions, but didn't have 417 // a corresponding keyword. 418 OtherPotentialMentions []string 419 420 // HereMentioned is true if the message contained @here. 421 HereMentioned bool 422 423 // AllMentioned is true if the message contained @all. 424 AllMentioned bool 425 426 // ChannelMentioned is true if the message contained @channel. 427 ChannelMentioned bool 428 } 429 430 // Given a message and a map mapping mention keywords to the users who use them, returns a map of mentioned 431 // users and a slice of potential mention users not in the channel and whether or not @here was mentioned. 432 func GetExplicitMentions(post *model.Post, keywords map[string][]string) *ExplicitMentions { 433 ret := &ExplicitMentions{ 434 MentionedUserIds: make(map[string]bool), 435 } 436 systemMentions := map[string]bool{"@here": true, "@channel": true, "@all": true} 437 438 addMentionedUsers := func(ids []string) { 439 for _, id := range ids { 440 ret.MentionedUserIds[id] = true 441 } 442 } 443 checkForMention := func(word string) bool { 444 isMention := false 445 446 if strings.ToLower(word) == "@here" { 447 ret.HereMentioned = true 448 } 449 450 if strings.ToLower(word) == "@channel" { 451 ret.ChannelMentioned = true 452 } 453 454 if strings.ToLower(word) == "@all" { 455 ret.AllMentioned = true 456 } 457 458 // Non-case-sensitive check for regular keys 459 if ids, match := keywords[strings.ToLower(word)]; match { 460 addMentionedUsers(ids) 461 isMention = true 462 } 463 464 // Case-sensitive check for first name 465 if ids, match := keywords[word]; match { 466 addMentionedUsers(ids) 467 isMention = true 468 } 469 470 return isMention 471 } 472 processText := func(text string) { 473 for _, word := range strings.FieldsFunc(text, func(c rune) bool { 474 // Split on any whitespace or punctuation that can't be part of an at mention or emoji pattern 475 return !(c == ':' || c == '.' || c == '-' || c == '_' || c == '@' || unicode.IsLetter(c) || unicode.IsNumber(c)) 476 }) { 477 // skip word with format ':word:' with an assumption that it is an emoji format only 478 if word[0] == ':' && word[len(word)-1] == ':' { 479 continue 480 } 481 482 word = strings.TrimLeft(word, ":.-_") 483 484 if checkForMention(word) { 485 continue 486 } 487 488 foundWithoutSuffix := false 489 wordWithoutSuffix := word 490 for strings.LastIndexAny(wordWithoutSuffix, ".-:_") != -1 { 491 wordWithoutSuffix = wordWithoutSuffix[0 : len(wordWithoutSuffix)-1] 492 493 if checkForMention(wordWithoutSuffix) { 494 foundWithoutSuffix = true 495 break 496 } 497 } 498 499 if foundWithoutSuffix { 500 continue 501 } 502 503 if _, ok := systemMentions[word]; !ok && strings.HasPrefix(word, "@") { 504 ret.OtherPotentialMentions = append(ret.OtherPotentialMentions, word[1:]) 505 } else if strings.ContainsAny(word, ".-:") { 506 // This word contains a character that may be the end of a sentence, so split further 507 splitWords := strings.FieldsFunc(word, func(c rune) bool { 508 return c == '.' || c == '-' || c == ':' 509 }) 510 511 for _, splitWord := range splitWords { 512 if checkForMention(splitWord) { 513 continue 514 } 515 if _, ok := systemMentions[splitWord]; !ok && strings.HasPrefix(splitWord, "@") { 516 ret.OtherPotentialMentions = append(ret.OtherPotentialMentions, splitWord[1:]) 517 } 518 } 519 } 520 } 521 } 522 523 buf := "" 524 mentionsEnabledFields := GetMentionsEnabledFields(post) 525 for _, message := range mentionsEnabledFields { 526 markdown.Inspect(message, func(node interface{}) bool { 527 text, ok := node.(*markdown.Text) 528 if !ok { 529 processText(buf) 530 buf = "" 531 return true 532 } 533 buf += text.Text 534 return false 535 }) 536 } 537 processText(buf) 538 539 return ret 540 } 541 542 // Given a post returns the values of the fields in which mentions are possible. 543 // post.message, preText and text in the attachment are enabled. 544 func GetMentionsEnabledFields(post *model.Post) model.StringArray { 545 ret := []string{} 546 547 ret = append(ret, post.Message) 548 for _, attachment := range post.Attachments() { 549 550 if len(attachment.Pretext) != 0 { 551 ret = append(ret, attachment.Pretext) 552 } 553 if len(attachment.Text) != 0 { 554 ret = append(ret, attachment.Text) 555 } 556 } 557 return ret 558 } 559 560 // Given a map of user IDs to profiles, returns a list of mention 561 // keywords for all users in the channel. 562 func (a *App) GetMentionKeywordsInChannel(profiles map[string]*model.User, lookForSpecialMentions bool) map[string][]string { 563 keywords := make(map[string][]string) 564 565 for id, profile := range profiles { 566 userMention := "@" + strings.ToLower(profile.Username) 567 keywords[userMention] = append(keywords[userMention], id) 568 569 if len(profile.NotifyProps["mention_keys"]) > 0 { 570 // Add all the user's mention keys 571 splitKeys := strings.Split(profile.NotifyProps["mention_keys"], ",") 572 for _, k := range splitKeys { 573 // note that these are made lower case so that we can do a case insensitive check for them 574 key := strings.ToLower(k) 575 keywords[key] = append(keywords[key], id) 576 } 577 } 578 579 // If turned on, add the user's case sensitive first name 580 if profile.NotifyProps["first_name"] == "true" { 581 keywords[profile.FirstName] = append(keywords[profile.FirstName], profile.Id) 582 } 583 584 // Add @channel and @all to keywords if user has them turned on 585 if lookForSpecialMentions { 586 if int64(len(profiles)) <= *a.Config().TeamSettings.MaxNotificationsPerChannel && profile.NotifyProps["channel"] == "true" { 587 keywords["@channel"] = append(keywords["@channel"], profile.Id) 588 keywords["@all"] = append(keywords["@all"], profile.Id) 589 590 status := GetStatusFromCache(profile.Id) 591 if status != nil && status.Status == model.STATUS_ONLINE { 592 keywords["@here"] = append(keywords["@here"], profile.Id) 593 } 594 } 595 } 596 } 597 598 return keywords 599 } 600 601 // Represents either an email or push notification and contains the fields required to send it to any user. 602 type postNotification struct { 603 channel *model.Channel 604 post *model.Post 605 profileMap map[string]*model.User 606 sender *model.User 607 } 608 609 // Returns the name of the channel for this notification. For direct messages, this is the sender's name 610 // preceeded by an at sign. For group messages, this is a comma-separated list of the members of the 611 // channel, with an option to exclude the recipient of the message from that list. 612 func (n *postNotification) GetChannelName(userNameFormat string, excludeId string) string { 613 switch n.channel.Type { 614 case model.CHANNEL_DIRECT: 615 return fmt.Sprintf("@%s", n.sender.GetDisplayName(userNameFormat)) 616 case model.CHANNEL_GROUP: 617 names := []string{} 618 for _, user := range n.profileMap { 619 if user.Id != excludeId { 620 names = append(names, user.GetDisplayName(userNameFormat)) 621 } 622 } 623 624 sort.Strings(names) 625 626 return strings.Join(names, ", ") 627 default: 628 return n.channel.DisplayName 629 } 630 } 631 632 // Returns the name of the sender of this notification, accounting for things like system messages 633 // and whether or not the username has been overridden by an integration. 634 func (n *postNotification) GetSenderName(userNameFormat string, overridesAllowed bool) string { 635 if n.post.IsSystemMessage() { 636 return utils.T("system.message.name") 637 } 638 639 if overridesAllowed && n.channel.Type != model.CHANNEL_DIRECT { 640 if value, ok := n.post.Props["override_username"]; ok && n.post.Props["from_webhook"] == "true" { 641 return value.(string) 642 } 643 } 644 645 return n.sender.GetDisplayName(userNameFormat) 646 }