-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSocket.gd
More file actions
255 lines (187 loc) · 6.12 KB
/
Socket.gd
File metadata and controls
255 lines (187 loc) · 6.12 KB
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
class_name Socket
extends Node
const MAXIMUM_PACKET_SIZE := 512 * 1024
const CONNECTION_COMMAND := '[{"cmd":"Connect","password":"{password}","game":"{game}","name":"{slot}","uuid":"{uuid}","version":{version},"items_handling":{items_handling},"tags":["AP","Tracker","DeathLink","TextOnly"],"slot_data":true}]'
signal updates_received(updates: Array[Update])
var socket = WebSocketPeer.new()
var url := ""
var password := ""
var room_info := {}
var pending_packets := []
func _init(url: String, password: String) -> void:
self.url = url
self.password = password
func _ready():
socket.inbound_buffer_size = MAXIMUM_PACKET_SIZE
set_process(false)
func fetch_room_info():
var err = socket.connect_to_url(url)
if err == OK:
print("Connecting to %s..." % url)
else:
push_error("Unable to connect.")
return
var packet = await await_packet(socket)
room_info = packet[0]
func close():
socket.close()
queue_free()
func await_packet(socket: WebSocketPeer):
while true:
socket.poll()
var state := socket.get_ready_state()
if state == WebSocketPeer.STATE_OPEN:
while socket.get_available_packet_count():
var packet = socket.get_packet()
if socket.was_string_packet():
var packet_text = packet.get_string_from_utf8()
return JSON.parse_string(packet_text)
else:
print("Received binary data")
elif state == WebSocketPeer.STATE_CLOSED:
var code = socket.get_close_code()
var reason = socket.get_close_reason()
print("WebSocket closed with code: %d, reason %s. Clean: %s" % [code, reason, code != -1])
await get_tree().physics_frame
func await_cmd_packet(socket: WebSocketPeer, cmd: String):
while true:
var packet_pack = await await_packet(socket)
if packet_pack == null:
continue
for packet in packet_pack:
if packet["cmd"] == cmd:
return packet
func fetch_data_package(game):
socket.send_text('[{"cmd":"GetDataPackage","games":["' + game + '"]}]')
var data_package = await await_cmd_packet(socket, "DataPackage")
return data_package["data"]["games"][game]
func fetch_inventory(game: String, slot: String, uuid: String) -> Game_Inventory:
var inventory := Game_Inventory.new()
var game_socket := WebSocketPeer.new()
game_socket.inbound_buffer_size = MAXIMUM_PACKET_SIZE
var err = game_socket.connect_to_url(url)
if err != OK:
push_error("Unable to connect.")
return
await await_cmd_packet(game_socket, "RoomInfo")
var command := CONNECTION_COMMAND.format({
"password": password,
"game": game,
"slot": slot,
"uuid": uuid,
"items_handling": "7",
"version": JSON.stringify(Counter.settings.archipelago_connection_data.version)
})
game_socket.send_text(command)
var packet_pack = await await_packet(game_socket)
for packet in packet_pack:
match packet["cmd"]:
"Connected":
inventory.connected_packet = packet
"ReceivedItems":
inventory.received_items_packet = packet
return inventory
func watch_for_updates(game: String, slot: String, uuid: String):
set_process(true) # Start polling the socket in _process
var command := CONNECTION_COMMAND.format({
"password": password,
"game": game,
"slot": slot,
"uuid": uuid,
"items_handling": "0",
"version": JSON.stringify(Counter.settings.archipelago_connection_data.version)
})
socket.send_text(command)
while true:
while len(pending_packets) == 0:
await get_tree().physics_frame
var updates: Array[Update] = []
while len(pending_packets) > 0:
var packet_pack = pending_packets.pop_front()
for packet in packet_pack:
var update: Update
match packet["cmd"]:
"PrintJSON":
update = print_json_update(packet)
"Bounced":
update = bounced_update(packet)
if update != null:
updates.append(update)
updates_received.emit(updates)
func _process(delta: float) -> void:
socket.poll()
var state := socket.get_ready_state()
if state == WebSocketPeer.STATE_OPEN:
while socket.get_available_packet_count():
var packet = socket.get_packet()
if socket.was_string_packet():
var packet_text = packet.get_string_from_utf8()
pending_packets.append(JSON.parse_string(packet_text))
elif state == WebSocketPeer.STATE_CLOSED:
pass
func print_json_update(packet) -> Update:
if not packet.has("type"):
return null
match packet["type"]:
"Join":
if packet["data"][0]["text"].contains("playing"):
var update := Update_Player.new()
update.update_type = Update_Player.Player_Update_Type.Join
update.slot = int(packet["slot"])
return update
"Part":
if packet["data"][0]["text"].contains("left"):
var update := Update_Player.new()
update.update_type = Update_Player.Player_Update_Type.Part
update.slot = int(packet["slot"])
return update
"ItemSend":
var update := Update_Item.new()
update.item_id = int(packet["item"]["item"])
update.location_id = int(packet["item"]["location"])
update.receiving_player_id = int(packet["receiving"])
update.sending_player_id = int(packet["item"]["player"])
update.flags = int(packet["item"]["flags"])
return update
"Goal":
var update := Update_Goal.new()
update.slot = int(packet["slot"])
return update
"Collect":
var update := Update_Collect.new()
update.slot = int(packet["slot"])
return update
"Release":
var update := Update_Release.new()
update.slot = int(packet["slot"])
return update
return null
func bounced_update(packet) -> Update:
if "DeathLink" in packet["tags"]:
var update := Update_DeathLink.new()
update.slot = Counter.get_slot_id_from_name(packet["data"]["source"])
return update
return null
class Game_Inventory:
var connected_packet: Dictionary
var received_items_packet: Dictionary
class Update:
pass
class Update_Player extends Update:
enum Player_Update_Type { Join, Part }
var update_type: Player_Update_Type
var slot: int
class Update_Item extends Update:
var item_id: int
var location_id: int
var receiving_player_id: int
var sending_player_id: int
var flags: int
class Update_Goal extends Update:
var slot: int
class Update_Collect extends Update:
var slot: int
class Update_Release extends Update:
var slot: int
class Update_DeathLink extends Update:
var slot: int