Files
opl-cli/internal/art.go

95 lines
1.8 KiB
Go

package oplcli
import (
"fmt"
"io"
"net/http"
"os"
"path"
)
type artUrls struct {
cover string
cover2 string
background string
disc string
spine string
logo string
screenshot string
}
func getArtUrlForGameFromGithub(gameID string) artUrls {
const baseURL = "https://raw.githubusercontent.com/Luden02/psx-ps2-opl-art-database/refs/heads/main/PS2"
prefix := gameID[0:4]
num1 := gameID[5:8]
num2 := gameID[8:10]
newGameID := fmt.Sprintf("%s_%s.%s", prefix, num1, num2)
genURL := func(kind string) string {
return fmt.Sprintf("%s/%s/%s_%s.png", baseURL, newGameID, newGameID, 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"),
}
}
func downloadArtForGame(gameID string, targetDir string) error {
urls := getArtUrlForGameFromGithub(gameID)
dl := func(url, kind string) (bool, error) {
return downloadFile(url, path.Join(targetDir, fmt.Sprintf("%s_%s.png", gameID, kind)))
}
dl(urls.cover, "COV")
dl(urls.cover2, "COV2")
dl(urls.disc, "ICO")
dl(urls.background, "BG")
dl(urls.screenshot, "SCR")
dl(urls.spine, "LAB")
return nil
}
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
}