Skip to content

Commit 7049d87

Browse files
TMHSDigitalclaude
andcommitted
Fetch and cache the catalog feed, with an offline fallback
feed.gd parses and checks plugin-feed.json: refuses a newer format with an "update the plugin" message, drops malformed entries, ignores unknown keys, and parses quietly so an HTML login page does not print an engine error. feed_cache.gd keeps the last good feed and its ETag and Last-Modified in the editor cache folder, never the project, swapping in a new copy only once it is fully written. feed_client.gd uses the cache when it is under a day old, otherwise sends a conditional request (304 keeps the cache), and falls back to the cache with a reason when offline, on a server error or on a too-new feed. The dock shows "N entries, data from vYYYY.MM.DD" and a Refresh / Retry button. tests/run_tests.gd: 50 headless checks against a fixture feed, every response path included, with no network. Refs TMHSDigital/Free-Game-Dev-Assets#279 Co-Authored-By: Claude Opus 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_01LpkeXPtfg3jGzhfoGMshTE
1 parent e53208b commit 7049d87

11 files changed

Lines changed: 706 additions & 6 deletions

File tree

‎README.md‎

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,7 @@ Early development. Planned work is tracked in [TMHSDigital/Free-Game-Dev-Assets#
1818

1919
- [x] Plugin feed published by the catalog build ([#277](https://github.com/TMHSDigital/Free-Game-Dev-Assets/issues/277))
2020
- [x] Skeleton addon with an empty dock ([#278](https://github.com/TMHSDigital/Free-Game-Dev-Assets/issues/278))
21-
- [ ] Fetch and cache the feed, offline fallback ([#279](https://github.com/TMHSDigital/Free-Game-Dev-Assets/issues/279))
21+
- [x] Fetch and cache the feed, offline fallback ([#279](https://github.com/TMHSDigital/Free-Game-Dev-Assets/issues/279))
2222
- [ ] Browse list with search and filters ([#280](https://github.com/TMHSDigital/Free-Game-Dev-Assets/issues/280))
2323
- [ ] Entry details and actions ([#281](https://github.com/TMHSDigital/Free-Game-Dev-Assets/issues/281))
2424
- [ ] Project asset list and `CREDITS.md` export ([#282](https://github.com/TMHSDigital/Free-Game-Dev-Assets/issues/282))
@@ -43,6 +43,14 @@ godot --headless --editor --quit-after 120 --verbose --path .
4343

4444
The output should include `free_game_dev_assets: dock added` and no `SCRIPT ERROR`. `project.godot` is left out of the Asset Library download.
4545

46+
Unit tests (no network, no editor):
47+
48+
```
49+
godot --headless --path . --script tests/run_tests.gd
50+
```
51+
52+
The plugin reads [`plugin-feed.json`](https://tmhsdigital.github.io/Free-Game-Dev-Assets/plugin-feed.json) ([format notes](https://github.com/TMHSDigital/Free-Game-Dev-Assets/blob/main/docs/data.md#plugin-feed)). It caches the feed in the editor's cache folder, not in your project, and checks for a newer one at most once a day, or whenever you press Refresh.
53+
4654
## Licence
4755

4856
Plugin code: [MIT](LICENSE). Catalog data: [CC0 1.0](https://github.com/TMHSDigital/Free-Game-Dev-Assets/blob/main/LICENSE). The assets the catalog lists keep their own licences.

‎addons/free_game_dev_assets/dock.gd‎

Lines changed: 51 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -3,15 +3,61 @@ extends VBoxContainer
33
## The "Free Assets" dock. Built in code rather than a .tscn so one source
44
## loads the same in every Godot 4.x the plugin supports.
55

6+
## Emitted when a feed arrives (from the network or the cache).
7+
signal feed_changed(feed: Dictionary)
8+
9+
const FeedClient := preload("feed_client.gd")
10+
11+
## The loaded feed, or {} before one arrives.
12+
var feed: Dictionary = {}
13+
14+
var _client: Node
15+
var _status: Label
16+
var _refresh: Button
17+
618

719
func _ready() -> void:
820
var title := Label.new()
921
title.text = "Free Game Dev Assets"
1022
title.add_theme_font_size_override("font_size", 16)
1123
add_child(title)
1224

13-
var note := Label.new()
14-
note.text = "The catalog browser is coming. See the plugin's README for progress."
15-
note.autowrap_mode = TextServer.AUTOWRAP_WORD_SMART
16-
note.size_flags_horizontal = Control.SIZE_EXPAND_FILL
17-
add_child(note)
25+
var bar := HBoxContainer.new()
26+
add_child(bar)
27+
_status = Label.new()
28+
_status.text = "Loading the catalog…"
29+
_status.autowrap_mode = TextServer.AUTOWRAP_WORD_SMART
30+
_status.size_flags_horizontal = Control.SIZE_EXPAND_FILL
31+
bar.add_child(_status)
32+
_refresh = Button.new()
33+
_refresh.text = "Refresh"
34+
_refresh.tooltip_text = "Fetch the latest catalog now"
35+
_refresh.disabled = true
36+
_refresh.pressed.connect(_on_refresh_pressed)
37+
bar.add_child(_refresh)
38+
39+
_client = FeedClient.new()
40+
_client.cache_dir = EditorInterface.get_editor_paths().get_cache_dir()
41+
add_child(_client)
42+
_client.loaded.connect(_on_loaded)
43+
_client.refresh()
44+
45+
46+
func _on_refresh_pressed() -> void:
47+
_refresh.disabled = true
48+
_status.text = "Checking for a newer catalog…"
49+
_client.refresh(true)
50+
51+
52+
func _on_loaded(state: Dictionary) -> void:
53+
_refresh.disabled = false
54+
var message := String(state.get("message", ""))
55+
if state["feed"].is_empty():
56+
_refresh.text = "Retry"
57+
_status.text = message
58+
return
59+
_refresh.text = "Refresh"
60+
feed = state["feed"]
61+
var line := "%d entries, data from %s" % [feed["entries"].size(), feed["version"]]
62+
_status.text = line if message == "" else "%s\n%s" % [line, message]
63+
feed_changed.emit(feed)
Lines changed: 79 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,79 @@
1+
@tool
2+
extends RefCounted
3+
## Parses and checks plugin-feed.json from the Free Game Dev Assets catalog.
4+
## No nodes and no editor APIs, so the tests can run it headless.
5+
##
6+
## The feed's `format` goes up only on a breaking change; new keys can appear
7+
## at any time and are ignored. See
8+
## https://github.com/TMHSDigital/Free-Game-Dev-Assets/blob/main/docs/data.md#plugin-feed
9+
10+
const URL := "https://tmhsdigital.github.io/Free-Game-Dev-Assets/plugin-feed.json"
11+
const DEFAULT_SITE_URL := "https://tmhsdigital.github.io/Free-Game-Dev-Assets/"
12+
13+
## The highest feed format this plugin understands.
14+
const SUPPORTED_FORMAT := 1
15+
16+
const _ENTRY_STRINGS := ["id", "name", "url", "page", "category", "license"]
17+
const _ENTRY_ARRAYS := ["formats", "tags", "works_in", "made_for"]
18+
19+
20+
## Parses feed text. Returns a Dictionary:
21+
## ok: bool, error: String, too_new: bool,
22+
## feed: Dictionary (the parsed feed when ok), dropped: int (malformed entries left out).
23+
static func parse(text: String) -> Dictionary:
24+
var out := {"ok": false, "error": "", "too_new": false, "feed": {}, "dropped": 0}
25+
var data = quiet_json(text)
26+
if typeof(data) != TYPE_DICTIONARY:
27+
out["error"] = "the catalog feed is not valid JSON"
28+
return out
29+
var fmt = data.get("format")
30+
# JSON numbers arrive as floats.
31+
if typeof(fmt) != TYPE_INT and typeof(fmt) != TYPE_FLOAT:
32+
out["error"] = "the catalog feed has no format number"
33+
return out
34+
if int(fmt) > SUPPORTED_FORMAT:
35+
out["too_new"] = true
36+
out["error"] = "the catalog feed (format %d) is newer than this plugin (format %d): update the plugin" % [int(fmt), SUPPORTED_FORMAT]
37+
return out
38+
if typeof(data.get("version")) != TYPE_STRING or typeof(data.get("entries")) != TYPE_ARRAY:
39+
out["error"] = "the catalog feed is missing its version or entries"
40+
return out
41+
42+
var kept: Array = []
43+
for e in data["entries"]:
44+
if _valid_entry(e):
45+
kept.append(e)
46+
else:
47+
out["dropped"] += 1
48+
data["entries"] = kept
49+
for key in ["categories", "licenseFamilies", "engines"]:
50+
if typeof(data.get(key)) != TYPE_DICTIONARY:
51+
data[key] = {}
52+
var site = data.get("siteUrl")
53+
if typeof(site) != TYPE_STRING or not String(site).begins_with("https://"):
54+
data["siteUrl"] = DEFAULT_SITE_URL
55+
out["ok"] = true
56+
out["feed"] = data
57+
return out
58+
59+
60+
## Parses JSON, or returns null, without printing an engine error: a Wi-Fi
61+
## login page that answers 200 with HTML should not put red text in the
62+
## user's Output panel.
63+
static func quiet_json(text: String):
64+
var json := JSON.new()
65+
if json.parse(text) != OK:
66+
return null
67+
return json.data
68+
69+
70+
static func _valid_entry(e) -> bool:
71+
if typeof(e) != TYPE_DICTIONARY:
72+
return false
73+
for key in _ENTRY_STRINGS:
74+
if typeof(e.get(key)) != TYPE_STRING:
75+
return false
76+
for key in _ENTRY_ARRAYS:
77+
if typeof(e.get(key)) != TYPE_ARRAY:
78+
return false
79+
return true
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
uid://drvfa5kck8d4n
Lines changed: 67 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,67 @@
1+
@tool
2+
extends RefCounted
3+
## The last good feed and its HTTP validators, kept on disk in the editor's
4+
## cache folder (never in the user's project). Every function takes the folder,
5+
## so tests can point it at a scratch directory.
6+
7+
const FEED_FILE := "free_game_dev_assets_feed.json"
8+
const META_FILE := "free_game_dev_assets_feed.meta.json"
9+
10+
## Refresh on its own at most once a day.
11+
const MAX_AGE_SEC := 24 * 60 * 60
12+
13+
14+
static func read_text(dir: String) -> String:
15+
var path := dir.path_join(FEED_FILE)
16+
if not FileAccess.file_exists(path):
17+
return ""
18+
return FileAccess.get_file_as_string(path)
19+
20+
21+
## {"etag": String, "last_modified": String, "fetched_at": float}, or {} when there is none.
22+
static func read_meta(dir: String) -> Dictionary:
23+
var path := dir.path_join(META_FILE)
24+
if not FileAccess.file_exists(path):
25+
return {}
26+
var json := JSON.new()
27+
if json.parse(FileAccess.get_file_as_string(path)) != OK or typeof(json.data) != TYPE_DICTIONARY:
28+
return {}
29+
return json.data
30+
31+
32+
## Saves a feed that parsed cleanly, with its validators. Returns false if it could not be written.
33+
static func write(dir: String, text: String, meta: Dictionary) -> bool:
34+
DirAccess.make_dir_recursive_absolute(dir)
35+
# Write beside the old copy and swap, so a crash mid-write keeps the old one.
36+
var path := dir.path_join(FEED_FILE)
37+
var tmp := path + ".tmp"
38+
var f := FileAccess.open(tmp, FileAccess.WRITE)
39+
if f == null:
40+
return false
41+
f.store_string(text)
42+
f.close()
43+
if FileAccess.file_exists(path):
44+
DirAccess.remove_absolute(path)
45+
if DirAccess.rename_absolute(tmp, path) != OK:
46+
return false
47+
return write_meta(dir, meta)
48+
49+
50+
static func write_meta(dir: String, meta: Dictionary) -> bool:
51+
DirAccess.make_dir_recursive_absolute(dir)
52+
var f := FileAccess.open(dir.path_join(META_FILE), FileAccess.WRITE)
53+
if f == null:
54+
return false
55+
f.store_string(JSON.stringify(meta))
56+
f.close()
57+
return true
58+
59+
60+
## True when the cached copy was fetched (or confirmed by a 304) less than a day ago.
61+
## A clock that went backwards counts as stale.
62+
static func is_fresh(meta: Dictionary, now: float) -> bool:
63+
var at = meta.get("fetched_at")
64+
if typeof(at) != TYPE_FLOAT and typeof(at) != TYPE_INT:
65+
return false
66+
var age := now - float(at)
67+
return age >= 0.0 and age < MAX_AGE_SEC
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
uid://b51r6noqgri6n
Lines changed: 132 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,132 @@
1+
@tool
2+
extends Node
3+
## Loads the catalog feed and reports what it got through `loaded`.
4+
##
5+
## - Uses the cached copy when it is under a day old (unless forced).
6+
## - Otherwise sends a conditional request (If-None-Match / If-Modified-Since);
7+
## a 304 keeps the cached copy and marks it fresh.
8+
## - When the request fails, or the feed is too new or broken, it falls back to
9+
## the cached copy and says why; with no cache it reports the problem.
10+
11+
## state: {"feed": Dictionary ({} when there is none), "source": "network" | "cache" | "none", "message": String}
12+
signal loaded(state: Dictionary)
13+
14+
const Feed := preload("feed.gd")
15+
const Cache := preload("feed_cache.gd")
16+
17+
const TIMEOUT_SEC := 20.0
18+
const USER_AGENT := "free-game-dev-assets-godot (+https://github.com/TMHSDigital/free-game-dev-assets-godot)"
19+
20+
## Folder for the cached feed. The dock sets it to the editor's cache folder.
21+
var cache_dir := ""
22+
var url := Feed.URL
23+
24+
var _http: HTTPRequest
25+
var _busy := false
26+
27+
28+
func _ready() -> void:
29+
_http = HTTPRequest.new()
30+
_http.timeout = TIMEOUT_SEC
31+
_http.accept_gzip = true
32+
add_child(_http)
33+
_http.request_completed.connect(_on_request_completed)
34+
35+
36+
func is_busy() -> bool:
37+
return _busy
38+
39+
40+
## Loads the feed. `force` skips the once-a-day rule (the Refresh button).
41+
func refresh(force := false) -> void:
42+
if _busy:
43+
return
44+
var cached := _cached()
45+
var meta := Cache.read_meta(cache_dir)
46+
if not force and cached["ok"] and Cache.is_fresh(meta, _now()):
47+
loaded.emit(_state(cached["feed"], "cache", ""))
48+
return
49+
var headers := PackedStringArray(["User-Agent: " + USER_AGENT])
50+
# Validators only make sense when there is a cached body to fall back on.
51+
if cached["ok"]:
52+
if String(meta.get("etag", "")) != "":
53+
headers.append("If-None-Match: " + String(meta["etag"]))
54+
if String(meta.get("last_modified", "")) != "":
55+
headers.append("If-Modified-Since: " + String(meta["last_modified"]))
56+
_busy = true
57+
var err := _http.request(url, headers)
58+
if err != OK:
59+
_busy = false
60+
_fall_back(cached, "the request could not start (error %d)" % err)
61+
62+
63+
func _on_request_completed(result: int, code: int, headers: PackedStringArray, body: PackedByteArray) -> void:
64+
_busy = false
65+
var cached := _cached()
66+
if result != HTTPRequest.RESULT_SUCCESS:
67+
_fall_back(cached, "offline or unreachable (%s)" % _result_text(result))
68+
return
69+
if code == 304 and cached["ok"]:
70+
var meta := Cache.read_meta(cache_dir)
71+
meta["fetched_at"] = _now()
72+
Cache.write_meta(cache_dir, meta)
73+
loaded.emit(_state(cached["feed"], "cache", ""))
74+
return
75+
if code != 200:
76+
_fall_back(cached, "the catalog answered HTTP %d" % code)
77+
return
78+
var text := body.get_string_from_utf8()
79+
var parsed := Feed.parse(text)
80+
if not parsed["ok"]:
81+
_fall_back(cached, parsed["error"])
82+
return
83+
Cache.write(cache_dir, text, {
84+
"etag": _header(headers, "etag"),
85+
"last_modified": _header(headers, "last-modified"),
86+
"fetched_at": _now(),
87+
})
88+
loaded.emit(_state(parsed["feed"], "network", ""))
89+
90+
91+
func _fall_back(cached: Dictionary, why: String) -> void:
92+
if cached["ok"]:
93+
var version := String(cached["feed"].get("version", ""))
94+
loaded.emit(_state(cached["feed"], "cache", "Showing saved data from %s: %s." % [version, why]))
95+
else:
96+
loaded.emit(_state({}, "none", "Could not load the catalog: %s." % why))
97+
98+
99+
func _cached() -> Dictionary:
100+
var text := Cache.read_text(cache_dir)
101+
if text == "":
102+
return {"ok": false}
103+
# A cache written by a newer plugin version can be too new for this one.
104+
return Feed.parse(text)
105+
106+
107+
func _state(feed: Dictionary, source: String, message: String) -> Dictionary:
108+
return {"feed": feed, "source": source, "message": message}
109+
110+
111+
static func _header(headers: PackedStringArray, name: String) -> String:
112+
var prefix := name.to_lower() + ":"
113+
for h in headers:
114+
if h.to_lower().begins_with(prefix):
115+
return h.substr(prefix.length()).strip_edges()
116+
return ""
117+
118+
119+
static func _result_text(result: int) -> String:
120+
match result:
121+
HTTPRequest.RESULT_CANT_CONNECT, HTTPRequest.RESULT_CANT_RESOLVE:
122+
return "no connection"
123+
HTTPRequest.RESULT_TIMEOUT:
124+
return "timed out"
125+
HTTPRequest.RESULT_TLS_HANDSHAKE_ERROR:
126+
return "TLS error"
127+
_:
128+
return "request error %d" % result
129+
130+
131+
func _now() -> float:
132+
return Time.get_unix_time_from_system()
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
uid://j4pccpiihnjs

0 commit comments

Comments
 (0)