github.com/vnforks/kid@v5.11.1+incompatible/model/command_response.go (about)

     1  // Copyright (c) 2016-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/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  	Attachments    []*SlackAttachment `json:"attachments"`
    31  	ExtraResponses []*CommandResponse `json:"extra_responses"`
    32  }
    33  
    34  func (o *CommandResponse) ToJson() string {
    35  	b, _ := json.Marshal(o)
    36  	return string(b)
    37  }
    38  
    39  func CommandResponseFromHTTPBody(contentType string, body io.Reader) (*CommandResponse, error) {
    40  	if strings.TrimSpace(strings.Split(contentType, ";")[0]) == "application/json" {
    41  		return CommandResponseFromJson(body)
    42  	}
    43  	if b, err := ioutil.ReadAll(body); err == nil {
    44  		return CommandResponseFromPlainText(string(b)), nil
    45  	}
    46  	return nil, nil
    47  }
    48  
    49  func CommandResponseFromPlainText(text string) *CommandResponse {
    50  	return &CommandResponse{
    51  		Text: text,
    52  	}
    53  }
    54  
    55  func CommandResponseFromJson(data io.Reader) (*CommandResponse, error) {
    56  	b, err := ioutil.ReadAll(data)
    57  	if err != nil {
    58  		return nil, err
    59  	}
    60  
    61  	var o CommandResponse
    62  	err = json.Unmarshal(b, &o)
    63  	if err != nil {
    64  		return nil, jsonutils.HumanizeJsonError(err, b)
    65  	}
    66  
    67  	o.Attachments = StringifySlackFieldValue(o.Attachments)
    68  
    69  	if o.ExtraResponses != nil {
    70  		for _, resp := range o.ExtraResponses {
    71  			resp.Attachments = StringifySlackFieldValue(resp.Attachments)
    72  		}
    73  	}
    74  
    75  	return &o, nil
    76  }