saltyim is the Go library and reference client and broker implementation for Salty IM it contains a command-line client (cli), a terminal user interface (tui), builtin server/broker and a Mobile / Desktop App PWA (progressive web app) https://salty.im/
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 
saltyim/format.go

65 lines
1.4 KiB

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(),
)
}