mirror of
https://git.mills.io/saltyim/saltyim.git
synced 2024-06-24 07:48:19 +00:00
![James Mills](/assets/img/avatar_default.png)
Co-authored-by: James Mills <prologic@shortcircuit.net.au> Reviewed-on: https://git.mills.io/prologic/saltyim/pulls/46
66 lines
1.4 KiB
Go
66 lines
1.4 KiB
Go
package saltyim
|
|
|
|
import (
|
|
"bytes"
|
|
"fmt"
|
|
"hash/fnv"
|
|
"os"
|
|
|
|
"github.com/logrusorgru/aurora"
|
|
"github.com/posener/formatter"
|
|
log "github.com/sirupsen/logrus"
|
|
"go.yarn.social/lextwt"
|
|
)
|
|
|
|
const (
|
|
DateTimeFormat = "2006-01-02 15:04:05"
|
|
)
|
|
|
|
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)
|
|
}
|
|
|
|
// 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 := GetUserColor(st.User.String(), 16, 231)
|
|
|
|
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(userColor, st.User.String())),
|
|
buf.String(),
|
|
)
|
|
}
|