meowlib/usermessage.go

61 lines
1.6 KiB
Go
Raw Normal View History

2022-01-15 22:19:29 +01:00
package meowlib
import (
"encoding/json"
"strings"
"time"
"github.com/google/uuid"
"github.com/rs/zerolog/log"
)
type InternalMessage struct {
With Peer `json:"with,omitempty"`
SentByMe bool `json:"sent_by_me,omitempty"`
MessageData UserMessage `json:"message_data,omitempty"`
ServerUuid string `json:"server_uuid,omitempty"`
Received time.Time `json:"received,omitempty"`
Processed time.Time `json:"processed,omitempty"`
TransferPath []Server `json:"transfer_path,omitempty"`
}
func CreateText(Destination Peer, text string) *InternalMessage {
var msg InternalMessage
msg.With = Destination
msg.SentByMe = true
msg.MessageData.From = Destination.Me.Public
msg.MessageData.Destination = Destination.Contact.ContactPublicKey
msg.MessageData.Status.Sent = uint64(time.Now().Unix())
msg.MessageData.Status.LocalUuid = strings.Replace(uuid.New().String(), "-", "", -1)
msg.MessageData.Type = "t"
msg.MessageData.Data = []byte(text)
return &msg
}
func (msg *UserMessage) Pack() *PackedUserMessage {
var pck PackedUserMessage
jsonMsg, _ := json.Marshal(msg)
armor, err := Encrypt(msg.Destination, jsonMsg)
if err != nil {
log.Error().Msg("Message encryption failed")
}
pck.Destination = msg.Destination
pck.Payload = []byte(armor)
return &pck
}
func (pck *PackedUserMessage) Unpack(privateKey string) *UserMessage {
var msg *UserMessage
decrypted, err := Decrypt(privateKey, pck.Payload)
if err != nil {
log.Error().Msg("Message decryption failed")
}
err = json.Unmarshal(decrypted, &msg)
if err != nil {
log.Error().Msg("Message encryption failed")
}
return msg
}