croc/src/message/message.go

71 lines
1.4 KiB
Go
Raw Normal View History

2019-04-30 02:03:19 +02:00
package message
import (
"encoding/json"
2021-04-17 19:33:38 +02:00
"github.com/schollz/croc/v9/src/comm"
"github.com/schollz/croc/v9/src/compress"
"github.com/schollz/croc/v9/src/crypt"
2019-09-07 18:41:24 +02:00
log "github.com/schollz/logger"
2019-04-30 02:03:19 +02:00
)
2019-04-30 04:19:48 +02:00
// Message is the possible payload for messaging
2019-04-30 02:03:19 +02:00
type Message struct {
Type string `json:"t,omitempty"`
Message string `json:"m,omitempty"`
Bytes []byte `json:"b,omitempty"`
2021-04-16 23:25:57 +02:00
Bytes2 []byte `json:"b2,omitempty"`
2019-04-30 02:03:19 +02:00
Num int `json:"n,omitempty"`
}
2019-04-30 04:19:48 +02:00
func (m Message) String() string {
b, _ := json.Marshal(m)
return string(b)
}
2019-04-30 04:50:01 +02:00
// Send will send out
2019-11-18 16:53:57 +01:00
func Send(c *comm.Comm, key []byte, m Message) (err error) {
2019-04-30 04:50:01 +02:00
mSend, err := Encode(key, m)
2019-04-30 04:19:48 +02:00
if err != nil {
return
}
err = c.Send(mSend)
2019-04-30 04:50:01 +02:00
return
2019-04-30 04:19:48 +02:00
}
// Encode will convert to bytes
2019-11-18 16:53:57 +01:00
func Encode(key []byte, m Message) (b []byte, err error) {
2019-04-30 02:03:19 +02:00
b, err = json.Marshal(m)
if err != nil {
return
}
b = compress.Compress(b)
2019-11-18 16:53:57 +01:00
if key != nil {
2020-02-28 22:02:23 +01:00
log.Debugf("writing %s message (encrypted)", m.Type)
2019-11-18 16:53:57 +01:00
b, err = crypt.Encrypt(b, key)
2020-02-28 22:02:23 +01:00
} else {
2021-04-17 00:12:11 +02:00
log.Debugf("writing %s message (unencrypted)", m.Type)
2019-11-18 16:53:57 +01:00
}
2019-04-30 02:03:19 +02:00
return
}
2019-04-30 04:19:48 +02:00
// Decode will convert from bytes
2019-11-18 16:53:57 +01:00
func Decode(key []byte, b []byte) (m Message, err error) {
if key != nil {
b, err = crypt.Decrypt(b, key)
if err != nil {
return
}
2019-04-30 02:03:19 +02:00
}
b = compress.Decompress(b)
err = json.Unmarshal(b, &m)
2021-04-17 00:12:11 +02:00
if err == nil {
if key != nil {
log.Debugf("read %s message (encrypted)", m.Type)
} else {
log.Debugf("read %s message (unencrypted)", m.Type)
}
}
2019-04-30 02:03:19 +02:00
return
}