lodestone-fetcher/main.go

72 lines
1.3 KiB
Go
Raw Normal View History

2023-12-16 05:51:06 +00:00
package main
import (
2024-02-01 07:48:09 +00:00
"encoding/json"
2024-02-01 08:52:42 +00:00
"errors"
2024-02-01 07:48:09 +00:00
"fmt"
2023-12-16 05:51:06 +00:00
"log"
2024-02-01 08:52:42 +00:00
"os"
"path"
"time"
2023-12-16 05:51:06 +00:00
"github.com/karashiiro/bingode"
"github.com/xivapi/godestone/v2"
)
2024-02-01 08:52:42 +00:00
const CachePath = "./.cache"
type CacheRecord struct {
Time time.Time `json:"time"`
Data string `json:"data"`
}
type Cache map[uint32]CacheRecord
2023-12-16 05:51:06 +00:00
func main() {
2024-02-01 08:52:42 +00:00
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)
}
2023-12-16 05:51:06 +00:00
2024-02-01 08:52:42 +00:00
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)
2023-12-16 05:51:06 +00:00
if err != nil {
log.Fatalln(err)
}
2024-02-01 08:52:42 +00:00
err = os.WriteFile(path.Join(CachePath, "cache.json"), cache_as_stored, 0755)
if err != nil {
log.Fatalln(err)
}
fmt.Printf("%s\n", data.Data)
2023-12-16 05:51:06 +00:00
}