mlpcardgame/Scenes/Global/Remote.gd

37 lines
1.3 KiB
GDScript3
Raw Normal View History

extends Node
const HOST = "https://mcg.zyg.ovh/"
const IMGURL = 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, "_request_completed", [url, cbObj, cbFn])
req.request(url)
func _request_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)