github.com/gigforks/mattermost-server@v4.9.1-0.20180619094218-800d97fa55d0+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 = 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  		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  				method := "POST"
   234  				if cmd.Method == model.COMMAND_METHOD_GET {
   235  					method = "GET"
   236  				}
   237  
   238  				req, _ := http.NewRequest(method, cmd.URL, strings.NewReader(p.Encode()))
   239  				req.Header.Set("Accept", "application/json")
   240  				req.Header.Set("Authorization", "Token "+cmd.Token)
   241  				if cmd.Method == model.COMMAND_METHOD_POST {
   242  					req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
   243  				}
   244  
   245  				if resp, err := a.HTTPClient(false).Do(req); err != nil {
   246  					return nil, model.NewAppError("command", "api.command.execute_command.failed.app_error", map[string]interface{}{"Trigger": trigger}, err.Error(), http.StatusInternalServerError)
   247  				} else {
   248  					if resp.StatusCode == http.StatusOK {
   249  						if response, err := model.CommandResponseFromHTTPBody(resp.Header.Get("Content-Type"), resp.Body); err != nil {
   250  							return nil, model.NewAppError("command", "api.command.execute_command.failed.app_error", map[string]interface{}{"Trigger": trigger}, err.Error(), http.StatusInternalServerError)
   251  						} else if response == nil {
   252  							return nil, model.NewAppError("command", "api.command.execute_command.failed_empty.app_error", map[string]interface{}{"Trigger": trigger}, "", http.StatusInternalServerError)
   253  						} else {
   254  							return a.HandleCommandResponse(cmd, args, response, false)
   255  						}
   256  					} else {
   257  						defer resp.Body.Close()
   258  						body, _ := ioutil.ReadAll(resp.Body)
   259  						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)
   260  					}
   261  				}
   262  			}
   263  		}
   264  	}
   265  
   266  	return nil, model.NewAppError("command", "api.command.execute_command.not_found.app_error", map[string]interface{}{"Trigger": trigger}, "", http.StatusNotFound)
   267  }
   268  
   269  func (a *App) HandleCommandResponse(command *model.Command, args *model.CommandArgs, response *model.CommandResponse, builtIn bool) (*model.CommandResponse, *model.AppError) {
   270  	post := &model.Post{}
   271  	post.ChannelId = args.ChannelId
   272  	post.RootId = args.RootId
   273  	post.ParentId = args.ParentId
   274  	post.UserId = args.UserId
   275  	post.Type = response.Type
   276  	post.Props = response.Props
   277  
   278  	isBotPost := !builtIn
   279  
   280  	if a.Config().ServiceSettings.EnablePostUsernameOverride {
   281  		if len(command.Username) != 0 {
   282  			post.AddProp("override_username", command.Username)
   283  			isBotPost = true
   284  		} else if len(response.Username) != 0 {
   285  			post.AddProp("override_username", response.Username)
   286  			isBotPost = true
   287  		}
   288  	}
   289  
   290  	if a.Config().ServiceSettings.EnablePostIconOverride {
   291  		if len(command.IconURL) != 0 {
   292  			post.AddProp("override_icon_url", command.IconURL)
   293  			isBotPost = true
   294  		} else if len(response.IconURL) != 0 {
   295  			post.AddProp("override_icon_url", response.IconURL)
   296  			isBotPost = true
   297  		} else {
   298  			post.AddProp("override_icon_url", "")
   299  		}
   300  	}
   301  
   302  	if isBotPost {
   303  		post.AddProp("from_webhook", "true")
   304  	}
   305  
   306  	// Process Slack text replacements
   307  	response.Text = a.ProcessSlackText(response.Text)
   308  	response.Attachments = a.ProcessSlackAttachments(response.Attachments)
   309  
   310  	if _, err := a.CreateCommandPost(post, args.TeamId, response); err != nil {
   311  		mlog.Error(err.Error())
   312  	}
   313  
   314  	return response, nil
   315  }
   316  
   317  func (a *App) CreateCommand(cmd *model.Command) (*model.Command, *model.AppError) {
   318  	if !*a.Config().ServiceSettings.EnableCommands {
   319  		return nil, model.NewAppError("CreateCommand", "api.command.disabled.app_error", nil, "", http.StatusNotImplemented)
   320  	}
   321  
   322  	cmd.Trigger = strings.ToLower(cmd.Trigger)
   323  
   324  	if result := <-a.Srv.Store.Command().GetByTeam(cmd.TeamId); result.Err != nil {
   325  		return nil, result.Err
   326  	} else {
   327  		teamCmds := result.Data.([]*model.Command)
   328  		for _, existingCommand := range teamCmds {
   329  			if cmd.Trigger == existingCommand.Trigger {
   330  				return nil, model.NewAppError("CreateCommand", "api.command.duplicate_trigger.app_error", nil, "", http.StatusBadRequest)
   331  			}
   332  		}
   333  		for _, builtInProvider := range commandProviders {
   334  			builtInCommand := builtInProvider.GetCommand(a, utils.T)
   335  			if builtInCommand != nil && cmd.Trigger == builtInCommand.Trigger {
   336  				return nil, model.NewAppError("CreateCommand", "api.command.duplicate_trigger.app_error", nil, "", http.StatusBadRequest)
   337  			}
   338  		}
   339  	}
   340  
   341  	if result := <-a.Srv.Store.Command().Save(cmd); result.Err != nil {
   342  		return nil, result.Err
   343  	} else {
   344  		return result.Data.(*model.Command), nil
   345  	}
   346  }
   347  
   348  func (a *App) GetCommand(commandId string) (*model.Command, *model.AppError) {
   349  	if !*a.Config().ServiceSettings.EnableCommands {
   350  		return nil, model.NewAppError("GetCommand", "api.command.disabled.app_error", nil, "", http.StatusNotImplemented)
   351  	}
   352  
   353  	if result := <-a.Srv.Store.Command().Get(commandId); result.Err != nil {
   354  		result.Err.StatusCode = http.StatusNotFound
   355  		return nil, result.Err
   356  	} else {
   357  		return result.Data.(*model.Command), nil
   358  	}
   359  }
   360  
   361  func (a *App) UpdateCommand(oldCmd, updatedCmd *model.Command) (*model.Command, *model.AppError) {
   362  	if !*a.Config().ServiceSettings.EnableCommands {
   363  		return nil, model.NewAppError("UpdateCommand", "api.command.disabled.app_error", nil, "", http.StatusNotImplemented)
   364  	}
   365  
   366  	updatedCmd.Trigger = strings.ToLower(updatedCmd.Trigger)
   367  	updatedCmd.Id = oldCmd.Id
   368  	updatedCmd.Token = oldCmd.Token
   369  	updatedCmd.CreateAt = oldCmd.CreateAt
   370  	updatedCmd.UpdateAt = model.GetMillis()
   371  	updatedCmd.DeleteAt = oldCmd.DeleteAt
   372  	updatedCmd.CreatorId = oldCmd.CreatorId
   373  	updatedCmd.TeamId = oldCmd.TeamId
   374  
   375  	if result := <-a.Srv.Store.Command().Update(updatedCmd); result.Err != nil {
   376  		return nil, result.Err
   377  	} else {
   378  		return result.Data.(*model.Command), nil
   379  	}
   380  }
   381  
   382  func (a *App) MoveCommand(team *model.Team, command *model.Command) *model.AppError {
   383  	command.TeamId = team.Id
   384  
   385  	if result := <-a.Srv.Store.Command().Update(command); result.Err != nil {
   386  		return result.Err
   387  	}
   388  
   389  	return nil
   390  }
   391  
   392  func (a *App) RegenCommandToken(cmd *model.Command) (*model.Command, *model.AppError) {
   393  	if !*a.Config().ServiceSettings.EnableCommands {
   394  		return nil, model.NewAppError("RegenCommandToken", "api.command.disabled.app_error", nil, "", http.StatusNotImplemented)
   395  	}
   396  
   397  	cmd.Token = model.NewId()
   398  
   399  	if result := <-a.Srv.Store.Command().Update(cmd); result.Err != nil {
   400  		return nil, result.Err
   401  	} else {
   402  		return result.Data.(*model.Command), nil
   403  	}
   404  }
   405  
   406  func (a *App) DeleteCommand(commandId string) *model.AppError {
   407  	if !*a.Config().ServiceSettings.EnableCommands {
   408  		return model.NewAppError("DeleteCommand", "api.command.disabled.app_error", nil, "", http.StatusNotImplemented)
   409  	}
   410  
   411  	if err := (<-a.Srv.Store.Command().Delete(commandId, model.GetMillis())).Err; err != nil {
   412  		return err
   413  	}
   414  
   415  	return nil
   416  }