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
16 changes: 11 additions & 5 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 <message-id>` | Retrieve a message by ID, including the short text body for `text/*` messages |
| `fmsg send <recipient> <file\|text\|->` | Send a message (file path, text, or `-` for stdin) |
| `fmsg draft create <recipient> <file\|text\|->` | Create a draft message without sending |
Expand All @@ -97,7 +97,7 @@ Programmatic clients use API keys issued by fmsg-webapi.
| `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) |
| `fmsg get-data <message-id> [output-file] [--original]` | Download message body data (stdout if no output file); an edited message downloads as edited unless `--original` |
| `fmsg rm-attach <message-id> <filename>` | Remove an attachment from a message |
| `fmsg sub-accounts list` | List sub-accounts owned by the authenticated user |
| `fmsg sub-accounts get <agent>` | Retrieve a single sub-account grant |
Expand Down Expand Up @@ -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.
Expand Down Expand Up @@ -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"
Expand All @@ -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
Expand Down
19 changes: 17 additions & 2 deletions cmd/get.go
Original file line number Diff line number Diff line change
Expand Up @@ -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")
}
Expand Down
13 changes: 10 additions & 3 deletions cmd/get_data.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,10 +8,16 @@ import (
"github.com/spf13/cobra"
)

var getDataOriginal bool

var getDataCmd = &cobra.Command{
Use: "get-data <message-id> [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]

Expand All @@ -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
}

Expand All @@ -35,13 +41,14 @@ 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
},
}

func init() {
getDataCmd.Flags().BoolVar(&getDataOriginal, "original", false, "Download the data as first sent, ignoring any edit")
rootCmd.AddCommand(getDataCmd)
}
29 changes: 28 additions & 1 deletion cmd/list.go
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand All @@ -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
},
Expand All @@ -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
}
28 changes: 18 additions & 10 deletions cmd/msgid.go
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand All @@ -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
}
56 changes: 56 additions & 0 deletions cmd/msgid_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}
}
}
13 changes: 12 additions & 1 deletion cmd/sent.go
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand All @@ -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
},
Expand All @@ -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)
}
2 changes: 1 addition & 1 deletion cmd/update.go
Original file line number Diff line number Diff line change
Expand Up @@ -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()
Expand Down
11 changes: 8 additions & 3 deletions cmd/watch.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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)
Expand Down
Loading
Loading