Skip to content

Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.

Go

fix(lark): preserve rich-text post file attachments (#9302)

ZIce1ad7fa1f94a3
diff --git a/server/internal/integrations/lark/content_flatten.go b/server/internal/integrations/lark/content_flatten.go
index 878c18894b..37cc1fdd4f 100644
--- a/server/internal/integrations/lark/content_flatten.go
+++ b/server/internal/integrations/lark/content_flatten.go
@@ -60,9 +60,8 @@ func flattenContent(msgType, rawContent string) string {
}
// larkPostContent mirrors the RECEIVE-side shape of a `post` rich-text
-// body.content. Crucially this is NOT the locale-wrapped form the SEND
-// API takes ({"zh_cn": {...}}): an inbound post body.content unmarshals
-// directly into {title, content}. content is a 2-D array — the outer
+// body.content after normalization. This is not the locale-wrapped form
+// the SEND API takes ({"zh_cn": {...}}). Content is a 2-D array — the outer
// array is the ordered list of paragraphs, each inner array the ordered
// spans of that paragraph; the newline between paragraphs is implicit in
// the array boundary, not a span.
@@ -71,11 +70,63 @@ type larkPostContent struct {
Content [][]larkPostSpan `json:"content"`
}
+// decodePostContent normalizes the receive-side variants for both text and
+// attachment discovery. Prefer legacy paragraphs when present; content_v2 may
+// be a paragraph array or a JSON-encoded paragraph array.
+func decodePostContent(raw string) (larkPostContent, error) {
+ var payload struct {
+ Title string `json:"title"`
+ Content json.RawMessage `json:"content"`
+ ContentV2 json.RawMessage `json:"content_v2"`
+ Files []larkPostSpan `json:"files"`
+ }
+ if err := json.Unmarshal([]byte(raw), &payload); err != nil {
+ return larkPostContent{}, err
+ }
+ doc := larkPostContent{Title: payload.Title}
+ for _, content := range []json.RawMessage{payload.Content, payload.ContentV2} {
+ var encoded string
+ if json.Unmarshal(content, &encoded) == nil {
+ content = json.RawMessage(encoded)
+ }
+ var paragraphs [][]larkPostSpan
+ if json.Unmarshal(content, &paragraphs) == nil && len(paragraphs) > 0 {
+ doc.Content = paragraphs
+ break
+ }
+ }
+ seen := make(map[string]*larkPostSpan)
+ for _, para := range doc.Content {
+ for i := range para {
+ span := &para[i]
+ if (span.Tag == "file" || span.Tag == "media") && !span.IsFolder && seen[span.FileKey] == nil {
+ seen[span.FileKey] = span
+ }
+ }
+ }
+ for _, file := range payload.Files {
+ if file.IsFolder || file.FileKey == "" {
+ continue
+ }
+ if span := seen[file.FileKey]; span != nil {
+ span.FileName = firstNonEmpty(span.FileName, span.Name, file.FileName, file.Name)
+ span.MimeType = firstNonEmpty(span.MimeType, file.MimeType)
+ continue
+ }
+ file.Tag = "file"
+ para := []larkPostSpan{file}
+ doc.Content = append(doc.Content, para)
+ seen[file.FileKey] = &para[0]
+ }
+ return doc, nil
+}
+
// larkPostSpan is one node inside a post paragraph. Only the fields that
// carry renderable text are modelled; the tag set is extensible, so the
// flattener emits `text` for any unrecognized tag and skips it otherwise
// rather than failing.
type larkPostSpan struct {
+ IsFolder bool `json:"is_folder"`
Tag string `json:"tag"`
Text string `json:"text"`
Href string `json:"href"`
@@ -104,8 +155,8 @@ func flattenPostContent(raw string) string {
if raw == "" {
return ""
}
- var doc larkPostContent
- if err := json.Unmarshal([]byte(raw), &doc); err != nil {
+ doc, err := decodePostContent(raw)
+ if err != nil {
return ""
}
@@ -155,6 +206,15 @@ func flattenPostParagraph(spans []larkPostSpan) string {
}
case "img":
parts = append(parts, "[Image]")
+ case "file":
+ if s.IsFolder || s.FileKey == "" {
+ continue
+ }
+ if name := firstNonEmpty(s.FileName, s.Name); name != "" {
+ parts = append(parts, "[File: "+name+"]")
+ } else {
+ parts = append(parts, "[File]")
+ }
case "media":
parts = append(parts, "[Video]")
case "emotion":
diff --git a/server/internal/integrations/lark/media_ingest.go b/server/internal/integrations/lark/media_ingest.go
index 318bc9f547..d489f63829 100644
--- a/server/internal/integrations/lark/media_ingest.go
+++ b/server/internal/integrations/lark/media_ingest.go
@@ -306,8 +306,8 @@ func mediaResourcesFromPost(lm InboundMessage) []larkMediaResource {
if lm.Content == "" {
return nil
}
- var doc larkPostContent
- if err := json.Unmarshal([]byte(lm.Content), &doc); err != nil {
+ doc, err := decodePostContent(lm.Content)
+ if err != nil {
return nil
}
var out []larkMediaResource
@@ -334,14 +334,18 @@ func mediaResourcesFromPost(lm InboundMessage) []larkMediaResource {
mimeType: span.MimeType,
messageID: lm.MessageID,
})
- case "media":
- if span.FileKey == "" || seen["file\x00"+span.FileKey] {
+ case "media", "file":
+ if span.IsFolder || span.FileKey == "" || seen["file\x00"+span.FileKey] {
continue
}
seen["file\x00"+span.FileKey] = true
+ kind := channel.MsgTypeVideo
+ if span.Tag == "file" {
+ kind = channel.MsgTypeFile
+ }
out = append(out, larkMediaResource{
key: span.FileKey,
- kind: channel.MsgTypeVideo,
+ kind: kind,
fetchType: "file",
filename: firstNonEmpty(span.FileName, span.Name),
mimeType: span.MimeType,
diff --git a/server/internal/integrations/lark/post_files_test.go b/server/internal/integrations/lark/post_files_test.go
new file mode 100644
index 0000000000..bb94040989
--- /dev/null
+++ b/server/internal/integrations/lark/post_files_test.go
@@ -0,0 +1,95 @@
+package lark
+
+import (
+ "context"
+ "errors"
+ "testing"
+
+ "github.com/multica-ai/multica/server/internal/integrations/channel"
+ "github.com/multica-ai/multica/server/internal/integrations/channel/engine"
+)
+
+const postDOCX = `{"title":"Review","content":[[{"tag":"text","text":"Please read"}]],"files":[{"file_key":"file_docx","file_name":"demo.docx","is_folder":false}]}`
+
+func TestPostFilesCompatibility(t *testing.T) {
+ for _, tc := range []struct {
+ name, raw, text string
+ resources int
+ }{
+ {"top-level DOCX", postDOCX, "Review\nPlease read\n[File: demo.docx]", 1},
+ {"files only", `{"files":[{"file_key":"f"}]}`, "[File]", 1},
+ {"folders and missing keys", `{"files":[{"file_key":"folder","is_folder":true},{"file_name":"missing.docx"}]}`, "", 0},
+ {"repeated files", `{"files":[{"file_key":"f","name":"demo.docx"},{"file_key":"f","name":"demo.docx"}]}`, "[File: demo.docx]", 1},
+ {"span and file", `{"content":[[{"tag":"file","file_key":"f","file_name":"demo.docx"}]],"files":[{"file_key":"f","file_name":"demo.docx"}]}`, "[File: demo.docx]", 1},
+ {"file metadata fills span", `{"content":[[{"tag":"file","file_key":"f"}]],"files":[{"file_key":"f","file_name":"demo.docx"}]}`, "[File: demo.docx]", 1},
+ {"video span and file", `{"content":[[{"tag":"media","file_key":"f"}]],"files":[{"file_key":"f"}]}`, "[Video]", 1},
+ {"legacy wins", `{"content":[[{"tag":"text","text":"legacy"}]],"content_v2":[[{"tag":"text","text":"new"}]]}`, "legacy", 0},
+ {"v2 array", `{"content":[],"content_v2":[[{"tag":"text","text":"new"},{"tag":"file","file_key":"f"}]]}`, "new [File]", 1},
+ {"null legacy fallback", `{"content":null,"content_v2":[[{"tag":"text","text":"new"}]],"files":[{"file_key":"f"}]}`, "new\n[File]", 1},
+ {"image and file namespaces", `{"content":[[{"tag":"img","image_key":"same"}]],"files":[{"file_key":"same"}]}`, "[Image]\n[File]", 2},
+ {"v2 encoded", `{"content_v2":"[[{\"tag\":\"text\",\"text\":\"new\"},{\"tag\":\"img\",\"image_key\":\"i\"}]]"}`, "new [Image]", 1},
+ {"invalid legacy fallback", `{"content":{},"content_v2":[[{"tag":"text","text":"new"}]]}`, "new", 0},
+ {"invalid v2 preserves files", `{"content_v2":"invalid","files":[{"file_key":"f"}]}`, "[File]", 1},
+ {"malformed JSON", `{`, "", 0},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ if got := flattenPostContent(tc.raw); got != tc.text {
+ t.Fatalf("text = %q, want %q", got, tc.text)
+ }
+ lm := InboundMessage{MessageID: "om_post", MessageType: "post", Content: tc.raw}
+ if got := mediaResourcesFromMessage(lm); len(got) != tc.resources {
+ t.Fatalf("resources = %+v, want %d", got, tc.resources)
+ }
+ resolver := NewFeishuMediaResolver(nil, nil, nil, nil, nil)
+ if got := resolver.HasMedia(channelMessageFromLark(lm)); got != (tc.resources > 0) {
+ t.Fatalf("HasMedia = %v", got)
+ }
+ })
+ }
+}
+
+func TestPostDOCXResolution(t *testing.T) {
+ for _, fail := range []bool{false, true} {
+ name := "success"
+ if fail {
+ name = "download failure"
+ }
+ t.Run(name, func(t *testing.T) {
+ sender := &fakeSender{downloaded: DownloadedResource{Data: []byte("synthetic document"), ContentType: "application/vnd.openxmlformats-officedocument.wordprocessingml.document", SizeBytes: 18}}
+ if fail {
+ sender.downloadErr = errors.New("unavailable")
+ }
+ storage := &fakeMediaStorage{}
+ resolver := NewFeishuMediaResolver(sender, fakeCreds{secret: "plain"}, storage, &fakeMediaLedger{}, newDiscardLogger())
+ lm := InboundMessage{MessageID: "om_docx", MessageType: "post", Content: postDOCX, Body: flattenPostContent(postDOCX)}
+ got := resolver.ResolveMedia(context.Background(), testMediaInstallation(t), engine.ResolvedIdentity{},
+ uuidFromString(t, "22222222-2222-2222-2222-222222222222"), uuidFromString(t, "33333333-3333-4333-8333-333333333333"), channelMessageFromLark(lm))
+ if len(sender.downloadCalls) != 1 {
+ t.Fatalf("downloads = %d", len(sender.downloadCalls))
+ }
+ call := sender.downloadCalls[0]
+ if call.MessageID != "om_docx" || call.FileKey != "file_docx" || call.Type != "file" {
+ t.Fatalf("download params = %+v", call)
+ }
+ if got.Text != "Review\nPlease read\n[File: demo.docx]" {
+ t.Fatalf("text = %q", got.Text)
+ }
+ if fail {
+ if len(got.MediaRefs) != 0 || len(storage.uploads) != 0 {
+ t.Fatalf("failed download created attachments: %+v", got)
+ }
+ return
+ }
+ if len(got.MediaRefs) != 1 || len(storage.uploads) != 1 {
+ t.Fatalf("refs = %+v, uploads = %d", got.MediaRefs, len(storage.uploads))
+ }
+ if string(storage.uploads[0].data) != "synthetic document" {
+ t.Fatalf("uploaded bytes = %q", storage.uploads[0].data)
+ }
+ ref := got.MediaRefs[0]
+ if ref.Filename != "demo.docx" || ref.Type != channel.MsgTypeFile || ref.MimeType != sender.downloaded.ContentType {
+ t.Fatalf("ref = %+v", ref)
+ }
+ })
+ }
+}