Files
Docwell/Server/internal/convert/import.go
T
tajniak81andClaude Opus 5.5 ec2c1661b0 Add Word and Notion import and PDF export
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>
2026-11-01 09:55:00 +01:00

380 lines
11 KiB
Go

// SPDX-License-Identifier: AGPL-3.0-or-later
package convert
import (
"bytes"
"regexp"
"strconv"
"strings"
"github.com/yuin/goldmark"
"github.com/yuin/goldmark/extension"
"golang.org/x/net/html"
"golang.org/x/net/html/atom"
)
// ImportOptions adjust how an import reads links and images.
type ImportOptions struct {
// Resolve, when set, sees every link and image URL first (relative ones
// included). ok means the result is used as it is ("" drops the link or
// image); otherwise the URL goes through the usual safety check.
Resolve func(url string) (out string, ok bool)
}
// FromMarkdown reads CommonMark (with GitHub's strikethrough, autolinks and
// task lists, the latter as plain lists). Raw HTML in the Markdown is dropped.
func FromMarkdown(md string) (Node, error) { return FromMarkdownWith(md, ImportOptions{}) }
// FromMarkdownWith is FromMarkdown with options.
func FromMarkdownWith(md string, o ImportOptions) (Node, error) {
var buf bytes.Buffer
gm := goldmark.New(goldmark.WithExtensions(extension.Strikethrough, extension.Linkify, extension.TaskList))
if err := gm.Convert([]byte(md), &buf); err != nil {
return Node{}, err
}
return FromHTMLWith(buf.String(), o)
}
// FromHTML reads an HTML document or fragment into the Docwell schema.
// Elements the schema has no node for are unwrapped (their text is kept);
// script, style and similar elements are dropped with their content.
func FromHTML(src string) (Node, error) { return FromHTMLWith(src, ImportOptions{}) }
// FromHTMLWith is FromHTML with options.
func FromHTMLWith(src string, o ImportOptions) (Node, error) {
root, err := html.Parse(strings.NewReader(src))
if err != nil {
return Node{}, err
}
body := find(root, atom.Body)
if body == nil {
body = root
}
r := &reader{o: o}
doc := Node{Type: "doc", Content: r.blocks(body)}
if len(doc.Content) == 0 {
doc.Content = []Node{{Type: "paragraph"}}
}
return doc, nil
}
func find(n *html.Node, a atom.Atom) *html.Node {
if n.Type == html.ElementNode && n.DataAtom == a {
return n
}
for c := n.FirstChild; c != nil; c = c.NextSibling {
if f := find(c, a); f != nil {
return f
}
}
return nil
}
func attrOf(n *html.Node, key string) string {
for _, a := range n.Attr {
if a.Key == key {
return a.Val
}
}
return ""
}
var dropped = map[atom.Atom]bool{
atom.Script: true, atom.Style: true, atom.Noscript: true, atom.Template: true, atom.Iframe: true,
atom.Object: true, atom.Embed: true, atom.Head: true, atom.Title: true, atom.Svg: true, atom.Math: true,
atom.Button: true, atom.Select: true, atom.Textarea: true, atom.Input: true,
}
var blockAtoms = map[atom.Atom]bool{
atom.P: true, atom.H1: true, atom.H2: true, atom.H3: true, atom.H4: true, atom.H5: true, atom.H6: true,
atom.Ul: true, atom.Ol: true, atom.Li: true, atom.Blockquote: true, atom.Pre: true, atom.Hr: true,
atom.Div: true, atom.Section: true, atom.Article: true, atom.Main: true, atom.Header: true, atom.Footer: true,
atom.Aside: true, atom.Nav: true, atom.Figure: true, atom.Table: true, atom.Tr: true, atom.Img: true,
atom.Dl: true, atom.Dt: true, atom.Dd: true, atom.Details: true, atom.Summary: true, atom.Figcaption: true,
atom.Thead: true, atom.Tbody: true, atom.Tfoot: true, atom.Td: true, atom.Th: true,
}
type reader struct{ o ImportOptions }
// url applies the resolver and the safety check; "" means drop.
func (r *reader) url(u string) string {
if r.o.Resolve != nil {
if out, ok := r.o.Resolve(u); ok {
return out
}
}
if safeURL.MatchString(u) {
return u
}
return ""
}
// lonelyImage is the image a link holds and nothing else besides blank text
// (how Notion and many sites wrap images), or nil.
func lonelyImage(n *html.Node) *html.Node {
var img *html.Node
for c := n.FirstChild; c != nil; c = c.NextSibling {
switch {
case c.Type == html.TextNode && strings.TrimSpace(c.Data) == "":
case c.Type == html.ElementNode && c.DataAtom == atom.Img && img == nil:
img = c
default:
return nil
}
}
return img
}
type mark = Mark
// blocks reads the children of n as block nodes; loose inline content is
// gathered into paragraphs.
func (r *reader) blocks(n *html.Node) []Node {
var out []Node
var loose []Node
flush := func() {
if p := trimInline(loose); len(p) > 0 {
out = append(out, Node{Type: "paragraph", Content: p})
}
loose = nil
}
for c := n.FirstChild; c != nil; c = c.NextSibling {
if c.Type == html.ElementNode && dropped[c.DataAtom] {
continue
}
if c.Type == html.ElementNode && c.DataAtom == atom.A {
if img := lonelyImage(c); img != nil {
flush()
out = append(out, r.block(img)...)
continue
}
}
if c.Type == html.ElementNode && blockAtoms[c.DataAtom] {
flush()
out = append(out, r.block(c)...)
continue
}
loose = append(loose, r.inline(c, nil)...)
}
flush()
return out
}
var headingLevel = map[atom.Atom]int{atom.H1: 1, atom.H2: 2, atom.H3: 3, atom.H4: 3, atom.H5: 3, atom.H6: 3}
var languageClass = regexp.MustCompile(`(?:^|\s)(?:language|lang)-([A-Za-z0-9_+#.-]{1,40})`)
func (r *reader) block(n *html.Node) []Node {
switch n.DataAtom {
case atom.P, atom.Dt, atom.Dd, atom.Summary, atom.Figcaption, atom.Td, atom.Th:
// Text becomes a paragraph; images (blocks in the schema, but inside
// <p> in Markdown output) are lifted out next to it.
return r.blocks(n)
case atom.H1, atom.H2, atom.H3, atom.H4, atom.H5, atom.H6:
h := Node{Type: "heading", Attrs: map[string]any{"level": float64(headingLevel[n.DataAtom])}}
h.Content = trimInline(r.inlineChildren(n, nil))
return []Node{h}
case atom.Ul, atom.Ol:
list := Node{Type: "bulletList"}
if n.DataAtom == atom.Ol {
list.Type = "orderedList"
start := 1
if s, err := strconv.Atoi(attrOf(n, "start")); err == nil {
start = s
}
list.Attrs = map[string]any{"start": float64(start)}
}
for c := n.FirstChild; c != nil; c = c.NextSibling {
if c.Type != html.ElementNode {
continue
}
list.Content = append(list.Content, r.listItem(c))
}
if len(list.Content) == 0 {
return nil
}
return []Node{list}
case atom.Li:
return []Node{{Type: "bulletList", Content: []Node{r.listItem(n)}}}
case atom.Blockquote:
content := r.blocks(n)
if len(content) == 0 {
content = []Node{{Type: "paragraph"}}
}
return []Node{{Type: "blockquote", Content: content}}
case atom.Pre:
code := Node{Type: "codeBlock", Attrs: map[string]any{"language": nil}}
if c := find(n, atom.Code); c != nil {
if m := languageClass.FindStringSubmatch(attrOf(c, "class")); m != nil {
code.Attrs["language"] = m[1]
}
}
text := strings.TrimSuffix(textOf(n), "\n")
if code.Attrs["language"] == "mermaid" || strings.Contains(" "+attrOf(n, "class")+" ", " mermaid ") {
return []Node{{Type: "mermaid", Attrs: map[string]any{"code": text}}}
}
if text != "" {
code.Content = []Node{{Type: "text", Text: text}}
}
return []Node{code}
case atom.Hr:
return []Node{{Type: "horizontalRule"}}
case atom.Img:
src := r.url(attrOf(n, "src"))
if src == "" {
return nil
}
return []Node{{Type: "image", Attrs: map[string]any{"src": src, "alt": attrOf(n, "alt"), "title": nil}}}
case atom.Tr:
// Tables are not in the schema yet; each row becomes a paragraph of cells.
var cells []Node
for c := n.FirstChild; c != nil; c = c.NextSibling {
if c.Type == html.ElementNode && (c.DataAtom == atom.Td || c.DataAtom == atom.Th) {
if len(cells) > 0 {
cells = append(cells, Node{Type: "text", Text: " · "})
}
cells = append(cells, trimInline(r.inlineChildren(c, nil))...)
}
}
if len(cells) == 0 {
return nil
}
return []Node{{Type: "paragraph", Content: cells}}
}
// Containers (div, section, table, ...) contribute their children.
return r.blocks(n)
}
func (r *reader) listItem(n *html.Node) Node {
item := Node{Type: "listItem", Content: r.blocks(n)}
if len(item.Content) == 0 || item.Content[0].Type != "paragraph" {
item.Content = append([]Node{{Type: "paragraph"}}, item.Content...)
}
return item
}
func (r *reader) inlineChildren(n *html.Node, marks []mark) []Node {
var out []Node
for c := n.FirstChild; c != nil; c = c.NextSibling {
out = append(out, r.inline(c, marks)...)
}
return out
}
var whitespace = regexp.MustCompile(`[ \t\r\n\f]+`)
func (r *reader) inline(n *html.Node, marks []mark) []Node {
switch n.Type {
case html.TextNode:
text := whitespace.ReplaceAllString(n.Data, " ")
if text == "" {
return nil
}
return []Node{{Type: "text", Text: text, Marks: append([]mark(nil), marks...)}}
case html.ElementNode:
default:
return nil
}
if dropped[n.DataAtom] {
return nil
}
add := func(m mark) []mark {
for _, have := range marks {
if have.Type == m.Type {
return marks
}
}
return append(append([]mark(nil), marks...), m)
}
switch n.DataAtom {
case atom.Br:
return []Node{{Type: "hardBreak"}}
case atom.Strong, atom.B:
marks = add(mark{Type: "bold"})
case atom.Em, atom.I:
marks = add(mark{Type: "italic"})
case atom.S, atom.Del, atom.Strike:
marks = add(mark{Type: "strike"})
case atom.U, atom.Ins:
marks = add(mark{Type: "underline"})
case atom.Code, atom.Kbd, atom.Samp:
marks = add(mark{Type: "code"})
case atom.A:
if href := r.url(attrOf(n, "href")); href != "" {
marks = add(mark{Type: "link", Attrs: map[string]any{
"href": href, "target": "_blank", "rel": "noopener noreferrer nofollow", "class": nil,
}})
}
case atom.Img:
// An image nested in inline markup (a link, bold text) cannot be a
// block here; keep its alt text.
if alt := attrOf(n, "alt"); alt != "" {
return []Node{{Type: "text", Text: alt, Marks: append([]mark(nil), marks...)}}
}
return nil
}
// Other elements (span, and blocks inside inline content such as <p> in
// <a>) keep their text inline.
return r.inlineChildren(n, marks)
}
// trimInline drops whitespace at the edges of a paragraph and merges runs
// with equal marks.
func trimInline(nodes []Node) []Node {
for len(nodes) > 0 && nodes[0].Type == "text" && strings.TrimSpace(nodes[0].Text) == "" {
nodes = nodes[1:]
}
for len(nodes) > 0 && nodes[len(nodes)-1].Type == "text" && strings.TrimSpace(nodes[len(nodes)-1].Text) == "" {
nodes = nodes[:len(nodes)-1]
}
if len(nodes) == 0 {
return nil
}
if nodes[0].Type == "text" {
nodes[0].Text = strings.TrimLeft(nodes[0].Text, " ")
}
if last := len(nodes) - 1; nodes[last].Type == "text" {
nodes[last].Text = strings.TrimRight(nodes[last].Text, " ")
}
var out []Node
for _, n := range nodes {
if l := len(out) - 1; l >= 0 && n.Type == "text" && out[l].Type == "text" && sameMarks(out[l].Marks, n.Marks) {
out[l].Text += n.Text
continue
}
if n.Type == "text" && n.Text == "" {
continue
}
out = append(out, n)
}
return out
}
func sameMarks(a, b []mark) bool {
if len(a) != len(b) {
return false
}
for i := range a {
if a[i].Type != b[i].Type || (a[i].Type == "link" && a[i].attr("href") != b[i].attr("href")) {
return false
}
}
return true
}
func textOf(n *html.Node) string {
if n.Type == html.TextNode {
return n.Data
}
var b strings.Builder
for c := n.FirstChild; c != nil; c = c.NextSibling {
if c.Type == html.ElementNode && c.DataAtom == atom.Br {
b.WriteString("\n")
continue
}
b.WriteString(textOf(c))
}
return b.String()
}