package httpapi import ( "encoding/json" "errors" "io" "net/http" "github.com/gin-gonic/gin" "git.kmalloc.org/squid/sonda/internal/usersettings" ) // userSettingsHandlers serve the signed-in user's own settings. type userSettingsHandlers struct{ svc userSettingsService } type userSettingsJSON struct { DiscoverFromListening bool `json:"discover_from_listening"` RadioInApps bool `json:"radio_in_apps"` } func toUserSettingsJSON(s usersettings.Settings) userSettingsJSON { return userSettingsJSON{DiscoverFromListening: s.DiscoverFromListening, RadioInApps: s.RadioInApps} } func writeUserSettingsError(c *gin.Context, err error) { if errors.Is(err, usersettings.ErrUserNotFound) { writeError(c, http.StatusUnauthorized, "unauthorized", "account no longer exists") return } _ = c.Error(err) writeError(c, http.StatusInternalServerError, "internal", "internal error") } func (h *userSettingsHandlers) get(c *gin.Context) { s, err := h.svc.Get(c.Request.Context(), currentUserID(c)) if err != nil { writeUserSettingsError(c, err) return } c.JSON(http.StatusOK, toUserSettingsJSON(s)) } // settingKeys are the settings a PATCH may name, spelt exactly like this. var settingKeys = map[string]bool{"discover_from_listening": true, "radio_in_apps": true} // parseSettingsPatch reads the body of PATCH /me/settings. It is strict because // the settings are about privacy: one JSON object and nothing after it, only known // settings spelt exactly, and a boolean (or null, which means "leave it alone") for each. func parseSettingsPatch(body []byte) (usersettings.Patch, bool) { var fields map[string]json.RawMessage if err := json.Unmarshal(body, &fields); err != nil || fields == nil { return usersettings.Patch{}, false // not JSON, text after the object, or null } var p usersettings.Patch for key, value := range fields { if !settingKeys[key] { return usersettings.Patch{}, false } var b *bool if err := json.Unmarshal(value, &b); err != nil { return usersettings.Patch{}, false } switch key { case "discover_from_listening": p.DiscoverFromListening = b case "radio_in_apps": p.RadioInApps = b } } return p, true } func (h *userSettingsHandlers) update(c *gin.Context) { body, err := io.ReadAll(c.Request.Body) if err != nil { writeError(c, http.StatusBadRequest, "invalid_input", "malformed JSON body") return } patch, ok := parseSettingsPatch(body) if !ok { writeError(c, http.StatusBadRequest, "invalid_input", "the body must be one JSON object with known settings, each a boolean") return } s, err := h.svc.Update(c.Request.Context(), currentUserID(c), patch) if err != nil { writeUserSettingsError(c, err) return } c.JSON(http.StatusOK, toUserSettingsJSON(s)) }