6
1
mirror of https://git.mills.io/saltyim/saltyim.git synced 2024-06-28 17:51:04 +00:00
prologic-saltyim/readmsgs.go
2022-03-20 12:37:36 +10:00

77 lines
1.7 KiB
Go

package saltyim
import (
"bytes"
"context"
"fmt"
"os"
"time"
"git.mills.io/prologic/msgbus"
"git.mills.io/prologic/msgbus/client"
"github.com/gen2brain/beeep"
"github.com/keys-pub/keys"
log "github.com/sirupsen/logrus"
"go.mills.io/salty"
)
const (
defaultRunCmdTimeout = time.Second * 3
)
func handleMessage(key *keys.EdX25519Key, prehook, posthook string, msgs chan string) msgbus.HandlerFunc {
return func(msg *msgbus.Message) error {
if prehook != "" {
out, err := RunCmd(defaultRunCmdTimeout, prehook, bytes.NewBuffer(msg.Payload))
if err != nil {
log.WithError(err).Debugf("error running pre-hook %s", prehook)
}
log.Debugf("pre-hook: %q", out)
}
data, _, err := salty.Decrypt(key, msg.Payload)
if err != nil {
fmt.Fprintf(os.Stderr, "error decrypting message")
return err
}
msgs <- string(data)
// Errors are ignored silently
if err := beeep.Alert("Salty IM", "You have a new Salty Message", ""); err != nil {
log.WithError(err).Debug("error sending desktop notification")
}
if posthook != "" {
out, err := RunCmd(defaultRunCmdTimeout, posthook, bytes.NewBuffer(data))
if err != nil {
log.WithError(err).Debugf("error running post-hook %s", posthook)
}
log.Debugf("post-hook: %q", out)
}
return nil
}
}
// Read ...
func Read(ctx context.Context, key *keys.EdX25519Key, uri, inbox, prehook, posthook string) chan string {
client := client.NewClient(uri, nil)
msgs := make(chan string)
s := client.Subscribe(inbox, handleMessage(key, prehook, posthook, msgs))
s.Start()
log.Infof("Connected to %s/%s", uri, inbox)
go func() {
<-ctx.Done()
s.Stop()
close(msgs)
}()
return msgs
}