mlpcardgame/Scenes/Global/Remote.gd

37 lines
1.3 KiB
GDScript3
Raw Normal View History

extends Node
const Host = "http://192.168.22.23/"
const ImageURL = Host + "images/cards/"
func res_file_name(url: String) -> String:
return "user://" + url.trim_prefix(Host).replace("/","_")
func fetch(url: String, cbObj: Object, cbFn: String):
# Check for cached resource
var file := File.new()
var fname := res_file_name(url)
# Return cached resource if available
if file.file_exists(fname):
file.open(fname, File.READ)
var flen := file.get_len()
var buf := file.get_buffer(flen)
cbObj.call(cbFn, HTTPRequest.RESULT_SUCCESS, 200, [], buf)
return
var req := HTTPRequest.new()
# On HTML5 we cannot use threaded requests
# On other platforms (such as Android), we *need* to!
req.use_threads = !OS.has_feature("HTML5")
add_child(req)
req.connect("request_completed", self, "_fetch_completed", [url, cbObj, cbFn])
req.request(url)
func _fetch_completed(result: int, response_code: int, headers: PoolStringArray, body: PoolByteArray, url: String, cbObj: Object, cbFn: String):
# Cache result for later
if result == HTTPRequest.RESULT_SUCCESS:
# Get file name by trimming the host
var file := File.new()
file.open(res_file_name(url), File.WRITE)
file.store_buffer(body)
file.close()
# Call callback
cbObj.call(cbFn, result, response_code, headers, body)