6
1
mirror of https://git.mills.io/saltyim/saltyim.git synced 2024-06-28 17:51:04 +00:00
prologic-saltyim/format.go

66 lines
1.4 KiB
Go
Raw Normal View History

2022-03-20 03:44:22 +00:00
package saltyim
import (
2022-03-20 05:46:38 +00:00
"bytes"
2022-03-20 03:44:22 +00:00
"fmt"
"hash/fnv"
"os"
"github.com/logrusorgru/aurora"
2022-03-20 05:46:38 +00:00
"github.com/posener/formatter"
log "github.com/sirupsen/logrus"
2022-03-20 03:44:22 +00:00
"go.yarn.social/lextwt"
)
const (
DateTimeFormat = "2006-01-02 15:04:05"
)
2022-03-20 03:44:22 +00:00
func boundedInt(value, low, high uint8) uint8 {
diff := high - low
return (((value - low) % diff) + low)
}
func GetUserColor(user string, lower, upper uint8) uint8 {
h := fnv.New32()
h.Sum([]byte(user))
return boundedInt(uint8(h.Sum32()), lower, upper)
}
2022-03-20 05:46:38 +00:00
// FormatMessage formats the msg for display on the terminal
2022-03-20 03:44:22 +00:00
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)
2022-03-20 03:44:22 +00:00
return ""
}
userColor := GetUserColor(st.User.String(), 16, 231)
2022-03-20 05:46:38 +00:00
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 ""
}
2022-03-20 03:44:22 +00:00
return fmt.Sprintf(
2022-03-20 05:46:38 +00:00
"%s\t%s\n%s\n",
aurora.Sprintf(aurora.Blue(st.Timestamp.DateTime().Local().Format(DateTimeFormat))),
2022-03-20 03:44:22 +00:00
aurora.Sprintf(aurora.Index(userColor, st.User.String())),
2022-03-20 05:46:38 +00:00
buf.String(),
2022-03-20 03:44:22 +00:00
)
}