Editor:
- Toggles (Tiptap Details). Open state is per reader, not saved.
- Embeds for YouTube, Vimeo, Loom, Figma, CodePen, Spotify, Google Docs
and Maps, in sandboxed frames. Other addresses become link cards.
- Link cards with title, description and picture read by docwell-server
(GET /link-preview). The fetcher refuses private, loopback, link-local
and CGNAT addresses after DNS resolution, redirects included.
- Block links: a margin button gives a block a short id and copies
/p/<id>#b-<block>. Opening one jumps to the block and flashes it.
- Markdown, HTML and PDF exports handle the new blocks; HTML import reads
<details> as a toggle.
Pages and spaces:
- History gets a Changes view: block and word diff against the previous
version or the page as it is now.
- Archive: archived pages leave the tree and become read-only but stay
readable; a space's Archive lists them with Unarchive. New migration
(pages.archived_at) and page.archived / page.unarchived webhook events.
- Full space export (GET /spaces/{id}/export): a zip of Markdown or HTML
files with subpages in folders, an index, and attachments under _files/.
Links between exported pages and to attachments become relative paths.
Desktop 1.0:
- Several servers, each with its own sign-in; old settings files carry over.
- Session tokens in the system keychain (go-keyring), moved out of
localStorage on first start.
- Native menu bar (File, Edit, View, Window, Help) with a Server submenu.
- docwell:// links may point at a block.
- Release workflow builds Windows NSIS, macOS DMG and Linux deb, rpm and
AppImage installers and attaches them to the release;
build/set-version.mjs stamps the version into their metadata.
Not yet run: the release workflow, the desktop menus by eye, and macOS or
Linux builds.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
282 lines
8.4 KiB
Go
282 lines
8.4 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
|
|
}
|
|
|
|
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})
|
|
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
|
|
},
|
|
}
|
|
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
|
|
}
|