lodestone-fetcher/main.go

89 lines
1.6 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"
2024-02-25 21:36:20 +00:00
"strconv"
2024-02-01 08:52:42 +00:00
"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-25 21:36:20 +00:00
args := os.Args[1:]
2024-02-01 08:52:42 +00:00
2024-02-25 21:36:20 +00:00
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)
}
2023-12-16 05:51:06 +00:00
2024-02-25 21:36:20 +00:00
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)
2024-02-01 08:52:42 +00:00
}
2023-12-16 05:51:06 +00:00
}
func refetch_data(id uint32) CacheRecord {
2024-02-02 06:20:17 +00:00
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)}
}