github.com/lologarithm/mattermost-server@v5.3.2-0.20181002060438-c82a84ed765b+incompatible/app/command.go (about)

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