mirror of
https://github.com/larksuite/cli.git
synced 2026-07-06 16:18:05 +08:00
Compare commits
1 Commits
fix/minute
...
codex/insp
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
b54abe817c |
@@ -23,7 +23,7 @@ func FetchDriveMeta(runtime *RuntimeContext, token, docType string, withURL bool
|
||||
body["with_url"] = true
|
||||
}
|
||||
|
||||
data, err := runtime.CallAPI(
|
||||
data, err := runtime.CallAPITyped(
|
||||
"POST",
|
||||
"/open-apis/drive/v1/metas/batch_query",
|
||||
nil,
|
||||
|
||||
@@ -10,6 +10,7 @@ import (
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
|
||||
"github.com/larksuite/cli/errs"
|
||||
"github.com/larksuite/cli/internal/cmdutil"
|
||||
"github.com/larksuite/cli/internal/core"
|
||||
"github.com/larksuite/cli/internal/httpmock"
|
||||
@@ -103,6 +104,13 @@ func TestFetchDriveMetaTitle(t *testing.T) {
|
||||
if err == nil {
|
||||
t.Fatal("FetchDriveMetaTitle() expected error, got nil")
|
||||
}
|
||||
p, ok := errs.ProblemOf(err)
|
||||
if !ok {
|
||||
t.Fatalf("expected typed error, got %T", err)
|
||||
}
|
||||
if p.Code != 99991668 {
|
||||
t.Fatalf("code = %d, want 99991668", p.Code)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
|
||||
@@ -8,11 +8,19 @@ import (
|
||||
"fmt"
|
||||
"io"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/larksuite/cli/errs"
|
||||
"github.com/larksuite/cli/shortcuts/common"
|
||||
)
|
||||
|
||||
const (
|
||||
driveInspectRateLimitRetries = 2
|
||||
driveInspectRetryInitialBackoff = 200 * time.Millisecond
|
||||
)
|
||||
|
||||
var driveInspectAfter = time.After
|
||||
|
||||
var DriveInspect = common.Shortcut{
|
||||
Service: "drive",
|
||||
Command: "+inspect",
|
||||
@@ -35,32 +43,15 @@ var DriveInspect = common.Shortcut{
|
||||
},
|
||||
},
|
||||
Validate: func(ctx context.Context, runtime *common.RuntimeContext) error {
|
||||
raw := strings.TrimSpace(runtime.Str("url"))
|
||||
if raw == "" {
|
||||
return errs.NewValidationError(errs.SubtypeInvalidArgument, "--url cannot be empty").WithParam("--url")
|
||||
}
|
||||
|
||||
_, ok := common.ParseResourceURL(raw)
|
||||
if !ok {
|
||||
// Not a recognized URL pattern.
|
||||
if strings.Contains(raw, "://") {
|
||||
return errs.NewValidationError(errs.SubtypeInvalidArgument, "unsupported --url %q: use a recognized Lark document URL or a bare token with --type", raw).WithParam("--url")
|
||||
}
|
||||
// Bare token: --type is required.
|
||||
if strings.TrimSpace(runtime.Str("type")) == "" {
|
||||
return errs.NewValidationError(errs.SubtypeInvalidArgument, "--type is required when --url is a bare token (allowed: doc, docx, sheet, bitable, wiki, file, folder, mindnote, slides)").WithParam("--type")
|
||||
}
|
||||
if _, err := driveInspectResolveRef(runtime); err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
},
|
||||
DryRun: func(ctx context.Context, runtime *common.RuntimeContext) *common.DryRunAPI {
|
||||
raw := strings.TrimSpace(runtime.Str("url"))
|
||||
ref, ok := common.ParseResourceURL(raw)
|
||||
if !ok {
|
||||
ref = common.ResourceRef{
|
||||
Type: strings.TrimSpace(runtime.Str("type")),
|
||||
Token: raw,
|
||||
}
|
||||
ref, err := driveInspectResolveRef(runtime)
|
||||
if err != nil {
|
||||
return common.NewDryRunAPI()
|
||||
}
|
||||
|
||||
dry := common.NewDryRunAPI()
|
||||
@@ -91,15 +82,9 @@ var DriveInspect = common.Shortcut{
|
||||
},
|
||||
Execute: func(ctx context.Context, runtime *common.RuntimeContext) error {
|
||||
raw := strings.TrimSpace(runtime.Str("url"))
|
||||
|
||||
// Step 1: Parse URL to extract {type, token}.
|
||||
ref, ok := common.ParseResourceURL(raw)
|
||||
if !ok {
|
||||
// Bare token: use --type.
|
||||
ref = common.ResourceRef{
|
||||
Type: strings.TrimSpace(runtime.Str("type")),
|
||||
Token: raw,
|
||||
}
|
||||
ref, err := driveInspectResolveRef(runtime)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
inputURL := raw
|
||||
@@ -111,14 +96,19 @@ var DriveInspect = common.Shortcut{
|
||||
// Step 2: If type is "wiki", unwrap via get_node API.
|
||||
if docType == "wiki" {
|
||||
fmt.Fprintf(runtime.IO().ErrOut, "Inspecting wiki node: %s\n", common.MaskToken(docToken))
|
||||
data, err := runtime.CallAPITyped(
|
||||
"GET",
|
||||
"/open-apis/wiki/v2/spaces/get_node",
|
||||
map[string]interface{}{"token": docToken},
|
||||
nil,
|
||||
data, err := driveInspectCallWithRetry(
|
||||
ctx,
|
||||
func() (map[string]interface{}, error) {
|
||||
return runtime.CallAPITyped(
|
||||
"GET",
|
||||
"/open-apis/wiki/v2/spaces/get_node",
|
||||
map[string]interface{}{"token": docToken},
|
||||
nil,
|
||||
)
|
||||
},
|
||||
)
|
||||
if err != nil {
|
||||
return err
|
||||
return driveInspectAnnotateError("resolve_wiki", err)
|
||||
}
|
||||
|
||||
node := common.GetMap(data, "node")
|
||||
@@ -145,9 +135,9 @@ var DriveInspect = common.Shortcut{
|
||||
}
|
||||
|
||||
// Step 3: Call batch_query to verify and get title.
|
||||
title, err := common.FetchDriveMetaTitle(runtime, docToken, docType)
|
||||
title, err := driveInspectFetchMetaTitle(ctx, runtime, docToken, docType)
|
||||
if err != nil {
|
||||
return err
|
||||
return driveInspectAnnotateError("query_meta", err)
|
||||
}
|
||||
|
||||
// Step 4: Build the resolved URL.
|
||||
@@ -181,3 +171,116 @@ var DriveInspect = common.Shortcut{
|
||||
return nil
|
||||
},
|
||||
}
|
||||
|
||||
func driveInspectResolveRef(runtime *common.RuntimeContext) (common.ResourceRef, error) {
|
||||
raw := strings.TrimSpace(runtime.Str("url"))
|
||||
if raw == "" {
|
||||
return common.ResourceRef{}, errs.NewValidationError(errs.SubtypeInvalidArgument, "--url cannot be empty").WithParam("--url")
|
||||
}
|
||||
|
||||
inputType := strings.ToLower(strings.TrimSpace(runtime.Str("type")))
|
||||
ref, ok := common.ParseResourceURL(raw)
|
||||
if ok {
|
||||
if inputType != "" && inputType != ref.Type {
|
||||
return common.ResourceRef{}, errs.NewValidationError(
|
||||
errs.SubtypeInvalidArgument,
|
||||
"--type %q conflicts with URL path type %q; remove --type or use a matching value",
|
||||
inputType,
|
||||
ref.Type,
|
||||
).WithParam("--type")
|
||||
}
|
||||
return ref, nil
|
||||
}
|
||||
|
||||
if strings.Contains(raw, "://") {
|
||||
return common.ResourceRef{}, errs.NewValidationError(errs.SubtypeInvalidArgument, "unsupported --url %q: use a recognized Lark document URL or a bare token with --type", raw).WithParam("--url")
|
||||
}
|
||||
if strings.ContainsAny(raw, "/?#") {
|
||||
return common.ResourceRef{}, errs.NewValidationError(errs.SubtypeInvalidArgument, "invalid bare token %q: remove path/query fragments and pass only the raw token with --type", raw).WithParam("--url")
|
||||
}
|
||||
if inputType == "" {
|
||||
return common.ResourceRef{}, errs.NewValidationError(errs.SubtypeInvalidArgument, "--type is required when --url is a bare token (allowed: doc, docx, sheet, bitable, wiki, file, folder, mindnote, slides)").WithParam("--type")
|
||||
}
|
||||
return common.ResourceRef{Type: inputType, Token: raw}, nil
|
||||
}
|
||||
|
||||
func driveInspectFetchMetaTitle(ctx context.Context, runtime *common.RuntimeContext, token, docType string) (string, error) {
|
||||
var title string
|
||||
_, err := driveInspectCallWithRetry(ctx, func() (map[string]interface{}, error) {
|
||||
got, callErr := common.FetchDriveMeta(runtime, token, docType, false)
|
||||
if callErr != nil {
|
||||
return nil, callErr
|
||||
}
|
||||
title = got.Title
|
||||
return map[string]interface{}{"title": got.Title}, nil
|
||||
})
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
return title, nil
|
||||
}
|
||||
|
||||
func driveInspectCallWithRetry(ctx context.Context, call func() (map[string]interface{}, error)) (map[string]interface{}, error) {
|
||||
var lastErr error
|
||||
for attempt := 0; attempt <= driveInspectRateLimitRetries; attempt++ {
|
||||
data, err := call()
|
||||
if err == nil {
|
||||
return data, nil
|
||||
}
|
||||
lastErr = err
|
||||
if !driveInspectShouldRetry(err) || attempt == driveInspectRateLimitRetries {
|
||||
return nil, err
|
||||
}
|
||||
backoff := driveInspectRetryInitialBackoff * time.Duration(1<<attempt)
|
||||
if waitErr := driveInspectWait(ctx, backoff); waitErr != nil {
|
||||
return nil, waitErr
|
||||
}
|
||||
}
|
||||
return nil, lastErr
|
||||
}
|
||||
|
||||
func driveInspectShouldRetry(err error) bool {
|
||||
problem, ok := errs.ProblemOf(err)
|
||||
if !ok || problem == nil {
|
||||
return false
|
||||
}
|
||||
return problem.Subtype == errs.SubtypeRateLimit || problem.Code == 99991400 || problem.Retryable
|
||||
}
|
||||
|
||||
func driveInspectWait(ctx context.Context, d time.Duration) error {
|
||||
if d <= 0 {
|
||||
return nil
|
||||
}
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return errs.WrapInternal(ctx.Err())
|
||||
case <-driveInspectAfter(d):
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
func driveInspectAnnotateError(stage string, err error) error {
|
||||
problem, ok := errs.ProblemOf(err)
|
||||
if !ok || problem == nil {
|
||||
return err
|
||||
}
|
||||
label := map[string]string{
|
||||
"resolve_wiki": "resolve wiki node",
|
||||
"query_meta": "query document metadata",
|
||||
}[stage]
|
||||
if label == "" {
|
||||
label = stage
|
||||
}
|
||||
problem.Message = fmt.Sprintf("%s failed: %s", label, problem.Message)
|
||||
if strings.TrimSpace(problem.Hint) == "" {
|
||||
switch stage {
|
||||
case "resolve_wiki":
|
||||
problem.Hint = "check that the wiki URL/token is valid and that the current identity can read the wiki node"
|
||||
case "query_meta":
|
||||
problem.Hint = "check that the resolved document still exists and that the current identity can read its metadata"
|
||||
}
|
||||
} else if !strings.Contains(problem.Hint, label) {
|
||||
problem.Hint = label + ": " + problem.Hint
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
@@ -6,10 +6,13 @@ package drive
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
|
||||
"github.com/larksuite/cli/errs"
|
||||
"github.com/larksuite/cli/internal/cmdutil"
|
||||
"github.com/larksuite/cli/internal/core"
|
||||
"github.com/larksuite/cli/internal/httpmock"
|
||||
@@ -83,6 +86,34 @@ func TestDriveInspectValidate_BareTokenWithType(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestDriveInspectValidate_URLTypeConflict(t *testing.T) {
|
||||
cmd := &cobra.Command{Use: "drive +inspect"}
|
||||
cmd.Flags().String("url", "", "")
|
||||
cmd.Flags().String("type", "", "")
|
||||
_ = cmd.Flags().Set("url", "https://xxx.feishu.cn/docx/doxcnBareToken")
|
||||
_ = cmd.Flags().Set("type", "sheet")
|
||||
|
||||
runtime := common.TestNewRuntimeContext(cmd, &core.CliConfig{})
|
||||
err := DriveInspect.Validate(context.Background(), runtime)
|
||||
if err == nil {
|
||||
t.Fatal("expected error for conflicting --type, got nil")
|
||||
}
|
||||
}
|
||||
|
||||
func TestDriveInspectValidate_BareTokenWithPathFragment(t *testing.T) {
|
||||
cmd := &cobra.Command{Use: "drive +inspect"}
|
||||
cmd.Flags().String("url", "", "")
|
||||
cmd.Flags().String("type", "", "")
|
||||
_ = cmd.Flags().Set("url", "doxcnBareToken/extra")
|
||||
_ = cmd.Flags().Set("type", "docx")
|
||||
|
||||
runtime := common.TestNewRuntimeContext(cmd, &core.CliConfig{})
|
||||
err := DriveInspect.Validate(context.Background(), runtime)
|
||||
if err == nil {
|
||||
t.Fatal("expected error for bare token with path fragment, got nil")
|
||||
}
|
||||
}
|
||||
|
||||
func TestDriveInspectValidate_ValidDocxURL(t *testing.T) {
|
||||
cmd := &cobra.Command{Use: "drive +inspect"}
|
||||
cmd.Flags().String("url", "", "")
|
||||
@@ -540,6 +571,76 @@ func TestDriveInspectExecute_BatchQueryError(t *testing.T) {
|
||||
if err == nil {
|
||||
t.Fatal("expected error for batch_query failure, got nil")
|
||||
}
|
||||
p, ok := errs.ProblemOf(err)
|
||||
if !ok {
|
||||
t.Fatalf("expected typed error, got %T", err)
|
||||
}
|
||||
if !strings.Contains(p.Message, "query document metadata failed") {
|
||||
t.Fatalf("message = %q, want query document metadata prefix", p.Message)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDriveInspectExecute_RetriesRateLimitOnWikiResolve(t *testing.T) {
|
||||
cfg := driveTestConfig()
|
||||
f, stdout, _, reg := cmdutil.TestFactory(t, cfg)
|
||||
|
||||
reg.Register(&httpmock.Stub{
|
||||
Method: "GET",
|
||||
URL: "/open-apis/wiki/v2/spaces/get_node",
|
||||
Body: map[string]interface{}{
|
||||
"code": 99991400,
|
||||
"msg": "request trigger frequency limit",
|
||||
},
|
||||
})
|
||||
reg.Register(&httpmock.Stub{
|
||||
Method: "GET",
|
||||
URL: "/open-apis/wiki/v2/spaces/get_node",
|
||||
Body: map[string]interface{}{
|
||||
"code": 0,
|
||||
"data": map[string]interface{}{
|
||||
"node": map[string]interface{}{
|
||||
"obj_type": "docx",
|
||||
"obj_token": "doxcnUnwrapped",
|
||||
"space_id": "space123",
|
||||
"node_token": "wikcnNodeToken",
|
||||
},
|
||||
},
|
||||
},
|
||||
})
|
||||
reg.Register(&httpmock.Stub{
|
||||
Method: "POST",
|
||||
URL: "/open-apis/drive/v1/metas/batch_query",
|
||||
Body: map[string]interface{}{
|
||||
"code": 0,
|
||||
"data": map[string]interface{}{
|
||||
"metas": []map[string]interface{}{
|
||||
{"doc_token": "doxcnUnwrapped", "doc_type": "docx", "title": "Wiki Doc"},
|
||||
},
|
||||
},
|
||||
},
|
||||
})
|
||||
|
||||
origAfter := driveInspectAfter
|
||||
driveInspectAfter = func(time.Duration) <-chan time.Time {
|
||||
ch := make(chan time.Time, 1)
|
||||
ch <- time.Now()
|
||||
return ch
|
||||
}
|
||||
defer func() { driveInspectAfter = origAfter }()
|
||||
|
||||
err := mountAndRunDrive(t, DriveInspect, []string{
|
||||
"+inspect",
|
||||
"--url", "https://xxx.feishu.cn/wiki/wikcnABC",
|
||||
"--as", "bot",
|
||||
}, f, stdout)
|
||||
if err != nil {
|
||||
t.Fatalf("unexpected error after retry: %v", err)
|
||||
}
|
||||
|
||||
data := decodeDriveEnvelope(t, stdout)
|
||||
if data["token"] != "doxcnUnwrapped" {
|
||||
t.Fatalf("token = %v, want doxcnUnwrapped", data["token"])
|
||||
}
|
||||
}
|
||||
|
||||
func TestDriveInspectExecute_PrettyFormat(t *testing.T) {
|
||||
|
||||
@@ -80,11 +80,6 @@ var MinutesDownload = common.Shortcut{
|
||||
if err := common.ValidateSafePathTyped(runtime.FileIO(), outDir); err != nil {
|
||||
return err
|
||||
}
|
||||
if fi, statErr := runtime.FileIO().Stat(outDir); statErr == nil && !fi.IsDir() {
|
||||
return errs.NewValidationError(errs.SubtypeInvalidArgument, "--output-dir %q must be a directory", outDir).WithParam("--output-dir")
|
||||
} else if statErr != nil && !errors.Is(statErr, fs.ErrNotExist) {
|
||||
return errs.NewInternalError(errs.SubtypeFileIO, "cannot access --output-dir %q: %s", outDir, statErr).WithCause(statErr)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
},
|
||||
|
||||
@@ -588,34 +588,6 @@ func TestDownload_OutputDirFlag_SingleToken(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestDownload_Validation_OutputDirIsExistingFile(t *testing.T) {
|
||||
chdir(t, t.TempDir())
|
||||
if err := os.WriteFile("not-a-dir", []byte("x"), 0644); err != nil {
|
||||
t.Fatalf("setup: %v", err)
|
||||
}
|
||||
|
||||
f, _, _, _ := cmdutil.TestFactory(t, defaultConfig())
|
||||
err := mountAndRun(t, MinutesDownload, []string{
|
||||
"+download", "--minute-tokens", "tok001", "--output-dir", "not-a-dir", "--as", "user",
|
||||
}, f, nil)
|
||||
if err == nil {
|
||||
t.Fatal("expected validation error for --output-dir pointing at a file")
|
||||
}
|
||||
var ve *errs.ValidationError
|
||||
if !errors.As(err, &ve) {
|
||||
t.Fatalf("expected *errs.ValidationError, got %T: %v", err, err)
|
||||
}
|
||||
if ve.Subtype != errs.SubtypeInvalidArgument {
|
||||
t.Errorf("Subtype = %q, want %q", ve.Subtype, errs.SubtypeInvalidArgument)
|
||||
}
|
||||
if ve.Param != "--output-dir" {
|
||||
t.Errorf("Param = %q, want --output-dir", ve.Param)
|
||||
}
|
||||
if !strings.Contains(err.Error(), "must be a directory") {
|
||||
t.Errorf("expected directory validation message, got: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDownload_Batch_OutputNonExistentPath(t *testing.T) {
|
||||
// Batch mode with --output pointing at a path that doesn't exist yet:
|
||||
// auto-upgrade to --output-dir semantics and create the directory.
|
||||
|
||||
@@ -76,11 +76,9 @@ func minutesReadError(err error, minuteToken string) error {
|
||||
if !ok || p.Code != minutesNoReadPermissionCode {
|
||||
return err
|
||||
}
|
||||
return errs.NewPermissionError(errs.SubtypePermissionDenied,
|
||||
"No read permission for minute %s: cannot query the minute.", minuteToken).
|
||||
WithCode(minutesNoReadPermissionCode).
|
||||
WithHint("Ask the minute owner for minute file read permission").
|
||||
WithCause(err)
|
||||
p.Message = fmt.Sprintf("No read permission for minute %s: cannot query the minute.", minuteToken)
|
||||
p.Hint = "Ask the minute owner for minute file read permission"
|
||||
return err
|
||||
}
|
||||
|
||||
// validMinuteToken matches the server's minute-token format and blocks any
|
||||
@@ -369,28 +367,18 @@ func joinErrors(msgs ...string) string {
|
||||
return strings.Join(parts, "; ")
|
||||
}
|
||||
|
||||
// hasNotesPayload reports whether a result map carries usable note or minute
|
||||
// payload. An echoed --minute-tokens input alone is not treated as payload when
|
||||
// that item also carries an error; a meeting/calendar-derived minute_token is.
|
||||
// hasNotesPayload reports whether a result map carries any usable note or
|
||||
// minute payload, irrespective of partial failures surfaced via `error`.
|
||||
func hasNotesPayload(m map[string]any) bool {
|
||||
if m == nil {
|
||||
return false
|
||||
}
|
||||
for _, k := range []string{"note_doc_token", "verbatim_doc_token", "meeting_notes", "shared_doc_tokens", "artifacts"} {
|
||||
for _, k := range []string{"note_doc_token", "verbatim_doc_token", "minute_token", "meeting_notes", "shared_doc_tokens", "artifacts"} {
|
||||
if v, ok := m[k]; ok && v != nil && v != "" {
|
||||
return true
|
||||
}
|
||||
}
|
||||
minuteToken, _ := m["minute_token"].(string)
|
||||
if minuteToken == "" {
|
||||
return false
|
||||
}
|
||||
if errMsg, _ := m["error"].(string); errMsg == "" {
|
||||
return true
|
||||
}
|
||||
_, fromMeeting := m["meeting_id"]
|
||||
_, fromCalendarEvent := m["calendar_event_id"]
|
||||
return fromMeeting || fromCalendarEvent
|
||||
return false
|
||||
}
|
||||
|
||||
// fetchNoteByMinuteToken queries notes via minute_token.
|
||||
|
||||
@@ -1219,38 +1219,29 @@ func minuteGetErrStub(token string, code int, msg string) *httpmock.Stub {
|
||||
}
|
||||
}
|
||||
|
||||
// TestMinutesReadError_AllFailed_OutPartialFailure verifies that a failing
|
||||
// minute-token lookup is treated as a failed item even though the result keeps
|
||||
// the input minute_token for caller correlation.
|
||||
func TestMinutesReadError_AllFailed_OutPartialFailure(t *testing.T) {
|
||||
// TestMinutesReadError_ProblemOf_EnrichesMessage pins that minutesReadError
|
||||
// mutates the typed error's Message and Hint in-place via errs.ProblemOf when
|
||||
// the server returns code 2091005 (minutes no-read-permission).
|
||||
func TestMinutesReadError_ProblemOf_EnrichesMessage(t *testing.T) {
|
||||
t.Setenv("LARKSUITE_CLI_CONFIG_DIR", t.TempDir())
|
||||
f, stdout, _, reg := cmdutil.TestFactory(t, defaultConfig())
|
||||
reg.Register(minuteGetErrStub("tokperm", minutesNoReadPermissionCode, "no permission"))
|
||||
// artifactsStub not needed: we never reach it on error
|
||||
|
||||
err := mountAndRun(t, VCNotes, []string{"+notes", "--minute-tokens", "tokperm", "--as", "user"}, f, stdout)
|
||||
if err == nil {
|
||||
t.Fatal("expected all-failed minute-token query to return an error")
|
||||
}
|
||||
var pfErr *output.PartialFailureError
|
||||
if !errors.As(err, &pfErr) {
|
||||
t.Fatalf("expected *output.PartialFailureError, got %T: %v", err, err)
|
||||
}
|
||||
if pfErr.Code != output.ExitAPI {
|
||||
t.Errorf("PartialFailureError.Code = %d, want ExitAPI (%d)", pfErr.Code, output.ExitAPI)
|
||||
// A single minute-token that fails on a no-read-permission code still
|
||||
// produces a note carrying minute_token, so the batch exits 0 with the
|
||||
// enriched error surfaced inline rather than becoming an all-fail.
|
||||
if err := mountAndRun(t, VCNotes, []string{"+notes", "--minute-tokens", "tokperm", "--as", "user"}, f, stdout); err != nil {
|
||||
t.Fatalf("unexpected error: %v", err)
|
||||
}
|
||||
|
||||
var resp struct {
|
||||
OK bool `json:"ok"`
|
||||
Data map[string]any `json:"data"`
|
||||
}
|
||||
// stdout carries the note with the enriched error/hint
|
||||
var resp map[string]any
|
||||
if parseErr := json.Unmarshal(stdout.Bytes(), &resp); parseErr != nil {
|
||||
t.Fatalf("unmarshal stdout: %v\n%s", parseErr, stdout.String())
|
||||
}
|
||||
if resp.OK {
|
||||
t.Errorf("ok must be false on all-failed minute-token query, got ok:true")
|
||||
}
|
||||
notes, _ := resp.Data["notes"].([]any)
|
||||
data, _ := resp["data"].(map[string]any)
|
||||
notes, _ := data["notes"].([]any)
|
||||
if len(notes) != 1 {
|
||||
t.Fatalf("expected 1 note, got %d", len(notes))
|
||||
}
|
||||
|
||||
@@ -20,7 +20,6 @@ import (
|
||||
|
||||
"github.com/larksuite/cli/errs"
|
||||
"github.com/larksuite/cli/internal/auth"
|
||||
"github.com/larksuite/cli/internal/credential"
|
||||
"github.com/larksuite/cli/internal/output"
|
||||
"github.com/larksuite/cli/internal/validate"
|
||||
"github.com/larksuite/cli/shortcuts/common"
|
||||
@@ -98,7 +97,7 @@ var VCRecording = common.Shortcut{
|
||||
{Name: "meeting-ids", Desc: "meeting IDs, comma-separated for batch"},
|
||||
{Name: "calendar-event-ids", Desc: "calendar event instance IDs, comma-separated for batch"},
|
||||
},
|
||||
Validate: func(ctx context.Context, runtime *common.RuntimeContext) error {
|
||||
Validate: func(_ context.Context, runtime *common.RuntimeContext) error {
|
||||
if err := common.ExactlyOneTyped(runtime, "meeting-ids", "calendar-event-ids"); err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -117,14 +116,18 @@ var VCRecording = common.Shortcut{
|
||||
case runtime.Str("calendar-event-ids") != "":
|
||||
required = scopesRecordingCalendarEventIDs
|
||||
}
|
||||
result, err := runtime.Factory.Credential.ResolveToken(ctx, credential.NewTokenSpec(runtime.As(), runtime.Config.AppID))
|
||||
if err == nil && result != nil && result.Scopes != "" {
|
||||
if missing := auth.MissingScopes(result.Scopes, required); len(missing) > 0 {
|
||||
return errs.NewPermissionError(errs.SubtypeMissingScope,
|
||||
"missing required scope(s): %s", strings.Join(missing, ", ")).
|
||||
WithHint("run `lark-cli auth login --scope %q` in the background. It blocks and outputs a verification URL — retrieve the URL and open it in a browser to complete login.", strings.Join(missing, " ")).
|
||||
WithMissingScopes(missing...).
|
||||
WithIdentity(string(runtime.As()))
|
||||
appID := runtime.Config.AppID
|
||||
userOpenID := runtime.UserOpenId()
|
||||
if appID != "" && userOpenID != "" {
|
||||
stored := auth.GetStoredToken(appID, userOpenID)
|
||||
if stored != nil {
|
||||
if missing := auth.MissingScopes(stored.Scope, required); len(missing) > 0 {
|
||||
return errs.NewPermissionError(errs.SubtypeMissingScope,
|
||||
"missing required scope(s): %s", strings.Join(missing, ", ")).
|
||||
WithHint("run `lark-cli auth login --scope %q` in the background. It blocks and outputs a verification URL — retrieve the URL and open it in a browser to complete login.", strings.Join(missing, " ")).
|
||||
WithMissingScopes(missing...).
|
||||
WithIdentity(string(runtime.As()))
|
||||
}
|
||||
}
|
||||
}
|
||||
return nil
|
||||
|
||||
@@ -10,25 +10,19 @@ import (
|
||||
"fmt"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
keyring "github.com/zalando/go-keyring"
|
||||
|
||||
"github.com/larksuite/cli/errs"
|
||||
"github.com/larksuite/cli/internal/auth"
|
||||
"github.com/larksuite/cli/internal/cmdutil"
|
||||
"github.com/larksuite/cli/internal/credential"
|
||||
"github.com/larksuite/cli/internal/httpmock"
|
||||
"github.com/larksuite/cli/internal/output"
|
||||
"github.com/larksuite/cli/shortcuts/common"
|
||||
)
|
||||
|
||||
type recordingScopeTokenResolver struct {
|
||||
scopes string
|
||||
}
|
||||
|
||||
func (r recordingScopeTokenResolver) ResolveToken(context.Context, credential.TokenSpec) (*credential.TokenResult, error) {
|
||||
return &credential.TokenResult{Token: "test-token", Scopes: r.scopes}, nil
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Unit tests: extractMinuteToken
|
||||
// ---------------------------------------------------------------------------
|
||||
@@ -147,12 +141,27 @@ func TestRecording_BatchLimit_CalendarEventIDs(t *testing.T) {
|
||||
}
|
||||
|
||||
func TestRecording_Validate_MissingScope(t *testing.T) {
|
||||
cfg := defaultConfig()
|
||||
f, _, _, _ := cmdutil.TestFactory(t, cfg)
|
||||
f.Credential = credential.NewCredentialProvider(nil, nil, recordingScopeTokenResolver{
|
||||
scopes: "calendar:calendar:read",
|
||||
}, nil)
|
||||
keyring.MockInit() // use in-memory keyring to avoid macOS keychain popups
|
||||
t.Setenv("HOME", t.TempDir())
|
||||
|
||||
cfg := defaultConfig()
|
||||
// Store a token that intentionally lacks the vc:record:readonly scope.
|
||||
token := &auth.StoredUAToken{
|
||||
UserOpenId: cfg.UserOpenId,
|
||||
AppId: cfg.AppID,
|
||||
AccessToken: "test-user-access-token",
|
||||
RefreshToken: "test-refresh-token",
|
||||
ExpiresAt: time.Now().Add(1 * time.Hour).UnixMilli(),
|
||||
RefreshExpiresAt: time.Now().Add(24 * time.Hour).UnixMilli(),
|
||||
Scope: "calendar:calendar:read",
|
||||
GrantedAt: time.Now().Add(-1 * time.Hour).UnixMilli(),
|
||||
}
|
||||
if err := auth.SetStoredToken(token); err != nil {
|
||||
t.Fatalf("SetStoredToken() error = %v", err)
|
||||
}
|
||||
t.Cleanup(func() { _ = auth.RemoveStoredToken(cfg.AppID, cfg.UserOpenId) })
|
||||
|
||||
f, _, _, _ := cmdutil.TestFactory(t, cfg)
|
||||
err := mountAndRun(t, VCRecording, []string{"+recording", "--meeting-ids", "m001", "--as", "user"}, f, nil)
|
||||
if err == nil {
|
||||
t.Fatal("expected missing_scope error, got nil")
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
---
|
||||
name: lark-slides
|
||||
version: 1.0.0
|
||||
description: "飞书幻灯片:创建和编辑幻灯片。创建演示文稿、读取幻灯片内容、管理幻灯片页面(创建、删除、读取、局部替换)。当用户需要创建或编辑幻灯片、读取或修改单个页面时使用。当用户给出 doubao.com 的 /slides/ URL/token 时,也应直接使用本 skill,不要因为域名不是飞书而回退到 WebFetch;路由依据是 URL 路径模式和 token,而不是域名。不负责:云文档内容编辑(走 lark-doc)、云文档里的独立画板对象(走 lark-whiteboard,注意 slide 内嵌的流程图/架构图仍属本 skill)、上传或下载普通文件(走 lark-drive)。"
|
||||
description: "飞书幻灯片:创建和编辑幻灯片,接口通过 XML 协议通信。创建演示文稿、读取幻灯片内容、管理幻灯片页面(创建、删除、读取、局部替换)。当用户需要创建或编辑幻灯片、读取或修改单个页面时使用。当用户给出 doubao.com 的 /slides/ URL/token 时,也应直接使用本 skill,不要因为域名不是飞书而回退到 WebFetch;路由依据是 URL 路径模式和 token,而不是域名。"
|
||||
metadata:
|
||||
requires:
|
||||
bins: ["lark-cli"]
|
||||
@@ -25,7 +25,7 @@ metadata:
|
||||
| 用户提到模板、主题、版式 | 先检索模板,再摘要,必要时裁切骨架 | `template_tool.py search → summarize → extract` |
|
||||
| 创建失败、空白页、3350001、布局异常 | 先回读状态,再按排障清单修复,不假设原操作原子成功 | `troubleshooting.md`、`validation-checklist.md` |
|
||||
|
||||
**CRITICAL — 开始前 MUST 先用 Read 工具读取 [`../lark-shared/SKILL.md`](../lark-shared/SKILL.md),认证、权限和全局参数均以 lark-shared 为准。**
|
||||
**CRITICAL — 开始前 MUST 先用 Read 工具读取 [`../lark-shared/SKILL.md`](../lark-shared/SKILL.md),其中包含认证、权限处理**
|
||||
|
||||
**CRITICAL — 生成任何 XML 之前,MUST 先用 Read 工具读取 [xml-schema-quick-ref.md](references/xml-schema-quick-ref.md),禁止凭记忆猜测 XML 结构。**
|
||||
|
||||
@@ -267,14 +267,12 @@ Shortcut 是对常用操作的高级封装(`lark-cli slides +<verb> [flags]`
|
||||
| [`+media-upload`](references/lark-slides-media-upload.md) | 上传本地图片到指定演示文稿,返回 `file_token`(用作 `<img src="...">`),最大 20 MB |
|
||||
| [`+replace-slide`](references/lark-slides-replace-slide.md) | 对已有幻灯片页面进行块级替换/插入(`block_replace` / `block_insert`),自动注入 id 和 `<content/>`,不改变页序 |
|
||||
|
||||
没有 Shortcut 覆盖时使用原生 API。高频资源:`xml_presentations.get` 读取全文;`xml_presentation.slide.create/delete/get/replace` 管理单页。
|
||||
|
||||
```bash
|
||||
lark-cli schema slides.<resource>.<method> # 调用 API 前必须先查看参数结构
|
||||
lark-cli slides <resource> <method> [flags] # 调用 API
|
||||
```
|
||||
|
||||
> **重要**:使用原生 API 时,必须先运行 `schema` 查看 `--data` / `--params` 参数结构,不要猜测字段格式。
|
||||
原生 API 高频资源:`xml_presentations.get` 读取全文;`xml_presentation.slide.create/delete/get/replace` 管理单页。使用原生 API 时,必须先运行 `schema` 查看 `--data` / `--params` 参数结构,不要猜字段。
|
||||
|
||||
## 核心规则
|
||||
|
||||
@@ -287,4 +285,17 @@ lark-cli slides <resource> <method> [flags] # 调用 API
|
||||
7. **编辑已有页面优先块级替换**:修改单个 shape/img 用 `+replace-slide`(`block_replace` / `block_insert`),不要整页重建;只有需要替换整页结构时才用 `slide.delete` + `slide.create`
|
||||
8. **`<img src>` 只能用上传到飞书 drive 的 `file_token`,禁止使用 http(s) 外链 URL**:飞书 slides 渲染端不会代理外链图片,外链 src 在 PPT 里通常不显示或显示破图。流程必须是「先把图存到本地 → 用 `slides +media-upload` 上传或 `+create --slides` 的 `@./path` 占位符自动上传 → 拿 `file_token` 写进 `<img src>`」。如果用户给了网图链接,先 `curl`/下载到 CWD 内再走上传流程,不要直接把外链 URL 塞进 `src`。**图片最大 20 MB**(slides upload API 不支持分片上传)。
|
||||
|
||||
## 权限速查
|
||||
|
||||
| 方法 | 所需 scope |
|
||||
|------|-----------|
|
||||
| `slides +create` | `slides:presentation:create`, `slides:presentation:write_only`(含 `@` 占位符时还需 `docs:document.media:upload`) |
|
||||
| `slides +media-upload` | `docs:document.media:upload`(wiki URL 解析还需 `wiki:node:read`) |
|
||||
| `slides +replace-slide` | `slides:presentation:update`(wiki URL 解析还需 `wiki:node:read`) |
|
||||
| `xml_presentations.get` | `slides:presentation:read` |
|
||||
| `xml_presentation.slide.create` | `slides:presentation:update` 或 `slides:presentation:write_only` |
|
||||
| `xml_presentation.slide.delete` | `slides:presentation:update` 或 `slides:presentation:write_only` |
|
||||
| `xml_presentation.slide.get` | `slides:presentation:read` |
|
||||
| `xml_presentation.slide.replace` | `slides:presentation:update` |
|
||||
|
||||
> **注意**:如果 md 内容与 `slides_xml_schema_definition.xml` 或 `lark-cli schema slides.<resource>.<method>` 输出不一致,以后两者为准。
|
||||
|
||||
Reference in New Issue
Block a user