WeKnora deployment source with the reviewed wiki identity, summary and recovery fixes
Anydoc / anydoc parser engine (push) Canceled after 0s
App / Format, vet, test, and build (push) Canceled after 0s
CLI / test (macos-latest / go 1.26) (push) Canceled after 0s
CLI / test (ubuntu-latest / go 1.26) (push) Canceled after 0s
CLI / test (windows-latest / go 1.26) (push) Canceled after 0s
Build and Push Docker Image / build-ui (push) Canceled after 0s
Build and Push Docker Image / build-docreader (push) Canceled after 0s
Build and Push Docker Image / build-sandbox (push) Canceled after 0s
Build and Push Docker Image / build-app (amd64, linux/amd64, ubuntu-latest) (push) Canceled after 0s
Build and Push Docker Image / build-app (arm64, linux/arm64, ubuntu-24.04-arm) (push) Canceled after 0s
DocReader / Python tests and Go client tests (push) Canceled after 0s
Build & Publish (dsh-weknora) / Typecheck, test, pack (push) Canceled after 0s
Build & Publish (dsh-weknora) / End-to-end inside dsh (pinned) (push) Canceled after 0s
Build & Publish (dsh-weknora) / End-to-end inside dsh (latest, advisory) (push) Canceled after 0s
Frontend / Test, type-check, and build (push) Canceled after 0s
Go Lint Cache / warm lint cache (.) (push) Canceled after 0s
Go Lint Cache / warm lint cache (cli) (push) Canceled after 0s
Go Lint Cache / warm lint cache (client) (push) Canceled after 0s
Build & Publish (mcp-server) / Test (Python 3.10) (push) Canceled after 0s
Build & Publish (mcp-server) / Test (Python 3.11) (push) Canceled after 0s
Build & Publish (mcp-server) / Test (Python 3.12) (push) Canceled after 0s
Build & Publish (mcp-server) / Test (Python 3.13) (push) Canceled after 0s
Build and Push Docker Image / merge (push) Canceled after 0s
Build & Publish (dsh-weknora) / Publish to npm (push) Canceled after 0s
Build & Publish (mcp-server) / Build sdist + wheel (push) Canceled after 0s
Build & Publish (mcp-server) / Publish to PyPI (push) Canceled after 0s

This commit is contained in:
yawan
2026-09-22 16:19:06 +08:00
commit f7fc992f57
3929 changed files with 1006607 additions and 0 deletions
+357
View File
@@ -0,0 +1,357 @@
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 == "" {
// Outgoing webhooks may omit root_id for thread replies.
// Fetch the post to resolve the actual thread root.
if actualRootID, err := a.client.GetPost(c.Request.Context(), payload.PostID); err == nil && actualRootID != "" {
threadRoot = actualRootID
} else {
// Top-level message: use its own PostID as thread root.
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,
ThreadID: threadRoot,
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) UpdateStreamContent(ctx context.Context, incoming *im.IncomingMessage, streamID string, fullContent string) error {
if fullContent == "" {
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.Reset()
state.content.WriteString(fullContent)
postID := state.postID
state.mu.Unlock()
if err := a.client.PatchPostMessage(ctx, postID, fullContent); err != nil {
logger.Warnf(ctx, "[Mattermost] Patch post failed: %v", err)
}
return nil
}
func (a *Adapter) FinalizeStream(ctx context.Context, incoming *im.IncomingMessage, streamID string, finalContent string) error {
return a.UpdateStreamContent(ctx, incoming, streamID, finalContent)
}
func (a *Adapter) SendStreamChunk(ctx context.Context, incoming *im.IncomingMessage, streamID string, content string) error {
return a.UpdateStreamContent(ctx, incoming, streamID, content)
}
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
}
+195
View File
@@ -0,0 +1,195 @@
package mattermost
import (
"context"
"encoding/json"
stderrors "errors"
"net/http"
"net/http/httptest"
"testing"
secutils "github.com/Tencent/WeKnora/internal/utils"
)
func withMattermostSSRFWhitelist(t *testing.T, whitelist string) {
t.Helper()
t.Setenv("SSRF_WHITELIST", whitelist)
secutils.ResetSSRFWhitelistForTest()
t.Cleanup(secutils.ResetSSRFWhitelistForTest)
}
func TestParseOutgoingBody_ThreadRoot(t *testing.T) {
tests := []struct {
name string
payload outgoingPayload
postReplyToMain bool
wantThreadRoot string
}{
{
name: "threaded reply has RootID",
payload: outgoingPayload{
PostID: "post-123",
RootID: "root-456",
},
postReplyToMain: false,
wantThreadRoot: "root-456",
},
{
name: "top-level message uses PostID as thread root",
payload: outgoingPayload{
PostID: "post-789",
RootID: "",
},
postReplyToMain: false,
wantThreadRoot: "post-789",
},
{
name: "postReplyToMain clears thread root",
payload: outgoingPayload{
PostID: "post-123",
RootID: "root-456",
},
postReplyToMain: true,
wantThreadRoot: "",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
var threadRoot string
if tt.postReplyToMain {
threadRoot = ""
} else {
threadRoot = tt.payload.RootID
if threadRoot == "" {
threadRoot = tt.payload.PostID
}
}
if threadRoot != tt.wantThreadRoot {
t.Errorf("threadRoot = %q, want %q", threadRoot, tt.wantThreadRoot)
}
})
}
}
func TestNewClientRejectsPrivateSiteURL(t *testing.T) {
withMattermostSSRFWhitelist(t, "")
if _, err := NewClient("http://127.0.0.1:8065", "bot-token"); err == nil {
t.Fatal("expected private Mattermost site_url to be rejected")
}
}
func TestMattermostClientBlocksRedirectToInternalURL(t *testing.T) {
withMattermostSSRFWhitelist(t, "127.0.0.1")
origin := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
http.Redirect(w, r, "http://169.254.169.254/latest/meta-data/", http.StatusFound)
}))
defer origin.Close()
client, err := NewClient(origin.URL, "bot-token")
if err != nil {
t.Fatalf("NewClient: %v", err)
}
_, err = client.CreatePost(context.Background(), "channel", "", "hello")
if err == nil {
t.Fatal("expected redirect to link-local metadata endpoint to be blocked")
}
if !stderrors.Is(err, secutils.ErrSSRFRedirectBlocked) {
t.Fatalf("error = %v, want ErrSSRFRedirectBlocked", err)
}
}
func TestParseOutgoingBody_JSON(t *testing.T) {
body := `{"token":"tok","user_id":"u1","user_name":"alice","channel_id":"ch1","post_id":"p1","text":"hello","root_id":"r1"}`
payload, err := parseOutgoingBody("application/json", []byte(body))
if err != nil {
t.Fatalf("parseOutgoingBody error: %v", err)
}
if payload.RootID != "r1" {
t.Errorf("RootID = %q, want %q", payload.RootID, "r1")
}
if payload.PostID != "p1" {
t.Errorf("PostID = %q, want %q", payload.PostID, "p1")
}
}
func TestParseOutgoingBody_FormEncoded(t *testing.T) {
body := "token=tok&user_id=u1&channel_id=ch1&post_id=p2&text=hello&root_id=r2"
payload, err := parseOutgoingBody("application/x-www-form-urlencoded", []byte(body))
if err != nil {
t.Fatalf("parseOutgoingBody error: %v", err)
}
if payload.RootID != "r2" {
t.Errorf("RootID = %q, want %q", payload.RootID, "r2")
}
if payload.PostID != "p2" {
t.Errorf("PostID = %q, want %q", payload.PostID, "p2")
}
}
func TestThreadIDInMessage(t *testing.T) {
// Simulate the adapter logic: build the message and verify ThreadID
payload := outgoingPayload{
Token: "tok",
UserID: "user-1",
UserName: "alice",
ChannelID: "ch-1",
PostID: "post-100",
Text: "hello",
RootID: "root-200",
}
threadRoot := payload.RootID
if threadRoot == "" {
threadRoot = payload.PostID
}
// Verify the Extra map and ThreadID would be consistent
extra := map[string]string{
extraKeyThreadRoot: threadRoot,
extraKeyChannelID: payload.ChannelID,
}
if extra[extraKeyThreadRoot] != "root-200" {
t.Errorf("Extra thread_root_id = %q, want %q", extra[extraKeyThreadRoot], "root-200")
}
// ThreadID should equal threadRoot
threadID := threadRoot
if threadID != "root-200" {
t.Errorf("ThreadID = %q, want %q", threadID, "root-200")
}
}
func TestParseFileIDs(t *testing.T) {
tests := []struct {
name string
raw json.RawMessage
want []string
}{
{"array", json.RawMessage(`["f1","f2"]`), []string{"f1", "f2"}},
{"string", json.RawMessage(`"f3"`), []string{"f3"}},
{"empty", nil, nil},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got := parseFileIDs(tt.raw)
if len(got) != len(tt.want) {
t.Fatalf("parseFileIDs() len = %d, want %d", len(got), len(tt.want))
}
for i := range got {
if got[i] != tt.want[i] {
t.Errorf("parseFileIDs()[%d] = %q, want %q", i, got[i], tt.want[i])
}
}
})
}
}
+245
View File
@@ -0,0 +1,245 @@
package mattermost
import (
"bytes"
"context"
"encoding/json"
"fmt"
"io"
"net/http"
"net/url"
"strings"
"time"
secutils "github.com/Tencent/WeKnora/internal/utils"
)
// 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")
}
parsed, err := url.Parse(siteURL)
if err != nil || parsed.Host == "" {
return nil, fmt.Errorf("invalid site_url: must be a valid http(s) URL")
}
if parsed.Scheme != "http" && parsed.Scheme != "https" {
return nil, fmt.Errorf("invalid site_url: must use http or https")
}
if err := secutils.ValidateURLForSSRF(siteURL); err != nil {
return nil, fmt.Errorf(
"invalid site_url: %w (for private Mattermost deployments, add the hostname to SSRF_WHITELIST)",
err,
)
}
if strings.TrimSpace(botToken) == "" {
return nil, fmt.Errorf("bot_token is required")
}
return &Client{
baseURL: siteURL + "/api/v4",
httpClient: secutils.NewSSRFSafeHTTPClient(secutils.SSRFSafeHTTPClientConfig{
Timeout: 60 * time.Second,
MaxRedirects: 5,
}),
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, err := io.ReadAll(resp.Body)
if err != nil {
return "", fmt.Errorf("read mattermost create post response: %w", err)
}
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
}
// GetPost fetches a post by ID, returning its root_id (empty if top-level).
func (c *Client) GetPost(ctx context.Context, postID string) (rootID string, err error) {
url := fmt.Sprintf("%s/posts/%s", c.baseURL, postID)
req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil)
if err != nil {
return "", err
}
c.authHeader(req)
req.Header.Del("Content-Type")
resp, err := c.httpClient.Do(req)
if err != nil {
return "", err
}
defer resp.Body.Close()
respBody, err := io.ReadAll(resp.Body)
if err != nil {
return "", fmt.Errorf("read mattermost get post response: %w", err)
}
if resp.StatusCode < 200 || resp.StatusCode >= 300 {
return "", fmt.Errorf("mattermost get post: status=%d body=%s", resp.StatusCode, truncateForErr(respBody))
}
var post struct {
ID string `json:"id"`
RootID string `json:"root_id"`
}
if err := json.Unmarshal(respBody, &post); err != nil {
return "", fmt.Errorf("decode get post: %w", err)
}
return post.RootID, 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, err := io.ReadAll(resp.Body)
if err != nil {
return fmt.Errorf("read mattermost patch post response: %w", err)
}
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, err := io.ReadAll(resp.Body)
if err != nil {
return nil, fmt.Errorf("read mattermost file info response: %w", err)
}
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, readErr := io.ReadAll(resp.Body)
resp.Body.Close()
if readErr != nil {
return nil, fmt.Errorf("read mattermost get file error response (status=%d): %w", resp.StatusCode, readErr)
}
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
}
+43
View File
@@ -0,0 +1,43 @@
package mattermost
import (
"context"
"fmt"
"github.com/Tencent/WeKnora/internal/im"
)
// NewFactory returns an im.AdapterFactory for Mattermost channels.
// Only "webhook" mode is supported (outgoing webhook + REST API);
// the default mode is "webhook" (not "websocket" like other platforms).
func NewFactory() im.AdapterFactory {
return func(factoryCtx context.Context, channel *im.IMChannel, msgHandler func(context.Context, *im.IncomingMessage) error) (im.Adapter, context.CancelFunc, error) {
creds, err := im.ParseCredentials(channel.Credentials)
if err != nil {
return nil, nil, fmt.Errorf("parse mattermost credentials: %w", err)
}
mode := im.ResolveMode(channel, "webhook")
if mode != "webhook" {
return nil, nil, fmt.Errorf("unsupported mattermost mode: %s (only webhook is supported)", mode)
}
siteURL := im.GetString(creds, "site_url")
botToken := im.GetString(creds, "bot_token")
outgoingToken := im.GetString(creds, "outgoing_token")
botUserID := im.GetString(creds, "bot_user_id")
if outgoingToken == "" {
return nil, nil, fmt.Errorf("mattermost outgoing_token is required")
}
client, err := NewClient(siteURL, botToken)
if err != nil {
return nil, nil, err
}
postReplyToMain := im.GetBool(creds, "post_to_main")
adapter := NewAdapter(client, outgoingToken, botUserID, postReplyToMain)
return adapter, func() {}, nil
}
}
+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
}