Files
tajniak81andClaude Opus 5.5 e441880f2f
CI / desktop (ubuntu-latest) (push) Successful in 1h15m48s
CI / mobile (push) Failing after 3m6s
CI / desktop (macos-latest) (push) Canceled after 0s
CI / desktop (windows-latest) (push) Canceled after 0s
CI / go (Media) (push) Successful in 10m21s
CI / go (Server) (push) Failing after 19m16s
CI / go (Web-App) (push) Successful in 10m27s
CI / frontend (push) Failing after 7m25s
CI / docker (push) Successful in 46m48s
Add the block types Docmost has and Docwell lacked
The slash menu gains Video, Audio, Page break, Footnote, Tabs, Status,
Emoji, Subpages, Synced block and a fifth column size:
- Video and audio upload a file that plays on the page.
- Page breaks show as a labelled line and start a new page in print,
  Word and PDF.
- Footnotes are numbered in reading order and listed at the end of the
  page. Their notes hold bold, italic, code and links, with a plain copy
  kept for search.
- Tabs hold blocks on several named tabs; which one shows is each
  reader's own choice.
- Status badges are coloured words in the text.
- Typing ":" and a word picks an emoji, from the list the page icon
  picker uses, now kept in the editor package.
- Subpages lists the page's child pages, read afresh from the page tree.
- A synced block is a synced page that shows one block of another page,
  made from a copied block link.

Exports (HTML, Markdown, Word, PDF) and search handle every new block.
Page and space exports list a page's subpages. Labels are translated in
all five languages.

The phone toolbar gets Tabs, Footnote, Status, Emoji, Subpages and Page
break, and the app answers the editor's request for the page's
subpages. The bridge protocol goes to version 5.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 17:37:32 +01:00

290 lines
8.7 KiB
Go

// SPDX-License-Identifier: AGPL-3.0-or-later
package directory
import (
"archive/zip"
"context"
"fmt"
"html"
"io"
"log/slog"
"net/url"
"strings"
"time"
"docwell/server/internal/access"
"docwell/server/internal/apperr"
"docwell/server/internal/convert"
"docwell/server/internal/store/pocketbase"
)
// ---- Space export ----------------------------------------------------------
//
// A space exports as one zip: a file per page, with a page's subpages in a
// folder next to it, an index, and every attachment of those pages under
// _files/. Links between exported pages and to attachments become relative
// paths, so the folder reads on its own (in a file browser, a Markdown
// viewer or a static site). Archived pages are included; trashed ones are not.
// SpaceExport is a prepared export: everything is checked and listed, and
// WriteTo produces the zip. Errors before WriteTo still become a normal
// error response.
type SpaceExport struct {
Filename string
s *Service
format string
title string
pages []exportedPage
byID map[string]*exportedPage
files []exportedFile
fileByID map[string]string
}
type exportedPage struct {
rec pageRecord
path string // file inside the zip, e.g. "Guides/Setup.md"
depth int
// parent is the nearest exported page above this one ("" at the top),
// whose subpages blocks list this page.
parent string
}
type exportedFile struct {
rec attachmentRecord
path string
}
// PrepareSpaceExport lists what an export of the space holds: the live pages
// c can open, as markdown ("markdown") or HTML ("html") files (viewer).
func (s *Service) PrepareSpaceExport(ctx context.Context, c access.Caller, spaceID, format string) (*SpaceExport, error) {
ext := map[string]string{"markdown": ".md", "md": ".md", "": ".md", "html": ".html"}[format]
if ext == "" {
return nil, apperr.InvalidFields(map[string]string{"format": "Format must be markdown or html."})
}
a, rules, err := s.spaceRules(ctx, c, spaceID)
if err != nil {
return nil, err
}
t, err := s.loadTree(ctx, a.space.ID)
if err != nil {
return nil, err
}
e := &SpaceExport{
Filename: exportName(a.space.Name, ".zip"), s: s, format: ext, title: a.space.Name,
byID: map[string]*exportedPage{}, fileByID: map[string]string{},
}
// Siblings need different names; "index" and "_files" are taken at the top.
taken := map[string]map[string]bool{"": {"index": true, "_files": true}}
var walk func(parent, dir, shownParent string, depth int)
walk = func(parent, dir, shownParent string, depth int) {
for _, p := range t.children[parent] {
under, underDir, d := shownParent, dir, depth
if rules.role(p.ID) != "" {
name := uniqueName(taken, dir, exportBase(p.Title))
path := name + ext
if dir != "" {
path = dir + "/" + path
}
e.pages = append(e.pages, exportedPage{rec: p, path: path, depth: depth, parent: shownParent})
under, d = p.ID, depth+1
underDir = strings.TrimSuffix(path, ext)
}
walk(p.ID, underDir, under, d)
}
}
walk("", "", "", 0)
for i := range e.pages {
e.byID[e.pages[i].rec.ID] = &e.pages[i]
}
if len(e.pages) > 0 {
atts, err := listAll[attachmentRecord](ctx, s, "attachments", pocketbase.ListOptions{
Filter: fmt.Sprintf("workspace = '%s'", a.space.Workspace),
})
if err != nil {
return nil, err
}
names := map[string]map[string]bool{}
for _, f := range atts {
if e.byID[f.Page] == nil {
continue
}
path := "_files/" + uniqueName(names, "", cleanFilename(f.Name))
e.files = append(e.files, exportedFile{rec: f, path: path})
e.fileByID[f.ID] = path
}
}
return e, nil
}
// exportBase is a page's file name without the extension.
func exportBase(title string) string { return strings.TrimSuffix(exportName(title, ".x"), ".x") }
// uniqueName returns name, or "name (2)", "name (3)", … when dir already has it.
func uniqueName(taken map[string]map[string]bool, dir, name string) string {
if taken[dir] == nil {
taken[dir] = map[string]bool{}
}
out := name
for i := 2; taken[dir][strings.ToLower(out)]; i++ {
out = fmt.Sprintf("%s (%d)", name, i)
}
taken[dir][strings.ToLower(out)] = true
return out
}
// relPath is the link from file from to file to, both slash paths from the
// zip's root, with each part escaped for use in a link.
func relPath(from, to string) string {
fromDir := strings.Split(from, "/")
fromDir = fromDir[:len(fromDir)-1]
parts := strings.Split(to, "/")
common := 0
for common < len(fromDir) && common < len(parts)-1 && fromDir[common] == parts[common] {
common++
}
var out []string
for range fromDir[common:] {
out = append(out, "..")
}
for _, p := range parts[common:] {
out = append(out, url.PathEscape(p))
}
return strings.Join(out, "/")
}
// WriteTo writes the zip. A page or file that fails to load is replaced by a
// note in the zip, so one broken attachment does not lose the whole export.
func (e *SpaceExport) WriteTo(ctx context.Context, w io.Writer) error {
z := zip.NewWriter(w)
if err := e.writeIndex(z); err != nil {
return err
}
for _, p := range e.pages {
body, err := e.render(ctx, p)
if err != nil {
slog.Warn("space export: page skipped", "page", p.rec.ID, "err", err)
body = []byte(fmt.Sprintf("This page could not be exported: %v\n", err))
}
if err := writeZipFile(z, p.path, modTime(p.rec.Updated), body); err != nil {
return err
}
}
for _, f := range e.files {
if err := e.copyFile(ctx, z, f); err != nil {
return err
}
}
return z.Close()
}
func (e *SpaceExport) render(ctx context.Context, p exportedPage) ([]byte, error) {
raw, err := e.s.docs.Content(ctx, p.rec.ID)
if err != nil {
return nil, err
}
doc, err := convert.Parse(raw)
if err != nil {
return nil, err
}
opts := convert.Options{
FileURL: func(path string) string {
id := strings.TrimPrefix(strings.SplitN(path, "?", 2)[0], FileURL(""))
if to, ok := e.fileByID[id]; ok {
return relPath(p.path, to)
}
return e.s.publicURL + path
},
PageURL: func(id, fragment string) string {
if to, ok := e.byID[id]; ok {
return relPath(p.path, to.path) + fragment
}
// A page outside the export (another space, or hidden): the server.
return e.s.publicURL + "/p/" + id + fragment
},
}
for _, c := range e.pages {
if c.parent == p.rec.ID {
opts.Subpages = append(opts.Subpages, convert.PageLink{ID: c.rec.ID, Title: c.rec.Title, Icon: c.rec.Icon})
}
}
if e.format == ".html" {
return []byte(convert.HTMLPage(p.rec.Title, doc, opts)), nil
}
return []byte(convert.MarkdownPage(p.rec.Title, doc, opts)), nil
}
// writeIndex lists every page as a nested list, in tree order.
func (e *SpaceExport) writeIndex(z *zip.Writer) error {
var b strings.Builder
untitled := func(t string) string {
if strings.TrimSpace(t) == "" {
return "Untitled"
}
return t
}
if e.format == ".html" {
t := html.EscapeString(e.title)
b.WriteString("<!doctype html>\n<html>\n<head>\n<meta charset=\"utf-8\">\n<title>" + t + "</title>\n</head>\n<body>\n<h1>" + t + "</h1>\n")
depth := -1
for _, p := range e.pages {
for ; depth < p.depth; depth++ {
b.WriteString("<ul>\n")
}
for ; depth > p.depth; depth-- {
b.WriteString("</ul>\n")
}
fmt.Fprintf(&b, "<li><a href=\"%s\">%s</a></li>\n", html.EscapeString(relPath("index.html", p.path)), html.EscapeString(untitled(p.rec.Title)))
}
for ; depth >= 0; depth-- {
b.WriteString("</ul>\n")
}
b.WriteString("</body>\n</html>\n")
return writeZipFile(z, "index.html", time.Now(), []byte(b.String()))
}
b.WriteString("# " + e.title + "\n\n")
for _, p := range e.pages {
fmt.Fprintf(&b, "%s- [%s](%s)\n", strings.Repeat(" ", p.depth), mdLinkText(untitled(p.rec.Title)), relPath("index.md", p.path))
}
return writeZipFile(z, "index.md", time.Now(), []byte(b.String()))
}
func mdLinkText(s string) string {
return strings.NewReplacer(`\`, `\\`, "[", `\[`, "]", `\]`).Replace(s)
}
func (e *SpaceExport) copyFile(ctx context.Context, z *zip.Writer, f exportedFile) error {
file, err := e.s.openFile(ctx, f.rec, nil)
if err != nil {
slog.Warn("space export: file skipped", "file", f.rec.ID, "err", err)
return nil
}
defer func() { _ = file.Body.Close() }()
// Most attachments (images, PDFs, archives) are compressed already.
out, err := z.CreateHeader(&zip.FileHeader{Name: f.path, Method: zip.Store, Modified: modTime(f.rec.Created)})
if err != nil {
return err
}
_, err = io.Copy(out, file.Body)
return err
}
func writeZipFile(z *zip.Writer, name string, mod time.Time, body []byte) error {
w, err := z.CreateHeader(&zip.FileHeader{Name: name, Method: zip.Deflate, Modified: mod})
if err != nil {
return err
}
_, err = w.Write(body)
return err
}
// modTime reads a PocketBase date; a bad one is "now".
func modTime(s string) time.Time {
t, err := time.Parse("2006-01-02 15:04:05.000Z", s)
if err != nil {
return time.Now()
}
return t
}