chipmunkbot3/util/player_data.js
2024-05-27 18:35:11 -04:00

72 lines
2 KiB
JavaScript

const PersistentData = require('./persistent_data')
const nbt = require('prismarine-nbt')
class PlayerData extends PersistentData {
_bots = new Set()
parse (data) {
const parsed = {}
data = data.value // * Convenient since I don't need to write data.value a bunch of times
if (data.username) parsed.username = data.username?.value
if (data.seen?.value) {
parsed.seen = {}
if (data.seen.value.first?.value) parsed.seen.first = new Date(Number(data.seen.value.first?.value))
if (data.seen.value.last?.value) parsed.seen.last = new Date(Number(data.seen.value.last?.value))
}
if (data.mail?.value?.value && Array.isArray(data.mail.value.value)) {
parsed.mail = data.mail.value.value.map(this.#parseMail)
}
return parsed
}
#parseMail (mail) {
const signedPort = Number(mail?.port?.value ?? 25565)
const uint16Array = new Uint16Array(1)
uint16Array[0] = signedPort
const unsignedPort = uint16Array[0]
return {
sender: String(mail?.sender?.value),
message: String(mail?.message?.value),
host: String(mail?.host?.value),
port: unsignedPort
}
}
unparse (parsed) {
const data = {}
if (parsed.username) data.username = nbt.string(parsed.username)
if (parsed.seen) {
data.seen = nbt.comp({ first: nbt.long(BigInt(parsed.seen.first.getTime())), last: nbt.long(BigInt(parsed.seen.last.getTime())) })
}
if (parsed.mail) {
data.mail = nbt.list(nbt.comp(parsed.mail.map(this.#unparseMail)))
}
return nbt.comp(data)
}
#unparseMail (mail) {
const unsignedPort = mail.port ?? 25565
const int16Array = new Int16Array(1)
int16Array[0] = unsignedPort
const signedPort = int16Array[0]
const result = {
sender: nbt.string(mail.sender),
message: nbt.string(mail.message),
host: nbt.string(mail.host)
}
if (unsignedPort !== 25565) result.port = nbt.short(signedPort)
return result
}
}
module.exports = PlayerData