risk/api/api.go

109 lines
2.8 KiB
Go
Raw Normal View History

2021-01-24 18:12:33 -04:00
package api
import (
"encoding/json"
"io/ioutil"
"os"
"r2mod-go/utils"
"time"
"github.com/fatih/color"
// TODO: eliminate this dependency
)
// Mod contains info about a mod from thunderstore API
type Mod struct {
Name string `json:"name"`
FullName string `json:"full_name"`
PackageURL string `json:"package_url"`
DateCreated string `json:"date_created"`
DateUpdated string `json:"date_updated"`
UUID4 string `json:"uuid4"`
RatingScore int `json:"rating_score"`
IsPinned bool `json:"is_pinned"`
IsDeprecated bool `json:"is_deprecated"`
HasNSFWContent bool `json:"has_nsfw_content"`
Categories []string `json:"categories"`
Versions []Version `json:"versions"`
}
// Version contains info about a specific version of a mod
type Version struct {
Name string `json:"name"`
FullName string `json:"full_name"`
Description string `json:"description"`
Icon string `json:"icon"`
VersionNumber string `json:"version_number"`
Dependencies []string `json:"dependencies"`
DownloadURL string `json:"download_url"`
Downloads int `json:"downloads"`
DateCreated string `json:"date_created"`
WebsiteURL string `json:"website_url"`
IsActive bool `json:"is_active"`
UUID4 string `json:"uuid4"`
}
// CheckAPICache checks if the cached json is expired
func CheckAPICache() {
// TODO: move the printing out, add returns
color.Blue("> Checking API Cache")
if !utils.PathExists(utils.SystemInfo.TmpDir + "/pkg.json") {
color.Red("> API Cache is outdated")
UpdateAPICache()
} else {
info, err := os.Stat(utils.SystemInfo.TmpDir + "/pkg.json")
utils.CheckErr(err)
lastModTime := info.ModTime()
currentTime := time.Now()
if currentTime.Sub(lastModTime).Seconds() > 7200 {
color.Red("> API Cache is outdated")
color.Blue("> Updating API Cache")
UpdateAPICache()
} else {
color.Green("> API Cache is up to date")
}
}
}
// UpdateAPICache gets a new copy of the thunderstore pkgfile
func UpdateAPICache() {
apiURL := "https://thunderstore.io/api/v1/package/"
err := utils.DownloadFile(utils.SystemInfo.TmpDir+"/pkg.json", apiURL)
utils.CheckErr(err)
}
// GetModData gets object of mod by depString
func GetModData(depString string) Mod {
if depString == "R2API" {
depString = "tristanmcpherson-R2API"
}
pkgFile, err := os.Open(utils.SystemInfo.TmpDir + "/pkg.json")
utils.CheckErr(err)
byteValue, err := ioutil.ReadAll(pkgFile)
utils.CheckErr(err)
var mods []Mod
err = json.Unmarshal(byteValue, &mods)
utils.CheckErr(err)
var selectedMod Mod
for i := 0; i < len(mods); i++ {
if mods[i].FullName == depString {
selectedMod = mods[i]
}
}
defer pkgFile.Close()
// TODO: export this lol
return selectedMod
}