This commit is contained in:
37
lib/cobblemon_ui_web/sprite_static.ex
Normal file
37
lib/cobblemon_ui_web/sprite_static.ex
Normal file
@@ -0,0 +1,37 @@
|
||||
defmodule CobblemonUiWeb.Plugs.SpriteStatic do
|
||||
@moduledoc """
|
||||
Serves cached Pokémon sprite images from the sprites cache directory.
|
||||
|
||||
Matches requests to `/sprites/<name>.png` and serves the corresponding
|
||||
file from `CobblemonUi.SpriteCache.sprites_dir()`. If the file doesn't
|
||||
exist locally, triggers an on-demand download before responding.
|
||||
"""
|
||||
|
||||
import Plug.Conn
|
||||
|
||||
def init(opts), do: opts
|
||||
|
||||
def call(%Plug.Conn{request_path: "/sprites/" <> filename} = conn, _opts) do
|
||||
if String.ends_with?(filename, ".png") do
|
||||
species = String.trim_trailing(filename, ".png")
|
||||
CobblemonUi.SpriteCache.ensure_sprite(species)
|
||||
path = CobblemonUi.SpriteCache.sprite_path(species)
|
||||
|
||||
if File.exists?(path) do
|
||||
conn
|
||||
|> put_resp_content_type("image/png")
|
||||
|> put_resp_header("cache-control", "public, max-age=604800, immutable")
|
||||
|> send_file(200, path)
|
||||
|> halt()
|
||||
else
|
||||
conn
|
||||
|> send_resp(404, "Not found")
|
||||
|> halt()
|
||||
end
|
||||
else
|
||||
conn
|
||||
end
|
||||
end
|
||||
|
||||
def call(conn, _opts), do: conn
|
||||
end
|
||||
Reference in New Issue
Block a user