feat: add DingTalk directory-backed session titles

This commit is contained in:
姚章浩
2026-07-23 10:55:25 +08:00
parent 39c5fbbaef
commit 5e0694835a
33 changed files with 1648 additions and 62 deletions
+121
View File
@@ -0,0 +1,121 @@
package directory
import (
"bytes"
"context"
"encoding/json"
"errors"
"net/http"
"net/url"
"strconv"
"strings"
"sync"
"time"
)
type DingTalkLookupConfig struct {
TokenURL string
APIBaseURL string
ClientID string
ClientSecret string
Timeout time.Duration
}
type DingTalkLookup struct {
tokenURL string
apiBaseURL string
clientID string
clientSecret string
httpClient *http.Client
mu sync.Mutex
token string
tokenExpiry time.Time
now func() time.Time
}
func NewDingTalkLookup(cfg DingTalkLookupConfig) (*DingTalkLookup, error) {
cfg.TokenURL = strings.TrimSpace(cfg.TokenURL)
cfg.APIBaseURL = strings.TrimRight(strings.TrimSpace(cfg.APIBaseURL), "/")
if cfg.TokenURL == "" || cfg.APIBaseURL == "" || strings.TrimSpace(cfg.ClientID) == "" || strings.TrimSpace(cfg.ClientSecret) == "" {
return nil, errors.New("dingtalk lookup endpoints and credentials are required")
}
if _, err := url.ParseRequestURI(cfg.TokenURL); err != nil { return nil, errors.New("invalid dingtalk token endpoint") }
if _, err := url.ParseRequestURI(cfg.APIBaseURL); err != nil { return nil, errors.New("invalid dingtalk API endpoint") }
if cfg.Timeout <= 0 { cfg.Timeout = 10 * time.Second }
return &DingTalkLookup{
tokenURL: cfg.TokenURL, apiBaseURL: cfg.APIBaseURL,
clientID: cfg.ClientID, clientSecret: cfg.ClientSecret,
httpClient: &http.Client{Timeout: cfg.Timeout}, now: time.Now,
}, nil
}
func (c *DingTalkLookup) LookupUser(ctx context.Context, staffID string) (Profile, error) {
staffID = strings.TrimSpace(staffID)
if staffID == "" { return Profile{}, errors.New("dingtalk user id is required") }
token, err := c.accessToken(ctx)
if err != nil { return Profile{}, err }
payload, _ := json.Marshal(map[string]string{"userid": staffID})
endpoint := c.apiBaseURL + "/topapi/v2/user/get?access_token=" + url.QueryEscape(token)
req, err := http.NewRequestWithContext(ctx, http.MethodPost, endpoint, bytes.NewReader(payload))
if err != nil { return Profile{}, errors.New("dingtalk user request failed") }
req.Header.Set("Content-Type", "application/json")
resp, err := c.httpClient.Do(req)
if err != nil { return Profile{}, errors.New("dingtalk user request failed") }
defer resp.Body.Close()
if resp.StatusCode < 200 || resp.StatusCode >= 300 { return Profile{}, errors.New("dingtalk user HTTP failure") }
var decoded struct {
ErrCode int `json:"errcode"`
Result struct {
UserID string `json:"userid"`
UnionID string `json:"unionid"`
Name string `json:"name"`
Nickname string `json:"nickname"`
Title string `json:"title"`
DepartmentIDs []int64 `json:"dept_id_list"`
Status int `json:"status"`
} `json:"result"`
}
if err := json.NewDecoder(resp.Body).Decode(&decoded); err != nil || decoded.ErrCode != 0 {
return Profile{}, errors.New("dingtalk user response invalid")
}
ids := make([]string, 0, len(decoded.Result.DepartmentIDs))
for _, id := range decoded.Result.DepartmentIDs { ids = append(ids, strconv.FormatInt(id, 10)) }
return Profile{
StaffID: staffID, UnionID: decoded.Result.UnionID, Name: strings.TrimSpace(decoded.Result.Name),
Nickname: decoded.Result.Nickname, JobTitle: decoded.Result.Title, DepartmentIDs: ids,
EmploymentStatus: strconv.Itoa(decoded.Result.Status), Source: SourceOnDemand, SyncedAt: c.now().UTC(),
}, nil
}
func (c *DingTalkLookup) accessToken(ctx context.Context) (string, error) {
c.mu.Lock()
defer c.mu.Unlock()
if c.token != "" && c.now().Before(c.tokenExpiry) { return c.token, nil }
parsed, err := url.Parse(c.tokenURL)
if err != nil { return "", errors.New("dingtalk token request failed") }
query := parsed.Query()
query.Set("appkey", c.clientID)
query.Set("appsecret", c.clientSecret)
parsed.RawQuery = query.Encode()
req, err := http.NewRequestWithContext(ctx, http.MethodGet, parsed.String(), nil)
if err != nil { return "", errors.New("dingtalk token request failed") }
resp, err := c.httpClient.Do(req)
if err != nil { return "", errors.New("dingtalk token request failed") }
defer resp.Body.Close()
if resp.StatusCode < 200 || resp.StatusCode >= 300 { return "", errors.New("dingtalk token HTTP failure") }
var decoded struct {
ErrCode int `json:"errcode"`
AccessToken string `json:"access_token"`
ExpiresIn int `json:"expires_in"`
}
if err := json.NewDecoder(resp.Body).Decode(&decoded); err != nil || decoded.ErrCode != 0 || decoded.AccessToken == "" {
return "", errors.New("dingtalk token response invalid")
}
ttl := time.Duration(decoded.ExpiresIn) * time.Second
if ttl <= 0 { ttl = time.Hour }
refreshMargin := 5 * time.Minute
if ttl <= refreshMargin { refreshMargin = ttl / 2 }
c.token = decoded.AccessToken
c.tokenExpiry = c.now().Add(ttl - refreshMargin)
return c.token, nil
}
@@ -0,0 +1,81 @@
package directory
import (
"context"
"fmt"
"net/http"
"net/http/httptest"
"strings"
"sync/atomic"
"testing"
"time"
)
func TestDingTalkLookupFetchesUserAndCachesToken(t *testing.T) {
var tokenCalls atomic.Int32
var userCalls atomic.Int32
mux := http.NewServeMux()
mux.HandleFunc("/gettoken", func(w http.ResponseWriter, r *http.Request) {
tokenCalls.Add(1)
if r.Method != http.MethodGet || r.URL.Query().Get("appkey") != "app-key" || r.URL.Query().Get("appsecret") != "app-secret" {
t.Fatalf("unexpected token request: %s %s", r.Method, r.URL.String())
}
_, _ = w.Write([]byte(`{"errcode":0,"access_token":"token-secret","expires_in":7200}`))
})
mux.HandleFunc("/topapi/v2/user/get", func(w http.ResponseWriter, r *http.Request) {
userCalls.Add(1)
if r.Method != http.MethodPost || r.URL.Query().Get("access_token") != "token-secret" {
t.Fatalf("unexpected user request: %s %s", r.Method, r.URL.String())
}
var body [256]byte
n, _ := r.Body.Read(body[:])
if !strings.Contains(string(body[:n]), `"userid":"staff-1"`) {
t.Fatalf("unexpected body: %s", body[:n])
}
_, _ = w.Write([]byte(`{"errcode":0,"result":{"userid":"staff-1","unionid":"union-1","name":"张三","nickname":"小张","title":"工程师","dept_id_list":[100,200],"status":5}}`))
})
server := httptest.NewServer(mux)
defer server.Close()
lookup, err := NewDingTalkLookup(DingTalkLookupConfig{
TokenURL: server.URL + "/gettoken", APIBaseURL: server.URL,
ClientID: "app-key", ClientSecret: "app-secret", Timeout: 2 * time.Second,
})
if err != nil { t.Fatal(err) }
for i := 0; i < 2; i++ {
profile, err := lookup.LookupUser(context.Background(), "staff-1")
if err != nil { t.Fatalf("LookupUser(%d): %v", i, err) }
if profile.Name != "张三" || profile.UnionID != "union-1" || profile.JobTitle != "工程师" || len(profile.DepartmentIDs) != 2 || profile.DepartmentIDs[1] != "200" {
t.Fatalf("profile=%+v", profile)
}
}
if tokenCalls.Load() != 1 || userCalls.Load() != 2 {
t.Fatalf("token calls=%d user calls=%d", tokenCalls.Load(), userCalls.Load())
}
}
func TestDingTalkLookupErrorsAreSanitized(t *testing.T) {
for _, failPath := range []string{"token", "user"} {
t.Run(failPath, func(t *testing.T) {
mux := http.NewServeMux()
mux.HandleFunc("/gettoken", func(w http.ResponseWriter, _ *http.Request) {
if failPath == "token" { http.Error(w, "raw-secret-body", 500); return }
_, _ = w.Write([]byte(`{"errcode":0,"access_token":"token-secret","expires_in":7200}`))
})
mux.HandleFunc("/topapi/v2/user/get", func(w http.ResponseWriter, _ *http.Request) {
http.Error(w, "raw-secret-body", 500)
})
server := httptest.NewServer(mux)
defer server.Close()
lookup, err := NewDingTalkLookup(DingTalkLookupConfig{TokenURL: server.URL + "/gettoken", APIBaseURL: server.URL, ClientID: "app-key", ClientSecret: "app-secret", Timeout: time.Second})
if err != nil { t.Fatal(err) }
_, err = lookup.LookupUser(context.Background(), "staff-secret")
if err == nil { t.Fatal("expected error") }
for _, forbidden := range []string{"raw-secret-body", "app-secret", "token-secret", "staff-secret"} {
if strings.Contains(err.Error(), forbidden) { t.Fatalf("error leaked %q: %v", forbidden, err) }
}
if !strings.Contains(err.Error(), fmt.Sprintf("dingtalk %s", failPath)) {
t.Fatalf("error=%q", err)
}
})
}
}
+105
View File
@@ -0,0 +1,105 @@
package directory
import (
"context"
"encoding/csv"
"errors"
"fmt"
"io"
"strings"
"time"
)
var requiredCSVHeaders = []string{"user_id", "name", "dept_name"}
// ImportCSV validates the complete snapshot before making one repository call.
// It consumes the tested Python sync output and accepts optional production
// enrichment columns without reimplementing the bulk DingTalk crawler in Go.
func ImportCSV(ctx context.Context, tenantKey string, input io.Reader, writer SnapshotWriter) (int, error) {
tenantKey = strings.TrimSpace(tenantKey)
if tenantKey == "" || input == nil || writer == nil {
return 0, errors.New("tenant, CSV input and writer are required")
}
r := csv.NewReader(input)
r.FieldsPerRecord = -1
header, err := r.Read()
if err != nil {
return 0, fmt.Errorf("read directory CSV header: %w", err)
}
columns := make(map[string]int, len(header))
for i, name := range header {
name = strings.TrimSpace(strings.TrimPrefix(name, "\ufeff"))
columns[name] = i
}
for _, name := range requiredCSVHeaders {
if _, ok := columns[name]; !ok {
return 0, fmt.Errorf("directory CSV missing required header %q", name)
}
}
profiles := make([]Profile, 0, 256)
line := 1
for {
record, readErr := r.Read()
if errors.Is(readErr, io.EOF) {
break
}
line++
if readErr != nil {
return 0, fmt.Errorf("read directory CSV line %d: %w", line, readErr)
}
value := func(name string) string {
idx, ok := columns[name]
if !ok || idx >= len(record) {
return ""
}
return strings.TrimSpace(record[idx])
}
staffID := value("user_id")
name := value("name")
if staffID == "" || name == "" {
return 0, fmt.Errorf("directory CSV line %d has empty user_id or name", line)
}
profiles = append(profiles, Profile{
StaffID: staffID,
UnionID: value("union_id"),
Name: name,
Nickname: value("nickname"),
JobTitle: value("title"),
DepartmentIDs: splitDepartmentIDs(value("department_ids")),
DepartmentName: value("dept_name"),
MainDepartmentName: value("main_department_name"),
Region: value("region"),
EmploymentStatus: value("employment_status"),
Source: SourceFullSync,
SyncedAt: parseSyncTime(value("sync_time")),
})
}
if len(profiles) == 0 {
return 0, errors.New("directory CSV snapshot is empty")
}
if err := writer.UpsertDirectoryProfiles(ctx, tenantKey, profiles); err != nil {
return 0, fmt.Errorf("write directory snapshot: %w", err)
}
return len(profiles), nil
}
func splitDepartmentIDs(raw string) []string {
parts := strings.FieldsFunc(raw, func(r rune) bool { return r == '/' || r == ',' || r == ';' })
out := make([]string, 0, len(parts))
for _, part := range parts {
if part = strings.TrimSpace(part); part != "" {
out = append(out, part)
}
}
return out
}
func parseSyncTime(raw string) time.Time {
for _, layout := range []string{time.RFC3339, "2006-01-02 15:04:05"} {
if parsed, err := time.Parse(layout, raw); err == nil {
return parsed
}
}
return time.Time{}
}
+87
View File
@@ -0,0 +1,87 @@
package directory
import (
"context"
"errors"
"strings"
"testing"
)
type recordingWriter struct {
calls int
tenant string
profiles []Profile
err error
}
func (w *recordingWriter) UpsertDirectoryProfiles(_ context.Context, tenant string, profiles []Profile) error {
w.calls++
w.tenant = tenant
w.profiles = append([]Profile(nil), profiles...)
return w.err
}
func TestImportCSVAcceptsTestedSyncOutputAndExtendedFields(t *testing.T) {
csv := "\ufeffuser_id,union_id,name,nickname,title,department_ids,dept_name,main_department_name,region,employment_status,sync_time,mobile\n" +
"staff-1,union-1, 张三 ,小张,工程师,100/200,公司/技术支持部,技术支持部,APAC,on_job,2026-07-22 02:30:00,13800000000\n"
writer := &recordingWriter{}
count, err := ImportCSV(context.Background(), "tenant-a", strings.NewReader(csv), writer)
if err != nil {
t.Fatalf("ImportCSV: %v", err)
}
if count != 1 || writer.calls != 1 || writer.tenant != "tenant-a" || len(writer.profiles) != 1 {
t.Fatalf("count=%d calls=%d tenant=%q profiles=%d", count, writer.calls, writer.tenant, len(writer.profiles))
}
p := writer.profiles[0]
if p.StaffID != "staff-1" || p.Name != "张三" || p.DepartmentName != "公司/技术支持部" || p.MainDepartmentName != "技术支持部" || p.Region != "APAC" || p.EmploymentStatus != "on_job" || p.Source != SourceFullSync {
t.Fatalf("profile mismatch: %+v", p)
}
if len(p.DepartmentIDs) != 2 || p.DepartmentIDs[0] != "100" || p.DepartmentIDs[1] != "200" {
t.Fatalf("department ids: %v", p.DepartmentIDs)
}
// The domain type intentionally has no mobile/email/raw payload fields.
}
func TestImportCSVAcceptsCurrentSevenColumnOutput(t *testing.T) {
csv := "user_id,union_id,name,nickname,title,department_ids,dept_name\n" +
"staff-2,union-2,李四,,经理,300,公司/销售部\n"
writer := &recordingWriter{}
count, err := ImportCSV(context.Background(), "tenant-a", strings.NewReader(csv), writer)
if err != nil {
t.Fatalf("ImportCSV: %v", err)
}
if count != 1 || writer.profiles[0].Name != "李四" || writer.profiles[0].Region != "" {
t.Fatalf("count=%d profile=%+v", count, writer.profiles[0])
}
}
func TestImportCSVRejectsInvalidSnapshotBeforeWrite(t *testing.T) {
tests := []struct {
name string
csv string
}{
{name: "missing required header", csv: "user_id,dept_name\nstaff-1,技术支持部\n"},
{name: "empty snapshot", csv: "user_id,name,dept_name\n"},
{name: "empty staff id", csv: "user_id,name,dept_name\n,张三,技术支持部\n"},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
writer := &recordingWriter{}
_, err := ImportCSV(context.Background(), "tenant-a", strings.NewReader(tt.csv), writer)
if err == nil {
t.Fatal("expected error")
}
if writer.calls != 0 {
t.Fatalf("writer called %d times before validation", writer.calls)
}
})
}
}
func TestImportCSVPropagatesWriterError(t *testing.T) {
writer := &recordingWriter{err: errors.New("db unavailable")}
_, err := ImportCSV(context.Background(), "tenant-a", strings.NewReader("user_id,name,dept_name\nstaff-1,张三,技术支持部\n"), writer)
if err == nil || writer.calls != 1 {
t.Fatalf("error=%v calls=%d", err, writer.calls)
}
}
+32
View File
@@ -0,0 +1,32 @@
package directory
import (
"context"
"time"
)
const (
SourceFullSync = "full_sync"
SourceOnDemand = "on_demand"
)
// Profile is the minimum non-sensitive DingTalk directory record used by
// DobotAI. It deliberately excludes mobile, email, credentials and raw payloads.
type Profile struct {
StaffID string
UnionID string
Name string
Nickname string
JobTitle string
DepartmentIDs []string
DepartmentName string
MainDepartmentName string
Region string
EmploymentStatus string
Source string
SyncedAt time.Time
}
type SnapshotWriter interface {
UpsertDirectoryProfiles(ctx context.Context, tenantKey string, profiles []Profile) error
}
+65
View File
@@ -0,0 +1,65 @@
package directory
import (
"context"
"errors"
"strings"
"time"
)
type ProfileStore interface {
LookupDirectoryProfile(ctx context.Context, tenantKey, staffID string) (Profile, bool, error)
UpsertDirectoryProfiles(ctx context.Context, tenantKey string, profiles []Profile) error
}
type UserLookup interface {
LookupUser(ctx context.Context, staffID string) (Profile, error)
}
type Resolver struct {
store ProfileStore
lookup UserLookup
now func() time.Time
}
func NewResolver(store ProfileStore, lookup UserLookup) (*Resolver, error) {
if store == nil {
return nil, errors.New("directory profile store is required")
}
return &Resolver{store: store, lookup: lookup, now: time.Now}, nil
}
// ResolveUser always returns a safe callback-based fallback profile when the
// cache or on-demand lookup is unavailable. The diagnostic error is intentionally
// generic so identifiers and upstream payloads cannot leak into logs.
func (r *Resolver) ResolveUser(ctx context.Context, tenantKey, staffID, fallbackName string) (Profile, error) {
fallback := Profile{StaffID: strings.TrimSpace(staffID), Name: strings.TrimSpace(fallbackName)}
profile, found, err := r.store.LookupDirectoryProfile(ctx, tenantKey, fallback.StaffID)
if err != nil {
return fallback, errors.New("directory local lookup failed")
}
if found && strings.TrimSpace(profile.Name) != "" {
profile.Name = strings.TrimSpace(profile.Name)
return profile, nil
}
if r.lookup == nil {
return fallback, nil
}
profile, err = r.lookup.LookupUser(ctx, fallback.StaffID)
if err != nil {
return fallback, errors.New("directory on-demand lookup failed")
}
profile.StaffID = fallback.StaffID
profile.Name = strings.TrimSpace(profile.Name)
if profile.Name == "" {
return fallback, errors.New("directory on-demand lookup returned no name")
}
profile.Source = SourceOnDemand
if profile.SyncedAt.IsZero() {
profile.SyncedAt = r.now().UTC()
}
if err := r.store.UpsertDirectoryProfiles(ctx, tenantKey, []Profile{profile}); err != nil {
return profile, errors.New("directory on-demand cache write failed")
}
return profile, nil
}
+93
View File
@@ -0,0 +1,93 @@
package directory
import (
"context"
"errors"
"testing"
)
type fakeStore struct {
profile Profile
found bool
readErr error
writeErr error
writes int
}
func (s *fakeStore) LookupDirectoryProfile(context.Context, string, string) (Profile, bool, error) {
return s.profile, s.found, s.readErr
}
func (s *fakeStore) UpsertDirectoryProfiles(_ context.Context, _ string, profiles []Profile) error {
s.writes++
if len(profiles) > 0 {
s.profile = profiles[0]
}
return s.writeErr
}
type fakeLookup struct {
profile Profile
err error
calls int
}
func (l *fakeLookup) LookupUser(context.Context, string) (Profile, error) {
l.calls++
return l.profile, l.err
}
func TestResolverUsesLocalProfileWithoutRemoteLookup(t *testing.T) {
store := &fakeStore{profile: Profile{StaffID: "staff-1", Name: "张三", DepartmentName: "技术支持部", Region: "APAC"}, found: true}
lookup := &fakeLookup{}
resolver, err := NewResolver(store, lookup)
if err != nil { t.Fatal(err) }
profile, err := resolver.ResolveUser(context.Background(), "tenant-a", "staff-1", "昵称")
if err != nil { t.Fatalf("ResolveUser: %v", err) }
if profile.Name != "张三" || lookup.calls != 0 || store.writes != 0 {
t.Fatalf("profile=%+v lookup=%d writes=%d", profile, lookup.calls, store.writes)
}
}
func TestResolverLooksUpAndCachesMissingUser(t *testing.T) {
store := &fakeStore{}
lookup := &fakeLookup{profile: Profile{Name: "李四", DepartmentName: "销售部", Region: "EMEA"}}
resolver, err := NewResolver(store, lookup)
if err != nil { t.Fatal(err) }
profile, err := resolver.ResolveUser(context.Background(), "tenant-a", "staff-2", "昵称")
if err != nil { t.Fatalf("ResolveUser: %v", err) }
if profile.StaffID != "staff-2" || profile.Name != "李四" || profile.Source != SourceOnDemand || lookup.calls != 1 || store.writes != 1 {
t.Fatalf("profile=%+v lookup=%d writes=%d", profile, lookup.calls, store.writes)
}
}
func TestResolverFallsBackWithoutBlockingOnFailures(t *testing.T) {
tests := []struct{
name string
store *fakeStore
lookup *fakeLookup
}{
{name: "local read fails", store: &fakeStore{readErr: errors.New("db unavailable")}, lookup: &fakeLookup{}},
{name: "remote lookup fails", store: &fakeStore{}, lookup: &fakeLookup{err: errors.New("remote unavailable")}},
{name: "cache write fails but resolved profile survives", store: &fakeStore{writeErr: errors.New("db unavailable")}, lookup: &fakeLookup{profile: Profile{Name: "王五"}}},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
resolver, err := NewResolver(tt.store, tt.lookup)
if err != nil { t.Fatal(err) }
profile, resolveErr := resolver.ResolveUser(context.Background(), "tenant-a", "staff-3", " 回调昵称 ")
if profile.Name == "" { t.Fatalf("empty fallback profile: %+v", profile) }
if tt.name != "cache write fails but resolved profile survives" && profile.Name != "回调昵称" {
t.Fatalf("profile name=%q, want fallback", profile.Name)
}
if resolveErr == nil { t.Fatal("expected diagnostic error") }
})
}
}
func TestResolverWithoutRemoteUsesFallback(t *testing.T) {
resolver, err := NewResolver(&fakeStore{}, nil)
if err != nil { t.Fatal(err) }
profile, err := resolver.ResolveUser(context.Background(), "tenant-a", "staff-4", "赵六")
if err != nil || profile.Name != "赵六" || profile.StaffID != "staff-4" {
t.Fatalf("profile=%+v err=%v", profile, err)
}
}