Import (Import on a space's page list, or POST /spaces/{id}/import):
- Word (.docx, up to 25 MB): Title and heading styles, bulleted and
numbered lists with nesting, quotes, code styles, bold, italic,
underline, strikethrough, links (including HYPERLINK fields) and
images, which are stored as attachments of the new page. Tables come in
as one paragraph per row, as in HTML import.
- Notion export (.zip, Markdown & CSV or HTML, up to 100 MB and 2000
pages, split exports included): rebuilds the page tree, points links
between the pages (relative and notion.so ones) at the new pages, and
stores images and files as attachments. A database becomes a page that
lists its rows, with the row pages under it. The response lists the
pages made at the parent's level.
- Every file is read before any page is made, so a bad file leaves
nothing behind. Archives are capped by bytes actually unpacked, not by
the sizes they declare.
PDF export (page menu, or ?format=pdf): A4 with the Go fonts (Latin,
Polish, Greek, Cyrillic), a bookmark per heading and page numbers.
Images on the page are drawn in (JPEG as is; PNG, GIF and WebP redrawn);
images on other sites are not fetched. Diagrams become a link to their
file and Mermaid charts show their source. Emoji are left out, since the
fonts have none.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
317 lines
9.1 KiB
Go
317 lines
9.1 KiB
Go
// SPDX-License-Identifier: AGPL-3.0-or-later
|
|
|
|
package directory
|
|
|
|
import (
|
|
"bytes"
|
|
"context"
|
|
"encoding/json"
|
|
"errors"
|
|
"fmt"
|
|
"io"
|
|
"path"
|
|
"regexp"
|
|
"strings"
|
|
"unicode/utf8"
|
|
|
|
"docwell/server/internal/access"
|
|
"docwell/server/internal/apperr"
|
|
"docwell/server/internal/convert"
|
|
)
|
|
|
|
// ---- Import and export -----------------------------------------------------
|
|
|
|
// Import limits: one Markdown or HTML file, one Word file, one Notion
|
|
// export (zipped).
|
|
const (
|
|
maxImportBytes = 5 << 20
|
|
maxDocxBytes = 25 << 20
|
|
maxZipBytes = 100 << 20
|
|
// maxImportPages caps the pages one import creates.
|
|
maxImportPages = 2000
|
|
// maxPDFImage caps one image drawn into a PDF.
|
|
maxPDFImage = 20 << 20
|
|
)
|
|
|
|
// MaxImportFile is the largest file ImportPages accepts (a Notion export).
|
|
const MaxImportFile = maxZipBytes
|
|
|
|
// SetPublicURL is docwell-server's external URL; exported files link
|
|
// attachments there.
|
|
func (s *Service) SetPublicURL(u string) { s.publicURL = strings.TrimRight(u, "/") }
|
|
|
|
// Export is a page rendered as a file.
|
|
type Export struct {
|
|
Filename string
|
|
ContentType string
|
|
Body []byte
|
|
}
|
|
|
|
var unsafeFilename = regexp.MustCompile(`[^\p{L}\p{N} ._-]+`)
|
|
|
|
func exportName(title, ext string) string {
|
|
name := strings.TrimSpace(unsafeFilename.ReplaceAllString(title, ""))
|
|
if name == "" {
|
|
name = "Untitled"
|
|
}
|
|
if utf8.RuneCountInString(name) > 100 {
|
|
name = string([]rune(name)[:100])
|
|
}
|
|
return name + ext
|
|
}
|
|
|
|
// ExportPage renders a page as Markdown ("markdown"), HTML ("html") or PDF
|
|
// ("pdf") (viewer).
|
|
func (s *Service) ExportPage(ctx context.Context, c access.Caller, id, format string) (Export, error) {
|
|
p, _, err := s.pageFor(ctx, c, id)
|
|
if err != nil {
|
|
return Export{}, err
|
|
}
|
|
raw, err := s.docs.Content(ctx, p.ID)
|
|
if err != nil {
|
|
return Export{}, err
|
|
}
|
|
doc, err := convert.Parse(raw)
|
|
if err != nil {
|
|
return Export{}, err
|
|
}
|
|
opts := convert.Options{FileURL: func(path string) string { return s.publicURL + path }}
|
|
switch format {
|
|
case "markdown", "md", "":
|
|
return Export{
|
|
Filename: exportName(p.Title, ".md"), ContentType: "text/markdown; charset=utf-8",
|
|
Body: []byte(convert.MarkdownPage(p.Title, doc, opts)),
|
|
}, nil
|
|
case "html":
|
|
return Export{
|
|
Filename: exportName(p.Title, ".html"), ContentType: "text/html; charset=utf-8",
|
|
Body: []byte(convert.HTMLPage(p.Title, doc, opts)),
|
|
}, nil
|
|
case "pdf":
|
|
body, err := convert.PDF(p.Title, doc, convert.PDFOptions{
|
|
Options: opts, BaseURL: s.publicURL,
|
|
Image: func(src string) ([]byte, error) { return s.pdfImage(ctx, c, src) },
|
|
})
|
|
if err != nil {
|
|
return Export{}, err
|
|
}
|
|
return Export{Filename: exportName(p.Title, ".pdf"), ContentType: "application/pdf", Body: body}, nil
|
|
}
|
|
return Export{}, apperr.InvalidFields(map[string]string{"format": "Format must be markdown, html or pdf."})
|
|
}
|
|
|
|
// pdfImage loads an attachment the caller can read for a PDF export. Images
|
|
// on other sites are not fetched: the server would make requests on a
|
|
// reader's behalf to wherever a document points.
|
|
func (s *Service) pdfImage(ctx context.Context, c access.Caller, src string) ([]byte, error) {
|
|
id, ok := strings.CutPrefix(src, FileURL(""))
|
|
if !ok || !validID(id) {
|
|
return nil, errors.New("not an attachment")
|
|
}
|
|
f, err := s.OpenAttachment(ctx, c, id, nil)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
defer func() { _ = f.Body.Close() }()
|
|
if !strings.HasPrefix(f.Mime, "image/") {
|
|
return nil, errors.New("not an image")
|
|
}
|
|
data, err := io.ReadAll(io.LimitReader(f.Body, maxPDFImage+1))
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
if len(data) > maxPDFImage {
|
|
return nil, errors.New("image too large")
|
|
}
|
|
return data, nil
|
|
}
|
|
|
|
// ImportFile is one uploaded document.
|
|
type ImportFile struct {
|
|
Name string
|
|
Data []byte
|
|
}
|
|
|
|
// importBatch is what one file turns into: pages (parents first, linking to
|
|
// each other with convert.PageRef) and the files they use (convert.AssetRef).
|
|
type importBatch struct {
|
|
pages []convert.NotionPage
|
|
assets []convert.Asset
|
|
}
|
|
|
|
// ImportPages creates pages from files under parent ("" = top level)
|
|
// (editor) and returns the pages made at that level. Markdown (.md,
|
|
// .markdown, .txt), HTML (.html, .htm) and Word (.docx) files become a page
|
|
// each; a leading level-1 heading (or Word title) becomes the title,
|
|
// otherwise the file name does. A .zip is read as a Notion export and keeps
|
|
// its page tree, links between its pages and its images and files.
|
|
func (s *Service) ImportPages(ctx context.Context, c access.Caller, spaceID, parent string, files []ImportFile) ([]Page, error) {
|
|
a, rules, err := s.spaceRules(ctx, c, spaceID)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
if err := access.CreatePageUnder(a.role, rules.role(parent), parent == ""); err != nil {
|
|
return nil, err
|
|
}
|
|
if len(files) == 0 {
|
|
return nil, apperr.InvalidFields(map[string]string{"file": "Choose at least one file."})
|
|
}
|
|
// Everything is read before the first page is made, so a bad file
|
|
// leaves nothing half imported.
|
|
var batches []importBatch
|
|
total := 0
|
|
for _, f := range files {
|
|
b, err := readImport(f)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
if total += len(b.pages); total > maxImportPages {
|
|
return nil, apperr.InvalidFields(map[string]string{"file": fmt.Sprintf("Import at most %d pages at once.", maxImportPages)})
|
|
}
|
|
batches = append(batches, b)
|
|
}
|
|
|
|
out := []Page{}
|
|
for _, b := range batches {
|
|
created := make([]Page, len(b.pages))
|
|
for i, p := range b.pages {
|
|
under := parent
|
|
if p.Parent >= 0 {
|
|
under = created[p.Parent].ID
|
|
}
|
|
title := p.Title
|
|
if len(title) > 500 {
|
|
title = title[:500]
|
|
}
|
|
page, err := s.CreatePage(ctx, c, a.space.ID, CreatePageInput{Parent: under, Title: title})
|
|
if err != nil {
|
|
return out, err
|
|
}
|
|
created[i] = page
|
|
if p.Parent < 0 {
|
|
out = append(out, page)
|
|
}
|
|
}
|
|
// Files go to the first page that uses them.
|
|
stored := map[string]string{}
|
|
for i, p := range b.pages {
|
|
var uploadErr error
|
|
doc := convert.RewriteURLs(p.Doc, func(u string) string {
|
|
if n, ok := refIndex(u, "page:"); ok && n < len(created) {
|
|
return "/p/" + created[n].ID
|
|
}
|
|
n, ok := refIndex(u, "asset:")
|
|
if !ok {
|
|
return u
|
|
}
|
|
if url, done := stored[u]; done {
|
|
return url
|
|
}
|
|
if n >= len(b.assets) || uploadErr != nil {
|
|
return ""
|
|
}
|
|
att, err := s.UploadAttachment(ctx, c, created[i].ID, b.assets[n].Name, bytes.NewReader(b.assets[n].Data))
|
|
if err != nil {
|
|
uploadErr = err
|
|
return ""
|
|
}
|
|
stored[u] = att.URL
|
|
return att.URL
|
|
})
|
|
if uploadErr != nil {
|
|
return out, uploadErr
|
|
}
|
|
raw, err := json.Marshal(doc)
|
|
if err != nil {
|
|
return out, err
|
|
}
|
|
if err := s.docs.Replace(ctx, created[i].ID, c.ID, raw, "import"); err != nil {
|
|
return out, err
|
|
}
|
|
}
|
|
}
|
|
return out, nil
|
|
}
|
|
|
|
// refIndex reads the number of a "page:N" or "asset:N" placeholder.
|
|
func refIndex(u, prefix string) (int, bool) {
|
|
rest, ok := strings.CutPrefix(u, prefix)
|
|
if !ok || rest == "" || len(rest) > 6 {
|
|
return 0, false
|
|
}
|
|
n := 0
|
|
for _, r := range rest {
|
|
if r < '0' || r > '9' {
|
|
return 0, false
|
|
}
|
|
n = n*10 + int(r-'0')
|
|
}
|
|
return n, true
|
|
}
|
|
|
|
// readImport converts one uploaded file.
|
|
func readImport(f ImportFile) (importBatch, error) {
|
|
bad := func(msg string) (importBatch, error) {
|
|
return importBatch{}, apperr.InvalidFields(map[string]string{"file": f.Name + msg})
|
|
}
|
|
name := path.Base(strings.ReplaceAll(f.Name, "\\", "/"))
|
|
ext := strings.ToLower(path.Ext(name))
|
|
page := func(doc convert.Node, assets []convert.Asset) importBatch {
|
|
title, body := convert.Title(doc)
|
|
if strings.TrimSpace(title) == "" {
|
|
title = strings.TrimSuffix(name, path.Ext(name))
|
|
}
|
|
if len(body.Content) == 0 {
|
|
body.Content = []convert.Node{{Type: "paragraph"}}
|
|
}
|
|
return importBatch{pages: []convert.NotionPage{{Title: strings.TrimSpace(title), Parent: -1, Doc: body}}, assets: assets}
|
|
}
|
|
switch ext {
|
|
case ".md", ".markdown", ".txt", ".html", ".htm":
|
|
if len(f.Data) > maxImportBytes {
|
|
return bad(" is larger than 5 MB.")
|
|
}
|
|
if !utf8.Valid(f.Data) {
|
|
return bad(" is not UTF-8 text.")
|
|
}
|
|
var doc convert.Node
|
|
var err error
|
|
if ext == ".html" || ext == ".htm" {
|
|
doc, err = convert.FromHTML(string(f.Data))
|
|
} else {
|
|
doc, err = convert.FromMarkdown(string(f.Data))
|
|
}
|
|
if err != nil {
|
|
return bad(" could not be read.")
|
|
}
|
|
return page(doc, nil), nil
|
|
case ".docx":
|
|
if len(f.Data) > maxDocxBytes {
|
|
return bad(" is larger than 25 MB.")
|
|
}
|
|
doc, assets, err := convert.FromDOCX(f.Data)
|
|
if errors.Is(err, convert.ErrTooLarge) {
|
|
return bad(" holds a part larger than 50 MB.")
|
|
}
|
|
if err != nil {
|
|
return bad(" is not a Word document (.docx).")
|
|
}
|
|
return page(doc, assets), nil
|
|
case ".zip":
|
|
if len(f.Data) > maxZipBytes {
|
|
return bad(" is larger than 100 MB.")
|
|
}
|
|
pages, assets, err := convert.ReadNotion(f.Data)
|
|
switch {
|
|
case errors.Is(err, convert.ErrNotNotion):
|
|
return bad(" is not a Notion export: it holds no Markdown, HTML or CSV pages.")
|
|
case errors.Is(err, convert.ErrTooLarge):
|
|
return bad(" unpacks to more than 512 MB, or holds a file larger than 50 MB.")
|
|
case err != nil:
|
|
return bad(" could not be read: " + err.Error())
|
|
}
|
|
return importBatch{pages: pages, assets: assets}, nil
|
|
}
|
|
return bad(": only Markdown, HTML, Word (.docx) and Notion export (.zip) files can be imported.")
|
|
}
|