forked from Tnze/go-mc
-
Notifications
You must be signed in to change notification settings - Fork 0
/
message.go
335 lines (296 loc) · 8.07 KB
/
message.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
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
// Package chat implements Minecraft's chat message encoding system.
//
// The type Message is the Minecraft chat message. Can be encoded as JSON
// or net/packet.Field .
//
// It's very recommended that use SetLanguage before using Message.String or Message.ClearString,
// or the `github.com/SkyVillageMC/go-mc/data/en-us` will be used.
// Note: The package of data/lang/... will SetLanguage on theirs init() so you don't need to call by your self.
//
// Some of these docs is copied from https://wiki.vg/Chat.
package chat
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"io"
"regexp"
"strings"
en_us "github.com/SkyVillageMC/go-mc/data/lang/en-us"
pk "github.com/SkyVillageMC/go-mc/net/packet"
)
const (
Chat = iota
System
GameInfo
SayCommand
MsgCommand
TeamMsgCommand
EmoteCommand
TellrawCommand
)
// Colors
const (
Black = "black"
DarkBlue = "dark_blue"
DarkGreen = "dark_green"
DarkAqua = "dark_aqua"
DarkRed = "dark_red"
DarkPurple = "dark_purple"
Gold = "gold"
Gray = "gray"
DarkGray = "dark_gray"
Blue = "blue"
Green = "green"
Aqua = "aqua"
Red = "red"
LightPurple = "light_purple"
Yellow = "yellow"
White = "white"
)
// Message is a message sent by other
type Message struct {
Text string `json:"text"`
Bold bool `json:"bold,omitempty"` // 粗体
Italic bool `json:"italic,omitempty"` // 斜体
UnderLined bool `json:"underlined,omitempty"` // 下划线
StrikeThrough bool `json:"strikethrough,omitempty"` // 删除线
Obfuscated bool `json:"obfuscated,omitempty"` // 随机
// Font of the message, could be one of minecraft:uniform, minecraft:alt or minecraft:default
// This option is only valid on 1.16+, otherwise the property is ignored.
Font string `json:"font,omitempty"` // 字体
Color string `json:"color,omitempty"` // 颜色
// Insertion contains text to insert. Only used for messages in chat.
// When shift is held, clicking the component inserts the given text
// into the chat box at the cursor (potentially replacing selected text).
Insertion string `json:"insertion,omitempty"`
ClickEvent *ClickEvent `json:"clickEvent,omitempty"`
HoverEvent *HoverEvent `json:"hoverEvent,omitempty"`
Translate string `json:"translate,omitempty"`
With []Message `json:"with,omitempty"`
Extra []Message `json:"extra,omitempty"`
}
// Same as Message, but "Text" is omitempty
type translateMsg struct {
Text string `json:"text,omitempty"`
Bold bool `json:"bold,omitempty"`
Italic bool `json:"italic,omitempty"`
UnderLined bool `json:"underlined,omitempty"`
StrikeThrough bool `json:"strikethrough,omitempty"`
Obfuscated bool `json:"obfuscated,omitempty"`
Font string `json:"font,omitempty"`
Color string `json:"color,omitempty"`
Insertion string `json:"insertion,omitempty"`
ClickEvent *ClickEvent `json:"clickEvent,omitempty"`
HoverEvent *HoverEvent `json:"hoverEvent,omitempty"`
Translate string `json:"translate"`
With []Message `json:"with,omitempty"`
Extra []Message `json:"extra,omitempty"`
}
type jsonMsg Message
func (m Message) MarshalJSON() ([]byte, error) {
if m.Translate != "" {
return json.Marshal(translateMsg(m))
} else {
return json.Marshal(jsonMsg(m))
}
}
// UnmarshalJSON decode json to Message
func (m *Message) UnmarshalJSON(raw []byte) (err error) {
raw = bytes.TrimSpace(raw)
if len(raw) == 0 {
return io.EOF
}
// The right way to distinguish JSON String and Object
// is to look up the first character.
switch raw[0] {
case '"':
return json.Unmarshal(raw, &m.Text) // Unmarshal as jsonString
case '{':
return json.Unmarshal(raw, (*jsonMsg)(m)) // Unmarshal as jsonMsg
case '[':
return json.Unmarshal(raw, &m.Extra) // Unmarshal as []Message
default:
return errors.New("unknown chat message type: '" + string(raw[0]) + "'")
}
}
// ReadFrom decode Message in a ChatMsg packet
func (m *Message) ReadFrom(r io.Reader) (int64, error) {
var code pk.String
n, err := code.ReadFrom(r)
if err != nil {
return n, err
}
err = json.Unmarshal([]byte(code), m)
return n, err
}
// WriteTo encode Message into a ChatMsg packet
func (m Message) WriteTo(w io.Writer) (int64, error) {
code, err := json.Marshal(m)
if err != nil {
panic(err)
}
return pk.String(code).WriteTo(w)
}
// Append extra message to the end of the message and return the new one.
// The source message remains unchanged.
func (m Message) Append(extraMsg ...Message) Message {
origLen := len(m.Extra)
finalLen := origLen + len(extraMsg)
var extra []Message
if cap(m.Extra) < len(m.Extra)+len(extraMsg) {
extra = make([]Message, finalLen)
copy(extra, m.Extra)
} else {
extra = m.Extra[:finalLen]
}
copy(extra[origLen:], extraMsg)
m.Extra = extra
return m
}
func (m Message) SetColor(color string) Message {
m.Color = color
return m
}
func Text(str string) Message {
return Message{Text: str}
}
func TranslateMsg(key string, with ...Message) (m Message) {
m.Translate = key
m.With = with
return
}
var fmtCode = map[byte]string{
'0': "30",
'1': "34",
'2': "32",
'3': "36",
'4': "31",
'5': "35",
'6': "33",
'7': "37",
'8': "90",
'9': "94",
'a': "92",
'b': "96",
'c': "91",
'd': "95",
'e': "93",
'f': "97",
// 'k':"", //random
'l': "1",
'm': "9",
'n': "4",
'o': "3",
'r': "0",
}
var colors = map[string]string{
Black: "30",
DarkBlue: "34",
DarkGreen: "32",
DarkAqua: "36",
DarkRed: "31",
DarkPurple: "35",
Gold: "33",
Gray: "37",
DarkGray: "90",
Blue: "94",
Green: "92",
Aqua: "96",
Red: "91",
LightPurple: "95",
Yellow: "93",
White: "97",
}
// translateMap is the translation table.
// By default, it's en-us.
var translateMap = en_us.Map
// SetLanguage set the default language used by String() and ClearString().
func SetLanguage(trans map[string]string) {
translateMap = trans
}
// ClearString return the message String without escape sequence for ansi color.
func (m Message) ClearString() string {
var msg strings.Builder
text, _ := TransCtrlSeq(m.Text, false)
msg.WriteString(text)
// handle translate
if m.Translate != "" {
args := make([]interface{}, len(m.With))
for i, v := range m.With {
args[i] = v.ClearString()
}
_, _ = fmt.Fprintf(&msg, translateMap[m.Translate], args...)
}
if m.Extra != nil {
for i := range m.Extra {
msg.WriteString(m.Extra[i].ClearString())
}
}
return msg.String()
}
// String return the message string with escape sequence for ansi color.
// To convert Translated Message to string, you must set
// On Windows, you may want print this string using github.com/mattn/go-colorable.
func (m Message) String() string {
var msg, format strings.Builder
if m.Bold {
format.WriteString("1;")
}
if m.Italic {
format.WriteString("3;")
}
if m.UnderLined {
format.WriteString("4;")
}
if m.StrikeThrough {
format.WriteString("9;")
}
if m.Color != "" {
format.WriteString(colors[m.Color] + ";")
}
if format.Len() > 0 {
msg.WriteString("\033[" + format.String()[:format.Len()-1] + "m")
}
text, ok := TransCtrlSeq(m.Text, true)
msg.WriteString(text)
// handle translate
if m.Translate != "" {
args := make([]interface{}, len(m.With))
for i, v := range m.With {
args[i] = v
}
_, _ = fmt.Fprintf(&msg, translateMap[m.Translate], args...)
}
if m.Extra != nil {
for i := range m.Extra {
msg.WriteString(m.Extra[i].String())
}
}
if format.Len() > 0 || ok {
msg.WriteString("\033[0m")
}
return msg.String()
}
var fmtPat = regexp.MustCompile(`(?i)§[\dA-FK-OR]`)
// TransCtrlSeq will transform control sequences into ANSI code
// or simply filter them. Depends on the second argument.
// if the str contains control sequences, returned change=true.
func TransCtrlSeq(str string, ansi bool) (dst string, change bool) {
dst = fmtPat.ReplaceAllStringFunc(
str,
func(str string) string {
f, ok := fmtCode[str[2]]
if ok {
if ansi {
change = true
return "\033[" + f + "m" // enable, add ANSI code
}
return "" // disable, remove the § code
}
return str // not a § code
},
)
return
}