Files
pages/internal/server/semantic_handlers.go
T

342 lines
10 KiB
Go

package server
import (
"context"
"database/sql"
"errors"
"html/template"
"net/http"
"path"
"strings"
"time"
"unicode/utf8"
"pageswiki/internal/grammaratur"
"pageswiki/internal/store"
)
func (s *Server) renderPageNotFound(w http.ResponseWriter, r *http.Request, missingPath string) {
missingPath = "/" + strings.TrimLeft(path.Clean("/"+missingPath), "/")
query := strings.Trim(strings.TrimSuffix(path.Base(missingPath), "/"), " .")
suggestions := []store.SearchResult{}
if query != "" && query != "." {
ctx, cancel := context.WithTimeout(r.Context(), 350*time.Millisecond)
defer cancel()
if found, err := s.store.SearchPathsInDomainFiltered(ctx, s.domainUUIDForRequest(r), "/", query, 5, s.pathReadFilter(r)); err == nil {
suggestions = found
}
}
w.WriteHeader(http.StatusNotFound)
if r.Method == http.MethodHead {
return
}
s.renderWithContext(w, r, "not_found.gohtml", map[string]any{
"MissingPath": missingPath,
"SuggestionQuery": query,
"Suggestions": suggestions,
"NavItems": resolveNavItems(s.getSystemNavItems(s.domainUUIDForRequest(r)), NavContext{Path: missingPath}),
})
}
func (s *Server) handleSemanticRoute(
w http.ResponseWriter,
r *http.Request,
) {
path := r.URL.Path
objectUUID, err :=
s.store.ResolvePathInDomain(s.domainUUIDForRequest(r), path)
if err != nil {
if !errors.Is(err, sql.ErrNoRows) {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
domainUUID := s.domainUUIDForRequest(r)
children, childErr := s.store.ListChildPathsInDomain(domainUUID, path)
if childErr != nil {
http.Error(w, childErr.Error(), http.StatusInternalServerError)
return
}
if !s.getVirtualFolderPages(domainUUID) || len(children) == 0 {
s.renderPageNotFound(w, r, path)
return
}
rendered := s.expandMacrosForRequest(r,
"{{children}}",
path,
domainUUID,
)
s.renderWithContext(
w,
r,
"page.gohtml",
map[string]any{
"Title": path,
"Path": path,
"Breadcrumbs": buildBreadcrumbs(path),
"ContentView": contentView{
Kind: "html",
ContentType: "text/html; charset=utf-8",
},
"NavItems": resolveNavItems(
s.getSystemNavItems(domainUUID),
NavContext{Path: path},
),
"RenderedHTML": template.HTML(rendered),
},
)
return
}
windowedView, useWindowedView, windowedErr := s.windowedContentViewForRequest(r, objectUUID, path)
if windowedErr != nil {
http.Error(w, windowedErr.Error(), http.StatusInternalServerError)
return
}
if useWindowedView {
bs := buildBreadcrumbs(path)
citySpots, _ := s.pageSpotAppearancesForRequest(r, objectUUID)
governanceEndpoint := ""
if len(citySpots) > 0 {
governanceEndpoint = s.governanceForUI(r, "spot", citySpots[0].SpotUUID)
}
s.renderWithContext(w, r, "page.gohtml", map[string]any{"Title": path, "Path": path, "Breadcrumbs": bs, "ObjectUUID": objectUUID, "CitySpots": citySpots, "GovernanceEndpoint": governanceEndpoint, "ContentView": windowedView, "ComicMode": r.URL.Query().Get("comic") == "1", "NavItems": resolveNavItems(s.getSystemNavItems(s.domainUUIDForRequest(r)), NavContext{Path: path, ObjectUUID: objectUUID, ObjectURI: "uuid:" + objectUUID})})
return
}
latest, err := s.latestRevisionForRequest(r, objectUUID)
if err != nil {
http.Error(
w,
err.Error(),
500,
)
return
}
bs := buildBreadcrumbs(path)
citySpots, _ := s.pageSpotAppearancesForRequest(r, objectUUID)
governanceEndpoint := ""
if len(citySpots) > 0 {
governanceEndpoint = s.governanceForUI(r, "spot", citySpots[0].SpotUUID)
}
contentView := revisionContentView(latest, path)
contentView.RawURL = rawProjectionURL("path:" + path)
if contentView.Kind == "pdf" || contentView.Kind == "excalidraw" {
// Native PDF viewers issue several independent Range requests. Pin the
// frame to the immutable Revision so every range resolves to one body.
contentView.RawURL = rawProjectionURL("rev:" + latest.UUID)
contentView.RevisionUUID = latest.UUID
if contentView.Kind == "pdf" {
contentView.PDFPages = s.pdfPageCount(latest.DocumentHash)
}
}
rendered := ""
if contentView.Kind == "html" {
rendered = s.safeHTMLProjection(r, latest.Body, path, true)
}
s.renderWithContext(
w,
r,
"page.gohtml",
map[string]any{
"Title": path,
"Path": path,
"Breadcrumbs": bs,
"ObjectUUID": objectUUID,
"CitySpots": citySpots,
"GovernanceEndpoint": governanceEndpoint,
"ContentView": contentView,
"SocialSource": func() string {
if contentView.Kind == "html" {
return latest.Body
}
return ""
}(),
"ComicMode": r.URL.Query().Get("comic") == "1",
"NavItems": resolveNavItems(
s.getSystemNavItems(s.domainUUIDForRequest(r)),
NavContext{
Path: path,
ObjectUUID: objectUUID,
ObjectURI: "uuid:" + objectUUID,
},
),
"RenderedHTML": template.HTML(
rendered,
),
},
)
}
func (s *Server) handleSemanticEditor(
w http.ResponseWriter,
r *http.Request,
) {
requestedEditType := r.URL.Query().Get("edittype")
if requestedEditType != "" && requestedEditType != "html" && requestedEditType != "markdown" && requestedEditType != "plain" {
http.Error(w, "unsupported editor format", http.StatusBadRequest)
return
}
path := semanticEditorPath(r.URL.Path)
objectUUID, err :=
s.store.ResolvePathInDomain(s.domainUUIDForRequest(r), path)
if err != nil && !errors.Is(err, sql.ErrNoRows) {
http.Error(w, "could not resolve editor path", http.StatusInternalServerError)
return
}
if errors.Is(err, sql.ErrNoRows) {
objectUUID, err =
s.store.CreatePageAtPathInDomain(s.domainUUIDForRequest(r), path)
if err != nil {
http.Error(
w,
err.Error(),
500,
)
return
}
}
// CSV editing needs the complete source, never the viewer's truncated window.
// Check metadata before loading a potentially large document.
metadata, metaErr := s.store.GetLatestRevisionMetadataForLanguagesContext(r.Context(), objectUUID, s.revisionLanguageCandidates(r))
if lang := r.URL.Query().Get("lang"); lang != "" {
metadata, metaErr = s.store.GetRevisionMetadataForExactLanguage(objectUUID, lang)
}
if metaErr != nil || metadata == nil {
http.Error(w, "revision unavailable or invalid language", http.StatusBadRequest)
return
}
csvEditor := selectProjectionAdapter(contentDescriptor{MediaType: strings.ToLower(strings.TrimSpace(strings.Split(metadata.ContentType, ";")[0])), Filename: metadata.Filename}).Kind == "csv"
if csvEditor {
size, sizeErr := s.store.DocumentSizeContext(r.Context(), metadata.DocumentHash)
if sizeErr != nil || size > maxCSVMacroBytes {
http.Error(w, "CSV editor requires a complete document of at most 256 KiB", http.StatusRequestEntityTooLarge)
return
}
}
var latest *store.Revision
if csvEditor {
// Load the immutable revision we checked; a concurrent new head is
// handled by the normal save CAS, not by an unbounded second read.
window, readErr := s.store.ReadDocumentWindowContext(r.Context(), metadata.DocumentHash, 0, maxCSVMacroBytes)
if readErr != nil || window.Truncated {
http.Error(w, "CSV source unavailable", http.StatusServiceUnavailable)
return
}
latest = metadata
latest.Body = string(window.Data)
} else {
latest, err = s.latestRevisionForRequest(r, objectUUID)
if lang := r.URL.Query().Get("lang"); lang != "" {
latest, err = s.store.GetRevisionForExactLanguage(objectUUID, lang)
}
}
body := ""
if err != nil {
http.Error(w, "revision unavailable or invalid language", 400)
return
}
baseBody := latest.Body
editType := "html"
contentType := "text/html; charset=utf-8"
filename := ""
if err == nil {
if latest.UUID != "" {
view := revisionContentView(latest, path)
if view.Kind == "csv" {
if !csvEditor || !utf8.ValidString(latest.Body) || strings.ContainsRune(latest.Body, 0) || len(latest.Body) > maxCSVMacroBytes {
http.Error(w, "CSV editor requires bounded UTF-8 text", http.StatusUnsupportedMediaType)
return
}
editType = "code"
} else if view.Kind == "code" {
editType = "code"
if strings.EqualFold(strings.TrimSpace(strings.Split(latest.ContentType, ";")[0]), "text/plain") {
editType = "plain"
}
} else if view.Kind != "html" {
http.Error(
w,
"this Content-Type is not editable as text",
http.StatusUnsupportedMediaType,
)
return
}
contentType = latest.ContentType
filename = latest.Filename
}
body = latest.Body
}
if requestedEditType == "plain" && latest.UUID != "" && editType != "plain" {
http.Error(w, "PlainText is available for new documents and text/plain files; existing content is not converted", http.StatusConflict)
return
}
if latest.UUID == "" && requestedEditType == "plain" {
editType = "plain"
contentType = "text/plain; charset=utf-8"
filename = path[strings.LastIndex(path, "/")+1:]
} else if editType != "code" && editType != "plain" && requestedEditType != "" {
editType = requestedEditType
} else if editType != "code" && editType != "plain" && requestedEditType == "" {
editType = s.getEditorFormat(s.domainUUIDForRequest(r))
}
if editType == "markdown" {
compiled, err := grammaratur.HTMLToMarkdownAuthoring(body)
if err != nil {
http.Error(
w,
err.Error(),
500,
)
return
}
body = compiled
}
s.renderWithContext(
w,
r,
"editor.gohtml",
map[string]any{
"Title": path,
"Path": path,
"ObjectUUID": objectUUID,
"Body": body,
"BaseBody": baseBody,
"BaseRevision": latest.UUID,
"EditType": editType,
"CSVEditor": csvEditor,
"PageLanguage": latest.Language,
"PageContentType": contentType,
"PageFilename": filename,
"EditorKeymap": s.getEditorKeymap(s.domainUUIDForRequest(r)),
"EditorPreviewDefault": s.getEditorPreviewDefault(s.domainUUIDForRequest(r)),
"EditorSyntax": s.getEditorSyntaxHighlight(s.domainUUIDForRequest(r)),
"EditorAutocomplete": s.getEditorAutocomplete(s.domainUUIDForRequest(r)),
},
)
}