forked from mattermost/mattermost
-
Notifications
You must be signed in to change notification settings - Fork 0
/
command.go
367 lines (307 loc) · 11 KB
/
command.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
// Copyright (c) 2016-present Mattermost, Inc. All Rights Reserved.
// See License.txt for license information.
package app
import (
"crypto/tls"
"fmt"
"io/ioutil"
"net/http"
"net/url"
"strings"
l4g "github.com/alecthomas/log4go"
"github.com/mattermost/platform/model"
"github.com/mattermost/platform/utils"
goi18n "github.com/nicksnyder/go-i18n/i18n"
)
type CommandProvider interface {
GetTrigger() string
GetCommand(T goi18n.TranslateFunc) *model.Command
DoCommand(args *model.CommandArgs, message string) *model.CommandResponse
}
var commandProviders = make(map[string]CommandProvider)
func RegisterCommandProvider(newProvider CommandProvider) {
commandProviders[newProvider.GetTrigger()] = newProvider
}
func GetCommandProvider(name string) CommandProvider {
provider, ok := commandProviders[name]
if ok {
return provider
}
return nil
}
func CreateCommandPost(post *model.Post, teamId string, response *model.CommandResponse) (*model.Post, *model.AppError) {
post.Message = parseSlackLinksToMarkdown(response.Text)
post.CreateAt = model.GetMillis()
if response.Attachments != nil {
parseSlackAttachment(post, response.Attachments)
}
switch response.ResponseType {
case model.COMMAND_RESPONSE_TYPE_IN_CHANNEL:
return CreatePost(post, teamId, true)
case model.COMMAND_RESPONSE_TYPE_EPHEMERAL:
if response.Text == "" {
return post, nil
}
post.ParentId = ""
SendEphemeralPost(teamId, post.UserId, post)
}
return post, nil
}
// previous ListCommands now ListAutocompleteCommands
func ListAutocompleteCommands(teamId string, T goi18n.TranslateFunc) ([]*model.Command, *model.AppError) {
commands := make([]*model.Command, 0, 32)
seen := make(map[string]bool)
for _, value := range commandProviders {
cpy := *value.GetCommand(T)
if cpy.AutoComplete && !seen[cpy.Id] {
cpy.Sanitize()
seen[cpy.Trigger] = true
commands = append(commands, &cpy)
}
}
if *utils.Cfg.ServiceSettings.EnableCommands {
if result := <-Srv.Store.Command().GetByTeam(teamId); result.Err != nil {
return nil, result.Err
} else {
teamCmds := result.Data.([]*model.Command)
for _, cmd := range teamCmds {
if cmd.AutoComplete && !seen[cmd.Id] {
cmd.Sanitize()
seen[cmd.Trigger] = true
commands = append(commands, cmd)
}
}
}
}
return commands, nil
}
func ListTeamCommands(teamId string) ([]*model.Command, *model.AppError) {
if !*utils.Cfg.ServiceSettings.EnableCommands {
return nil, model.NewAppError("ListTeamCommands", "api.command.disabled.app_error", nil, "", http.StatusNotImplemented)
}
if result := <-Srv.Store.Command().GetByTeam(teamId); result.Err != nil {
return nil, result.Err
} else {
return result.Data.([]*model.Command), nil
}
}
func ListAllCommands(teamId string, T goi18n.TranslateFunc) ([]*model.Command, *model.AppError) {
commands := make([]*model.Command, 0, 32)
seen := make(map[string]bool)
for _, value := range commandProviders {
cpy := *value.GetCommand(T)
if cpy.AutoComplete && !seen[cpy.Id] {
cpy.Sanitize()
seen[cpy.Trigger] = true
commands = append(commands, &cpy)
}
}
if *utils.Cfg.ServiceSettings.EnableCommands {
if result := <-Srv.Store.Command().GetByTeam(teamId); result.Err != nil {
return nil, result.Err
} else {
teamCmds := result.Data.([]*model.Command)
for _, cmd := range teamCmds {
if !seen[cmd.Id] {
cmd.Sanitize()
seen[cmd.Trigger] = true
commands = append(commands, cmd)
}
}
}
}
return commands, nil
}
func ExecuteCommand(args *model.CommandArgs) (*model.CommandResponse, *model.AppError) {
parts := strings.Split(args.Command, " ")
trigger := parts[0][1:]
trigger = strings.ToLower(trigger)
message := strings.Join(parts[1:], " ")
provider := GetCommandProvider(trigger)
if provider != nil {
response := provider.DoCommand(args, message)
return HandleCommandResponse(provider.GetCommand(args.T), args, response, true)
} else {
if !*utils.Cfg.ServiceSettings.EnableCommands {
return nil, model.NewAppError("ExecuteCommand", "api.command.disabled.app_error", nil, "", http.StatusNotImplemented)
}
chanChan := Srv.Store.Channel().Get(args.ChannelId, true)
teamChan := Srv.Store.Team().Get(args.TeamId)
userChan := Srv.Store.User().Get(args.UserId)
if result := <-Srv.Store.Command().GetByTeam(args.TeamId); result.Err != nil {
return nil, result.Err
} else {
var team *model.Team
if tr := <-teamChan; tr.Err != nil {
return nil, tr.Err
} else {
team = tr.Data.(*model.Team)
}
var user *model.User
if ur := <-userChan; ur.Err != nil {
return nil, ur.Err
} else {
user = ur.Data.(*model.User)
}
var channel *model.Channel
if cr := <-chanChan; cr.Err != nil {
return nil, cr.Err
} else {
channel = cr.Data.(*model.Channel)
}
teamCmds := result.Data.([]*model.Command)
for _, cmd := range teamCmds {
if trigger == cmd.Trigger {
l4g.Debug(fmt.Sprintf(utils.T("api.command.execute_command.debug"), trigger, args.UserId))
p := url.Values{}
p.Set("token", cmd.Token)
p.Set("team_id", cmd.TeamId)
p.Set("team_domain", team.Name)
p.Set("channel_id", args.ChannelId)
p.Set("channel_name", channel.Name)
p.Set("user_id", args.UserId)
p.Set("user_name", user.Username)
p.Set("command", "/"+trigger)
p.Set("text", message)
p.Set("response_url", "not supported yet")
method := "POST"
if cmd.Method == model.COMMAND_METHOD_GET {
method = "GET"
}
tr := &http.Transport{
TLSClientConfig: &tls.Config{InsecureSkipVerify: *utils.Cfg.ServiceSettings.EnableInsecureOutgoingConnections},
}
client := &http.Client{Transport: tr}
req, _ := http.NewRequest(method, cmd.URL, strings.NewReader(p.Encode()))
req.Header.Set("Accept", "application/json")
if cmd.Method == model.COMMAND_METHOD_POST {
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
}
if resp, err := client.Do(req); err != nil {
return nil, model.NewAppError("command", "api.command.execute_command.failed.app_error", map[string]interface{}{"Trigger": trigger}, err.Error(), http.StatusInternalServerError)
} else {
if resp.StatusCode == http.StatusOK {
response := model.CommandResponseFromJson(resp.Body)
if response == nil {
return nil, model.NewAppError("command", "api.command.execute_command.failed_empty.app_error", map[string]interface{}{"Trigger": trigger}, "", http.StatusInternalServerError)
} else {
return HandleCommandResponse(cmd, args, response, false)
}
} else {
defer resp.Body.Close()
body, _ := ioutil.ReadAll(resp.Body)
return nil, model.NewAppError("command", "api.command.execute_command.failed_resp.app_error", map[string]interface{}{"Trigger": trigger, "Status": resp.Status}, string(body), http.StatusInternalServerError)
}
}
}
}
}
}
return nil, model.NewAppError("command", "api.command.execute_command.not_found.app_error", map[string]interface{}{"Trigger": trigger}, "", http.StatusNotFound)
}
func HandleCommandResponse(command *model.Command, args *model.CommandArgs, response *model.CommandResponse, builtIn bool) (*model.CommandResponse, *model.AppError) {
post := &model.Post{}
post.ChannelId = args.ChannelId
post.RootId = args.RootId
post.ParentId = args.ParentId
post.UserId = args.UserId
if !builtIn {
post.AddProp("from_webhook", "true")
}
if utils.Cfg.ServiceSettings.EnablePostUsernameOverride {
if len(command.Username) != 0 {
post.AddProp("override_username", command.Username)
} else if len(response.Username) != 0 {
post.AddProp("override_username", response.Username)
}
}
if utils.Cfg.ServiceSettings.EnablePostIconOverride {
if len(command.IconURL) != 0 {
post.AddProp("override_icon_url", command.IconURL)
} else if len(response.IconURL) != 0 {
post.AddProp("override_icon_url", response.IconURL)
} else {
post.AddProp("override_icon_url", "")
}
}
if _, err := CreateCommandPost(post, args.TeamId, response); err != nil {
l4g.Error(err.Error())
}
return response, nil
}
func CreateCommand(cmd *model.Command) (*model.Command, *model.AppError) {
if !*utils.Cfg.ServiceSettings.EnableCommands {
return nil, model.NewAppError("CreateCommand", "api.command.disabled.app_error", nil, "", http.StatusNotImplemented)
}
cmd.Trigger = strings.ToLower(cmd.Trigger)
if result := <-Srv.Store.Command().GetByTeam(cmd.TeamId); result.Err != nil {
return nil, result.Err
} else {
teamCmds := result.Data.([]*model.Command)
for _, existingCommand := range teamCmds {
if cmd.Trigger == existingCommand.Trigger {
return nil, model.NewAppError("CreateCommand", "api.command.duplicate_trigger.app_error", nil, "", http.StatusBadRequest)
}
}
for _, builtInProvider := range commandProviders {
builtInCommand := *builtInProvider.GetCommand(utils.T)
if cmd.Trigger == builtInCommand.Trigger {
return nil, model.NewAppError("CreateCommand", "api.command.duplicate_trigger.app_error", nil, "", http.StatusBadRequest)
}
}
}
if result := <-Srv.Store.Command().Save(cmd); result.Err != nil {
return nil, result.Err
} else {
return result.Data.(*model.Command), nil
}
}
func GetCommand(commandId string) (*model.Command, *model.AppError) {
if !*utils.Cfg.ServiceSettings.EnableCommands {
return nil, model.NewAppError("GetCommand", "api.command.disabled.app_error", nil, "", http.StatusNotImplemented)
}
if result := <-Srv.Store.Command().Get(commandId); result.Err != nil {
result.Err.StatusCode = http.StatusNotFound
return nil, result.Err
} else {
return result.Data.(*model.Command), nil
}
}
func UpdateCommand(oldCmd, updatedCmd *model.Command) (*model.Command, *model.AppError) {
if !*utils.Cfg.ServiceSettings.EnableCommands {
return nil, model.NewAppError("UpdateCommand", "api.command.disabled.app_error", nil, "", http.StatusNotImplemented)
}
updatedCmd.Trigger = strings.ToLower(updatedCmd.Trigger)
updatedCmd.Id = oldCmd.Id
updatedCmd.Token = oldCmd.Token
updatedCmd.CreateAt = oldCmd.CreateAt
updatedCmd.UpdateAt = model.GetMillis()
updatedCmd.DeleteAt = oldCmd.DeleteAt
updatedCmd.CreatorId = oldCmd.CreatorId
updatedCmd.TeamId = oldCmd.TeamId
if result := <-Srv.Store.Command().Update(updatedCmd); result.Err != nil {
return nil, result.Err
} else {
return result.Data.(*model.Command), nil
}
}
func RegenCommandToken(cmd *model.Command) (*model.Command, *model.AppError) {
if !*utils.Cfg.ServiceSettings.EnableCommands {
return nil, model.NewAppError("RegenCommandToken", "api.command.disabled.app_error", nil, "", http.StatusNotImplemented)
}
cmd.Token = model.NewId()
if result := <-Srv.Store.Command().Update(cmd); result.Err != nil {
return nil, result.Err
} else {
return result.Data.(*model.Command), nil
}
}
func DeleteCommand(commandId string) *model.AppError {
if !*utils.Cfg.ServiceSettings.EnableCommands {
return model.NewAppError("DeleteCommand", "api.command.disabled.app_error", nil, "", http.StatusNotImplemented)
}
if err := (<-Srv.Store.Command().Delete(commandId, model.GetMillis())).Err; err != nil {
return err
}
return nil
}