OverviewFilesCommitsIssuesDocsReleasesPeers

hypergodot2 / example.gd

98 lines · gd ref:
extends Control

@export var hostname: String = 'localhost'
@export var port: int = 4772
@export var protocol: String = 'tcp'

signal rpc_response(response)

const HYPER = "hyper://"

var id = 0
var socket = StreamPeerTCP.new()
var buffer: PackedByteArray = PackedByteArray()
var newline = "\n".unicode_at(0)

# Called when the node enters the scene tree for the first time.
func _ready() -> void:
	connect_to_rpc()

# Called every frame. 'delta' is the elapsed time since the previous frame.
func _process(_delta: float) -> void:
	socket.poll()
	if socket.get_status() != StreamPeerTCP.STATUS_CONNECTED:
		return
	var available_bytes: int = socket.get_available_bytes()
	if available_bytes <= 0:
		return
	var chunk = socket.get_partial_data(available_bytes)
	if chunk[0] != OK:
		printerr(chunk[0])
		return
	buffer.append_array(chunk[1])
	
	while true:
		var index = buffer.find(newline)
		if index <= 0:
			print("Temp Buffer",newline, buffer)
			break
		var line = buffer.slice(0, index).get_string_from_utf8()
		buffer = buffer.slice(index+1)
		var response = JSON.parse_string(line)
		rpc_response.emit(response)

func _on_line_edit_text_submitted(new_text: String) -> void:
	print(new_text)
	if !new_text.begins_with(HYPER):
		printerr("Invalid hyper URL submitted")
		return
	var sections = new_text.substr(HYPER.length()).split("/")
	var hostname = sections[0]
	var path = "/" + "/".join(sections.slice(1))
	if path.ends_with("/"):
		var result = await send_rpc("sdk.getDrive(hostname).readdir(path)", {
			hostname=HYPER+hostname,
			path=path
		})
		if result.has("error"):
			print(result["error"])
			return
		var paths = "- " + "\n- ".join(result["result"])
		%OutputBox.text = paths
		print(paths)
		
	else:
		var result = await send_rpc("sdk.getDrive(hostname).get(path)", {
			hostname=HYPER+hostname,
			path=path
		})
		if result.has("error"):
			print(result["error"])
			return
		var content = PackedByteArray(result["result"]["data"]).get_string_from_utf8()
		%OutputBox.text = content
		print(content)

func connect_to_rpc():
	if socket.get_status() != socket.STATUS_CONNECTED:
		socket.connect_to_host(hostname, port)

func  send_rpc(method: String, params):
	print(method, params)
	var next_id = id+1
	id = next_id
	var call = {
		id = next_id,
		method = method,
		params = params,
	}
	var data = (JSON.stringify(call) + '\n').to_utf8_buffer()
	socket.put_data(data)
	var got_id = -1
	var response = null
	while got_id != next_id:
		response = await rpc_response
		print(response)
		got_id = response["id"]
	return response