package server
import (
"fmt"
"html"
"net/http"
"net/url"
"os"
"path/filepath"
"strconv"
"strings"
"time"
"pageswiki/internal/store"
)
func (s *Server) handleChildrenProjection(w http.ResponseWriter, r *http.Request) {
args := parseChildrenMacroArgs("", r.URL.Query().Get("path"))
args.View = r.URL.Query().Get("view")
if args.View == "compact" {
args.View = "icon"
}
if args.View != "icon" && args.View != "detail" {
args.View = "list"
}
args.Excludes = splitExcludePatterns(r.URL.Query().Get("exclude"))
args.Offset, _ = strconv.Atoi(r.URL.Query().Get("offset"))
args.Limit, _ = strconv.Atoi(r.URL.Query().Get("limit"))
if args.Limit <= 0 || args.Limit > 400 {
args.Limit = 120
}
rendered, err := s.renderReadableChildren(r, args)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "text/html; charset=utf-8")
w.Header().Set("Cache-Control", "private, no-store")
_, _ = w.Write([]byte(rendered))
}
func (s *Server) renderChildrenProjection(
domainUUID string,
args childrenMacroArgs,
) (string, error) {
return s.renderChildrenProjectionFiltered(domainUUID, args, nil)
}
func (s *Server) renderChildrenProjectionFiltered(
domainUUID string,
args childrenMacroArgs,
allowed func(string) bool,
) (string, error) {
// /u is a profile/user-Wiki namespace, not a root directory entry. Keep it
// reachable by URL while hiding it from every root children projection,
// including asynchronous view switches and cached continuation requests.
if args.TargetPath == "/" && !isExcludedPath("/u", args.Excludes) {
args.Excludes = append(args.Excludes, "/u")
}
if args.View == "list" {
entries, total, err := s.store.ListChildEntriesPageInDomain(domainUUID, args.TargetPath, args.Offset, args.Limit)
if err != nil {
return "", err
}
var body strings.Builder
body.WriteString(`
`)
} else {
body.WriteString(`
` +
`| Name | Type | Size | Updated | ` +
`
`)
}
for _, entry := range entries {
if isExcludedPath(entry.Path, args.Excludes) || (allowed != nil && !allowed(entry.Path)) {
continue
}
if args.View == "icon" {
body.WriteString(s.renderChildIcon(args.TargetPath, entry))
continue
}
contentType := entry.ContentType
if entry.IsDir {
contentType = "folder"
}
updated := "—"
if entry.UpdatedAt > 0 {
updated = time.Unix(entry.UpdatedAt, 0).Format("2006-01-02 15:04")
}
displayName := entry.Title
if displayName == "" {
displayName = childName(args.TargetPath, entry.Path)
}
body.WriteString(fmt.Sprintf(
`| %s | %s | %d | %s |
`,
html.EscapeString(entry.Path),
html.EscapeString((&url.URL{Path: entry.Path}).EscapedPath()),
html.EscapeString(displayName),
html.EscapeString(contentType),
entry.Size,
updated,
))
}
if args.View == "icon" {
body.WriteString("")
} else {
body.WriteString("
")
}
writeChildrenMore(&body, args, args.Offset+len(entries), total)
return body.String(), nil
}
func writeChildrenMore(
body *strings.Builder,
args childrenMacroArgs,
nextOffset, total int,
) {
if nextOffset >= total {
return
}
query := url.Values{
"path": {args.TargetPath},
"view": {args.View},
"offset": {strconv.Itoa(nextOffset)},
"limit": {strconv.Itoa(args.Limit)},
}
if len(args.Excludes) > 0 {
query.Set("exclude", strings.Join(args.Excludes, ","))
}
body.WriteString(fmt.Sprintf(
`
`,
html.EscapeString("/v/children?"+query.Encode()),
))
}
func childName(parent, child string) string {
return strings.TrimPrefix(strings.TrimPrefix(child, parent), "/")
}
func (s *Server) renderChildIcon(parent string, entry store.BrowserEntry) string {
path := html.EscapeString(entry.Path)
name := entry.Title
if name == "" {
name = childName(parent, entry.Path)
}
name = html.EscapeString(name)
preview := s.entryPreviewHTML(entry, true)
return fmt.Sprintf(
`
%s%s`,
path,
html.EscapeString((&url.URL{Path: entry.Path}).EscapedPath()),
preview,
name,
)
}
// entryPreviewHTML is shared by directory listings and search results. Callers
// that render broad result sets can disable enqueueing and rely on the periodic
// preview scheduler, avoiding a burst of database writes during navigation.
func (s *Server) entryPreviewHTML(
entry store.BrowserEntry,
enqueueMissing bool,
) string {
if entry.IsDir {
return childTypeIcon("folder")
}
filename := entry.Filename
if filename == "" {
filename = filepath.Base(entry.Path)
}
adapter := selectProjectionAdapter(contentDescriptor{
MediaType: strings.ToLower(strings.Split(entry.ContentType, ";")[0]),
Filename: filename,
SizeBytes: int64(entry.Size),
})
previewURL, cached := s.entryPreviewState(entry, adapter.ID, enqueueMissing)
if cached {
badge := ""
switch adapter.ID {
case "pdf":
badge = "PDF"
case "video":
badge = "▶"
case "excalidraw":
badge = "EX"
case "archive":
badge = "ZIP"
}
badgeHTML := ""
if badge != "" {
badgeHTML = `
` + badge + ``
}
return fmt.Sprintf(
`
%s`,
html.EscapeString(previewURL),
badgeHTML,
)
}
switch adapter.ID {
case "image":
return pendingPreviewIcon("image", previewURL, "")
case "video":
return pendingPreviewIcon("video", previewURL, "▶")
case "pdf":
return pendingPreviewIcon("pdf", previewURL, "PDF")
case "excalidraw":
return pendingPreviewIcon("drawing", previewURL, "EX")
case "archive":
return childTypeIcon("archive")
case "debian-package":
return childTypeIcon("package")
case "audio":
return childTypeIcon("audio")
case "text", "csv":
if isProgramFilename(filename) {
return childTypeIcon("code")
}
return childTypeIcon("text")
default:
if isProgramFilename(filename) {
return childTypeIcon("code")
}
switch strings.ToLower(filepath.Ext(filename)) {
case ".txt", ".md", ".log", ".rst":
return childTypeIcon("text")
}
return childTypeIcon("file")
}
}
func (s *Server) entryPreviewState(
entry store.BrowserEntry,
kind string,
enqueueMissing bool,
) (string, bool) {
if enqueueMissing {
return s.enqueuePreview(entry)
}
switch kind {
case "image", "pdf", "video", "excalidraw", "archive":
default:
return "", false
}
if s.previewRoot == "" || entry.DocumentHash == "" {
return "", false
}
cacheURL := s.previewCacheURL(entry.DocumentHash, kind)
info, err := os.Stat(s.previewCachePath(entry.DocumentHash, kind))
return cacheURL, err == nil && info.Size() > 0
}
func pendingPreviewIcon(kind, cacheURL, badge string) string {
if cacheURL == "" {
return childTypeIcon(kind)
}
badgeHTML := ""
if badge != "" {
badgeHTML = `
` + badge + ``
}
return `
` +
childTypeIcon(kind) + badgeHTML + ``
}
func isProgramFilename(filename string) bool {
switch strings.ToLower(filepath.Ext(filename)) {
case ".py", ".sh", ".bash", ".zsh", ".js", ".jsx", ".ts", ".tsx",
".go", ".rs", ".c", ".h", ".cc", ".cpp", ".java", ".rb", ".php",
".sql", ".css", ".html", ".yaml", ".yml", ".toml":
return true
default:
return false
}
}
func childTypeIcon(kind string) string {
paths := map[string]string{
"folder": `
`,
"archive": `
`,
"package": `
`,
"audio": `
`,
"image": `
`,
"video": `
`,
"pdf": `
`,
"drawing": `
`,
"code": `
`,
"text": `
`,
"file": `
`,
}
path := paths[kind]
if path == "" {
path = paths["file"]
}
return `
`
}