aboutsummaryrefslogtreecommitdiff
path: root/internal/admin/api_players.go
blob: 2d0c09b4669f9c0962ed23e38be1bd3c96fbd735 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
package admin

import (
	"net/http"
	"os"
	"path/filepath"
	"strings"

	"gopkg.in/yaml.v3"

	"thehouseoficarus/internal/player"
)

func (s *AdminServer) handlePlayers(w http.ResponseWriter, r *http.Request) {
	if r.Method != http.MethodGet {
		http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
		return
	}

	nameFilter := r.URL.Query().Get("name")

	if nameFilter != "" {
		name, err := s.accountStore.FindCharacter(nameFilter)
		if err != nil {
			writeJSON(w, map[string]any{"error": "character not found: " + nameFilter})
			return
		}
		charPath := s.accountStore.CharPath(name)
		data, err := os.ReadFile(charPath)
		if err != nil {
			writeJSON(w, map[string]any{"error": "read error: " + err.Error()})
			return
		}
		var p player.Player
		if err := yaml.Unmarshal(data, &p); err != nil {
			writeJSON(w, map[string]any{"error": "parse error: " + err.Error()})
			return
		}
		writeJSON(w, p)
		return
	}

	charsDir := filepath.Join(s.dataDir, "players", "characters")
	entries, err := os.ReadDir(charsDir)
	if err != nil {
		writeJSON(w, map[string]any{"error": err.Error()})
		return
	}

	type playerSummary struct {
		Name  string `json:"name"`
		Level int    `json:"level"`
		Room  int    `json:"room"`
	}

	var players []playerSummary
	for _, e := range entries {
		if e.IsDir() || filepath.Ext(e.Name()) != ".yaml" {
			continue
		}
		rawName := strings.TrimSuffix(e.Name(), ".yaml")
		data, err := os.ReadFile(filepath.Join(charsDir, e.Name()))
		if err != nil {
			continue
		}
		var p player.Player
		if err := yaml.Unmarshal(data, &p); err != nil {
			continue
		}
		players = append(players, playerSummary{
			Name:  rawName,
			Level: p.CombatLevel(),
			Room:  p.RoomID,
		})
	}
	writeJSON(w, players)
}