forked from PrismarineJS/flying-squid
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlogin.js
254 lines (224 loc) · 8.09 KB
/
login.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
const Vec3 = require('vec3').Vec3
const crypto = require('crypto')
const playerDat = require('../playerDat')
const convertInventorySlotId = require('../convertInventorySlotId')
const plugins = require('./index')
module.exports.server = function (serv, options) {
serv._server.on('connection', (client) => {
client.on('error', error => serv.emit('clientError', client, error))
})
serv._server.on('login', async (client) => {
if (!serv.pluginsReady) {
client.end('Server is still starting! Please wait before reconnecting.')
serv.info(`[${client.socket.remoteAddress}] ${client.username} (${client.uuid}) disconnected as server is still starting`)
return
}
serv.debug?.(`[login] ${client.socket?.remoteAddress} - ${client.username} (${client.uuid}) connected`, client.version, client.protocolVersion)
try {
const player = serv.initEntity('player', null, serv.overworld, new Vec3(0, 0, 0))
player._client = client
player.profileProperties = player._client.profile ? player._client.profile.properties : []
for (const plugin of plugins.builtinPlugins) plugin.player?.(player, serv, options)
serv.emit('newPlayer', player)
player.emit('asap')
await player.login()
} catch (err) {
setTimeout(() => { throw err }, 0)
}
})
serv.hashedSeed = [0, 0]
serv.on('seed', (seed) => {
const seedBuf = Buffer.allocUnsafe(8)
seedBuf.writeBigInt64LE(BigInt(seed))
const seedHash = crypto.createHash('sha256').update(seedBuf).digest().subarray(0, 8).readBigInt64LE()
serv.hashedSeed = [Number(BigInt.asIntN(64, seedHash) < 0 ? -(BigInt.asUintN(32, (-seedHash) >> 32n) + 1n) : seedHash >> 32n), Number(BigInt.asIntN(32, seedHash & (2n ** 32n - 1n)))] // convert BigInt to mcpc long
})
}
module.exports.player = async function (player, serv, settings) {
const Item = require('prismarine-item')(serv.registry)
let playerData
async function addPlayer () {
player.type = 'player'
player.crouching = false // Needs added in prismarine-entity later
player.op = settings['everybody-op'] // REMOVE THIS WHEN OUT OF TESTING
player.username = player._client.username
player.uuid = player._client.uuid
await player.findSpawnPoint()
playerData = await playerDat.read(player.uuid, player.spawnPoint, settings.worldFolder)
Object.keys(playerData.player).forEach(k => { player[k] = playerData.player[k] })
serv.players.push(player)
serv.uuidToPlayer[player.uuid] = player
player.loadedChunks = {}
}
function updateInventory () {
playerData.inventory.forEach((item) => {
const itemName = item.id.value.slice(10) // skip game brand prefix
const theItem = serv.registry.itemsByName[itemName] || serv.registry.blocksByName[itemName]
let newItem
if (serv.registry.version['<']('1.13')) newItem = new Item(theItem.id, item.Count.value, item.Damage.value)
else if (item.tag) newItem = new Item(theItem.id, item.Count.value, item.tag)
else newItem = new Item(theItem.id, item.Count.value)
const slot = convertInventorySlotId.fromNBT(item.Slot.value)
player.inventory.updateSlot(slot, newItem)
})
player._client.write('held_item_slot', {
slot: player.heldItemSlot
})
}
function sendLogin () {
// send init data so client will start rendering world
player._client.write('login', {
...serv.registry.loginPacket,
entityId: player.id,
levelType: 'default',
gameMode: player.gameMode,
previousGameMode: 0,
worldNames: Object.values(serv.dimensionNames),
dimensionCodec: serv.registry.loginPacket?.dimensionCodec,
worldName: serv.dimensionNames[0],
dimension: (serv.supportFeature('dimensionIsAString') || serv.supportFeature('dimensionIsAWorld')) ? serv.registry.loginPacket.dimension : 0,
hashedSeed: serv.hashedSeed,
difficulty: serv.difficulty,
viewDistance: settings['view-distance'],
reducedDebugInfo: false,
maxPlayers: Math.min(255, serv._server.maxPlayers),
enableRespawnScreen: true,
isDebug: false,
isFlat: settings.generation?.name === 'superflat'
})
if (serv.supportFeature('difficultySentSeparately')) {
player._client.write('difficulty', {
difficulty: serv.difficulty,
difficultyLocked: false
})
}
}
function sendChunkWhenMove () {
player.on('move', () => {
if (!player.sendingChunks && player.position.distanceTo(player.lastPositionChunkUpdated) > 16) { player.worldSendRestOfChunks() }
if (!serv.supportFeature('updateViewPosition')) {
return
}
const chunkX = Math.floor(player.position.x / 16)
const chunkZ = Math.floor(player.position.z / 16)
const lastChunkX = Math.floor(player.lastPositionPlayersUpdated.x / 16)
const lastChunkZ = Math.floor(player.lastPositionPlayersUpdated.z / 16)
if (chunkX !== lastChunkX || chunkZ !== lastChunkZ) {
player._client.write('update_view_position', {
chunkX,
chunkZ
})
}
})
}
function updateTime () {
player._client.write('update_time', {
age: [0, 0],
time: [0, serv.time]
})
}
player.setGameMode = (gameMode) => {
if (gameMode !== player.gameMode) player.prevGameMode = player.gameMode
player.gameMode = gameMode
player._client.write('game_state_change', {
reason: 3,
gameMode: player.gameMode
})
serv._writeAll('player_info', {
action: 1,
data: [{
UUID: player.uuid,
gamemode: player.gameMode
}]
})
player.sendAbilities()
}
function fillTabList () {
player._writeOthers('player_info', {
action: 0,
data: [{
UUID: player.uuid,
name: player.username,
properties: player.profileProperties,
gamemode: player.gameMode,
ping: player._client.latency
}]
})
player._client.write('player_info', {
action: 0,
data: serv.players.map((otherPlayer) => ({
UUID: otherPlayer.uuid,
name: otherPlayer.username,
properties: otherPlayer.profileProperties,
gamemode: otherPlayer.gameMode,
ping: otherPlayer._client.latency
}))
})
setInterval(() => player._client.write('player_info', {
action: 2,
data: serv.players.map(otherPlayer => ({
UUID: otherPlayer.uuid,
ping: otherPlayer._client.latency
}))
}), 5000)
}
function announceJoin () {
serv.broadcast(serv.color.yellow + player.username + ' joined the game.')
player.emit('connected')
}
player.waitPlayerLogin = () => {
const events = ['flying', 'look']
return new Promise(function (resolve) {
const listener = () => {
events.map(event => player._client.removeListener(event, listener))
resolve()
}
events.map(event => player._client.on(event, listener))
})
}
function sendStatus () {
player._client.write('held_item_slot', { slot: 0 })
player._client.write('entity_status', {
entityId: player.id,
entityStatus: 23
})
player._client.write('entity_status', {
entityId: player.id,
entityStatus: 24
})
}
player.login = async () => {
if (serv.uuidToPlayer[player.uuid]) {
player.kick('You are already connected')
return
}
if (serv.bannedPlayers[player.uuid]) {
player.kick(serv.bannedPlayers[player.uuid].reason)
return
}
if (serv.bannedIPs[player._client.socket?.remoteAddress]) {
player.kick(serv.bannedIPs[player._client.socket?.remoteAddress].reason)
return
}
await addPlayer()
sendLogin()
sendStatus()
player.sendSpawnPosition()
player.sendSelfPosition()
player.sendAbilities()
await player.worldSendInitialChunks()
player.setXp(player.xp)
updateInventory()
updateTime()
fillTabList()
player.updateAndSpawn()
announceJoin()
// mineflayer emits spawn event on health update so it needs to be done as last step
player.updateHealth(player.health)
player.emit('spawned')
await player.waitPlayerLogin()
player.worldSendRestOfChunks()
sendChunkWhenMove()
player.save()
}
}