xonecas.ioDon't click! Sean Caetano Martin Sign in
tiny-adventure / internal / server / run.go 158 lines4.2 kB Raw
1package server
2
3import (
4	"bytes"
5	"errors"
6	"fmt"
7	"html"
8	"net/http"
9	"os"
10	"path/filepath"
11	"strings"
12
13	"tinyadventure/internal/model"
14)
15
16var errNoRun = errors.New("no finished run with that id")
17
18func (g *game) run() model.Run {
19	s := g.snapshot()
20	steps := s.Campaign.Main.Steps
21	out := model.Run{
22		Game: s.Game, Seed: s.Seed, Phase: s.Phase, Mission: s.Campaign.Main.Name, Day: s.Clock.Day,
23		Keys: len(s.Party.Keys), Gold: s.Party.Gold, Summary: s.Summary,
24	}
25	for _, st := range steps {
26		if st.Slots.Item != "" {
27			out.KeysOf++
28		}
29	}
30	if enc, ok := g.encs[steps[len(steps)-1].POI]; ok && len(enc.Enemies) > 0 {
31		out.Boss = enc.Enemies[0].Name
32	}
33	for _, u := range s.Party.Units {
34		out.Party = append(out.Party, model.RunHero{Name: u.Name, Race: u.Race, Class: u.Class, Level: u.Level})
35	}
36	return out
37}
38
39func (s *Server) findRun(id string) (model.Run, error) {
40	if !gameID.MatchString(id) {
41		return model.Run{}, errNoRun
42	}
43	var g *game
44	for _, st := range s.seats {
45		if st.g.state.Game == id {
46			g = st.g
47		}
48	}
49	if g == nil {
50		loaded, err := s.store.load(id)
51		if err != nil {
52			return model.Run{}, errNoRun
53		}
54		g = loaded
55	}
56	if !g.finished() {
57		return model.Run{}, errNoRun
58	}
59	return g.run(), nil
60}
61
62func (s *Server) lookup(r *http.Request) (model.Run, int, error) {
63	if !s.limits.allow(clientIP(r), "read") {
64		return model.Run{}, http.StatusTooManyRequests, errors.New("slow down")
65	}
66	s.mu.Lock()
67	defer s.mu.Unlock()
68	run, err := s.findRun(r.PathValue("id"))
69	if err != nil {
70		return run, http.StatusNotFound, err
71	}
72	return run, http.StatusOK, nil
73}
74
75func (s *Server) handleRun(w http.ResponseWriter, r *http.Request) {
76	run, code, err := s.lookup(r)
77	if err != nil {
78		fail(w, code, err)
79		return
80	}
81	reply(w, code, run)
82}
83
84func headline(run model.Run) (string, string) {
85	names := make([]string, len(run.Party))
86	for i, h := range run.Party {
87		names[i] = h.Name
88	}
89	who := strings.Join(names[:len(names)-1], ", ") + " and " + names[len(names)-1]
90	if run.Phase == "victory" {
91		return fmt.Sprintf("Victory on day %d", run.Day), fmt.Sprintf("%s slew %s. %d battles, %d foes, %d keys. Seed %d.", who, run.Boss, run.Summary.Battles, run.Summary.Kills, run.Keys, run.Seed)
92	}
93	return fmt.Sprintf("Fell on day %d", run.Day), fmt.Sprintf("%s fell on the road to %s. %d battles, %d foes, %d of %d keys. Seed %d.", who, run.Boss, run.Summary.Battles, run.Summary.Kills, run.Keys, run.KeysOf, run.Seed)
94}
95
96func (s *Server) handleShare(w http.ResponseWriter, r *http.Request) {
97	page, err := os.ReadFile(filepath.Join(s.web, "index.html"))
98	if err != nil {
99		fail(w, http.StatusInternalServerError, err)
100		return
101	}
102	if run, _, err := s.lookup(r); err == nil {
103		title, desc := headline(run)
104		scheme := "http"
105		if r.TLS != nil || r.Header.Get("X-Forwarded-Proto") == "https" {
106			scheme = "https"
107		}
108		img := fmt.Sprintf("%s://%s/r/%s/card.png", scheme, r.Host, run.Game)
109		t, d := html.EscapeString(title+" ยท Tiny Adventure"), html.EscapeString(desc)
110		meta := fmt.Sprintf(`<title>%s</title>
111<meta name="description" content="%s">
112<meta property="og:title" content="%s">
113<meta property="og:description" content="%s">
114<meta property="og:image" content="%s">
115<meta property="og:image:width" content="1200">
116<meta property="og:image:height" content="630">
117<meta name="twitter:card" content="summary_large_image">`, t, d, t, d, img)
118		if i := bytes.Index(page, []byte("<title>")); i >= 0 {
119			if n := bytes.IndexByte(page[i:], '\n'); n >= 0 {
120				page = append(page[:i:i], append([]byte(meta), page[i+n:]...)...)
121			}
122		}
123	}
124	w.Header().Set("Content-Type", "text/html; charset=utf-8")
125	w.Header().Set("Cache-Control", "no-cache")
126	w.Write(page)
127}
128
129func (s *Server) handleCard(w http.ResponseWriter, r *http.Request) {
130	run, code, err := s.lookup(r)
131	if err != nil {
132		fail(w, code, err)
133		return
134	}
135	cached := ""
136	if s.store.dir != "" {
137		cached = s.store.path("cards", run.Game+".png")
138		if b, err := os.ReadFile(cached); err == nil {
139			writePNG(w, b)
140			return
141		}
142	}
143	b, err := card(run, r.Host)
144	if err != nil {
145		fail(w, http.StatusInternalServerError, err)
146		return
147	}
148	if cached != "" {
149		os.WriteFile(cached, b, 0o644)
150	}
151	writePNG(w, b)
152}
153
154func writePNG(w http.ResponseWriter, b []byte) {
155	w.Header().Set("Content-Type", "image/png")
156	w.Header().Set("Cache-Control", "public, max-age=86400")
157	w.Write(b)
158}