Files
opl-cli/internal/art.go
2026-01-09 17:44:45 +01:00

106 lines
2.2 KiB
Go

package oplcli
import (
"fmt"
"io"
"log/slog"
"net/http"
"os"
"path"
)
type artUrls struct {
cover string
cover2 string
background string
disc string
spine string
logo string
screenshot string
screenshot2 string
}
func getArtUrlForGameFromGithub(gameID string) artUrls {
const baseURL = "https://raw.githubusercontent.com/Luden02/psx-ps2-opl-art-database/refs/heads/main/PS2"
genURL := func(kind string) string {
return fmt.Sprintf("%s/%s/%s_%s.png", baseURL, gameID, gameID, kind)
}
return artUrls{
cover: genURL("COV"),
cover2: genURL("COV2"),
background: genURL("BG_00"),
disc: genURL("ICO"),
spine: genURL("LAB"),
logo: genURL("LGO"),
screenshot: genURL("SCR_00"),
screenshot2: genURL("SCR_01"),
}
}
func downloadArtForGame(gameID string, targetDir string) {
urls := getArtUrlForGameFromGithub(gameID)
totalDownloads := 0
dl := func(url, kind string) {
file := path.Join(targetDir, fmt.Sprintf("%s_%s.png", gameID, kind))
found, err := downloadFile(url, file)
if err != nil {
slog.Warn("Failed to download art file", "gameID", gameID, "url", url)
}
if found {
slog.Debug("Downloaded art file", "gameID", gameID, "kind", kind, "target", file)
totalDownloads++
}
}
dl(urls.cover, "COV")
dl(urls.cover2, "COV2")
dl(urls.disc, "ICO")
dl(urls.background, "BG")
dl(urls.screenshot, "SCR")
dl(urls.screenshot2, "SRC2")
dl(urls.spine, "LAB")
if totalDownloads == 0 {
slog.Error("No art files found", "gameID", gameID)
} else {
slog.Info("Finished downloading art files", "gameID", gameID, "total", totalDownloads)
}
}
func downloadFile(url, target string) (bool, error) {
out, err := os.Create(target)
if err != nil {
return false, err
}
defer out.Close()
resp, err := http.Get(url)
if err != nil {
return false, err
}
defer resp.Body.Close()
if resp.StatusCode == 404 {
return false, nil
}
if resp.StatusCode >= 400 {
return false, fmt.Errorf("status code: %s", resp.Status)
}
n, err := io.Copy(out, resp.Body)
if err != nil {
return false, err
}
if n == 0 {
return false, fmt.Errorf("Got empty file")
}
return true, nil
}