server/remote/challenge-sync-airbus/timestamp.go

72 lines
1.2 KiB
Go

package main
import (
"encoding/json"
"log"
"os"
"time"
)
type TSValue struct {
Time time.Time `json:"t"`
Score int64 `json:"s"`
}
func loadTS(tspath string) (timestamp map[string]*TSValue, err error) {
var fd *os.File
if _, err = os.Stat(tspath); os.IsNotExist(err) {
timestamp = map[string]*TSValue{}
err = saveTS(tspath, timestamp)
return
} else if fd, err = os.Open(tspath); err != nil {
return nil, err
} else {
defer fd.Close()
jdec := json.NewDecoder(fd)
if err = jdec.Decode(&timestamp); err != nil {
return
}
return
}
}
func loadTSFromAPI(teams map[string]*AirbusTeam) (timestamp map[string]*TSValue, err error) {
now := time.Now()
timestamp = map[string]*TSValue{}
for _, team := range teams {
timestamp[team.Name] = &TSValue{
Time: now,
Score: team.Score,
}
}
return
}
func saveTS(tspath string, ts map[string]*TSValue) error {
if dryRun {
tmp := map[string]TSValue{}
for k, v := range ts {
tmp[k] = *v
}
log.Println("saving TS: ", tmp)
return nil
}
if fd, err := os.Create(tspath); err != nil {
return err
} else {
defer fd.Close()
jenc := json.NewEncoder(fd)
if err := jenc.Encode(ts); err != nil {
return err
}
return nil
}
}