api.gno
4.47 Kb · 184 lines
1package hall
2
3import (
4 "strconv"
5 "strings"
6
7 "gno.land/p/nt/mux/v0"
8)
9
10// renderAPI answers api/<what> with JSON for the Cellar web client:
11// challenges, board, board-<season>, feed, seasons, player-<address>.
12func renderAPI(res *mux.ResponseWriter, req *mux.Request) {
13 what := req.GetVar("what")
14 switch {
15 case what == "challenges":
16 res.Write(challengesJSON())
17 case what == "board":
18 res.Write(boardJSON(0))
19 case strings.HasPrefix(what, "board-"):
20 n, err := strconv.Atoi(strings.TrimPrefix(what, "board-"))
21 if err != nil || n < 1 || n > len(seasons) {
22 res.Write(`{"error":"no such season"}`)
23 return
24 }
25 res.Write(boardJSON(n))
26 case what == "feed":
27 res.Write(feedJSON())
28 case what == "seasons":
29 res.Write(seasonsJSON())
30 case strings.HasPrefix(what, "player-"):
31 res.Write(playerJSON(strings.TrimPrefix(what, "player-")))
32 default:
33 res.Write(`{"error":"unknown endpoint"}`)
34 }
35}
36
37func challengesJSON() string {
38 var items []string
39 eachEntry(func(slug string, e *entry) {
40 first := ""
41 if len(e.solvers) > 0 {
42 first = e.solvers[0].String()
43 }
44 items = append(items, object(
45 "slug", quote(slug),
46 "title", quote(e.info.Title),
47 "difficulty", quote(e.info.Difficulty.String()),
48 "category", quote(e.info.Category),
49 "brief", quote(e.info.Brief),
50 "path", quote(e.path),
51 "official", strconv.FormatBool(e.official),
52 "status", quote(e.status.String()),
53 "solves", strconv.Itoa(len(e.solvers)),
54 "value", strconv.Itoa(e.value()),
55 "firstBloodBonus", strconv.Itoa(e.info.Difficulty.FirstBloodBonus()),
56 "firstBlood", quote(first),
57 "enlistedAt", strconv.FormatInt(e.enlistedAt, 10),
58 ))
59 })
60 return array(items)
61}
62
63func boardJSON(season int) string {
64 var items []string
65 for _, r := range standings(season) {
66 items = append(items, object(
67 "player", quote(r.Player.String()),
68 "name", quote(DisplayName(r.Player)),
69 "points", strconv.Itoa(r.Points),
70 "solves", strconv.Itoa(r.Solves),
71 ))
72 }
73 return array(items)
74}
75
76func feedJSON() string {
77 var items []string
78 for i := len(feed) - 1; i >= 0; i-- {
79 items = append(items, solveJSON(feed[i]))
80 }
81 return array(items)
82}
83
84func solveJSON(s Solve) string {
85 return object(
86 "player", quote(s.Player.String()),
87 "name", quote(DisplayName(s.Player)),
88 "slug", quote(s.Slug),
89 "height", strconv.FormatInt(s.Height, 10),
90 "season", strconv.Itoa(s.Season),
91 "firstBlood", strconv.FormatBool(s.FirstBlood),
92 "points", strconv.Itoa(solvePoints(s)),
93 )
94}
95
96func seasonsJSON() string {
97 var items []string
98 for _, s := range seasons {
99 var podium []string
100 for _, a := range s.Podium {
101 podium = append(podium, quote(a.String()))
102 }
103 items = append(items, object(
104 "number", strconv.Itoa(s.Number),
105 "name", quote(s.Name),
106 "openedAt", strconv.FormatInt(s.OpenedAt, 10),
107 "closedAt", strconv.FormatInt(s.ClosedAt, 10),
108 "claims", strconv.Itoa(s.Claims),
109 "podium", array(podium),
110 ))
111 }
112 return array(items)
113}
114
115func playerJSON(who string) string {
116 addr, ok := resolvePlayer(who)
117 if !ok {
118 return `{"error":"unknown player"}`
119 }
120 p, found := findProfile(addr)
121 if !found {
122 p = &profile{addr: addr}
123 }
124 all, n, _ := p.score(0)
125 season, _, _ := p.score(currentSeason().Number)
126 var solves, badges []string
127 for _, s := range p.solves {
128 solves = append(solves, solveJSON(s))
129 }
130 for _, tid := range p.badges {
131 badges = append(badges, object("id", quote(tid), "uri", quote(BadgeURI(tid))))
132 }
133 return object(
134 "player", quote(addr.String()),
135 "name", quote(DisplayName(addr)),
136 "handle", quote(p.handle),
137 "points", strconv.Itoa(all),
138 "seasonPoints", strconv.Itoa(season),
139 "flags", strconv.Itoa(n),
140 "solves", array(solves),
141 "badges", array(badges),
142 )
143}
144
145// object renders alternating keys and raw JSON values as a JSON object.
146func object(kv ...string) string {
147 var b strings.Builder
148 b.WriteByte('{')
149 for i := 0; i+1 < len(kv); i += 2 {
150 if i > 0 {
151 b.WriteByte(',')
152 }
153 b.WriteString(quote(kv[i]) + ":" + kv[i+1])
154 }
155 b.WriteByte('}')
156 return b.String()
157}
158
159func array(items []string) string { return "[" + strings.Join(items, ",") + "]" }
160
161// quote encodes s as a JSON string.
162func quote(s string) string {
163 const hex = "0123456789abcdef"
164 var b strings.Builder
165 b.WriteByte('"')
166 for i := 0; i < len(s); i++ {
167 c := s[i]
168 switch {
169 case c == '"' || c == '\\':
170 b.WriteByte('\\')
171 b.WriteByte(c)
172 case c == '\n':
173 b.WriteString(`\n`)
174 case c < 0x20:
175 b.WriteString(`\u00`)
176 b.WriteByte(hex[c>>4])
177 b.WriteByte(hex[c&0xf])
178 default:
179 b.WriteByte(c)
180 }
181 }
182 b.WriteByte('"')
183 return b.String()
184}