-
Notifications
You must be signed in to change notification settings - Fork 8
/
subscribe.go
289 lines (242 loc) · 10.2 KB
/
subscribe.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
package plugin
import (
"fmt"
"strings"
"github.com/mattermost/mattermost-server/v5/model"
"github.com/mattermost/mattermost-plugin-circleci/server/store"
)
const (
subscribeTrigger = "subscription"
subscribeHint = "<" + subscribeListTrigger + "|" +
subscribeChannelTrigger + "|" +
subscribeUnsubscribeChannelTrigger + "|" +
subscribeListAllChannelsTrigger + ">"
subscribeHelpText = "Manage your subscriptions"
subscribeListTrigger = "list"
subscribeListHint = ""
subscribeListHelpText = "List the CircleCI subscriptions for the current channel"
subscribeChannelTrigger = "add"
subscribeChannelHint = "[--flags]"
subscribeChannelHelpText = "Subscribe the current channel to CircleCI notifications"
subscribeUnsubscribeChannelTrigger = "remove"
subscribeUnsubscribeChannelHint = "[--flags]"
subscribeUnsubscribeChannelHelpText = "Unsubscribe the current channel to CircleCI notifications"
subscribeListAllChannelsTrigger = "list-channels"
subscribeListAllChannelsHint = ""
subscribeListAllChannelsHelpText = "List all channels in the current team subscribed to notifications"
)
func getSubscribeAutoCompleteData() *model.AutocompleteData {
subscribe := model.NewAutocompleteData(subscribeTrigger, subscribeHint, subscribeHelpText)
subscribeList := model.NewAutocompleteData(subscribeListTrigger, subscribeListHint, subscribeListHelpText)
subscribeChannel := model.NewAutocompleteData(subscribeChannelTrigger, subscribeChannelHint, subscribeChannelHelpText)
subscribeChannel.AddNamedTextArgument(store.FlagOnlyFailedJobs, "Only receive notifications for failed builds", "[write anything to continue autocomplete]", "", false)
subscribeChannel.AddNamedDynamicListArgument(namedArgProjectName, namedArgProjectHelpText, routeAutocomplete+subrouteFollowedProjects, false)
unsubscribeChannel := model.NewAutocompleteData(subscribeUnsubscribeChannelTrigger, subscribeUnsubscribeChannelHint, subscribeUnsubscribeChannelHelpText)
unsubscribeChannel.AddNamedDynamicListArgument(namedArgProjectName, namedArgProjectHelpText, routeAutocomplete+subrouteFollowedProjects, false)
listAllSubscribedChannels := model.NewAutocompleteData(subscribeListAllChannelsTrigger, subscribeListAllChannelsHint, subscribeListAllChannelsHelpText)
listAllSubscribedChannels.AddNamedDynamicListArgument(namedArgProjectName, namedArgProjectHelpText, routeAutocomplete+subrouteFollowedProjects, false)
subscribe.AddCommand(subscribeChannel)
subscribe.AddCommand(unsubscribeChannel)
subscribe.AddCommand(subscribeList)
subscribe.AddCommand(listAllSubscribedChannels)
return subscribe
}
func (p *Plugin) executeSubscribe(args *model.CommandArgs, circleciToken string, project *store.ProjectIdentifier, split []string) (*model.CommandResponse, *model.AppError) {
subcommand := commandHelpTrigger
if len(split) > 0 {
subcommand = split[0]
}
switch subcommand {
case commandHelpTrigger:
return p.sendHelpResponse(args, subscribeTrigger)
case subscribeListTrigger:
return executeSubscribeList(p, args)
case subscribeChannelTrigger:
var rawFlags []string
if len(split) > 1 {
rawFlags = split[1:]
}
return executeSubscribeChannel(p, args, project, rawFlags)
case subscribeUnsubscribeChannelTrigger:
return executeUnsubscribeChannel(p, args, project)
case subscribeListAllChannelsTrigger:
return executeSubscribeListAllChannels(p, args, project)
default:
return p.sendIncorrectSubcommandResponse(args, subscribeTrigger)
}
}
func executeSubscribeList(p *Plugin, args *model.CommandArgs) (*model.CommandResponse, *model.AppError) {
allSubs, err := p.Store.GetSubscriptions()
if err != nil {
p.API.LogError("Unable to get subscriptions", "err", err)
return p.sendEphemeralResponse(args, ":red_circle: Internal error when getting subscriptions"), nil
}
subs := allSubs.GetSubscriptionsByChannel(args.ChannelId)
if subs == nil {
return p.sendEphemeralResponse(
args,
fmt.Sprintf(
":information_source: This channel is not subscribed to any repository. Try `/%s %s %s`",
commandTrigger,
subscribeTrigger,
subscribeChannelTrigger,
),
), nil
}
attachment := model.SlackAttachment{
Title: "Repositories this channel is subscribed to :",
Fallback: "List of repositories this channel is subscribed to",
}
for _, sub := range subs {
username := "Unknown user"
if user, appErr := p.API.GetUser(sub.CreatorID); appErr != nil {
p.API.LogError("Unable to get username", "userID", sub.CreatorID)
} else {
username = user.Username
}
attachment.Fields = append(attachment.Fields, sub.ToSlackAttachmentField(username))
}
p.sendEphemeralPost(args, "", []*model.SlackAttachment{&attachment})
return &model.CommandResponse{}, nil
}
func executeSubscribeChannel(p *Plugin, args *model.CommandArgs, project *store.ProjectIdentifier, rawFlags []string) (*model.CommandResponse, *model.AppError) {
subs, err := p.Store.GetSubscriptions()
if err != nil {
p.API.LogError("Unable to get subscriptions", "err", err)
return p.sendEphemeralResponse(args, ":red_circle: Internal error when getting subscriptions"), nil
}
newSub := &store.Subscription{
ChannelID: args.ChannelId,
CreatorID: args.UserId,
Flags: store.SubscriptionFlags{},
ProjectInformation: *project,
}
for _, arg := range rawFlags {
if strings.HasPrefix(arg, "--") {
flag := arg[2:]
err := newSub.Flags.AddFlag(flag)
if err != nil {
return p.sendEphemeralResponse(args, fmt.Sprintf(
"Unknown subscription flag `%s`. Try `/%s %s %s`",
arg,
commandTrigger,
subscribeTrigger,
commandHelpTrigger,
)), nil
}
}
}
p.API.LogDebug("Adding a new subscription", "subscription", newSub)
wasUpdated := subs.AddSubscription(newSub)
if err := p.Store.StoreSubscriptions(subs); err != nil {
p.API.LogError("Unable to store subscriptions", "error", err)
return p.sendEphemeralResponse(args, ":red_circle: Internal error when storing new subscription."), nil
}
var msg string
var ephemeralMsg string
if wasUpdated {
msg = fmt.Sprintf("The subscription for this channel to %s has been been updated with flags `%s` by %s. [Learn more](%s/user-guide/webhooks-notifications)",
project.ToMarkdown(),
newSub.Flags.String(),
p.getUsername(args.UserId),
manifest.HomepageURL,
)
ephemeralMsg = fmt.Sprintf(
":white_check_mark: Subscription successfully updated!\n"+
"The [Mattermost Plugin Notify Orb](%s) should already be configured, but you can check it to be sure. See the full guide [here](%s/user-guide/webhooks-notifications).\n"+
"**Webhook URL: `%s`**",
circleOrbDocumentationLink,
manifest.HomepageURL,
p.getWebhookURL(),
)
} else {
msg = fmt.Sprintf("This channel has been subscribed to notifications from %s with flags: `%s` by %s. [Learn more](%s/user-guide/webhooks-notifications)",
project.ToMarkdown(),
newSub.Flags.String(),
p.getUsername(args.UserId),
manifest.HomepageURL,
)
ephemeralMsg = fmt.Sprintf(
":white_check_mark: Subscription saved! \n"+
"#### How to finish setup:\n"+
"(See the full guide [here](%s/admin-guide/configuration)).\n"+
"1. Setup the [Mattermost Plugin Notify Orb](%s) for your CircleCI project\n"+
"2. Add the `MM_WEBHOOK` environment variable to your project using the [CircleCI UI](https://circleci.com/docs/2.0/env-vars/#setting-an-environment-variable-in-a-project) or with \n```\n/%s %s %s %s MM_WEBHOOK %s\n```\n"+
"**Webhook URL: `%s`**",
manifest.HomepageURL,
circleOrbDocumentationLink,
commandTrigger,
projectTrigger,
projectEnvVarTrigger,
projectEnvVarAddTrigger,
p.getWebhookURL(),
p.getWebhookURL(),
)
}
channelPost := &model.Post{
ChannelId: newSub.ChannelID,
UserId: p.botUserID,
Message: msg,
}
p.createPost(channelPost)
return p.sendEphemeralResponse(args, ephemeralMsg), nil
}
func executeUnsubscribeChannel(p *Plugin, args *model.CommandArgs, project *store.ProjectIdentifier) (*model.CommandResponse, *model.AppError) {
subs, err := p.Store.GetSubscriptions()
if err != nil {
p.API.LogError("Unable to get subscriptions", "err", err)
return p.sendEphemeralResponse(args, ":red_circle: Internal error when getting subscriptions"), nil
}
if removed := subs.RemoveSubscription(args.ChannelId, project); !removed {
return p.sendEphemeralResponse(args,
fmt.Sprintf(":red_circle: This channel was not subscribed to %s", project.ToMarkdown()),
), nil
}
if err := p.Store.StoreSubscriptions(subs); err != nil {
p.API.LogError("Unable to store subscriptions", "error", err)
return p.sendEphemeralResponse(args, ":red_circle: Internal error when storing new subscription."), nil
}
channelPost := &model.Post{
ChannelId: args.ChannelId,
UserId: p.botUserID,
Message: fmt.Sprintf(
"This channel has been unsubscribed to notifications from %s by %s. [Learn more](%s/user-guide/webhooks-notifications)",
project.ToMarkdown(),
p.getUsername(args.UserId),
manifest.HomepageURL,
),
}
p.createPost(channelPost)
return p.sendEphemeralResponse(args,
fmt.Sprintf(":white_check_mark: Successfully unsubscribed this channel from %s", project.ToMarkdown()),
), nil
}
func executeSubscribeListAllChannels(p *Plugin, context *model.CommandArgs, project *store.ProjectIdentifier) (*model.CommandResponse, *model.AppError) {
allSubs, err := p.Store.GetSubscriptions()
if err != nil {
p.API.LogError("Unable to get subscriptions", "err", err)
return p.sendEphemeralResponse(context, ":red_circle: Internal error when getting subscriptions"), nil
}
channelIDs := allSubs.GetSubscribedChannelsForProject(project)
if channelIDs == nil {
return p.sendEphemeralResponse(
context,
fmt.Sprintf(
":information_source: No channel is subscribed to the project %s. Try `/%s %s %s`",
project.ToMarkdown(),
commandTrigger,
subscribeTrigger,
subscribeChannelTrigger,
),
), nil
}
message := fmt.Sprintf(":information_source: Channels of this team subscribed to %s\n", project.ToMarkdown())
for _, channelID := range channelIDs {
channel, appErr := p.API.GetChannel(channelID)
if appErr != nil {
p.API.LogError("Unable to get channel", "channelID", channelID)
}
message += fmt.Sprintf("- ~%s\n", channel.Name)
}
return p.sendEphemeralResponse(context, message), nil
}