36 lines
1.2 KiB
GDScript3
36 lines
1.2 KiB
GDScript3
|
extends Node
|
||
|
|
||
|
const HOST = "https://mlpccg.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)
|
||
|
print("CACHED")
|
||
|
return
|
||
|
var req := HTTPRequest.new()
|
||
|
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()
|
||
|
print("SAVED")
|
||
|
# Call callback
|
||
|
cbObj.call(cbFn, result, response_code, headers, body)
|