github.com/mattermosttest/mattermost-server/v5@v5.0.0-20200917143240-9dfa12e121f9/model/command_response.go (about)

     1  // Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved.
     2  // See LICENSE.txt for license information.
     3  
     4  package model
     5  
     6  import (
     7  	"encoding/json"
     8  	"io"
     9  	"io/ioutil"
    10  	"strings"
    11  
    12  	"github.com/mattermost/mattermost-server/v5/utils/jsonutils"
    13  )
    14  
    15  const (
    16  	COMMAND_RESPONSE_TYPE_IN_CHANNEL = "in_channel"
    17  	COMMAND_RESPONSE_TYPE_EPHEMERAL  = "ephemeral"
    18  )
    19  
    20  type CommandResponse struct {
    21  	ResponseType     string             `json:"response_type"`
    22  	Text             string             `json:"text"`
    23  	Username         string             `json:"username"`
    24  	ChannelId        string             `json:"channel_id"`
    25  	IconURL          string             `json:"icon_url"`
    26  	Type             string             `json:"type"`
    27  	Props            StringInterface    `json:"props"`
    28  	GotoLocation     string             `json:"goto_location"`
    29  	TriggerId        string             `json:"trigger_id"`
    30  	SkipSlackParsing bool               `json:"skip_slack_parsing"` // Set to `true` to skip the Slack-compatibility handling of Text.
    31  	Attachments      []*SlackAttachment `json:"attachments"`
    32  	ExtraResponses   []*CommandResponse `json:"extra_responses"`
    33  }
    34  
    35  func (o *CommandResponse) ToJson() string {
    36  	b, _ := json.Marshal(o)
    37  	return string(b)
    38  }
    39  
    40  func CommandResponseFromHTTPBody(contentType string, body io.Reader) (*CommandResponse, error) {
    41  	if strings.TrimSpace(strings.Split(contentType, ";")[0]) == "application/json" {
    42  		return CommandResponseFromJson(body)
    43  	}
    44  	if b, err := ioutil.ReadAll(body); err == nil {
    45  		return CommandResponseFromPlainText(string(b)), nil
    46  	}
    47  	return nil, nil
    48  }
    49  
    50  func CommandResponseFromPlainText(text string) *CommandResponse {
    51  	return &CommandResponse{
    52  		Text: text,
    53  	}
    54  }
    55  
    56  func CommandResponseFromJson(data io.Reader) (*CommandResponse, error) {
    57  	b, err := ioutil.ReadAll(data)
    58  	if err != nil {
    59  		return nil, err
    60  	}
    61  
    62  	var o CommandResponse
    63  	err = json.Unmarshal(b, &o)
    64  	if err != nil {
    65  		return nil, jsonutils.HumanizeJsonError(err, b)
    66  	}
    67  
    68  	o.Attachments = StringifySlackFieldValue(o.Attachments)
    69  
    70  	if o.ExtraResponses != nil {
    71  		for _, resp := range o.ExtraResponses {
    72  			resp.Attachments = StringifySlackFieldValue(resp.Attachments)
    73  		}
    74  	}
    75  
    76  	return &o, nil
    77  }