Files
pages/internal/server/city_handler.go
Anya Tokugawa c1175d389f Implement Knowledge City platform, organizer and DAV integration
Capture accumulated application, UI, CLI, regression tests and design documentation changes, including task project mapping and default CalDAV list naming.

Keep deployment data, backups, local credentials and build artifacts out of Git. Move the Compose enrollment token to an ignored local environment file.
2026-09-27 14:44:43 +09:00

410 lines
15 KiB
Go

package server
import (
"context"
"database/sql"
"encoding/json"
"errors"
"net/http"
"strconv"
"strings"
"pageswiki/internal/store"
)
func cityReadErrorStatus(err error) int {
switch {
case errors.Is(err, store.ErrAccessDenied), errors.Is(err, sql.ErrNoRows), errors.Is(err, store.ErrCityNameAmbiguous):
return http.StatusNotFound
case errors.Is(err, store.ErrCityMapBudget), errors.Is(err, context.DeadlineExceeded), errors.Is(err, context.Canceled):
return http.StatusServiceUnavailable
default:
return http.StatusInternalServerError
}
}
func (s *Server) handleCityMap(w http.ResponseWriter, r *http.Request) {
privateCityResponse(w)
domainUUID := s.domainUUIDForRequest(r)
principal := s.requestPrincipal(r)
canPlan := principal != nil && (s.store.IsBuiltinGroupAdmin(domainUUID, principal.UUID, "domain_admin") || s.store.Authorize(store.AuthorizationRequest{DomainUUID: domainUUID, PrincipalUUID: principal.UUID, Capability: "manage", TargetType: "domain", TargetID: domainUUID}) == nil)
path := strings.Trim(strings.TrimPrefix(r.URL.Path, "/v/city"), "/")
if path != "" {
parts := strings.Split(path, "/")
kinds := map[string]string{"q": "quartier", "s": "street", "p": "spot"}
kind := ""
if len(parts) == 2 || (len(parts) == 3 && parts[0] == "s") {
kind = kinds[parts[0]]
}
if kind == "" {
http.NotFound(w, r)
return
}
detail, err := s.store.CityNodeContext(r.Context(), domainUUID, kind, strings.Join(parts[1:], "/"))
if err != nil {
status := cityReadErrorStatus(err)
if status == http.StatusNotFound {
http.NotFound(w, r)
return
}
if status == http.StatusServiceUnavailable {
w.Header().Set("Retry-After", "5")
}
http.Error(w, http.StatusText(status), status)
return
}
if !canReadCityNode(detail, s.pathReadFilter(r)) {
http.NotFound(w, r)
return
}
pages := []store.CityPagePlacement{}
if kind == "spot" {
pages, err = s.spotPagesForRequest(r, detail.UUID)
if err != nil {
status := cityReadErrorStatus(err)
if status == http.StatusServiceUnavailable {
w.Header().Set("Retry-After", "5")
}
http.Error(w, http.StatusText(status), status)
return
}
}
pageViews := make([]cityPageView, 0, len(pages))
for _, page := range pages {
pageViews = append(pageViews, cityPageView{page, cityPageHref(page.Path)})
}
quartierHref, streetHref := "", ""
if detail.Quartier != nil {
quartierHref = cityDetailHref("quartier", detail.Quartier.Name, "", detail.Quartier.UUID)
}
if detail.Street != nil {
streetHref = cityDetailHref("street", detail.Street.Name, detail.Quartier.Name, detail.Street.UUID)
}
s.renderWithContext(w, r, "city_node.gohtml", map[string]any{"Title": detail.Title, "Node": detail, "Pages": pageViews, "QuartierHref": quartierHref, "StreetHref": streetHref, "MapHref": "/v/city?" + kind + "=" + detail.UUID, "CanPlan": canPlan, "Locale": s.getLocale(domainUUID), "GovernanceEndpoint": s.governanceForUI(r, kind, detail.UUID)})
return
}
s.renderWithContext(w, r, "city_map.gohtml", map[string]any{"Title": translate(s.getLocale(domainUUID), "city.map"), "CanPlan": canPlan, "Locale": s.getLocale(domainUUID), "GovernanceEndpoint": s.governanceForUI(r, "domain", domainUUID)})
}
func (s *Server) handleCityAPI(w http.ResponseWriter, r *http.Request) {
if cityGovernanceRoute(r.URL.Path) {
s.handleCityGovernance(w, r)
return
}
domainUUID := s.domainUUIDForRequest(r)
action := strings.Trim(strings.TrimPrefix(r.URL.Path, "/_/api/v1/city/"), "/")
w.Header().Set("Content-Type", "application/json; charset=utf-8")
if action == "map" && r.Method == http.MethodGet {
privateCityResponse(w)
city, err := s.cityProjectionForRequest(r)
if err != nil {
status := cityReadErrorStatus(err)
if status == http.StatusServiceUnavailable {
w.Header().Set("Retry-After", "5")
}
writeEventJSON(w, status, map[string]string{"error": err.Error()})
return
}
_ = json.NewEncoder(w).Encode(city)
return
}
parts := strings.Split(action, "/")
if len(parts) == 3 && parts[0] == "spots" && parts[2] == "pages" && r.Method == http.MethodGet {
privateCityResponse(w)
pages, err := s.spotPagesForRequest(r, parts[1])
if err != nil {
status := cityReadErrorStatus(err)
if status == http.StatusServiceUnavailable {
w.Header().Set("Retry-After", "5")
}
message := http.StatusText(status)
if status == http.StatusNotFound {
message = "Spot not found"
}
writeEventJSON(w, status, map[string]string{"error": message})
return
}
_ = json.NewEncoder(w).Encode(map[string]any{"pages": pages})
return
}
principal := s.requestPrincipal(r)
if principal == nil || (!s.store.IsBuiltinGroupAdmin(domainUUID, principal.UUID, "domain_admin") && s.store.Authorize(store.AuthorizationRequest{DomainUUID: domainUUID, PrincipalUUID: principal.UUID, Capability: "manage", TargetType: "domain", TargetID: domainUUID}) != nil) {
writeEventJSON(w, http.StatusForbidden, map[string]string{"error": "domain admin required"})
return
}
if action == "organize" && r.Method == http.MethodPost {
var request store.CityOrganizeRequest
if json.NewDecoder(http.MaxBytesReader(w, r.Body, 128<<10)).Decode(&request) != nil {
writeEventJSON(w, 400, map[string]string{"error": "city_invalid_selection"})
return
}
result, err := s.store.OrganizeCity(domainUUID, principal.UUID, request)
if err != nil {
writeCityOrganizeError(w, err)
return
}
writeEventJSON(w, http.StatusOK, result)
return
}
if len(parts) == 3 && (parts[0] == "spots" || parts[0] == "zones") && parts[2] == "title" && r.Method == http.MethodPost {
var request struct {
Kind string `json:"kind"`
Title string `json:"title"`
BaseVersion int64 `json:"base_version"`
}
if json.NewDecoder(http.MaxBytesReader(w, r.Body, 4<<10)).Decode(&request) != nil {
writeEventJSON(w, 400, map[string]string{"error": "city_invalid_title"})
return
}
if parts[0] == "spots" {
request.Kind = "spot"
} else if request.Kind != "quartier" && request.Kind != "street" {
writeEventJSON(w, 400, map[string]string{"error": "city_invalid_selection"})
return
}
if err := s.store.RenameCityTitle(domainUUID, principal.UUID, request.Kind, parts[1], request.Title, request.BaseVersion); err != nil {
writeCityOrganizeError(w, err)
return
}
writeEventJSON(w, http.StatusOK, map[string]string{"status": "ok"})
return
}
if action == "health" && r.Method == http.MethodGet {
health, err := s.store.GetCityHealth(domainUUID)
if err != nil {
writeEventJSON(w, 500, map[string]string{"error": err.Error()})
return
}
_ = json.NewEncoder(w).Encode(health)
return
}
if action == "events" && r.Method == http.MethodGet {
afterVersion, _ := strconv.ParseInt(r.URL.Query().Get("after_version"), 10, 64)
limit, _ := strconv.Atoi(r.URL.Query().Get("limit"))
events, err := s.store.ListTopologyEvents(domainUUID, afterVersion, limit)
if err != nil {
writeEventJSON(w, 500, map[string]string{"error": err.Error()})
return
}
_ = json.NewEncoder(w).Encode(map[string]any{"events": events, "count": len(events)})
return
}
if (action == "plans/preview" || action == "plans/apply") && r.Method == http.MethodPost {
var plan store.CityPlan
if json.NewDecoder(http.MaxBytesReader(w, r.Body, 2<<20)).Decode(&plan) != nil {
writeEventJSON(w, 400, map[string]string{"error": "invalid City plan JSON"})
return
}
var preview store.CityPlanPreview
var err error
if action == "plans/apply" {
preview, err = s.store.ApplyCityPlan(domainUUID, principal.UUID, plan)
} else {
preview, err = s.store.PreviewCityPlan(domainUUID, plan)
}
if err != nil {
writeEventJSON(w, 409, map[string]any{"error": err.Error(), "preview": preview})
return
}
_ = json.NewEncoder(w).Encode(preview)
return
}
if action == "autoplan" && r.Method == http.MethodGet {
plan, err := s.buildCityAutoPlan(domainUUID)
if err != nil {
writeEventJSON(w, 500, map[string]string{"error": err.Error()})
return
}
_ = json.NewEncoder(w).Encode(map[string]any{"items": plan, "count": len(plan)})
return
}
if action == "autoplan" && r.Method == http.MethodPost {
count, err := s.applyCityAutoPlan(domainUUID, principal.UUID)
if err != nil {
writeEventJSON(w, 400, map[string]string{"error": err.Error()})
return
}
writeEventJSON(w, 200, map[string]any{"status": "ok", "applied": count})
return
}
if action == "zones" && r.Method == http.MethodPost {
var request struct {
Kind string `json:"kind"`
ParentUUID string `json:"parent_uuid"`
Name string `json:"name"`
Title string `json:"title"`
Description string `json:"description"`
PathPrefix string `json:"path_prefix"`
}
if json.NewDecoder(http.MaxBytesReader(w, r.Body, 1<<20)).Decode(&request) != nil {
writeEventJSON(w, 400, map[string]string{"error": "invalid JSON"})
return
}
id, err := s.store.CreateZoneAtPath(domainUUID, principal.UUID, request.Kind, request.ParentUUID, request.Name, request.Title, request.Description, request.PathPrefix)
if err != nil {
writeEventJSON(w, 400, map[string]string{"error": err.Error()})
return
}
writeEventJSON(w, http.StatusCreated, map[string]string{"uuid": id})
return
}
if action == "spots" && r.Method == http.MethodPost {
var request struct {
StreetUUID string `json:"street_uuid"`
Name string `json:"name"`
Title string `json:"title"`
Summary string `json:"summary"`
PathPrefix string `json:"path_prefix"`
}
if json.NewDecoder(http.MaxBytesReader(w, r.Body, 1<<20)).Decode(&request) != nil {
writeEventJSON(w, 400, map[string]string{"error": "invalid JSON"})
return
}
id, err := s.store.CreateSpotAtPath(domainUUID, principal.UUID, request.StreetUUID, request.Name, request.Title, request.Summary, request.PathPrefix)
if err != nil {
writeEventJSON(w, 400, map[string]string{"error": err.Error()})
return
}
writeEventJSON(w, http.StatusCreated, map[string]string{"uuid": id})
return
}
if len(parts) == 2 && (parts[0] == "zones" || parts[0] == "spots") && r.Method == http.MethodDelete {
kind := "spot"
if parts[0] == "zones" {
var request struct {
Kind string `json:"kind"`
}
if json.NewDecoder(http.MaxBytesReader(w, r.Body, 1<<20)).Decode(&request) != nil {
writeEventJSON(w, 400, map[string]string{"error": "invalid JSON"})
return
}
kind = request.Kind
}
if err := s.store.DeleteCityNode(domainUUID, principal.UUID, kind, parts[1]); err != nil {
writeEventJSON(w, 400, map[string]string{"error": err.Error()})
return
}
writeEventJSON(w, http.StatusOK, map[string]string{"status": "ok"})
return
}
if len(parts) == 2 && (parts[0] == "zones" || parts[0] == "spots") && r.Method == http.MethodPatch {
var request struct {
Kind string `json:"kind"`
PathPrefix string `json:"path_prefix"`
}
if json.NewDecoder(http.MaxBytesReader(w, r.Body, 1<<20)).Decode(&request) != nil || strings.TrimSpace(request.PathPrefix) == "" {
writeEventJSON(w, 400, map[string]string{"error": "invalid JSON or Path"})
return
}
kind := "spot"
if parts[0] == "zones" {
kind = request.Kind
}
if err := s.store.UpdateCityNodePath(domainUUID, principal.UUID, kind, parts[1], request.PathPrefix); err != nil {
writeEventJSON(w, 400, map[string]string{"error": err.Error()})
return
}
writeEventJSON(w, http.StatusOK, map[string]string{"status": "ok"})
return
}
if len(parts) == 3 && parts[0] == "spots" && parts[2] == "pages" && (r.Method == http.MethodPost || r.Method == http.MethodDelete) {
var request struct {
PageUUID string `json:"page_uuid"`
Path string `json:"path"`
EdgeType string `json:"edge_type"`
Label string `json:"label"`
}
if json.NewDecoder(http.MaxBytesReader(w, r.Body, 1<<20)).Decode(&request) != nil {
writeEventJSON(w, 400, map[string]string{"error": "invalid JSON"})
return
}
var err error
if r.Method == http.MethodDelete {
err = s.store.RemoveSpotPage(domainUUID, principal.UUID, parts[1], request.PageUUID, request.EdgeType)
} else {
err = s.store.AddSpotPage(domainUUID, principal.UUID, parts[1], request.PageUUID, request.Path, request.EdgeType, request.Label)
}
if err != nil {
writeEventJSON(w, 400, map[string]string{"error": err.Error()})
return
}
writeEventJSON(w, http.StatusOK, map[string]string{"status": "ok"})
return
}
if len(parts) == 3 && parts[0] == "spots" && parts[2] == "relations" && r.Method == http.MethodPost {
var request struct {
TargetSpotUUID string `json:"target_spot_uuid"`
RelationType string `json:"relation_type"`
}
if json.NewDecoder(http.MaxBytesReader(w, r.Body, 1<<20)).Decode(&request) != nil {
writeEventJSON(w, 400, map[string]string{"error": "invalid JSON"})
return
}
if err := s.store.AddSpotRelation(domainUUID, principal.UUID, parts[1], request.TargetSpotUUID, request.RelationType); err != nil {
writeEventJSON(w, 400, map[string]string{"error": err.Error()})
return
}
writeEventJSON(w, http.StatusOK, map[string]string{"status": "ok"})
return
}
if len(parts) == 3 && parts[0] == "spots" && parts[2] == "relations" && r.Method == http.MethodDelete {
var request struct {
TargetSpotUUID string `json:"target_spot_uuid"`
RelationType string `json:"relation_type"`
}
if json.NewDecoder(http.MaxBytesReader(w, r.Body, 1<<20)).Decode(&request) != nil {
writeEventJSON(w, 400, map[string]string{"error": "invalid JSON"})
return
}
if err := s.store.RemoveSpotRelation(domainUUID, principal.UUID, parts[1], request.TargetSpotUUID, request.RelationType); err != nil {
writeEventJSON(w, 400, map[string]string{"error": err.Error()})
return
}
writeEventJSON(w, http.StatusOK, map[string]string{"status": "ok"})
return
}
if len(parts) == 3 && parts[2] == "move" && r.Method == http.MethodPost {
var request struct {
ParentUUID string `json:"parent_uuid"`
StreetUUID string `json:"street_uuid"`
SortKey int `json:"sort_key"`
}
if json.NewDecoder(http.MaxBytesReader(w, r.Body, 1<<20)).Decode(&request) != nil {
writeEventJSON(w, 400, map[string]string{"error": "invalid JSON"})
return
}
var err error
if parts[0] == "zones" {
err = s.store.MoveStreet(domainUUID, principal.UUID, parts[1], request.ParentUUID, request.SortKey)
} else if parts[0] == "spots" {
err = s.store.MoveSpot(domainUUID, principal.UUID, parts[1], request.StreetUUID, request.SortKey)
} else {
err = store.ErrAccessDenied
}
if err != nil {
writeEventJSON(w, 400, map[string]string{"error": err.Error()})
return
}
writeEventJSON(w, http.StatusOK, map[string]string{"status": "ok"})
return
}
w.Header().Set("Allow", "GET, POST")
writeEventJSON(w, http.StatusMethodNotAllowed, map[string]string{"error": "method not allowed"})
}
func jsonNumber(value int64) string {
return strconv.FormatInt(value, 10)
}
func writeCityOrganizeError(w http.ResponseWriter, err error) {
status := http.StatusBadRequest
if errors.Is(err, store.ErrCityChanged) {
status = http.StatusConflict
}
if errors.Is(err, sql.ErrNoRows) {
writeEventJSON(w, http.StatusNotFound, map[string]string{"error": "city_invalid_selection"})
return
}
writeEventJSON(w, status, map[string]string{"error": err.Error()})
}