112 lines
2.7 KiB
Go
112 lines
2.7 KiB
Go
package main
|
|
|
|
import (
|
|
"time"
|
|
"log"
|
|
"net/http"
|
|
"strings"
|
|
|
|
"git.snrd.de/Spaenny/steamServer"
|
|
"git.snrd.de/Spaenny/steamServer/postgres"
|
|
"git.snrd.de/Spaenny/steamServer/web"
|
|
"github.com/rumblefrog/go-a2s"
|
|
"github.com/robfig/cron/v3"
|
|
)
|
|
|
|
func main() {
|
|
dsn := "postgres://postgres:secret@postgres:5432/postgres?sslmode=disable"
|
|
|
|
store, err := postgres.NewStore(dsn)
|
|
if err != nil {
|
|
log.Fatal(err)
|
|
}
|
|
|
|
ss, err := store.Servers()
|
|
if err != nil {
|
|
log.Fatal("There is an issue with the databse: %w", err)
|
|
}
|
|
|
|
var addedServers []string
|
|
for _, server := range addedServers {
|
|
println(server)
|
|
}
|
|
for _, s := range ss {
|
|
serverString := s.ServerIP
|
|
if !stringInSlice(s.ServerIP, addedServers) {
|
|
addedServers = append(addedServers, s.ServerIP)
|
|
c := cron.New()
|
|
c.AddFunc("*/1 * * * *", func() { updateServers(serverString, store) })
|
|
c.Start()
|
|
}
|
|
}
|
|
cronjob := cron.New()
|
|
cronjob.AddFunc("*/5 * * * *", func() {
|
|
for _, s := range ss {
|
|
serverString := s.ServerIP
|
|
if !stringInSlice(s.ServerIP, addedServers) {
|
|
addedServers = append(addedServers, s.ServerIP)
|
|
c := cron.New()
|
|
c.AddFunc("*/1 * * * *", func() { updateServers(serverString, store) })
|
|
c.Start()
|
|
}
|
|
}
|
|
})
|
|
cronjob.Start()
|
|
|
|
|
|
h := web.NewHandler(store)
|
|
http.ListenAndServe(":3000", h)
|
|
}
|
|
|
|
func stringInSlice(a string, list []string) bool {
|
|
for _, b := range list {
|
|
if b == a {
|
|
return true
|
|
}
|
|
}
|
|
return false
|
|
}
|
|
|
|
func updateServers(host string, store steamServer.Store) {
|
|
client, err := a2s.NewClient(host, a2s.TimeoutOption(time.Second * 10))
|
|
|
|
if err != nil {
|
|
log.Fatal("Creation of client failed: %w", err)
|
|
return
|
|
}
|
|
|
|
defer client.Close()
|
|
|
|
info, err := client.QueryInfo()
|
|
|
|
if err != nil {
|
|
log.Printf("Querying failed: %s", err)
|
|
server := steamServer.Server {
|
|
Name: host,
|
|
Map: "Server didn't reply.",
|
|
Players: 0,
|
|
}
|
|
|
|
store.UpdateServerByQuery(&server, host)
|
|
return
|
|
}
|
|
|
|
log.Printf("%s - %s\n", host, info.Name)
|
|
|
|
// Some Servers use workshop maps and add a prefix, we don't need that
|
|
if strings.HasPrefix(info.Map, "workshop/") {
|
|
mapSplit := strings.Split(info.Map, "/")
|
|
info.Map = mapSplit[1]
|
|
}
|
|
|
|
|
|
server := steamServer.Server {
|
|
AppID: info.ID,
|
|
Name: info.Name,
|
|
Map: info.Map,
|
|
Players: info.Players,
|
|
MaxPlayers: info.MaxPlayers,
|
|
}
|
|
|
|
store.UpdateServerByQuery(&server, host)
|
|
}
|