-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathpackets.py
1288 lines (978 loc) · 30.6 KB
/
packets.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
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
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# -*- coding: utf-8 -*-
# NOTE: at some point, parts (or all) of this may
# be rewritten in cython (or c++ ported with cython)?
# i'm not sure how well it works with an async setup
# like this, but we'll see B) massive speed gains tho
import random
import struct
from abc import ABC
from enum import IntEnum, unique
from functools import cache, lru_cache
from typing import TYPE_CHECKING, Iterator, NamedTuple, Sequence, Union
from constants.gamemodes import GameMode
from constants.mods import Mods
from constants.types import osuTypes
from objects import glob
#from objects.beatmap import BeatmapInfo
from objects.match import (Match, MatchTeams, MatchTeamTypes,
MatchWinConditions, ScoreFrame, SlotStatus)
from utils.misc import escape_enum, pymysql_encode
if TYPE_CHECKING:
from objects.player import Player
# tuple of some of struct's format specifiers
# for clean access within packet pack/unpack.
@unique
@pymysql_encode(escape_enum)
class ClientPackets(IntEnum):
CHANGE_ACTION = 0
SEND_PUBLIC_MESSAGE = 1
LOGOUT = 2
REQUEST_STATUS_UPDATE = 3
PING = 4
START_SPECTATING = 16
STOP_SPECTATING = 17
SPECTATE_FRAMES = 18
ERROR_REPORT = 20
CANT_SPECTATE = 21
SEND_PRIVATE_MESSAGE = 25
PART_LOBBY = 29
JOIN_LOBBY = 30
CREATE_MATCH = 31
JOIN_MATCH = 32
PART_MATCH = 33
MATCH_CHANGE_SLOT = 38
MATCH_READY = 39
MATCH_LOCK = 40
MATCH_CHANGE_SETTINGS = 41
MATCH_START = 44
MATCH_SCORE_UPDATE = 47
MATCH_COMPLETE = 49
MATCH_CHANGE_MODS = 51
MATCH_LOAD_COMPLETE = 52
MATCH_NO_BEATMAP = 54
MATCH_NOT_READY = 55
MATCH_FAILED = 56
MATCH_HAS_BEATMAP = 59
MATCH_SKIP_REQUEST = 60
CHANNEL_JOIN = 63
BEATMAP_INFO_REQUEST = 68
MATCH_TRANSFER_HOST = 70
FRIEND_ADD = 73
FRIEND_REMOVE = 74
MATCH_CHANGE_TEAM = 77
CHANNEL_PART = 78
RECEIVE_UPDATES = 79
SET_AWAY_MESSAGE = 82
IRC_ONLY = 84
USER_STATS_REQUEST = 85
MATCH_INVITE = 87
MATCH_CHANGE_PASSWORD = 90
TOURNAMENT_MATCH_INFO_REQUEST = 93
USER_PRESENCE_REQUEST = 97
USER_PRESENCE_REQUEST_ALL = 98
TOGGLE_BLOCK_NON_FRIEND_DMS = 99
TOURNAMENT_JOIN_MATCH_CHANNEL = 108
TOURNAMENT_LEAVE_MATCH_CHANNEL = 109
def __repr__(self) -> str:
return f'<{self.name} ({self.value})>'
@unique
@pymysql_encode(escape_enum)
class ServerPackets(IntEnum):
USER_ID = 5
SEND_MESSAGE = 7
PONG = 8
HANDLE_IRC_CHANGE_USERNAME = 9 # unused
HANDLE_IRC_QUIT = 10
USER_STATS = 11
USER_LOGOUT = 12
SPECTATOR_JOINED = 13
SPECTATOR_LEFT = 14
SPECTATE_FRAMES = 15
VERSION_UPDATE = 19
SPECTATOR_CANT_SPECTATE = 22
GET_ATTENTION = 23
NOTIFICATION = 24
UPDATE_MATCH = 26
NEW_MATCH = 27
DISPOSE_MATCH = 28
TOGGLE_BLOCK_NON_FRIEND_DMS = 34
MATCH_JOIN_SUCCESS = 36
MATCH_JOIN_FAIL = 37
FELLOW_SPECTATOR_JOINED = 42
FELLOW_SPECTATOR_LEFT = 43
ALL_PLAYERS_LOADED = 45
MATCH_START = 46
MATCH_SCORE_UPDATE = 48
MATCH_TRANSFER_HOST = 50
MATCH_ALL_PLAYERS_LOADED = 53
MATCH_PLAYER_FAILED = 57
MATCH_COMPLETE = 58
MATCH_SKIP = 61
UNAUTHORIZED = 62 # unused
CHANNEL_JOIN_SUCCESS = 64
CHANNEL_INFO = 65
CHANNEL_KICK = 66
CHANNEL_AUTO_JOIN = 67
BEATMAP_INFO_REPLY = 69
PRIVILEGES = 71
FRIENDS_LIST = 72
PROTOCOL_VERSION = 75
MAIN_MENU_ICON = 76
MONITOR = 80 # unused
MATCH_PLAYER_SKIPPED = 81
USER_PRESENCE = 83
RESTART = 86
MATCH_INVITE = 88
CHANNEL_INFO_END = 89
MATCH_CHANGE_PASSWORD = 91
SILENCE_END = 92
USER_SILENCED = 94
USER_PRESENCE_SINGLE = 95
USER_PRESENCE_BUNDLE = 96
USER_DM_BLOCKED = 100
TARGET_IS_SILENCED = 101
VERSION_UPDATE_FORCED = 102
SWITCH_SERVER = 103
ACCOUNT_RESTRICTED = 104
RTX = 105 # unused
MATCH_ABORT = 106
SWITCH_TOURNAMENT_SERVER = 107
def __repr__(self) -> str:
return f'<{self.name} ({self.value})>'
class Message(NamedTuple):
sender: str
text: str
recipient: str
sender_id: int
class Channel(NamedTuple):
name: str
topic: str
players: int
class ReplayAction(IntEnum):
Standard = 0
NewSong = 1
Skip = 2
Completion = 3
Fail = 4
Pause = 5
Unpause = 6
SongSelect = 7
WatchingOther = 8
class ReplayFrame(NamedTuple):
button_state: int
taiko_byte: int # pre-taiko support (<=2008)
x: float
y: float
time: int
class ReplayFrameBundle(NamedTuple):
replay_frames: list[ReplayFrame]
score_frame: ScoreFrame
action: ReplayAction
extra: int
sequence: int
raw_data: memoryview # readonly
class BasePacket(ABC):
def __init__(self, reader: 'BanchoPacketReader') -> None: ...
async def handle(self, p: 'Player') -> None: ...
class BanchoPacketReader:
"""\
A class for reading bancho packets
from the osu! client's request body.
Attributes
-----------
body_view: `memoryview`
A readonly view of the request's body.
packet_map: `dict[ClientPackets, BasePacket]`
The map of registered packets the reader may handle.
current_length: int
The length in bytes of the packet currently being handled.
Intended Usage:
```
for packet in BanchoPacketReader(conn.body):
# once you're ready to handle the packet,
# simply call it's .handle() method.
await packet.handle()
```
"""
__slots__ = ('body_view', 'packet_map', 'current_len')
def __init__(self, body_view: memoryview, packet_map: dict) -> None:
self.body_view = body_view # readonly
self.packet_map = packet_map
self.current_len = 0 # last read packet's length
def __iter__(self) -> Iterator[BasePacket]:
return self
def __next__(self) -> BasePacket:
# do not break until we've read the
# header of a packet we can handle.
while self.body_view: # len(self.view) < 7?
p_type, p_len = self._read_header()
if p_type not in self.packet_map:
# packet type not handled, remove
# from internal buffer and continue.
if p_len != 0:
self.body_view = self.body_view[p_len:]
else:
# we can handle this one.
break
else:
raise StopIteration
# we have a packet handler for this.
packet_cls = self.packet_map[p_type]
self.current_len = p_len
return packet_cls(self)
def _read_header(self) -> tuple[ClientPackets, int]:
"""Read the header of an osu! packet (id & length)."""
# read type & length from the body
data = struct.unpack('<HxI', self.body_view[:7])
self.body_view = self.body_view[7:]
return ClientPackets(data[0]), data[1]
""" public API (exposed for packet handler's __init__ methods) """
def read_raw(self) -> memoryview:
val = self.body_view[:self.current_len]
self.body_view = self.body_view[self.current_len:]
return val
# integral types
def read_i8(self) -> int:
val = self.body_view[0]
self.body_view = self.body_view[1:]
return val - 256 if val > 127 else val
def read_u8(self) -> int:
val = self.body_view[0]
self.body_view = self.body_view[1:]
return val
def read_i16(self) -> int:
val = int.from_bytes(self.body_view[:2], 'little', signed=True)
self.body_view = self.body_view[2:]
return val
def read_u16(self) -> int:
val = int.from_bytes(self.body_view[:2], 'little', signed=False)
self.body_view = self.body_view[2:]
return val
def read_i32(self) -> int:
val = int.from_bytes(self.body_view[:4], 'little', signed=True)
self.body_view = self.body_view[4:]
return val
def read_u32(self) -> int:
val = int.from_bytes(self.body_view[:4], 'little', signed=False)
self.body_view = self.body_view[4:]
return val
def read_i64(self) -> int:
val = int.from_bytes(self.body_view[:8], 'little', signed=True)
self.body_view = self.body_view[8:]
return val
def read_u64(self) -> int:
val = int.from_bytes(self.body_view[:8], 'little', signed=False)
self.body_view = self.body_view[8:]
return val
# floating-point types
def read_f16(self) -> float:
val, = struct.unpack_from('<e', self.body_view[:2])
self.body_view = self.body_view[2:]
return val
def read_f32(self) -> float:
val, = struct.unpack_from('<f', self.body_view[:4])
self.body_view = self.body_view[4:]
return val
def read_f64(self) -> float:
val, = struct.unpack_from('<d', self.body_view[:8])
self.body_view = self.body_view[8:]
return val
# complex types
# XXX: some osu! packets use i16 for
# array length, while others use i32
def read_i32_list_i16l(self) -> tuple[int]:
length = int.from_bytes(self.body_view[:2], 'little')
self.body_view = self.body_view[2:]
val = struct.unpack(f'<{"I" * length}', self.body_view[:length * 4])
self.body_view = self.body_view[length * 4:]
return val
def read_i32_list_i32l(self) -> tuple[int]:
length = int.from_bytes(self.body_view[:4], 'little')
self.body_view = self.body_view[4:]
val = struct.unpack(f'<{"I" * length}', self.body_view[:length * 4])
self.body_view = self.body_view[length * 4:]
return val
def read_string(self) -> str:
exists = self.body_view[0] == 0x0b
self.body_view = self.body_view[1:]
if not exists:
# no string sent.
return ''
# non-empty string, decode str length (uleb128)
length = shift = 0
while True:
b = self.body_view[0]
self.body_view = self.body_view[1:]
length |= (b & 0b01111111) << shift
if (b & 0b10000000) == 0:
break
shift += 7
val = self.body_view[:length].tobytes().decode() # copy
self.body_view = self.body_view[length:]
return val
# custom osu! types
def read_message(self) -> Message:
"""Read an osu! message from the internal buffer."""
return Message(
sender=self.read_string(),
text=self.read_string(),
recipient=self.read_string(),
sender_id=self.read_i32()
)
def read_channel(self) -> Channel:
"""Read an osu! channel from the internal buffer."""
return Channel(
name=self.read_string(),
topic=self.read_string(),
players=self.read_i32()
)
def read_match(self) -> Match:
"""Read an osu! match from the internal buffer."""
m = Match()
# ignore match id (i16) and inprogress (i8).
self.body_view = self.body_view[3:]
self.read_i8() # powerplay unused
m.mods = Mods(self.read_i32())
m.name = self.read_string()
m.passwd = self.read_string()
m.map_name = self.read_string()
m.map_id = self.read_i32()
m.map_md5 = self.read_string()
for slot in m.slots:
slot.status = SlotStatus(self.read_i8())
for slot in m.slots:
slot.team = MatchTeams(self.read_i8())
for slot in m.slots:
if slot.status & SlotStatus.has_player:
# we don't need this, ignore it.
self.body_view = self.body_view[4:]
host_id = self.read_i32()
m.host = glob.players.get(id=host_id)
m.mode = GameMode(self.read_i8())
m.win_condition = MatchWinConditions(self.read_i8())
m.team_type = MatchTeamTypes(self.read_i8())
m.freemods = self.read_i8() == 1
# if we're in freemods mode,
# read individual slot mods.
if m.freemods:
for slot in m.slots:
slot.mods = Mods(self.read_i32())
# read the seed (used for mania)
m.seed = self.read_i32()
return m
def read_scoreframe(self) -> ScoreFrame:
sf = ScoreFrame(*SCOREFRAME_FMT.unpack_from(self.body_view[:29]))
self.body_view = self.body_view[29:]
if sf.score_v2:
sf.combo_portion = self.read_f64()
sf.bonus_portion = self.read_f64()
return sf
def read_replayframe(self) -> ReplayFrame:
return ReplayFrame(
button_state=self.read_u8(),
taiko_byte=self.read_u8(), # pre-taiko support (<=2008)
x=self.read_f32(),
y=self.read_f32(),
time=self.read_i32()
)
def read_replayframe_bundle(self) -> ReplayFrameBundle:
# save raw format to distribute to the other clients
raw_data = self.body_view[:self.current_len]
extra = self.read_i32() # bancho proto >= 18
framecount = self.read_u16()
frames = [self.read_replayframe() for _ in range(framecount)]
action = ReplayAction(self.read_u8())
scoreframe = self.read_scoreframe()
sequence = self.read_u16()
return ReplayFrameBundle(
frames, scoreframe, action,
extra, sequence, raw_data
)
# write functions
def write_uleb128(num: int) -> Union[bytes, bytearray]:
""" Write `num` into an unsigned LEB128. """
if num == 0:
return b'\x00'
ret = bytearray()
length = 0
while num > 0:
ret.append(num & 0b01111111)
num >>= 7
if num != 0:
ret[length] |= 0b10000000
length += 1
return ret
def write_string(s: str) -> bytes:
""" Write `s` into bytes (ULEB128 & string). """
if s:
encoded = s.encode()
ret = b'\x0b' + write_uleb128(len(encoded)) + encoded
else:
ret = b'\x00'
return ret
def write_i32_list(l: Sequence[int]) -> bytearray:
""" Write `l` into bytes (int32 list). """
ret = bytearray(len(l).to_bytes(2, 'little'))
for i in l:
ret += i.to_bytes(4, 'little')
return ret
def write_message(sender: str, msg: str, recipient: str,
sender_id: int) -> bytearray:
""" Write params into bytes (osu! message). """
ret = bytearray(write_string(sender))
ret += write_string(msg)
ret += write_string(recipient)
ret += sender_id.to_bytes(4, 'little', signed=True)
return ret
def write_channel(name: str, topic: str,
count: int) -> bytearray:
""" Write params into bytes (osu! channel). """
ret = bytearray(write_string(name))
ret += write_string(topic)
ret += count.to_bytes(2, 'little')
return ret
# XXX: deprecated
# def write_mapInfoReply(maps: Sequence[BeatmapInfo]) -> bytearray:
# """ Write `maps` into bytes (osu! map info). """
# ret = bytearray(len(maps).to_bytes(4, 'little'))
#
# # Write files
# for m in maps:
# ret += struct.pack('<hiiiBbbbb',
# m.id, m.map_id, m.set_id, m.thread_id, m.status,
# m.osu_rank, m.fruits_rank, m.taiko_rank, m.mania_rank
# )
# ret += write_string(m.map_md5)
#
# return ret
def write_match(m: Match, send_pw: bool = True) -> bytearray:
""" Write `m` into bytes (osu! match). """
# 0 is for match type
ret = bytearray(struct.pack('<HbbI', m.id, m.in_progress, 0, m.mods))
ret += write_string(m.name)
# osu expects \x0b\x00 if there's a password but it's
# not being sent, and \x00 if there's no password.
if m.passwd:
if send_pw:
ret += write_string(m.passwd)
else:
ret += b'\x0b\x00'
else:
ret += b'\x00'
ret += write_string(m.map_name)
ret += m.map_id.to_bytes(4, 'little', signed=True)
ret += write_string(m.map_md5)
ret.extend([s.status for s in m.slots])
ret.extend([s.team for s in m.slots])
for s in m.slots:
if s.status & SlotStatus.has_player:
ret += s.player.id.to_bytes(4, 'little')
ret += m.host.id.to_bytes(4, 'little')
ret.extend((m.mode, m.win_condition,
m.team_type, m.freemods))
if m.freemods:
for s in m.slots:
ret += s.mods.to_bytes(4, 'little')
ret += m.seed.to_bytes(4, 'little')
return ret
SCOREFRAME_FMT = struct.Struct('<iBHHHHHHiHH?BB?')
def write_scoreframe(s: ScoreFrame) -> bytes:
""" Write `s` into bytes (osu! scoreframe). """
return SCOREFRAME_FMT.pack(
s.time, s.id, s.num300, s.num100, s.num50, s.num_geki,
s.num_katu, s.num_miss, s.total_score, s.current_combo,
s.max_combo, s.perfect, s.current_hp, s.tag_byte, s.score_v2
)
_noexpand_types = {
# base
osuTypes.i8: struct.Struct('<b').pack,
osuTypes.u8: struct.Struct('<B').pack,
osuTypes.i16: struct.Struct('<h').pack,
osuTypes.u16: struct.Struct('<H').pack,
osuTypes.i32: struct.Struct('<i').pack,
osuTypes.u32: struct.Struct('<I').pack,
# osuTypes.f16: struct.Struct('<e').pack, # futureproofing
osuTypes.f32: struct.Struct('<f').pack,
osuTypes.i64: struct.Struct('<q').pack,
osuTypes.u64: struct.Struct('<Q').pack,
osuTypes.f64: struct.Struct('<d').pack,
# more complex
osuTypes.string: write_string,
osuTypes.i32_list: write_i32_list,
osuTypes.scoreframe: write_scoreframe,
# TODO: write replayframe & bundle?
}
_expand_types = {
# multiarg, tuple expansion
osuTypes.message: write_message,
osuTypes.channel: write_channel,
osuTypes.match: write_match,
}
def write(packid: int, *args: Sequence[object]) -> bytes:
""" Write `args` into bytes. """
ret = bytearray(struct.pack('<Hx', packid))
for p_args, p_type in args:
if p_type == osuTypes.raw:
ret += p_args
elif p_type in _noexpand_types:
ret += _noexpand_types[p_type](p_args)
elif p_type in _expand_types:
ret += _expand_types[p_type](*p_args)
# add size
ret[3:3] = struct.pack('<I', len(ret) - 3)
return bytes(ret)
#
# packets
#
# packet id: 5
@cache
def userID(id: int) -> bytes:
# id responses:
# -1: authentication failed
# -2: old client
# -3: banned
# -4: banned
# -5: error occurred
# -6: needs supporter
# -7: password reset
# -8: requires verification
# ??: valid id
return write(
ServerPackets.USER_ID,
(id, osuTypes.i32)
)
# packet id: 7
def sendMessage(sender: str, msg: str, recipient: str,
sender_id: int) -> bytes:
return write(
ServerPackets.SEND_MESSAGE,
((sender, msg, recipient, sender_id), osuTypes.message)
)
# packet id: 8
@cache
def pong() -> bytes:
return write(ServerPackets.PONG)
# packet id: 9
# NOTE: deprecated
def changeUsername(old: str, new: str) -> bytes:
return write(
ServerPackets.HANDLE_IRC_CHANGE_USERNAME,
(f'{old}>>>>{new}', osuTypes.string)
)
BOT_STATUSES = (
(3, 'the source code..'), # editing
(6, 'geohot livestreams..'), # watching
(6, 'over the server..'), # watching
(8, 'out new features..'), # testing
(9, 'a pull request..'), # submitting
)
# since the bot is always online and is
# also automatically added to all player's
# friends list, their stats are requested
# *very* frequently, and should be cached.
# NOTE: this is cleared once in a while by
# `bg_loops.reroll_bot_status` to keep fresh.
@cache
def botStats() -> bytes:
# pick at random from list of potential statuses.
status_id, status_txt = random.choice(BOT_STATUSES)
return write(
ServerPackets.USER_STATS,
(glob.bot.id, osuTypes.i32), # id
(status_id, osuTypes.u8), # action
(status_txt, osuTypes.string), # info_text
('', osuTypes.string), # map_md5
(0, osuTypes.i32), # mods
(0, osuTypes.u8), # mode
(0, osuTypes.i32), # map_id
(0, osuTypes.i64), # rscore
(0.0, osuTypes.f32), # acc
(0, osuTypes.i32), # plays
(0, osuTypes.i64), # tscore
(0, osuTypes.i32), # rank
(0, osuTypes.i16) # pp
)
# packet id: 11
def userStats(p: 'Player') -> bytes:
if p is glob.bot:
return botStats()
gm_stats = p.gm_stats
if gm_stats.pp > 0x7fff:
# over osu! pp cap, we'll have to
# show their pp as ranked score.
rscore = gm_stats.pp
pp = 0
else:
rscore = gm_stats.rscore
pp = gm_stats.pp
return write(
ServerPackets.USER_STATS,
(p.id, osuTypes.i32),
(p.status.action, osuTypes.u8),
(p.status.info_text, osuTypes.string),
(p.status.map_md5, osuTypes.string),
(p.status.mods, osuTypes.i32),
(p.status.mode.as_vanilla, osuTypes.u8),
(p.status.map_id, osuTypes.i32),
(rscore, osuTypes.i64),
(gm_stats.acc / 100.0, osuTypes.f32),
(gm_stats.plays, osuTypes.i32),
(gm_stats.tscore, osuTypes.i64),
(gm_stats.rank, osuTypes.i32),
(pp, osuTypes.i16) # why not u16 peppy :(
)
# packet id: 12
@cache
def logout(userID: int) -> bytes:
return write(
ServerPackets.USER_LOGOUT,
(userID, osuTypes.i32),
(0, osuTypes.u8)
)
# packet id: 13
@cache
def spectatorJoined(id: int) -> bytes:
return write(
ServerPackets.SPECTATOR_JOINED,
(id, osuTypes.i32)
)
# packet id: 14
@cache
def spectatorLeft(id: int) -> bytes:
return write(
ServerPackets.SPECTATOR_LEFT,
(id, osuTypes.i32)
)
# packet id: 15
# TODO: perhaps optimize this and match
# frames to be a bit more efficient, since
# they're literally spammed between clients.
def spectateFrames(data: bytes) -> bytes:
return write(
ServerPackets.SPECTATE_FRAMES,
(data, osuTypes.raw)
)
# packet id: 19
@cache
def versionUpdate() -> bytes:
return write(ServerPackets.VERSION_UPDATE)
# packet id: 22
@cache
def spectatorCantSpectate(id: int) -> bytes:
return write(
ServerPackets.SPECTATOR_CANT_SPECTATE,
(id, osuTypes.i32)
)
# packet id: 23
@cache
def getAttention() -> bytes:
return write(ServerPackets.GET_ATTENTION)
# packet id: 24
@lru_cache(maxsize=4)
def notification(msg: str) -> bytes:
return write(
ServerPackets.NOTIFICATION,
(msg, osuTypes.string)
)
# packet id: 26
def updateMatch(m: Match, send_pw: bool = True) -> bytes:
return write(
ServerPackets.UPDATE_MATCH,
((m, send_pw), osuTypes.match)
)
# packet id: 27
def newMatch(m: Match) -> bytes:
return write(
ServerPackets.NEW_MATCH,
((m, True), osuTypes.match)
)
# packet id: 28
@cache
def disposeMatch(id: int) -> bytes:
return write(
ServerPackets.DISPOSE_MATCH,
(id, osuTypes.i32)
)
# packet id: 34
@cache
def toggleBlockNonFriendPM() -> bytes:
return write(ServerPackets.TOGGLE_BLOCK_NON_FRIEND_DMS)
# packet id: 36
def matchJoinSuccess(m: Match) -> bytes:
return write(
ServerPackets.MATCH_JOIN_SUCCESS,
((m, True), osuTypes.match)
)
# packet id: 37
@cache
def matchJoinFail() -> bytes:
return write(ServerPackets.MATCH_JOIN_FAIL)
# packet id: 42
@cache
def fellowSpectatorJoined(id: int) -> bytes:
return write(
ServerPackets.FELLOW_SPECTATOR_JOINED,
(id, osuTypes.i32)
)
# packet id: 43
@cache
def fellowSpectatorLeft(id: int) -> bytes:
return write(
ServerPackets.FELLOW_SPECTATOR_LEFT,
(id, osuTypes.i32)
)
# packet id: 46
def matchStart(m: Match) -> bytes:
return write(
ServerPackets.MATCH_START,
((m, True), osuTypes.match)
)
# packet id: 48
# NOTE: this is actually unused, since it's
# much faster to just send the bytes back
# rather than parsing them.. though I might
# end up doing it eventually for security reasons
def matchScoreUpdate(frame: ScoreFrame) -> bytes:
return write(
ServerPackets.MATCH_SCORE_UPDATE,
(frame, osuTypes.scoreframe)
)
# packet id: 50
@cache
def matchTransferHost() -> bytes:
return write(ServerPackets.MATCH_TRANSFER_HOST)
# packet id: 53
@cache
def matchAllPlayerLoaded() -> bytes:
return write(ServerPackets.MATCH_ALL_PLAYERS_LOADED)
# packet id: 57
@cache
def matchPlayerFailed(slot_id: int) -> bytes:
return write(
ServerPackets.MATCH_PLAYER_FAILED,
(slot_id, osuTypes.i32)
)
# packet id: 58
@cache
def matchComplete() -> bytes:
return write(ServerPackets.MATCH_COMPLETE)
# packet id: 61
@cache
def matchSkip() -> bytes:
return write(ServerPackets.MATCH_SKIP)
# packet id: 64
@lru_cache(maxsize=16)
def channelJoin(name: str) -> bytes:
return write(
ServerPackets.CHANNEL_JOIN_SUCCESS,
(name, osuTypes.string)
)
# packet id: 65
@lru_cache(maxsize=8)
def channelInfo(name: str, topic: str,
p_count: int) -> bytes: