aorecomp

Anarchy Online classic in the browser

git clone https://aorecomp.ubeagle.com/code/aorecomp.git


server/admin_pages.go (14975B)


      1 package main
      2 
      3 import (
      4 	"ao/server/gamedata"
      5 	"context"
      6 	"database/sql"
      7 	"encoding/csv"
      8 	"encoding/json"
      9 	"fmt"
     10 	"html"
     11 	"net/http"
     12 	"os"
     13 	"strings"
     14 	"time"
     15 )
     16 
     17 func (server *server) adminPageStart(w http.ResponseWriter, title, section string) {
     18 	w.Header().Set("Content-Type", "text/html; charset=utf-8")
     19 	fmt.Fprintf(w, `<!doctype html><html lang='en'><head><meta charset='utf-8'><meta name='viewport' content='width=device-width,initial-scale=1'><base href='%s'><title>%s - AO Admin</title><style>
     20  *{box-sizing:border-box}body{margin:0;background:#f4f6f8;color:#182634;font:15px system-ui,sans-serif}a{color:#175d8d;text-underline-offset:3px}header{background:#142c3e;color:white;padding:12px 24px;display:flex;align-items:center;gap:24px;flex-wrap:wrap}header strong{font-size:18px}nav{display:flex;gap:6px;flex-wrap:wrap}nav a{color:#d7e4ed;text-decoration:none;padding:10px 14px;border-radius:6px}nav a[aria-current=page],nav a:hover{background:#2b4d65;color:white}header form{margin-left:auto}main{padding:24px;max-width:1600px;margin:auto;overflow-x:auto}h1{font-size:26px;margin:0 0 20px}h2{font-size:19px;margin-top:26px}section,.cards>div{background:white;border:1px solid #d9e1e7;border-radius:8px;padding:20px;margin-bottom:20px}.cards{display:grid;grid-template-columns:repeat(auto-fit,minmax(150px,1fr));gap:12px}.cards strong{display:block;font-size:28px;margin-top:8px}label{display:inline-flex;gap:8px;align-items:center;flex-wrap:wrap;margin:5px 10px 5px 0}input,select,textarea,button{font:inherit;border:1px solid #a7b8c5;border-radius:5px;padding:10px;max-width:100%%}input[type=checkbox]{width:20px;height:20px}button{background:#175d8d;color:white;border-color:#175d8d;cursor:pointer;min-height:44px}button:disabled{opacity:.5;cursor:default}input:focus-visible,select:focus-visible,textarea:focus-visible,button:focus-visible,a:focus-visible{outline:3px solid #e0a22a;outline-offset:2px}textarea{display:block;width:100%%;font:14px ui-monospace,monospace;line-height:1.5;background:white}table{border-collapse:collapse;background:white;width:100%%;margin:16px 0}th,td{text-align:left;padding:10px 12px;border-bottom:1px solid #dce3e9;vertical-align:top}th{background:#e7edf2;position:sticky;top:0}.login{max-width:430px;margin:8vh auto}.login label{display:flex;align-items:stretch;flex-direction:column;margin:16px 0}.login input{width:100%%}.muted{color:#526777}.error{color:#a02121;white-space:pre-wrap}pre{white-space:pre-wrap;overflow-wrap:anywhere}canvas[data-map-canvas]{width:100%%;height:calc(100dvh - 310px);min-height:320px;display:block;touch-action:none;border-radius:8px}body:has(.map-page){height:100dvh;display:flex;flex-direction:column}body:has(.map-page) header{flex-shrink:0}body:has(.map-page) main{flex:1;min-height:0;margin:0;width:100%%;max-width:none;display:flex;flex-direction:column}.map-page,.map-page [data-world-map]{flex:1;min-height:0;display:flex;flex-direction:column}.map-page h1{font-size:22px;margin:0}.map-page [hidden]{display:none}.map-page form{margin-bottom:8px}.map-page p{margin:6px 0}.map-page canvas{flex:1;min-height:200px;height:0}details{margin:16px 0}.item-icon{display:inline-block;width:32px;height:32px;object-fit:contain;vertical-align:middle;margin-right:8px;border-radius:3px;background:#e7edf2}summary{cursor:pointer;padding:10px 0}@media(max-width:600px){header{padding:12px;gap:10px}nav a{padding:10px}main{padding:14px}header form{margin-left:0}th,td{padding:8px}canvas[data-map-canvas]{height:60dvh}}
     21  </style></head><body>`, html.EscapeString(server.baseURL), html.EscapeString(title))
     22 	if section != "" {
     23 		fmt.Fprint(w, "<header><strong>AO Admin</strong><nav aria-label='Main navigation'>")
     24 		for _, item := range []struct{ name, path string }{{"General", "admin"}, {"Map", "admin/map"}, {"Players", "admin/players"}, {"IP bans", "admin/ip-bans"}, {"Items", "admin/items"}, {"SQL", "admin/sql"}, {"Admins", "admin/admins"}} {
     25 			current := ""
     26 			if item.name == section {
     27 				current = " aria-current='page'"
     28 			}
     29 			fmt.Fprintf(w, "<a href='%s'%s>%s</a>", item.path, current, item.name)
     30 		}
     31 		fmt.Fprint(w, "</nav><form method='post' action='admin/logout'><button>Log out</button></form></header>")
     32 	}
     33 	fmt.Fprint(w, "<main>")
     34 }
     35 
     36 func (server *server) controlPage(w http.ResponseWriter, r *http.Request) {
     37 	var seconds, weather, items int
     38 	counts := &zoneAdminCounts{}
     39 	if server.world == nil {
     40 		seconds, weather, items = int(currentGameSeconds(server.gameSeconds, server.clockStarted)), server.weather, len(server.items)
     41 		counts.execute(server)
     42 	} else {
     43 		snapshot, err := server.world.snapshot()
     44 		if err != nil {
     45 			http.Error(w, err.Error(), http.StatusInternalServerError)
     46 			return
     47 		}
     48 		seconds, weather = int(snapshot.seconds), snapshot.weather
     49 		for _, owner := range snapshot.zones {
     50 			if err := owner.observe(counts); err != nil {
     51 				http.Error(w, err.Error(), http.StatusInternalServerError)
     52 				return
     53 			}
     54 		}
     55 		// SQLite also contains unassigned items with no simulation owner.
     56 		err = server.db.QueryRow("SELECT COUNT(*) FROM items").Scan(&items)
     57 		if err != nil {
     58 			http.Error(w, err.Error(), http.StatusInternalServerError)
     59 			return
     60 		}
     61 	}
     62 
     63 	var size int64
     64 	for _, path := range []string{"data/world.sqlite", "data/world.sqlite-wal"} {
     65 		if info, err := os.Stat(path); err == nil {
     66 			size += info.Size()
     67 		}
     68 	}
     69 	server.adminPageStart(w, "General", "General")
     70 	fmt.Fprint(w, "<h1>General</h1><div class='cards'>")
     71 	for _, stat := range []struct {
     72 		label string
     73 		value any
     74 	}{{"Players", counts.players}, {"Connected", counts.connected}, {"Item instances", items}, {"NPCs", counts.npcs}, {"Database + WAL", fmt.Sprintf("%.1f MB", float64(size)/1048576)}} {
     75 		fmt.Fprintf(w, "<div>%s<strong>%v</strong></div>", stat.label, stat.value)
     76 	}
     77 	fmt.Fprint(w, "<div>Database queries / second<strong id='query-rate'>-</strong></div></div><section><h2>Game time</h2>")
     78 	fmt.Fprintf(w, "<p>Game time: %02d:%02d</p><form method='post' action='admin/time'><label>Hour (0-26)<input type='number' name='hour' min='0' max='26' value='%d' required></label><label>Minute<input type='number' name='minute' min='0' max='59' value='%d' required></label><button>Set time</button></form></section>", seconds/3600, seconds/60%60, seconds/3600, seconds/60%60)
     79 	fmt.Fprint(w, "<section><h2>Weather</h2><form method='post' action='admin/weather'><label>Conditions<select name='weather' aria-label='Conditions' required>")
     80 	if weather == 0 {
     81 		fmt.Fprint(w, "<option value='' disabled selected>Choose weather</option>")
     82 	}
     83 	for index, name := range []string{"Clear", "Rain", "Clouds", "Fog and clouds"} {
     84 		value := index + 1
     85 		selected := ""
     86 		if value == weather {
     87 			selected = " selected"
     88 		}
     89 		fmt.Fprintf(w, "<option value='%d'%s>%s</option>", value, selected, name)
     90 	}
     91 	fmt.Fprint(w, "</select></label><button>Set weather</button></form><small class='muted'>5 minutes, then automatic weather resumes.</small></section><script>let sample;async function stats(){try{if(!document.hidden){const response=await fetch('admin/stats');if(!response.ok)throw new Error();const next=await response.json();if(sample)document.querySelector('#query-rate').textContent=((next.queries-sample.queries)/(next.time-sample.time)).toFixed(1);sample=next;}}catch{document.querySelector('#query-rate').textContent='Unavailable';}setTimeout(stats,2000)}stats();</script></main></body></html>")
     92 
     93 }
     94 
     95 func (server *server) usersPage(w http.ResponseWriter, r *http.Request) {
     96 	players, err := server.adminPlayers()
     97 	if err != nil {
     98 		http.Error(w, err.Error(), http.StatusInternalServerError)
     99 		return
    100 	}
    101 
    102 	// SQLite owns the player roster. A zone transfer can fall between live samples.
    103 	live := make(map[uint32]mapPlayer, len(players))
    104 	for _, player := range players {
    105 		live[player.ID] = player
    106 	}
    107 	rows, err := server.db.Query(`SELECT id, name, title, playfield, last_ip, connected_seconds, last_connected_at
    108 		FROM characters JOIN players USING(id) ORDER BY id`)
    109 	if err != nil {
    110 		http.Error(w, err.Error(), http.StatusInternalServerError)
    111 		return
    112 	}
    113 	defer rows.Close()
    114 	var entries []adminTableRow
    115 	for rows.Next() {
    116 		var player mapPlayer
    117 		var address string
    118 		var seconds int64
    119 		var lastConnected time.Time
    120 		if err := rows.Scan(&player.ID, &player.Name, &player.Title, &player.Playfield, &address, &seconds, &lastConnected); err != nil {
    121 			http.Error(w, err.Error(), http.StatusInternalServerError)
    122 			return
    123 		}
    124 		if sample, ok := live[player.ID]; ok {
    125 			player = sample
    126 		}
    127 		status := "Offline"
    128 		if address == "" {
    129 			address = "-"
    130 		}
    131 		if player.Connected {
    132 			status = "Connected"
    133 		}
    134 		zone := fmt.Sprintf("%s (%d)", gamedata.Playfields[player.Playfield].Name, player.Playfield)
    135 		connectedTime := (time.Duration(seconds) * time.Second).String()
    136 		connectedAt := "-"
    137 		if !lastConnected.IsZero() {
    138 			connectedAt = lastConnected.UTC().Format("2006-01-02 15:04:05 MST")
    139 		}
    140 		entries = append(entries, adminTableRow{
    141 			values: []string{fmt.Sprint(player.ID), adminName(player.Name), player.Title, status, address, connectedAt, fmt.Sprint(seconds), zone},
    142 			markup: fmt.Sprintf("<tr><td>%d</td><td><a href='admin/players/%d'>%s</a></td><td>%s</td><td>%s</td><td>%s</td><td>%s</td><td>%s</td><td>%s</td></tr>", player.ID, player.ID, html.EscapeString(adminName(player.Name)), html.EscapeString(player.Title), status, html.EscapeString(address), connectedAt, connectedTime, html.EscapeString(zone)),
    143 		})
    144 	}
    145 	if err := rows.Err(); err != nil {
    146 		http.Error(w, err.Error(), http.StatusInternalServerError)
    147 		return
    148 	}
    149 	server.adminPageStart(w, "Players", "Players")
    150 	fmt.Fprint(w, "<h1>Players</h1>")
    151 	adminFilter(w, r)
    152 	adminTable(w, r, []string{"ID", "Name", "Title", "Status", "Last IP address", "Last connected", "Connected time", "Zone"}, entries)
    153 	fmt.Fprint(w, "</main></body></html>")
    154 }
    155 
    156 func (server *server) mapPage(w http.ResponseWriter, r *http.Request) {
    157 	server.adminPageStart(w, "Map", "Map")
    158 	fmt.Fprint(w, "<div class='map-page'><h1>Map</h1>")
    159 	controlMap(w, 0)
    160 	fmt.Fprint(w, "</div></main></body></html>")
    161 }
    162 
    163 func (server *server) sqlPage(w http.ResponseWriter, r *http.Request) {
    164 	query := "SELECT name, type, sql FROM sqlite_schema ORDER BY type, name;"
    165 	var columns []string
    166 	var values [][]string
    167 	var queryError error
    168 	truncated := false
    169 	if r.Method == http.MethodPost {
    170 		r.Body = http.MaxBytesReader(w, r.Body, 65536)
    171 		if err := r.ParseForm(); err != nil {
    172 			http.Error(w, "Query is too large", 400)
    173 			return
    174 		}
    175 		query = r.PostForm.Get("query")
    176 		// Bound query duration and retained output, including queries with RETURNING.
    177 		ctx, cancel := context.WithTimeout(r.Context(), 5*time.Second)
    178 		defer cancel()
    179 		// Isolate console transactions and PRAGMAs from the live game's connection.
    180 		db := sql.OpenDB(databaseConnector{&server.databaseQueries})
    181 		defer db.Close()
    182 		db.SetMaxOpenConns(1)
    183 		statements, err := sqlStatements(query)
    184 		queryError = err
    185 		for _, statement := range statements {
    186 			rows, err := db.QueryContext(ctx, statement)
    187 			queryError = err
    188 			if err != nil {
    189 				break
    190 			}
    191 			names, err := rows.Columns()
    192 			queryError = err
    193 			// Keep the most recent result set when trailing comments or writes follow it.
    194 			if len(names) > 0 {
    195 				columns = names
    196 				values = nil
    197 				truncated = false
    198 			}
    199 			bytes := 0
    200 			for queryError == nil && rows.Next() {
    201 				row := make([]any, len(names))
    202 				destinations := make([]any, len(names))
    203 				for index := range row {
    204 					destinations[index] = &row[index]
    205 				}
    206 				if queryError = rows.Scan(destinations...); queryError != nil {
    207 					break
    208 				}
    209 				if len(values) >= 1000 || bytes >= 2*1024*1024 {
    210 					truncated = true
    211 					continue
    212 				}
    213 				cells := make([]string, len(row))
    214 				for index, value := range row {
    215 					switch value := value.(type) {
    216 					case nil:
    217 						cells[index] = "NULL"
    218 					case []byte:
    219 						cells[index] = fmt.Sprintf("%x", value)
    220 					default:
    221 						cells[index] = fmt.Sprint(value)
    222 					}
    223 					bytes += len(cells[index])
    224 				}
    225 				values = append(values, cells)
    226 			}
    227 			if err := rows.Err(); queryError == nil {
    228 				queryError = err
    229 			}
    230 			rows.Close()
    231 			if queryError != nil {
    232 				break
    233 			}
    234 		}
    235 	}
    236 	server.adminPageStart(w, "SQL", "SQL")
    237 	fmt.Fprint(w, `<h1>SQL</h1><p class='muted'>Direct database access. Live game state may overwrite edits; restart to reload it.</p><form method='post' action='admin/sql'><label>Starter query<select id='preset'><option value=''>Choose...</option>`)
    238 	for _, preset := range []struct{ name, query string }{{"Tables", "SELECT name, type, sql FROM sqlite_schema ORDER BY type, name;"}, {"Players", "SELECT characters.* FROM characters JOIN players USING(id) ORDER BY id;"}, {"Items", "SELECT * FROM items ORDER BY id;"}, {"NPCs", "SELECT * FROM npcs ORDER BY id;"}, {"Administrators", "SELECT id, username FROM admin_users ORDER BY id;"}} {
    239 		fmt.Fprintf(w, "<option value='%s'>%s</option>", html.EscapeString(preset.query), preset.name)
    240 	}
    241 	fmt.Fprintf(w, "</select></label><label for='query'>Query</label><textarea id='query' name='query' rows='8' required spellcheck='false'>%s</textarea><p><button>Run query</button></p></form>", html.EscapeString(query))
    242 	if queryError != nil {
    243 		fmt.Fprintf(w, "<p role='alert' class='error'>%s</p>", html.EscapeString(queryError.Error()))
    244 	} else if r.Method == http.MethodPost {
    245 		fmt.Fprintf(w, "<p role='status'>Query completed. %d rows displayed%s.</p>", len(values), map[bool]string{true: " (output limited)", false: ""}[truncated])
    246 		if len(columns) > 0 {
    247 			fmt.Fprint(w, "<label>Output<select id='format' aria-label='Output'><option value='table'>Table</option><option value='csv'>CSV</option></select></label><div id='result-table'><table><thead><tr>")
    248 			for _, column := range columns {
    249 				fmt.Fprintf(w, "<th>%s</th>", html.EscapeString(column))
    250 			}
    251 			fmt.Fprint(w, "</tr></thead><tbody>")
    252 			for _, row := range values {
    253 				fmt.Fprint(w, "<tr>")
    254 				for _, cell := range row {
    255 					fmt.Fprintf(w, "<td>%s</td>", html.EscapeString(cell))
    256 				}
    257 				fmt.Fprint(w, "</tr>")
    258 			}
    259 			fmt.Fprint(w, "</tbody></table></div>")
    260 			var output strings.Builder
    261 			writer := csv.NewWriter(&output)
    262 			writer.Write(columns)
    263 			writer.WriteAll(values)
    264 			fmt.Fprintf(w, "<div id='result-csv' hidden><pre aria-label='CSV output'>%s</pre></div>", html.EscapeString(output.String()))
    265 		}
    266 	}
    267 	fmt.Fprint(w, `<script>document.querySelector('#preset').addEventListener('change',event=>{if(event.target.value)document.querySelector('#query').value=event.target.value});document.querySelector('#format')?.addEventListener('change',event=>{document.querySelector('#result-table').hidden=event.target.value!=='table';document.querySelector('#result-csv').hidden=event.target.value!=='csv'});</script></main></body></html>`)
    268 }
    269 
    270 func (server *server) adminStats(w http.ResponseWriter, r *http.Request) {
    271 	w.Header().Set("Content-Type", "application/json")
    272 	json.NewEncoder(w).Encode(map[string]any{"queries": server.databaseQueries.Load(), "time": float64(time.Now().UnixMilli()) / 1000})
    273 }