-
Notifications
You must be signed in to change notification settings - Fork 0
/
lobby.py
254 lines (225 loc) · 8.19 KB
/
lobby.py
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
#!/usr/bin/python3
# PyCraft lobby
from utils.nolog import *
from pycraft.server import *
from pycraft.client import *
logstart('Lobby')
class LobbyConfig(ServerConfig):
version_name = 'PyCraft Lobby {}'
default_gamemode = 1
difficulty = 0
players_max = -1
reduced_debug_info = True
motd = "A PyCraft Lobby"
class LobbyClientConfig(ClientConfig):
connect_timeout = 1
class MCLobby(MCServer):
handlers = Handlers(MCServer.handlers)
def __init__(self, lobby_serverips, lobby_userdata, *args, config=LobbyConfig, **kwargs):
super().__init__(*args, config=config, **kwargs)
self.lobby_serverips, self.lobby_userdata = lobby_serverips, lobby_userdata
self.lobby_playerstate = Sdict(lambda: False) # False = authorization, str = register confirmation, True = logged in, other = playing
self.lobby_clientsettings = dict()
def handle_client_packet(self, c, **kwargs):
s = self.lobby_playerstate[c]
if (not isinstance(s, (bool, str))): self.pass_packets(c, s)
else: super().handle_client_packet(c, **kwargs)
def pass_packets(self, c, s):
if (isinstance(s, MCClient)):
#try: pid, p = s.handle()
#except NoServer: c.disconnect(); s.disconnect(); del self.lobby_playerstate[c]; return
#else:
# if (p is None): continue
# elif (isinstance(p, dict)): s.handlers[s, pid].send(c, **p)
# else: c.sendPacket(pid, p)
try: l, pid = s.readPacketHeader(nolog=True)
except NoServer: c.disconnect(); del self.lobby_playerstate[c]; return
except NoPacket: pass
else: c.sendPacket(pid, s.packet.read(l), nolog=True)
try: l, pid = c.readPacketHeader(nolog=True)
except NoServer: s.disconnect(); del self.lobby_playerstate[c]; return
except NoPacket: pass
else: s.sendPacket(pid, c.packet.read(l), nolog=True)
elif (isinstance(s, socket.socket)):
try:
try: c.socket.send(s.recv(2048))
except OSError as ex:
if (not isinstance(ex, socket.timeout) and ex.errno != socket.EWOULDBLOCK): raise
try: s.send(c.socket.recv(2048))
except OSError as ex:
if (not isinstance(ex, socket.timeout) and ex.errno != socket.EWOULDBLOCK): raise
except OSError: c.disconnect(); s.setblocking(True); s.close(); del self.lobby_playerstate[c]
@MCLobby.handler(S.LoginStart)
def handleLoginStart(server, c, p):
pv = requireProtocolVersion(c.pv)
if (c.pv != pv): raise Disconnect(f"Outdated {'client' if (c.pv < pv) else 'server'}")
try: profile = MojangAPI.profile(p.name)[0]
except Exception: profile = {'name': p.name, 'id': uuid3(NAMESPACE_OID, "OfflinePlayer:"+p.name)}
c.player = server.entities.add_player(Player(
name=profile['name'],
uuid=profile['id'],
gamemode=server.config.default_gamemode,
dimension=-1,
))
C.LoginSuccess.send(c,
uuid = c.player.uuid,
username = c.player.name,
)
c.setstate(PLAY)
C.JoinGame.send(c,
eid = c.player.eid,
gamemode = c.player.gamemode,
dimension = c.player.dimension,
difficulty = server.env.difficulty,
players_max = server.config.players_max,
level_type = server.config.level_type,
reduced_debug_info = server.config.reduced_debug_info,
)
C.PlayerPositionAndLook.send(c,
x = c.player.pos.x,
y = c.player.pos.head_y,
z = c.player.pos.z,
yaw = c.player.pos.yaw,
pitch = c.player.pos.pitch,
on_ground = c.player.pos.on_ground,
flags = 0,
)
C.ChatMessage.send(c,
message = {'text': '', 'extra': [
{'text': server.config.motd, 'bold': True},
]},
)
registered = (c.player.name in server.lobby_userdata)
C.ChatMessage.send(c,
message = {'text': '', 'extra': [
{'text': "[Login]" if (registered) else "[Register]", 'color': 'green' if (registered) else 'blue', 'bold': True},
{'text': " Enter your password."},
]},
)
@MCLobby.handler(S.ChatMessage)
def handleChatMessage(server, c, p):
phash = hashlib.sha3_256(b'Py\0'+p.message.encode()+b'\1Craft').hexdigest()
if (server.lobby_playerstate[c] is None):
del server.lobby_playerstate[c]
raise Disconnect("Error.", color='red')
if (server.lobby_playerstate[c] is False):
if (c.player.name not in server.lobby_userdata):
server.lobby_playerstate[c] = phash
C.ChatMessage.send(c,
message = {'text': "Confirm the password"},
)
return
if (phash != server.lobby_userdata[c.player.name]): raise Disconnect("Wrong password.", color='red')
server.lobby_playerstate[c] = True
done = 'Login'
elif (isinstance(server.lobby_playerstate[c], str)):
if (server.lobby_playerstate[c] != phash): raise Disconnect("Passwords don't match.", color='red')
server.lobby_userdata[c.player.name] = phash
server.lobby_playerstate[c] = True
done = 'Register'
else:
try: server_ip = server.lobby_serverips[int(p.message)-(int(p.message) > 0)]
except Exception as ex: raise Disconnect({'text': f"{type(ex).__name__}: ", 'color': 'red', 'bold': True}, {'text': str(ex)})
try: cs = server.lobby_clientsettings.pop(c)
except KeyError: cs = None
class config(LobbyClientConfig):
username = c.player.name
if (cs is not None):
locale = cs.locale
difficulty = cs.difficulty
view_distance = cs.view_distance
chat_mode = cs.chat_flags & 0b11
chat_colors = cs.chat_colors
skin_parts = cs.skin_parts if ('skin_parts' in cs) else cs.show_cape
main_hand = cs.get('main_hand', 1)
try: sc = Builder(MCClient, config=config, pv=c.pv, nolog=True) \
.connect(server_ip) \
.login() \
.block(pid=C.JoinGame) \
.build()
except NoServer: raise Disconnect("This server is offline.", color='red')
except Exception as ex: raise Disconnect({'text': f"{type(ex).__name__}: ", 'color': 'red', 'bold': True}, {'text': str(ex)})
#C.Respawn.send(c,
# dimension = (sc.player.dimension+1) % 2,
# difficulty = sc.difficulty,
# gamemode = sc.player.gamemode,
# level_type = sc.level_type,
#)
#C.PlayerPositionAndLook.send(c,
# x = sc.player.pos.x,
# y = sc.player.pos.y,
# z = sc.player.pos.z,
# yaw = sc.player.pos.yaw,
# pitch = sc.player.pos.pitch,
# on_ground = sc.player.pos.on_ground,
# flags = 0,
#)
if (not (c.player.dimension == sc.player.dimension
and server.env.difficulty == sc.difficulty
and c.player.gamemode == sc.player.gamemode
and server.config.level_type == sc.level_type)):
C.Respawn.send(c,
dimension = sc.player.dimension,
difficulty = sc.difficulty,
gamemode = sc.player.gamemode,
level_type = sc.level_type,
)
sc.socket.setblocking(False)
c.socket.setblocking(False)
server.lobby_playerstate[c] = sc.socket
return
C.ChatMessage.send(c,
message = {'text': '', 'extra': [
{'text': f"{done} successful!", 'color': 'green'},
]},
)
C.ChatMessage.send(c,
message = {'text': "Choose the server to join:"},
)
for ii, i in enumerate(server.lobby_serverips):
try: s = Builder(MCClient, config=LobbyClientConfig, nolog=True).connect(i).build().status()
except NoServer:
m = [
{'text': f"[{ii+1}] ", 'bold': True, 'color': 'dark_gray'},
{'text': "<offline>", 'color': 'dark_gray'},
]
except Exception as ex:
m = [
{'text': f"[{ii+1}] ", 'bold': True, 'color': 'red'},
{'text': f"<error: {ex}>", 'color': 'red'},
]
else:
m = [
{'text': f"[{ii+1}] ", 'bold': True},
s['description'],
{'text': f" ({s['players']['online']}/{s['players']['max']}, {s['version']['name']})"},
]
C.ChatMessage.send(c,
message = {'text': '', 'extra': m},
)
@MCLobby.handler(S.ClientSettings)
def handleClientSettings(server, c, p):
server.lobby_clientsettings[c] = p
@apmain
@aparg('serverlist', metavar='<serverlist>', type=argparse.FileType('r'))
@aparg('-p', '--port', metavar='port', type=int, default=25565)
def main(cargs):
global lobby_userdata
lobby_userdata = dict()
setlogfile('PyCraft_lobby.log')
db.setfile('PyCraft_lobby.db')
db.register('lobby_userdata')
db.load()
ips = [tuple(cast(str, int)(i.strip().split(':'))) for i in cargs.serverlist if i.strip()[:1] not in '#']
class config(LobbyConfig):
server_port = cargs.port
motd = f"§d§lPyCraft§f Lobby§r of §{'bc'[not ips]}§l{decline(len(ips), ('server', 'servers'), sep='§r ')}"
server = MCLobby(ips, lobby_userdata, config=config)
server.start()
while (True):
try: server.handle()
except Exception as ex: exception(ex)
except KeyboardInterrupt: sys.stderr.write('\r'); server.stop(); exit()
if (__name__ == '__main__'): exit(main())
else: logimported()
# by Sdore, 2020