diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..ceddaa3 --- /dev/null +++ b/.gitignore @@ -0,0 +1 @@ +.cache/ diff --git a/clear_cache.sh b/clear_cache.sh new file mode 100755 index 0000000..9aee7bd --- /dev/null +++ b/clear_cache.sh @@ -0,0 +1,3 @@ +#!/bin/sh + +rm -rf .cache diff --git a/main.go b/main.go index 4765774..a2ef6f2 100644 --- a/main.go +++ b/main.go @@ -2,21 +2,70 @@ package main import ( "encoding/json" + "errors" "fmt" "log" + "os" + "path" + "time" "github.com/karashiiro/bingode" "github.com/xivapi/godestone/v2" ) -func main() { - s := godestone.NewScraper(bingode.New(), godestone.EN) +const CachePath = "./.cache" - c, err := s.FetchCharacter(29932586) +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) + } + + var id uint32 = 29932586 + data, ok := cache[id] + if !ok { + log.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) + data = CacheRecord{Time: time.Now(), Data: string(raw_data)} + + cache[id] = data + } + + cache_as_stored, err := json.Marshal(cache) if err != nil { log.Fatalln(err) } - data, _ := json.Marshal(c.ClassJobs) - fmt.Printf("%s\n", data) + err = os.WriteFile(path.Join(CachePath, "cache.json"), cache_as_stored, 0755) + if err != nil { + log.Fatalln(err) + } + fmt.Printf("%s\n", data.Data) }