|
package slack |
|
|
|
import ( |
|
"context" |
|
"fmt" |
|
"sort" |
|
"strings" |
|
|
|
"github.com/slack-go/slack/slackutilsx" |
|
"github.com/target/goalert/notification" |
|
"github.com/target/goalert/user" |
|
"github.com/target/goalert/util/log" |
|
) |
|
|
|
|
|
|
|
|
|
|
|
func (s *ChannelSender) onCallNotificationText(ctx context.Context, t notification.ScheduleOnCallUsers) string { |
|
if len(t.Users) == 0 { |
|
return renderOnCallNotificationMessage(t, nil) |
|
} |
|
|
|
teamID, err := s.TeamID(ctx) |
|
if err != nil { |
|
log.Log(ctx, fmt.Errorf("lookup team ID: %w", err)) |
|
return renderOnCallNotificationMessage(t, nil) |
|
} |
|
|
|
userIDs := make([]string, len(t.Users)) |
|
for i, u := range t.Users { |
|
userIDs[i] = u.ID |
|
} |
|
|
|
userSlackIDs := make(map[string]string, len(t.Users)) |
|
err = s.cfg.UserStore.AuthSubjectsFunc(ctx, "slack:"+teamID, userIDs, func(sub user.AuthSubject) error { |
|
userSlackIDs[sub.UserID] = sub.SubjectID |
|
return nil |
|
}) |
|
if err != nil { |
|
log.Log(ctx, fmt.Errorf("lookup auth subjects for slack: %w", err)) |
|
|
|
} |
|
|
|
return renderOnCallNotificationMessage(t, userSlackIDs) |
|
} |
|
|
|
|
|
|
|
|
|
func renderOnCallNotificationMessage(msg notification.ScheduleOnCallUsers, userSlackIDs map[string]string) string { |
|
suffix := fmt.Sprintf("on-call for <%s|%s>", slackutilsx.EscapeMessage(msg.ScheduleURL), slackutilsx.EscapeMessage(msg.ScheduleName)) |
|
|
|
sort.Slice(msg.Users, func(i, j int) bool { |
|
ui, uj := msg.Users[i], msg.Users[j] |
|
if ui.Name == uj.Name { |
|
return ui.ID < uj.ID |
|
} |
|
|
|
return ui.Name < uj.Name |
|
}) |
|
|
|
var userLinks []string |
|
for _, u := range msg.Users { |
|
var subjectID string |
|
if userSlackIDs != nil { |
|
subjectID = userSlackIDs[u.ID] |
|
} |
|
if subjectID == "" { |
|
|
|
userLinks = append(userLinks, fmt.Sprintf("<%s|%s>", slackutilsx.EscapeMessage(u.URL), slackutilsx.EscapeMessage(u.Name))) |
|
continue |
|
} |
|
|
|
userLinks = append(userLinks, fmt.Sprintf("<@%s>", slackutilsx.EscapeMessage(subjectID))) |
|
} |
|
|
|
if len(userLinks) == 0 { |
|
return "No users are " + suffix |
|
} |
|
if len(userLinks) == 1 { |
|
return fmt.Sprintf("%s is %s", userLinks[0], suffix) |
|
} |
|
if len(userLinks) == 2 { |
|
return fmt.Sprintf("%s and %s are %s", userLinks[0], userLinks[1], suffix) |
|
} |
|
|
|
return fmt.Sprintf("%s, and %s are %s", strings.Join(userLinks[:len(userLinks)-1], ", "), userLinks[len(userLinks)-1], suffix) |
|
} |
|
|