6
1
mirror of https://git.mills.io/saltyim/saltyim.git synced 2024-06-25 16:28:20 +00:00
prologic-saltyim/cmd/salty-chat/read.go
2023-03-12 15:17:57 +10:00

118 lines
2.4 KiB
Go

package main
import (
"context"
"fmt"
"os"
"os/signal"
"syscall"
"github.com/mattn/go-isatty"
log "github.com/sirupsen/logrus"
"github.com/spf13/cobra"
"go.salty.im/saltyim"
)
var readCmd = &cobra.Command{
Use: "read [<inbox>]",
Short: "Reads messages from an inbox",
Long: `This command subscribes to the provided inbox (optiona) which if
not specified defaults to the local user ($USER)`,
PreRunE: initializeClient,
PostRunE: shutdownClient,
Run: func(cmd *cobra.Command, args []string) {
follow, err := cmd.Flags().GetBool("follow")
if err != nil {
log.Fatal("error getting -f--follow flag")
}
extraenvs, err := cmd.Flags().GetString("extra-envs")
if err != nil {
log.Fatal("error getting --extra-envs flag")
}
prehook, err := cmd.Flags().GetString("pre-hook")
if err != nil {
log.Fatal("error getting --pre-hook flag")
}
posthook, err := cmd.Flags().GetString("post-hook")
if err != nil {
log.Fatal("error getting --post-hook flag")
}
read(follow, extraenvs, prehook, posthook, args...)
},
}
type profile struct {
User string
Identity string
}
func init() {
rootCmd.AddCommand(readCmd)
readCmd.Flags().BoolP(
"follow", "f", false,
"Subscribe to the inbox and follow all messages",
)
readCmd.Flags().String(
"extra-envs", "",
"List of extra env vars to pass to pre/post hooks (KEY=[VALUE] ...)",
)
readCmd.Flags().String(
"pre-hook", "",
"Execute pre-hook before message decryption",
)
readCmd.Flags().String(
"post-hook", "",
"Execute post-hook after message decryption",
)
}
func read(follow bool, extraenvs, prehook, posthook string, args ...string) {
ctx, cancel := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
defer cancel()
opts := []saltyim.ReadOption{
saltyim.WithExtraEnvs(extraenvs),
saltyim.WithPreHook(prehook),
saltyim.WithPostHook(posthook),
}
if !follow {
msg, err := cli.Read(opts...)
if err != nil {
if err == saltyim.ErrNoMessages {
os.Exit(0)
}
fmt.Fprintf(os.Stderr, "error reading message: %s\n", err)
os.Exit(2)
}
if isatty.IsTerminal(os.Stdout.Fd()) {
fmt.Println(saltyim.FormatMessage(msg.Text))
} else {
fmt.Println(msg.Text)
}
return
}
msgs := cli.Subscribe(ctx, opts...)
select {
case msg := <-msgs:
if isatty.IsTerminal(os.Stdout.Fd()) {
fmt.Println(saltyim.FormatMessage(msg.Text))
} else {
fmt.Println(msg.Text)
}
case <-ctx.Done():
close(msgs)
return
}
}