extends Node # Change SERVER_URL to your server address before deploying. # Set the same HMAC_SECRET on the server via env var SPACEL_SECRET. const SERVER_URL := "https://lb.alpacaman.de" const HMAC_SECRET := "63f4945d921d599f27ae4fdf5bada3f1" signal scores_fetched(scores: Array, error: String) signal submit_done(ok: bool) var _http: HTTPRequest var _mode: String = "" func _ready() -> void: _http = HTTPRequest.new() add_child(_http) _http.request_completed.connect(_on_completed) func fetch_scores() -> void: if _mode != "": return _mode = "fetch" _http.request(SERVER_URL + "/scores") func submit_score(player_name: String, score: int, wave: int) -> void: if _mode != "": return var ts := int(Time.get_unix_time_from_system()) var raw := player_name + str(score) + str(wave) + str(ts) var hmac := Crypto.new().hmac_digest( HashingContext.HASH_SHA256, HMAC_SECRET.to_utf8_buffer(), raw.to_utf8_buffer() ).hex_encode() var body := JSON.stringify({ "name": player_name, "score": score, "wave": wave, "timestamp": ts, "hmac": hmac }) _mode = "submit" _http.request( SERVER_URL + "/scores", PackedStringArray(["Content-Type: application/json"]), HTTPClient.METHOD_POST, body ) func _on_completed(result: int, code: int, _headers: PackedStringArray, body: PackedByteArray) -> void: var ok := result == HTTPRequest.RESULT_SUCCESS and code == 200 if _mode == "fetch": if ok: var json := JSON.new() if json.parse(body.get_string_from_utf8()) == OK: var data = json.get_data() if data is Array: scores_fetched.emit(data as Array, "") _mode = "" return scores_fetched.emit([], "lb_error") elif _mode == "submit": submit_done.emit(ok) _mode = ""