-
Notifications
You must be signed in to change notification settings - Fork 1
/
messages.go
91 lines (78 loc) · 2.02 KB
/
messages.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
package main
import (
"encoding/json"
"fmt"
"github.com/nknorg/nkn-sdk-go"
)
var chatId uint64 = 0
// Message struct represents a generic message with a type and content
type Message struct {
Type string `json:"type"`
Content json.RawMessage `json:"content"`
}
type ChatMessage struct {
Id uint64 `json:"id,string"`
Text string `json:"text"`
Hash string `json:"hash"`
Src string `json:"src"`
Role string `json:"role"`
}
type DeleteChatMessage struct {
MsgId uint64 `json:"msgId,string"`
}
func DecodeMessage(receivedMessage *nkn.Message) {
// Unmarshal the JSON into a Message struct
var msg Message
if err := json.Unmarshal(receivedMessage.Data, &msg); err != nil {
fmt.Println("Error deserializing JSON:", err)
return
}
// Handle the message based on its type
switch msg.Type {
case "chat-message":
chatMsg := &ChatMessage{
Src: receivedMessage.Src,
}
if err := json.Unmarshal(msg.Content, &chatMsg); err != nil {
fmt.Println("Error unmarshalling message content:", err)
return
}
HandleChatMessage(chatMsg, receivedMessage)
case "delete-chat-message":
{
if receivedMessage.Src == config.Owner {
var deleteMsg DeleteChatMessage
if err := json.Unmarshal(msg.Content, &deleteMsg); err != nil {
fmt.Println("Error unmarshalling message content:", err)
return
}
publishText(string(receivedMessage.Data))
}
}
default:
fmt.Println("Unknown message type:", msg.Type, "content:", string(msg.Content))
}
}
func HandleChatMessage(msg *ChatMessage, nknMessage *nkn.Message) {
go func() {
fmt.Println("Message:", msg.Text)
err := ValidateDonation(msg, true)
if err != nil {
fmt.Println("donation validation error", err.Error())
nknMessage.Reply([]byte("error: donation validation error - " + err.Error()))
return
} else {
nknMessage.Reply([]byte("success"))
}
msg.Id = chatId
if msg.Src == config.Owner {
msg.Role = "owner"
}
chatId++
binary, err := json.Marshal(msg)
if err != nil {
panic(err)
}
publish(binary)
}()
}