feat(datasource): add WeCom document integration and callback setup

- Implemented WeCom document connector to sync smart documents and WeDrive files into WeKnora.
- Added detailed documentation for WeCom integration, including setup instructions for callback URL and API access.
- Enhanced frontend localization to support WeCom-specific messages and instructions.
- Updated data source management UI to include WeCom configuration options and callback URL handling.
- Improved error handling and validation for WeCom API interactions.
This commit is contained in:
wizardchen
2026-03-30 10:57:30 +08:00
committed by lyingbug
parent f1efac3860
commit 11cabd5952
14 changed files with 1638 additions and 27 deletions
+3 -3
View File
@@ -153,10 +153,10 @@ var ConnectorMetadataRegistry = map[string]ConnectorMetadata{
types.ConnectorTypeWecomDoc: {
Type: types.ConnectorTypeWecomDoc,
Name: "WeCom Docs (企微文档)",
Description: "Sync documents and content from WeCom",
Description: "Sync smart documents and WeDrive files from WeCom",
Priority: 8,
AuthType: "api_key",
Capabilities: []string{"incremental"},
AuthType: "corp_secret",
Capabilities: []string{"incremental", "deletion_sync"},
},
types.ConnectorTypeWebCrawler: {
Type: types.ConnectorTypeWebCrawler,
@@ -0,0 +1,109 @@
package wecom
import (
"crypto/aes"
"crypto/cipher"
"crypto/sha1"
"encoding/base64"
"encoding/binary"
"fmt"
"sort"
"strings"
)
// CallbackConfig holds the parameters needed for WeCom callback URL verification.
// These are generated by the WeCom admin console when configuring "接收消息服务器URL".
type CallbackConfig struct {
Token string `json:"callback_token"`
EncodingAESKey string `json:"callback_aes_key"`
CorpID string `json:"corp_id"`
}
// VerifyCallback verifies a WeCom callback URL verification request and returns
// the decrypted echostr that should be sent back as the HTTP response body.
//
// WeCom sends a GET request with query params: msg_signature, timestamp, nonce, echostr.
// We must verify the signature, decrypt echostr, and return the plaintext.
func VerifyCallback(cfg CallbackConfig, msgSignature, timestamp, nonce, echostr string) ([]byte, error) {
if cfg.Token == "" || cfg.EncodingAESKey == "" || cfg.CorpID == "" {
return nil, fmt.Errorf("incomplete callback config: token, encoding_aes_key, and corp_id are all required")
}
// Step 1: Verify signature = SHA1(sort(token, timestamp, nonce, echostr))
if err := verifySignature(cfg.Token, timestamp, nonce, echostr, msgSignature); err != nil {
return nil, fmt.Errorf("signature verification failed: %w", err)
}
// Step 2: Decode the AES key (EncodingAESKey is 43-char base64 without trailing '=')
aesKey, err := base64.StdEncoding.DecodeString(cfg.EncodingAESKey + "=")
if err != nil {
return nil, fmt.Errorf("decode EncodingAESKey: %w", err)
}
if len(aesKey) != 32 {
return nil, fmt.Errorf("invalid AES key length: got %d, want 32", len(aesKey))
}
// Step 3: Base64-decode the echostr ciphertext
ciphertext, err := base64.StdEncoding.DecodeString(echostr)
if err != nil {
return nil, fmt.Errorf("base64 decode echostr: %w", err)
}
// Step 4: AES-256-CBC decrypt (IV = first 16 bytes of AES key)
plaintext, err := aesDecrypt(ciphertext, aesKey)
if err != nil {
return nil, fmt.Errorf("AES decrypt: %w", err)
}
// Step 5: Parse plaintext: 16-byte random + 4-byte msg_len (big-endian) + msg + corp_id
if len(plaintext) < 20 {
return nil, fmt.Errorf("decrypted data too short: %d bytes", len(plaintext))
}
msgLen := binary.BigEndian.Uint32(plaintext[16:20])
if 20+int(msgLen) > len(plaintext) {
return nil, fmt.Errorf("invalid msg_len %d, plaintext only %d bytes", msgLen, len(plaintext))
}
msg := plaintext[20 : 20+msgLen]
receivedCorpID := string(plaintext[20+msgLen:])
if receivedCorpID != cfg.CorpID {
return nil, fmt.Errorf("corp_id mismatch: expected %q, got %q", cfg.CorpID, receivedCorpID)
}
return msg, nil
}
func verifySignature(token, timestamp, nonce, echostr, expected string) error {
parts := []string{token, timestamp, nonce, echostr}
sort.Strings(parts)
h := sha1.New()
h.Write([]byte(strings.Join(parts, "")))
got := fmt.Sprintf("%x", h.Sum(nil))
if got != expected {
return fmt.Errorf("got %s, expected %s", got, expected)
}
return nil
}
func aesDecrypt(ciphertext, key []byte) ([]byte, error) {
block, err := aes.NewCipher(key)
if err != nil {
return nil, err
}
if len(ciphertext)%aes.BlockSize != 0 {
return nil, fmt.Errorf("ciphertext length %d is not a multiple of block size %d", len(ciphertext), aes.BlockSize)
}
iv := key[:aes.BlockSize]
mode := cipher.NewCBCDecrypter(block, iv)
plaintext := make([]byte, len(ciphertext))
mode.CryptBlocks(plaintext, ciphertext)
// PKCS#7 unpadding
if len(plaintext) == 0 {
return nil, fmt.Errorf("empty plaintext after decryption")
}
padLen := int(plaintext[len(plaintext)-1])
if padLen < 1 || padLen > aes.BlockSize || padLen > len(plaintext) {
return nil, fmt.Errorf("invalid PKCS7 padding: %d", padLen)
}
return plaintext[:len(plaintext)-padLen], nil
}
@@ -0,0 +1,338 @@
package wecom
import (
"bytes"
"context"
"encoding/json"
"fmt"
"io"
"net/http"
"sync"
"time"
"github.com/Tencent/WeKnora/internal/logger"
)
// Client wraps the WeCom API for document and WeDrive operations.
type Client struct {
corpID string
corpSecret string
httpClient *http.Client
tokenMu sync.Mutex
tokenCache string
tokenExpAt time.Time
}
// NewClient creates a new WeCom API client.
func NewClient(config *Config) *Client {
return &Client{
corpID: config.CorpID,
corpSecret: config.CorpSecret,
httpClient: &http.Client{Timeout: 30 * time.Second},
}
}
// getAccessToken retrieves (or returns cached) access token.
// WeCom tokens expire in 7200s (2 hours); we cache with a 5-minute safety margin.
func (c *Client) getAccessToken(ctx context.Context) (string, error) {
c.tokenMu.Lock()
defer c.tokenMu.Unlock()
if c.tokenCache != "" && time.Now().Before(c.tokenExpAt) {
return c.tokenCache, nil
}
url := fmt.Sprintf("%s/cgi-bin/gettoken?corpid=%s&corpsecret=%s", BaseURL, c.corpID, c.corpSecret)
req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil)
if err != nil {
return "", fmt.Errorf("create token request: %w", err)
}
resp, err := c.httpClient.Do(req)
if err != nil {
return "", fmt.Errorf("request token: %w", err)
}
defer resp.Body.Close()
var result tokenResponse
if err := json.NewDecoder(resp.Body).Decode(&result); err != nil {
return "", fmt.Errorf("decode token response: %w", err)
}
if !result.ok() {
return "", result.wrapError("wecom auth")
}
c.tokenCache = result.AccessToken
ttl := time.Duration(result.ExpiresIn) * time.Second
if ttl > 5*time.Minute {
ttl -= 5 * time.Minute
}
c.tokenExpAt = time.Now().Add(ttl)
logger.Infof(ctx, "[WeCom] got access_token: %s...%s expires_in=%ds",
safePrefix(result.AccessToken, 8), safeSuffix(result.AccessToken, 4), result.ExpiresIn)
return c.tokenCache, nil
}
// doPost executes an authenticated POST request and decodes the JSON response.
func (c *Client) doPost(ctx context.Context, path string, body interface{}, result interface{}) error {
token, err := c.getAccessToken(ctx)
if err != nil {
return err
}
var bodyReader io.Reader
if body != nil {
bodyBytes, err := json.Marshal(body)
if err != nil {
return fmt.Errorf("marshal request body: %w", err)
}
bodyReader = bytes.NewReader(bodyBytes)
}
url := fmt.Sprintf("%s%s?access_token=%s", BaseURL, path, token)
req, err := http.NewRequestWithContext(ctx, http.MethodPost, url, bodyReader)
if err != nil {
return fmt.Errorf("create request: %w", err)
}
req.Header.Set("Content-Type", "application/json; charset=utf-8")
logger.Infof(ctx, "[WeCom] POST %s", path)
resp, err := c.httpClient.Do(req)
if err != nil {
return fmt.Errorf("execute request: %w", err)
}
defer resp.Body.Close()
respBody, err := io.ReadAll(resp.Body)
if err != nil {
return fmt.Errorf("read response body: %w", err)
}
logger.Infof(ctx, "[WeCom] POST %s → status=%d bodyLen=%d body=%s",
path, resp.StatusCode, len(respBody), truncate(string(respBody), 1000))
if resp.StatusCode != http.StatusOK {
return fmt.Errorf("wecom api error: status=%d body=%s", resp.StatusCode, string(respBody))
}
if result != nil {
if err := json.Unmarshal(respBody, result); err != nil {
return fmt.Errorf("decode response: %w", err)
}
}
return nil
}
// Ping verifies the credentials by attempting to get an access token.
func (c *Client) Ping(ctx context.Context) error {
_, err := c.getAccessToken(ctx)
return err
}
// ──────────────────────────────────────────────────────────────────────
// Smart Document APIs (wedoc)
// ──────────────────────────────────────────────────────────────────────
// ListSmartDocuments lists all smart documents accessible to the app.
// docType: 0=all, 3=doc, 4=sheet, 10=form.
func (c *Client) ListSmartDocuments(ctx context.Context, docType int) ([]docListItem, error) {
var allDocs []docListItem
cursor := ""
for {
body := map[string]interface{}{
"limit": 50,
}
if docType != DocFilterAll {
body["doc_type"] = docType
}
if cursor != "" {
body["cursor"] = cursor
}
var resp docListResponse
if err := c.doPost(ctx, "/cgi-bin/wedoc/doc_list", body, &resp); err != nil {
return nil, fmt.Errorf("list smart documents: %w", err)
}
if !resp.ok() {
return nil, resp.wrapError("list smart documents")
}
logger.Infof(ctx, "[WeCom] ListSmartDocuments: got %d docs, has_more=%v", len(resp.DocInfoList), resp.HasMore)
allDocs = append(allDocs, resp.DocInfoList...)
if !resp.HasMore || resp.NextCursor == "" {
break
}
cursor = resp.NextCursor
}
logger.Infof(ctx, "[WeCom] ListSmartDocuments: total %d docs (type=%d)", len(allDocs), docType)
return allDocs, nil
}
// GetDocBaseInfo retrieves metadata for a single document.
func (c *Client) GetDocBaseInfo(ctx context.Context, docID string) (*docBaseInfo, error) {
body := map[string]string{"docid": docID}
var resp docBaseInfoResponse
if err := c.doPost(ctx, "/cgi-bin/wedoc/get_doc_base_info", body, &resp); err != nil {
return nil, fmt.Errorf("get doc base info: %w", err)
}
if !resp.ok() {
return nil, resp.wrapError("get doc base info")
}
return &resp.DocBaseInfo, nil
}
// ──────────────────────────────────────────────────────────────────────
// WeDrive APIs (微盘)
// ──────────────────────────────────────────────────────────────────────
// ListDriveFiles lists all files in a WeDrive space folder recursively.
// If fatherID is empty, lists files in the space root.
func (c *Client) ListDriveFiles(ctx context.Context, spaceID, fatherID string) ([]driveFileItem, error) {
var allFiles []driveFileItem
start := 0
for {
body := map[string]interface{}{
"spaceid": spaceID,
"sort_type": 5, // sort by modify time desc
"start": start,
"limit": 1000,
}
if fatherID != "" {
body["fatherid"] = fatherID
}
var resp driveFileListResponse
if err := c.doPost(ctx, "/cgi-bin/wedrive/file_list", body, &resp); err != nil {
return nil, fmt.Errorf("list drive files: %w", err)
}
if !resp.ok() {
return nil, resp.wrapError("list drive files")
}
allFiles = append(allFiles, resp.FileList.Item...)
if !resp.FileList.HasMore || len(resp.FileList.Item) == 0 {
break
}
start += len(resp.FileList.Item)
}
return allFiles, nil
}
// ListAllDriveFilesRecursive recursively lists all files in a WeDrive space.
func (c *Client) ListAllDriveFilesRecursive(ctx context.Context, spaceID string) ([]driveFileItem, error) {
topFiles, err := c.ListDriveFiles(ctx, spaceID, "")
if err != nil {
return nil, err
}
var allFiles []driveFileItem
var walk func(files []driveFileItem) error
walk = func(files []driveFileItem) error {
for _, f := range files {
allFiles = append(allFiles, f)
if f.FileType == FileTypeFolder {
children, err := c.ListDriveFiles(ctx, spaceID, f.FileID)
if err != nil {
return fmt.Errorf("list children of %s: %w", f.FileID, err)
}
if err := walk(children); err != nil {
return err
}
}
}
return nil
}
if err := walk(topFiles); err != nil {
return nil, err
}
return allFiles, nil
}
// GetDriveFileDownloadURL gets the temporary download URL for a WeDrive file.
func (c *Client) GetDriveFileDownloadURL(ctx context.Context, fileID, userID string) (*driveFileDownloadResponse, error) {
body := map[string]string{
"fileid": fileID,
"userid": userID,
}
var resp driveFileDownloadResponse
if err := c.doPost(ctx, "/cgi-bin/wedrive/file_download", body, &resp); err != nil {
return nil, fmt.Errorf("get drive file download url: %w", err)
}
if !resp.ok() {
return nil, resp.wrapError("get drive file download url")
}
return &resp, nil
}
// DownloadFromURL downloads the file content from a temporary download URL with cookie auth.
func (c *Client) DownloadFromURL(ctx context.Context, downloadURL, cookieName, cookieValue string) ([]byte, error) {
req, err := http.NewRequestWithContext(ctx, http.MethodGet, downloadURL, nil)
if err != nil {
return nil, fmt.Errorf("create download request: %w", err)
}
if cookieName != "" && cookieValue != "" {
req.AddCookie(&http.Cookie{Name: cookieName, Value: cookieValue})
}
logger.Infof(ctx, "[WeCom] download GET %s", truncate(downloadURL, 100))
resp, err := c.httpClient.Do(req)
if err != nil {
return nil, fmt.Errorf("download request: %w", err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
body, _ := io.ReadAll(resp.Body)
return nil, fmt.Errorf("download failed: status=%d body=%s", resp.StatusCode, truncate(string(body), 500))
}
data, err := io.ReadAll(resp.Body)
if err != nil {
return nil, fmt.Errorf("read download body: %w", err)
}
logger.Infof(ctx, "[WeCom] download → OK, %d bytes", len(data))
return data, nil
}
// --- Helper functions ---
func truncate(s string, maxLen int) string {
if len(s) <= maxLen {
return s
}
return s[:maxLen] + "..."
}
func safePrefix(s string, n int) string {
if len(s) < n {
return s
}
return s[:n]
}
func safeSuffix(s string, n int) string {
if len(s) < n {
return s
}
return s[len(s)-n:]
}
@@ -0,0 +1,533 @@
package wecom
import (
"context"
"encoding/json"
"fmt"
"strings"
"time"
"github.com/Tencent/WeKnora/internal/logger"
"github.com/Tencent/WeKnora/internal/types"
)
// Connector implements the datasource.Connector interface for WeCom (企业微信).
type Connector struct{}
// NewConnector creates a new WeCom document connector.
func NewConnector() *Connector {
return &Connector{}
}
// Type returns the connector type identifier.
func (c *Connector) Type() string {
return types.ConnectorTypeWecomDoc
}
// Validate verifies that the WeCom configuration is valid by testing connectivity.
func (c *Connector) Validate(ctx context.Context, config *types.DataSourceConfig) error {
wecomConfig, err := parseWecomConfig(config)
if err != nil {
return err
}
client := NewClient(wecomConfig)
if err := client.Ping(ctx); err != nil {
return fmt.Errorf("wecom connection failed: %w", err)
}
return nil
}
// ListResources lists available smart document categories as selectable resources.
// Each "resource" represents a document type category (all, docs, sheets).
func (c *Connector) ListResources(ctx context.Context, config *types.DataSourceConfig) ([]types.Resource, error) {
wecomConfig, err := parseWecomConfig(config)
if err != nil {
return nil, err
}
// Verify connectivity
client := NewClient(wecomConfig)
if err := client.Ping(ctx); err != nil {
return nil, fmt.Errorf("wecom connection failed: %w", err)
}
// Fetch actual doc counts per category to show the user
allDocs, err := client.ListSmartDocuments(ctx, DocFilterAll)
if err != nil {
logger.Warnf(ctx, "[WeCom] failed to list documents for resource discovery: %v", err)
}
docCount, sheetCount := 0, 0
for _, d := range allDocs {
switch d.DocType {
case DocFilterDoc:
docCount++
case DocFilterSheet:
sheetCount++
}
}
resources := []types.Resource{
{
ExternalID: ResourceAllDocs,
Name: "全部文档",
Type: "doc_category",
Description: fmt.Sprintf("所有智能文档 (%d 个)", len(allDocs)),
},
{
ExternalID: ResourceDocs,
Name: "文档",
Type: "doc_category",
Description: fmt.Sprintf("仅智能文档类型 (%d 个)", docCount),
},
{
ExternalID: ResourceSheets,
Name: "表格",
Type: "doc_category",
Description: fmt.Sprintf("仅智能表格类型 (%d 个)", sheetCount),
},
}
// If WeDrive space IDs are configured in settings, list them too
if spaceIDs := getSettingStringSlice(config, "space_ids"); len(spaceIDs) > 0 {
for _, sid := range spaceIDs {
resources = append(resources, types.Resource{
ExternalID: "wedrive:" + sid,
Name: "微盘空间: " + sid,
Type: "wedrive_space",
Description: "企业微信微盘空间",
})
}
}
return resources, nil
}
// FetchAll performs a full sync of all documents from the selected resources.
func (c *Connector) FetchAll(ctx context.Context, config *types.DataSourceConfig, resourceIDs []string) ([]types.FetchedItem, error) {
wecomConfig, err := parseWecomConfig(config)
if err != nil {
return nil, err
}
client := NewClient(wecomConfig)
var allItems []types.FetchedItem
for _, resID := range resourceIDs {
if strings.HasPrefix(resID, "wedrive:") {
spaceID := strings.TrimPrefix(resID, "wedrive:")
items, err := c.fetchDriveFiles(ctx, client, config, spaceID)
if err != nil {
return nil, fmt.Errorf("fetch wedrive space %s: %w", spaceID, err)
}
allItems = append(allItems, items...)
} else {
items, err := c.fetchSmartDocs(ctx, client, resID)
if err != nil {
return nil, fmt.Errorf("fetch smart docs (resource=%s): %w", resID, err)
}
allItems = append(allItems, items...)
}
}
return allItems, nil
}
// FetchIncremental performs an incremental sync by comparing document modify times.
func (c *Connector) FetchIncremental(ctx context.Context, config *types.DataSourceConfig, cursor *types.SyncCursor) ([]types.FetchedItem, *types.SyncCursor, error) {
wecomConfig, err := parseWecomConfig(config)
if err != nil {
return nil, nil, err
}
client := NewClient(wecomConfig)
var prevCursor wecomCursor
if cursor != nil && cursor.ConnectorCursor != nil {
cursorBytes, _ := json.Marshal(cursor.ConnectorCursor)
_ = json.Unmarshal(cursorBytes, &prevCursor)
}
newCursor := wecomCursor{
LastSyncTime: time.Now(),
DocModifyTimes: make(map[string]int64),
}
var changedItems []types.FetchedItem
resourceIDs := config.ResourceIDs
if len(resourceIDs) == 0 {
return nil, nil, fmt.Errorf("no resource IDs configured")
}
for _, resID := range resourceIDs {
if strings.HasPrefix(resID, "wedrive:") {
spaceID := strings.TrimPrefix(resID, "wedrive:")
items, driveModTimes, err := c.fetchDriveFilesIncremental(ctx, client, config, spaceID, prevCursor.DocModifyTimes)
if err != nil {
return nil, nil, fmt.Errorf("incremental fetch wedrive space %s: %w", spaceID, err)
}
changedItems = append(changedItems, items...)
for k, v := range driveModTimes {
newCursor.DocModifyTimes[k] = v
}
continue
}
docFilter, ok := docFilterForResource[resID]
if !ok {
docFilter = DocFilterAll
}
docs, err := client.ListSmartDocuments(ctx, docFilter)
if err != nil {
return nil, nil, fmt.Errorf("list smart docs for incremental: %w", err)
}
currentDocIDs := make(map[string]bool)
for _, doc := range docs {
currentDocIDs[doc.DocID] = true
info, err := client.GetDocBaseInfo(ctx, doc.DocID)
if err != nil {
logger.Warnf(ctx, "[WeCom] failed to get doc info for %s: %v", doc.DocID, err)
changedItems = append(changedItems, types.FetchedItem{
ExternalID: doc.DocID,
Title: doc.DocName,
Metadata: map[string]string{"error": err.Error()},
})
newCursor.DocModifyTimes[doc.DocID] = 0
continue
}
newCursor.DocModifyTimes[doc.DocID] = info.ModifyTime
if prevModTime, exists := prevCursor.DocModifyTimes[doc.DocID]; exists {
if prevModTime == info.ModifyTime {
continue // unchanged
}
}
item := c.buildSmartDocItem(doc.DocID, info)
changedItems = append(changedItems, item)
}
// Detect deleted docs
for docID := range prevCursor.DocModifyTimes {
if !currentDocIDs[docID] && !strings.HasPrefix(docID, "wedrive:") {
changedItems = append(changedItems, types.FetchedItem{
ExternalID: docID,
IsDeleted: true,
})
}
}
}
nextCursorMap := make(map[string]interface{})
cursorBytes, _ := json.Marshal(newCursor)
_ = json.Unmarshal(cursorBytes, &nextCursorMap)
nextSyncCursor := &types.SyncCursor{
LastSyncTime: time.Now(),
ConnectorCursor: nextCursorMap,
}
return changedItems, nextSyncCursor, nil
}
// ──────────────────────────────────────────────────────────────────────
// Internal fetch helpers
// ──────────────────────────────────────────────────────────────────────
// fetchSmartDocs fetches all smart documents for a given resource category.
func (c *Connector) fetchSmartDocs(ctx context.Context, client *Client, resourceID string) ([]types.FetchedItem, error) {
docFilter, ok := docFilterForResource[resourceID]
if !ok {
docFilter = DocFilterAll
}
docs, err := client.ListSmartDocuments(ctx, docFilter)
if err != nil {
return nil, err
}
var items []types.FetchedItem
for _, doc := range docs {
info, err := client.GetDocBaseInfo(ctx, doc.DocID)
if err != nil {
items = append(items, types.FetchedItem{
ExternalID: doc.DocID,
Title: doc.DocName,
Metadata: map[string]string{"error": err.Error()},
})
continue
}
items = append(items, c.buildSmartDocItem(doc.DocID, info))
}
return items, nil
}
// buildSmartDocItem constructs a FetchedItem for a smart document.
func (c *Connector) buildSmartDocItem(docID string, info *docBaseInfo) types.FetchedItem {
docURL := buildDocURL(docID, info.DocType)
modTime := time.Unix(info.ModifyTime, 0)
return types.FetchedItem{
ExternalID: docID,
Title: info.DocName,
URL: docURL,
ContentType: "text/html",
UpdatedAt: modTime,
Metadata: map[string]string{
"doc_type": fmt.Sprintf("%d", info.DocType),
"create_time": fmt.Sprintf("%d", info.CreateTime),
"modify_time": fmt.Sprintf("%d", info.ModifyTime),
"channel": types.ChannelWecom,
},
}
}
// fetchDriveFiles fetches all files from a WeDrive space.
func (c *Connector) fetchDriveFiles(ctx context.Context, client *Client, config *types.DataSourceConfig, spaceID string) ([]types.FetchedItem, error) {
files, err := client.ListAllDriveFilesRecursive(ctx, spaceID)
if err != nil {
return nil, err
}
userID := getSettingString(config, "userid")
var items []types.FetchedItem
for _, f := range files {
if f.FileType == FileTypeFolder {
continue
}
item, err := c.fetchDriveFileContent(ctx, client, f, spaceID, userID)
if err != nil {
items = append(items, types.FetchedItem{
ExternalID: "wedrive:" + f.FileID,
Title: f.FileName,
SourceResourceID: "wedrive:" + spaceID,
Metadata: map[string]string{"error": err.Error()},
})
continue
}
if item != nil {
items = append(items, *item)
}
}
return items, nil
}
// fetchDriveFilesIncremental performs incremental fetch for a WeDrive space.
func (c *Connector) fetchDriveFilesIncremental(ctx context.Context, client *Client, config *types.DataSourceConfig, spaceID string, prevModTimes map[string]int64) ([]types.FetchedItem, map[string]int64, error) {
files, err := client.ListAllDriveFilesRecursive(ctx, spaceID)
if err != nil {
return nil, nil, err
}
userID := getSettingString(config, "userid")
modTimes := make(map[string]int64)
currentIDs := make(map[string]bool)
var changed []types.FetchedItem
for _, f := range files {
if f.FileType == FileTypeFolder {
continue
}
key := "wedrive:" + f.FileID
currentIDs[key] = true
modTimes[key] = f.ModifyTime
if prevMod, exists := prevModTimes[key]; exists && prevMod == f.ModifyTime {
continue // unchanged
}
item, err := c.fetchDriveFileContent(ctx, client, f, spaceID, userID)
if err != nil {
changed = append(changed, types.FetchedItem{
ExternalID: key,
Title: f.FileName,
SourceResourceID: "wedrive:" + spaceID,
Metadata: map[string]string{"error": err.Error()},
})
continue
}
if item != nil {
changed = append(changed, *item)
}
}
// Detect deletions
for prevKey := range prevModTimes {
if strings.HasPrefix(prevKey, "wedrive:") && !currentIDs[prevKey] {
changed = append(changed, types.FetchedItem{
ExternalID: prevKey,
IsDeleted: true,
SourceResourceID: "wedrive:" + spaceID,
})
}
}
return changed, modTimes, nil
}
// fetchDriveFileContent downloads file content for a WeDrive file.
func (c *Connector) fetchDriveFileContent(ctx context.Context, client *Client, f driveFileItem, spaceID, userID string) (*types.FetchedItem, error) {
modTime := time.Unix(f.ModifyTime, 0)
externalID := "wedrive:" + f.FileID
baseMeta := map[string]string{
"file_type": fmt.Sprintf("%d", f.FileType),
"file_id": f.FileID,
"space_id": spaceID,
"create_userid": f.CreateUserID,
"update_userid": f.UpdateUserID,
"channel": types.ChannelWecom,
}
switch f.FileType {
case FileTypeFile:
// Binary uploaded file — download via WeDrive API
if userID == "" {
return &types.FetchedItem{
ExternalID: externalID,
Title: f.FileName,
URL: f.URL,
UpdatedAt: modTime,
SourceResourceID: "wedrive:" + spaceID,
Metadata: baseMeta,
}, nil
}
dlResp, err := client.GetDriveFileDownloadURL(ctx, f.FileID, userID)
if err != nil {
return nil, fmt.Errorf("get download url for %s: %w", f.FileName, err)
}
data, err := client.DownloadFromURL(ctx, dlResp.DownloadURL, dlResp.CookieName, dlResp.CookieValue)
if err != nil {
return nil, fmt.Errorf("download file %s: %w", f.FileName, err)
}
return &types.FetchedItem{
ExternalID: externalID,
Title: f.FileName,
Content: data,
ContentType: "application/octet-stream",
FileName: f.FileName,
URL: f.URL,
UpdatedAt: modTime,
SourceResourceID: "wedrive:" + spaceID,
Metadata: baseMeta,
}, nil
case FileTypeDoc, FileTypeSheet, FileTypeForm:
// Smart doc in WeDrive — import via URL
url := f.URL
if url == "" {
url = buildDocURL(f.FileID, f.FileType)
}
return &types.FetchedItem{
ExternalID: externalID,
Title: f.FileName,
URL: url,
ContentType: "text/html",
UpdatedAt: modTime,
SourceResourceID: "wedrive:" + spaceID,
Metadata: baseMeta,
}, nil
default:
return nil, nil
}
}
// ──────────────────────────────────────────────────────────────────────
// Helper functions
// ──────────────────────────────────────────────────────────────────────
func parseWecomConfig(config *types.DataSourceConfig) (*Config, error) {
if config == nil {
return nil, fmt.Errorf("config is nil")
}
credBytes, err := json.Marshal(config.Credentials)
if err != nil {
return nil, fmt.Errorf("marshal credentials: %w", err)
}
var wecomConfig Config
if err := json.Unmarshal(credBytes, &wecomConfig); err != nil {
return nil, fmt.Errorf("parse wecom credentials: %w", err)
}
if wecomConfig.CorpID == "" || wecomConfig.CorpSecret == "" {
return nil, fmt.Errorf("wecom corp_id and corp_secret are required")
}
return &wecomConfig, nil
}
// buildDocURL constructs the WeCom document URL based on doc type.
// docType can be either DocFilter* or FileType* constants (4 = sheet in both).
func buildDocURL(docID string, docType int) string {
switch docType {
case FileTypeSheet: // also matches DocFilterSheet (both are 4)
return fmt.Sprintf("https://doc.weixin.qq.com/sheet/%s", docID)
case FileTypeForm, DocFilterForm:
return fmt.Sprintf("https://doc.weixin.qq.com/forms/%s", docID)
default:
return fmt.Sprintf("https://doc.weixin.qq.com/doc/%s", docID)
}
}
// getSettingString retrieves a string value from config.Settings.
func getSettingString(config *types.DataSourceConfig, key string) string {
if config == nil || config.Settings == nil {
return ""
}
v, ok := config.Settings[key]
if !ok {
return ""
}
s, _ := v.(string)
return s
}
// getSettingStringSlice retrieves a string slice from config.Settings.
func getSettingStringSlice(config *types.DataSourceConfig, key string) []string {
if config == nil || config.Settings == nil {
return nil
}
v, ok := config.Settings[key]
if !ok {
return nil
}
switch val := v.(type) {
case []string:
return val
case []interface{}:
result := make([]string, 0, len(val))
for _, item := range val {
if s, ok := item.(string); ok {
result = append(result, s)
}
}
return result
case string:
if val == "" {
return nil
}
return strings.Split(val, ",")
default:
return nil
}
}
@@ -0,0 +1,155 @@
// Package wecom implements the WeCom (企业微信) document data source connector for WeKnora.
//
// It syncs smart documents and WeDrive files from WeCom into WeKnora knowledge bases.
//
// WeCom API docs:
// - Auth: https://developer.work.weixin.qq.com/document/path/91039
// - Smart doc list: https://developer.work.weixin.qq.com/document/path/97460
// - Doc base info: https://developer.work.weixin.qq.com/document/path/97461
// - WeDrive file list: https://developer.work.weixin.qq.com/document/path/95859
// - WeDrive download: https://developer.work.weixin.qq.com/document/path/98021
package wecom
import (
"fmt"
"time"
)
// Config holds WeCom-specific configuration for the data source connector.
type Config struct {
CorpID string `json:"corp_id"`
CorpSecret string `json:"corp_secret"`
}
// BaseURL is the WeCom API base URL.
const BaseURL = "https://qyapi.weixin.qq.com"
// Smart document type filter values for POST /cgi-bin/wedoc/doc_list.
const (
DocFilterAll = 0 // All types
DocFilterDoc = 3 // Documents (文档)
DocFilterSheet = 4 // Spreadsheets (表格)
DocFilterForm = 10 // Collect forms (收集表)
)
// WeDrive file_type values returned by file_list / file_info.
const (
FileTypeFolder = 1 // Folder
FileTypeFile = 2 // Uploaded file (binary)
FileTypeDoc = 3 // Smart doc (文档)
FileTypeSheet = 4 // Smart sheet (表格)
FileTypeForm = 5 // Collect form (收集表)
)
// Resource type identifiers used by ListResources.
const (
ResourceAllDocs = "all_documents"
ResourceDocs = "documents"
ResourceSheets = "sheets"
)
// docFilterForResource maps resource type IDs to doc/list type parameters.
var docFilterForResource = map[string]int{
ResourceAllDocs: DocFilterAll,
ResourceDocs: DocFilterDoc,
ResourceSheets: DocFilterSheet,
}
// --- WeCom API response structures ---
type apiResponse struct {
ErrCode int `json:"errcode"`
ErrMsg string `json:"errmsg"`
}
func (r *apiResponse) ok() bool { return r.ErrCode == 0 }
func (r *apiResponse) wrapError(action string) error {
hint := ""
switch r.ErrCode {
case 48002:
hint = " (应用未被授权调用此接口,请在管理后台「协作→文档→API」中将应用添加为「可调用接口的应用」,并检查「企业可信IP」配置)"
case 60020:
hint = " (IP 不在企业可信 IP 白名单中,请在应用详情页底部添加服务器 IP)"
case 40014, 42001:
hint = " (access_token 无效或已过期)"
case 301002:
hint = " (应用无文档访问权限,请检查可见范围设置)"
}
return fmt.Errorf("%s: errcode=%d errmsg=%s%s", action, r.ErrCode, r.ErrMsg, hint)
}
type tokenResponse struct {
apiResponse
AccessToken string `json:"access_token"`
ExpiresIn int `json:"expires_in"` // seconds, typically 7200
}
// docListItem is a single item returned by the doc list API.
type docListItem struct {
DocID string `json:"docid"`
DocName string `json:"doc_name"`
DocType int `json:"doc_type,omitempty"`
}
// docListResponse is the response for POST /cgi-bin/wedoc/doc_list.
type docListResponse struct {
apiResponse
DocInfoList []docListItem `json:"doc_info_list"`
HasMore bool `json:"has_more"`
NextCursor string `json:"next_cursor"`
}
// docBaseInfo is the detailed metadata of a single document.
type docBaseInfo struct {
DocID string `json:"docid"`
DocName string `json:"doc_name"`
CreateTime int64 `json:"create_time"` // unix timestamp
ModifyTime int64 `json:"modify_time"` // unix timestamp
DocType int `json:"doc_type"` // 3=doc, 4=sheet
}
// docBaseInfoResponse is the response for POST /cgi-bin/wedoc/get_doc_base_info.
type docBaseInfoResponse struct {
apiResponse
DocBaseInfo docBaseInfo `json:"doc_base_info"`
}
// driveFileItem represents a file/folder in WeDrive.
type driveFileItem struct {
FileID string `json:"fileid"`
FileName string `json:"file_name"`
SpaceID string `json:"spaceid"`
FatherID string `json:"fatherid"`
FileSize int64 `json:"file_size"`
CreateTime int64 `json:"ctime"`
ModifyTime int64 `json:"mtime"`
FileType int `json:"file_type"` // 1=folder, 2=file, 3=doc, 4=sheet, 5=form
FileStatus int `json:"file_status"`
CreateUserID string `json:"create_userid"`
UpdateUserID string `json:"update_userid"`
URL string `json:"url"` // non-empty for smart doc types
}
// driveFileListResponse is the response for POST /cgi-bin/wedrive/file_list.
type driveFileListResponse struct {
apiResponse
FileList struct {
Item []driveFileItem `json:"item"`
HasMore bool `json:"has_more"`
} `json:"file_list"`
}
// driveFileDownloadResponse is the response for POST /cgi-bin/wedrive/file_download.
type driveFileDownloadResponse struct {
apiResponse
DownloadURL string `json:"download_url"`
CookieName string `json:"cookie_name"`
CookieValue string `json:"cookie_value"`
}
// wecomCursor stores incremental sync state for WeCom.
type wecomCursor struct {
LastSyncTime time.Time `json:"last_sync_time"`
DocModifyTimes map[string]int64 `json:"doc_modify_times,omitempty"` // docid -> modify_time
}