command.go 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537
  1. // Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved.
  2. // See LICENSE.txt for license information.
  3. package app
  4. import (
  5. "io"
  6. "io/ioutil"
  7. "net/http"
  8. "net/url"
  9. "strings"
  10. goi18n "github.com/mattermost/go-i18n/i18n"
  11. "github.com/mattermost/mattermost-server/v5/mlog"
  12. "github.com/mattermost/mattermost-server/v5/model"
  13. "github.com/mattermost/mattermost-server/v5/store"
  14. "github.com/mattermost/mattermost-server/v5/utils"
  15. )
  16. type CommandProvider interface {
  17. GetTrigger() string
  18. GetCommand(a *App, T goi18n.TranslateFunc) *model.Command
  19. DoCommand(a *App, args *model.CommandArgs, message string) *model.CommandResponse
  20. }
  21. var commandProviders = make(map[string]CommandProvider)
  22. func RegisterCommandProvider(newProvider CommandProvider) {
  23. commandProviders[newProvider.GetTrigger()] = newProvider
  24. }
  25. func GetCommandProvider(name string) CommandProvider {
  26. provider, ok := commandProviders[name]
  27. if ok {
  28. return provider
  29. }
  30. return nil
  31. }
  32. func (a *App) CreateCommandPost(post *model.Post, teamId string, response *model.CommandResponse, skipSlackParsing bool) (*model.Post, *model.AppError) {
  33. if skipSlackParsing {
  34. post.Message = response.Text
  35. } else {
  36. post.Message = model.ParseSlackLinksToMarkdown(response.Text)
  37. }
  38. post.CreateAt = model.GetMillis()
  39. if strings.HasPrefix(post.Type, model.POST_SYSTEM_MESSAGE_PREFIX) {
  40. err := model.NewAppError("CreateCommandPost", "api.context.invalid_param.app_error", map[string]interface{}{"Name": "post.type"}, "", http.StatusBadRequest)
  41. return nil, err
  42. }
  43. if response.Attachments != nil {
  44. model.ParseSlackAttachment(post, response.Attachments)
  45. }
  46. if response.ResponseType == model.COMMAND_RESPONSE_TYPE_IN_CHANNEL {
  47. return a.CreatePostMissingChannel(post, true)
  48. }
  49. if (response.ResponseType == "" || response.ResponseType == model.COMMAND_RESPONSE_TYPE_EPHEMERAL) && (response.Text != "" || response.Attachments != nil) {
  50. post.ParentId = ""
  51. a.SendEphemeralPost(post.UserId, post)
  52. }
  53. return post, nil
  54. }
  55. // previous ListCommands now ListAutocompleteCommands
  56. func (a *App) ListAutocompleteCommands(teamId string, T goi18n.TranslateFunc) ([]*model.Command, *model.AppError) {
  57. commands := make([]*model.Command, 0, 32)
  58. seen := make(map[string]bool)
  59. for _, value := range commandProviders {
  60. if cmd := value.GetCommand(a, T); cmd != nil {
  61. cpy := *cmd
  62. if cpy.AutoComplete && !seen[cpy.Id] {
  63. cpy.Sanitize()
  64. seen[cpy.Trigger] = true
  65. commands = append(commands, &cpy)
  66. }
  67. }
  68. }
  69. for _, cmd := range a.PluginCommandsForTeam(teamId) {
  70. if cmd.AutoComplete && !seen[cmd.Trigger] {
  71. seen[cmd.Trigger] = true
  72. commands = append(commands, cmd)
  73. }
  74. }
  75. if *a.Config().ServiceSettings.EnableCommands {
  76. teamCmds, err := a.Srv.Store.Command().GetByTeam(teamId)
  77. if err != nil {
  78. return nil, err
  79. }
  80. for _, cmd := range teamCmds {
  81. if cmd.AutoComplete && !seen[cmd.Id] {
  82. cmd.Sanitize()
  83. seen[cmd.Trigger] = true
  84. commands = append(commands, cmd)
  85. }
  86. }
  87. }
  88. return commands, nil
  89. }
  90. func (a *App) ListTeamCommands(teamId string) ([]*model.Command, *model.AppError) {
  91. if !*a.Config().ServiceSettings.EnableCommands {
  92. return nil, model.NewAppError("ListTeamCommands", "api.command.disabled.app_error", nil, "", http.StatusNotImplemented)
  93. }
  94. return a.Srv.Store.Command().GetByTeam(teamId)
  95. }
  96. func (a *App) ListAllCommands(teamId string, T goi18n.TranslateFunc) ([]*model.Command, *model.AppError) {
  97. commands := make([]*model.Command, 0, 32)
  98. seen := make(map[string]bool)
  99. for _, value := range commandProviders {
  100. if cmd := value.GetCommand(a, T); cmd != nil {
  101. cpy := *cmd
  102. if cpy.AutoComplete && !seen[cpy.Trigger] {
  103. cpy.Sanitize()
  104. seen[cpy.Trigger] = true
  105. commands = append(commands, &cpy)
  106. }
  107. }
  108. }
  109. for _, cmd := range a.PluginCommandsForTeam(teamId) {
  110. if !seen[cmd.Trigger] {
  111. seen[cmd.Trigger] = true
  112. commands = append(commands, cmd)
  113. }
  114. }
  115. if *a.Config().ServiceSettings.EnableCommands {
  116. teamCmds, err := a.Srv.Store.Command().GetByTeam(teamId)
  117. if err != nil {
  118. return nil, err
  119. }
  120. for _, cmd := range teamCmds {
  121. if !seen[cmd.Trigger] {
  122. cmd.Sanitize()
  123. seen[cmd.Trigger] = true
  124. commands = append(commands, cmd)
  125. }
  126. }
  127. }
  128. return commands, nil
  129. }
  130. func (a *App) ExecuteCommand(args *model.CommandArgs) (*model.CommandResponse, *model.AppError) {
  131. parts := strings.Split(args.Command, " ")
  132. trigger := parts[0][1:]
  133. trigger = strings.ToLower(trigger)
  134. message := strings.Join(parts[1:], " ")
  135. clientTriggerId, triggerId, appErr := model.GenerateTriggerId(args.UserId, a.AsymmetricSigningKey())
  136. if appErr != nil {
  137. mlog.Error("error occurred in generating trigger Id for a user ", mlog.Err(appErr))
  138. }
  139. args.TriggerId = triggerId
  140. cmd, response := a.tryExecuteBuiltInCommand(args, trigger, message)
  141. if cmd != nil && response != nil {
  142. return a.HandleCommandResponse(cmd, args, response, true)
  143. }
  144. cmd, response, appErr = a.tryExecutePluginCommand(args)
  145. if appErr != nil {
  146. return nil, appErr
  147. } else if cmd != nil && response != nil {
  148. response.TriggerId = clientTriggerId
  149. return a.HandleCommandResponse(cmd, args, response, true)
  150. }
  151. cmd, response, appErr = a.tryExecuteCustomCommand(args, trigger, message)
  152. if appErr != nil {
  153. return nil, appErr
  154. } else if cmd != nil && response != nil {
  155. response.TriggerId = clientTriggerId
  156. return a.HandleCommandResponse(cmd, args, response, false)
  157. }
  158. return nil, model.NewAppError("command", "api.command.execute_command.not_found.app_error", map[string]interface{}{"Trigger": trigger}, "", http.StatusNotFound)
  159. }
  160. // tryExecuteBuiltInCommand attempts to run a built in command based on the given arguments. If no such command can be
  161. // found, returns nil for all arguments.
  162. func (a *App) tryExecuteBuiltInCommand(args *model.CommandArgs, trigger string, message string) (*model.Command, *model.CommandResponse) {
  163. provider := GetCommandProvider(trigger)
  164. if provider == nil {
  165. return nil, nil
  166. }
  167. cmd := provider.GetCommand(a, args.T)
  168. if cmd == nil {
  169. return nil, nil
  170. }
  171. return cmd, provider.DoCommand(a, args, message)
  172. }
  173. // tryExecuteCustomCommand attempts to run a custom command based on the given arguments. If no such command can be
  174. // found, returns nil for all arguments.
  175. func (a *App) tryExecuteCustomCommand(args *model.CommandArgs, trigger string, message string) (*model.Command, *model.CommandResponse, *model.AppError) {
  176. // Handle custom commands
  177. if !*a.Config().ServiceSettings.EnableCommands {
  178. return nil, nil, model.NewAppError("ExecuteCommand", "api.command.disabled.app_error", nil, "", http.StatusNotImplemented)
  179. }
  180. chanChan := make(chan store.StoreResult, 1)
  181. go func() {
  182. channel, err := a.Srv.Store.Channel().Get(args.ChannelId, true)
  183. chanChan <- store.StoreResult{Data: channel, Err: err}
  184. close(chanChan)
  185. }()
  186. teamChan := make(chan store.StoreResult, 1)
  187. go func() {
  188. team, err := a.Srv.Store.Team().Get(args.TeamId)
  189. teamChan <- store.StoreResult{Data: team, Err: err}
  190. close(teamChan)
  191. }()
  192. userChan := make(chan store.StoreResult, 1)
  193. go func() {
  194. user, err := a.Srv.Store.User().Get(args.UserId)
  195. userChan <- store.StoreResult{Data: user, Err: err}
  196. close(userChan)
  197. }()
  198. teamCmds, err := a.Srv.Store.Command().GetByTeam(args.TeamId)
  199. if err != nil {
  200. return nil, nil, err
  201. }
  202. tr := <-teamChan
  203. if tr.Err != nil {
  204. return nil, nil, tr.Err
  205. }
  206. team := tr.Data.(*model.Team)
  207. ur := <-userChan
  208. if ur.Err != nil {
  209. return nil, nil, ur.Err
  210. }
  211. user := ur.Data.(*model.User)
  212. cr := <-chanChan
  213. if cr.Err != nil {
  214. return nil, nil, cr.Err
  215. }
  216. channel := cr.Data.(*model.Channel)
  217. var cmd *model.Command
  218. for _, teamCmd := range teamCmds {
  219. if trigger == teamCmd.Trigger {
  220. cmd = teamCmd
  221. }
  222. }
  223. if cmd == nil {
  224. return nil, nil, nil
  225. }
  226. mlog.Debug("Executing command", mlog.String("command", trigger), mlog.String("user_id", args.UserId))
  227. p := url.Values{}
  228. p.Set("token", cmd.Token)
  229. p.Set("team_id", cmd.TeamId)
  230. p.Set("team_domain", team.Name)
  231. p.Set("channel_id", args.ChannelId)
  232. p.Set("channel_name", channel.Name)
  233. p.Set("user_id", args.UserId)
  234. p.Set("user_name", user.Username)
  235. p.Set("command", "/"+trigger)
  236. p.Set("text", message)
  237. p.Set("trigger_id", args.TriggerId)
  238. hook, appErr := a.CreateCommandWebhook(cmd.Id, args)
  239. if appErr != nil {
  240. return cmd, nil, model.NewAppError("command", "api.command.execute_command.failed.app_error", map[string]interface{}{"Trigger": trigger}, appErr.Error(), http.StatusInternalServerError)
  241. }
  242. p.Set("response_url", args.SiteURL+"/hooks/commands/"+hook.Id)
  243. return a.doCommandRequest(cmd, p)
  244. }
  245. func (a *App) doCommandRequest(cmd *model.Command, p url.Values) (*model.Command, *model.CommandResponse, *model.AppError) {
  246. // Prepare the request
  247. var req *http.Request
  248. var err error
  249. if cmd.Method == model.COMMAND_METHOD_GET {
  250. req, err = http.NewRequest(http.MethodGet, cmd.URL, nil)
  251. } else {
  252. req, err = http.NewRequest(http.MethodPost, cmd.URL, strings.NewReader(p.Encode()))
  253. }
  254. if err != nil {
  255. return cmd, nil, model.NewAppError("command", "api.command.execute_command.failed.app_error", map[string]interface{}{"Trigger": cmd.Trigger}, err.Error(), http.StatusInternalServerError)
  256. }
  257. if cmd.Method == model.COMMAND_METHOD_GET {
  258. if req.URL.RawQuery != "" {
  259. req.URL.RawQuery += "&"
  260. }
  261. req.URL.RawQuery += p.Encode()
  262. }
  263. req.Header.Set("Accept", "application/json")
  264. req.Header.Set("Authorization", "Token "+cmd.Token)
  265. if cmd.Method == model.COMMAND_METHOD_POST {
  266. req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
  267. }
  268. // Send the request
  269. resp, err := a.HTTPService.MakeClient(false).Do(req)
  270. if err != nil {
  271. return cmd, nil, model.NewAppError("command", "api.command.execute_command.failed.app_error", map[string]interface{}{"Trigger": cmd.Trigger}, err.Error(), http.StatusInternalServerError)
  272. }
  273. defer resp.Body.Close()
  274. // Handle the response
  275. body := io.LimitReader(resp.Body, MaxIntegrationResponseSize)
  276. if resp.StatusCode != http.StatusOK {
  277. // Ignore the error below because the resulting string will just be the empty string if bodyBytes is nil
  278. bodyBytes, _ := ioutil.ReadAll(body)
  279. return cmd, nil, model.NewAppError("command", "api.command.execute_command.failed_resp.app_error", map[string]interface{}{"Trigger": cmd.Trigger, "Status": resp.Status}, string(bodyBytes), http.StatusInternalServerError)
  280. }
  281. response, err := model.CommandResponseFromHTTPBody(resp.Header.Get("Content-Type"), body)
  282. if err != nil {
  283. return cmd, nil, model.NewAppError("command", "api.command.execute_command.failed.app_error", map[string]interface{}{"Trigger": cmd.Trigger}, err.Error(), http.StatusInternalServerError)
  284. } else if response == nil {
  285. return cmd, nil, model.NewAppError("command", "api.command.execute_command.failed_empty.app_error", map[string]interface{}{"Trigger": cmd.Trigger}, "", http.StatusInternalServerError)
  286. }
  287. return cmd, response, nil
  288. }
  289. func (a *App) HandleCommandResponse(command *model.Command, args *model.CommandArgs, response *model.CommandResponse, builtIn bool) (*model.CommandResponse, *model.AppError) {
  290. trigger := ""
  291. if len(args.Command) != 0 {
  292. parts := strings.Split(args.Command, " ")
  293. trigger = parts[0][1:]
  294. trigger = strings.ToLower(trigger)
  295. }
  296. var lastError *model.AppError
  297. _, err := a.HandleCommandResponsePost(command, args, response, builtIn)
  298. if err != nil {
  299. mlog.Error("error occurred in handling command response post", mlog.Err(err))
  300. lastError = err
  301. }
  302. if response.ExtraResponses != nil {
  303. for _, resp := range response.ExtraResponses {
  304. _, err := a.HandleCommandResponsePost(command, args, resp, builtIn)
  305. if err != nil {
  306. mlog.Error("error occurred in handling command response post", mlog.Err(err))
  307. lastError = err
  308. }
  309. }
  310. }
  311. if lastError != nil {
  312. return response, model.NewAppError("command", "api.command.execute_command.create_post_failed.app_error", map[string]interface{}{"Trigger": trigger}, "", http.StatusInternalServerError)
  313. }
  314. return response, nil
  315. }
  316. func (a *App) HandleCommandResponsePost(command *model.Command, args *model.CommandArgs, response *model.CommandResponse, builtIn bool) (*model.Post, *model.AppError) {
  317. post := &model.Post{}
  318. post.ChannelId = args.ChannelId
  319. post.RootId = args.RootId
  320. post.ParentId = args.ParentId
  321. post.UserId = args.UserId
  322. post.Type = response.Type
  323. post.Props = response.Props
  324. if len(response.ChannelId) != 0 {
  325. _, err := a.GetChannelMember(response.ChannelId, args.UserId)
  326. if err != nil {
  327. err = model.NewAppError("HandleCommandResponsePost", "api.command.command_post.forbidden.app_error", nil, err.Error(), http.StatusForbidden)
  328. return nil, err
  329. }
  330. post.ChannelId = response.ChannelId
  331. }
  332. isBotPost := !builtIn
  333. if *a.Config().ServiceSettings.EnablePostUsernameOverride {
  334. if len(command.Username) != 0 {
  335. post.AddProp("override_username", command.Username)
  336. isBotPost = true
  337. } else if len(response.Username) != 0 {
  338. post.AddProp("override_username", response.Username)
  339. isBotPost = true
  340. }
  341. }
  342. if *a.Config().ServiceSettings.EnablePostIconOverride {
  343. if len(command.IconURL) != 0 {
  344. post.AddProp("override_icon_url", command.IconURL)
  345. isBotPost = true
  346. } else if len(response.IconURL) != 0 {
  347. post.AddProp("override_icon_url", response.IconURL)
  348. isBotPost = true
  349. } else {
  350. post.AddProp("override_icon_url", "")
  351. }
  352. }
  353. if isBotPost {
  354. post.AddProp("from_webhook", "true")
  355. }
  356. // Process Slack text replacements if the response does not contain "skip_slack_parsing": true.
  357. if !response.SkipSlackParsing {
  358. response.Text = a.ProcessSlackText(response.Text)
  359. response.Attachments = a.ProcessSlackAttachments(response.Attachments)
  360. }
  361. if _, err := a.CreateCommandPost(post, args.TeamId, response, response.SkipSlackParsing); err != nil {
  362. return post, err
  363. }
  364. return post, nil
  365. }
  366. func (a *App) CreateCommand(cmd *model.Command) (*model.Command, *model.AppError) {
  367. if !*a.Config().ServiceSettings.EnableCommands {
  368. return nil, model.NewAppError("CreateCommand", "api.command.disabled.app_error", nil, "", http.StatusNotImplemented)
  369. }
  370. cmd.Trigger = strings.ToLower(cmd.Trigger)
  371. teamCmds, err := a.Srv.Store.Command().GetByTeam(cmd.TeamId)
  372. if err != nil {
  373. return nil, err
  374. }
  375. for _, existingCommand := range teamCmds {
  376. if cmd.Trigger == existingCommand.Trigger {
  377. return nil, model.NewAppError("CreateCommand", "api.command.duplicate_trigger.app_error", nil, "", http.StatusBadRequest)
  378. }
  379. }
  380. for _, builtInProvider := range commandProviders {
  381. builtInCommand := builtInProvider.GetCommand(a, utils.T)
  382. if builtInCommand != nil && cmd.Trigger == builtInCommand.Trigger {
  383. return nil, model.NewAppError("CreateCommand", "api.command.duplicate_trigger.app_error", nil, "", http.StatusBadRequest)
  384. }
  385. }
  386. return a.Srv.Store.Command().Save(cmd)
  387. }
  388. func (a *App) GetCommand(commandId string) (*model.Command, *model.AppError) {
  389. if !*a.Config().ServiceSettings.EnableCommands {
  390. return nil, model.NewAppError("GetCommand", "api.command.disabled.app_error", nil, "", http.StatusNotImplemented)
  391. }
  392. cmd, err := a.Srv.Store.Command().Get(commandId)
  393. if err != nil {
  394. err.StatusCode = http.StatusNotFound
  395. return nil, err
  396. }
  397. return cmd, nil
  398. }
  399. func (a *App) UpdateCommand(oldCmd, updatedCmd *model.Command) (*model.Command, *model.AppError) {
  400. if !*a.Config().ServiceSettings.EnableCommands {
  401. return nil, model.NewAppError("UpdateCommand", "api.command.disabled.app_error", nil, "", http.StatusNotImplemented)
  402. }
  403. updatedCmd.Trigger = strings.ToLower(updatedCmd.Trigger)
  404. updatedCmd.Id = oldCmd.Id
  405. updatedCmd.Token = oldCmd.Token
  406. updatedCmd.CreateAt = oldCmd.CreateAt
  407. updatedCmd.UpdateAt = model.GetMillis()
  408. updatedCmd.DeleteAt = oldCmd.DeleteAt
  409. updatedCmd.CreatorId = oldCmd.CreatorId
  410. updatedCmd.TeamId = oldCmd.TeamId
  411. return a.Srv.Store.Command().Update(updatedCmd)
  412. }
  413. func (a *App) MoveCommand(team *model.Team, command *model.Command) *model.AppError {
  414. command.TeamId = team.Id
  415. _, err := a.Srv.Store.Command().Update(command)
  416. if err != nil {
  417. return err
  418. }
  419. return nil
  420. }
  421. func (a *App) RegenCommandToken(cmd *model.Command) (*model.Command, *model.AppError) {
  422. if !*a.Config().ServiceSettings.EnableCommands {
  423. return nil, model.NewAppError("RegenCommandToken", "api.command.disabled.app_error", nil, "", http.StatusNotImplemented)
  424. }
  425. cmd.Token = model.NewId()
  426. return a.Srv.Store.Command().Update(cmd)
  427. }
  428. func (a *App) DeleteCommand(commandId string) *model.AppError {
  429. if !*a.Config().ServiceSettings.EnableCommands {
  430. return model.NewAppError("DeleteCommand", "api.command.disabled.app_error", nil, "", http.StatusNotImplemented)
  431. }
  432. return a.Srv.Store.Command().Delete(commandId, model.GetMillis())
  433. }