-
Notifications
You must be signed in to change notification settings - Fork 146
/
plugin.go
577 lines (461 loc) · 16.1 KB
/
plugin.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
package main
import (
"context"
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"net/url"
"path"
"path/filepath"
"regexp"
"strings"
"sync"
"github.com/google/go-github/v31/github"
"github.com/gorilla/mux"
"github.com/mattermost/mattermost-server/v5/mlog"
"github.com/mattermost/mattermost-server/v5/model"
"github.com/mattermost/mattermost-server/v5/plugin"
"github.com/pkg/errors"
"golang.org/x/oauth2"
)
const (
githubTokenKey = "_githubtoken"
githubUsernameKey = "_githubusername"
githubPrivateRepoKey = "_githubprivate"
wsEventConnect = "connect"
wsEventDisconnect = "disconnect"
wsEventRefresh = "refresh"
settingButtonsTeam = "team"
settingNotifications = "notifications"
settingReminders = "reminders"
settingOn = "on"
settingOff = "off"
notificationReasonSubscribed = "subscribed"
)
type Plugin struct {
plugin.MattermostPlugin
// githubPermalinkRegex is used to parse github permalinks in post messages.
githubPermalinkRegex *regexp.Regexp
BotUserID string
CommandHandlers map[string]CommandHandleFunc
// configurationLock synchronizes access to the configuration.
configurationLock sync.RWMutex
// configuration is the active plugin configuration. Consult getConfiguration and
// setConfiguration for usage.
configuration *configuration
router *mux.Router
}
// NewPlugin returns an instance of a Plugin.
func NewPlugin() *Plugin {
p := &Plugin{
githubPermalinkRegex: regexp.MustCompile(`https?://(?P<haswww>www\.)?github\.com/(?P<user>[\w-]+)/(?P<repo>[\w-]+)/blob/(?P<commit>\w+)/(?P<path>[\w-/.]+)#(?P<line>[\w-]+)?`),
}
p.CommandHandlers = map[string]CommandHandleFunc{
"subscribe": p.handleSubscribe,
"unsubscribe": p.handleUnsubscribe,
"disconnect": p.handleDisconnect,
"todo": p.handleTodo,
"me": p.handleMe,
"help": p.handleHelp,
"": p.handleEmpty,
"settings": p.handleSettings,
}
return p
}
func (p *Plugin) githubConnect(token oauth2.Token) *github.Client {
config := p.getConfiguration()
ts := oauth2.StaticTokenSource(&token)
tc := oauth2.NewClient(context.Background(), ts)
if len(config.EnterpriseBaseURL) == 0 || len(config.EnterpriseUploadURL) == 0 {
return github.NewClient(tc)
}
baseURL, _ := url.Parse(config.EnterpriseBaseURL)
baseURL.Path = path.Join(baseURL.Path, "api", "v3")
uploadURL, _ := url.Parse(config.EnterpriseUploadURL)
uploadURL.Path = path.Join(uploadURL.Path, "api", "v3")
client, err := github.NewEnterpriseClient(baseURL.String(), uploadURL.String(), tc)
if err != nil {
mlog.Error(err.Error())
return github.NewClient(tc)
}
return client
}
func (p *Plugin) OnActivate() error {
config := p.getConfiguration()
if err := config.IsValid(); err != nil {
return errors.Wrap(err, "invalid config")
}
if p.API.GetConfig().ServiceSettings.SiteURL == nil {
return errors.New("siteURL is not set. Please set a siteURL and restart the plugin")
}
p.initializeAPI()
err := p.API.RegisterCommand(getCommand())
if err != nil {
return errors.Wrap(err, "failed to register command")
}
botID, err := p.Helpers.EnsureBot(&model.Bot{
Username: "github",
DisplayName: "GitHub",
Description: "Created by the GitHub plugin.",
})
if err != nil {
return errors.Wrap(err, "failed to ensure github bot")
}
p.BotUserID = botID
bundlePath, err := p.API.GetBundlePath()
if err != nil {
return errors.Wrap(err, "couldn't get bundle path")
}
profileImage, err := ioutil.ReadFile(filepath.Join(bundlePath, "assets", "profile.png"))
if err != nil {
return errors.Wrap(err, "couldn't read profile image")
}
appErr := p.API.SetProfileImage(botID, profileImage)
if appErr != nil {
return errors.Wrap(appErr, "couldn't set profile image")
}
registerGitHubToUsernameMappingCallback(p.getGitHubToUsernameMapping)
return nil
}
func (p *Plugin) MessageWillBePosted(c *plugin.Context, post *model.Post) (*model.Post, string) {
// If not enabled in config, ignore.
config := p.getConfiguration()
if !config.EnableCodePreview {
return nil, ""
}
if post.UserId == "" {
return nil, ""
}
msg := post.Message
info, err := p.getGitHubUserInfo(post.UserId)
if err != nil {
p.API.LogError("error in getting user info", "error", err.Message)
return nil, ""
}
// TODO: make this part of the Plugin struct and reuse it.
ghClient := p.githubConnect(*info.Token)
replacements := p.getReplacements(msg)
post.Message = p.makeReplacements(msg, replacements, ghClient)
return post, ""
}
func (p *Plugin) getOAuthConfig(privateAllowed bool) *oauth2.Config {
config := p.getConfiguration()
baseURL := p.getBaseURL()
authURL, _ := url.Parse(baseURL)
tokenURL, _ := url.Parse(baseURL)
authURL.Path = path.Join(authURL.Path, "login", "oauth", "authorize")
tokenURL.Path = path.Join(tokenURL.Path, "login", "oauth", "access_token")
repo := github.ScopePublicRepo
if config.EnablePrivateRepo && privateAllowed {
// means that asks scope for private repositories
repo = github.ScopeRepo
}
return &oauth2.Config{
ClientID: config.GitHubOAuthClientID,
ClientSecret: config.GitHubOAuthClientSecret,
Scopes: []string{string(repo), string(github.ScopeNotifications), string(github.ScopeReadOrg)},
Endpoint: oauth2.Endpoint{
AuthURL: authURL.String(),
TokenURL: tokenURL.String(),
},
}
}
type GitHubUserInfo struct {
UserID string
Token *oauth2.Token
GitHubUsername string
LastToDoPostAt int64
Settings *UserSettings
AllowedPrivateRepos bool
}
type UserSettings struct {
SidebarButtons string `json:"sidebar_buttons"`
DailyReminder bool `json:"daily_reminder"`
Notifications bool `json:"notifications"`
}
func (p *Plugin) storeGitHubUserInfo(info *GitHubUserInfo) error {
config := p.getConfiguration()
encryptedToken, err := encrypt([]byte(config.EncryptionKey), info.Token.AccessToken)
if err != nil {
return errors.Wrap(err, "error occurred while encrypting access token")
}
info.Token.AccessToken = encryptedToken
jsonInfo, err := json.Marshal(info)
if err != nil {
return errors.Wrap(err, "error while converting user info to json")
}
if err := p.API.KVSet(info.UserID+githubTokenKey, jsonInfo); err != nil {
return errors.Wrap(err, "error occurred while trying to store user info into KV store")
}
return nil
}
func (p *Plugin) getGitHubUserInfo(userID string) (*GitHubUserInfo, *APIErrorResponse) {
config := p.getConfiguration()
var userInfo GitHubUserInfo
infoBytes, appErr := p.API.KVGet(userID + githubTokenKey)
if appErr != nil || infoBytes == nil {
return nil, &APIErrorResponse{ID: apiErrorIDNotConnected, Message: "Must connect user account to GitHub first.", StatusCode: http.StatusBadRequest}
}
if err := json.Unmarshal(infoBytes, &userInfo); err != nil {
return nil, &APIErrorResponse{ID: "", Message: "Unable to parse token.", StatusCode: http.StatusInternalServerError}
}
unencryptedToken, err := decrypt([]byte(config.EncryptionKey), userInfo.Token.AccessToken)
if err != nil {
mlog.Error(err.Error())
return nil, &APIErrorResponse{ID: "", Message: "Unable to decrypt access token.", StatusCode: http.StatusInternalServerError}
}
userInfo.Token.AccessToken = unencryptedToken
return &userInfo, nil
}
func (p *Plugin) storeGitHubToUserIDMapping(githubUsername, userID string) error {
if err := p.API.KVSet(githubUsername+githubUsernameKey, []byte(userID)); err != nil {
return errors.New("encountered error saving github username mapping")
}
return nil
}
func (p *Plugin) getGitHubToUserIDMapping(githubUsername string) string {
userID, _ := p.API.KVGet(githubUsername + githubUsernameKey)
return string(userID)
}
// getGitHubToUsernameMapping maps a GitHub username to the corresponding Mattermost username, if any.
func (p *Plugin) getGitHubToUsernameMapping(githubUsername string) string {
user, _ := p.API.GetUser(p.getGitHubToUserIDMapping(githubUsername))
if user == nil {
return ""
}
return user.Username
}
func (p *Plugin) disconnectGitHubAccount(userID string) {
userInfo, _ := p.getGitHubUserInfo(userID)
if userInfo == nil {
return
}
if appErr := p.API.KVDelete(userID + githubTokenKey); appErr != nil {
p.API.LogWarn("Failed to delete github token from KV store", "userID", userID, "error", appErr.Error())
}
if appErr := p.API.KVDelete(userInfo.GitHubUsername + githubUsernameKey); appErr != nil {
p.API.LogWarn("Failed to delete github token from KV store", "userID", userID, "error", appErr.Error())
}
user, appErr := p.API.GetUser(userID)
if appErr != nil {
p.API.LogWarn("Failed to get user props", "userID", userID, "error", appErr.Error())
} else {
_, ok := user.Props["git_user"]
if ok {
delete(user.Props, "git_user")
_, appErr := p.API.UpdateUser(user)
if appErr != nil {
p.API.LogWarn("Failed to get update user props", "userID", userID, "error", appErr.Error())
}
}
}
p.API.PublishWebSocketEvent(
wsEventDisconnect,
nil,
&model.WebsocketBroadcast{UserId: userID},
)
}
// CreateBotDMPost posts a direct message using the bot account.
// Any error are not returned and instead logged.
func (p *Plugin) CreateBotDMPost(userID, message, postType string) {
channel, err := p.API.GetDirectChannel(userID, p.BotUserID)
if err != nil {
p.API.LogWarn("Couldn't get bot's DM channel", "userID", userID, "error", err.Error())
return
}
post := &model.Post{
UserId: p.BotUserID,
ChannelId: channel.Id,
Message: message,
Type: postType,
}
if _, err := p.API.CreatePost(post); err != nil {
p.API.LogWarn("Failed to create DM post", "userID", userID, "error", err.Error())
return
}
}
func (p *Plugin) PostToDo(info *GitHubUserInfo) {
text, err := p.GetToDo(context.Background(), info.GitHubUsername, p.githubConnect(*info.Token))
if err != nil {
p.API.LogWarn("Failed to get todo text", "userID", info.UserID, "error", err.Error())
return
}
p.CreateBotDMPost(info.UserID, text, "custom_git_todo")
}
func (p *Plugin) GetToDo(ctx context.Context, username string, githubClient *github.Client) (string, error) {
config := p.getConfiguration()
baseURL := p.getBaseURL()
issueResults, _, err := githubClient.Search.Issues(ctx, getReviewSearchQuery(username, config.GitHubOrg), &github.SearchOptions{})
if err != nil {
return "", errors.Wrap(err, "Error occurred while searching for reviews")
}
notifications, _, err := githubClient.Activity.ListNotifications(ctx, &github.NotificationListOptions{})
if err != nil {
return "", errors.Wrap(err, "error occurred while listing notifications")
}
yourPrs, _, err := githubClient.Search.Issues(ctx, getYourPrsSearchQuery(username, config.GitHubOrg), &github.SearchOptions{})
if err != nil {
return "", errors.Wrap(err, "error occurred while searching for PRs")
}
yourAssignments, _, err := githubClient.Search.Issues(ctx, getYourAssigneeSearchQuery(username, config.GitHubOrg), &github.SearchOptions{})
if err != nil {
return "", errors.Wrap(err, "error occurred while searching for assignments")
}
text := "##### Unread Messages\n"
notificationCount := 0
notificationContent := ""
for _, n := range notifications {
if n.GetReason() == notificationReasonSubscribed {
continue
}
if n.GetRepository() == nil {
p.API.LogError("unable to get repository for notification in todo list. Skipping.")
continue
}
if p.checkOrg(n.GetRepository().GetOwner().GetLogin()) != nil {
continue
}
notificationSubject := n.GetSubject()
notificationType := notificationSubject.GetType()
switch notificationType {
case "RepositoryVulnerabilityAlert":
message := fmt.Sprintf("[Vulnerability Alert for %v](%v)", n.GetRepository().GetFullName(), fixGithubNotificationSubjectURL(n.GetSubject().GetURL()))
notificationContent += fmt.Sprintf("* %v\n", message)
default:
notificationTitle := notificationSubject.GetTitle()
notificationURL := fixGithubNotificationSubjectURL(notificationSubject.GetURL())
notificationContent += getToDoDisplayText(baseURL, notificationTitle, notificationURL, notificationType)
}
notificationCount++
}
if notificationCount == 0 {
text += "You don't have any unread messages.\n"
} else {
text += fmt.Sprintf("You have %v unread messages:\n", notificationCount)
text += notificationContent
}
text += "##### Review Requests\n"
if issueResults.GetTotal() == 0 {
text += "You don't have any pull requests awaiting your review.\n"
} else {
text += fmt.Sprintf("You have %v pull requests awaiting your review:\n", issueResults.GetTotal())
for _, pr := range issueResults.Issues {
text += getToDoDisplayText(baseURL, pr.GetTitle(), pr.GetHTMLURL(), "")
}
}
text += "##### Your Open Pull Requests\n"
if yourPrs.GetTotal() == 0 {
text += "You don't have any open pull requests.\n"
} else {
text += fmt.Sprintf("You have %v open pull requests:\n", yourPrs.GetTotal())
for _, pr := range yourPrs.Issues {
text += getToDoDisplayText(baseURL, pr.GetTitle(), pr.GetHTMLURL(), "")
}
}
text += "##### Your Assignments\n"
if yourAssignments.GetTotal() == 0 {
text += "You don't have any assignments.\n"
} else {
text += fmt.Sprintf("You have %v assignments:\n", yourAssignments.GetTotal())
for _, assign := range yourAssignments.Issues {
text += getToDoDisplayText(baseURL, assign.GetTitle(), assign.GetHTMLURL(), "")
}
}
return text, nil
}
func (p *Plugin) HasUnreads(info *GitHubUserInfo) bool {
username := info.GitHubUsername
ctx := context.Background()
githubClient := p.githubConnect(*info.Token)
config := p.getConfiguration()
issues, _, err := githubClient.Search.Issues(ctx, getReviewSearchQuery(username, config.GitHubOrg), &github.SearchOptions{})
if err != nil {
mlog.Error(err.Error())
return false
}
yourPrs, _, err := githubClient.Search.Issues(ctx, getYourPrsSearchQuery(username, config.GitHubOrg), &github.SearchOptions{})
if err != nil {
mlog.Error(err.Error())
return false
}
yourAssignments, _, err := githubClient.Search.Issues(ctx, getYourAssigneeSearchQuery(username, config.GitHubOrg), &github.SearchOptions{})
if err != nil {
mlog.Error(err.Error())
return false
}
relevantNotifications := false
notifications, _, err := githubClient.Activity.ListNotifications(ctx, &github.NotificationListOptions{})
if err != nil {
mlog.Error(err.Error())
return false
}
for _, n := range notifications {
if n.GetReason() == notificationReasonSubscribed {
continue
}
if n.GetRepository() == nil {
p.API.LogError("Unable to get repository for notification in todo list. Skipping.")
continue
}
if p.checkOrg(n.GetRepository().GetOwner().GetLogin()) != nil {
continue
}
relevantNotifications = true
break
}
if issues.GetTotal() == 0 && !relevantNotifications && yourPrs.GetTotal() == 0 && yourAssignments.GetTotal() == 0 {
return false
}
return true
}
func (p *Plugin) checkOrg(org string) error {
config := p.getConfiguration()
configOrg := strings.TrimSpace(config.GitHubOrg)
if configOrg != "" && configOrg != org {
return errors.Errorf("only repositories in the %v organization are supported", configOrg)
}
return nil
}
func (p *Plugin) isUserOrganizationMember(githubClient *github.Client, user *github.User, organization string) bool {
if organization == "" {
return false
}
isMember, _, err := githubClient.Organizations.IsMember(context.Background(), organization, *user.Login)
if err != nil {
mlog.Warn(err.Error())
return false
}
return isMember
}
func (p *Plugin) sendRefreshEvent(userID string) {
p.API.PublishWebSocketEvent(
wsEventRefresh,
nil,
&model.WebsocketBroadcast{UserId: userID},
)
}
func (p *Plugin) getBaseURL() string {
config := p.getConfiguration()
if config.EnterpriseBaseURL != "" {
return config.EnterpriseBaseURL
}
return "https://github.com/"
}
// getUsername returns the GitHub username for a given Mattermost user,
// if the user is connected to GitHub via this plugin.
// Otherwise it return the Mattermost username. It will be escaped via backticks.
func (p *Plugin) getUsername(mmUserID string) (string, error) {
info, apiEr := p.getGitHubUserInfo(mmUserID)
if apiEr != nil {
if apiEr.ID != apiErrorIDNotConnected {
return "", apiEr
}
user, appEr := p.API.GetUser(mmUserID)
if appEr != nil {
return "", appEr
}
return fmt.Sprintf("`@%s`", user.Username), nil
}
return "@" + info.GitHubUsername, nil
}