itchio-opengamepadui-artpro.../core/boxart_itch.gd
Jose Falanga 4efe3a9110
All checks were successful
Build plugin / build (push) Successful in 1m8s
Combine two screenshots side-by-side for banner layout
2026-08-17 01:51:54 -03:00

227 lines
7.3 KiB
GDScript

extends BoxArtProvider
## itch.io box art provider for OpenGamepadUI
##
## Fetches cover art and screenshots from itch.io game pages. Works alongside
## the itch.io library plugin to provide per-layout artwork: the cover for
## portrait/logo, full-res screenshots for landscape/banner.
##
## Enriches game metadata by scraping the itch.io page HTML for screenshots
## (the itch.io API does not expose them), caches the result in
## itch_art_meta.json, and uses HTTPImageFetcher for async image downloads.
const _boxart_dir := "user://boxart/itch"
const _meta_cache_file := "itch_art_meta.json"
@export var use_caching: bool = true
var http_image := HTTPImageFetcher.new()
var _cache_dir := "itch_art"
var _enriched: Dictionary = {}
var layout_map: Dictionary = {
LAYOUT.GRID_PORTRAIT: "-portrait",
LAYOUT.GRID_LANDSCAPE: "-landscape",
LAYOUT.BANNER: "-banner",
LAYOUT.LOGO: "-logo",
}
func _init() -> void:
super()
DirAccess.make_dir_recursive_absolute(ProjectSettings.globalize_path(_boxart_dir))
provider_id = "itch"
logger_name = "BoxArtItch"
func _ready() -> void:
super()
_enriched = _load_enriched_meta()
logger.info("itch.io Art Provider loaded")
add_child(http_image)
func get_boxart(item: LibraryItem, kind: LAYOUT) -> Texture2D:
if not kind in layout_map:
logger.error("Unsupported boxart layout: {0}".format([kind]))
return null
var game := _itch_game(item)
if game.is_empty():
return null
var game_id := int(game.get("id", 0))
var title: String = game.get("title", "")
var cover_url := _cover_url(game)
if title.is_empty() or cover_url.is_empty():
return null
# Enrich on first access: scrape the itch.io page for screenshots.
var meta: Dictionary = _enriched.get(game_id, {})
if meta.is_empty() and game.has("url"):
meta = _fetch_game_page_metadata(game)
if not meta.is_empty():
_enriched[game_id] = meta
_save_enriched_meta(game_id, meta)
var screenshots: Array = meta.get("screenshots", [])
var cache_flags := Cache.FLAGS.NONE
if use_caching:
cache_flags = Cache.FLAGS.LOAD | Cache.FLAGS.SAVE
# Banner: combine two screenshots side-by-side when available.
if kind == LAYOUT.BANNER and screenshots.size() >= 2:
logger.debug("Fetching itch.io banner (2 screenshots) for: " + item.name)
var tex_a := await http_image.fetch(screenshots[0], cache_flags)
var tex_b := await http_image.fetch(screenshots[1], cache_flags)
if tex_a != null and tex_b != null:
return _combine_side_by_side(tex_a, tex_b)
# Fall through to single-image path if either failed.
if tex_a != null:
return tex_a
if tex_b != null:
return tex_b
var url := _url_for_layout(kind, cover_url, screenshots)
if url.is_empty():
return null
logger.debug("Fetching itch.io box art for: " + item.name)
var texture: Texture2D = await http_image.fetch(url, cache_flags)
if texture == null:
logger.debug("Image couldn't be downloaded for: " + item.name)
return texture
## Finds the itch.io game dict from the library item's launch items.
func _itch_game(item: LibraryItem) -> Dictionary:
for launch_item in item.launch_items:
if launch_item._provider_id != "itch":
continue
var game: Dictionary = launch_item.metadata.get("game", {})
if not game.is_empty():
return game
return {}
func _url_for_layout(kind: LAYOUT, cover_url: String, screenshots: Array) -> String:
match kind:
LAYOUT.GRID_PORTRAIT, LAYOUT.LOGO:
return cover_url
LAYOUT.GRID_LANDSCAPE:
return screenshots[0] if not screenshots.is_empty() else cover_url
LAYOUT.BANNER:
# Single screenshot fallback (two-screenshot case handled in get_boxart).
return screenshots[0] if not screenshots.is_empty() else cover_url
return ""
func _cover_url(game: Dictionary) -> String:
var still: String = game.get("stillCoverUrl", "")
if not still.is_empty():
return still
return game.get("coverUrl", "")
## Combines two textures side-by-side into a single banner image.
## Both images are scaled to the same height, then placed left and right.
func _combine_side_by_side(a: Texture2D, b: Texture2D) -> Texture2D:
var img_a := a.get_image()
var img_b := b.get_image()
if img_a == null or img_b == null:
return a
# Scale both to the same height (use the taller one).
var target_h: int = max(img_a.get_height(), img_b.get_height())
if img_a.get_height() != target_h:
var scale: float = float(target_h) / float(img_a.get_height())
img_a.resize(int(img_a.get_width() * scale), target_h, Image.INTERPOLATE_BILINEAR)
if img_b.get_height() != target_h:
var scale: float = float(target_h) / float(img_b.get_height())
img_b.resize(int(img_b.get_width() * scale), target_h, Image.INTERPOLATE_BILINEAR)
var combined := Image.create(img_a.get_width() + img_b.get_width(), target_h, false, img_a.get_format())
combined.blit_rect(img_a, Rect2i(0, 0, img_a.get_width(), target_h), Vector2i.ZERO)
combined.blit_rect(img_b, Rect2i(0, 0, img_b.get_width(), target_h), Vector2i(img_a.get_width(), 0))
return ImageTexture.create_from_image(combined)
## Scrapes the itch.io game page for screenshots. The itch.io API does not
## expose screenshots, so the page HTML is the only source.
func _fetch_game_page_metadata(game: Dictionary) -> Dictionary:
var page_url: String = game.get("url", "")
if page_url.is_empty():
return {}
var http := HTTPClient.new()
var parts := page_url.split("/")
var use_tls := parts[0] == "https:"
var err := http.connect_to_host(parts[2], 443 if use_tls else 80, TLSOptions.client() if use_tls else null)
if err != OK:
return {}
var deadline := Time.get_ticks_msec() + 15000
while http.get_status() == HTTPClient.STATUS_CONNECTING or http.get_status() == HTTPClient.STATUS_RESOLVING:
http.poll()
if Time.get_ticks_msec() > deadline:
http.close()
return {}
OS.delay_msec(50)
if http.get_status() != HTTPClient.STATUS_CONNECTED:
http.close()
return {}
http.request(HTTPClient.METHOD_GET, "/" + "/".join(parts.slice(3)), PackedStringArray())
deadline = Time.get_ticks_msec() + 15000
while http.get_status() == HTTPClient.STATUS_REQUESTING:
http.poll()
if Time.get_ticks_msec() > deadline:
http.close()
return {}
OS.delay_msec(10)
var body := PackedByteArray()
while http.get_status() == HTTPClient.STATUS_BODY:
http.poll()
var chunk: PackedByteArray = http.read_response_body_chunk()
if chunk.is_empty():
if Time.get_ticks_msec() > deadline:
http.close()
return {}
OS.delay_msec(10)
continue
body.append_array(chunk)
http.close()
var html := body.get_string_from_utf8()
if html.is_empty():
return {}
var shot_re := RegEx.new()
shot_re.compile("https://img\\.itch\\.zone/aW1hZ2Uv[^\"]*/original/[^\"]*")
var screenshots: Array = []
for m in shot_re.search_all(html):
var url: String = m.get_string(0)
if url.to_lower().ends_with(".gif"):
logger.debug("Skipping GIF screenshot: " + url)
continue
screenshots.append(url)
return {"screenshots": screenshots}
func _load_enriched_meta() -> Dictionary:
var raw: Variant = Cache.get_json(_cache_dir, _meta_cache_file)
if typeof(raw) != TYPE_DICTIONARY:
return {}
var out := {}
for key in raw:
out[int(key)] = raw[key]
return out
func _save_enriched_meta(game_id: int, meta: Dictionary) -> void:
var raw: Variant = Cache.get_json(_cache_dir, _meta_cache_file)
if typeof(raw) != TYPE_DICTIONARY:
raw = {}
raw[str(game_id)] = meta
Cache.save_json(_cache_dir, _meta_cache_file, raw)