conjure-os/lib/provider/provider.go
2025-01-07 19:18:06 -05:00

124 lines
2.4 KiB
Go

package provider
import (
"encoding/json"
"fmt"
"io/fs"
"log"
"net/http"
"net/url"
"os"
"strings"
"gopkg.in/yaml.v3"
)
type Game struct {
Title string
Developper string
Year int
Cartridge string
Description string
}
var token string
const game_path = "/Users/guillaumelanglois/Games/conjure"
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.Println("client: status code: %d\n", res.StatusCode)
}
func ObtainConjureGameInfo() []Game {
entries, err := os.ReadDir(game_path)
if err != nil {
log.Fatal(err)
}
games := []Game{}
for _, e := range entries {
if e.IsDir() {
newGames := readFolder(e, game_path)
games = append(newGames, games...)
}
}
if len(games) > 0 {
fmt.Println("Found Conjure Games: " + string(len(games)))
} else {
fmt.Println("No Conjure games Found")
}
return games
}
func readFolder(entry fs.DirEntry, path string) []Game {
newPath := path + "/" + entry.Name()
entries, err := os.ReadDir(newPath)
check(err)
games := []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) Game {
data, err := os.ReadFile(path)
check(err)
game := Game{}
err = yaml.Unmarshal(data, &game)
check(err)
return game
}
func check(e error) {
if e != nil {
panic(e)
}
}