| 1 |
package mattermost |
| 2 |
|
| 3 |
import ( |
| 4 |
"encoding/json" |
| 5 |
"fmt" |
| 6 |
"strings" |
| 7 |
|
| 8 |
"github.com/nicholas-fedor/shoutrrr/pkg/types" |
| 9 |
) |
| 10 |
|
| 11 |
// JSON represents the payload structure for Mattermost notifications. |
| 12 |
type JSON struct { |
| 13 |
Text string `json:"text"` |
| 14 |
UserName string `json:"username,omitempty"` |
| 15 |
Channel string `json:"channel,omitempty"` |
| 16 |
IconEmoji string `json:"icon_emoji,omitempty"` |
| 17 |
IconURL string `json:"icon_url,omitempty"` |
| 18 |
} |
| 19 |
|
| 20 |
// SetIcon sets the appropriate icon field in the payload based on whether the input is a URL or not. |
| 21 |
func (j *JSON) SetIcon(icon string) { |
| 22 |
j.IconURL = "" |
| 23 |
j.IconEmoji = "" |
| 24 |
|
| 25 |
if icon != "" { |
| 26 |
lower := strings.ToLower(icon) |
| 27 |
if strings.HasPrefix(lower, "http://") || strings.HasPrefix(lower, "https://") { |
| 28 |
j.IconURL = icon |
| 29 |
} else { |
| 30 |
j.IconEmoji = icon |
| 31 |
} |
| 32 |
} |
| 33 |
} |
| 34 |
|
| 35 |
// CreateJSONPayload generates a JSON payload for the Mattermost service. |
| 36 |
func CreateJSONPayload(config *Config, message string, params *types.Params) ([]byte, error) { |
| 37 |
// Extract title from params if provided, before building the text |
| 38 |
title := config.Title |
| 39 |
|
| 40 |
if params != nil { |
| 41 |
if value, found := (*params)["title"]; found { |
| 42 |
title = value |
| 43 |
} |
| 44 |
} |
| 45 |
|
| 46 |
// Prepend title to message when present |
| 47 |
text := message |
| 48 |
if title != "" { |
| 49 |
text = title + "\n" + message |
| 50 |
} |
| 51 |
|
| 52 |
payload := JSON{ |
| 53 |
Text: text, |
| 54 |
UserName: config.UserName, |
| 55 |
Channel: config.Channel, |
| 56 |
IconEmoji: "", |
| 57 |
IconURL: "", |
| 58 |
} |
| 59 |
|
| 60 |
icon := config.Icon |
| 61 |
|
| 62 |
if params != nil { |
| 63 |
if value, found := (*params)["username"]; found { |
| 64 |
payload.UserName = value |
| 65 |
} |
| 66 |
|
| 67 |
if value, found := (*params)["channel"]; found { |
| 68 |
payload.Channel = value |
| 69 |
} |
| 70 |
|
| 71 |
if value, found := (*params)["icon"]; found { |
| 72 |
icon = value |
| 73 |
} |
| 74 |
} |
| 75 |
|
| 76 |
payload.SetIcon(icon) |
| 77 |
|
| 78 |
payloadBytes, err := json.Marshal(payload) |
| 79 |
if err != nil { |
| 80 |
return nil, fmt.Errorf("marshaling Mattermost payload to JSON: %w", err) |
| 81 |
} |
| 82 |
|
| 83 |
return payloadBytes, nil |
| 84 |
} |