forked from PrismarineJS/prismarine-chat
-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.js
377 lines (354 loc) · 11.8 KB
/
index.js
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
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
const mojangson = require('mojangson')
const vsprintf = require('sprintf-js').vsprintf
const { MessageBuilder } = require('./MessageBuilder')('1.8.9')
class ChatMessage {
constructor (message, displayWarning = false) {
if (typeof message === 'string') {
if (message === '') {
this.json = { text: '' }
} else {
this.json = MessageBuilder.fromString(message, { colorSeparator: '§' })
}
} else if (typeof message === 'number') {
this.json = { text: message }
} else if (typeof message === 'object' && Array.isArray(message)) {
this.json = { extra: message }
} else if (typeof message === 'object') {
this.json = message
} else {
throw new Error('Expected String or Object for Message argument')
}
this.parse(displayWarning)
}
/**
* Parses the this.json property to decorate the properties of the ChatMessage.
* Called by the Constructor
* @return {void}
*/
parse (displayWarning = false) {
const json = this.json
// Message scope for callback functions
// There is EITHER, a text property or a translate property
// If there is no translate property, there is no with property
// HOWEVER! If there is a translate property, there may not be a with property
if (typeof json.text === 'string' || typeof json.text === 'number') {
this.text = json.text
} else if (typeof json.translate === 'string') {
this.translate = json.translate
if (typeof json.with === 'object') {
if (!Array.isArray(json.with)) {
throw new Error('Expected with property to be an Array in ChatMessage')
}
this.with = json.with.map(entry => new ChatMessage(entry))
}
}
// Parse extra property
// Extras are appended to the initial text
if (typeof json.extra === 'object') {
if (!Array.isArray(json.extra)) {
throw new Error('Expected extra property to be an Array in ChatMessage')
}
this.extra = json.extra.map(entry => new ChatMessage(entry))
}
// Text modifiers
this.bold = json.bold
this.italic = json.italic
this.underlined = json.underlined
this.strikethrough = json.strikethrough
this.obfuscated = json.obfuscated
// Supported constants @ 2014-04-21
const supportedColors = [
'black',
'dark_blue',
'dark_green',
'dark_aqua',
'dark_red',
'dark_purple',
'gold',
'gray',
'dark_gray',
'blue',
'green',
'aqua',
'red',
'light_purple',
'yellow',
'white',
'obfuscated',
'bold',
'strikethrough',
'underlined',
'italic',
'reset'
]
const supportedClick = [
'open_url',
'open_file',
'run_command',
'suggest_command'
]
const supportedHover = [
'show_text',
'show_achievement',
'show_item',
'show_entity'
]
// Parse color
this.color = json.color
switch (this.color) {
case 'obfuscated':
this.obfuscated = true
this.color = null
break
case 'bold':
this.bold = true
this.color = null
break
case 'strikethrough':
this.strikethrough = true
this.color = null
break
case 'underlined':
this.underlined = true
this.color = null
break
case 'italic':
this.italic = true
this.color = null
break
case 'reset':
this.reset = true
this.color = null
break
}
// Make sure color is valid
if (Array.prototype.indexOf && this.color &&
supportedColors.indexOf(this.color) === -1 &&
!this.color.match(/#[a-fA-F\d]{6}/) && displayWarning) {
console.warn('ChatMessage parsed with unsupported color', this.color)
}
// Parse click event
if (typeof json.clickEvent === 'object') {
this.clickEvent = json.clickEvent
if (typeof this.clickEvent.action !== 'string') {
throw new Error('ClickEvent action missing in ChatMessage')
} else if (Array.prototype.indexOf && supportedClick.indexOf(this.clickEvent.action) === -1 && displayWarning) {
console.warn('ChatMessage parsed with unsupported clickEvent', this.clickEvent.action)
}
}
// Parse hover event
if (typeof json.hoverEvent === 'object') {
this.hoverEvent = json.hoverEvent
if (typeof this.hoverEvent.action !== 'string') {
throw new Error('HoverEvent action missing in ChatMessage')
} else if (Array.prototype.indexOf && supportedHover.indexOf(this.hoverEvent.action) === -1 && displayWarning) {
console.warn('ChatMessage parsed with unsupported hoverEvent', this.hoverEvent.action)
}
// Special case
if (this.hoverEvent.action === 'show_item') {
let content
if (this.hoverEvent.value instanceof Array) {
if (this.hoverEvent.value[0] instanceof Object) {
content = this.hoverEvent.value[0].text
} else {
content = this.hoverEvent.value[0]
}
} else {
if (this.hoverEvent.value instanceof Object) {
content = this.hoverEvent.value.text
} else {
content = this.hoverEvent.value
}
}
try {
this.hoverEvent.value = mojangson.parse(content)
} catch (err) {
}
}
}
}
/**
* Append one or more ChatMessages
* @param {...object|string} messages ChatMessage
* @return {void}
*/
append (...messages) {
if (this.extra === undefined) this.extra = []
messages.forEach((message) => {
if (typeof message === 'object' && !Array.isArray(message)) {
this.extra.push(message)
} else if (typeof message === 'string') {
this.extra.push(new ChatMessage(message))
}
})
}
/**
* Returns a clone of the ChatMessage
* @return {ChatMessage}
*/
clone () {
return new ChatMessage(JSON.parse(JSON.stringify(this.json)))
}
/**
* Returns the count of text extras and child ChatMessages
* Does not count recursively in to the children
* @return {Number}
*/
length () {
let count = 0
if (this.text) count++
else if (this.with) count += this.with.length
if (this.extra) count += this.extra.length
return count
}
/**
* Returns a text part from the message
* @param {Number} idx Index of the part
* @return {String}
*/
getText (idx, lang = 'en-US') {
// If the index is not defined is is invalid, return toString
if (typeof idx !== 'number') return this.toString(lang)
// If we are not a translating message, return the text
if (this.text && idx === 0) return this.text.replace(/§[0-9a-flnmokr]/g, '')
// Else return the with child if it's in range
else if (this.with.length > idx) return this.with[idx].toString(lang)
// Else return the extra if it's in range
if (this.extra && this.extra.length + (this.text ? 1 : this.with.length) > idx) {
return this.extra[idx - (this.text ? 1 : this.with.length)].toString(lang)
}
// Not sure how you want to default this
// Undefined, an error ?
return ''
}
/**
* Flattens the message in to plain-text
* @return {String}
*/
toString (lang = 'en-US') {
let message = ''
if (typeof this.text === 'string' || typeof this.text === 'number') message += this.text
else if (this.with) {
const args = this.with.map(entry => entry.toString(lang))
const format = lang[this.translate]
if (!format) message += args.join('')
else message += vsprintf(format, args)
} else if (this.translate) {
message += lang[this.translate]
}
if (this.extra) {
message += this.extra.map((entry) => entry.toString(lang)).join('')
}
return message.replace(/§[0-9a-flnmokr]/g, '')
}
valueOf () {
return this.toString()
}
toMotd (lang = 'en-US', parent = {}) {
const codes = {
color: {
black: '§0',
dark_blue: '§1',
dark_green: '§2',
dark_aqua: '§3',
dark_red: '§4',
dark_purple: '§5',
gold: '§6',
gray: '§7',
dark_gray: '§8',
blue: '§9',
green: '§a',
aqua: '§b',
red: '§c',
light_purple: '§d',
yellow: '§e',
white: '§f'
},
bold: '§l',
italic: '§o',
underlined: '§n',
strikethrough: '§m',
obfuscated: '§k'
}
let message = Object.keys(codes).map((code) => {
this[code] = this[code] || parent[code]
// don't color code empty strings
if (!this[code] || this[code] === 'false' || this.text === '') return null
if (code === 'color') {
// return hex codes in this format
if (this.color.startsWith('#')) return `§${this.color}`
return codes.color[this.color]
}
return codes[code]
}).join('')
// don't add empty strings
if ((typeof this.text === 'string' || typeof this.text === 'number') && this.text !== '') message += `${this.text}§r`
else if (this.with) {
const args = this.with.map(entry => entry.toMotd(lang))
const format = lang[this.translate]
if (!format) message += args.join('')
else message += vsprintf(format, args)
} else if (this.translate) {
message += lang[this.translate]
}
if (this.extra) {
message += this.extra.map(entry => entry.toMotd(lang, this)).join('')
}
return message
}
toAnsi (lang = 'en-US', message) {
const codes = {
'§0': '\u001b[38;5;240m',
'§1': '\u001b[38;5;19m',
'§2': '\u001b[38;5;34m',
'§3': '\u001b[38;5;37m',
'§4': '\u001b[38;5;124m',
'§5': '\u001b[38;5;127m',
'§6': '\u001b[38;5;214m',
'§7': '\u001b[38;5;250m',
'§8': '\u001b[38;5;245m',
'§9': '\u001b[38;5;63m',
'§a': '\u001b[38;5;83m',
'§b': '\u001b[38;5;87m',
'§c': '\u001b[38;5;203m',
'§d': '\u001b[38;5;207m',
'§e': '\u001b[38;5;227m',
'§f': '\u001b[97m',
'§l': '\u001b[1m',
'§o': '\u001b[3m',
'§n': '\u001b[4m',
'§m': '\u001b[9m',
'§k': '\u001b[6m',
'§r': '\u001b[0m'
}
if (message == null) message = this.toMotd(lang)
for (const k in codes) {
message = message.replace(new RegExp(k, 'g'), codes[k])
}
const hexRegex = /§#?([a-fA-F\d]{2})([a-fA-F\d]{2})([a-fA-F\d]{2})/
while (message.search(hexRegex) !== -1) {
// Stolen from https://stackoverflow.com/questions/5623838/rgb-to-hex-and-hex-to-rgb
const hexCodes = hexRegex.exec(message)
// Iterate over each hexColorCode match (§#69420, §#ABCDEF, §#A1B2C3)
const red = parseInt(hexCodes[1], 16)
const green = parseInt(hexCodes[2], 16)
const blue = parseInt(hexCodes[3], 16)
// ANSI from https://gist.github.com/fnky/458719343aabd01cfb17a3a4f7296797#rgb-colors
message = message.replace(hexRegex, `\u001b[38;2;${red};${green};${blue}m`)
}
return message + '\u001b[0m'
}
static fromNotch (msg) {
let toRet
try {
toRet = new ChatMessage(JSON.parse(msg))
} catch (e) {
toRet = new ChatMessage(msg)
}
return toRet
}
}
module.exports = {
ChatMessage,
MessageBuilder
}