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.
531 lines
16 KiB
Go
531 lines
16 KiB
Go
package server
|
|
|
|
import (
|
|
"database/sql"
|
|
"encoding/json"
|
|
"errors"
|
|
"io"
|
|
"net/http"
|
|
"net/url"
|
|
"sort"
|
|
"strconv"
|
|
"strings"
|
|
"time"
|
|
|
|
"pageswiki/internal/render"
|
|
"pageswiki/internal/store"
|
|
)
|
|
|
|
func periodicalRoute(target string) (kind, operation string) {
|
|
for _, kind := range []string{"diary", "blog"} {
|
|
if target == "/v/"+kind+"/-/new" {
|
|
return kind, "new"
|
|
}
|
|
if target == "/v/"+kind || strings.HasPrefix(target, "/v/"+kind+"/") {
|
|
return kind, "view"
|
|
}
|
|
for _, op := range []string{"settings", "entries", "plan", "posts"} {
|
|
if target == "/_/api/v1/extension/content."+kind+"/"+op {
|
|
return kind, op
|
|
}
|
|
}
|
|
}
|
|
return "", ""
|
|
}
|
|
|
|
// A dated viewer is a projection, not the article's semantic Path. Keeping
|
|
// dated navigation under /v avoids collisions with prefix=/ article URLs.
|
|
func periodicalDatePath(kind, month, day string) string {
|
|
base := "/v/" + kind
|
|
if day != "" {
|
|
return base + "/" + strings.ReplaceAll(day, "-", "/")
|
|
}
|
|
if month != "" {
|
|
return base + "/" + strings.ReplaceAll(month, "-", "/")
|
|
}
|
|
return base
|
|
}
|
|
|
|
func periodicalURL(target string, q url.Values) string {
|
|
// own is a presence flag; never emit the older numeric mine=1 spelling.
|
|
q.Del("month")
|
|
q.Del("date")
|
|
q.Del("mine")
|
|
own := q.Has("own")
|
|
q.Del("own")
|
|
query := q.Encode()
|
|
if own {
|
|
if query != "" {
|
|
query += "&"
|
|
}
|
|
query += "own"
|
|
}
|
|
if query == "" {
|
|
return target
|
|
}
|
|
return target + "?" + query
|
|
}
|
|
|
|
func periodicalSelection(r *http.Request, kind string) (month, day string, err error) {
|
|
base := "/v/" + kind
|
|
if r.URL.Path != "/" && r.URL.Path != base {
|
|
suffix := strings.TrimPrefix(r.URL.Path, base+"/")
|
|
parts := strings.Split(suffix, "/")
|
|
if len(parts) != 2 && len(parts) != 3 {
|
|
return "", "", store.ErrPeriodicalInvalid
|
|
}
|
|
month = strings.Join(parts[:2], "-")
|
|
if len(parts) == 3 {
|
|
day = strings.Join(parts, "-")
|
|
}
|
|
}
|
|
q := r.URL.Query()
|
|
if values := q["month"]; len(values) > 1 {
|
|
return "", "", store.ErrPeriodicalInvalid
|
|
}
|
|
if values := q["date"]; len(values) > 1 {
|
|
return "", "", store.ErrPeriodicalInvalid
|
|
}
|
|
if value := q.Get("month"); value != "" {
|
|
if month != "" && month != value {
|
|
return "", "", store.ErrPeriodicalInvalid
|
|
}
|
|
month = value
|
|
}
|
|
if value := q.Get("date"); value != "" {
|
|
if day != "" && day != value {
|
|
return "", "", store.ErrPeriodicalInvalid
|
|
}
|
|
day = value
|
|
}
|
|
if day != "" {
|
|
d, e := time.Parse("2006-01-02", day)
|
|
if e != nil || d.Year() < 1 || d.Format("2006-01-02") != day {
|
|
return "", "", store.ErrPeriodicalInvalid
|
|
}
|
|
if month != "" && month != d.Format("2006-01") {
|
|
return "", "", store.ErrPeriodicalInvalid
|
|
}
|
|
month = d.Format("2006-01")
|
|
}
|
|
if month != "" {
|
|
d, e := time.Parse("2006-01", month)
|
|
if e != nil || d.Year() < 1 || d.Format("2006-01") != month {
|
|
return "", "", store.ErrPeriodicalInvalid
|
|
}
|
|
}
|
|
return month, day, nil
|
|
}
|
|
|
|
func (s *Server) handlePeriodical(w http.ResponseWriter, r *http.Request) {
|
|
kind, op := periodicalRoute(r.URL.Path)
|
|
s.handlePeriodicalView(w, r, kind, op)
|
|
}
|
|
|
|
func (s *Server) handlePeriodicalView(w http.ResponseWriter, r *http.Request, kind, op string) {
|
|
if kind == "" {
|
|
http.NotFound(w, r)
|
|
return
|
|
}
|
|
if !s.systemExtensionEnabled(s.domainUUIDForRequest(r), "content."+kind) {
|
|
http.Error(w, "extension disabled", http.StatusNotFound)
|
|
return
|
|
}
|
|
if op == "new" {
|
|
s.handlePeriodicalNew(w, r, kind)
|
|
return
|
|
}
|
|
if op == "view" && s.homeLayout(s.domainUUIDForRequest(r)) == kind && s.servePublicPeriodical(w, r) {
|
|
return
|
|
}
|
|
if r.Method != "GET" && r.Method != "POST" {
|
|
w.Header().Set("Allow", "GET, POST")
|
|
http.Error(w, "method not allowed", 405)
|
|
return
|
|
}
|
|
// Initial metadata/UI slice requires a real session even in legacy mode.
|
|
// Public article bodies continue through existing exact publication approval.
|
|
domain := s.domainUUIDForRequest(r)
|
|
principal, err := s.store.PrincipalForSession(domain, s.authTokenFromRequest(r))
|
|
if err != nil {
|
|
if op == "view" && s.servePublicPeriodical(w, r) {
|
|
return
|
|
}
|
|
s.authRequired(w, r)
|
|
return
|
|
}
|
|
w.Header().Set("Cache-Control", "private, no-store")
|
|
projection, err := s.store.PeriodicalProjection(r.Context(), domain, kind)
|
|
if err != nil {
|
|
http.Error(w, "projection unavailable", 503)
|
|
return
|
|
}
|
|
contentDomain, sourceBase := domain, ""
|
|
if projection != nil {
|
|
if op != "settings" && (r.Method != "GET" || op == "plan") {
|
|
http.Error(w, "edit articles on the source Domain", 403)
|
|
return
|
|
}
|
|
contentDomain = projection.Source
|
|
host, e := s.store.GetDomainEffectiveHost(contentDomain)
|
|
if e != nil || host == "" {
|
|
http.Error(w, "projection unavailable", 503)
|
|
return
|
|
}
|
|
sourceBase = "//" + host
|
|
}
|
|
selectedMonth, selected := "", ""
|
|
if op == "view" && r.Method == "GET" {
|
|
selectedMonth, selected, err = periodicalSelection(r, kind)
|
|
if err != nil {
|
|
http.Error(w, "invalid diary/blog date", 400)
|
|
return
|
|
}
|
|
q := r.URL.Query()
|
|
if q.Has("month") || q.Has("date") || q.Has("mine") || (q.Has("own") && q.Get("own") != "") {
|
|
if q.Get("mine") == "1" {
|
|
q.Set("own", "")
|
|
}
|
|
target := periodicalDatePath(kind, selectedMonth, selected)
|
|
if r.URL.Path == "/" && selectedMonth == "" {
|
|
target = "/"
|
|
}
|
|
http.Redirect(w, r, periodicalURL(target, q), http.StatusFound)
|
|
return
|
|
}
|
|
}
|
|
if r.Method == "POST" {
|
|
if op == "view" || op == "plan" {
|
|
http.Error(w, "method not allowed", 405)
|
|
return
|
|
}
|
|
limit := int64(8192)
|
|
if op == "posts" {
|
|
limit = 320 << 10
|
|
}
|
|
decoder := json.NewDecoder(http.MaxBytesReader(w, r.Body, limit))
|
|
decoder.DisallowUnknownFields()
|
|
var entry store.PeriodicalEntry
|
|
var post store.PeriodicalPost
|
|
var setting struct {
|
|
Enabled *bool `json:"enabled"`
|
|
Prefix *string `json:"prefix"`
|
|
}
|
|
if op == "settings" {
|
|
err = decoder.Decode(&setting)
|
|
} else if op == "posts" {
|
|
err = decoder.Decode(&post)
|
|
} else {
|
|
err = decoder.Decode(&entry)
|
|
}
|
|
if err != nil || decoder.Decode(new(any)) != io.EOF {
|
|
http.Error(w, "invalid JSON", 400)
|
|
return
|
|
}
|
|
if op == "settings" {
|
|
if setting.Enabled == nil {
|
|
http.Error(w, "enabled required", 400)
|
|
return
|
|
}
|
|
prefixes := []string{}
|
|
if setting.Prefix != nil {
|
|
prefixes = append(prefixes, *setting.Prefix)
|
|
}
|
|
err = s.store.ChangePeriodical(r.Context(), domain, principal.UUID, kind, setting.Enabled, nil, prefixes...)
|
|
} else if op == "posts" {
|
|
post.Body = render.Markdown(post.Body)
|
|
post.Timezone = s.getLocation(domain).String()
|
|
err = s.store.CreatePeriodical(r.Context(), domain, principal.UUID, kind, &post)
|
|
} else {
|
|
entry.Timezone = s.getLocation(domain).String()
|
|
err = s.store.ChangePeriodical(r.Context(), domain, principal.UUID, kind, nil, &entry)
|
|
}
|
|
if err != nil {
|
|
status := 500
|
|
message := "Could not save entry"
|
|
switch {
|
|
case errors.Is(err, store.ErrAccessDenied):
|
|
status = 403
|
|
message = "Forbidden"
|
|
case errors.Is(err, store.ErrPeriodicalConflict):
|
|
status = 409
|
|
message = translate(s.getLocale(domain), "periodical.conflict")
|
|
case errors.Is(err, store.ErrPeriodicalInvalid):
|
|
status = 400
|
|
message = translate(s.getLocale(domain), "periodical.invalid")
|
|
case errors.Is(err, store.ErrEmbeddedAssetUnavailable):
|
|
status = 400
|
|
message = "Embedded asset unavailable"
|
|
case errors.Is(err, store.ErrPeriodicalDisabled):
|
|
status = 409
|
|
message = translate(s.getLocale(domain), "periodical.disabled")
|
|
case errors.Is(err, sql.ErrNoRows):
|
|
status = 404
|
|
message = translate(s.getLocale(domain), "periodical.missing")
|
|
}
|
|
http.Error(w, message, status)
|
|
return
|
|
}
|
|
if op == "posts" {
|
|
_, publicErr := s.store.AnonymousRevision(r.Context(), domain, post.Path, s.revisionLanguageCandidates(r))
|
|
writeEventJSON(w, 200, map[string]any{"ok": true, "page_uuid": post.PageUUID, "path": post.Path, "href": cityPageHref(post.Path), "share_targets": s.periodicalShareTargets(r, kind, post.Path), "published": publicErr == nil})
|
|
return
|
|
}
|
|
writeEventJSON(w, 200, map[string]bool{"ok": true})
|
|
return
|
|
}
|
|
if op == "posts" {
|
|
w.Header().Set("Allow", "POST")
|
|
http.Error(w, "method not allowed", 405)
|
|
return
|
|
}
|
|
enabled, err := s.store.PeriodicalEnabled(r.Context(), domain, kind)
|
|
if err != nil {
|
|
http.Error(w, "extension unavailable", 503)
|
|
return
|
|
}
|
|
if op == "settings" {
|
|
prefix, err := s.store.PeriodicalPrefix(r.Context(), domain, kind)
|
|
if err != nil {
|
|
http.Error(w, "extension unavailable", 503)
|
|
return
|
|
}
|
|
controlled, err := s.store.DomainEntryControlled(domain)
|
|
if err != nil {
|
|
http.Error(w, "extension unavailable", 503)
|
|
return
|
|
}
|
|
writeEventJSON(w, 200, map[string]any{"enabled": enabled, "prefix": prefix, "controlled": controlled})
|
|
return
|
|
}
|
|
if op == "plan" {
|
|
if !enabled {
|
|
http.Error(w, translate(s.getLocale(domain), "periodical.disabled"), 409)
|
|
return
|
|
}
|
|
prefix, err := s.store.PeriodicalPrefix(r.Context(), domain, kind)
|
|
if err != nil {
|
|
http.Error(w, "extension unavailable", 503)
|
|
return
|
|
}
|
|
target, err := store.PeriodicalPath(prefix, r.URL.Query().Get("date"), r.URL.Query().Get("keyword"))
|
|
if err != nil {
|
|
http.Error(w, translate(s.getLocale(domain), "periodical.invalid"), 400)
|
|
return
|
|
}
|
|
allowed := principal.State == "active" && s.store.Authorize(store.AuthorizationRequest{DomainUUID: domain, PrincipalUUID: principal.UUID, Capability: "write", TargetType: "path", TargetID: target}) == nil
|
|
if principal.State == "active" && ownUserEditorPath("/e"+target, principal.Username) && s.store.CheckLocalityAccessCaps(domain, principal.UUID, "write", target) == nil {
|
|
allowed = true
|
|
}
|
|
if !allowed {
|
|
http.Error(w, "Forbidden", 403)
|
|
return
|
|
}
|
|
_, err = s.store.ResolvePathInDomain(domain, target)
|
|
if err == nil {
|
|
http.Error(w, translate(s.getLocale(domain), "periodical.path_exists"), 409)
|
|
return
|
|
}
|
|
if !errors.Is(err, sql.ErrNoRows) {
|
|
http.Error(w, "path unavailable", 503)
|
|
return
|
|
}
|
|
writeEventJSON(w, 200, map[string]string{"path": target, "editor_href": cityPageHref("/e" + target)})
|
|
return
|
|
}
|
|
if projection != nil {
|
|
on, e := s.store.PeriodicalEnabled(r.Context(), contentDomain, kind)
|
|
if e != nil {
|
|
http.Error(w, "projection unavailable", 503)
|
|
return
|
|
}
|
|
enabled = enabled && on
|
|
}
|
|
entries := []store.PeriodicalEntry{}
|
|
if enabled {
|
|
all, e := s.store.ListPeriodicalEntries(r.Context(), contentDomain, kind)
|
|
if e != nil {
|
|
http.Error(w, "entry index unavailable", 503)
|
|
return
|
|
}
|
|
allowed := s.pathReadFilter(r)
|
|
if projection != nil {
|
|
targetAllowed := allowed
|
|
sourcePolicy, e := s.store.LoadReadPathPolicy(contentDomain, principal.UUID)
|
|
if e != nil {
|
|
http.Error(w, "projection permissions unavailable", 503)
|
|
return
|
|
}
|
|
allowed = func(target string) bool {
|
|
if projection.Prefix != "/" && target != projection.Prefix && !strings.HasPrefix(target, projection.Prefix+"/") {
|
|
return false
|
|
}
|
|
return targetAllowed(target) && sourcePolicy.Allows(target)
|
|
}
|
|
}
|
|
seen := map[string]bool{}
|
|
for _, entry := range all {
|
|
if !seen[entry.PageUUID] && allowed(entry.Path) {
|
|
seen[entry.PageUUID] = true
|
|
entries = append(entries, entry)
|
|
}
|
|
}
|
|
}
|
|
if op == "entries" {
|
|
writeEventJSON(w, 200, map[string]any{"enabled": enabled, "entries": entries, "source_domain": contentDomain, "source_origin": sourceBase, "projection": projection != nil})
|
|
return
|
|
}
|
|
s.renderPeriodical(w, r, domain, contentDomain, sourceBase, kind, selectedMonth, selected, enabled, projection, principal, entries)
|
|
}
|
|
|
|
func (s *Server) renderPeriodical(w http.ResponseWriter, r *http.Request, domain, contentDomain, sourceBase, kind, selectedMonth, selected string, enabled bool, projection *store.PeriodicalProjection, principal *store.Principal, entries []store.PeriodicalEntry) {
|
|
public := isAnonymousProjection(r)
|
|
dedicated := projection != nil && s.homeLayout(domain) == kind
|
|
now := time.Now().In(s.getLocation(contentDomain))
|
|
month := now.Format("2006-01")
|
|
if selectedMonth != "" {
|
|
month = selectedMonth
|
|
}
|
|
first, _ := time.Parse("2006-01", month)
|
|
category := r.URL.Query().Get("category")
|
|
mine := r.URL.Query().Has("own")
|
|
filtered := []periodicalItem{}
|
|
recent := []periodicalItem{}
|
|
dates := map[string]int{}
|
|
categories := map[string]bool{}
|
|
for _, entry := range entries {
|
|
if mine && entry.Owner != principal.UUID {
|
|
continue
|
|
}
|
|
categories[entry.Category] = true
|
|
item := periodicalItem{PeriodicalEntry: entry, Href: cityPageHref(entry.Path), EditHref: cityPageHref("/e" + entry.Path)}
|
|
if projection != nil {
|
|
item.Href = sourceBase + item.Href
|
|
item.EditHref = sourceBase + item.EditHref
|
|
if dedicated {
|
|
if href := projectedArticleHref(projection.Prefix, entry.Path); href != "" {
|
|
item.Href = href
|
|
}
|
|
}
|
|
}
|
|
if len(recent) < 8 {
|
|
recent = append(recent, item)
|
|
}
|
|
if category != "" && entry.Category != category {
|
|
continue
|
|
}
|
|
if strings.HasPrefix(entry.Date, month+"-") {
|
|
dates[entry.Date]++
|
|
}
|
|
if selected != "" && entry.Date != selected {
|
|
continue
|
|
}
|
|
if kind == "diary" && !strings.HasPrefix(entry.Date, month+"-") {
|
|
continue
|
|
}
|
|
if kind == "blog" && selectedMonth != "" && !strings.HasPrefix(entry.Date, month+"-") {
|
|
continue
|
|
}
|
|
filtered = append(filtered, item)
|
|
}
|
|
categoryNames := []string{}
|
|
for c := range categories {
|
|
if c != "" {
|
|
categoryNames = append(categoryNames, c)
|
|
}
|
|
}
|
|
sort.Strings(categoryNames)
|
|
offset, _ := strconv.Atoi(r.URL.Query().Get("offset"))
|
|
offset = max(0, min(offset, len(filtered)))
|
|
end := min(offset+20, len(filtered))
|
|
for i := offset; i < end; i++ {
|
|
if projection != nil {
|
|
continue
|
|
}
|
|
filtered[i].CanEdit = s.store.Authorize(store.AuthorizationRequest{DomainUUID: domain, PrincipalUUID: principal.UUID, Capability: "write", TargetType: "path", TargetID: filtered[i].Path}) == nil
|
|
if principal.State == "active" && ownUserEditorPath("/e"+filtered[i].Path, principal.Username) && s.store.CheckLocalityAccessCaps(domain, principal.UUID, "write", filtered[i].Path) == nil {
|
|
filtered[i].CanEdit = true
|
|
}
|
|
}
|
|
link := func(offset int) string {
|
|
q := r.URL.Query()
|
|
q.Set("offset", strconv.Itoa(offset))
|
|
return periodicalURL(r.URL.Path, q)
|
|
}
|
|
days := []periodicalDay{}
|
|
for i := 0; i < int(first.Weekday()); i++ {
|
|
days = append(days, periodicalDay{})
|
|
}
|
|
for day := first; day.Month() == first.Month(); day = day.AddDate(0, 0, 1) {
|
|
date := day.Format("2006-01-02")
|
|
q := url.Values{}
|
|
if mine {
|
|
q.Set("own", "")
|
|
}
|
|
if category != "" {
|
|
q.Set("category", category)
|
|
}
|
|
days = append(days, periodicalDay{Number: day.Day(), Count: dates[date], Href: periodicalURL(periodicalDatePath(kind, month, date), q), Selected: date == selected})
|
|
}
|
|
data := map[string]any{"Kind": kind, "Title": translate(s.getLocale(domain), "periodical."+kind), "Enabled": enabled, "CanConfigure": s.store.IsBuiltinGroupAdmin(domain, principal.UUID, "domain_admin"), "Entries": filtered[offset:end], "Recent": recent, "Days": days, "Month": month, "Today": now.Format("2006-01-02"), "Category": category, "Categories": categoryNames, "Mine": mine, "Locale": s.getLocale(domain)}
|
|
data["FilterMonth"] = month
|
|
data["Public"] = public
|
|
if dedicated {
|
|
data["Title"] = s.getWikiName(domain)
|
|
}
|
|
data["Projection"] = projection != nil
|
|
if projection != nil {
|
|
data["SourceViewer"] = sourceBase + "/v/" + kind
|
|
}
|
|
data["BasePath"] = "/v/" + kind
|
|
if r.URL.Path == "/" {
|
|
data["BasePath"] = "/"
|
|
}
|
|
data["FilterAction"] = "/v/" + kind
|
|
prefix, err := s.store.PeriodicalPrefix(r.Context(), domain, kind)
|
|
if err != nil {
|
|
http.Error(w, "extension unavailable", 503)
|
|
return
|
|
}
|
|
data["Prefix"] = prefix
|
|
if kind == "blog" && selectedMonth == "" {
|
|
data["FilterMonth"] = ""
|
|
}
|
|
monthLink := func(delta int) string {
|
|
q := r.URL.Query()
|
|
q.Del("offset")
|
|
q.Del("date")
|
|
month := first.AddDate(0, delta, 0)
|
|
if month.Year() < 1 || month.Year() > 9999 {
|
|
month = first
|
|
}
|
|
return periodicalURL(periodicalDatePath(kind, month.Format("2006-01"), ""), q)
|
|
}
|
|
data["PreviousMonth"] = monthLink(-1)
|
|
data["NextMonth"] = monthLink(1)
|
|
if offset > 0 {
|
|
data["Previous"] = link(max(0, offset-20))
|
|
}
|
|
if end < len(filtered) {
|
|
data["Next"] = link(end)
|
|
}
|
|
if public {
|
|
data["CanConfigure"] = false
|
|
data["Context"] = s.BuildRequestContext(r)
|
|
s.render(w, "periodical.gohtml", data)
|
|
} else {
|
|
s.renderWithContext(w, r, "periodical.gohtml", data)
|
|
}
|
|
}
|
|
|
|
type periodicalItem struct {
|
|
store.PeriodicalEntry
|
|
Href, EditHref string
|
|
CanEdit bool
|
|
}
|
|
type periodicalDay struct {
|
|
Number, Count int
|
|
Href string
|
|
Selected bool
|
|
}
|