conjure-os/lib/provider/provider.go
2025-06-29 16:51:47 -04:00

132 lines
2.6 KiB
Go

package provider
import (
"conjure-os/lib/config"
"conjure-os/lib/models"
"encoding/json"
"fmt"
"io/fs"
"log"
"net/http"
"net/url"
"os"
"strings"
"gopkg.in/yaml.v3"
)
var token string
func Update() {
//requestURL := fmt.Sprintf("http://localhost:%d", 8080)
//login(requestURL)
//allGames(requestURL)
}
type AuthResponse struct {
Token string `json:"token"`
}
func login(requestURL string) {
client := &http.Client{}
form := url.Values{
"username": {"test"},
"password": {"test"}}
req, _ := http.NewRequest("POST", requestURL+"/login", strings.NewReader(form.Encode()))
req.Header.Set("API-Version", "1")
req.Header.Add("Content-Type", "application/x-www-form-urlencoded")
res, err := client.Do(req)
check(err)
var auth AuthResponse
err = json.NewDecoder(res.Body).Decode(&auth)
check(err)
token = auth.Token
}
func allGames(requestURL string) {
client := &http.Client{}
req, _ := http.NewRequest("GET", requestURL+"/games", nil)
req.Header.Set("Authorization", token)
req.Header.Set("API-Version", "1")
res, err := client.Do(req)
check(err)
fmt.Printf("client: status code: %d\n", res.StatusCode)
}
func GetOrSetEnvKey(key string, defaultValue string) string {
value, exist := os.LookupEnv(key)
if exist {
return value
}
err := os.Setenv(key, defaultValue)
if err != nil {
log.Println(err)
}
return defaultValue
}
func GetConjureGameInfo() []models.Game {
gamePath := config.GetDefaultConjureGamesDirectory()
entries, err := os.ReadDir(gamePath)
if err != nil {
log.Fatal(err)
}
var games []models.Game
for _, e := range entries {
if e.IsDir() {
newGames := readFolder(e, gamePath)
games = append(newGames, games...)
}
}
if len(games) > 0 {
fmt.Println("Found Conjure Games: " + string(rune(len(games))))
} else {
fmt.Println("No Conjure games Found")
}
return games
}
func readFolder(entry fs.DirEntry, path string) []models.Game {
newPath := path + "/" + entry.Name()
entries, err := os.ReadDir(newPath)
check(err)
var games []models.Game
for _, e := range entries {
if e.IsDir() {
games = append(games, readFolder(e, newPath)...)
} else {
filenamesplit := strings.Split(e.Name(), ".")
if filenamesplit[1] == "conf" && filenamesplit[2] == "yml" {
game := parseGameInfoFromFile(newPath + "/" + e.Name())
games = append(games, game)
}
}
}
return games
}
func parseGameInfoFromFile(path string) models.Game {
data, err := os.ReadFile(path)
check(err)
game := models.Game{}
err = yaml.Unmarshal(data, &game)
check(err)
return game
}
func check(e error) {
if e != nil {
panic(e)
}
}