summaryrefslogtreecommitdiff
path: root/Game/Lobby/game_lobby.gd
blob: ffc66f3349ff42056e0a30ba6983da37eb9911a3 (plain)
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
extends Node


class HTTPRequestConfig extends Resource:
	var headers: PackedStringArray
	var method: HTTPClient.Method
	var data: Dictionary
	var node: HTTPRequest
	
	@warning_ignore("shadowed_variable")
	func _init(
		headers := PackedStringArray(),
		method := HTTPClient.METHOD_GET,
		data := {},
		node := HTTPRequest.new()
	) -> void:
		self.headers = headers
		self.method = method
		self.data = data
		self.node = node


class HTTPResponse extends Resource:
	var result_code: HTTPRequest.Result
	var response_code: int
	var headers: PackedStringArray
	var body: PackedByteArray
	
	func parse_json() -> Dictionary:
		return JSON.parse_string(body.get_string_from_utf8())


var server_base_url: String = Client.get_config().get_value("general", "game_lobby_server_base_url")
var current_game_id: String
var current_secret: String


func request(
	url: String,
	config: HTTPRequestConfig = HTTPRequestConfig.new()
) -> HTTPResponse:
	get_tree().root.add_child(config.node)
	
	if config.method == HTTPClient.METHOD_POST:
		config.data["id"] = current_game_id
		config.data["secret"] = current_secret
	
	var response = HTTPResponse.new()
	config.node.request_completed.connect(
		func (
			result_code: int,
			response_code: int,
			headers: PackedStringArray,
			body: PackedByteArray
		):
			response.result_code = result_code
			response.response_code = response_code
			response.headers = headers
			response.body = body
			
			get_tree().root.remove_child(config.node)
	)
	
	config.node.request(
		"%s%s" % [server_base_url, url],
		config.headers,
		config.method,
		JSON.stringify(config.data)
	)
	
	await config.node.request_completed
	return response


func request_get(url: String, headers := PackedStringArray()):
	var config := HTTPRequestConfig.new(headers)
	
	return await request(url, config)


func request_post(url: String, data: Dictionary = {}, headers := PackedStringArray()):
	var config := HTTPRequestConfig.new(headers, HTTPClient.METHOD_POST, data)
	
	return await request(url, config)


func check_available() -> bool:
	var response = await GameLobby.request_get("")
	
	return response.result_code == HTTPRequest.RESULT_SUCCESS