// 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("\n\n\n\n" + t + "\n\n\n

" + t + "

\n") depth := -1 for _, p := range e.pages { for ; depth < p.depth; depth++ { b.WriteString("\n") } fmt.Fprintf(&b, "
  • %s
  • \n", html.EscapeString(relPath("index.html", p.path)), html.EscapeString(untitled(p.rec.Title))) } for ; depth >= 0; depth-- { b.WriteString("\n") } b.WriteString("\n\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 }