2019-04-30 02:03:19 +02:00
|
|
|
package message
|
|
|
|
|
|
|
|
import (
|
|
|
|
"encoding/json"
|
2019-05-03 16:30:35 +02:00
|
|
|
|
|
|
|
log "github.com/cihub/seelog"
|
2019-04-30 04:50:01 +02:00
|
|
|
"github.com/schollz/croc/v6/src/comm"
|
2019-04-30 02:03:19 +02:00
|
|
|
"github.com/schollz/croc/v6/src/compress"
|
|
|
|
"github.com/schollz/croc/v6/src/crypt"
|
|
|
|
)
|
|
|
|
|
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"`
|
|
|
|
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
|
|
|
|
func Send(c *comm.Comm, key crypt.Encryption, m Message) (err error) {
|
|
|
|
mSend, err := Encode(key, m)
|
2019-04-30 04:19:48 +02:00
|
|
|
if err != nil {
|
|
|
|
return
|
|
|
|
}
|
2019-05-03 16:30:35 +02:00
|
|
|
log.Debugf("writing %s message (%d bytes)",m.Type,len(mSend))
|
2019-04-30 04:19:48 +02:00
|
|
|
_, err = c.Write(mSend)
|
2019-04-30 04:50:01 +02:00
|
|
|
return
|
2019-04-30 04:19:48 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
// Encode will convert to bytes
|
2019-04-30 04:50:01 +02:00
|
|
|
func Encode(key crypt.Encryption, 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-04-30 04:50:01 +02:00
|
|
|
b, err = key.Encrypt(b)
|
2019-04-30 02:03:19 +02:00
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2019-04-30 04:19:48 +02:00
|
|
|
// Decode will convert from bytes
|
2019-04-30 04:50:01 +02:00
|
|
|
func Decode(key crypt.Encryption, b []byte) (m Message, err error) {
|
|
|
|
b, err = key.Decrypt(b)
|
|
|
|
if err != nil {
|
|
|
|
return
|
2019-04-30 02:03:19 +02:00
|
|
|
}
|
|
|
|
b = compress.Decompress(b)
|
|
|
|
err = json.Unmarshal(b, &m)
|
|
|
|
return
|
|
|
|
}
|