package web import ( "encoding/json" "errors" "io" "net/http" "github.com/go-chi/chi/v5" "amadan.net/oficina/base/internal/catalog" "amadan.net/oficina/base/internal/install" "amadan.net/oficina/base/internal/store" ) // Store and People for the native app (docs/api/base-native-v1.md "Store" // and "People"): what the pages of the same names show, from the same // builders, behind the same member gate and owner checks. type apiStoreRow struct { ID string `json:"id"` Name string `json:"name"` Summary string `json:"summary"` Tint string `json:"tint"` IconSVG string `json:"icon_svg"` // State is "", "installing", "installed" or "failed"; Error is a // failed install's reason, and may be "". State string `json:"state"` Error string `json:"error"` } type apiStore struct { Owner bool `json:"owner"` Rows []apiStoreRow `json:"rows"` } func storeJSON(c storeContent) apiStore { out := apiStore{Owner: c.IsOwner, Rows: []apiStoreRow{}} for _, r := range c.Rows { 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}) } return out } type apiPerson struct { ID string `json:"id"` Initial string `json:"initial"` // Name is "" for someone who has given none; show Email then. Name string `json:"name"` Email string `json:"email"` // Role is "owner", "member" or "invited" (not yet signed in). Role string `json:"role"` } type apiPeople struct { Owner bool `json:"owner"` People []apiPerson `json:"people"` } func personJSON(p personRow) apiPerson { return apiPerson{ID: p.ID, Initial: p.Initial, Name: p.Name, Email: p.Email, Role: p.Role} } // apiStoreRead is GET /api/v1/store. func (a *app) apiStoreRead(w http.ResponseWriter, r *http.Request) { me, _ := CurrentMember(r) c, err := a.storeContent(r.Context(), me) if err != nil { a.logger.Error("api store", "err", err) writeJSON(w, http.StatusServiceUnavailable, apiError{Code: "unavailable"}) return } writeJSON(w, http.StatusOK, storeJSON(c)) } // apiPeopleRead is GET /api/v1/people. func (a *app) apiPeopleRead(w http.ResponseWriter, r *http.Request) { me, _ := CurrentMember(r) c, err := a.peopleContent(r.Context(), me) if err != nil { a.logger.Error("api people", "err", err) writeJSON(w, http.StatusServiceUnavailable, apiError{Code: "unavailable"}) return } out := apiPeople{Owner: c.IsOwner, People: []apiPerson{}} for _, p := range c.People { out.People = append(out.People, personJSON(p)) } writeJSON(w, http.StatusOK, out) } // apiStoreAnswer is a Store write's answer: the store as it now stands. type apiStoreAnswer struct { Store apiStore `json:"store"` } // apiOwner is the catalogue entry named in the URL when the member asking // is the owner. Otherwise it answers 403 owner_only or 404 unknown_app, in // that order, as the page's owner check does. func (a *app) apiOwner(w http.ResponseWriter, me store.Member, id string) (catalog.Entry, bool) { if me.Role != "owner" { writeJSON(w, http.StatusForbidden, apiError{Code: "owner_only"}) return catalog.Entry{}, false } e, ok := catalog.Get(id) if !ok { writeJSON(w, http.StatusNotFound, apiError{Code: "unknown_app"}) return catalog.Entry{}, false } return e, true } // apiStoreInstall is POST /api/v1/store/{app}/install. It answers 202 with // the app installing, and the app polls the store until it isn't. An app // already installing answers 202 and one installed 200, and neither starts // anything. Start returns an error only from before its claim (install.go), // so when it fails the store is read again: a row that now reads installing // was claimed by another request and is answered 202 as it stands, and // anything else, a failed row included (that failure is an earlier one), // is 503: this attempt never started. func (a *app) apiStoreInstall(w http.ResponseWriter, r *http.Request) { me, _ := CurrentMember(r) e, ok := a.apiOwner(w, me, chi.URLParam(r, "app")) if !ok { return } c, err := a.storeContent(r.Context(), me) if err != nil { a.logger.Error("api install", "app", e.ID, "err", err) writeJSON(w, http.StatusServiceUnavailable, apiError{Code: "unavailable"}) return } switch row, _ := c.row(e.ID); row.State { case "installing": writeJSON(w, http.StatusAccepted, apiStoreAnswer{storeJSON(c)}) return case "installed": writeJSON(w, http.StatusOK, apiStoreAnswer{storeJSON(c)}) return } startErr := a.inst.Start(r.Context(), e.ID) if startErr != nil { a.logger.Error("api install", "app", e.ID, "err", startErr) } if c, err = a.storeContent(r.Context(), me); err != nil { a.logger.Error("api install", "app", e.ID, "err", err) writeJSON(w, http.StatusServiceUnavailable, apiError{Code: "unavailable"}) return } if row, _ := c.row(e.ID); startErr != nil && row.State != "installing" { writeJSON(w, http.StatusServiceUnavailable, apiError{Code: "unavailable"}) return } writeJSON(w, http.StatusAccepted, apiStoreAnswer{storeJSON(c)}) } // apiStoreUninstall is POST /api/v1/store/{app}/uninstall: 200 with the // store, also when it was uninstalled already, and 409 busy while it is // still installing. func (a *app) apiStoreUninstall(w http.ResponseWriter, r *http.Request) { me, _ := CurrentMember(r) e, ok := a.apiOwner(w, me, chi.URLParam(r, "app")) if !ok { return } switch err := a.inst.Uninstall(r.Context(), e.ID); { case errors.Is(err, install.ErrBusy): writeJSON(w, http.StatusConflict, apiError{Code: "busy"}) return case errors.Is(err, store.ErrNoInstall): // Already uninstalled. case err != nil: a.logger.Error("api uninstall", "app", e.ID, "err", err) writeJSON(w, http.StatusServiceUnavailable, apiError{Code: "unavailable"}) return } c, err := a.storeContent(r.Context(), me) if err != nil { a.logger.Error("api uninstall", "app", e.ID, "err", err) writeJSON(w, http.StatusServiceUnavailable, apiError{Code: "unavailable"}) return } writeJSON(w, http.StatusOK, apiStoreAnswer{storeJSON(c)}) } // maxInviteBody bounds POST /api/v1/people's body, {"email": …}. const maxInviteBody = 4 << 10 // apiPeopleInvite is POST /api/v1/people, {"email": …}: the People form's // invitation, as JSON. It answers 200 with the person, invited now or // already here. func (a *app) apiPeopleInvite(w http.ResponseWriter, r *http.Request) { me, _ := CurrentMember(r) if me.Role != "owner" { writeJSON(w, http.StatusForbidden, apiError{Code: "owner_only"}) return } if !isJSONBody(r) { writeJSON(w, http.StatusUnsupportedMediaType, apiError{Code: "json_only"}) return } raw, err := io.ReadAll(http.MaxBytesReader(w, r.Body, maxInviteBody)) if err != nil { if mbe := (*http.MaxBytesError)(nil); errors.As(err, &mbe) { writeJSON(w, http.StatusRequestEntityTooLarge, apiError{Code: "too_large"}) return } writeJSON(w, http.StatusBadRequest, apiError{Code: "bad_request"}) return } var in struct { Email string `json:"email"` } if err := json.Unmarshal(raw, &in); err != nil { writeJSON(w, http.StatusBadRequest, apiError{Code: "bad_request"}) return } m, res, err := a.invitePerson(r.Context(), in.Email) switch { case err != nil: a.logger.Error("api invite", "err", err) writeJSON(w, http.StatusServiceUnavailable, apiError{Code: "unavailable"}) case res == inviteBadEmail: writeJSON(w, http.StatusUnprocessableEntity, apiError{Code: "bad_email"}) case res == inviteMailFailed: writeJSON(w, http.StatusBadGateway, apiError{Code: "mail_failed"}) default: writeJSON(w, http.StatusOK, struct { Person apiPerson `json:"person"` }{personJSON(personFor(m))}) } }