Add im channel Mattermost

This commit is contained in:
Austin Xia
2026-03-27 11:07:09 +08:00
committed by lyingbug
parent 72dfb9ce75
commit 463f40fadc
14 changed files with 874 additions and 26 deletions
+56
View File
@@ -56,6 +56,7 @@ import (
imPkg "github.com/Tencent/WeKnora/internal/im"
"github.com/Tencent/WeKnora/internal/im/dingtalk"
"github.com/Tencent/WeKnora/internal/im/feishu"
"github.com/Tencent/WeKnora/internal/im/mattermost"
"github.com/Tencent/WeKnora/internal/im/slack"
"github.com/Tencent/WeKnora/internal/im/telegram"
"github.com/Tencent/WeKnora/internal/im/wecom"
@@ -1171,6 +1172,40 @@ func registerIMAdapterFactories(imService *imPkg.Service) {
}
})
// Register Mattermost adapter factory (outgoing webhook + REST API).
imService.RegisterAdapterFactory("mattermost", func(factoryCtx context.Context, channel *imPkg.IMChannel, msgHandler func(context.Context, *imPkg.IncomingMessage) error) (imPkg.Adapter, context.CancelFunc, error) {
creds, err := parseCredentials(channel.Credentials)
if err != nil {
return nil, nil, fmt.Errorf("parse mattermost credentials: %w", err)
}
mode := channel.Mode
if mode == "" {
mode = "webhook"
}
if mode != "webhook" {
return nil, nil, fmt.Errorf("unsupported mattermost mode: %s (only webhook is supported)", mode)
}
siteURL := getString(creds, "site_url")
botToken := getString(creds, "bot_token")
outgoingToken := getString(creds, "outgoing_token")
botUserID := getString(creds, "bot_user_id")
if outgoingToken == "" {
return nil, nil, fmt.Errorf("mattermost outgoing_token is required")
}
client, err := mattermost.NewClient(siteURL, botToken)
if err != nil {
return nil, nil, err
}
postReplyToMain := credentialBool(creds, "post_to_main")
adapter := mattermost.NewAdapter(client, outgoingToken, botUserID, postReplyToMain)
return adapter, func() {}, nil
})
// Load and start all enabled channels from database
if err := imService.LoadAndStartChannels(); err != nil {
logger.Warnf(ctx, "[IM] Failed to load channels from database: %v", err)
@@ -1198,3 +1233,24 @@ func getString(creds map[string]interface{}, key string) string {
}
return ""
}
// credentialBool reads a boolean from JSON credentials (bool, string "true"/"1", or non-zero number).
func credentialBool(creds map[string]interface{}, key string) bool {
v, ok := creds[key]
if !ok {
return false
}
switch x := v.(type) {
case bool:
return x
case string:
s := strings.TrimSpace(strings.ToLower(x))
return s == "true" || s == "1" || s == "yes"
case float64:
return x != 0
case int:
return x != 0
default:
return false
}
}
+16 -3
View File
@@ -12,7 +12,9 @@ import (
)
// validIMPlatforms is the set of supported IM platforms.
var validIMPlatforms = map[string]bool{"wecom": true, "feishu": true, "slack": true, "telegram": true, "dingtalk": true}
var validIMPlatforms = map[string]bool{
"wecom": true, "feishu": true, "slack": true, "telegram": true, "dingtalk": true, "mattermost": true,
}
// IMHandler handles IM platform callback requests and channel CRUD.
type IMHandler struct {
@@ -57,7 +59,7 @@ func (h *IMHandler) CreateIMChannel(c *gin.Context) {
}
if !validIMPlatforms[req.Platform] {
c.JSON(http.StatusBadRequest, gin.H{"error": "platform must be 'wecom', 'feishu', 'slack', 'telegram' or 'dingtalk'"})
c.JSON(http.StatusBadRequest, gin.H{"error": "platform must be 'wecom', 'feishu', 'slack', 'telegram', 'dingtalk' or 'mattermost'"})
return
}
@@ -76,7 +78,11 @@ func (h *IMHandler) CreateIMChannel(c *gin.Context) {
channel.Enabled = *req.Enabled
}
if channel.Mode == "" {
channel.Mode = "websocket"
if channel.Platform == "mattermost" {
channel.Mode = "webhook"
} else {
channel.Mode = "websocket"
}
}
if channel.OutputMode == "" {
channel.OutputMode = "stream"
@@ -265,6 +271,8 @@ func (h *IMHandler) IMCallback(c *gin.Context) {
return
}
logger.Infof(ctx, "[IM] Callback received platform=%s path_channel_id=%s", channel.Platform, channelID)
// Handle URL verification
if adapter.HandleURLVerification(c) {
return
@@ -287,6 +295,11 @@ func (h *IMHandler) IMCallback(c *gin.Context) {
// If nil, it's a non-message event - just acknowledge
if msg == nil {
if channel.Platform == "mattermost" {
logger.Infof(ctx, "[IM] Mattermost callback ignored (no message): path_channel_id=%s — check: (1) trigger word must be the *first word* of the post; (2) if channel+trigger are both set, post must be in that channel; (3) bot_user_id must not match the sender", channelID)
} else {
logger.Infof(ctx, "[IM] Callback parsed no message to process platform=%s path_channel_id=%s", channel.Platform, channelID)
}
c.JSON(http.StatusOK, gin.H{"success": true})
return
}
+6 -5
View File
@@ -11,11 +11,12 @@ import (
type Platform string
const (
PlatformWeCom Platform = "wecom"
PlatformFeishu Platform = "feishu"
PlatformSlack Platform = "slack"
PlatformTelegram Platform = "telegram"
PlatformDingtalk Platform = "dingtalk"
PlatformWeCom Platform = "wecom"
PlatformFeishu Platform = "feishu"
PlatformSlack Platform = "slack"
PlatformTelegram Platform = "telegram"
PlatformDingtalk Platform = "dingtalk"
PlatformMattermost Platform = "mattermost"
)
// MessageType identifies the kind of IM message.
+341
View File
@@ -0,0 +1,341 @@
package mattermost
import (
"bytes"
"context"
"encoding/json"
"fmt"
"io"
"strings"
"sync"
"github.com/gin-gonic/gin"
"github.com/Tencent/WeKnora/internal/im"
"github.com/Tencent/WeKnora/internal/logger"
)
// Compile-time checks.
var (
_ im.Adapter = (*Adapter)(nil)
_ im.StreamSender = (*Adapter)(nil)
_ im.FileDownloader = (*Adapter)(nil)
)
const (
extraKeyThreadRoot = "thread_root_id"
extraKeyChannelID = "channel_id"
)
// Adapter implements im integration for Mattermost (outgoing webhook inbound + REST outbound).
type Adapter struct {
client *Client
outgoingToken string
botUserID string
// postReplyToMain: when true, bot replies are new top-level channel posts (visible in main timeline).
// When false (default), replies use root_id tied to the trigger post so they appear in Mattermost threads.
postReplyToMain bool
}
// NewAdapter creates a Mattermost adapter.
func NewAdapter(client *Client, outgoingToken, botUserID string, postReplyToMain bool) *Adapter {
return &Adapter{
client: client,
outgoingToken: strings.TrimSpace(outgoingToken),
botUserID: strings.TrimSpace(botUserID),
postReplyToMain: postReplyToMain,
}
}
// outgoingPayload matches Mattermost outgoing webhook parameters (JSON or form).
type outgoingPayload struct {
Token string `json:"token"`
UserID string `json:"user_id"`
UserName string `json:"user_name"`
ChannelID string `json:"channel_id"`
PostID string `json:"post_id"`
Text string `json:"text"`
RootID string `json:"root_id"`
FileIDsRaw json.RawMessage `json:"file_ids"`
}
func (a *Adapter) Platform() im.Platform {
return im.PlatformMattermost
}
func (a *Adapter) HandleURLVerification(c *gin.Context) bool {
return false
}
func (a *Adapter) VerifyCallback(c *gin.Context) error {
bodyBytes, err := io.ReadAll(c.Request.Body)
if err != nil {
return fmt.Errorf("read body: %w", err)
}
c.Request.Body = io.NopCloser(bytes.NewReader(bodyBytes))
payload, err := parseOutgoingBody(c.Request.Header.Get("Content-Type"), bodyBytes)
if err != nil {
return fmt.Errorf("parse outgoing payload: %w", err)
}
if a.outgoingToken != "" && payload.Token != a.outgoingToken {
return fmt.Errorf("invalid outgoing webhook token")
}
return nil
}
func (a *Adapter) ParseCallback(c *gin.Context) (*im.IncomingMessage, error) {
bodyBytes, err := io.ReadAll(c.Request.Body)
if err != nil {
return nil, fmt.Errorf("read body: %w", err)
}
c.Request.Body = io.NopCloser(bytes.NewReader(bodyBytes))
payload, err := parseOutgoingBody(c.Request.Header.Get("Content-Type"), bodyBytes)
if err != nil {
return nil, err
}
if a.botUserID != "" && payload.UserID == a.botUserID {
logger.Infof(c.Request.Context(), "[Mattermost] Skip callback: user_id matches bot_user_id (avoid self-reply loop)")
return nil, nil
}
if strings.TrimSpace(payload.Text) == "" && len(parseFileIDs(payload.FileIDsRaw)) == 0 {
logger.Infof(c.Request.Context(), "[Mattermost] Skip callback: empty text and no file_ids")
return nil, nil
}
var threadRoot string
if a.postReplyToMain {
threadRoot = ""
} else {
threadRoot = payload.RootID
if threadRoot == "" {
threadRoot = payload.PostID
}
}
msg := &im.IncomingMessage{
Platform: im.PlatformMattermost,
UserID: payload.UserID,
UserName: payload.UserName,
ChatID: payload.ChannelID,
ChatType: im.ChatTypeGroup,
Content: strings.TrimSpace(payload.Text),
MessageID: payload.PostID,
Extra: map[string]string{
extraKeyThreadRoot: threadRoot,
extraKeyChannelID: payload.ChannelID,
},
}
fileIDs := parseFileIDs(payload.FileIDsRaw)
if len(fileIDs) > 0 {
msg.MessageType = im.MessageTypeFile
msg.FileKey = fileIDs[0]
if len(fileIDs) > 1 {
msg.Extra["file_ids"] = strings.Join(fileIDs, ",")
}
} else {
msg.MessageType = im.MessageTypeText
}
return msg, nil
}
func parseOutgoingBody(contentType string, body []byte) (*outgoingPayload, error) {
ct := strings.ToLower(strings.TrimSpace(strings.Split(contentType, ";")[0]))
switch {
case ct == "application/json" || strings.HasSuffix(ct, "+json"):
var p outgoingPayload
if err := json.Unmarshal(body, &p); err != nil {
return nil, err
}
return &p, nil
case ct == "application/x-www-form-urlencoded" || ct == "":
// Parse as form (Mattermost default for some configs).
values, err := parseFormBody(body)
if err != nil {
return nil, err
}
p := &outgoingPayload{
Token: values.Get("token"),
UserID: values.Get("user_id"),
UserName: values.Get("user_name"),
ChannelID: values.Get("channel_id"),
PostID: values.Get("post_id"),
Text: values.Get("text"),
RootID: values.Get("root_id"),
}
if f := values.Get("file_ids"); f != "" {
p.FileIDsRaw = json.RawMessage(jsonArrayFromCSV(f))
}
return p, nil
default:
// Try JSON fallback for unknown types.
var p outgoingPayload
if err := json.Unmarshal(body, &p); err == nil && (p.Token != "" || p.ChannelID != "") {
return &p, nil
}
return nil, fmt.Errorf("unsupported content-type: %s", contentType)
}
}
func parseFileIDs(raw json.RawMessage) []string {
if len(raw) == 0 {
return nil
}
var arr []string
if err := json.Unmarshal(raw, &arr); err == nil {
return arr
}
var s string
if err := json.Unmarshal(raw, &s); err == nil && s != "" {
return splitFileIDs(s)
}
return nil
}
func splitFileIDs(s string) []string {
parts := strings.Split(s, ",")
out := make([]string, 0, len(parts))
for _, p := range parts {
p = strings.TrimSpace(p)
if p != "" {
out = append(out, p)
}
}
return out
}
func (a *Adapter) SendReply(ctx context.Context, incoming *im.IncomingMessage, reply *im.ReplyMessage) error {
channelID := incoming.ChatID
if channelID == "" {
channelID = incoming.Extra[extraKeyChannelID]
}
if channelID == "" {
return fmt.Errorf("missing channel_id")
}
threadRoot := ""
if incoming.Extra != nil {
threadRoot = incoming.Extra[extraKeyThreadRoot]
}
_, err := a.client.CreatePost(ctx, channelID, threadRoot, reply.Content)
return err
}
type mmStreamState struct {
mu sync.Mutex
content strings.Builder
postID string
channel string
}
var (
mmStreamsMu sync.Mutex
mmStreams = map[string]*mmStreamState{}
)
func (a *Adapter) StartStream(ctx context.Context, incoming *im.IncomingMessage) (string, error) {
channelID := incoming.ChatID
if channelID == "" {
channelID = incoming.Extra[extraKeyChannelID]
}
threadRoot := ""
if incoming.Extra != nil {
threadRoot = incoming.Extra[extraKeyThreadRoot]
}
postID, err := a.client.CreatePost(ctx, channelID, threadRoot, "正在思考...")
if err != nil {
return "", err
}
streamID := channelID + ":" + postID
mmStreamsMu.Lock()
mmStreams[streamID] = &mmStreamState{postID: postID, channel: channelID}
mmStreamsMu.Unlock()
logger.Infof(ctx, "[Mattermost] Streaming started: stream_id=%s", streamID)
return streamID, nil
}
func (a *Adapter) SendStreamChunk(ctx context.Context, incoming *im.IncomingMessage, streamID string, content string) error {
if content == "" {
return nil
}
mmStreamsMu.Lock()
state, ok := mmStreams[streamID]
mmStreamsMu.Unlock()
if !ok {
return fmt.Errorf("unknown stream ID: %s", streamID)
}
state.mu.Lock()
state.content.WriteString(content)
full := state.content.String()
postID := state.postID
state.mu.Unlock()
if err := a.client.PatchPostMessage(ctx, postID, full); err != nil {
logger.Warnf(ctx, "[Mattermost] Patch post failed: %v", err)
}
return nil
}
func (a *Adapter) EndStream(ctx context.Context, incoming *im.IncomingMessage, streamID string) error {
mmStreamsMu.Lock()
state, ok := mmStreams[streamID]
delete(mmStreams, streamID)
mmStreamsMu.Unlock()
if !ok {
return nil
}
state.mu.Lock()
full := state.content.String()
postID := state.postID
state.mu.Unlock()
if err := a.client.PatchPostMessage(ctx, postID, full); err != nil {
logger.Warnf(ctx, "[Mattermost] EndStream patch failed: %v", err)
}
logger.Infof(ctx, "[Mattermost] Streaming ended: post_id=%s", postID)
return nil
}
func (a *Adapter) DownloadFile(ctx context.Context, msg *im.IncomingMessage) (io.ReadCloser, string, error) {
if msg.FileKey == "" {
return nil, "", fmt.Errorf("file_key is required")
}
info, err := a.client.GetFileInfo(ctx, msg.FileKey)
if err != nil {
return nil, "", fmt.Errorf("file info: %w", err)
}
name := info.Name
if name == "" {
name = msg.FileName
}
if name == "" {
name = msg.FileKey
}
rc, err := a.client.GetFileReader(ctx, msg.FileKey)
if err != nil {
return nil, "", err
}
return rc, name, nil
}
+182
View File
@@ -0,0 +1,182 @@
package mattermost
import (
"bytes"
"context"
"encoding/json"
"fmt"
"io"
"net/http"
"strings"
"time"
)
// Client calls Mattermost REST API v4.
type Client struct {
baseURL string
httpClient *http.Client
token string
}
// NewClient builds an API client. siteURL is the Mattermost server root (e.g. https://mm.example.com).
func NewClient(siteURL, botToken string) (*Client, error) {
siteURL = strings.TrimSpace(siteURL)
siteURL = strings.TrimRight(siteURL, "/")
if siteURL == "" {
return nil, fmt.Errorf("site_url is required")
}
if strings.TrimSpace(botToken) == "" {
return nil, fmt.Errorf("bot_token is required")
}
return &Client{
baseURL: siteURL + "/api/v4",
httpClient: &http.Client{
Timeout: 60 * time.Second,
},
token: strings.TrimSpace(botToken),
}, nil
}
func (c *Client) authHeader(req *http.Request) {
req.Header.Set("Authorization", "Bearer "+c.token)
req.Header.Set("Content-Type", "application/json")
}
// CreatePost creates a channel post. rootID is the thread root post id (empty for new top-level post).
func (c *Client) CreatePost(ctx context.Context, channelID, rootID, message string) (postID string, err error) {
body := map[string]string{
"channel_id": channelID,
"message": message,
}
if rootID != "" {
body["root_id"] = rootID
}
payload, err := json.Marshal(body)
if err != nil {
return "", err
}
req, err := http.NewRequestWithContext(ctx, http.MethodPost, c.baseURL+"/posts", bytes.NewReader(payload))
if err != nil {
return "", err
}
c.authHeader(req)
resp, err := c.httpClient.Do(req)
if err != nil {
return "", err
}
defer resp.Body.Close()
respBody, _ := io.ReadAll(resp.Body)
if resp.StatusCode < 200 || resp.StatusCode >= 300 {
if resp.StatusCode == http.StatusForbidden {
return "", fmt.Errorf("mattermost create post: 403 forbidden — add the bot user to this Mattermost channel (Channel menu → Members → Add); body=%s", truncateForErr(respBody))
}
return "", fmt.Errorf("mattermost create post: status=%d body=%s", resp.StatusCode, truncateForErr(respBody))
}
var created struct {
ID string `json:"id"`
}
if err := json.Unmarshal(respBody, &created); err != nil {
return "", fmt.Errorf("decode create post: %w", err)
}
if created.ID == "" {
return "", fmt.Errorf("mattermost create post: empty id")
}
return created.ID, nil
}
// PatchPostMessage updates a post's message field.
func (c *Client) PatchPostMessage(ctx context.Context, postID, message string) error {
payload, err := json.Marshal(map[string]string{"message": message})
if err != nil {
return err
}
url := fmt.Sprintf("%s/posts/%s/patch", c.baseURL, postID)
req, err := http.NewRequestWithContext(ctx, http.MethodPut, url, bytes.NewReader(payload))
if err != nil {
return err
}
c.authHeader(req)
resp, err := c.httpClient.Do(req)
if err != nil {
return err
}
defer resp.Body.Close()
respBody, _ := io.ReadAll(resp.Body)
if resp.StatusCode < 200 || resp.StatusCode >= 300 {
return fmt.Errorf("mattermost patch post: status=%d body=%s", resp.StatusCode, truncateForErr(respBody))
}
return nil
}
// FileInfo holds metadata from GET /files/{id}/info.
type FileInfo struct {
ID string `json:"id"`
Name string `json:"name"`
Size int64 `json:"size"`
}
// GetFileInfo fetches file metadata.
func (c *Client) GetFileInfo(ctx context.Context, fileID string) (*FileInfo, error) {
url := fmt.Sprintf("%s/files/%s/info", c.baseURL, fileID)
req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil)
if err != nil {
return nil, err
}
c.authHeader(req)
req.Header.Del("Content-Type")
resp, err := c.httpClient.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
respBody, _ := io.ReadAll(resp.Body)
if resp.StatusCode < 200 || resp.StatusCode >= 300 {
return nil, fmt.Errorf("mattermost file info: status=%d body=%s", resp.StatusCode, truncateForErr(respBody))
}
var info FileInfo
if err := json.Unmarshal(respBody, &info); err != nil {
return nil, fmt.Errorf("decode file info: %w", err)
}
return &info, nil
}
// GetFileReader opens a download stream for file content.
func (c *Client) GetFileReader(ctx context.Context, fileID string) (io.ReadCloser, error) {
url := fmt.Sprintf("%s/files/%s", c.baseURL, fileID)
req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil)
if err != nil {
return nil, err
}
c.authHeader(req)
req.Header.Del("Content-Type")
resp, err := c.httpClient.Do(req)
if err != nil {
return nil, err
}
if resp.StatusCode < 200 || resp.StatusCode >= 300 {
body, _ := io.ReadAll(resp.Body)
resp.Body.Close()
return nil, fmt.Errorf("mattermost get file: status=%d body=%s", resp.StatusCode, truncateForErr(body))
}
return resp.Body, nil
}
func truncateForErr(b []byte) string {
const max = 512
s := string(b)
if len(s) > max {
return s[:max] + "..."
}
return s
}
+27
View File
@@ -0,0 +1,27 @@
package mattermost
import (
"encoding/json"
"fmt"
"net/url"
)
func parseFormBody(body []byte) (url.Values, error) {
values, err := url.ParseQuery(string(body))
if err != nil {
return nil, fmt.Errorf("parse form: %w", err)
}
return values, nil
}
func jsonArrayFromCSV(csv string) []byte {
parts := splitFileIDs(csv)
if len(parts) == 0 {
return []byte("[]")
}
b, err := json.Marshal(parts)
if err != nil {
return []byte("[]")
}
return b
}
+9 -1
View File
@@ -39,7 +39,11 @@ func (ch *IMChannel) BeforeCreate(tx *gorm.DB) error {
ch.ID = uuid.New().String()
}
if ch.Mode == "" {
ch.Mode = "websocket"
if ch.Platform == "mattermost" {
ch.Mode = "webhook"
} else {
ch.Mode = "websocket"
}
}
if ch.OutputMode == "" {
ch.OutputMode = "stream"
@@ -104,6 +108,10 @@ func (ch *IMChannel) computeBotIdentity() string {
if clientID := str("client_id"); clientID != "" {
return "dingtalk:" + clientID
}
case "mattermost":
if tok := str("outgoing_token"); tok != "" {
return "mattermost:wh:" + tok
}
}
return ""
}