gameStatusUpdate/server/router.go
2024-11-05 05:29:32 -08:00

58 lines
1.3 KiB
Go

package main
import (
"encoding/json"
"net/http"
"strings"
)
// InitRoutes initializes all HTTP routes for the plugin
func InitRoutes(p *Plugin) http.Handler {
mux := http.NewServeMux()
mux.HandleFunc("/processlist", p.handleProcessList)
return mux
}
// StartHTTPServer starts the HTTP server on a specific port
func StartHTTPServer(p *Plugin) {
httpServer := &http.Server{
Addr: "0.0.0.0:8780",
Handler: p.apiRouter,
}
if err := httpServer.ListenAndServe(); err != nil && err != http.ErrServerClosed {
p.API.LogError("Failed to start HTTP server", "error", err.Error())
}
}
// handleProcessList handles the incoming process list from the desktop app
func (p *Plugin) handleProcessList(w http.ResponseWriter, r *http.Request) {
var requestData struct {
ProcessList string `json:"processList"`
UserID string `json:"userID"`
}
if err := json.NewDecoder(r.Body).Decode(&requestData); err != nil {
http.Error(w, "Invalid request payload", http.StatusBadRequest)
return
}
game := ""
for knownGame := range knownGames {
if strings.Contains(requestData.ProcessList, knownGame) {
game = knownGame
break
}
}
if game != "" {
err := p.SetUserGameStatus(requestData.UserID, game)
if err != nil {
http.Error(w, "Failed to update user status", http.StatusInternalServerError)
return
}
}
w.WriteHeader(http.StatusOK)
}