-
Notifications
You must be signed in to change notification settings - Fork 155
/
Copy pathapi.go
1572 lines (1311 loc) · 49.5 KB
/
api.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
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package plugin
import (
"context"
"encoding/json"
"fmt"
"net/http"
"runtime/debug"
"strconv"
"strings"
"sync"
"time"
"github.com/google/go-github/v54/github"
"github.com/gorilla/mux"
"github.com/pkg/errors"
"golang.org/x/oauth2"
"github.com/mattermost/mattermost/server/public/model"
"github.com/mattermost/mattermost/server/public/plugin"
"github.com/mattermost/mattermost/server/public/pluginapi"
"github.com/mattermost/mattermost/server/public/pluginapi/experimental/bot/logger"
"github.com/mattermost/mattermost/server/public/pluginapi/experimental/flow"
)
const (
apiErrorIDNotConnected = "not_connected"
// TokenTTL is the OAuth token expiry duration in seconds
TokenTTL = 10 * 60
requestTimeout = 30 * time.Second
oauthCompleteTimeout = 2 * time.Minute
)
type OAuthState struct {
UserID string `json:"user_id"`
Token string `json:"token"`
PrivateAllowed bool `json:"private_allowed"`
}
type APIErrorResponse struct {
ID string `json:"id"`
Message string `json:"message"`
StatusCode int `json:"status_code"`
}
func (e *APIErrorResponse) Error() string {
return e.Message
}
type PRDetails struct {
URL string `json:"url"`
Number int `json:"number"`
Status string `json:"status"`
Mergeable bool `json:"mergeable"`
RequestedReviewers []*string `json:"requestedReviewers"`
Reviews []*github.PullRequestReview `json:"reviews"`
}
type FilteredNotification struct {
github.Notification
HTMLURL string `json:"html_url"`
}
type SidebarContent struct {
PRs []*github.Issue `json:"prs"`
Reviews []*github.Issue `json:"reviews"`
Assignments []*github.Issue `json:"assignments"`
Unreads []*FilteredNotification `json:"unreads"`
}
type Context struct {
Ctx context.Context
UserID string
Log logger.Logger
}
// HTTPHandlerFuncWithContext is http.HandleFunc but with a Context attached
type HTTPHandlerFuncWithContext func(c *Context, w http.ResponseWriter, r *http.Request)
type UserContext struct {
Context
GHInfo *GitHubUserInfo
}
// HTTPHandlerFuncWithUserContext is http.HandleFunc but with a UserContext attached
type HTTPHandlerFuncWithUserContext func(c *UserContext, w http.ResponseWriter, r *http.Request)
// ResponseType indicates type of response returned by api
type ResponseType string
const (
// ResponseTypeJSON indicates that response type is json
ResponseTypeJSON ResponseType = "JSON_RESPONSE"
// ResponseTypePlain indicates that response type is text plain
ResponseTypePlain ResponseType = "TEXT_RESPONSE"
)
func (p *Plugin) writeJSON(w http.ResponseWriter, v interface{}) {
b, err := json.Marshal(v)
if err != nil {
p.client.Log.Warn("Failed to marshal JSON response", "error", err.Error())
w.WriteHeader(http.StatusInternalServerError)
return
}
_, err = w.Write(b)
if err != nil {
p.client.Log.Warn("Failed to write JSON response", "error", err.Error())
w.WriteHeader(http.StatusInternalServerError)
return
}
}
func (p *Plugin) writeAPIError(w http.ResponseWriter, apiErr *APIErrorResponse) {
b, err := json.Marshal(apiErr)
if err != nil {
p.client.Log.Warn("Failed to marshal API error", "error", err.Error())
w.WriteHeader(http.StatusInternalServerError)
return
}
w.WriteHeader(apiErr.StatusCode)
_, err = w.Write(b)
if err != nil {
p.client.Log.Warn("Failed to write JSON response", "error", err.Error())
w.WriteHeader(http.StatusInternalServerError)
return
}
}
func (p *Plugin) initializeAPI() {
p.router = mux.NewRouter()
p.router.Use(p.withRecovery)
oauthRouter := p.router.PathPrefix("/oauth").Subrouter()
apiRouter := p.router.PathPrefix("/api/v1").Subrouter()
apiRouter.Use(p.checkConfigured)
p.router.HandleFunc("/webhook", p.handleWebhook).Methods(http.MethodPost)
oauthRouter.HandleFunc("/connect", p.checkAuth(p.attachContext(p.connectUserToGitHub), ResponseTypePlain)).Methods(http.MethodGet)
oauthRouter.HandleFunc("/complete", p.checkAuth(p.attachContext(p.completeConnectUserToGitHub), ResponseTypePlain)).Methods(http.MethodGet)
apiRouter.HandleFunc("/connected", p.attachContext(p.getConnected)).Methods(http.MethodGet)
apiRouter.HandleFunc("/user", p.checkAuth(p.attachContext(p.getGitHubUser), ResponseTypeJSON)).Methods(http.MethodPost)
apiRouter.HandleFunc("/todo", p.checkAuth(p.attachUserContext(p.postToDo), ResponseTypeJSON)).Methods(http.MethodPost)
apiRouter.HandleFunc("/prsdetails", p.checkAuth(p.attachUserContext(p.getPrsDetails), ResponseTypePlain)).Methods(http.MethodPost)
apiRouter.HandleFunc("/searchissues", p.checkAuth(p.attachUserContext(p.searchIssues), ResponseTypePlain)).Methods(http.MethodGet)
apiRouter.HandleFunc("/createissue", p.checkAuth(p.attachUserContext(p.createIssue), ResponseTypePlain)).Methods(http.MethodPost)
apiRouter.HandleFunc("/createissuecomment", p.checkAuth(p.attachUserContext(p.createIssueComment), ResponseTypePlain)).Methods(http.MethodPost)
apiRouter.HandleFunc("/mentions", p.checkAuth(p.attachUserContext(p.getMentions), ResponseTypePlain)).Methods(http.MethodGet)
apiRouter.HandleFunc("/labels", p.checkAuth(p.attachUserContext(p.getLabels), ResponseTypePlain)).Methods(http.MethodGet)
apiRouter.HandleFunc("/milestones", p.checkAuth(p.attachUserContext(p.getMilestones), ResponseTypePlain)).Methods(http.MethodGet)
apiRouter.HandleFunc("/assignees", p.checkAuth(p.attachUserContext(p.getAssignees), ResponseTypePlain)).Methods(http.MethodGet)
apiRouter.HandleFunc("/organizations", p.checkAuth(p.attachUserContext(p.getOrganizations), ResponseTypePlain)).Methods(http.MethodGet)
apiRouter.HandleFunc("/repos_by_org", p.checkAuth(p.attachUserContext(p.getReposByOrg), ResponseTypePlain)).Methods(http.MethodGet)
apiRouter.HandleFunc("/repositories", p.checkAuth(p.attachUserContext(p.getRepositories), ResponseTypePlain)).Methods(http.MethodGet)
apiRouter.HandleFunc("/settings", p.checkAuth(p.attachUserContext(p.updateSettings), ResponseTypePlain)).Methods(http.MethodPost)
apiRouter.HandleFunc("/issue", p.checkAuth(p.attachUserContext(p.getIssueByNumber), ResponseTypePlain)).Methods(http.MethodGet)
apiRouter.HandleFunc("/pr", p.checkAuth(p.attachUserContext(p.getPrByNumber), ResponseTypePlain)).Methods(http.MethodGet)
apiRouter.HandleFunc("/lhs-content", p.checkAuth(p.attachUserContext(p.getSidebarContent), ResponseTypePlain)).Methods(http.MethodGet)
apiRouter.HandleFunc("/config", checkPluginRequest(p.getConfig)).Methods(http.MethodGet)
apiRouter.HandleFunc("/token", checkPluginRequest(p.getToken)).Methods(http.MethodGet)
}
func (p *Plugin) withRecovery(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
defer func() {
if x := recover(); x != nil {
p.client.Log.Warn("Recovered from a panic",
"url", r.URL.String(),
"error", x,
"stack", string(debug.Stack()))
}
}()
next.ServeHTTP(w, r)
})
}
func (p *Plugin) checkConfigured(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
config := p.getConfiguration()
if err := config.IsValid(); err != nil {
http.Error(w, "This plugin is not configured.", http.StatusNotImplemented)
return
}
next.ServeHTTP(w, r)
})
}
func (p *Plugin) checkAuth(handler http.HandlerFunc, responseType ResponseType) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
userID := r.Header.Get("Mattermost-User-ID")
if userID == "" {
switch responseType {
case ResponseTypeJSON:
p.writeAPIError(w, &APIErrorResponse{ID: "", Message: "Not authorized.", StatusCode: http.StatusUnauthorized})
case ResponseTypePlain:
http.Error(w, "Not authorized", http.StatusUnauthorized)
default:
p.client.Log.Debug("Unknown ResponseType detected")
}
return
}
handler(w, r)
}
}
func (p *Plugin) createContext(_ http.ResponseWriter, r *http.Request) (*Context, context.CancelFunc) {
userID := r.Header.Get("Mattermost-User-ID")
logger := logger.New(p.API).With(logger.LogContext{
"userid": userID,
})
ctx, cancel := context.WithTimeout(context.Background(), requestTimeout)
context := &Context{
Ctx: ctx,
UserID: userID,
Log: logger,
}
return context, cancel
}
func (p *Plugin) attachContext(handler HTTPHandlerFuncWithContext) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
context, cancel := p.createContext(w, r)
defer cancel()
handler(context, w, r)
}
}
func (p *Plugin) attachUserContext(handler HTTPHandlerFuncWithUserContext) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
context, cancel := p.createContext(w, r)
defer cancel()
info, apiErr := p.getGitHubUserInfo(context.UserID)
if apiErr != nil {
p.writeAPIError(w, apiErr)
return
}
context.Log = context.Log.With(logger.LogContext{
"github username": info.GitHubUsername,
})
userContext := &UserContext{
Context: *context,
GHInfo: info,
}
handler(userContext, w, r)
}
}
func checkPluginRequest(next http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
// All other plugins are allowed
pluginID := r.Header.Get("Mattermost-Plugin-ID")
if pluginID == "" {
http.Error(w, "Not authorized", http.StatusUnauthorized)
return
}
next(w, r)
}
}
func (p *Plugin) ServeHTTP(c *plugin.Context, w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
p.router.ServeHTTP(w, r)
}
func (p *Plugin) connectUserToGitHub(c *Context, w http.ResponseWriter, r *http.Request) {
privateAllowed := false
pValBool, _ := strconv.ParseBool(r.URL.Query().Get("private"))
if pValBool {
privateAllowed = true
}
conf := p.getOAuthConfig(privateAllowed)
state := OAuthState{
UserID: c.UserID,
Token: model.NewId()[:15],
PrivateAllowed: privateAllowed,
}
_, err := p.store.Set(githubOauthKey+state.Token, state, pluginapi.SetExpiry(TokenTTL))
if err != nil {
http.Error(w, "error setting stored state", http.StatusBadRequest)
return
}
url := conf.AuthCodeURL(state.Token, oauth2.AccessTypeOffline)
ch := p.oauthBroker.SubscribeOAuthComplete(c.UserID)
go func() {
ctx, cancel := context.WithTimeout(context.Background(), 45*time.Second)
defer cancel()
var errorMsg string
select {
case err := <-ch:
if err != nil {
errorMsg = err.Error()
}
case <-ctx.Done():
errorMsg = "Timed out waiting for OAuth connection. Please check if the SiteURL is correct."
}
if errorMsg != "" {
_, err := p.poster.DMWithAttachments(c.UserID, &model.SlackAttachment{
Text: fmt.Sprintf("There was an error connecting to your GitHub: `%s` Please double check your configuration.", errorMsg),
Color: string(flow.ColorDanger),
})
if err != nil {
c.Log.WithError(err).Warnf("Failed to DM with cancel information")
}
}
p.oauthBroker.UnsubscribeOAuthComplete(c.UserID, ch)
}()
http.Redirect(w, r, url, http.StatusFound)
}
func (p *Plugin) completeConnectUserToGitHub(c *Context, w http.ResponseWriter, r *http.Request) {
var rErr error
defer func() {
p.oauthBroker.publishOAuthComplete(c.UserID, rErr, false)
}()
code := r.URL.Query().Get("code")
if len(code) == 0 {
rErr = errors.New("missing authorization code")
http.Error(w, rErr.Error(), http.StatusBadRequest)
return
}
stateToken := r.URL.Query().Get("state")
var state OAuthState
err := p.store.Get(githubOauthKey+stateToken, &state)
if err != nil {
c.Log.Warnf("Failed to get state token", "error", err.Error())
rErr = errors.Wrap(err, "missing stored state")
http.Error(w, rErr.Error(), http.StatusBadRequest)
return
}
err = p.store.Delete(githubOauthKey + stateToken)
if err != nil {
c.Log.WithError(err).Warnf("Failed to delete state token")
rErr = errors.Wrap(err, "error deleting stored state")
http.Error(w, rErr.Error(), http.StatusBadRequest)
return
}
if state.Token != stateToken {
rErr = errors.New("invalid state token")
http.Error(w, rErr.Error(), http.StatusBadRequest)
return
}
if state.UserID != c.UserID {
rErr = errors.New("not authorized, incorrect user")
http.Error(w, rErr.Error(), http.StatusUnauthorized)
return
}
conf := p.getOAuthConfig(state.PrivateAllowed)
ctx, cancel := context.WithTimeout(context.Background(), oauthCompleteTimeout)
defer cancel()
tok, err := conf.Exchange(ctx, code)
if err != nil {
c.Log.WithError(err).Warnf("Failed to exchange oauth code into token")
rErr = errors.Wrap(err, "Failed to exchange oauth code into token")
http.Error(w, rErr.Error(), http.StatusInternalServerError)
return
}
githubClient := p.githubConnectToken(*tok)
gitUser, _, err := githubClient.Users.Get(ctx, "")
if err != nil {
c.Log.WithError(err).Warnf("Failed to get authenticated GitHub user")
rErr = errors.Wrap(err, "failed to get authenticated GitHub user")
http.Error(w, rErr.Error(), http.StatusInternalServerError)
return
}
// track the successful connection
p.TrackUserEvent("account_connected", c.UserID, nil)
userInfo := &GitHubUserInfo{
UserID: state.UserID,
Token: tok,
GitHubUsername: gitUser.GetLogin(),
LastToDoPostAt: model.GetMillis(),
Settings: &UserSettings{
SidebarButtons: settingButtonsTeam,
DailyReminder: true,
Notifications: true,
},
AllowedPrivateRepos: state.PrivateAllowed,
MM34646ResetTokenDone: true,
}
if err = p.storeGitHubUserInfo(userInfo); err != nil {
c.Log.WithError(err).Warnf("Failed to store GitHub user info")
rErr = errors.Wrap(err, "Unable to connect user to GitHub")
http.Error(w, rErr.Error(), http.StatusInternalServerError)
return
}
if err = p.storeGitHubToUserIDMapping(gitUser.GetLogin(), state.UserID); err != nil {
c.Log.WithError(err).Warnf("Failed to store GitHub user info mapping")
}
flow := p.flowManager.setupFlow.ForUser(c.UserID)
stepName, err := flow.GetCurrentStep()
if err != nil {
c.Log.WithError(err).Warnf("Failed to get current step")
}
if stepName == stepOAuthConnect {
err = flow.Go(stepWebhookQuestion)
if err != nil {
c.Log.WithError(err).Warnf("Failed go to next step")
}
} else {
// Only post introduction message if no setup wizard is running
var commandHelp string
commandHelp, err = renderTemplate("helpText", p.getConfiguration())
if err != nil {
c.Log.WithError(err).Warnf("Failed to render help template")
}
message := fmt.Sprintf("#### Welcome to the Mattermost GitHub Plugin!\n"+
"You've connected your Mattermost account to [%s](%s) on GitHub. Read about the features of this plugin below:\n\n"+
"##### Daily Reminders\n"+
"The first time you log in each day, you'll get a post right here letting you know what messages you need to read and what pull requests are awaiting your review.\n"+
"Turn off reminders with `/github settings reminders off`.\n\n"+
"##### Notifications\n"+
"When someone mentions you, requests your review, comments on or modifies one of your pull requests/issues, or assigns you, you'll get a post here about it.\n"+
"Turn off notifications with `/github settings notifications off`.\n\n"+
"##### Sidebar Buttons\n"+
"Check out the buttons in the left-hand sidebar of Mattermost.\n"+
"It shows your Open PRs, PRs that are awaiting your review, issues assigned to you, and all your unread messages you have in GitHub. \n"+
"* The first button tells you how many pull requests you have submitted.\n"+
"* The second shows the number of PR that are awaiting your review.\n"+
"* The third shows the number of PR and issues your are assiged to.\n"+
"* The fourth tracks the number of unread messages you have.\n"+
"* The fifth will refresh the numbers.\n\n"+
"Click on them!\n\n"+
"##### Slash Commands\n"+
commandHelp, gitUser.GetLogin(), gitUser.GetHTMLURL())
p.CreateBotDMPost(state.UserID, message, "custom_git_welcome")
}
config := p.getConfiguration()
p.client.Frontend.PublishWebSocketEvent(
wsEventConnect,
map[string]interface{}{
"connected": true,
"github_username": userInfo.GitHubUsername,
"github_client_id": config.GitHubOAuthClientID,
"enterprise_base_url": config.EnterpriseBaseURL,
"organization": config.GitHubOrg,
"configuration": config.ClientConfiguration(),
},
&model.WebsocketBroadcast{UserId: state.UserID},
)
html := `
<!DOCTYPE html>
<html>
<head>
<script>
window.close();
</script>
</head>
<body>
<p>Completed connecting to GitHub. Please close this window.</p>
</body>
</html>
`
w.Header().Set("Content-Type", "text/html")
_, err = w.Write([]byte(html))
if err != nil {
c.Log.WithError(err).Warnf("Failed to write HTML response")
w.WriteHeader(http.StatusInternalServerError)
return
}
}
func (p *Plugin) getGitHubUser(c *Context, w http.ResponseWriter, r *http.Request) {
type GitHubUserRequest struct {
UserID string `json:"user_id"`
}
req := &GitHubUserRequest{}
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
c.Log.WithError(err).Warnf("Error decoding GitHubUserRequest from JSON body")
p.writeAPIError(w, &APIErrorResponse{ID: "", Message: "Please provide a JSON object.", StatusCode: http.StatusBadRequest})
return
}
if req.UserID == "" {
p.writeAPIError(w, &APIErrorResponse{ID: "", Message: "Please provide a JSON object with a non-blank user_id field.", StatusCode: http.StatusBadRequest})
return
}
userInfo, apiErr := p.getGitHubUserInfo(req.UserID)
if apiErr != nil {
if apiErr.ID == apiErrorIDNotConnected {
p.writeAPIError(w, &APIErrorResponse{ID: "", Message: "User is not connected to a GitHub account.", StatusCode: http.StatusNotFound})
} else {
p.writeAPIError(w, apiErr)
}
return
}
if userInfo == nil {
p.writeAPIError(w, &APIErrorResponse{ID: "", Message: "User is not connected to a GitHub account.", StatusCode: http.StatusNotFound})
return
}
type GitHubUserResponse struct {
Username string `json:"username"`
}
resp := &GitHubUserResponse{Username: userInfo.GitHubUsername}
p.writeJSON(w, resp)
}
func (p *Plugin) getConnected(c *Context, w http.ResponseWriter, r *http.Request) {
config := p.getConfiguration()
type ConnectedResponse struct {
Connected bool `json:"connected"`
GitHubUsername string `json:"github_username"`
GitHubClientID string `json:"github_client_id"`
EnterpriseBaseURL string `json:"enterprise_base_url,omitempty"`
Organization string `json:"organization"`
UserSettings *UserSettings `json:"user_settings"`
ClientConfiguration map[string]interface{} `json:"configuration"`
}
resp := &ConnectedResponse{
Connected: false,
EnterpriseBaseURL: config.EnterpriseBaseURL,
Organization: config.GitHubOrg,
ClientConfiguration: p.getConfiguration().ClientConfiguration(),
}
if c.UserID == "" {
p.writeJSON(w, resp)
return
}
info, _ := p.getGitHubUserInfo(c.UserID)
if info == nil || info.Token == nil {
p.writeJSON(w, resp)
return
}
resp.Connected = true
resp.GitHubUsername = info.GitHubUsername
resp.GitHubClientID = config.GitHubOAuthClientID
resp.UserSettings = info.Settings
if info.Settings.DailyReminder && r.URL.Query().Get("reminder") == "true" {
lastPostAt := info.LastToDoPostAt
var timezone *time.Location
offset, _ := strconv.Atoi(r.Header.Get("X-Timezone-Offset"))
timezone = time.FixedZone("local", -60*offset)
// Post to do message if it's the next day and been more than an hour since the last post
now := model.GetMillis()
nt := time.Unix(now/1000, 0).In(timezone)
lt := time.Unix(lastPostAt/1000, 0).In(timezone)
if nt.Sub(lt).Hours() >= 1 && (nt.Day() != lt.Day() || nt.Month() != lt.Month() || nt.Year() != lt.Year()) {
if p.HasUnreads(info) {
if err := p.PostToDo(info, c.UserID); err != nil {
c.Log.WithError(err).Warnf("Failed to create GitHub todo message")
}
info.LastToDoPostAt = now
if err := p.storeGitHubUserInfo(info); err != nil {
c.Log.WithError(err).Warnf("Failed to store github info for new user")
}
}
}
}
privateRepoStoreKey := info.UserID + githubPrivateRepoKey
if config.EnablePrivateRepo && !info.AllowedPrivateRepos {
var val []byte
err := p.store.Get(privateRepoStoreKey, &val)
if err != nil {
c.Log.WithError(err).Warnf("Unable to get private repo key value")
return
}
// Inform the user once that private repositories enabled
if val == nil {
message := "Private repositories have been enabled for this plugin. To be able to use them you must disconnect and reconnect your GitHub account. To reconnect your account, use the following slash commands: `/github disconnect` followed by %s"
if config.ConnectToPrivateByDefault {
p.CreateBotDMPost(info.UserID, fmt.Sprintf(message, "`/github connect`."), "")
} else {
p.CreateBotDMPost(info.UserID, fmt.Sprintf(message, "`/github connect private`."), "")
}
_, err := p.store.Set(privateRepoStoreKey, []byte("1"))
if err != nil {
c.Log.WithError(err).Warnf("Unable to set private repo key value")
}
}
}
p.writeJSON(w, resp)
}
func (p *Plugin) getMentions(c *UserContext, w http.ResponseWriter, r *http.Request) {
config := p.getConfiguration()
githubClient := p.githubConnectUser(c.Context.Ctx, c.GHInfo)
username := c.GHInfo.GitHubUsername
query := getMentionSearchQuery(username, config.GitHubOrg)
result, _, err := githubClient.Search.Issues(c.Ctx, query, &github.SearchOptions{})
if err != nil {
c.Log.WithError(err).With(logger.LogContext{"query": query}).Warnf("Failed to search for issues")
return
}
p.writeJSON(w, result.Issues)
}
func (p *Plugin) getUnreadsData(c *UserContext) []*FilteredNotification {
githubClient := p.githubConnectUser(c.Context.Ctx, c.GHInfo)
notifications, _, err := githubClient.Activity.ListNotifications(c.Ctx, &github.NotificationListOptions{})
if err != nil {
c.Log.WithError(err).Warnf("Failed to list notifications")
return nil
}
filteredNotifications := []*FilteredNotification{}
for _, n := range notifications {
if n.GetReason() == notificationReasonSubscribed {
continue
}
if p.checkOrg(n.GetRepository().GetOwner().GetLogin()) != nil {
continue
}
issueURL := n.GetSubject().GetURL()
issueNumIndex := strings.LastIndex(issueURL, "/")
issueNum := issueURL[issueNumIndex+1:]
subjectURL := n.GetSubject().GetURL()
if n.GetSubject().GetLatestCommentURL() != "" {
subjectURL = n.GetSubject().GetLatestCommentURL()
}
filteredNotifications = append(filteredNotifications, &FilteredNotification{
Notification: *n,
HTMLURL: fixGithubNotificationSubjectURL(subjectURL, issueNum),
})
}
return filteredNotifications
}
func (p *Plugin) getPrsDetails(c *UserContext, w http.ResponseWriter, r *http.Request) {
githubClient := p.githubConnectUser(c.Context.Ctx, c.GHInfo)
var prList []*PRDetails
if err := json.NewDecoder(r.Body).Decode(&prList); err != nil {
c.Log.WithError(err).Warnf("Error decoding PRDetails JSON body")
p.writeAPIError(w, &APIErrorResponse{ID: "", Message: "Please provide a JSON object.", StatusCode: http.StatusBadRequest})
return
}
prDetails := make([]*PRDetails, len(prList))
var wg sync.WaitGroup
for i, pr := range prList {
i := i
pr := pr
wg.Add(1)
go func() {
defer wg.Done()
prDetail := p.fetchPRDetails(c, githubClient, pr.URL, pr.Number)
prDetails[i] = prDetail
}()
}
wg.Wait()
p.writeJSON(w, prDetails)
}
func (p *Plugin) fetchPRDetails(c *UserContext, client *github.Client, prURL string, prNumber int) *PRDetails {
var status string
var mergeable bool
// Initialize to a non-nil slice to simplify JSON handling semantics
requestedReviewers := []*string{}
reviewsList := []*github.PullRequestReview{}
repoOwner, repoName := getRepoOwnerAndNameFromURL(prURL)
var wg sync.WaitGroup
// Fetch reviews
wg.Add(1)
go func() {
defer wg.Done()
fetchedReviews, err := fetchReviews(c, client, repoOwner, repoName, prNumber)
if err != nil {
c.Log.WithError(err).Warnf("Failed to fetch reviews for PR details")
return
}
reviewsList = fetchedReviews
}()
// Fetch reviewers and status
wg.Add(1)
go func() {
defer wg.Done()
prInfo, _, err := client.PullRequests.Get(c.Ctx, repoOwner, repoName, prNumber)
if err != nil {
c.Log.WithError(err).Warnf("Failed to fetch PR for PR details")
return
}
mergeable = prInfo.GetMergeable()
for _, v := range prInfo.RequestedReviewers {
requestedReviewers = append(requestedReviewers, v.Login)
}
statuses, _, err := client.Repositories.GetCombinedStatus(c.Ctx, repoOwner, repoName, prInfo.GetHead().GetSHA(), nil)
if err != nil {
c.Log.WithError(err).Warnf("Failed to fetch combined status")
return
}
status = *statuses.State
}()
wg.Wait()
return &PRDetails{
URL: prURL,
Number: prNumber,
Status: status,
Mergeable: mergeable,
RequestedReviewers: requestedReviewers,
Reviews: reviewsList,
}
}
func fetchReviews(c *UserContext, client *github.Client, repoOwner string, repoName string, number int) ([]*github.PullRequestReview, error) {
reviewsList, _, err := client.PullRequests.ListReviews(c.Ctx, repoOwner, repoName, number, nil)
if err != nil {
return []*github.PullRequestReview{}, errors.Wrap(err, "could not list reviews")
}
return reviewsList, nil
}
func getRepoOwnerAndNameFromURL(url string) (string, string) {
splitted := strings.Split(url, "/")
return splitted[len(splitted)-2], splitted[len(splitted)-1]
}
func (p *Plugin) searchIssues(c *UserContext, w http.ResponseWriter, r *http.Request) {
config := p.getConfiguration()
githubClient := p.githubConnectUser(c.Context.Ctx, c.GHInfo)
searchTerm := r.FormValue("term")
query := getIssuesSearchQuery(config.GitHubOrg, searchTerm)
result, _, err := githubClient.Search.Issues(c.Ctx, query, &github.SearchOptions{})
if err != nil {
c.Log.WithError(err).With(logger.LogContext{"query": query}).Warnf("Failed to search for issues")
return
}
p.writeJSON(w, result.Issues)
}
func (p *Plugin) getPermaLink(postID string) string {
siteURL := *p.client.Configuration.GetConfig().ServiceSettings.SiteURL
return fmt.Sprintf("%v/_redirect/pl/%v", siteURL, postID)
}
func getFailReason(code int, repo string, username string) string {
cause := ""
switch code {
case http.StatusInternalServerError:
cause = "Internal server error"
case http.StatusBadRequest:
cause = "Bad request"
case http.StatusNotFound:
cause = fmt.Sprintf("Sorry, either you don't have access to the repo %s with the user %s or it is no longer available", repo, username)
case http.StatusUnauthorized:
cause = fmt.Sprintf("Sorry, your user %s is unauthorized to do this action", username)
case http.StatusForbidden:
cause = fmt.Sprintf("Sorry, you don't have enough permissions to comment in the repo %s with the user %s", repo, username)
default:
cause = fmt.Sprintf("Unknown status code %d", code)
}
return cause
}
func (p *Plugin) createIssueComment(c *UserContext, w http.ResponseWriter, r *http.Request) {
type CreateIssueCommentRequest struct {
PostID string `json:"post_id"`
Owner string `json:"owner"`
Repo string `json:"repo"`
Number int `json:"number"`
Comment string `json:"comment"`
}
req := &CreateIssueCommentRequest{}
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
c.Log.WithError(err).Warnf("Error decoding CreateIssueCommentRequest JSON body")
p.writeAPIError(w, &APIErrorResponse{ID: "", Message: "Please provide a JSON object.", StatusCode: http.StatusBadRequest})
return
}
if req.PostID == "" {
p.writeAPIError(w, &APIErrorResponse{ID: "", Message: "Please provide a valid post id", StatusCode: http.StatusBadRequest})
return
}
if req.Owner == "" {
p.writeAPIError(w, &APIErrorResponse{ID: "", Message: "Please provide a valid repo owner.", StatusCode: http.StatusBadRequest})
return
}
if req.Repo == "" {
p.writeAPIError(w, &APIErrorResponse{ID: "", Message: "Please provide a valid repo.", StatusCode: http.StatusBadRequest})
return
}
if req.Number == 0 {
p.writeAPIError(w, &APIErrorResponse{ID: "", Message: "Please provide a valid issue number.", StatusCode: http.StatusBadRequest})
return
}
if req.Comment == "" {
p.writeAPIError(w, &APIErrorResponse{ID: "", Message: "Please provide a valid non empty comment.", StatusCode: http.StatusBadRequest})
return
}
githubClient := p.githubConnectUser(c.Context.Ctx, c.GHInfo)
post, err := p.client.Post.GetPost(req.PostID)
if err != nil {
p.writeAPIError(w, &APIErrorResponse{ID: "", Message: "failed to load post " + req.PostID, StatusCode: http.StatusInternalServerError})
return
}
if post == nil {
p.writeAPIError(w, &APIErrorResponse{ID: "", Message: "failed to load post " + req.PostID + ": not found", StatusCode: http.StatusNotFound})
return
}
commentUsername, err := p.getUsername(post.UserId)
if err != nil {
p.writeAPIError(w, &APIErrorResponse{ID: "", Message: "failed to get username", StatusCode: http.StatusInternalServerError})
return
}
currentUsername := c.GHInfo.GitHubUsername
permalink := p.getPermaLink(req.PostID)
permalinkMessage := fmt.Sprintf("*@%s attached a* [message](%s) *from %s*\n\n", currentUsername, permalink, commentUsername)
req.Comment = permalinkMessage + req.Comment
comment := &github.IssueComment{
Body: &req.Comment,
}
result, rawResponse, err := githubClient.Issues.CreateComment(c.Ctx, req.Owner, req.Repo, req.Number, comment)
if err != nil {
statusCode := 500
if rawResponse != nil {
statusCode = rawResponse.StatusCode
}
p.writeAPIError(w, &APIErrorResponse{ID: "", Message: "failed to create an issue comment: " + getFailReason(statusCode, req.Repo, currentUsername), StatusCode: statusCode})
return
}
rootID := req.PostID
if post.RootId != "" {
// the original post was a reply
rootID = post.RootId
}
permalinkReplyMessage := fmt.Sprintf("[Message](%v) attached to GitHub issue [#%v](%v)", permalink, req.Number, result.GetHTMLURL())
reply := &model.Post{
Message: permalinkReplyMessage,
ChannelId: post.ChannelId,
RootId: rootID,
UserId: c.UserID,
}
err = p.client.Post.CreatePost(reply)
if err != nil {
p.writeAPIError(w, &APIErrorResponse{ID: "", Message: "failed to create notification post " + req.PostID, StatusCode: http.StatusInternalServerError})
return
}
p.writeJSON(w, result)
}
func (p *Plugin) getLHSData(c *UserContext) (reviewResp []*github.Issue, assignmentResp []*github.Issue, openPRResp []*github.Issue, err error) {
graphQLClient := p.graphQLConnect(c.GHInfo)
reviewResp, assignmentResp, openPRResp, err = graphQLClient.GetLHSData(c.Context.Ctx)
if err != nil {
return []*github.Issue{}, []*github.Issue{}, []*github.Issue{}, err
}
return reviewResp, assignmentResp, openPRResp, nil
}
func (p *Plugin) getSidebarData(c *UserContext) (*SidebarContent, error) {
reviewResp, assignmentResp, openPRResp, err := p.getLHSData(c)
if err != nil {
return nil, err
}
return &SidebarContent{
PRs: openPRResp,
Assignments: assignmentResp,
Reviews: reviewResp,
Unreads: p.getUnreadsData(c),
}, nil
}
func (p *Plugin) getSidebarContent(c *UserContext, w http.ResponseWriter, r *http.Request) {
sidebarContent, err := p.getSidebarData(c)
if err != nil {
c.Log.WithError(err).Warnf("Failed to search for the sidebar data")
return
}
p.writeJSON(w, sidebarContent)
}
func (p *Plugin) postToDo(c *UserContext, w http.ResponseWriter, r *http.Request) {
githubClient := p.githubConnectUser(c.Context.Ctx, c.GHInfo)
username := c.GHInfo.GitHubUsername
text, err := p.GetToDo(c.Ctx, username, githubClient)
if err != nil {
c.Log.WithError(err).Warnf("Failed to get Todos")
p.writeAPIError(w, &APIErrorResponse{ID: "", Message: "Encountered an error getting the to do items.", StatusCode: http.StatusUnauthorized})
return
}
p.CreateBotDMPost(c.UserID, text, "custom_git_todo")
resp := struct {
Status string
}{"OK"}
p.writeJSON(w, resp)
}
func (p *Plugin) updateSettings(c *UserContext, w http.ResponseWriter, r *http.Request) {
var settings *UserSettings
if err := json.NewDecoder(r.Body).Decode(&settings); err != nil {