Skip to content

Open-source LLM knowledge platform: turn raw documents into a queryable RAG, an autonomous reasoning agent, and a self-maintaining Wiki.

feat(datasource/ima): sync IMA notes via the note OpenAPI

wizardchen8d5540e26d6d
diff --git a/frontend/src/i18n/locales/en-US.ts b/frontend/src/i18n/locales/en-US.ts
index 205b34909..277faacfb 100755
--- a/frontend/src/i18n/locales/en-US.ts
+++ b/frontend/src/i18n/locales/en-US.ts
@@ -5486,7 +5486,7 @@ export default {
lark_drive: 'Sync documents, spreadsheets and files from a Lark Drive folder (Feishu international)',
notion: 'Sync pages and databases from Notion',
yuque: 'Sync documents from Yuque knowledge bases',
- ima: 'Sync documents and files from Tencent IMA knowledge bases (notes and AI sessions are not supported yet)',
+ ima: 'Sync documents, notes and files from Tencent IMA knowledge bases (AI sessions and video parses are not supported)',
rss: 'Sync articles from RSS / Atom feeds'
},
drive: {
diff --git a/frontend/src/i18n/locales/ko-KR.ts b/frontend/src/i18n/locales/ko-KR.ts
index 32116e899..4534f5484 100755
--- a/frontend/src/i18n/locales/ko-KR.ts
+++ b/frontend/src/i18n/locales/ko-KR.ts
@@ -704,7 +704,7 @@ export default {
lark_drive: "Lark 드라이브 폴더에서 문서, 스프레드시트, 파일 동기화",
notion: 'Notion에서 페이지 및 데이터베이스 동기화',
yuque: '위큐 지식베이스에서 문서 동기화',
- ima: 'Tencent IMA 지식베이스에서 문서 및 파일 동기화 (노트와 AI 세션은 아직 지원되지 않음)',
+ ima: 'Tencent IMA 지식베이스에서 문서, 노트 및 파일 동기화 (AI 세션과 동영상 분석은 지원되지 않음)',
rss: 'RSS / Atom 피드에서 글 동기화'
},
connector: {
diff --git a/frontend/src/i18n/locales/ru-RU.ts b/frontend/src/i18n/locales/ru-RU.ts
index 7ac69061f..de45910e4 100755
--- a/frontend/src/i18n/locales/ru-RU.ts
+++ b/frontend/src/i18n/locales/ru-RU.ts
@@ -704,7 +704,7 @@ export default {
lark_drive: 'Синхронизация документов, таблиц и файлов из папки Lark Drive',
notion: 'Синхронизация страниц и баз данных из Notion',
yuque: 'Синхронизация документов из баз знаний Yuque',
- ima: 'Синхронизация документов и файлов из баз знаний Tencent IMA (заметки и ИИ-сессии пока не поддерживаются)',
+ ima: 'Синхронизация документов, заметок и файлов из баз знаний Tencent IMA (ИИ-сессии и разбор видео не поддерживаются)',
rss: 'Синхронизация статей из лент RSS / Atom'
},
connector: {
diff --git a/frontend/src/i18n/locales/zh-CN.ts b/frontend/src/i18n/locales/zh-CN.ts
index 363c0d5fb..bcfae62f7 100755
--- a/frontend/src/i18n/locales/zh-CN.ts
+++ b/frontend/src/i18n/locales/zh-CN.ts
@@ -704,7 +704,7 @@ export default {
lark_drive: "同步 Lark 云盘文件夹中的文档、表格、文件(飞书国际版)",
notion: '同步 Notion 中的页面和数据库',
yuque: '同步语雀知识库中的文档',
- ima: '同步腾讯 IMA 知识库中的文档与文件(暂不支持笔记与 AI 会话)',
+ ima: '同步腾讯 IMA 知识库中的文档、笔记与文件(暂不支持 AI 会话与视频解析)',
rss: '同步 RSS / Atom 订阅源中的文章'
},
connector: {
diff --git a/internal/datasource/connector/ima/client.go b/internal/datasource/connector/ima/client.go
index aef65cda5..743dadf04 100644
--- a/internal/datasource/connector/ima/client.go
+++ b/internal/datasource/connector/ima/client.go
@@ -57,10 +57,20 @@ func newClient(cfg *Config) *client {
}
// callAPI executes an authenticated POST to /openapi/wiki/v1/<action>.
-// It parses the standard {code, msg, data} envelope and unmarshals `data`
-// into `result`. A non-zero business code is returned as a plain error so the
-// caller can surface `msg` to the user
func (c *client) callAPI(ctx context.Context, action string, req interface{}, result interface{}) error {
+ return c.callAPIAt(ctx, apiBasePath, action, req, result)
+}
+
+// callAPIAt executes an authenticated POST to <basePath>/<action>. It parses
+// the standard {code, msg, data} envelope and unmarshals `data` into `result`.
+// A non-zero business code is returned as a plain error so the caller can
+// surface `msg` to the user.
+//
+// basePath is a parameter because notes live under a second namespace
+// (/openapi/note/v1) that shares this authentication and envelope.
+func (c *client) callAPIAt(
+ ctx context.Context, basePath, action string, req interface{}, result interface{},
+) error {
const (
maxRetries = 3
max5xxRetries = 1
@@ -84,7 +94,10 @@ func (c *client) callAPI(ctx context.Context, action string, req interface{}, re
body = []byte("{}")
}
- url := c.baseURL + apiBasePath + "/" + action
+ url := c.baseURL + basePath + "/" + action
+ // Both namespaces expose distinct actions, but log the full path so the two
+ // are never ambiguous.
+ label := basePath + "/" + action
var lastErr error
for attempt := 0; attempt <= maxRetries; attempt++ {
@@ -98,9 +111,9 @@ func (c *client) callAPI(ctx context.Context, action string, req interface{}, re
httpReq.Header.Set("User-Agent", userAgent)
if attempt == 0 {
- logger.Infof(ctx, "[IMA] POST %s", action)
+ logger.Infof(ctx, "[IMA] POST %s", label)
} else {
- logger.Infof(ctx, "[IMA] POST %s (retry %d/%d)", action, attempt, maxRetries)
+ logger.Infof(ctx, "[IMA] POST %s (retry %d/%d)", label, attempt, maxRetries)
}
resp, err := c.httpClient.Do(httpReq)
@@ -132,7 +145,7 @@ func (c *client) callAPI(ctx context.Context, action string, req interface{}, re
// (get_media_info in particular) carry pre-signed storage URLs and
// per-request auth headers that must not land in the server log.
bodyPreview := truncate(string(respBody), 500)
- logger.Infof(ctx, "[IMA] POST %s → status=%d bodyLen=%d", action, resp.StatusCode, len(respBody))
+ logger.Infof(ctx, "[IMA] POST %s → status=%d bodyLen=%d", label, resp.StatusCode, len(respBody))
// HTTP-level auth failures: surface as ErrInvalidCredentials.
if resp.StatusCode == http.StatusUnauthorized || resp.StatusCode == http.StatusForbidden {
@@ -178,19 +191,19 @@ func (c *client) callAPI(ctx context.Context, action string, req interface{}, re
// 110021 (限频) is retried. Everything else — including 110001 (参数非法),
// which is a bug on our side rather than a credential problem — surfaces
// verbatim so the user sees IMA's own message.
- if env.Code != 0 {
- if env.Code == 110030 {
+ if code := env.statusCode(); code != 0 {
+ if code == 110030 {
return fmt.Errorf("%w: ima code=%d msg=%s",
- datasource.ErrInvalidCredentials, env.Code, env.Msg)
+ datasource.ErrInvalidCredentials, code, env.message())
}
- if env.Code == 110021 && attempt < maxRetries {
- lastErr = fmt.Errorf("ima rate limited: code=%d msg=%s", env.Code, env.Msg)
+ if code == 110021 && attempt < maxRetries {
+ lastErr = fmt.Errorf("ima rate limited: code=%d msg=%s", code, env.message())
if sErr := sleepCtx(ctx, backoff[minInt(attempt, len(backoff)-1)]); sErr != nil {
return sErr
}
continue
}
- return fmt.Errorf("ima api error: code=%d msg=%s", env.Code, env.Msg)
+ return fmt.Errorf("ima api error: code=%d msg=%s", code, env.message())
}
if result != nil && len(env.Data) > 0 && string(env.Data) != "null" {
@@ -295,6 +308,23 @@ func (c *client) GetMediaInfo(ctx context.Context, mediaID string) (*getMediaInf
return &resp, nil
}
+// GetNoteContent — POST /openapi/note/v1/get_doc_content. Returns an IMA note's
+// body as plain text (target_content_format=0).
+//
+// noteID is the notebook_id that get_media_info reports for a note: the wiki
+// namespace never exposes note bodies, it only points at them.
+func (c *client) GetNoteContent(ctx context.Context, noteID string) (string, error) {
+ req := map[string]interface{}{
+ "note_id": noteID,
+ "target_content_format": 0,
+ }
+ var resp getDocContentResp
+ if err := c.callAPIAt(ctx, noteBasePath, "get_doc_content", req, &resp); err != nil {
+ return "", err
+ }
+ return resp.Content, nil
+}
+
// DownloadURL fetches a URL returned by GetMediaInfo, respecting the auth
// headers IMA may return alongside it. Enforces maxDownloadBytes to avoid a
// runaway body blowing up sync memory.
diff --git a/internal/datasource/connector/ima/connector.go b/internal/datasource/connector/ima/connector.go
index dd579544e..89c305a19 100644
--- a/internal/datasource/connector/ima/connector.go
+++ b/internal/datasource/connector/ima/connector.go
@@ -407,6 +407,53 @@ func listAllKBFiles(
return out, folderPath, nil
}
+// fetchNote resolves an IMA note (media_type=11). Notes carry no downloadable
+// body: get_media_info only reports the notebook_id, and the text has to be
+// read from the separate note namespace.
+//
+// The body arrives as plain text but is ingested as Markdown, because IMA notes
+// are authored as rich text and the export keeps its heading and list markers —
+// parsing it as Markdown preserves that structure for chunking, and text with
+// no markers is unaffected.
+func fetchNote(
+ ctx context.Context, cli *client,
+ kbID string, externalID string, f walkedFile, folderPath map[string]string,
+ info *getMediaInfoResp,
+) (types.FetchedItem, fetchOutcome) {
+ noteID := info.NotebookExtInfo.NotebookID
+ if noteID == "" {
+ logger.Warnf(ctx, "[IMA] note %s (title=%q) has no notebook_id, skipping", f.MediaID, f.Title)
+ return types.FetchedItem{}, fetchSkipped
+ }
+
+ content, err := cli.GetNoteContent(ctx, noteID)
+ if err != nil {
+ logger.Warnf(ctx, "[IMA] get_doc_content(note %s, title=%q) failed, will retry next sync: %v",
+ noteID, f.Title, err)
+ return types.FetchedItem{}, fetchFailed
+ }
+ if strings.TrimSpace(content) == "" {
+ logger.Infof(ctx, "[IMA] note %s (title=%q) is empty, skipping", noteID, f.Title)
+ return types.FetchedItem{}, fetchSkipped
+ }
+
+ fileName := sanitizeFileName(f.Title)
+ if !strings.HasSuffix(strings.ToLower(fileName), ".md") {
+ fileName += ".md"
+ }
+
+ return types.FetchedItem{
+ ExternalID: externalID,
+ Title: f.Title,
+ Content: []byte(content),
+ ContentType: "text/markdown",
+ FileName: fileName,
+ SourceResourceID: kbID,
+ UpdatedAt: time.Now(),
+ Metadata: baseMetadata(externalID, f, folderPath, info, kbID),
+ }, fetchOK
+}
+
// fetchOutcome distinguishes the three ways fetchOneMedia can end, because the
// caller has to treat them differently when building the sync cursor: only a
// transient failure must stay out of the cursor so it is retried next run.
@@ -439,8 +486,12 @@ func fetchOneMedia(
return types.FetchedItem{}, fetchFailed
}
+ if info.MediaType == mediaTypeNote {
+ return fetchNote(ctx, cli, kbID, externalID, f, folderPath, info)
+ }
+
if isSkippableMediaType(info.MediaType) {
- logger.Infof(ctx, "[IMA] skip media %s (title=%q media_type=%d): unsupported by wiki OpenAPI",
+ logger.Infof(ctx, "[IMA] skip media %s (title=%q media_type=%d): unsupported by the IMA OpenAPI",
f.MediaID, f.Title, info.MediaType)
return types.FetchedItem{}, fetchSkipped
}
diff --git a/internal/datasource/connector/ima/connector_test.go b/internal/datasource/connector/ima/connector_test.go
index e724a77da..d1a447e78 100644
--- a/internal/datasource/connector/ima/connector_test.go
+++ b/internal/datasource/connector/ima/connector_test.go
@@ -203,6 +203,113 @@ func TestFetchIncremental_UnsupportedTypeIsProbedOnce(t *testing.T) {
}
}
+// TestFetchAll_NoteBodyIsReadFromNoteNamespace covers IMA notes. They expose no
+// url_info at all: get_media_info only reports a notebook_id, and the body has
+// to be read from /openapi/note/v1/get_doc_content.
+func TestFetchAll_NoteBodyIsReadFromNoteNamespace(t *testing.T) {
+ f := newFakeIMA(t)
+ f.setKB("kb1", []fakeFile{{
+ MediaID: "note_1",
+ Title: "Meeting notes",
+ MediaType: mediaTypeNote,
+ NotebookID: "987654321",
+ NoteBody: "# Standup\n- shipped the connector",
+ }})
+
+ items, err := NewConnector().FetchAll(context.Background(), f.config("kb1"), []string{"kb1"})
+ if err != nil {
+ t.Fatalf("FetchAll: %v", err)
+ }
+
+ note := mustFindItem(t, items, logicalKey("kb1", "", "Meeting notes"))
+ if string(note.Content) != "# Standup\n- shipped the connector" {
+ t.Errorf("content = %q, want the note body", note.Content)
+ }
+ if !strings.HasSuffix(note.FileName, ".md") {
+ t.Errorf("FileName = %q, want an .md suffix", note.FileName)
+ }
+ if note.ContentType != "text/markdown" {
+ t.Errorf("ContentType = %q, want text/markdown", note.ContentType)
+ }
+ if note.Metadata["notebook_id"] != "987654321" {
+ t.Errorf("metadata notebook_id = %q, want 987654321", note.Metadata["notebook_id"])
+ }
+ if f.callCount("get_doc_content:987654321") != 1 {
+ t.Errorf("get_doc_content calls = %d, want 1", f.callCount("get_doc_content:987654321"))
+ }
+}
+
+// TestFetchIncremental_NoteReadFailureIsRetried checks that a note whose body
+// could not be read follows the same retry path as a failed download rather
+// than being remembered as synced.
+func TestFetchIncremental_NoteReadFailureIsRetried(t *testing.T) {
+ f := newFakeIMA(t)
+ note := fakeFile{
+ MediaID: "note_1", Title: "Broken", MediaType: mediaTypeNote,
+ NotebookID: "111", NoteBody: "recovered", NoteFails: true,
+ }
+ f.setKB("kb1", []fakeFile{note})
+
+ c := NewConnector()
+ cfg := f.config("kb1")
+ key := logicalKey("kb1", "", "Broken")
+
+ items, cursor, err := c.FetchIncremental(context.Background(), cfg, nil)
+ if err != nil {
+ t.Fatalf("first FetchIncremental: %v", err)
+ }
+ if len(items) != 0 {
+ t.Fatalf("a note that could not be read must not be emitted, got %s", describeItems(items))
+ }
+ if _, recorded := decodeCursor(t, cursor).KBLogical["kb1"][key]; recorded {
+ t.Fatal("a failed note read must not be recorded in the cursor")
+ }
+
+ note.NoteFails = false
+ f.setKB("kb1", []fakeFile{note})
+ items2, _, err := c.FetchIncremental(context.Background(), cfg, cursor)
+ if err != nil {
+ t.Fatalf("second FetchIncremental: %v", err)
+ }
+ if got := mustFindItem(t, items2, key); string(got.Content) != "recovered" {
+ t.Errorf("content = %q, want recovered", got.Content)
+ }
+}
+
+func TestFetchAll_EmptyNoteIsSkipped(t *testing.T) {
+ f := newFakeIMA(t)
+ f.setKB("kb1", []fakeFile{{
+ MediaID: "note_1", Title: "Blank", MediaType: mediaTypeNote,
+ NotebookID: "222", NoteBody: " \n ",
+ }})
+
+ items, err := NewConnector().FetchAll(context.Background(), f.config("kb1"), []string{"kb1"})
+ if err != nil {
+ t.Fatalf("FetchAll: %v", err)
+ }
+ if len(items) != 0 {
+ t.Fatalf("an empty note must be skipped, got %s", describeItems(items))
+ }
+}
+
+// TestFetchAll_AISessionIsStillSkipped pins the types IMA genuinely cannot
+// export, so widening note support does not quietly widen these too.
+func TestFetchAll_AISessionIsStillSkipped(t *testing.T) {
+ f := newFakeIMA(t)
+ f.setKB("kb1", []fakeFile{
+ {MediaID: "m-ai", Title: "Chat", MediaType: mediaTypeAISession},
+ {MediaID: "m-video", Title: "Clip", MediaType: mediaTypeVideo},
+ })
+
+ items, err := NewConnector().FetchAll(context.Background(), f.config("kb1"), []string{"kb1"})
+ if err != nil {
+ t.Fatalf("FetchAll: %v", err)
+ }
+ if len(items) != 0 {
+ t.Fatalf("AI sessions and video parses must be skipped, got %s", describeItems(items))
+ }
+}
+
// TestFetchAll_AuthenticatedURLIsDownloaded covers media types with no fixed
// extension. When IMA attaches auth headers the URL is IMA-hosted and WeKnora's
// own fetch could not authenticate, so the connector must download it here and
diff --git a/internal/datasource/connector/ima/fake_ima_test.go b/internal/datasource/connector/ima/fake_ima_test.go
index 5183c0c33..f0026c62e 100644
--- a/internal/datasource/connector/ima/fake_ima_test.go
+++ b/internal/datasource/connector/ima/fake_ima_test.go
@@ -43,6 +43,13 @@ type fakeFile struct {
InfoFails bool
// DownloadFails makes the download URL return a 500.
DownloadFails bool
+
+ // NotebookID is reported under notebook_ext_info for notes.
+ NotebookID string
+ // NoteBody is what get_doc_content serves for NotebookID.
+ NoteBody string
+ // NoteFails makes get_doc_content return a business error.
+ NoteFails bool
}
// fakeFolder is a folder entry in a fake knowledge base listing.
@@ -83,6 +90,7 @@ func newFakeIMA(t *testing.T) *fakeIMA {
}
mux := http.NewServeMux()
mux.HandleFunc(apiBasePath+"/", f.handleAPI)
+ mux.HandleFunc(noteBasePath+"/", f.handleNoteAPI)
mux.HandleFunc("/dl/", f.handleDownload)
f.server = httptest.NewServer(mux)
t.Cleanup(f.server.Close)
@@ -218,7 +226,9 @@ func (f *fakeIMA) handleAPI(w http.ResponseWriter, r *http.Request) {
return
}
resp := getMediaInfoResp{MediaType: file.MediaType}
- if !file.NoURL {
+ resp.NotebookExtInfo = notebookExtInfo{NotebookID: file.NotebookID}
+ // Notes carry no url_info; the body lives in the note namespace.
+ if !file.NoURL && file.MediaType != mediaTypeNote {
resp.URLInfo = urlInfo{
URL: f.server.URL + "/dl/" + mediaID,
Headers: file.URLHeaders,
@@ -231,6 +241,42 @@ func (f *fakeIMA) handleAPI(w http.ResponseWriter, r *http.Request) {
}
}
+// handleNoteAPI serves the /openapi/note/v1 namespace.
+func (f *fakeIMA) handleNoteAPI(w http.ResponseWriter, r *http.Request) {
+ action := strings.TrimPrefix(r.URL.Path, noteBasePath+"/")
+ f.record("note/" + action)
+
+ var req map[string]interface{}
+ _ = json.NewDecoder(r.Body).Decode(&req)
+
+ if action != "get_doc_content" {
+ writeEnvelope(w, 110012, "unsupported note action "+action, nil)
+ return
+ }
+
+ noteID, _ := req["note_id"].(string)
+ f.record("get_doc_content:" + noteID)
+
+ f.mu.Lock()
+ defer f.mu.Unlock()
+ for _, byParent := range f.files {
+ for _, files := range byParent {
+ for _, file := range files {
+ if file.NotebookID != noteID || noteID == "" {
+ continue
+ }
+ if file.NoteFails {
+ writeEnvelope(w, 110011, "note read failed", nil)
+ return
+ }
+ writeEnvelope(w, 0, "", getDocContentResp{Content: file.NoteBody})
+ return
+ }
+ }
+ }
+ writeEnvelope(w, 110001, "unknown note", nil)
+}
+
func (f *fakeIMA) handleDownload(w http.ResponseWriter, r *http.Request) {
mediaID := strings.TrimPrefix(r.URL.Path, "/dl/")
f.record("download:" + mediaID)
diff --git a/internal/datasource/connector/ima/types.go b/internal/datasource/connector/ima/types.go
index 7c3f32984..48569f2e3 100644
--- a/internal/datasource/connector/ima/types.go
+++ b/internal/datasource/connector/ima/types.go
@@ -16,9 +16,14 @@ import (
// the client (see client.go); users only configure the host.
const DefaultBaseURL = "https://ima.qq.com"
-// Base path for every OpenAPI request.
+// Base path for knowledge-base OpenAPI requests.
const apiBasePath = "/openapi/wiki/v1"
+// Base path for the note OpenAPI. Notes live in their own namespace: the wiki
+// endpoints only ever hand back a notebook_id for them, and the body has to be
+// read from here.
+const noteBasePath = "/openapi/note/v1"
+
// Config holds IMA-specific configuration decoded from
// DataSourceConfig.Credentials. Both credentials are opaque strings and
// stored encrypted at rest by DataSourceConfig.ToJSON (see internal/types/datasource.go).
@@ -74,13 +79,40 @@ func parseIMAConfig(config *types.DataSourceConfig) (*Config, error) {
}
// apiEnvelope is the uniform IMA response wrapper: `{ code, msg, data }`.
-// A non-zero code is a business-level error and MUST be surfaced to the user
+// A non-zero code is a business-level error and MUST be surfaced to the user.
+//
+// Some published IMA references spell the same envelope `{ retcode, errmsg }`.
+// Accepting both costs nothing and avoids the failure mode where a mismatch
+// leaves Code at its zero value and every API error is silently read as
+// success.
type apiEnvelope struct {
- Code int `json:"code"`
- Msg string `json:"msg"`
+ Code int `json:"code"`
+ Msg string `json:"msg"`
+ RetErr *int `json:"retcode"`
+ ErrMsg string `json:"errmsg"`
+
Data json.RawMessage `json:"data"`
}
+// statusCode returns the business status code under either spelling.
+func (e apiEnvelope) statusCode() int {
+ if e.Code != 0 {
+ return e.Code
+ }
+ if e.RetErr != nil {
+ return *e.RetErr
+ }
+ return 0
+}
+
+// message returns the human-readable error under either spelling.
+func (e apiEnvelope) message() string {
+ if e.Msg != "" {
+ return e.Msg
+ }
+ return e.ErrMsg
+}
+
// KnowledgeBaseInfo mirrors IMA's KnowledgeBaseInfo (get_knowledge_base).
type knowledgeBaseInfo struct {
ID string `json:"id"`
@@ -200,6 +232,12 @@ type getMediaInfoResp struct {
NotebookExtInfo notebookExtInfo `json:"notebook_ext_info"`
}
+// getDocContentResp — note/v1 get_doc_content response. Content is the note
+// body; with target_content_format=0 it is plain text.
+type getDocContentResp struct {
+ Content string `json:"content"`
+}
+
// imaCursor tracks per-knowledge-base state seen during the last sync.
//
// KBLogical: { logical_key: media_id } — the authoritative source for both
@@ -385,6 +423,11 @@ func mimeForExtension(ext string) string {
}
}
+// isSkippableMediaType reports whether IMA offers no way to read this type's
+// content. AI sessions are only ever referenced by session_id with no read
+// endpoint, and video parses cannot even be added outside the IMA desktop app.
+// Notes are NOT listed here: they are read through the note namespace, see
+// fetchNote.
func isSkippableMediaType(t int32) bool {
- return t == mediaTypeNote || t == mediaTypeAISession || t == mediaTypeVideo
+ return t == mediaTypeAISession || t == mediaTypeVideo
}
diff --git a/internal/datasource/connector/ima/types_test.go b/internal/datasource/connector/ima/types_test.go
index d325b275a..d7859c04c 100644
--- a/internal/datasource/connector/ima/types_test.go
+++ b/internal/datasource/connector/ima/types_test.go
@@ -1,6 +1,7 @@
package ima
import (
+ "encoding/json"
"errors"
"strings"
"testing"
@@ -150,14 +151,46 @@ func TestSanitizeFileName(t *testing.T) {
}
func TestIsSkippableMediaType(t *testing.T) {
- for _, mt := range []int32{mediaTypeNote, mediaTypeAISession, mediaTypeVideo} {
+ for _, mt := range []int32{mediaTypeAISession, mediaTypeVideo} {
if !isSkippableMediaType(mt) {
t.Errorf("media type %d should be skippable", mt)
}
}
- for _, mt := range []int32{mediaTypePDF, mediaTypeMarkdown, mediaTypeWeb} {
+ // Notes are read through the note namespace rather than skipped.
+ for _, mt := range []int32{mediaTypePDF, mediaTypeMarkdown, mediaTypeWeb, mediaTypeNote} {
if isSkippableMediaType(mt) {
t.Errorf("media type %d should not be skippable", mt)
}
}
}
+
+// TestAPIEnvelope_AcceptsBothSpellings covers the retcode/errmsg variant some
+// IMA references describe: if only `code` were read, a non-zero retcode would
+// decode as 0 and every API error would be silently treated as success.
+func TestAPIEnvelope_AcceptsBothSpellings(t *testing.T) {
+ tests := []struct {
+ name string
+ body string
+ wantCode int
+ wantMsg string
+ }{
+ {"code/msg", `{"code":110030,"msg":"无权限"}`, 110030, "无权限"},
+ {"retcode/errmsg", `{"retcode":110030,"errmsg":"无权限"}`, 110030, "无权限"},
+ {"success", `{"code":0,"msg":"ok"}`, 0, "ok"},
+ {"retcode success", `{"retcode":0,"errmsg":"成功"}`, 0, "成功"},
+ }
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ var env apiEnvelope
+ if err := json.Unmarshal([]byte(tt.body), &env); err != nil {
+ t.Fatalf("unmarshal: %v", err)
+ }
+ if got := env.statusCode(); got != tt.wantCode {
+ t.Errorf("statusCode() = %d, want %d", got, tt.wantCode)
+ }
+ if got := env.message(); got != tt.wantMsg {
+ t.Errorf("message() = %q, want %q", got, tt.wantMsg)
+ }
+ })
+ }
+}