This repository has been archived on 2024-05-18. You can view files and clone it, but cannot push or open issues or pull requests.
steamServer/cmd/main.go

113 lines
2.7 KiB
Go
Raw Normal View History

2021-09-20 14:57:24 +02:00
package main
import (
"time"
2021-09-20 14:57:24 +02:00
"log"
"net/http"
2021-10-14 11:24:54 +02:00
"strings"
2021-09-20 14:57:24 +02:00
"git.snrd.de/Spaenny/steamServer"
"git.snrd.de/Spaenny/steamServer/postgres"
"git.snrd.de/Spaenny/steamServer/web"
2021-09-23 15:58:56 +02:00
"github.com/rumblefrog/go-a2s"
"github.com/robfig/cron/v3"
2021-09-20 14:57:24 +02:00
)
func main() {
2021-09-24 13:19:44 +02:00
dsn := "postgres://postgres:secret@postgres:5432/postgres?sslmode=disable"
2021-09-20 14:57:24 +02:00
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()
2021-09-20 14:57:24 +02:00
h := web.NewHandler(store)
http.ListenAndServe(":3000", h)
2021-09-20 14:57:24 +02:00
}
func stringInSlice(a string, list []string) bool {
for _, b := range list {
if b == a {
return true
}
}
return false
}
2021-09-23 15:58:56 +02:00
func updateServers(host string, store steamServer.Store) {
client, err := a2s.NewClient(host, a2s.TimeoutOption(time.Second * 10))
if err != nil {
2021-09-23 15:58:56 +02:00
log.Fatal("Creation of client failed: %w", err)
return
}
2021-09-23 15:58:56 +02:00
defer client.Close()
2021-09-23 15:58:56 +02:00
info, err := client.QueryInfo()
if err != nil {
2021-09-23 15:58:56 +02:00
log.Printf("Querying failed: %s", err)
server := steamServer.Server {
Name: host,
Map: "Server didn't reply.",
Players: 0,
}
store.UpdateServerByQuery(&server, host)
2021-09-23 15:58:56 +02:00
return
}
2021-09-23 15:58:56 +02:00
log.Printf("%s - %s\n", host, info.Name)
2021-10-14 11:24:54 +02:00
// 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]
}
2021-09-23 15:58:56 +02:00
server := steamServer.Server {
AppID: info.ID,
Name: info.Name,
Map: info.Map,
Players: info.Players,
MaxPlayers: info.MaxPlayers,
}
2021-09-23 15:58:56 +02:00
store.UpdateServerByQuery(&server, host)
}