gamboupload/gambo.go

108 lines
1.9 KiB
Go

package main
import (
"bytes"
"encoding/json"
"fmt"
"log"
"net/http"
"os"
"strings"
"time"
)
func gambo() {
b, err := os.ReadFile(config.Log)
if err != nil {
log.Fatal(err)
}
// Strip carriage returns because Windows is retarded
b = bytes.ReplaceAll(b, []byte("\r"), []byte(""))
lines := strings.Split(string(b), "\n")
fmt.Println("Parse entire log or just the last raid's entries?")
fmt.Println("1) Last raid")
fmt.Println("2) Full log")
var (
start int
choice int
)
_, err = fmt.Scanf("%d", &choice)
if err != nil {
log.Fatal(err)
}
switch choice {
case 1:
start = findStart(lines)
case 2:
start = 0
default:
log.Fatalf("%d is not a valid choice, retard\n", choice)
}
games, err := parseGames(lines, start)
if err != nil {
log.Fatal(err)
}
for _, game := range games {
err = uploadGambo(game, "https://forcek.in/game")
//err = uploadGamboTest(game)
if err != nil {
log.Fatal(err)
}
}
}
func findStart(lines []string) int {
now := time.Now()
t := time.Date(now.Year(), now.Month(), now.Day(), 15, 45, 0, 0, time.UTC)
for t.Weekday() != time.Sunday {
t = t.AddDate(0, 0, -1)
}
// skip ending newline
var i = len(lines) - 2
for ; i >= 0; i-- {
ts, err := timestamp(lines[i])
if err != nil {
log.Fatalf("Failed to rewind log: %v\n", err)
}
if ts.Before(t) {
break
}
}
return i + 1
}
func uploadGambo(game Game, endpoint string) error {
marshalled, err := json.Marshal(game)
if err != nil {
return err
}
req, err := http.NewRequest("POST", endpoint, bytes.NewBuffer(marshalled))
if err != nil {
return err
}
req.Header.Set("Content-Type", "application/json")
req.Header.Set("X-API-KEY", config.Apikey)
resp, err := http.DefaultClient.Do(req)
if err != nil {
return err
}
fmt.Println(resp.Status)
return nil
}
func uploadGamboTest(game Game) error {
return uploadGambo(game, "http://localhost:3000/game")
}