lodestone-fetcher/main.go

89 lines
1.6 KiB
Go

package main
import (
"encoding/json"
"errors"
"fmt"
"log"
"os"
"path"
"strconv"
"time"
"github.com/karashiiro/bingode"
"github.com/xivapi/godestone/v2"
)
const CachePath = "./.cache"
type CacheRecord struct {
Time time.Time `json:"time"`
Data string `json:"data"`
}
type Cache map[uint32]CacheRecord
func main() {
err := os.MkdirAll(CachePath, 0755)
if err != nil {
log.Fatal(err)
}
raw_cache, err := os.ReadFile(path.Join(CachePath, "cache.json"))
var cache Cache
if errors.Is(err, os.ErrNotExist) {
cache = make(Cache)
} else if err == nil {
err := json.Unmarshal(raw_cache, &cache)
if err != nil {
log.Fatalln(err)
}
} else {
log.Fatalln(err)
}
args := os.Args[1:]
for _, arg := range args {
id_64, err := strconv.ParseUint(arg, 10, 32)
if err != nil {
log.New(os.Stderr, "", 0).Println(err)
os.Exit(2)
}
id := uint32(id_64)
// bingle: 29932586
// dialus: 44540671
data, ok := cache[id]
if !ok || time.Now().After(data.Time.Add(time.Minute*10)) {
cache[id] = refetch_data(id)
data = cache[id]
}
cache_as_stored, err := json.Marshal(cache)
if err != nil {
log.Fatalln(err)
}
err = os.WriteFile(path.Join(CachePath, "cache.json"), cache_as_stored, 0755)
if err != nil {
log.Fatalln(err)
}
fmt.Printf("%s\n", data.Data)
}
}
func refetch_data(id uint32) CacheRecord {
log.New(os.Stderr, "", 0).Printf("Fetching fresh data for %d\n", id)
s := godestone.NewScraper(bingode.New(), godestone.EN)
c, err := s.FetchCharacter(id)
if err != nil {
log.Fatalln(err)
}
raw_data, _ := json.Marshal(c.ClassJobs)
return CacheRecord{Time: time.Now(), Data: string(raw_data)}
}