78 lines
2.1 KiB
GDScript
78 lines
2.1 KiB
GDScript
extends Node
|
|
|
|
var server: TCPServer
|
|
|
|
signal started
|
|
signal received(auth)
|
|
|
|
var clients: Array[StreamPeerTCP] = []
|
|
|
|
var listening = false
|
|
|
|
func start():
|
|
var port = get_parent().auth.PORT
|
|
print(port)
|
|
server = TCPServer.new()
|
|
server.listen(port)
|
|
|
|
|
|
|
|
func _process(delta):
|
|
if !server: return
|
|
if(!server.is_listening()): return;
|
|
|
|
if not listening:
|
|
print("SERVER STARTED")
|
|
started.emit()
|
|
listening = true
|
|
|
|
if(server.is_connection_available()):
|
|
_handle_connect();
|
|
|
|
for client in clients:
|
|
_process_request(client);
|
|
|
|
|
|
func _handle_connect():
|
|
var client := server.take_connection()
|
|
clients.push_back(client)
|
|
print("CONNECT")
|
|
|
|
|
|
func _process_request(client: StreamPeerTCP):
|
|
match client.get_status():
|
|
StreamPeerTCP.STATUS_CONNECTED:
|
|
client.poll()
|
|
if client.get_available_bytes() > 0:
|
|
var string = client.get_utf8_string(client.get_available_bytes())
|
|
var split = string.split("\n")
|
|
var first = split[0]
|
|
var regex = RegEx.new()
|
|
regex.compile("code=(.*)&")
|
|
var result = regex.search(first)
|
|
if result:
|
|
var auth = result.get_string(1)
|
|
_send_response(client, "200 OK", "<html><head><title>Login</title><script>window.close()</script></head><body>Success!</body></html>".to_utf8_buffer());
|
|
received.emit(auth)
|
|
|
|
func auth(arguments: Dictionary):
|
|
var comp_args = ""
|
|
|
|
for argument in arguments:
|
|
if comp_args == "":
|
|
comp_args += "?%s=%s" % [argument, arguments[argument]]
|
|
else:
|
|
comp_args += "&%s=%s" % [argument, arguments[argument]]
|
|
|
|
OS.shell_open("https://id.twitch.tv/oauth2/authorize%s" % [comp_args])
|
|
|
|
|
|
func _send_response(client, response_code : String, body : PackedByteArray) -> void:
|
|
client.put_data(("HTTP/1.1 %s\r\n" % response_code).to_utf8_buffer())
|
|
client.put_data("Server: Godot Engine\r\n".to_utf8_buffer())
|
|
client.put_data(("Content-Length: %d\r\n"% body.size()).to_utf8_buffer())
|
|
client.put_data("Connection: close\r\n".to_utf8_buffer())
|
|
client.put_data("Content-Type: text/html; charset=UTF-8\r\n".to_utf8_buffer())
|
|
client.put_data("\r\n".to_utf8_buffer())
|
|
client.put_data(body)
|
|
client.disconnect_from_host();
|