This repository has been archived by the owner on Aug 27, 2022. It is now read-only.
/
handlers_api.go
193 lines (153 loc) · 4.34 KB
/
handlers_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
package handlers
import (
"fmt"
"net/http"
"strings"
"time"
"github.com/gin-gonic/gin"
"github.com/nlopes/slack"
"github.com/gouline/blaster/internal/pkg/scache"
"github.com/gouline/blaster/internal/pkg/utils"
)
var suggestCache = scache.New(5*time.Minute, 10*time.Minute)
// APISuggest handles /api/suggest.
func APISuggest(c *gin.Context) {
token := authorizedToken(c)
if token == "" {
c.AbortWithError(http.StatusUnauthorized, fmt.Errorf("no token"))
return
}
cacheResponse := <-buildSuggestCache(token)
if cacheResponse.Error != nil {
c.AbortWithError(http.StatusInternalServerError, cacheResponse.Error)
return
}
allSuggestions := cacheResponse.Value.([]suggestion)
// Filter out all symbols from term
symbolReg := utils.NewAllSymbolsRegexp()
term := strings.ToLower(" " + c.Query("term"))
term = symbolReg.ReplaceAllString(term, "")
// Filter users by term
suggestions := []suggestion{}
for _, suggestion := range allSuggestions {
if strings.Contains(suggestion.Search, term) {
suggestions = append(suggestions, suggestion)
if len(suggestions) == 10 {
break
}
}
}
c.JSON(http.StatusOK, suggestions)
}
func buildSuggestCache(token string) <-chan scache.Response {
return suggestCache.ResponseChan(hashedToken(token), func(key string) (interface{}, error) {
client := slack.New(token)
symbolReg := utils.NewAllSymbolsRegexp()
var suggestions []suggestion
userLookup := map[string]suggestion{}
// Get all users
users, err := client.GetUsers()
if err != nil {
return nil, err
}
suggestions = []suggestion{}
for _, user := range users {
if user.Deleted || user.IsBot {
continue
}
realName := user.Profile.RealName
displayName := user.Profile.DisplayName
// Format label based on availability
label := realName
if displayName != "" {
label += " (" + displayName + ")"
}
// Filter out all symbols from search string
search := fmt.Sprintf(" %s %s", strings.ToLower(realName), strings.ToLower(displayName))
search = symbolReg.ReplaceAllString(search, "")
// Sanitize labels and values
sanitize := func(s string) string {
return strings.Replace(s, ",", "", -1)
}
s := suggestion{
Type: "user",
Label: sanitize(label),
Value: sanitize(user.ID),
Search: search,
}
suggestions = append(suggestions, s)
userLookup[user.ID] = s
}
usergroups, err := client.GetUserGroups(slack.GetUserGroupsOptionIncludeUsers(true))
for _, usergroup := range usergroups {
if !usergroup.IsUserGroup {
continue
}
children := []suggestion{}
for _, userID := range usergroup.Users {
user, found := userLookup[userID]
if !found {
continue
}
children = append(children, user)
}
name := usergroup.Name
handle := usergroup.Handle
label := name + " (" + handle + ")"
// Filter out all symbols from search string
search := fmt.Sprintf(" %s %s", strings.ToLower(name), strings.ToLower(handle))
search = symbolReg.ReplaceAllString(search, "")
suggestions = append(suggestions, suggestion{
Type: "usergroup",
Label: label,
Value: "null",
Search: search,
Children: children,
})
}
return suggestions, nil
})
}
// APISend handles /api/send.
func APISend(c *gin.Context) {
token := authorizedToken(c)
if token == "" {
c.AbortWithError(http.StatusUnauthorized, fmt.Errorf("no token"))
return
}
client := slack.New(token)
// Bind JSON request
var request sendRequest
err := c.BindJSON(&request)
if err != nil {
c.AbortWithError(http.StatusBadRequest, err)
return
}
// Open/get channel by user ID
_, _, channelID, err := client.OpenIMChannel(request.User)
if err != nil {
c.AbortWithError(http.StatusInternalServerError, err)
return
}
// Post message to opened channel
_, _, err = client.PostMessage(channelID, request.Message, slack.PostMessageParameters{
AsUser: request.AsUser,
})
if err != nil {
c.AbortWithError(http.StatusInternalServerError, err)
return
}
c.JSON(http.StatusOK, struct{}{})
}
type suggestion struct {
Type string `json:"type"`
Label string `json:"label"`
Value string `json:"value"`
Children []suggestion `json:"children,omitempty"`
Search string `json:"-"`
}
type sendRequest struct {
User string `json:"user"`
Message string `json:"message"`
AsUser bool `json:"as_user"`
}