diff --git a/README.md b/README.md index 821ef1d..87c521d 100644 --- a/README.md +++ b/README.md @@ -84,9 +84,9 @@ Programmatic clients use API keys issued by fmsg-webapi. |---------|-------------| | `fmsg login [api-key\|jwt] [--address @user@example.com]` | Authenticate and store credentials | | `fmsg whoami` | Print the authenticated fmsg address, API URL, and token expiry | -| `fmsg list` \| `fmsg ls [--limit N] [--offset N]` | List messages for the authenticated user | -| `fmsg sent [--limit N] [--offset N]` | List messages authored by the authenticated user | -| `fmsg watch [--events types] [--once] [--timeout D]` | Stream pushed events (new messages, deliveries) over the server's WebSocket until Ctrl-C | +| `fmsg list` \| `fmsg ls [--limit N] [--offset N] [--all]` | List messages for the authenticated user; edit messages are hidden unless `--all` | +| `fmsg sent [--limit N] [--offset N] [--all]` | List messages authored by the authenticated user; edit messages are hidden unless `--all` | +| `fmsg watch [--events types] [--once] [--timeout D]` | Stream pushed events (new messages, deliveries, edits) over the server's WebSocket until Ctrl-C | | `fmsg get ` | Retrieve a message by ID, including the short text body for `text/*` messages | | `fmsg send ` | Send a message (file path, text, or `-` for stdin) | | `fmsg draft create ` | Create a draft message without sending | @@ -97,7 +97,7 @@ Programmatic clients use API keys issued by fmsg-webapi. | `fmsg edit ` | Replace the body of a message you sent (FMSG-008 edit); `fmsg edit --revert` restores the original | | `fmsg attach ` | Upload a file attachment to a message | | `fmsg get-attach ` | Download an attachment | -| `fmsg get-data [output-file]` | Download message body data (stdout if no output file) | +| `fmsg get-data [output-file] [--original]` | Download message body data (stdout if no output file); an edited message downloads as edited unless `--original` | | `fmsg rm-attach ` | Remove an attachment from a message | | `fmsg sub-accounts list` | List sub-accounts owned by the authenticated user | | `fmsg sub-accounts get ` | Retrieve a single sub-account grant | @@ -150,7 +150,7 @@ callers: preceded by `{"type":"ready"}` once the socket is open (and again after every automatic reconnect, since events may have been missed while it was down: do a `list` catch-up when you see it). Filter with `--events - new_msg,delivered,recipients_added`; `--once` exits after the first + new_msg,delivered,recipients_added,edit`; `--once` exits after the first matching event; `--timeout 30s` stops after that long. Exit code 0 after an event or Ctrl-C, **2** if `--once`/`--timeout` ended before any event, 1 on error. @@ -226,6 +226,11 @@ fmsg add-to 101 @cc1@example.com @cc2@example.com fmsg edit 101 "See you there at 5pm" fmsg edit 101 --revert +# An edited message shows "(edited)" in list/sent and an "Edited:" line in +# get; the edit messages themselves are hidden unless --all is given, and +# negative indices (-1, -2, ...) do not count them +fmsg list --all + # Update a draft message fmsg update 42 --topic "New topic" fmsg update 42 --to @newrecipient@example.com "Updated body text" @@ -243,6 +248,7 @@ fmsg get-attach 101 report.pdf ./downloaded-report.pdf # Download message body data fmsg get-data 101 fmsg get-data 101 ./message-body.txt +fmsg get-data 101 --original # as first sent, ignoring any edit # Remove attachment fmsg rm-attach 101 report.pdf diff --git a/cmd/get.go b/cmd/get.go index 2ee8b4c..8d5d64c 100644 --- a/cmd/get.go +++ b/cmd/get.go @@ -43,16 +43,31 @@ var getCmd = &cobra.Command{ } } if msg.PID != nil { - fmt.Printf("PID: %d\n", *msg.PID) + if msg.Edit { + fmt.Printf("Edit of: %d\n", *msg.PID) + } else { + fmt.Printf("PID: %d\n", *msg.PID) + } } if msg.Topic != "" { fmt.Printf("Topic: %s\n", msg.Topic) } fmt.Printf("Type: %s\n", msg.Type) - fmt.Printf("Size: %d\n", msg.Size) + size := msg.Size + if msg.Edited != nil && msg.Edited.Size != nil { + size = *msg.Edited.Size + } + fmt.Printf("Size: %d\n", size) if msg.Time != nil { fmt.Printf("Time: %f\n", *msg.Time) } + if msg.Edited != nil { + if msg.Edited.Size != nil { + fmt.Printf("Edited: %f (edit message %d)\n", msg.Edited.Time, msg.Edited.ID) + } else { + fmt.Printf("Edited: %f (edit message %d could not be applied; showing the original)\n", msg.Edited.Time, msg.Edited.ID) + } + } if msg.Important { fmt.Println("Important: yes") } diff --git a/cmd/get_data.go b/cmd/get_data.go index d30168b..aecdb00 100644 --- a/cmd/get_data.go +++ b/cmd/get_data.go @@ -8,10 +8,16 @@ import ( "github.com/spf13/cobra" ) +var getDataOriginal bool + var getDataCmd = &cobra.Command{ Use: "get-data [output-file]", Short: "Download the body data of a message", - Args: cobra.RangeArgs(1, 2), + Long: `Download the body data of a message, to output-file or stdout. + +An edited message (FMSG-008) downloads as edited; --original downloads the +data as first sent, which stays stored.`, + Args: cobra.RangeArgs(1, 2), RunE: func(cmd *cobra.Command, args []string) error { messageID := args[0] @@ -23,7 +29,7 @@ var getDataCmd = &cobra.Command{ messageIDStr := strconv.FormatInt(resolvedID, 10) if len(args) == 2 { outputPath := args[1] - if err := client.DownloadData(messageIDStr, outputPath); err != nil { + if err := client.DownloadData(messageIDStr, getDataOriginal, outputPath); err != nil { return err } @@ -35,7 +41,7 @@ var getDataCmd = &cobra.Command{ return nil } - if err := client.DownloadDataToWriter(messageIDStr, os.Stdout); err != nil { + if err := client.DownloadDataToWriter(messageIDStr, getDataOriginal, os.Stdout); err != nil { return err } return nil @@ -43,5 +49,6 @@ var getDataCmd = &cobra.Command{ } func init() { + getDataCmd.Flags().BoolVar(&getDataOriginal, "original", false, "Download the data as first sent, ignoring any edit") rootCmd.AddCommand(getDataCmd) } diff --git a/cmd/list.go b/cmd/list.go index 3786218..d2f3dde 100644 --- a/cmd/list.go +++ b/cmd/list.go @@ -11,18 +11,28 @@ import ( var ( listLimit int listOffset int + listAll bool ) var listCmd = &cobra.Command{ Use: "list", Aliases: []string{"ls"}, Short: "List messages for the authenticated user", + Long: `List messages for the authenticated user, newest first. + +Edit messages (FMSG-008) are left out unless --all is given: the change each +one carries is already applied to the message it edits, which is marked +"(edited)". They are filtered after the server pages, so a page can hold +fewer than --limit rows.`, RunE: func(cmd *cobra.Command, args []string) error { client, _ := newAuthenticatedClient() messages, err := client.ListMessages(listLimit, listOffset) if err != nil { return err } + if !listAll { + messages = api.VisibleMessages(messages) + } if jsonOutput { if messages == nil { @@ -38,7 +48,7 @@ var listCmd = &cobra.Command{ for _, msg := range messages { to, _ := json.Marshal(msg.To) - fmt.Printf("ID: %d From: %s To: %s\n", msg.ID, msg.From, string(to)) + fmt.Println(listLine(msg, string(to))) } return nil }, @@ -47,5 +57,22 @@ var listCmd = &cobra.Command{ func init() { listCmd.Flags().IntVar(&listLimit, "limit", 20, "Max number of messages to return (1-100)") listCmd.Flags().IntVar(&listOffset, "offset", 0, "Number of messages to skip") + listCmd.Flags().BoolVar(&listAll, "all", false, "Include edit messages (FMSG-008), which are hidden by default") rootCmd.AddCommand(listCmd) } + +// listLine renders one list row; to is the already-encoded recipient list. +func listLine(msg api.MessageListItem, to string) string { + line := fmt.Sprintf("ID: %d From: %s To: %s", msg.ID, msg.From, to) + if msg.Edit { + if msg.PID != nil { + line += fmt.Sprintf(" (edit of %d)", *msg.PID) + } else { + line += " (edit)" + } + } + if msg.Edited != nil { + line += " (edited)" + } + return line +} diff --git a/cmd/msgid.go b/cmd/msgid.go index 84e8b88..0b2a6dc 100644 --- a/cmd/msgid.go +++ b/cmd/msgid.go @@ -11,6 +11,7 @@ import ( // as-is. Negative values are treated as reverse indices into the user's inbox // ordered by ID descending: -1 is the most recent message, -2 the second most // recent, and so on. Zero is not a valid message ID and returns an error. +// Edit messages (FMSG-008) are not counted, matching what "list" shows. // // When arg is negative the caller's inbox is fetched via GET /fmsg using the // provided client, so the client must already be authenticated. @@ -26,15 +27,22 @@ func resolveMessageID(client *api.Client, arg string) (int64, error) { return id, nil } - // Negative index: resolve via inbox list (ordered by ID desc). - // -1 → offset 0, -2 → offset 1, etc. - offset := int(-id) - 1 - msgs, err := client.ListMessages(1, offset) - if err != nil { - return 0, fmt.Errorf("resolving message index %d: %w", id, err) - } - if len(msgs) == 0 { - return 0, fmt.Errorf("no message at index %d", id) + // Negative index: walk the inbox list (ordered by ID desc) a page at a + // time, counting only the messages "list" shows. -1 is the first, etc. + const pageSize = 100 + remaining := int(-id) + for offset := 0; ; offset += pageSize { + page, err := client.ListMessages(pageSize, offset) + if err != nil { + return 0, fmt.Errorf("resolving message index %d: %w", id, err) + } + visible := api.VisibleMessages(page) + if remaining <= len(visible) { + return visible[remaining-1].ID, nil + } + remaining -= len(visible) + if len(page) < pageSize { + return 0, fmt.Errorf("no message at index %d", id) + } } - return msgs[0].ID, nil } diff --git a/cmd/msgid_test.go b/cmd/msgid_test.go index 0672078..62e6690 100644 --- a/cmd/msgid_test.go +++ b/cmd/msgid_test.go @@ -188,3 +188,59 @@ func TestInjectDashDash_FlagBeforeNegative(t *testing.T) { } } } + +// TestResolveMessageID_SkipsEditMessages pins that negative indices count the +// messages "list" shows: edit messages (FMSG-008) are passed over. +func TestResolveMessageID_SkipsEditMessages(t *testing.T) { + pid := int64(50) + items := []api.MessageListItem{ + {ID: 100, Edit: true, PID: &pid}, + {ID: 90}, + {ID: 80, Edit: true, PID: &pid}, + {ID: 50}, + } + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + offset, _ := strconv.Atoi(r.URL.Query().Get("offset")) + page := items + if offset >= len(page) { + page = nil + } else { + page = page[offset:] + } + w.Header().Set("Content-Type", "application/json") + _ = json.NewEncoder(w).Encode(page) + })) + defer srv.Close() + client := api.New(srv.URL, api.StaticTokenProvider("token")) + + for arg, want := range map[string]int64{"-1": 90, "-2": 50} { + id, err := resolveMessageID(client, arg) + if err != nil { + t.Fatalf("%s: unexpected error: %v", arg, err) + } + if id != want { + t.Fatalf("%s: want %d, got %d", arg, want, id) + } + } + if _, err := resolveMessageID(client, "-3"); err == nil { + t.Fatal("-3: want an error, only two messages are visible") + } +} + +func TestListLineMarksEditsAndEditedMessages(t *testing.T) { + pid := int64(7) + size := 5 + cases := []struct { + msg api.MessageListItem + want string + }{ + {api.MessageListItem{ID: 7, From: "@a@example.com"}, `ID: 7 From: @a@example.com To: []`}, + {api.MessageListItem{ID: 7, From: "@a@example.com", Edited: &api.Edited{ID: 9, Time: 1, Size: &size}}, `ID: 7 From: @a@example.com To: [] (edited)`}, + {api.MessageListItem{ID: 9, From: "@a@example.com", Edit: true, PID: &pid}, `ID: 9 From: @a@example.com To: [] (edit of 7)`}, + } + for _, c := range cases { + if got := listLine(c.msg, "[]"); got != c.want { + t.Errorf("listLine = %q, want %q", got, c.want) + } + } +} diff --git a/cmd/sent.go b/cmd/sent.go index f0433ba..46867bf 100644 --- a/cmd/sent.go +++ b/cmd/sent.go @@ -11,17 +11,27 @@ import ( var ( sentLimit int sentOffset int + sentAll bool ) var sentCmd = &cobra.Command{ Use: "sent", Short: "List messages authored by the authenticated user", + Long: `List messages authored by the authenticated user, newest first. + +Edit messages (FMSG-008) are left out unless --all is given: the change each +one carries is already applied to the message it edits, which is marked +"(edited)". They are filtered after the server pages, so a page can hold +fewer than --limit rows.`, RunE: func(cmd *cobra.Command, args []string) error { client, _ := newAuthenticatedClient() messages, err := client.ListSentMessages(sentLimit, sentOffset) if err != nil { return err } + if !sentAll { + messages = api.VisibleMessages(messages) + } if jsonOutput { if messages == nil { @@ -37,7 +47,7 @@ var sentCmd = &cobra.Command{ for _, msg := range messages { to, _ := json.Marshal(msg.To) - fmt.Printf("ID: %d From: %s To: %s\n", msg.ID, msg.From, string(to)) + fmt.Println(listLine(msg, string(to))) } return nil }, @@ -46,5 +56,6 @@ var sentCmd = &cobra.Command{ func init() { sentCmd.Flags().IntVar(&sentLimit, "limit", 20, "Max number of messages to return (1-100)") sentCmd.Flags().IntVar(&sentOffset, "offset", 0, "Number of messages to skip") + sentCmd.Flags().BoolVar(&sentAll, "all", false, "Include edit messages (FMSG-008), which are hidden by default") rootCmd.AddCommand(sentCmd) } diff --git a/cmd/update.go b/cmd/update.go index 2f488de..5933072 100644 --- a/cmd/update.go +++ b/cmd/update.go @@ -110,7 +110,7 @@ and merged first — unchanged fields are preserved.)`, } } else if existing.Size > 0 { var buf bytes.Buffer - if err := client.DownloadDataToWriter(idStr, &buf); err != nil { + if err := client.DownloadDataToWriter(idStr, false, &buf); err != nil { return fmt.Errorf("fetching current draft body: %w", err) } data = buf.Bytes() diff --git a/cmd/watch.go b/cmd/watch.go index 6643c9a..0711b78 100644 --- a/cmd/watch.go +++ b/cmd/watch.go @@ -36,8 +36,10 @@ var watchCmd = &cobra.Command{ arrives, until interrupted (Ctrl-C), --once, or --timeout. Events pushed by the server: new_msg (a message arrived for you), delivered -(a message you sent reached a recipient), recipients_added. Filter with ---events; every event carries the message in the same shape as a "list" item. +(a message you sent reached a recipient), recipients_added, edit (a message +was edited or an edit reverted; the event carries the message as it now +reads). Filter with --events; every event carries the message in the same +shape as a "list" item. With --json each event is one JSON line: {"type":"new_msg","data":{...}}. A {"type":"ready"} line is printed once the socket is open — and again after @@ -125,11 +127,14 @@ func printHumanEvent(ev api.WatchEvent) { if item.Topic != "" { line += fmt.Sprintf(" Topic: %q", item.Topic) } + if ev.Type == api.EventEdit && item.Edited == nil { + line += " (reverted)" + } fmt.Println(line) } func init() { - watchCmd.Flags().StringSliceVar(&watchEvents, "events", nil, "Only print these event types (comma-separated: new_msg,delivered,recipients_added); default all") + watchCmd.Flags().StringSliceVar(&watchEvents, "events", nil, "Only print these event types (comma-separated: new_msg,delivered,recipients_added,edit); default all") watchCmd.Flags().BoolVar(&watchOnce, "once", false, "Exit after the first matching event") watchCmd.Flags().DurationVar(&watchTimeout, "timeout", 0, "Stop after this duration (e.g. 30s, 5m); 0 means run until interrupted") rootCmd.AddCommand(watchCmd) diff --git a/internal/api/client.go b/internal/api/client.go index 2dc8ef1..55a42f9 100644 --- a/internal/api/client.go +++ b/internal/api/client.go @@ -175,6 +175,30 @@ type MessageListItem struct { Read bool `json:"read"` TimeRead *float64 `json:"time_read"` Attachments []Attachment `json:"attachments"` + Edit bool `json:"edit"` + Edited *Edited `json:"edited"` +} + +// Edited identifies the edit message in force on a message (FMSG-008). Size +// is the byte length of the edited data, nil when the edit could not be +// applied and the original data is shown instead. +type Edited struct { + ID int64 `json:"id"` + Time float64 `json:"time"` + Size *int `json:"size"` +} + +// VisibleMessages drops edit messages (FMSG-008) from items. They carry a +// change to another message, which the server already applies to that +// message, so they are not shown as messages in their own right. +func VisibleMessages(items []MessageListItem) []MessageListItem { + visible := make([]MessageListItem, 0, len(items)) + for _, item := range items { + if !item.Edit { + visible = append(visible, item) + } + } + return visible } // Message represents a fmsg message as exchanged over the HTTP API. @@ -198,6 +222,8 @@ type Message struct { Read bool `json:"read"` TimeRead *float64 `json:"time_read"` Attachments []Attachment `json:"attachments"` + Edit bool `json:"edit"` + Edited *Edited `json:"edited"` } // CreateMessageResponse is the response from creating a message. @@ -600,8 +626,13 @@ func (c *Client) UpdateMessage(id int64, body []byte) error { } // DownloadDataToWriter downloads the message body data and writes it to w. -func (c *Client) DownloadDataToWriter(id string, w io.Writer) error { - req, err := http.NewRequest(http.MethodGet, c.BaseURL+"/fmsg/"+id+"/data", nil) +// An edited message (FMSG-008) downloads as edited unless original is set. +func (c *Client) DownloadDataToWriter(id string, original bool, w io.Writer) error { + url := c.BaseURL + "/fmsg/" + id + "/data" + if original { + url += "?original=true" + } + req, err := http.NewRequest(http.MethodGet, url, nil) if err != nil { return err } @@ -623,14 +654,14 @@ func (c *Client) DownloadDataToWriter(id string, w io.Writer) error { } // DownloadData downloads the message body data and writes it to outputPath. -func (c *Client) DownloadData(id, outputPath string) error { +func (c *Client) DownloadData(id string, original bool, outputPath string) error { out, err := os.Create(outputPath) if err != nil { return fmt.Errorf("creating output file: %w", err) } defer out.Close() - if err := c.DownloadDataToWriter(id, out); err != nil { + if err := c.DownloadDataToWriter(id, original, out); err != nil { return err } return nil diff --git a/internal/api/client_test.go b/internal/api/client_test.go index 8682799..3b44c50 100644 --- a/internal/api/client_test.go +++ b/internal/api/client_test.go @@ -198,3 +198,60 @@ func TestEditMessageSendsDataAndReportsWhetherSent(t *testing.T) { t.Fatalf("request bodies = %q", bodies) } } + +// TestEditFieldsDecodeAndEditMessagesAreHidden pins the FMSG-008 fields on +// list items and that VisibleMessages drops the edit messages themselves. +func TestEditFieldsDecodeAndEditMessagesAreHidden(t *testing.T) { + const body = `[ + {"id": 9, "has_pid": true, "pid": 7, "from": "@alice@example.com", "edit": true, "edited": null}, + {"id": 8, "from": "@bob@example.com", "edit": false, "edited": {"id": 12, "time": 3.5, "size": null}}, + {"id": 7, "from": "@alice@example.com", "edit": false, "edited": {"id": 9, "time": 2.5, "size": 5}} + ]` + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "application/json") + _, _ = w.Write([]byte(body)) + })) + defer srv.Close() + + client := New(srv.URL, StaticTokenProvider("token")) + items, err := client.ListMessages(20, 0) + if err != nil { + t.Fatalf("ListMessages: %v", err) + } + if len(items) != 3 || !items[0].Edit { + t.Fatalf("items = %+v", items) + } + if e := items[1].Edited; e == nil || e.ID != 12 || e.Size != nil { + t.Fatalf("unappliable edit = %+v", e) + } + if e := items[2].Edited; e == nil || e.ID != 9 || e.Time != 2.5 || e.Size == nil || *e.Size != 5 { + t.Fatalf("edited = %+v", e) + } + + visible := VisibleMessages(items) + if len(visible) != 2 || visible[0].ID != 8 || visible[1].ID != 7 { + t.Fatalf("visible = %+v", visible) + } +} + +func TestDownloadDataRequestsTheOriginalOnlyWhenAsked(t *testing.T) { + var queries []string + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.URL.Path != "/fmsg/7/data" { + t.Fatalf("unexpected path %s", r.URL.Path) + } + queries = append(queries, r.URL.RawQuery) + _, _ = w.Write([]byte("body")) + })) + defer srv.Close() + + client := New(srv.URL, StaticTokenProvider("token")) + for _, original := range []bool{false, true} { + if err := client.DownloadDataToWriter("7", original, io.Discard); err != nil { + t.Fatal(err) + } + } + if len(queries) != 2 || queries[0] != "" || queries[1] != "original=true" { + t.Fatalf("queries = %q", queries) + } +} diff --git a/internal/api/watch.go b/internal/api/watch.go index ed54fb7..c464ae4 100644 --- a/internal/api/watch.go +++ b/internal/api/watch.go @@ -18,6 +18,7 @@ const ( EventNewMsg = "new_msg" EventDelivered = "delivered" EventRecipientsAdded = "recipients_added" + EventEdit = "edit" ) // WatchEvent is one frame from the WebSocket: a type discriminator and the