Initial commit

This commit is contained in:
MrFastwind
2026-07-06 01:29:23 +02:00
commit b853aead8c
48 changed files with 5822 additions and 0 deletions

View File

@@ -0,0 +1,114 @@
package api
import (
"net/http"
"strings"
"github.com/gin-gonic/gin"
)
type createConfigInput struct {
Name string `json:"name" binding:"required"`
Content string `json:"content"`
}
type updateConfigInput struct {
Content string `json:"content" binding:"required"`
}
type duplicateConfigInput struct {
NewName string `json:"new_name" binding:"required"`
}
func (h *Handler) ListConfigs(c *gin.Context) {
configs, err := h.configs.List()
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
c.JSON(http.StatusOK, configs)
}
func validateConfigName(name string) bool {
return name != "" && !strings.ContainsAny(name, "/\\")
}
func (h *Handler) CreateConfig(c *gin.Context) {
var input createConfigInput
if err := c.ShouldBindJSON(&input); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
if !validateConfigName(input.Name) {
c.JSON(http.StatusBadRequest, gin.H{"error": "invalid config name"})
return
}
if err := h.configs.Create(input.Name, input.Content); err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
c.JSON(http.StatusCreated, gin.H{"name": input.Name})
}
func (h *Handler) GetConfig(c *gin.Context) {
name := c.Param("name")
if !validateConfigName(name) {
c.JSON(http.StatusBadRequest, gin.H{"error": "invalid config name"})
return
}
content, err := h.configs.Get(name)
if err != nil {
c.JSON(http.StatusNotFound, gin.H{"error": err.Error()})
return
}
c.String(http.StatusOK, content)
}
func (h *Handler) UpdateConfig(c *gin.Context) {
var input updateConfigInput
if err := c.ShouldBindJSON(&input); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
name := c.Param("name")
if !validateConfigName(name) {
c.JSON(http.StatusBadRequest, gin.H{"error": "invalid config name"})
return
}
if err := h.configs.Update(name, input.Content); err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
c.JSON(http.StatusOK, gin.H{"status": "ok"})
}
func (h *Handler) DeleteConfig(c *gin.Context) {
name := c.Param("name")
if !validateConfigName(name) {
c.JSON(http.StatusBadRequest, gin.H{"error": "invalid config name"})
return
}
if err := h.configs.Delete(name); err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
c.JSON(http.StatusNoContent, nil)
}
func (h *Handler) DuplicateConfig(c *gin.Context) {
var input duplicateConfigInput
if err := c.ShouldBindJSON(&input); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
name := c.Param("name")
if !validateConfigName(name) || !validateConfigName(input.NewName) {
c.JSON(http.StatusBadRequest, gin.H{"error": "invalid config name"})
return
}
if err := h.configs.Duplicate(name, input.NewName); err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
c.JSON(http.StatusCreated, gin.H{"name": input.NewName})
}

View File

@@ -0,0 +1,196 @@
package api
import (
"io"
"log"
"net/http"
"os"
"path/filepath"
"slices"
"sort"
"strings"
"time"
"github.com/gin-gonic/gin"
"github.com/gorilla/websocket"
)
var upgrader = websocket.Upgrader{
CheckOrigin: func(r *http.Request) bool { return true },
}
func (h *Handler) StreamLogs(c *gin.Context) {
conn, err := upgrader.Upgrade(c.Writer, c.Request, nil)
if err != nil {
log.Printf("websocket upgrade error: %v", err)
return
}
defer conn.Close()
clientID := conn.RemoteAddr().String()
ch := h.streamer.Subscribe("server", clientID)
defer h.streamer.Unsubscribe("server", clientID)
for line := range ch {
if err := conn.WriteMessage(websocket.TextMessage, []byte(line)); err != nil {
break
}
}
}
func (h *Handler) ListLogs(c *gin.Context) {
profilesDir := h.process.ProfilesDir()
files := h.collectLogFiles(profilesDir, "")
logsDir := filepath.Join(profilesDir, "logs")
if fi, err := os.Stat(logsDir); err == nil && fi.IsDir() {
files = append(files, h.collectLogFiles(logsDir, "logs")...)
}
slices.Sort(files)
if files == nil {
files = []string{}
}
c.JSON(http.StatusOK, files)
}
func (h *Handler) collectLogFiles(dir, prefix string) []string {
entries, err := os.ReadDir(dir)
if err != nil {
return nil
}
var files []string
for _, e := range entries {
if !e.IsDir() {
ext := filepath.Ext(e.Name())
if ext == ".log" || ext == ".rpt" || e.Name() == "script.log" {
if prefix != "" {
files = append(files, prefix+"/"+e.Name())
} else {
files = append(files, e.Name())
}
}
}
}
return files
}
func (h *Handler) StreamSteamCMDLogs(c *gin.Context) {
conn, err := upgrader.Upgrade(c.Writer, c.Request, nil)
if err != nil {
log.Printf("websocket upgrade error: %v", err)
return
}
defer conn.Close()
clientID := conn.RemoteAddr().String()
ch := h.streamer.Subscribe("steamcmd", clientID)
defer h.streamer.Unsubscribe("steamcmd", clientID)
for line := range ch {
if err := conn.WriteMessage(websocket.TextMessage, []byte(line)); err != nil {
break
}
}
}
func (h *Handler) StreamRPTLogs(c *gin.Context) {
conn, err := upgrader.Upgrade(c.Writer, c.Request, nil)
if err != nil {
log.Printf("websocket upgrade error: %v", err)
return
}
defer conn.Close()
profilesDir := h.process.ProfilesDir()
var currentPath string
var currentOffset int64
ticker := time.NewTicker(250 * time.Millisecond)
defer ticker.Stop()
for range ticker.C {
path := findLatestRPT(profilesDir)
if path != currentPath {
currentPath = path
currentOffset = 0
if currentPath == "" {
continue
}
conn.WriteMessage(websocket.TextMessage, []byte("--- tailing: "+filepath.Base(currentPath)+" ---"))
}
if currentPath == "" {
continue
}
fi, err := os.Stat(currentPath)
if err != nil {
currentPath = ""
continue
}
if fi.Size() <= currentOffset {
continue
}
f, err := os.Open(currentPath)
if err != nil {
currentPath = ""
continue
}
f.Seek(currentOffset, io.SeekStart)
buf := make([]byte, fi.Size()-currentOffset)
n, _ := io.ReadFull(f, buf)
f.Close()
currentOffset += int64(n)
for _, line := range strings.Split(string(buf[:n]), "\n") {
if line == "" {
continue
}
if err := conn.WriteMessage(websocket.TextMessage, []byte(line)); err != nil {
return
}
}
}
}
func findLatestRPT(dir string) string {
pattern := filepath.Join(dir, "arma3server_x64_*.rpt")
matches, err := filepath.Glob(pattern)
if err != nil || len(matches) == 0 {
return ""
}
sort.Slice(matches, func(i, j int) bool {
fi, _ := os.Stat(matches[i])
fj, _ := os.Stat(matches[j])
return fi.ModTime().After(fj.ModTime())
})
return matches[0]
}
func (h *Handler) GetLog(c *gin.Context) {
filename := filepath.Base(c.Param("file"))
if filename == "" || strings.ContainsRune(c.Param("file"), os.PathSeparator) {
c.JSON(http.StatusBadRequest, gin.H{"error": "invalid filename"})
return
}
profilesDir := h.process.ProfilesDir()
path := filepath.Join(profilesDir, filename)
if _, err := os.Stat(path); os.IsNotExist(err) {
logsPath := filepath.Join(profilesDir, "logs", filename)
if _, err2 := os.Stat(logsPath); err2 == nil {
path = logsPath
} else {
c.JSON(http.StatusNotFound, gin.H{"error": "file not found"})
return
}
}
data, err := os.ReadFile(path)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
c.String(http.StatusOK, string(data))
}

View File

@@ -0,0 +1,202 @@
package api
import (
"net/http"
"arma3-web-server/internal/models"
"arma3-web-server/internal/services"
"github.com/gin-gonic/gin"
)
type createModlistInput struct {
Name string `json:"name" binding:"required"`
}
type updateModlistInput struct {
Name string `json:"name" binding:"required"`
Mods []models.ModEntry `json:"mods"`
}
type duplicateModlistInput struct {
Name string `json:"name" binding:"required"`
}
func (h *Handler) ListModlists(c *gin.Context) {
items, err := h.modlists.List()
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
c.JSON(http.StatusOK, items)
}
func (h *Handler) CreateModlist(c *gin.Context) {
var input createModlistInput
if err := c.ShouldBindJSON(&input); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
ml, err := h.modlists.Create(input.Name)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
c.JSON(http.StatusCreated, ml)
}
func (h *Handler) GetModlist(c *gin.Context) {
ml, err := h.modlists.Get(c.Param("id"))
if err != nil {
c.JSON(http.StatusNotFound, gin.H{"error": err.Error()})
return
}
c.JSON(http.StatusOK, ml)
}
func (h *Handler) UpdateModlist(c *gin.Context) {
var input updateModlistInput
if err := c.ShouldBindJSON(&input); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
ml, err := h.modlists.Update(c.Param("id"), input.Name, input.Mods)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
c.JSON(http.StatusOK, ml)
}
func (h *Handler) DeleteModlist(c *gin.Context) {
if err := h.modlists.Delete(c.Param("id")); err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
c.JSON(http.StatusNoContent, nil)
}
func (h *Handler) DuplicateModlist(c *gin.Context) {
var input duplicateModlistInput
if err := c.ShouldBindJSON(&input); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
ml, err := h.modlists.Duplicate(c.Param("id"), input.Name)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
c.JSON(http.StatusCreated, ml)
}
func (h *Handler) ImportModlist(c *gin.Context) {
file, header, err := c.Request.FormFile("file")
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": "file field required"})
return
}
defer file.Close()
_, mods, err := services.ParseModlistHTML(file)
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": "parse html: " + err.Error()})
return
}
listName := services.FileNameToModlistName(header.Filename)
ml, err := h.modlists.Create(listName)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
ml, err = h.modlists.Update(ml.ID, ml.Name, mods)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
c.JSON(http.StatusCreated, ml)
}
type modStatus struct {
ID string `json:"id"`
Name string `json:"name"`
Enabled bool `json:"enabled"`
Downloaded bool `json:"downloaded"`
}
func (h *Handler) CheckModlistMods(c *gin.Context) {
ml, err := h.modlists.Get(c.Param("id"))
if err != nil {
c.JSON(http.StatusNotFound, gin.H{"error": err.Error()})
return
}
dir := h.process.ServerfileDir()
var result []modStatus
for _, m := range ml.Mods {
result = append(result, modStatus{
ID: m.ID,
Name: m.Name,
Enabled: m.Enabled,
Downloaded: services.CheckWorkshopMod(dir, m.ID),
})
}
c.JSON(http.StatusOK, result)
}
func (h *Handler) DownloadMissingMods(c *gin.Context) {
ml, err := h.modlists.Get(c.Param("id"))
if err != nil {
c.JSON(http.StatusNotFound, gin.H{"error": err.Error()})
return
}
dir := h.process.ServerfileDir()
var missing []string
for _, m := range ml.Mods {
if m.ID != "" && !services.CheckWorkshopMod(dir, m.ID) {
missing = append(missing, m.ID)
}
}
if len(missing) == 0 {
c.JSON(http.StatusOK, gin.H{"status": "all mods present"})
return
}
if err := h.steamcmd.DownloadMods(missing); err != nil {
c.JSON(http.StatusConflict, gin.H{"error": err.Error()})
return
}
c.JSON(http.StatusOK, gin.H{"status": "downloading", "count": len(missing)})
}
func (h *Handler) UpdateAllMods(c *gin.Context) {
ml, err := h.modlists.Get(c.Param("id"))
if err != nil {
c.JSON(http.StatusNotFound, gin.H{"error": err.Error()})
return
}
var ids []string
for _, m := range ml.Mods {
if m.ID != "" {
ids = append(ids, m.ID)
}
}
if len(ids) == 0 {
c.JSON(http.StatusOK, gin.H{"status": "no mods with workshop ids"})
return
}
if err := h.steamcmd.DownloadMods(ids); err != nil {
c.JSON(http.StatusConflict, gin.H{"error": err.Error()})
return
}
c.JSON(http.StatusOK, gin.H{"status": "updating", "count": len(ids)})
}

View File

@@ -0,0 +1,85 @@
package api
import (
"arma3-web-server/internal/services"
"github.com/gin-gonic/gin"
)
type Handler struct {
settings *services.SettingsManager
configs *services.ConfigManager
modlists *services.ModlistManager
process *services.ProcessManager
steamcmd *services.SteamCmdManager
streamer *services.LogStreamer
serverfileDir string
modsDir string
cfgDir string
profilesDir string
}
func New(
settings *services.SettingsManager,
configs *services.ConfigManager,
modlists *services.ModlistManager,
process *services.ProcessManager,
steamcmd *services.SteamCmdManager,
streamer *services.LogStreamer,
serverfileDir, modsDir, cfgDir, profilesDir string,
) *Handler {
return &Handler{
settings: settings,
configs: configs,
modlists: modlists,
process: process,
steamcmd: steamcmd,
streamer: streamer,
serverfileDir: serverfileDir,
modsDir: modsDir,
cfgDir: cfgDir,
profilesDir: profilesDir,
}
}
func (h *Handler) SetupRoutes(r *gin.Engine) {
api := r.Group("/api")
{
api.GET("/server/settings", h.GetSettings)
api.PUT("/server/settings", h.UpdateSettings)
api.POST("/server/start", h.StartServer)
api.POST("/server/stop", h.StopServer)
api.POST("/server/restart", h.RestartServer)
api.GET("/server/status", h.ServerStatus)
api.GET("/server/steamcmd", h.SteamCMDSettings)
api.POST("/server/steamcmd/update-game", h.SteamCMDUpdateGame)
api.POST("/server/steamcmd/download-mod", h.SteamCMDDownloadMod)
api.GET("/server/steamcmd/status", h.SteamCMDStatus)
api.GET("/server/paths", h.ServerPaths)
api.GET("/server/logs", h.ListLogs)
api.GET("/server/logs/:file", h.GetLog)
api.GET("/configs", h.ListConfigs)
api.POST("/configs", h.CreateConfig)
api.GET("/configs/:name", h.GetConfig)
api.PUT("/configs/:name", h.UpdateConfig)
api.DELETE("/configs/:name", h.DeleteConfig)
api.POST("/configs/:name/duplicate", h.DuplicateConfig)
api.GET("/modlists", h.ListModlists)
api.POST("/modlists", h.CreateModlist)
api.GET("/modlists/:id", h.GetModlist)
api.PUT("/modlists/:id", h.UpdateModlist)
api.DELETE("/modlists/:id", h.DeleteModlist)
api.POST("/modlists/:id/duplicate", h.DuplicateModlist)
api.POST("/modlists/import", h.ImportModlist)
api.GET("/modlists/:id/check", h.CheckModlistMods)
api.POST("/modlists/:id/download-missing", h.DownloadMissingMods)
api.POST("/modlists/:id/update-all", h.UpdateAllMods)
}
r.GET("/ws/server/logs", h.StreamLogs)
r.GET("/ws/steamcmd/logs", h.StreamSteamCMDLogs)
r.GET("/ws/server/rpt", h.StreamRPTLogs)
}

View File

@@ -0,0 +1,173 @@
package api
import (
"net/http"
"github.com/gin-gonic/gin"
)
type updateSettingsInput struct {
IPPort *string `json:"ip_port"`
ServerParameters *string `json:"server_parameters"`
SteamBranch *string `json:"steam_branch"`
SteamUser *string `json:"steam_user"`
Platform *string `json:"platform"`
CBASettings *string `json:"cba_settings"`
AILevelPresets *string `json:"ai_level_presets"`
DifficultyPresets *string `json:"difficulty_presets"`
ActiveConfig *string `json:"active_config"`
ActiveModlist *string `json:"active_modlist"`
}
func (h *Handler) GetSettings(c *gin.Context) {
s, err := h.settings.Load()
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
c.JSON(http.StatusOK, s)
}
func (h *Handler) UpdateSettings(c *gin.Context) {
var input updateSettingsInput
if err := c.ShouldBindJSON(&input); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
s, err := h.settings.Load()
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
if input.IPPort != nil { s.IPPort = *input.IPPort }
if input.ServerParameters != nil { s.ServerParameters = *input.ServerParameters }
if input.SteamBranch != nil { s.SteamBranch = *input.SteamBranch }
if input.SteamUser != nil { s.SteamUser = *input.SteamUser }
if input.Platform != nil { s.Platform = *input.Platform }
if input.CBASettings != nil { s.CBASettings = *input.CBASettings }
if input.AILevelPresets != nil { s.AILevelPresets = *input.AILevelPresets }
if input.DifficultyPresets != nil { s.DifficultyPresets = *input.DifficultyPresets }
if input.ActiveConfig != nil { s.ActiveConfig = *input.ActiveConfig }
if input.ActiveModlist != nil { s.ActiveModlist = *input.ActiveModlist }
if err := h.process.WriteUserconfigFiles(s); err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": "write userconfig: " + err.Error()})
return
}
if err := h.settings.Save(s); err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
c.JSON(http.StatusOK, s)
}
func (h *Handler) StartServer(c *gin.Context) {
if err := h.process.Start(); err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
c.JSON(http.StatusOK, gin.H{"status": "starting"})
}
func (h *Handler) StopServer(c *gin.Context) {
if err := h.process.Stop(); err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
c.JSON(http.StatusOK, gin.H{"status": "stopping"})
}
func (h *Handler) RestartServer(c *gin.Context) {
if err := h.process.Restart(); err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
c.JSON(http.StatusOK, gin.H{"status": "restarting"})
}
func (h *Handler) ServerStatus(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{
"running": h.process.IsRunning(),
})
}
func (h *Handler) SteamCMDSettings(c *gin.Context) {
s, err := h.settings.Load()
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
c.JSON(http.StatusOK, gin.H{
"branch": s.SteamBranch,
"user": s.SteamUser,
"platform": s.Platform,
})
}
type steamcmdUpdateGameInput struct {
Branch string `json:"branch"`
User string `json:"user"`
}
func (h *Handler) SteamCMDUpdateGame(c *gin.Context) {
var input steamcmdUpdateGameInput
if err := c.ShouldBindJSON(&input); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
user := input.User
if user == "" {
user = "anonymous"
}
branch := input.Branch
if branch == "" {
branch = "stable"
}
if err := h.steamcmd.UpdateGame(branch, user); err != nil {
c.JSON(http.StatusConflict, gin.H{"error": err.Error()})
return
}
c.JSON(http.StatusOK, gin.H{"status": "started"})
}
type steamcmdDownloadModInput struct {
ModID string `json:"mod_id"`
}
func (h *Handler) SteamCMDDownloadMod(c *gin.Context) {
var input steamcmdDownloadModInput
if err := c.ShouldBindJSON(&input); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
if input.ModID == "" {
c.JSON(http.StatusBadRequest, gin.H{"error": "mod_id is required"})
return
}
if err := h.steamcmd.DownloadMod(input.ModID); err != nil {
c.JSON(http.StatusConflict, gin.H{"error": err.Error()})
return
}
c.JSON(http.StatusOK, gin.H{"status": "started"})
}
func (h *Handler) SteamCMDStatus(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{
"running": h.steamcmd.IsRunning(),
})
}
func (h *Handler) ServerPaths(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{
"serverfile_dir": h.serverfileDir,
"mods_dir": h.modsDir,
"cfg_dir": h.cfgDir,
"profiles_dir": h.profilesDir,
})
}

View File

@@ -0,0 +1,25 @@
package models
import "time"
type ModEntry struct {
ID string `json:"id"`
Name string `json:"name"`
Enabled bool `json:"enabled"`
}
type Modlist struct {
ID string `json:"id"`
Name string `json:"name"`
Mods []ModEntry `json:"mods"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
}
type ModlistListItem struct {
ID string `json:"id"`
Name string `json:"name"`
ModCount int `json:"mod_count"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
}

View File

@@ -0,0 +1,17 @@
package models
import "time"
type ServerSettings struct {
IPPort string `json:"ip_port"`
ServerParameters string `json:"server_parameters"`
SteamBranch string `json:"steam_branch"`
SteamUser string `json:"steam_user"`
Platform string `json:"platform"`
CBASettings string `json:"cba_settings"`
AILevelPresets string `json:"ai_level_presets"`
DifficultyPresets string `json:"difficulty_presets"`
ActiveConfig string `json:"active_config"`
ActiveModlist string `json:"active_modlist"`
UpdatedAt time.Time `json:"updated_at"`
}

View File

@@ -0,0 +1,89 @@
package services
import (
"fmt"
"os"
"path/filepath"
"strings"
)
type ConfigManager struct {
cfgDir string
}
func NewConfigManager(cfgDir string) *ConfigManager {
return &ConfigManager{cfgDir: cfgDir}
}
type ConfigInfo struct {
Name string `json:"name"`
Size int64 `json:"size"`
}
func (cm *ConfigManager) List() ([]ConfigInfo, error) {
entries, err := os.ReadDir(cm.cfgDir)
if err != nil {
if os.IsNotExist(err) {
return []ConfigInfo{}, nil
}
return nil, err
}
var configs []ConfigInfo
for _, e := range entries {
if !e.IsDir() && strings.HasSuffix(e.Name(), ".cfg") {
info, _ := e.Info()
configs = append(configs, ConfigInfo{
Name: strings.TrimSuffix(e.Name(), ".cfg"),
Size: info.Size(),
})
}
}
return configs, nil
}
func (cm *ConfigManager) Get(name string) (string, error) {
path := cm.path(name)
data, err := os.ReadFile(path)
if err != nil {
if os.IsNotExist(err) {
return "", fmt.Errorf("config not found")
}
return "", err
}
return string(data), nil
}
func (cm *ConfigManager) Create(name, content string) error {
path := cm.path(name)
if _, err := os.Stat(path); err == nil {
return fmt.Errorf("config already exists")
}
return os.WriteFile(path, []byte(content), 0644)
}
func (cm *ConfigManager) Update(name, content string) error {
return os.WriteFile(cm.path(name), []byte(content), 0644)
}
func (cm *ConfigManager) Delete(name string) error {
return os.Remove(cm.path(name))
}
func (cm *ConfigManager) Duplicate(name, newName string) error {
content, err := cm.Get(name)
if err != nil {
return err
}
return cm.Create(newName, content)
}
func (cm *ConfigManager) path(name string) string {
return filepath.Join(cm.cfgDir, sanitizeConfigName(name)+".cfg")
}
func sanitizeConfigName(name string) string {
name = filepath.Base(name)
name = strings.TrimSuffix(name, ".cfg")
return name
}

View File

@@ -0,0 +1,81 @@
package services
import (
"bufio"
"io"
"log"
"sync"
)
type LogStreamer struct {
mu sync.RWMutex
subs map[string]map[string]chan string
}
func NewLogStreamer() *LogStreamer {
return &LogStreamer{
subs: make(map[string]map[string]chan string),
}
}
func (ls *LogStreamer) Subscribe(serverID, clientID string) chan string {
ls.mu.Lock()
defer ls.mu.Unlock()
if ls.subs[serverID] == nil {
ls.subs[serverID] = make(map[string]chan string)
}
ch := make(chan string, 256)
ls.subs[serverID][clientID] = ch
return ch
}
func (ls *LogStreamer) Unsubscribe(serverID, clientID string) {
ls.mu.Lock()
defer ls.mu.Unlock()
if ls.subs[serverID] != nil {
if ch, ok := ls.subs[serverID][clientID]; ok {
close(ch)
delete(ls.subs[serverID], clientID)
}
if len(ls.subs[serverID]) == 0 {
delete(ls.subs, serverID)
}
}
}
func (ls *LogStreamer) Stream(serverID string, reader io.Reader, closeMsg string) {
scanner := bufio.NewScanner(reader)
for scanner.Scan() {
line := scanner.Text()
ls.broadcast(serverID, line)
}
if err := scanner.Err(); err != nil {
log.Printf("log stream error for server %s: %v", serverID, err)
}
if closeMsg != "" {
ls.broadcast(serverID, closeMsg)
}
}
func (ls *LogStreamer) Broadcast(serverID, line string) {
ls.broadcast(serverID, line)
}
func (ls *LogStreamer) broadcast(serverID, line string) {
ls.mu.RLock()
defer ls.mu.RUnlock()
if ls.subs[serverID] == nil {
return
}
for _, ch := range ls.subs[serverID] {
select {
case ch <- line:
default:
}
}
}

View File

@@ -0,0 +1,182 @@
package services
import (
"encoding/json"
"fmt"
"os"
"path/filepath"
"strings"
"sync"
"time"
"arma3-web-server/internal/models"
"github.com/google/uuid"
)
type ModlistManager struct {
dir string
mu sync.RWMutex
}
func NewModlistManager(dataDir string) *ModlistManager {
return &ModlistManager{
dir: filepath.Join(dataDir, "modlists"),
}
}
func (mm *ModlistManager) path(id string) string {
return filepath.Join(mm.dir, id+".json")
}
func (mm *ModlistManager) List() ([]models.ModlistListItem, error) {
mm.mu.RLock()
defer mm.mu.RUnlock()
entries, err := os.ReadDir(mm.dir)
if err != nil {
if os.IsNotExist(err) {
return []models.ModlistListItem{}, nil
}
return nil, err
}
var items []models.ModlistListItem
for _, e := range entries {
if e.IsDir() || !strings.HasSuffix(e.Name(), ".json") {
continue
}
data, err := os.ReadFile(filepath.Join(mm.dir, e.Name()))
if err != nil {
continue
}
var m models.Modlist
if err := json.Unmarshal(data, &m); err != nil {
continue
}
items = append(items, models.ModlistListItem{
ID: m.ID,
Name: m.Name,
ModCount: len(m.Mods),
CreatedAt: m.CreatedAt,
UpdatedAt: m.UpdatedAt,
})
}
return items, nil
}
func (mm *ModlistManager) Get(id string) (*models.Modlist, error) {
mm.mu.RLock()
defer mm.mu.RUnlock()
data, err := os.ReadFile(mm.path(id))
if err != nil {
if os.IsNotExist(err) {
return nil, fmt.Errorf("modlist not found")
}
return nil, err
}
var m models.Modlist
if err := json.Unmarshal(data, &m); err != nil {
return nil, err
}
return &m, nil
}
func (mm *ModlistManager) Create(name string) (*models.Modlist, error) {
mm.mu.Lock()
defer mm.mu.Unlock()
now := time.Now().UTC()
m := &models.Modlist{
ID: uuid.New().String(),
Name: name,
Mods: []models.ModEntry{},
CreatedAt: now,
UpdatedAt: now,
}
data, err := json.MarshalIndent(m, "", " ")
if err != nil {
return nil, err
}
if err := os.MkdirAll(mm.dir, 0755); err != nil {
return nil, err
}
if err := os.WriteFile(mm.path(m.ID), data, 0644); err != nil {
return nil, err
}
return m, nil
}
func (mm *ModlistManager) Update(id, name string, mods []models.ModEntry) (*models.Modlist, error) {
mm.mu.Lock()
defer mm.mu.Unlock()
m, err := mm.getLocked(id)
if err != nil {
return nil, err
}
m.Name = name
m.Mods = mods
m.UpdatedAt = time.Now().UTC()
data, err := json.MarshalIndent(m, "", " ")
if err != nil {
return nil, err
}
if err := os.WriteFile(mm.path(id), data, 0644); err != nil {
return nil, err
}
return m, nil
}
func (mm *ModlistManager) Delete(id string) error {
mm.mu.Lock()
defer mm.mu.Unlock()
return os.Remove(mm.path(id))
}
func (mm *ModlistManager) Duplicate(id, newName string) (*models.Modlist, error) {
mm.mu.Lock()
defer mm.mu.Unlock()
orig, err := mm.getLocked(id)
if err != nil {
return nil, err
}
now := time.Now().UTC()
dup := &models.Modlist{
ID: uuid.New().String(),
Name: newName,
Mods: orig.Mods,
CreatedAt: now,
UpdatedAt: now,
}
data, err := json.MarshalIndent(dup, "", " ")
if err != nil {
return nil, err
}
if err := os.WriteFile(mm.path(dup.ID), data, 0644); err != nil {
return nil, err
}
return dup, nil
}
func (mm *ModlistManager) getLocked(id string) (*models.Modlist, error) {
data, err := os.ReadFile(mm.path(id))
if err != nil {
if os.IsNotExist(err) {
return nil, fmt.Errorf("modlist not found")
}
return nil, err
}
var m models.Modlist
if err := json.Unmarshal(data, &m); err != nil {
return nil, err
}
return &m, nil
}

View File

@@ -0,0 +1,116 @@
package services
import (
"fmt"
"io"
"net/url"
"path"
"strings"
"arma3-web-server/internal/models"
"golang.org/x/net/html"
)
func ParseModlistHTML(r io.Reader) (string, []models.ModEntry, error) {
doc, err := html.Parse(r)
if err != nil {
return "", nil, fmt.Errorf("parse html: %w", err)
}
var mods []models.ModEntry
seen := map[string]bool{}
var walk func(*html.Node)
walk = func(n *html.Node) {
if n.Type == html.ElementNode && n.Data == "tr" {
if name, id, ok := extractModRow(n); ok && id != "" {
if !seen[id] {
seen[id] = true
mods = append(mods, models.ModEntry{
ID: id,
Name: cleanModName(name),
Enabled: true,
})
}
}
}
for c := n.FirstChild; c != nil; c = c.NextSibling {
walk(c)
}
}
walk(doc)
if mods == nil {
mods = []models.ModEntry{}
}
return "", mods, nil
}
func extractModRow(tr *html.Node) (name, id string, ok bool) {
var cells []*html.Node
for c := tr.FirstChild; c != nil; c = c.NextSibling {
if c.Type == html.ElementNode && c.Data == "td" {
cells = append(cells, c)
}
}
if len(cells) < 3 {
return "", "", false
}
name = extractText(cells[0])
for c := cells[2].FirstChild; c != nil; c = c.NextSibling {
if c.Type == html.ElementNode && c.Data == "a" {
id = extractWorkshopID(c)
break
}
}
if name == "" {
return "", "", false
}
return name, id, true
}
func extractText(n *html.Node) string {
var b strings.Builder
var walk func(*html.Node)
walk = func(n *html.Node) {
if n.Type == html.TextNode {
b.WriteString(n.Data)
}
for c := n.FirstChild; c != nil; c = c.NextSibling {
walk(c)
}
}
walk(n)
return strings.TrimSpace(b.String())
}
func extractWorkshopID(a *html.Node) string {
for _, attr := range a.Attr {
if attr.Key == "href" {
u, err := url.Parse(attr.Val)
if err != nil {
continue
}
return u.Query().Get("id")
}
}
return ""
}
func cleanModName(name string) string {
name = strings.TrimSpace(name)
name = strings.ReplaceAll(name, "/", "_")
name = strings.ReplaceAll(name, "\\", "_")
return name
}
func FileNameToModlistName(filename string) string {
ext := path.Ext(filename)
name := strings.TrimSuffix(filename, ext)
name = strings.ReplaceAll(name, "_", " ")
name = strings.ReplaceAll(name, "-", " ")
return name
}

View File

@@ -0,0 +1,267 @@
package services
import (
"context"
"fmt"
"net"
"os"
"os/exec"
"path/filepath"
"strings"
"sync"
"arma3-web-server/internal/models"
)
type ProcessManager struct {
serverfileDir string
modsDir string
cfgDir string
profilesDir string
settings *SettingsManager
modlists *ModlistManager
configs *ConfigManager
streamer *LogStreamer
proc *runningProcess
mu sync.RWMutex
}
type runningProcess struct {
cmd *exec.Cmd
cancel context.CancelFunc
exited chan struct{}
}
func NewProcessManager(serverfileDir, modsDir, cfgDir, profilesDir string, settings *SettingsManager, modlists *ModlistManager, configs *ConfigManager, streamer *LogStreamer) *ProcessManager {
return &ProcessManager{
serverfileDir: serverfileDir,
modsDir: modsDir,
cfgDir: cfgDir,
profilesDir: profilesDir,
settings: settings,
modlists: modlists,
configs: configs,
streamer: streamer,
}
}
func (pm *ProcessManager) ServerfileDir() string {
return pm.serverfileDir
}
func (pm *ProcessManager) ProfilesDir() string {
return pm.profilesDir
}
func (pm *ProcessManager) IsRunning() bool {
pm.mu.RLock()
defer pm.mu.RUnlock()
return pm.proc != nil
}
func (pm *ProcessManager) Start() error {
pm.mu.Lock()
if pm.proc != nil {
pm.mu.Unlock()
return fmt.Errorf("server already running")
}
pm.mu.Unlock()
s, err := pm.settings.Load()
if err != nil {
return fmt.Errorf("load settings: %w", err)
}
binName := "arma3server_x64"
if s.Platform == "windows" {
binName = "arma3server_x64.exe"
}
binPath := filepath.Join(pm.serverfileDir, binName)
ctx, cancel := context.WithCancel(context.Background())
var cmd *exec.Cmd
if strings.Contains(s.ServerParameters, "%command%") {
full := strings.ReplaceAll(s.ServerParameters, "%command%", binPath)
parts := splitArgs(full)
if len(parts) == 0 {
cancel()
return fmt.Errorf("empty command after %%command%% substitution")
}
autoArgs := pm.buildAutoArgs(s)
cmd = exec.CommandContext(ctx, parts[0], append(parts[1:], autoArgs...)...)
} else {
cmd = exec.CommandContext(ctx, binPath, pm.buildArgs(s)...)
}
cmd.Dir = pm.serverfileDir
stdout, err := cmd.StdoutPipe()
if err != nil {
cancel()
return fmt.Errorf("stdout pipe: %w", err)
}
stderr, err := cmd.StderrPipe()
if err != nil {
cancel()
return fmt.Errorf("stderr pipe: %w", err)
}
if err := cmd.Start(); err != nil {
cancel()
return fmt.Errorf("start: %w", err)
}
exited := make(chan struct{})
pm.mu.Lock()
pm.proc = &runningProcess{cmd: cmd, cancel: cancel, exited: exited}
pm.mu.Unlock()
go pm.streamer.Stream("server", stdout, "")
go pm.streamer.Stream("server", stderr, "")
go func() {
cmd.Wait()
pm.mu.Lock()
pm.proc = nil
pm.mu.Unlock()
close(exited)
pm.streamer.Broadcast("server", "[SERVER_PROCESS_EXITED]")
}()
return nil
}
func (pm *ProcessManager) Stop() error {
pm.mu.Lock()
rp := pm.proc
pm.mu.Unlock()
if rp == nil {
return fmt.Errorf("server not running")
}
rp.cancel()
<-rp.exited
return nil
}
func (pm *ProcessManager) Restart() error {
_ = pm.Stop()
return pm.Start()
}
func splitArgs(raw string) []string {
var args []string
for _, part := range strings.Fields(raw) {
part = strings.TrimSpace(part)
if part != "" {
args = append(args, part)
}
}
return args
}
func (pm *ProcessManager) buildAutoArgs(s *models.ServerSettings) []string {
var args []string
if s.ActiveConfig != "" {
cfgPath := filepath.Join(pm.cfgDir, s.ActiveConfig+".cfg")
args = append(args, "-config="+cfgPath)
}
if s.ActiveModlist != "" {
modPath := pm.buildModPath(s.ActiveModlist)
if modPath != "" {
args = append(args, modPath)
}
}
if pm.profilesDir != "" && !hasArgPrefix(args, "-profiles=") {
args = append(args, "-profiles="+pm.profilesDir)
}
if s.IPPort != "" && !hasArgPrefix(args, "-port=") {
if _, portStr, err := net.SplitHostPort(s.IPPort); err == nil && portStr != "" {
args = append(args, "-port="+portStr)
}
}
return args
}
func (pm *ProcessManager) buildArgs(s *models.ServerSettings) []string {
args := splitArgs(s.ServerParameters)
args = append(args, pm.buildAutoArgs(s)...)
return args
}
func hasArgPrefix(args []string, prefix string) bool {
for _, a := range args {
if strings.HasPrefix(a, prefix) {
return true
}
}
return false
}
const workshopAppID = "107410"
func (pm *ProcessManager) buildModPath(modlistID string) string {
ml, err := pm.modlists.Get(modlistID)
if err != nil {
return ""
}
var parts []string
for _, mod := range ml.Mods {
if !mod.Enabled {
continue
}
parts = append(parts, pm.resolveModPath(mod))
}
if len(parts) == 0 {
return ""
}
return "-mod=" + strings.Join(parts, ";")
}
func (pm *ProcessManager) resolveModPath(mod models.ModEntry) string {
if mod.Name != "" {
p := filepath.Join(pm.modsDir, "@"+mod.Name)
if _, err := os.Stat(p); err == nil {
return p
}
}
if mod.ID != "" {
p := filepath.Join(pm.serverfileDir, "steamapps", "workshop", "content", workshopAppID, mod.ID)
if _, err := os.Stat(p); err == nil {
return p
}
}
if mod.Name != "" {
return filepath.Join(pm.modsDir, "@"+mod.Name)
}
return ""
}
func (pm *ProcessManager) WriteUserconfigFiles(s *models.ServerSettings) error {
userconfigDir := filepath.Join(pm.serverfileDir, "userconfig")
if err := os.MkdirAll(userconfigDir, 0755); err != nil {
return err
}
files := map[string]string{
"cba_settings.sqf": s.CBASettings,
"CfgAILevelPresets.sqf": s.AILevelPresets,
"CfgDifficultyPresets.sqf": s.DifficultyPresets,
}
for name, content := range files {
path := filepath.Join(userconfigDir, name)
if err := os.WriteFile(path, []byte(content), 0644); err != nil {
return fmt.Errorf("write %s: %w", name, err)
}
}
return nil
}

View File

@@ -0,0 +1,66 @@
package services
import (
"encoding/json"
"os"
"path/filepath"
"sync"
"time"
"arma3-web-server/internal/models"
)
type SettingsManager struct {
path string
mu sync.Mutex
}
func NewSettingsManager(dataDir string) *SettingsManager {
return &SettingsManager{
path: filepath.Join(dataDir, "settings.json"),
}
}
func (sm *SettingsManager) Load() (*models.ServerSettings, error) {
sm.mu.Lock()
defer sm.mu.Unlock()
data, err := os.ReadFile(sm.path)
if err != nil {
if os.IsNotExist(err) {
return sm.defaults(), nil
}
return nil, err
}
var s models.ServerSettings
if err := json.Unmarshal(data, &s); err != nil {
return nil, err
}
return &s, nil
}
func (sm *SettingsManager) Save(s *models.ServerSettings) error {
sm.mu.Lock()
defer sm.mu.Unlock()
s.UpdatedAt = time.Now().UTC()
data, err := json.MarshalIndent(s, "", " ")
if err != nil {
return err
}
return os.WriteFile(sm.path, data, 0644)
}
func (sm *SettingsManager) defaults() *models.ServerSettings {
return &models.ServerSettings{
IPPort: "0.0.0.0:2302",
ServerParameters: "-server -world=empty -loadMissionToMemory -noPause",
SteamBranch: "stable",
SteamUser: "anonymous",
Platform: "linux",
ActiveConfig: "",
ActiveModlist: "",
UpdatedAt: time.Now().UTC(),
}
}

View File

@@ -0,0 +1,142 @@
package services
import (
"context"
"fmt"
"os"
"os/exec"
"path/filepath"
"sync"
"time"
)
func CheckWorkshopMod(serverfileDir, modID string) bool {
if modID == "" {
return false
}
p := filepath.Join(serverfileDir, "steamapps", "workshop", "content", "107410", modID)
fi, err := os.Stat(p)
return err == nil && fi.IsDir()
}
const arma3AppID = "233780"
type SteamCmdManager struct {
serverfileDir string
streamer *LogStreamer
mu sync.Mutex
cancel context.CancelFunc
running bool
}
func NewSteamCmdManager(serverfileDir string, streamer *LogStreamer) *SteamCmdManager {
return &SteamCmdManager{
serverfileDir: serverfileDir,
streamer: streamer,
}
}
func (s *SteamCmdManager) IsRunning() bool {
s.mu.Lock()
defer s.mu.Unlock()
return s.running
}
func (s *SteamCmdManager) UpdateGame(branch, user string) error {
s.mu.Lock()
if s.running {
s.mu.Unlock()
return fmt.Errorf("steamcmd already running")
}
s.mu.Unlock()
args := []string{
"+force_install_dir", s.serverfileDir,
"+login", user,
"+app_update", arma3AppID,
}
if branch != "" && branch != "stable" {
args = append(args, "-beta", branch)
}
args = append(args, "validate", "+quit")
return s.run("Game update", args)
}
func (s *SteamCmdManager) DownloadMod(modID string) error {
return s.DownloadMods([]string{modID})
}
func (s *SteamCmdManager) DownloadMods(modIDs []string) error {
s.mu.Lock()
if s.running {
s.mu.Unlock()
return fmt.Errorf("steamcmd already running")
}
s.mu.Unlock()
if len(modIDs) == 0 {
return fmt.Errorf("no mod ids provided")
}
args := []string{
"+force_install_dir", s.serverfileDir,
"+login", "anonymous",
}
for _, id := range modIDs {
args = append(args, "+workshop_download_item", "107410", id)
}
args = append(args, "+quit")
label := fmt.Sprintf("Download %d mod(s)", len(modIDs))
return s.run(label, args)
}
const steamcmdTimeout = 10 * time.Minute
func (s *SteamCmdManager) run(label string, args []string) error {
ctx, cancel := context.WithTimeout(context.Background(), steamcmdTimeout)
s.streamer.Broadcast("steamcmd", "[STEAMCMD] "+label+" starting...")
cmd := exec.CommandContext(ctx, "steamcmd", args...)
stdout, err := cmd.StdoutPipe()
if err != nil {
cancel()
return fmt.Errorf("stdout pipe: %w", err)
}
stderr, err := cmd.StderrPipe()
if err != nil {
cancel()
return fmt.Errorf("stderr pipe: %w", err)
}
if err := cmd.Start(); err != nil {
cancel()
return fmt.Errorf("start steamcmd: %w", err)
}
s.mu.Lock()
s.running = true
s.cancel = cancel
s.mu.Unlock()
go s.streamer.Stream("steamcmd", stdout, "")
go s.streamer.Stream("steamcmd", stderr, "")
go func() {
err := cmd.Wait()
s.mu.Lock()
s.running = false
s.cancel = nil
s.mu.Unlock()
if err == nil {
s.streamer.Broadcast("steamcmd", "[STEAMCMD] SUCCESS: "+label+" finished")
} else {
s.streamer.Broadcast("steamcmd", "[STEAMCMD] ERROR: "+label+" failed: "+err.Error())
}
}()
return nil
}