-
Notifications
You must be signed in to change notification settings - Fork 89
Expand file tree
/
Copy pathcommand.go
More file actions
1187 lines (1028 loc) · 43.7 KB
/
command.go
File metadata and controls
1187 lines (1028 loc) · 43.7 KB
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
// Copyright (c) 2019-present Mattermost, Inc. All Rights Reserved.
// See LICENSE.txt for license information.
package main
import (
"context"
"fmt"
"runtime/debug"
"strings"
"time"
"github.com/mattermost/mattermost/server/public/model"
"github.com/mattermost/mattermost/server/public/plugin"
"github.com/mattermost/mattermost/server/public/pluginapi/experimental/command"
"github.com/pkg/errors"
gitlabLib "github.com/xanzy/go-gitlab"
"golang.org/x/oauth2"
"github.com/mattermost/mattermost-plugin-gitlab/server/gitlab"
)
const commandHelp = `* |/gitlab connect| - Connect your Mattermost account to your GitLab account
* |/gitlab disconnect| - Disconnect your Mattermost account from your GitLab account
* |/gitlab todo| - Get a list of todos, assigned issues, assigned merge requests and merge requests awaiting your review
* |/gitlab subscriptions list| - Will list the current channel subscriptions
* |/gitlab subscriptions add owner[/repo] [features]| - Subscribe the current channel to receive notifications about opened merge requests and issues for a group or repository
* |features| is a comma-delimited list of one or more the following:
* issues - includes new and closed issues
* confidential_issues - includes new and closed confidential issues
* jobs - includes jobs status updates
* merges - includes new and closed merge requests
* pushes - includes pushes
* issue_comments - includes new issue comments
* merge_request_comments - include new merge-request comments
* merge_request_assigns - includes merge request assignment and unassignment notifications
* pipeline - includes pipeline runs
* tag - include tag creation
* pull_reviews - includes merge request reviews
* label:"<label-1-name>","<label-2-name>" - must include "merges" or "issues" in feature list when using labels
* deployments - includes deployments
* releases - includes releases
* Defaults to "merges,issues,tag"
* |/gitlab subscriptions delete owner/repo| - Unsubscribe the current channel from a repository
* |/gitlab pipelines run [owner]/repo [ref]| - Run a pipeline for specific repository and ref (branch/tag)
* |/gitlab me| - Display the connected GitLab account
* |/gitlab settings [setting] [value]| - Update your user settings
* |setting| can be "notifications" or "reminders"
* |value| can be "on" or "off"
* |/gitlab webhook list [owner]/repo| - Will list associated group or project hooks.
* |/gitlab webhook add owner[/repo] [options] [url] [token]|
* |options| is a comma-delimited list of one or more the following:
* |*| - or missing defaults to all with SSL verification enabled
* *noSSL - all triggers with SSL verification not enabled.
* PushEvents
* TagPushEvents
* Comments
* ConfidentialComments
* IssuesEvents
* ConfidentialIssuesEvents
* MergeRequestsEvents
* JobEvents
* PipelineEvents
* WikiPageEvents
* DeploymentEvents
* ReleaseEvents
* SSLverification
* |url| is the URL that will be called when triggered. Defaults to this plugins URL
* |token| Secret token. Defaults to secret token used in plugin's settings.
* |/gitlab about| - Display build information about the plugin
`
const (
inboundWebhookURL = "plugins/com.github.manland.mattermost-plugin-gitlab/webhook"
specifyRepositoryMessage = "Please specify a repository."
specifyRepositoryAndBranchMessage = "Please specify a repository and a branch."
unknownActionMessage = "Unknown action, please use `/gitlab help` to see all actions available."
newWebhookEmptySiteURLmessage = "Unable to create webhook. The Mattermot Site URL is not set. " +
"Set it in the Admin Console or rerun /gitlab webhook add group/project URL including the desired URL."
)
const (
groupNotFoundError = "404 {message: 404 Group Not Found}"
groupNotFoundMessage = "Unable to find GitLab group: "
projectNotFoundError = "404 {message: 404 Project Not Found}"
projectNotFoundMessage = "Unable to find project with namespace: "
invalidSubscribeSubCommand = "Invalid subscribe command. Available commands are add, delete, and list"
missingOrgOrRepoFromSubscribeCommand = "Please provide the owner[/repo]"
invalidPipelinesSubCommand = "Invalid pipelines command. Available commands are run, list"
)
const (
commandAdd = "add"
commandDelete = "delete"
commandList = "list"
commandRun = "run"
)
const (
commandTimeout = 30 * time.Second
)
func (p *Plugin) getCommand(config *configuration) (*model.Command, error) {
iconData, err := command.GetIconData(&p.client.System, "assets/icon.svg")
if err != nil {
return nil, errors.Wrap(err, "failed to get icon data")
}
return &model.Command{
Trigger: "gitlab",
AutoComplete: true,
AutoCompleteDesc: "Available commands: connect, disconnect, instance, todo, subscriptions, me, pipelines, settings, webhook, setup, help, about",
AutoCompleteHint: "[command]",
AutocompleteData: p.getAutocompleteData(config),
AutocompleteIconData: iconData,
}, nil
}
func (p *Plugin) postCommandResponse(args *model.CommandArgs, text string, isEphemeralPost bool) {
post := &model.Post{
UserId: p.BotUserID,
ChannelId: args.ChannelId,
RootId: args.RootId,
Message: text,
}
if isEphemeralPost {
p.client.Post.SendEphemeralPost(args.UserId, post)
return
}
if err := p.client.Post.CreatePost(post); err != nil {
p.client.Log.Error("Failed to create post", "error", err.Error())
}
}
func (p *Plugin) getCommandResponse(args *model.CommandArgs, text string, isEphemeralPost bool) *model.CommandResponse {
p.postCommandResponse(args, text, isEphemeralPost)
return &model.CommandResponse{}
}
type authenticatedCommandHandlerFunc func(ctx context.Context, args *model.CommandArgs, parameters []string, info *gitlab.UserInfo) (*model.CommandResponse, *model.AppError)
type unauthenticatedCommandHandlerFunc func(args *model.CommandArgs, parameters []string) (*model.CommandResponse, *model.AppError)
// ExecuteCommand is the entrypoint for /gitlab commands. It returns a message to display to the user or an error.
func (p *Plugin) ExecuteCommand(c *plugin.Context, args *model.CommandArgs) (res *model.CommandResponse, appErr *model.AppError) {
var (
split = strings.Fields(args.Command)
cmd = split[0]
action string
parameters []string
)
if len(split) > 1 {
action = split[1]
}
if len(split) > 2 {
parameters = split[2:]
}
if cmd != "/gitlab" {
return &model.CommandResponse{}, nil
}
ctx, cancel := context.WithTimeout(context.Background(), commandTimeout)
defer cancel()
defer p.recoverFromPanic(args)
unauthenticatedHandlers := map[string]unauthenticatedCommandHandlerFunc{
"about": p.handleAbout,
"setup": p.handleSetup,
"instance": p.handleInstance,
"connect": p.handleConnect,
"help": p.handleHelp,
"": p.handleHelp,
}
if handler, ok := unauthenticatedHandlers[action]; ok {
return handler(args, parameters)
}
config := p.getConfiguration()
if err := config.IsValid(); err != nil {
return p.handleConfigError(args, err)
}
info, apiErr := p.getGitlabUserInfoByMattermostID(args.UserId)
if apiErr != nil {
return p.handleUserNotConnected(args, apiErr)
}
authenticatedHandlers := map[string]authenticatedCommandHandlerFunc{
"subscriptions": p.handleSubscribe,
"subscription": p.handleSubscribe,
"subscribe": p.handleSubscribe,
"unsubscribe": p.handleUnsubscribe,
"disconnect": p.handleDisconnect,
"todo": p.handleTodo,
"issue": p.handleIssue,
"me": p.handleMe,
"settings": p.handleSettings,
"webhook": p.handleWebhookHandler,
"pipelines": p.handlePipelines,
}
if handler, ok := authenticatedHandlers[action]; ok {
return handler(ctx, args, parameters, info)
}
return p.getCommandResponse(args, unknownActionMessage, true), nil
}
func (p *Plugin) handleConfigError(args *model.CommandArgs, err error) (*model.CommandResponse, *model.AppError) {
isSysAdmin, sysErr := p.isAuthorizedSysAdmin(args.UserId)
var text string
switch {
case sysErr != nil:
text = "Error checking user's permissions"
p.client.Log.Warn(text, "error", sysErr.Error())
case isSysAdmin:
text = "Before using this plugin, you'll need to configure it by running `/gitlab setup`"
default:
text = "Please contact your system administrator to configure the GitLab plugin."
}
p.postCommandResponse(args, text, true)
return &model.CommandResponse{}, nil
}
func (p *Plugin) handleInstance(args *model.CommandArgs, parameters []string) (*model.CommandResponse, *model.AppError) {
isSysAdmin, sysErr := p.isAuthorizedSysAdmin(args.UserId)
if sysErr != nil {
p.client.Log.Warn("Failed to check if user is System Admin", "error", sysErr.Error())
return p.getCommandResponse(args, "Error checking user's permissions", true), nil
}
if !isSysAdmin {
return p.getCommandResponse(args, "Only System Admins are allowed to manage instances.", true), nil
}
if len(parameters) < 1 {
return p.getCommandResponse(args, "Please specify the instance command.", true), nil
}
switch parameters[0] {
case "install":
return p.handleInstallInstance(args, parameters[1:])
case "uninstall":
return p.handleUnInstallInstance(args, parameters[1:])
case "set-default":
return p.handleSetDefaultInstance(args, parameters[1:])
case "list":
return p.handleListInstance(args, parameters[1:])
default:
return p.getCommandResponse(args, "Unknown instance command. Available commands: install, uninstall, set-default, list", true), nil
}
}
func (p *Plugin) handleInstallInstance(args *model.CommandArgs, parameters []string) (*model.CommandResponse, *model.AppError) {
err := p.flowManager.StartOauthWizard(args.UserId)
if err != nil {
return p.getCommandResponse(args, err.Error(), true), nil
}
return &model.CommandResponse{}, nil
}
func (p *Plugin) handleUnInstallInstance(args *model.CommandArgs, parameters []string) (*model.CommandResponse, *model.AppError) {
if len(parameters) < 1 {
return p.getCommandResponse(args, "Please specify the instance name.", true), nil
}
instanceName := strings.TrimSpace(strings.Join(parameters, " "))
err := p.uninstallInstance(instanceName)
if err != nil {
return p.getCommandResponse(args, err.Error(), true), nil
}
return p.getCommandResponse(args, fmt.Sprintf("Instance '%s' has been uninstalled.", instanceName), true), nil
}
func (p *Plugin) handleSetDefaultInstance(args *model.CommandArgs, parameters []string) (*model.CommandResponse, *model.AppError) {
if len(parameters) < 1 {
return p.getCommandResponse(args, "Please specify the instance name.", true), nil
}
instanceName := strings.TrimSpace(strings.Join(parameters, " "))
err := p.setDefaultInstance(instanceName)
if err != nil {
return p.getCommandResponse(args, err.Error(), true), nil
}
return p.getCommandResponse(args, fmt.Sprintf("Instance '%s' has been set as the default.", instanceName), true), nil
}
func (p *Plugin) handleListInstance(args *model.CommandArgs, parameters []string) (*model.CommandResponse, *model.AppError) {
instanceDetailMap, err := p.getInstanceConfigMap()
if err != nil {
p.client.Log.Warn("Failed to get instance list", "error", err.Error())
return p.getCommandResponse(args, "Error retrieving instance list.", true), nil
}
if len(instanceDetailMap) == 0 {
return p.getCommandResponse(args, "No GitLab instances are currently installed.", true), nil
}
var builder strings.Builder
builder.WriteString("### Installed GitLab Instances\n")
builder.WriteString("| Instance Name | Instance URL |\n")
builder.WriteString("|--------------|--------------|\n")
for name, instanceConfiguration := range instanceDetailMap {
builder.WriteString(fmt.Sprintf("| %s | %s |\n", name, instanceConfiguration.GitlabURL))
}
return p.getCommandResponse(args, builder.String(), true), nil
}
func (p *Plugin) handleUserNotConnected(args *model.CommandArgs, apiErr *APIErrorResponse) (*model.CommandResponse, *model.AppError) {
text := "Unknown error."
if apiErr.ID == APIErrorIDNotConnected {
text = "You must connect your account to GitLab first. Either click on the GitLab logo in the bottom left of the screen or enter `/gitlab connect`."
}
return p.getCommandResponse(args, text, true), nil
}
func (p *Plugin) handleAbout(args *model.CommandArgs, parameters []string) (*model.CommandResponse, *model.AppError) {
text, err := command.BuildInfo(model.Manifest{
Id: manifest.Id,
Version: manifest.Version,
Name: manifest.Name,
})
if err != nil {
text = errors.Wrap(err, "failed to get build info").Error()
}
p.postCommandResponse(args, text, true)
return &model.CommandResponse{}, nil
}
func (p *Plugin) handleConnect(args *model.CommandArgs, parameters []string) (*model.CommandResponse, *model.AppError) {
if len(parameters) < 1 {
return p.getCommandResponse(args, "Please specify the instance name.", true), nil
}
// Set the default instance for the user before connecting
instanceName := strings.TrimSpace(strings.Join(parameters, " "))
err := p.setDefaultInstance(instanceName)
if err != nil {
return p.getCommandResponse(args, err.Error(), true), nil
}
pluginURL := getPluginURL(p.client)
if pluginURL == "" {
return p.getCommandResponse(args, "Encountered an error connecting to GitLab.", true), nil
}
resp := p.getCommandResponse(args, fmt.Sprintf("[Click here to link your GitLab account.](%s/oauth/connect)", pluginURL), true)
return resp, nil
}
func (p *Plugin) handleHelp(args *model.CommandArgs, parameters []string) (*model.CommandResponse, *model.AppError) {
text := "###### Mattermost GitLab Plugin - Slash Command Help\n" + strings.ReplaceAll(commandHelp, "|", "`")
return p.getCommandResponse(args, text, true), nil
}
func (p *Plugin) recoverFromPanic(args *model.CommandArgs) {
if r := recover(); r != nil {
p.client.Log.Warn("Recovered from a panic",
"Command", args.Command,
"UserId", args.UserId,
"error", r,
"stack", string(debug.Stack()))
p.postCommandResponse(args, "An unexpected error occurred. Please try again later.", true)
if *p.client.Configuration.GetConfig().ServiceSettings.EnableDeveloper {
p.postCommandResponse(args, fmt.Sprintf("error: %v, \nstack:\n```%s```", r, string(debug.Stack())), true)
}
}
}
func (p *Plugin) handleSetup(args *model.CommandArgs, parameters []string) (*model.CommandResponse, *model.AppError) {
userID := args.UserId
isSysAdmin, err := p.isAuthorizedSysAdmin(userID)
if err != nil {
p.client.Log.Warn("Failed to check if user is System Admin", "error", err.Error())
p.postCommandResponse(args, "Error checking user's permissions", true)
return &model.CommandResponse{}, nil
}
if !isSysAdmin {
p.postCommandResponse(args, "Only System Admins are allowed to set up the plugin.", true)
return &model.CommandResponse{}, nil
}
if len(parameters) == 0 {
err = p.flowManager.StartSetupWizard(userID, "")
} else {
switch parameters[0] {
case "oauth":
err = p.flowManager.StartOauthWizard(userID)
case "webhook":
err = p.flowManager.StartWebhookWizard(userID)
case "announcement":
err = p.flowManager.StartAnnouncementWizard(userID)
default:
p.postCommandResponse(args, fmt.Sprintf("Unknown subcommand %v", parameters[0]), true)
return &model.CommandResponse{}, nil
}
}
if err != nil {
p.postCommandResponse(args, err.Error(), true)
}
return &model.CommandResponse{}, nil
}
func (p *Plugin) handleSubscribe(ctx context.Context, args *model.CommandArgs, parameters []string, info *gitlab.UserInfo) (*model.CommandResponse, *model.AppError) {
config := p.getConfiguration()
message, isEphemeralPost := p.subscribeCommand(ctx, parameters, args.ChannelId, config, info)
return p.getCommandResponse(args, message, isEphemeralPost), nil
}
func (p *Plugin) handleUnsubscribe(ctx context.Context, args *model.CommandArgs, parameters []string, info *gitlab.UserInfo) (*model.CommandResponse, *model.AppError) {
config := p.getConfiguration()
var message string
var err error
var isEphemeralPost bool
if len(parameters) == 0 {
message = specifyRepositoryMessage
} else {
message, isEphemeralPost, err = p.subscriptionDelete(info, config, parameters[0], args.ChannelId)
if err != nil {
message = err.Error()
}
}
return p.getCommandResponse(args, message, isEphemeralPost), nil
}
func (p *Plugin) handleDisconnect(ctx context.Context, args *model.CommandArgs, parameters []string, info *gitlab.UserInfo) (*model.CommandResponse, *model.AppError) {
p.disconnectGitlabAccount(args.UserId)
return p.getCommandResponse(args, "Disconnected your GitLab account.", true), nil
}
func (p *Plugin) handleTodo(ctx context.Context, args *model.CommandArgs, parameters []string, info *gitlab.UserInfo) (*model.CommandResponse, *model.AppError) {
_, text, err := p.GetToDo(ctx, info)
if err != nil {
p.client.Log.Warn("can't get todo in command", "err", err.Error())
return p.getCommandResponse(args, "Encountered an error getting your todo items.", true), nil
}
return p.getCommandResponse(args, text, true), nil
}
func (p *Plugin) handleIssue(ctx context.Context, args *model.CommandArgs, parameters []string, info *gitlab.UserInfo) (*model.CommandResponse, *model.AppError) {
message := p.handleIssueHelper(nil, args, parameters)
if message != "" {
p.postCommandResponse(args, message, true)
}
return &model.CommandResponse{}, nil
}
func (p *Plugin) handleMe(ctx context.Context, args *model.CommandArgs, parameters []string, info *gitlab.UserInfo) (*model.CommandResponse, *model.AppError) {
var gitUser *gitlabLib.User
err := p.useGitlabClient(info, func(info *gitlab.UserInfo, token *oauth2.Token) error {
resp, err := p.GitlabClient.GetUserDetails(ctx, info, token)
if err != nil {
return err
}
gitUser = resp
return nil
})
if err != nil {
return p.getCommandResponse(args, "Encountered an error getting your GitLab profile.", true), nil
}
text := fmt.Sprintf("You are connected to GitLab as:\n# [](%s) [%s](%s)", gitUser.AvatarURL, gitUser.WebURL, gitUser.Username, gitUser.WebsiteURL)
return p.getCommandResponse(args, text, true), nil
}
func (p *Plugin) handleSettings(ctx context.Context, args *model.CommandArgs, parameters []string, info *gitlab.UserInfo) (*model.CommandResponse, *model.AppError) {
if len(parameters) < 2 {
return p.getCommandResponse(args, "Please specify both a setting and value. Use `/gitlab help` for more usage information.", true), nil
}
setting := parameters[0]
strValue := parameters[1]
value := false
if strValue == SettingOn {
value = true
} else if strValue != SettingOff {
return p.getCommandResponse(args, "Invalid value. Accepted values are: \"on\" or \"off\".", true), nil
}
switch setting {
case SettingNotifications:
if value {
if err := p.storeGitlabToUserIDMapping(info.GitlabUsername, info.UserID); err != nil {
p.client.Log.Warn("can't store GitLab to user id mapping", "err", err.Error())
return p.getCommandResponse(args, "Unknown error please retry or ask to an administrator to look at logs", true), nil
}
if err := p.storeGitlabIDToUserIDMapping(info.GitlabUsername, info.GitlabUserID); err != nil {
p.client.Log.Warn("can't store GitLab to GitLab id mapping", "err", err.Error())
return p.getCommandResponse(args, "Unknown error please retry or ask to an administrator to look at logs", true), nil
}
} else if err := p.deleteGitlabToUserIDMapping(info.GitlabUsername); err != nil {
p.client.Log.Warn("can't delete GitLab username in kvstore", "err", err.Error())
return p.getCommandResponse(args, "Unknown error please retry or ask to an administrator to look at logs", true), nil
}
info.Settings.Notifications = value
case SettingReminders:
info.Settings.DailyReminder = value
default:
return p.getCommandResponse(args, "Unknown setting.", true), nil
}
if err := p.storeGitlabUserInfo(info); err != nil {
p.client.Log.Warn("can't store user info after update by command", "err", err.Error())
return p.getCommandResponse(args, "Unknown error please retry or ask to an administrator to look at logs", true), nil
}
return p.getCommandResponse(args, "Settings updated.", true), nil
}
func (p *Plugin) handleWebhookHandler(ctx context.Context, args *model.CommandArgs, parameters []string, info *gitlab.UserInfo) (*model.CommandResponse, *model.AppError) {
isSysAdmin, err := p.isAuthorizedSysAdmin(args.UserId)
if err != nil {
p.client.Log.Warn("Failed to check if user is System Admin", "error", err.Error())
return p.getCommandResponse(args, "Error checking user's permissions", true), nil
}
if !isSysAdmin {
return p.getCommandResponse(args, "Only System Admins are allowed to manage webhooks.", true), nil
}
config := p.getConfiguration()
message := p.webhookCommand(ctx, parameters, info, config.EnablePrivateRepo)
return p.getCommandResponse(args, message, true), nil
}
func (p *Plugin) handlePipelines(ctx context.Context, args *model.CommandArgs, parameters []string, info *gitlab.UserInfo) (*model.CommandResponse, *model.AppError) {
message := p.pipelinesCommand(ctx, parameters, args.ChannelId, info)
return p.getCommandResponse(args, message, true), nil
}
func (p *Plugin) handleIssueHelper(_ *plugin.Context, args *model.CommandArgs, parameters []string) string {
if len(parameters) == 0 {
return "Invalid issue command. Available command is 'create'."
}
command := parameters[0]
parameters = parameters[1:]
switch command {
case "create":
p.openIssueCreateModal(args.UserId, args.ChannelId, strings.Join(parameters, " "))
return ""
default:
return fmt.Sprintf("This command is not implemented yet. Command: %v", command)
}
}
// webhookCommand processes the /gitlab webhook commands
func (p *Plugin) webhookCommand(ctx context.Context, parameters []string, info *gitlab.UserInfo, enablePrivateRepo bool) string {
if len(parameters) < 1 {
return unknownActionMessage
}
subCommand := parameters[0]
switch subCommand {
case commandList:
if len(parameters) != 2 {
return unknownActionMessage
}
namespace := parameters[1]
var group, project string
err := p.useGitlabClient(info, func(info *gitlab.UserInfo, token *oauth2.Token) error {
respGroup, respProject, err := p.GitlabClient.ResolveNamespaceAndProject(ctx, info, token, namespace, enablePrivateRepo)
if err != nil {
return err
}
group = respGroup
project = respProject
return nil
})
if err != nil {
return err.Error()
}
var webhookInfo []*gitlab.WebhookInfo
if project != "" {
err := p.useGitlabClient(info, func(info *gitlab.UserInfo, token *oauth2.Token) error {
resp, err := p.GitlabClient.GetProjectHooks(ctx, info, token, group, project)
if err != nil {
return err
}
webhookInfo = resp
return nil
})
if err != nil {
if strings.Contains(err.Error(), projectNotFoundError) {
return projectNotFoundMessage + namespace
}
return err.Error()
}
} else {
err := p.useGitlabClient(info, func(info *gitlab.UserInfo, token *oauth2.Token) error {
resp, err := p.GitlabClient.GetGroupHooks(ctx, info, token, group)
if err != nil {
return err
}
webhookInfo = resp
return nil
})
if err != nil {
if strings.Contains(err.Error(), groupNotFoundError) {
return groupNotFoundMessage + group
}
return err.Error()
}
}
if len(webhookInfo) == 0 {
return fmt.Sprintf("No webhooks found in %s", namespace)
}
var sb strings.Builder
for _, hook := range webhookInfo {
sb.WriteString(hook.String())
}
return sb.String()
case commandAdd:
if len(parameters) < 2 {
return unknownActionMessage
}
siteURL := getSiteURL(p.client)
if siteURL == "" {
return newWebhookEmptySiteURLmessage
}
urlPath := fmt.Sprintf("%v/%s", siteURL, inboundWebhookURL)
if len(parameters) > 3 {
urlPath = parameters[3]
}
// default to all triggers unless specified
hookOptions := parseTriggers("*")
if len(parameters) > 2 {
triggersCsv := parameters[2]
hookOptions = parseTriggers(triggersCsv)
}
hookOptions.URL = urlPath
if len(parameters) > 4 {
hookOptions.Token = parameters[4]
} else {
hookOptions.Token = p.getConfiguration().WebhookSecret
}
namespace := parameters[1]
var group, project string
namespaceErr := p.useGitlabClient(info, func(info *gitlab.UserInfo, token *oauth2.Token) error {
respGroup, respProject, err := p.GitlabClient.ResolveNamespaceAndProject(ctx, info, token, namespace, enablePrivateRepo)
if err != nil {
return err
}
group = respGroup
project = respProject
return nil
})
if namespaceErr != nil {
return namespaceErr.Error()
}
newWebhook, err := p.createHook(ctx, p.GitlabClient, info, group, project, hookOptions)
if err != nil {
return err.Error()
}
return fmt.Sprintf("Webhook Created:\n%s", newWebhook.String())
default:
return fmt.Sprintf("Unknown webhook command: %s", subCommand)
}
}
func parseTriggers(triggersCsv string) *gitlab.AddWebhookOptions {
var sslVerification, pushEvents, tagPushEvents, issuesEvents, confidentialIssuesEvents, noteEvents bool
var confidentialNoteEvents, mergeRequestsEvents, jobEvents, pipelineEvents, wikiPageEvents, deploymentEvents, releaseEvents bool
var all bool
if triggersCsv == "*" {
all = true
sslVerification = true
}
if strings.EqualFold(triggersCsv, "*noSSL") {
all = true
sslVerification = false
}
for trigger := range strings.SplitSeq(triggersCsv, ",") {
if strings.EqualFold(trigger, "SSLverification") {
sslVerification = true
}
if all || strings.EqualFold(trigger, "PushEvents") {
pushEvents = true
}
if all || strings.EqualFold(trigger, "TagPushEvents") {
tagPushEvents = true
}
if all || strings.EqualFold(trigger, "IssuesEvents") {
issuesEvents = true
}
if all || strings.EqualFold(trigger, "ConfidentialIssuesEvents") {
confidentialIssuesEvents = true
}
if all || strings.EqualFold(trigger, "Comments") {
noteEvents = true
}
if all || strings.EqualFold(trigger, "ConfidentialComments") {
confidentialNoteEvents = true
}
if all || strings.EqualFold(trigger, "MergeRequestsEvents") {
mergeRequestsEvents = true
}
if all || strings.EqualFold(trigger, "JobEvents") {
jobEvents = true
}
if all || strings.EqualFold(trigger, "PipelineEvents") {
pipelineEvents = true
}
if all || strings.EqualFold(trigger, "WikiPageEvents") {
wikiPageEvents = true
}
if all || strings.EqualFold(trigger, "DeploymentEvents") {
deploymentEvents = true
}
if all || strings.EqualFold(trigger, "ReleaseEvents") {
releaseEvents = true
}
}
return &gitlab.AddWebhookOptions{
EnableSSLVerification: sslVerification,
ConfidentialNoteEvents: confidentialNoteEvents,
PushEvents: pushEvents,
IssuesEvents: issuesEvents,
ConfidentialIssuesEvents: confidentialIssuesEvents,
MergeRequestsEvents: mergeRequestsEvents,
TagPushEvents: tagPushEvents,
NoteEvents: noteEvents,
JobEvents: jobEvents,
PipelineEvents: pipelineEvents,
WikiPageEvents: wikiPageEvents,
DeploymentEvents: deploymentEvents,
ReleaseEvents: releaseEvents,
}
}
func (p *Plugin) subscriptionDelete(userInfo *gitlab.UserInfo, config *configuration, fullPath, channelID string) (string, bool, error) {
normalizedPath := normalizePath(fullPath, config.GitlabURL)
deleted, updatedSubscriptions, err := p.Unsubscribe(channelID, normalizedPath)
if err != nil {
p.client.Log.Warn("can't unsubscribe channel in command", "err", err.Error())
return "Encountered an error trying to unsubscribe. Please try again.", true, nil
}
if !deleted {
return "Subscription not found, please check repository name.", true, nil
}
p.sendChannelSubscriptionsUpdated(updatedSubscriptions, channelID)
baseURL := config.GitlabURL
if !strings.HasSuffix(baseURL, "/") {
baseURL += "/"
}
owner := strings.Split(normalizedPath, "/")[0]
remainingPath := strings.Split(normalizedPath, "/")[1:]
ctx, cancel := context.WithTimeout(context.Background(), webhookTimeout)
defer cancel()
var project *gitlabLib.Project
var getProjectError error
err = p.useGitlabClient(userInfo, func(info *gitlab.UserInfo, token *oauth2.Token) error {
//nolint:govet // Ignore variable shadowing warning
resp, err := p.GitlabClient.GetProject(ctx, info, token, owner, strings.Join(remainingPath, "/"))
if err != nil {
getProjectError = err
} else {
project = resp
}
return nil
})
if project == nil || err != nil {
if err != nil {
p.client.Log.Warn("Can't get group in subscription delete", "err", err.Error(), "group", normalizedPath)
}
}
var webhookMsg string
if getProjectError == nil && project != nil {
webhookMsg = fmt.Sprintf("\n Please delete the [webhook](%s) for this subscription unless it's required for other subscriptions.", fmt.Sprintf("%s%s/-/hooks", baseURL, normalizedPath))
} else {
var group *gitlabLib.Group
var getGroupError error
err = p.useGitlabClient(userInfo, func(info *gitlab.UserInfo, token *oauth2.Token) error {
//nolint:govet // Ignore variable shadowing warning
resp, err := p.GitlabClient.GetGroup(ctx, info, token, owner, strings.Join(remainingPath, "/"))
if err != nil {
getGroupError = err
} else {
group = resp
}
return nil
})
if group == nil || err != nil {
if err != nil {
p.client.Log.Warn("Can't get project in subscription delete", "err", err.Error(), "project", normalizedPath)
}
}
if getGroupError == nil && group != nil {
webhookMsg = fmt.Sprintf("\n Please delete the [webhook](%s) for this subscription unless it's required for other subscriptions.", fmt.Sprintf("%sgroups/%s/-/hooks", baseURL, normalizedPath))
} else {
webhookMsg = "\n Please delete the webhook for this subscription unless it's required for other subscriptions."
}
}
unsubscribeMessage := fmt.Sprintf("Successfully deleted subscription for %s.", fmt.Sprintf("[%s](%s)", normalizedPath, baseURL+normalizedPath))
unsubscribeMessage += webhookMsg
return unsubscribeMessage, false, nil
}
// subscriptionsListCommand list GitLab subscriptions in a channel
func (p *Plugin) subscriptionsListCommand(channelID string) string {
var txt string
subs, err := p.GetSubscriptionsByChannel(channelID)
if err != nil {
return err.Error()
}
if len(subs) == 0 {
txt = "Currently there are no subscriptions in this channel"
} else {
txt = "### Subscriptions in this channel\n"
}
for _, sub := range subs {
txt += fmt.Sprintf("* `%s` - %s\n", strings.Trim(sub.Repository, "/"), sub.Features)
}
return txt
}
// subscriptionsAddCommand subscripes to A GitLab Project
func (p *Plugin) subscriptionsAddCommand(ctx context.Context, info *gitlab.UserInfo, config *configuration, fullPath, channelID, features string) string {
var namespace, project string
err := p.useGitlabClient(info, func(info *gitlab.UserInfo, token *oauth2.Token) error {
respGroup, respProject, err := p.GitlabClient.ResolveNamespaceAndProject(ctx, info, token, fullPath, config.EnablePrivateRepo)
if err != nil {
return err
}
namespace = respGroup
project = respProject
return nil
})
if err != nil {
if errors.Is(err, gitlab.ErrNotFound) {
return "Resource with such path is not found."
} else if errors.Is(err, gitlab.ErrPrivateResource) {
return "Requested resource is private."
}
p.client.Log.Warn(
"unable to resolve subscription namespace and project name",
"err", err.Error(),
)
return err.Error()
}
// Only check the permissions for a project if the project subscription is created (Not a group or a subgroup subscription)
if project != "" {
if hasPermission := p.permissionToProject(ctx, info.UserID, namespace, project); !hasPermission {
msg := "You don't have the permissions to create subscriptions for this project."
p.client.Log.Warn(msg)
return msg
}
}
updatedSubscriptions, subscribeErr := p.Subscribe(info, namespace, project, channelID, features)
if subscribeErr != nil {
p.client.Log.Warn(
"failed to subscribe",
"namespace", namespace,
"project", project,
"err", subscribeErr.Error(),
)
return subscribeErr.Error()
}
var hasHook bool
hasHookError := false
if project != "" {
hasHook, err = p.HasProjectHook(ctx, info, namespace, project)
if err != nil {
p.client.Log.Debug("Unable to fetch project webhook data", "Error", err.Error())
hasHookError = true
}
} else {
hasHook, err = p.HasGroupHook(ctx, info, namespace)
if err != nil {
p.client.Log.Debug("Unable to fetch group webhook data", "Error", err.Error())
hasHookError = true
}
}
hookErrorMessage := ""
if hasHookError {
hookErrorMessage = "\n**Note:** We are unable to determine the webhook status for this project. Please contact your project administrator"
}
var hookStatusMessage string
if !hasHook {
// no web hook found
hookStatusMessage = fmt.Sprintf("\nA Webhook is needed, run ```/gitlab webhook add %s``` to create one now.%s", fullPath, hookErrorMessage)
}
p.sendChannelSubscriptionsUpdated(updatedSubscriptions, channelID)
return fmt.Sprintf("Successfully subscribed to %s.%s", fullPath, hookStatusMessage)
}
// subscribeCommand process the /gitlab subscribe command.
// It returns a message and handles all errors my including helpful information in the message
func (p *Plugin) subscribeCommand(ctx context.Context, parameters []string, channelID string, config *configuration, info *gitlab.UserInfo) (string, bool) {
if len(parameters) == 0 {
return invalidSubscribeSubCommand, true
}
subcommand := parameters[0]
switch subcommand {
case commandList:
return p.subscriptionsListCommand(channelID), true
case commandAdd:
features := "merges,issues,tag"
if len(parameters) < 2 {
return missingOrgOrRepoFromSubscribeCommand, true
} else if len(parameters) > 2 {
features = strings.Join(parameters[2:], " ")
}
// Resolve namespace and project name
fullPath := normalizePath(parameters[1], config.GitlabURL)
return p.subscriptionsAddCommand(ctx, info, config, fullPath, channelID, features), false
case commandDelete:
if len(parameters) < 2 {
return specifyRepositoryMessage, true
}
message, isEphemeralPost, err := p.subscriptionDelete(info, config, parameters[1], channelID)
if err != nil {
return err.Error(), true
}
return message, isEphemeralPost
default:
return invalidSubscribeSubCommand, true
}
}
func (p *Plugin) pipelinesCommand(ctx context.Context, parameters []string, channelID string, info *gitlab.UserInfo) string {
if len(parameters) == 0 {
return invalidPipelinesSubCommand
}
subcommand := parameters[0]
switch subcommand {
case commandRun:
if len(parameters) < 3 {
return specifyRepositoryAndBranchMessage
}
namespace := parameters[1]
ref := parameters[2]
return p.pipelineRunCommand(ctx, namespace, ref, channelID, info)
default:
return unknownActionMessage
}
}
// pipelineRunCommand run a pipeline in a project
func (p *Plugin) pipelineRunCommand(ctx context.Context, namespace, ref, channelID string, info *gitlab.UserInfo) string {
var pipelineInfo *gitlab.PipelineInfo
err := p.useGitlabClient(info, func(info *gitlab.UserInfo, token *oauth2.Token) error {
groupName, projectName, err := p.GitlabClient.ResolveNamespaceAndProject(ctx, info, token, namespace, true)
if err != nil {
return err
}
project, err := p.GitlabClient.GetProject(ctx, info, token, groupName, projectName)
if err != nil {
return err
}
projectID := fmt.Sprintf("%d", project.ID)
pipelineInfo, err = p.GitlabClient.TriggerProjectPipeline(info, token, projectID, ref)
if err != nil {
return errors.Wrapf(err, "failed to run pipeline for Project: :%s", projectName)
}
return nil