oficina / base Public

Clone
git clone https://amadan.net/oficina/base

Plain git — no account needed to clone.

Download

Download this file

1package web
2
3import (
4 "encoding/json"
5 "errors"
6 "io"
7 "net/http"
8
9 "github.com/go-chi/chi/v5"
10
11 "amadan.net/oficina/base/internal/catalog"
12 "amadan.net/oficina/base/internal/install"
13 "amadan.net/oficina/base/internal/store"
14)
15
16// Store and People for the native app (docs/api/base-native-v1.md "Store"
17// and "People"): what the pages of the same names show, from the same
18// builders, behind the same member gate and owner checks.
19
20type apiStoreRow struct {
21 ID string `json:"id"`
22 Name string `json:"name"`
23 Summary string `json:"summary"`
24 Tint string `json:"tint"`
25 IconSVG string `json:"icon_svg"`
26 // State is "", "installing", "installed" or "failed"; Error is a
27 // failed install's reason, and may be "".
28 State string `json:"state"`
29 Error string `json:"error"`
30}
31
32type apiStore struct {
33 Owner bool `json:"owner"`
34 Rows []apiStoreRow `json:"rows"`
35}
36
37func storeJSON(c storeContent) apiStore {
38 out := apiStore{Owner: c.IsOwner, Rows: []apiStoreRow{}}
39 for _, r := range c.Rows {
40 out.Rows = append(out.Rows, apiStoreRow{ID: r.ID, Name: r.Name, Summary: r.Summary, Tint: r.Tint, IconSVG: r.Icon, State: r.State, Error: r.Error})
41 }
42 return out
43}
44
45type apiPerson struct {
46 ID string `json:"id"`
47 Initial string `json:"initial"`
48 // Name is "" for someone who has given none; show Email then.
49 Name string `json:"name"`
50 Email string `json:"email"`
51 // Role is "owner", "member" or "invited" (not yet signed in).
52 Role string `json:"role"`
53}
54
55type apiPeople struct {
56 Owner bool `json:"owner"`
57 People []apiPerson `json:"people"`
58}
59
60func personJSON(p personRow) apiPerson {
61 return apiPerson{ID: p.ID, Initial: p.Initial, Name: p.Name, Email: p.Email, Role: p.Role}
62}
63
64// apiStoreRead is GET /api/v1/store.
65func (a *app) apiStoreRead(w http.ResponseWriter, r *http.Request) {
66 me, _ := CurrentMember(r)
67 c, err := a.storeContent(r.Context(), me)
68 if err != nil {
69 a.logger.Error("api store", "err", err)
70 writeJSON(w, http.StatusServiceUnavailable, apiError{Code: "unavailable"})
71 return
72 }
73 writeJSON(w, http.StatusOK, storeJSON(c))
74}
75
76// apiPeopleRead is GET /api/v1/people.
77func (a *app) apiPeopleRead(w http.ResponseWriter, r *http.Request) {
78 me, _ := CurrentMember(r)
79 c, err := a.peopleContent(r.Context(), me)
80 if err != nil {
81 a.logger.Error("api people", "err", err)
82 writeJSON(w, http.StatusServiceUnavailable, apiError{Code: "unavailable"})
83 return
84 }
85 out := apiPeople{Owner: c.IsOwner, People: []apiPerson{}}
86 for _, p := range c.People {
87 out.People = append(out.People, personJSON(p))
88 }
89 writeJSON(w, http.StatusOK, out)
90}
91
92// apiStoreAnswer is a Store write's answer: the store as it now stands.
93type apiStoreAnswer struct {
94 Store apiStore `json:"store"`
95}
96
97// apiOwner is the catalogue entry named in the URL when the member asking
98// is the owner. Otherwise it answers 403 owner_only or 404 unknown_app, in
99// that order, as the page's owner check does.
100func (a *app) apiOwner(w http.ResponseWriter, me store.Member, id string) (catalog.Entry, bool) {
101 if me.Role != "owner" {
102 writeJSON(w, http.StatusForbidden, apiError{Code: "owner_only"})
103 return catalog.Entry{}, false
104 }
105 e, ok := catalog.Get(id)
106 if !ok {
107 writeJSON(w, http.StatusNotFound, apiError{Code: "unknown_app"})
108 return catalog.Entry{}, false
109 }
110 return e, true
111}
112
113// apiStoreInstall is POST /api/v1/store/{app}/install. It answers 202 with
114// the app installing, and the app polls the store until it isn't. An app
115// already installing answers 202 and one installed 200, and neither starts
116// anything. Start returns an error only from before its claim (install.go),
117// so when it fails the store is read again: a row that now reads installing
118// was claimed by another request and is answered 202 as it stands, and
119// anything else, a failed row included (that failure is an earlier one),
120// is 503: this attempt never started.
121func (a *app) apiStoreInstall(w http.ResponseWriter, r *http.Request) {
122 me, _ := CurrentMember(r)
123 e, ok := a.apiOwner(w, me, chi.URLParam(r, "app"))
124 if !ok {
125 return
126 }
127 c, err := a.storeContent(r.Context(), me)
128 if err != nil {
129 a.logger.Error("api install", "app", e.ID, "err", err)
130 writeJSON(w, http.StatusServiceUnavailable, apiError{Code: "unavailable"})
131 return
132 }
133 switch row, _ := c.row(e.ID); row.State {
134 case "installing":
135 writeJSON(w, http.StatusAccepted, apiStoreAnswer{storeJSON(c)})
136 return
137 case "installed":
138 writeJSON(w, http.StatusOK, apiStoreAnswer{storeJSON(c)})
139 return
140 }
141 startErr := a.inst.Start(r.Context(), e.ID)
142 if startErr != nil {
143 a.logger.Error("api install", "app", e.ID, "err", startErr)
144 }
145 if c, err = a.storeContent(r.Context(), me); err != nil {
146 a.logger.Error("api install", "app", e.ID, "err", err)
147 writeJSON(w, http.StatusServiceUnavailable, apiError{Code: "unavailable"})
148 return
149 }
150 if row, _ := c.row(e.ID); startErr != nil && row.State != "installing" {
151 writeJSON(w, http.StatusServiceUnavailable, apiError{Code: "unavailable"})
152 return
153 }
154 writeJSON(w, http.StatusAccepted, apiStoreAnswer{storeJSON(c)})
155}
156
157// apiStoreUninstall is POST /api/v1/store/{app}/uninstall: 200 with the
158// store, also when it was uninstalled already, and 409 busy while it is
159// still installing.
160func (a *app) apiStoreUninstall(w http.ResponseWriter, r *http.Request) {
161 me, _ := CurrentMember(r)
162 e, ok := a.apiOwner(w, me, chi.URLParam(r, "app"))
163 if !ok {
164 return
165 }
166 switch err := a.inst.Uninstall(r.Context(), e.ID); {
167 case errors.Is(err, install.ErrBusy):
168 writeJSON(w, http.StatusConflict, apiError{Code: "busy"})
169 return
170 case errors.Is(err, store.ErrNoInstall):
171 // Already uninstalled.
172 case err != nil:
173 a.logger.Error("api uninstall", "app", e.ID, "err", err)
174 writeJSON(w, http.StatusServiceUnavailable, apiError{Code: "unavailable"})
175 return
176 }
177 c, err := a.storeContent(r.Context(), me)
178 if err != nil {
179 a.logger.Error("api uninstall", "app", e.ID, "err", err)
180 writeJSON(w, http.StatusServiceUnavailable, apiError{Code: "unavailable"})
181 return
182 }
183 writeJSON(w, http.StatusOK, apiStoreAnswer{storeJSON(c)})
184}
185
186// maxInviteBody bounds POST /api/v1/people's body, {"email": …}.
187const maxInviteBody = 4 << 10
188
189// apiPeopleInvite is POST /api/v1/people, {"email": …}: the People form's
190// invitation, as JSON. It answers 200 with the person, invited now or
191// already here.
192func (a *app) apiPeopleInvite(w http.ResponseWriter, r *http.Request) {
193 me, _ := CurrentMember(r)
194 if me.Role != "owner" {
195 writeJSON(w, http.StatusForbidden, apiError{Code: "owner_only"})
196 return
197 }
198 if !isJSONBody(r) {
199 writeJSON(w, http.StatusUnsupportedMediaType, apiError{Code: "json_only"})
200 return
201 }
202 raw, err := io.ReadAll(http.MaxBytesReader(w, r.Body, maxInviteBody))
203 if err != nil {
204 if mbe := (*http.MaxBytesError)(nil); errors.As(err, &mbe) {
205 writeJSON(w, http.StatusRequestEntityTooLarge, apiError{Code: "too_large"})
206 return
207 }
208 writeJSON(w, http.StatusBadRequest, apiError{Code: "bad_request"})
209 return
210 }
211 var in struct {
212 Email string `json:"email"`
213 }
214 if err := json.Unmarshal(raw, &in); err != nil {
215 writeJSON(w, http.StatusBadRequest, apiError{Code: "bad_request"})
216 return
217 }
218 m, res, err := a.invitePerson(r.Context(), in.Email)
219 switch {
220 case err != nil:
221 a.logger.Error("api invite", "err", err)
222 writeJSON(w, http.StatusServiceUnavailable, apiError{Code: "unavailable"})
223 case res == inviteBadEmail:
224 writeJSON(w, http.StatusUnprocessableEntity, apiError{Code: "bad_email"})
225 case res == inviteMailFailed:
226 writeJSON(w, http.StatusBadGateway, apiError{Code: "mail_failed"})
227 default:
228 writeJSON(w, http.StatusOK, struct {
229 Person apiPerson `json:"person"`
230 }{personJSON(personFor(m))})
231 }
232}
233