-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathhandler.go
More file actions
163 lines (147 loc) · 5.89 KB
/
handler.go
File metadata and controls
163 lines (147 loc) · 5.89 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
package main
import (
"bytes"
"encoding/json"
"fmt"
"log"
"net/http"
"strings"
"github.com/slack-go/slack"
)
// interactionHandler is a http.Handler that can handle slack interaction callbacks.
// See https://api.slack.com/interactivity/handling for more details about interactions.
type interactionHandler struct {
verificationToken string
client *slack.Client
projectList *ProjectList
userList *UserList
interactorFactory *InteractorFactory
}
func getSlackError(system, msg string, user string) []byte {
respoonse := slack.Message{
Msg: slack.Msg{
ResponseType: "in_channel",
Text: fmt.Sprintf("%s: %s actioned by <@%s>", system, msg, user),
},
}
respoonse.ReplaceOriginal = true
responseBytes, _ := json.Marshal(respoonse)
return responseBytes
}
func (h interactionHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
// Parse input from request
if err := r.ParseForm(); err != nil {
log.Printf("[ERROR] Failed to parse form: %s", err)
// getSlackError is a helper to quickly render errors back to slack
responseBytes := getSlackError("Server Error", "An unknown error occurred", "unkown")
_, _ = w.Write(responseBytes) // not display message on slack
return
}
interactionRequest := slack.InteractionCallback{}
if err := json.Unmarshal([]byte(r.PostForm.Get("payload")), &interactionRequest); err != nil {
log.Printf("[ERROR] Failed to unmarshal interaction request: %s", err)
responseBytes := getSlackError("Server Error", "An unknown error occurred", "unkown")
_, _ = w.Write(responseBytes) // not display message on slack
return
}
// Get the action from the request, it'll always be the first one provided in my case
var actionValue string
switch interactionRequest.ActionCallback.BlockActions[0].Type {
case "button":
actionValue = interactionRequest.ActionCallback.BlockActions[0].Value
case "static_select":
actionValue = interactionRequest.ActionCallback.BlockActions[0].SelectedOption.Value
}
userID := interactionRequest.User.ID
// Handle close action
if strings.Contains(actionValue, "close") {
// Found this on stack overflow, unsure if this exists in the package
closeStr := fmt.Sprintf(`{
'response_type': 'in_channel',
'text': 'closed by <@%s>',
'replace_original': true,
'delete_original': true
}`, userID)
// Post close json back to response URL to close the message
if _, err := http.Post(interactionRequest.ResponseURL, "application/json", bytes.NewBuffer([]byte(closeStr))); err != nil {
log.Printf("[ERROR] Failed to post close action response: %v", err)
}
return
}
log.Printf("[INFO] Action Value: %s", actionValue)
if strings.HasPrefix(actionValue, "deploy") {
h.Deploy(w, interactionRequest)
return
}
log.Print("[ERROR] An unknown error occurred")
responseBytes := getSlackError("Server Error", "An unknown error occurred", userID)
if _, err := http.Post(interactionRequest.ResponseURL, "application/json", bytes.NewBuffer([]byte(responseBytes))); err != nil {
log.Printf("[ERROR] Failed to post unknown error response: %v", err)
}
}
func (h interactionHandler) Deploy(w http.ResponseWriter, interactionRequest slack.InteractionCallback) {
actionValue := interactionRequest.ActionCallback.BlockActions[0].Value
if actionValue == "" {
actionValue = interactionRequest.ActionCallback.BlockActions[0].SelectedOption.Value
}
userID := interactionRequest.User.ID
user := h.userList.FindBySlackUserID(userID)
if !user.IsDeveloper() {
h.postForbiddenError(interactionRequest.ResponseURL, userID)
return
}
params := strings.Split(actionValue, "|")
if len(params) != 2 {
h.postInternalServerError(interactionRequest.ResponseURL, userID)
return
}
interactor := h.interactorFactory.GetByParams(params[0])
var blocks []slack.Block
var err error
switch {
case strings.Contains(params[0], "request"):
p := strings.Split(params[1], "_")
if len(p) != 2 {
err = fmt.Errorf("Invalid Arguments")
break
}
pj := h.projectList.Find(p[0])
blocks, err = interactor.Request(pj, p[1], pj.DefaultBranch(), userID, interactionRequest.Channel.ID)
case strings.Contains(params[0], "approve"):
blocks, err = interactor.Approve(params[1], userID, interactionRequest.Channel.ID)
case strings.Contains(params[0], "reject"):
blocks, err = interactor.Reject(params[1], userID)
case strings.Contains(params[0], "selectbranch"):
blocks, err = interactor.SelectBranch(params[1], interactionRequest.ActionCallback.BlockActions[0].SelectedOption.Text.Text, userID, interactionRequest.Channel.ID)
case strings.Contains(params[0], "branchlist"):
blocks, err = interactor.BranchListFromRaw(params[1])
default:
h.postInternalServerError(interactionRequest.ResponseURL, userID)
return
}
if err != nil {
log.Print(err)
h.postInternalServerError(interactionRequest.ResponseURL, userID)
return
}
responseData := slack.NewBlockMessage(blocks...)
responseData.ReplaceOriginal = true
responseBytes, _ := json.Marshal(responseData)
if _, err := http.Post(interactionRequest.ResponseURL, "application/json", bytes.NewBuffer(responseBytes)); err != nil {
log.Printf("[ERROR] Failed to post deploy action response: %v", err)
}
}
func (h interactionHandler) postForbiddenError(responseURL string, userID string) {
log.Print("[ERROR] Forbidden Error")
responseBytes := getSlackError("Forbidden Error", "Please contact admin.", userID)
if _, err := http.Post(responseURL, "application/json", bytes.NewBuffer(responseBytes)); err != nil {
log.Printf("[ERROR] Failed to post forbidden error response: %v", err)
}
}
func (h interactionHandler) postInternalServerError(responseURL string, userID string) {
log.Print("[ERROR] Internal Server Error")
responseBytes := getSlackError("Internal Server Error", "Please contact admin.", userID)
if _, err := http.Post(responseURL, "application/json", bytes.NewBuffer(responseBytes)); err != nil {
log.Printf("[ERROR] Failed to post internal server error response: %v", err)
}
}