package cmd import ( "bytes" "context" "encoding/json" "fmt" "io" "os" "strings" "github.com/spf13/cobra" "tangled.org/matilde.at/km/internal/jmap" "tangled.org/matilde.at/km/internal/render" ) type apiOpts struct { Method string Fields []string // -f key=value (string) RawJSON []string // -F key=json Input string Using []string Session bool JQ string } func newAPICmd(f *Factory) *cobra.Command { o := &apiOpts{} c := &cobra.Command{ Use: "api []", Short: "Make a raw JMAP request", Long: `Call one JMAP method and print its response arguments. Arguments come from -f key=value (a string), -F key=json (any JSON value) or --input (a JSON object of arguments). accountId is filled in from the session unless given. A key starting with "#" is a result reference. Without a method, --input must hold a whole JMAP request ({"using": [...], "methodCalls": [...]}) and the whole response is printed.`, Example: ` km api Mailbox/get -F ids=null km api Email/query -F 'filter={"text":"invoice"}' -F limit=5 km api --session echo '{"using":["urn:ietf:params:jmap:core"],"methodCalls":[["Core/echo",{"hi":1},"0"]]}' | km api --input -`, Args: cobra.MaximumNArgs(1), RunE: func(cmd *cobra.Command, args []string) error { if len(args) == 1 { o.Method = args[0] } return runAPI(cmd.Context(), f, o) }, } c.Flags().StringArrayVarP(&o.Fields, "field", "f", nil, "Add a string argument `key=value`") c.Flags().StringArrayVarP(&o.RawJSON, "raw-field", "F", nil, "Add a JSON argument `key=json`") c.Flags().StringVar(&o.Input, "input", "", "Read arguments (or a whole request) from `file` (\"-\" for stdin)") c.Flags().StringSliceVar(&o.Using, "using", nil, "Extra capability `URNs` for the request") c.Flags().BoolVar(&o.Session, "session", false, "Print the JMAP session object") c.Flags().StringVarP(&o.JQ, "jq", "q", "", "Filter the output with a jq `expression`") return c } // capabilityFor guesses the capability a method needs from its type. func capabilityFor(method string) string { typ, _, _ := strings.Cut(method, "/") switch typ { case "Core": return jmap.CapCore case "Identity", "EmailSubmission": return jmap.CapSubmission case "SieveScript": return jmap.CapSieve case "VacationResponse": return jmap.CapVacation case "Blob": return jmap.CapBlob } return jmap.CapMail } func (o *apiOpts) printer(f *Factory) *render.Printer { p := &render.Printer{Out: f.IO.Out, IsTTY: f.IO.StdoutTTY} p.JSONFields = []string{} p.JQ = o.JQ return p } func emitRaw(p *render.Printer, raw []byte) error { var v any d := json.NewDecoder(bytes.NewReader(raw)) d.UseNumber() if err := d.Decode(&v); err != nil { return err } return p.Emit(v, nil) } func runAPI(ctx context.Context, f *Factory, o *apiOpts) error { c, err := f.JMAP(ctx) if err != nil { return err } p := o.printer(f) sess, err := c.Session(ctx) if err != nil { return err } if o.Session { return emitRaw(p, sess.Raw) } var input []byte if o.Input != "" { if o.Input == "-" { input, err = io.ReadAll(f.IO.In) } else { input, err = os.ReadFile(o.Input) } if err != nil { return err } } if o.Method == "" { if input == nil { return usagef("specify a method, --input with a whole request, or --session") } var check struct { MethodCalls json.RawMessage `json:"methodCalls"` } if json.Unmarshal(input, &check) != nil || check.MethodCalls == nil { return usagef("--input without a method must be a JMAP request object with methodCalls") } raw, err := c.DoRaw(ctx, input) if err != nil { return err } return emitRaw(p, raw) } if !strings.Contains(o.Method, "/") { return usagef("method %q should look like Type/method, e.g. Mailbox/get", o.Method) } args := map[string]any{} if input != nil { if err := json.Unmarshal(input, &args); err != nil { return usagef("--input must be a JSON object of arguments: %v", err) } } for _, kv := range o.Fields { k, v, ok := strings.Cut(kv, "=") if !ok { return usagef("-f %q: expected key=value", kv) } args[k] = v } for _, kv := range o.RawJSON { k, v, ok := strings.Cut(kv, "=") if !ok { return usagef("-F %q: expected key=json", kv) } var val any if err := json.Unmarshal([]byte(v), &val); err != nil { return usagef("-F %s: invalid JSON: %v", k, err) } args[k] = val } capability := capabilityFor(o.Method) if _, ok := args["accountId"]; !ok && capability != jmap.CapCore { acct, err := sess.AccountID(capability) if err != nil { return err } args["accountId"] = acct } using := []string{jmap.CapCore, jmap.CapMail} if capability != jmap.CapCore && capability != jmap.CapMail { using = append(using, capability) } using = append(using, o.Using...) req := &jmap.Request{Using: using} id := req.Add(o.Method, args) resp, err := c.Do(ctx, req) if err != nil { return err } var failed error for _, inv := range resp.MethodResponses { if inv.ID != id { continue } if inv.Name == "error" { failed = resp.Decode(id, nil) } out := inv.Args if len(resp.MethodResponses) > 1 { // Several responses (implicit calls): print them all, tagged. out, _ = json.Marshal(map[string]any{"name": inv.Name, "arguments": inv.Args}) } if err := emitRaw(p, out); err != nil { return err } } if failed != nil { return fmt.Errorf("%s failed: %w", o.Method, failed) } return nil }