package api import ( "encoding/json" "io/ioutil" "os" "r2go/utils" "time" "github.com/lithammer/fuzzysearch/fuzzy" ) // PkgList contains all mods in current package cache var PkgList []Mod // 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"` } // InitAPI stores the API in an object when needed. func InitAPI() { if CheckAPICache() != 0 { UpdateAPICache() } PkgList = UnpackAPI() } // CheckAPICache checks if the cached json is expired func CheckAPICache() int { if !utils.PathExists(utils.SystemInfo.ProgDir + "/pkg.json") { return 1 } info, err := os.Stat(utils.SystemInfo.ProgDir + "/pkg.json") utils.CheckErr(err) lastModTime := info.ModTime() currentTime := time.Now() if currentTime.Sub(lastModTime).Seconds() > 7200 { return 1 } return 0 } // UpdateAPICache gets a new copy of the thunderstore pkgfile func UpdateAPICache() { apiURL := "https://thunderstore.io/api/v1/package/" err := utils.DownloadFile(utils.SystemInfo.ProgDir+"/pkg.json", apiURL) utils.CheckErr(err) } // UnpackAPI stores the API cache as an object for later use. func UnpackAPI() []Mod { pkgFile, err := os.Open(utils.SystemInfo.ProgDir + "/pkg.json") utils.CheckErr(err) defer pkgFile.Close() byteValue, err := ioutil.ReadAll(pkgFile) utils.CheckErr(err) var mods []Mod err = json.Unmarshal(byteValue, &mods) utils.CheckErr(err) return mods } // SearchMods finds mods that match a fuzzy search func SearchMods(inp string) fuzzy.Ranks { var pkgNames []string for _, mod := range PkgList { pkgNames = append(pkgNames, mod.FullName) } results := fuzzy.RankFindFold(inp, pkgNames) return results } // GetModData gets object of mod by depString func GetModData(depString string) (int, Mod) { if depString == "R2API" { depString = "tristanmcpherson-R2API" } for i := 0; i < len(PkgList); i++ { if PkgList[i].FullName == depString { return 0, PkgList[i] } } return 1, Mod{} }