mirror of
https://git.mills.io/saltyim/saltyim.git
synced 2024-06-30 18:51:03 +00:00
![James Mills](/assets/img/avatar_default.png)
Co-authored-by: James Mills <1290234+prologic@users.noreply.github.com> Reviewed-on: https://git.mills.io/saltyim/saltyim/pulls/181
83 lines
1.9 KiB
Go
83 lines
1.9 KiB
Go
package saltyim
|
|
|
|
import (
|
|
"bytes"
|
|
"fmt"
|
|
"os"
|
|
"strings"
|
|
"time"
|
|
|
|
"github.com/logrusorgru/aurora"
|
|
"github.com/posener/formatter"
|
|
log "github.com/sirupsen/logrus"
|
|
colorhash "github.com/taigrr/go-colorhash"
|
|
"go.yarn.social/lextwt"
|
|
)
|
|
|
|
const (
|
|
// DateTimeFormat is the default date and time format used for displaying messages
|
|
DateTimeFormat = "2006-01-02 15:04:05"
|
|
)
|
|
|
|
// FormatMessage formats the msg for display on the terminal
|
|
func FormatMessage(msg string) string {
|
|
s, err := lextwt.ParseSalty(msg)
|
|
if err != nil {
|
|
fmt.Fprintf(os.Stderr, "error parsing message %q: %s", msg, err)
|
|
return ""
|
|
}
|
|
|
|
st, ok := s.(*lextwt.SaltyText)
|
|
if !ok {
|
|
log.Errorf("unexpected error, expected type lextwt.SaltyText got #%v", st)
|
|
return ""
|
|
}
|
|
|
|
userColor := colorhash.HashString(st.User.String())
|
|
|
|
buf := &bytes.Buffer{}
|
|
|
|
f := formatter.Formatter{
|
|
Writer: buf,
|
|
Indent: []byte("> "),
|
|
Width: 80,
|
|
}
|
|
|
|
if _, err := f.Write([]byte(st.LiteralText())); err != nil {
|
|
fmt.Fprintf(os.Stderr, "error formatting message: %s", err)
|
|
return ""
|
|
}
|
|
|
|
return fmt.Sprintf(
|
|
"%s\t%s\n%s\n",
|
|
aurora.Sprintf(aurora.Blue(st.Timestamp.DateTime().Local().Format(DateTimeFormat))),
|
|
aurora.Sprintf(aurora.Index(uint8(userColor), st.User.String())),
|
|
buf.String(),
|
|
)
|
|
}
|
|
|
|
// PackMessage formats an outgoing message in the Message Format
|
|
// <timestamp>\t(<sender>) <message>
|
|
func PackMessage(me Addr, msg string) []byte {
|
|
//log.Debug("pack: ", me.Formatted(), msg)
|
|
return []byte(
|
|
fmt.Sprint(
|
|
time.Now().UTC().Format(time.RFC3339), "\t",
|
|
me.Formatted(), "\t",
|
|
strings.TrimSpace(msg), "\n",
|
|
),
|
|
)
|
|
}
|
|
|
|
// PackMessageTime formats an incoming message in the Message Format using the existing timestamp
|
|
// <timestamp>\t(<sender>) <message>
|
|
func PackMessageTime(me Addr, msg string, t *lextwt.DateTime) []byte {
|
|
return []byte(
|
|
fmt.Sprint(
|
|
t.Literal(), "\t",
|
|
me.Formatted(), "\t",
|
|
strings.TrimSpace(msg), "\n",
|
|
),
|
|
)
|
|
}
|