Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -94,6 +94,7 @@ Programmatic clients use API keys issued by fmsg-webapi.
| `fmsg update <message-id> [file\|text\|-]` | Update a draft message |
| `fmsg del <message-id>` | Delete a draft message by ID |
| `fmsg add-to <message-id> <recipient> [recipient...]` | Add additional recipients to a message |
| `fmsg edit <message-id> <file\|text\|->` | Replace the body of a message you sent (FMSG-008 edit); `fmsg edit <message-id> --revert` restores the original |
| `fmsg attach <message-id> <file>` | Upload a file attachment to a message |
| `fmsg get-attach <message-id> <filename> <output-file>` | Download an attachment |
| `fmsg get-data <message-id> [output-file]` | Download message body data (stdout if no output file) |
Expand Down Expand Up @@ -221,6 +222,10 @@ fmsg draft send 42
fmsg add-to 101 @other@example.com
fmsg add-to 101 @cc1@example.com @cc2@example.com

# Edit a message you already sent, then revert it
fmsg edit 101 "See you there at 5pm"
fmsg edit 101 --revert

# Update a draft message
fmsg update 42 --topic "New topic"
fmsg update 42 --to @newrecipient@example.com "Updated body text"
Expand Down
83 changes: 83 additions & 0 deletions cmd/edit.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,83 @@
package cmd

import (
"errors"
"fmt"
"io"
"os"

"github.com/spf13/cobra"
)

var editRevert bool

var editCmd = &cobra.Command{
Use: "edit <message-id> [file|text|-]",
Short: "Edit the body of a message you sent, or revert it to the original",
Long: `Edit the body of a message you sent (FMSG-008).

The message content replaces the whole body and can be:
- A path to a file (the file contents are used)
- A text string (used directly)
- "-" to read from stdin

Use --revert instead of content to show the message as first sent.
Participants see the new text marked as edited; the original stays stored
and visible to them. Drafts are changed with "fmsg update" instead.`,
Args: cobra.RangeArgs(1, 2),
RunE: func(cmd *cobra.Command, args []string) error {
if editRevert == (len(args) == 2) {
return errors.New("give the new content, or --revert, but not both")
}

var data *string
if !editRevert {
var raw []byte
var err error
switch content := args[1]; content {
case "-":
raw, err = io.ReadAll(os.Stdin)
if err != nil {
return fmt.Errorf("reading stdin: %w", err)
}
default:
// Try as file first; fall back to using content directly as text.
if fileData, ferr := os.ReadFile(content); ferr == nil {
raw = fileData
} else {
raw = []byte(content)
}
}
text := string(raw)
data = &text
}

client, _ := newAuthenticatedClient()
msgID, err := resolveMessageID(client, args[0])
if err != nil {
return err
}
result, err := client.EditMessage(msgID, data)
if err != nil {
return err
}

if jsonOutput {
return printJSON(result)
}
switch {
case !result.Sent:
fmt.Printf("Message %d already reads that way; nothing sent\n", msgID)
case editRevert:
fmt.Printf("Reverted message %d to its original body\n", msgID)
default:
fmt.Printf("Edited message %d\n", msgID)
}
return nil
},
}

func init() {
editCmd.Flags().BoolVar(&editRevert, "revert", false, "revert the message to its original body")
rootCmd.AddCommand(editCmd)
}
42 changes: 42 additions & 0 deletions internal/api/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -420,6 +420,48 @@ func (c *Client) AddRecipients(id int64, addTo []string) (*AddRecipientsResponse
return &result, nil
}

// EditMessageResponse identifies the edit message in force on a message after
// an edit call; ID, Time and SHA256 are nil when the message has none. Sent is
// false when the body already read that way and nothing was sent.
type EditMessageResponse struct {
ID *int64 `json:"id"`
Time *float64 `json:"time"`
SHA256 *string `json:"sha256"`
Sent bool `json:"sent"`
}

// EditMessage replaces the body of a sent message the caller authored
// (FMSG-008), or reverts it to the original when data is nil.
func (c *Client) EditMessage(id int64, data *string) (*EditMessageResponse, error) {
body, err := json.Marshal(map[string]any{"data": data})
if err != nil {
return nil, fmt.Errorf("encoding request: %w", err)
}

req, err := http.NewRequest(http.MethodPost, c.BaseURL+"/fmsg/"+strconv.FormatInt(id, 10)+"/edit", bytes.NewReader(body))
if err != nil {
return nil, err
}
req.Header.Set("Content-Type", "application/json")

resp, err := c.do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()

if err := checkStatus(resp); err != nil {
return nil, err
}

var result EditMessageResponse
if err := json.NewDecoder(resp.Body).Decode(&result); err != nil {
return nil, fmt.Errorf("decoding response: %w", err)
}
result.Sent = resp.StatusCode == http.StatusCreated
return &result, nil
}

// DeleteMessage deletes a message by ID.
func (c *Client) DeleteMessage(id int64) error {
req, err := http.NewRequest(http.MethodDelete, c.BaseURL+"/fmsg/"+strconv.FormatInt(id, 10), nil)
Expand Down
39 changes: 39 additions & 0 deletions internal/api/client_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -159,3 +159,42 @@ func TestUploadAttachmentReturnsServerResponse(t *testing.T) {
t.Fatalf("upload response: got %+v", result)
}
}

func TestEditMessageSendsDataAndReportsWhetherSent(t *testing.T) {
var bodies []string
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path != "/fmsg/7/edit" || r.Method != http.MethodPost {
t.Fatalf("unexpected request %s %s", r.Method, r.URL.Path)
}
body, _ := io.ReadAll(r.Body)
bodies = append(bodies, string(body))
w.Header().Set("Content-Type", "application/json")
if len(bodies) == 1 {
w.WriteHeader(http.StatusCreated)
_, _ = w.Write([]byte(`{"id":9,"time":12.5,"sha256":"ab"}`))
return
}
_, _ = w.Write([]byte(`{"id":null,"time":null,"sha256":null}`))
}))
defer srv.Close()

client := New(srv.URL, &sequenceTokenProvider{})
text := "fixed"
edited, err := client.EditMessage(7, &text)
if err != nil {
t.Fatal(err)
}
if !edited.Sent || edited.ID == nil || *edited.ID != 9 {
t.Fatalf("edit result = %+v", edited)
}
reverted, err := client.EditMessage(7, nil)
if err != nil {
t.Fatal(err)
}
if reverted.Sent || reverted.ID != nil {
t.Fatalf("no-op revert result = %+v", reverted)
}
if bodies[0] != `{"data":"fixed"}` || bodies[1] != `{"data":null}` {
t.Fatalf("request bodies = %q", bodies)
}
}
Loading