// SPDX-License-Identifier: AGPL-3.0-or-later package convert // Confluence: a space exported as HTML (Space settings → Export space → // HTML) is a zip with one folder holding index.html (the space's page // tree), one HTML file per page, attachments// and the // export's styles. The page tree comes from index.html (or, for a page it // leaves out, the page's breadcrumbs); each page's #main-content is // cleaned of Confluence's macro markup (info panels, code, expand, // task lists, status lozenges, emoticons) into HTML FromHTML reads, and // files listed under the page's Attachments become links at its end. import ( "archive/zip" "bytes" "errors" "fmt" "path" "regexp" "sort" "strings" "unicode/utf8" "golang.org/x/net/html" "golang.org/x/net/html/atom" ) // VaultConfluence is a Confluence space export (HTML). const VaultConfluence VaultKind = "confluence" // ErrNoConfluence is returned for a zip that is not a Confluence HTML export. var ErrNoConfluence = errors.New("the archive is not a Confluence HTML export") // isConfluence reports whether the names in a zip look like a Confluence // HTML export: a folder with index.html and styles/site.css. func isConfluence(names []string) bool { has := map[string]bool{} for _, n := range names { has[n] = true } for _, n := range names { if path.Base(n) == "index.html" && has[path.Join(path.Dir(n), "styles", "site.css")] { return true } } return false } // ReadConfluence reads a Confluence space export. Pages come parents first. func ReadConfluence(data []byte) ([]NotionPage, []Asset, error) { n := ¬ionReader{files: map[string]*zip.File{}, assetAt: map[string]string{}, pageAt: map[string]int{}} if err := n.open(data, false); err != nil { return nil, nil, err } // The export's folder: the one with index.html next to styles/site.css. root := "" names := make([]string, 0, len(n.files)) for name := range n.files { names = append(names, name) } sort.Strings(names) for _, name := range names { if path.Base(name) == "index.html" { if _, ok := n.files[path.Join(path.Dir(name), "styles", "site.css")]; ok { root = path.Dir(name) break } } } if root == "" { return nil, nil, ErrNoConfluence } index := path.Join(root, "index.html") var files []string for _, name := range names { if path.Dir(name) == root && name != index && strings.EqualFold(path.Ext(name), ".html") { files = append(files, name) } } if len(files) == 0 { return nil, nil, ErrNoConfluence } if len(files) > maxNotionPages { return nil, nil, fmt.Errorf("the export has more than %d pages", maxNotionPages) } // The page tree from index.html: each listed page's parent and order. parentFile := map[string]string{} order := map[string]int{} if raw, err := n.read(n.files[index]); err == nil { if doc, err := html.Parse(bytes.NewReader(raw)); err == nil { seq := 0 var walk func(el *html.Node, parent string) walk = func(el *html.Node, parent string) { for c := el.FirstChild; c != nil; c = c.NextSibling { if c.Type != html.ElementNode { continue } if c.DataAtom == atom.Li { self := "" for a := c.FirstChild; a != nil; a = a.NextSibling { if a.Type == html.ElementNode && a.DataAtom == atom.A { self = pageFileOf(root, attrOf(a, "href")) break } } if self != "" { if _, seen := order[self]; !seen { order[self], parentFile[self] = seq, parent seq++ } walk(c, self) continue } } walk(c, parent) } } walk(doc, "") } } type page struct { file string doc *html.Node title string parent string } pages := make([]*page, 0, len(files)) byFile := map[string]*page{} for _, f := range files { raw, err := n.read(n.files[f]) if err != nil { return nil, nil, fmt.Errorf("%s: %w", f, err) } if !utf8.Valid(raw) { return nil, nil, fmt.Errorf("%s is not UTF-8 text", f) } doc, err := html.Parse(bytes.NewReader(raw)) if err != nil { return nil, nil, fmt.Errorf("%s could not be read: %w", f, err) } p := &page{file: f, doc: doc, title: confluenceTitle(doc)} if parent, ok := parentFile[f]; ok { p.parent = parent } else { p.parent = breadcrumbParent(doc, root, index) } pages = append(pages, p) byFile[f] = p } // A parent that is not in the export, or a loop, puts the page at the top. depth := map[string]int{} var depthOf func(f string, seen map[string]bool) int depthOf = func(f string, seen map[string]bool) int { if d, ok := depth[f]; ok { return d } p := byFile[f] if p.parent == "" || byFile[p.parent] == nil || seen[p.parent] { p.parent = "" depth[f] = 0 return 0 } seen[f] = true d := depthOf(p.parent, seen) + 1 depth[f] = d return d } for _, p := range pages { depthOf(p.file, map[string]bool{}) } sort.SliceStable(pages, func(i, j int) bool { a, b := pages[i], pages[j] if depth[a.file] != depth[b.file] { return depth[a.file] < depth[b.file] } oa, okA := order[a.file] ob, okB := order[b.file] if okA != okB { return okA } if oa != ob { return oa < ob } return a.file < b.file }) for i, p := range pages { n.pageAt[p.file] = i } out := make([]NotionPage, len(pages)) for i, p := range pages { body := confluenceBody(p.doc) var buf bytes.Buffer if err := html.Render(&buf, body); err != nil { return nil, nil, err } opts := ImportOptions{Resolve: func(u string) (string, bool) { return n.resolve(root, u) }} doc, err := FromHTMLWith(buf.String(), opts) if err != nil { return nil, nil, fmt.Errorf("%s could not be read: %w", p.file, err) } if n.err != nil { return nil, nil, n.err } if len(doc.Content) == 0 { doc.Content = []Node{{Type: "paragraph"}} } parent := -1 if p.parent != "" { parent = n.pageAt[p.parent] } title := p.title if title == "" { title = strings.TrimSuffix(path.Base(p.file), path.Ext(p.file)) } out[i] = NotionPage{Title: title, Parent: parent, Doc: doc} } return out, n.assets, nil } // pageFileOf is the page file a relative link in the export points to. func pageFileOf(root, href string) string { if href == "" || strings.Contains(href, ":") || strings.HasPrefix(href, "#") || strings.HasPrefix(href, "/") { return "" } if i := strings.IndexAny(href, "?#"); i >= 0 { href = href[:i] } if !strings.EqualFold(path.Ext(href), ".html") || strings.Contains(href, "/") { return "" } return path.Join(root, href) } // confluenceTitle is the page title without the space name before it. func confluenceTitle(doc *html.Node) string { t := "" if el := byID(doc, "title-text"); el != nil { t = textOf(el) } else if el := find(doc, atom.Title); el != nil { t = textOf(el) } t = strings.Join(strings.Fields(t), " ") if i := strings.Index(t, " : "); i >= 0 { t = t[i+3:] } return t } // breadcrumbParent is the last page in the breadcrumbs (the parent), if any. func breadcrumbParent(doc *html.Node, root, index string) string { bc := byID(doc, "breadcrumbs") if bc == nil { return "" } last := "" var walk func(*html.Node) walk = func(el *html.Node) { for c := el.FirstChild; c != nil; c = c.NextSibling { if c.Type == html.ElementNode && c.DataAtom == atom.A { if f := pageFileOf(root, attrOf(c, "href")); f != "" && f != index { last = f } } walk(c) } } walk(bc) return last } func byID(n *html.Node, id string) *html.Node { if n.Type == html.ElementNode && attrOf(n, "id") == id { return n } for c := n.FirstChild; c != nil; c = c.NextSibling { if found := byID(c, id); found != nil { return found } } return nil } // confluenceBody is the page's content, cleaned of Confluence's macro // markup, with its attachments listed at the end. func confluenceBody(doc *html.Node) *html.Node { main := byID(doc, "main-content") if main == nil { if main = find(doc, atom.Body); main == nil { main = doc } } out := &html.Node{Type: html.ElementNode, Data: "div", DataAtom: atom.Div} for c := main.FirstChild; c != nil; { next := c.NextSibling main.RemoveChild(c) out.AppendChild(c) c = next } cleanConfluence(out) if files := attachmentLinks(doc); len(files) > 0 { out.AppendChild(element("h2", atom.H2, nil, textNode("Attachments"))) list := element("ul", atom.Ul, nil) for _, a := range files { list.AppendChild(element("li", atom.Li, nil, element("a", atom.A, []html.Attribute{{Key: "href", Val: a.href}}, textNode(a.name)))) } out.AppendChild(list) } return out } type fileLink struct{ href, name string } // attachmentLinks are the files in the page's Attachments section. func attachmentLinks(doc *html.Node) []fileLink { h := byID(doc, "attachments") if h == nil { return nil } // The section is the header's enclosing .pageSection. sec := h.Parent for sec != nil && (sec.Type != html.ElementNode || !hasClass(sec, "pageSection")) { sec = sec.Parent } if sec == nil { return nil } var out []fileLink seen := map[string]bool{} var walk func(*html.Node) walk = func(el *html.Node) { for c := el.FirstChild; c != nil; c = c.NextSibling { if c.Type == html.ElementNode && c.DataAtom == atom.A { href := attrOf(c, "href") if strings.HasPrefix(href, "attachments/") && !seen[href] { seen[href] = true name := strings.TrimSpace(textOf(c)) if name == "" { name = path.Base(href) } out = append(out, fileLink{href: href, name: name}) } } walk(c) } } walk(sec) return out } var brushParam = regexp.MustCompile(`(?:^|;)\s*brush:\s*([A-Za-z0-9_+#.-]+)`) // confluenceLanguages maps Confluence's code brushes to editor languages. var confluenceLanguages = map[string]string{ "js": "javascript", "jscript": "javascript", "py": "python", "sh": "bash", "shell": "bash", "ps": "powershell", "c#": "csharp", "csharp": "csharp", "cpp": "cpp", "c++": "cpp", "text": "", "plain": "", "none": "", "xml": "xml", "html": "html", "yml": "yaml", "rb": "ruby", "ts": "typescript", "golang": "go", } // calloutKinds are Confluence's information macros as callout emoji and colour. var calloutKinds = map[string][2]string{ "confluence-information-macro-information": {"â„šī¸", "blue"}, "confluence-information-macro-note": {"📝", "yellow"}, "confluence-information-macro-tip": {"✅", "green"}, "confluence-information-macro-warning": {"âš ī¸", "red"}, } // cleanConfluence rewrites Confluence's markup under el into plain HTML. func cleanConfluence(el *html.Node) { for c := el.FirstChild; c != nil; { next := c.NextSibling if c.Type == html.ElementNode { if repl := confluenceNode(c); repl != c { if repl == nil { el.RemoveChild(c) } else { el.InsertBefore(repl, c) el.RemoveChild(c) cleanConfluence(repl) } c = next continue } cleanConfluence(c) } c = next } } // confluenceNode returns the replacement for one element: itself when it // stays, nil to drop it. func confluenceNode(c *html.Node) *html.Node { switch { case hasClass(c, "confluence-information-macro"): emoji, color := "💡", "gray" for _, cls := range strings.Fields(attrOf(c, "class")) { if k, ok := calloutKinds[cls]; ok { emoji, color = k[0], k[1] } } body := element("div", atom.Div, []html.Attribute{{Key: "class", Val: "callout-body"}}) if t := childWithClass(c, "title"); t != nil { body.AppendChild(element("p", atom.P, nil, element("strong", atom.Strong, nil, textNode(strings.TrimSpace(textOf(t)))))) } src := childWithClass(c, "confluence-information-macro-body") if src == nil { src = c } moveChildren(src, body) return element("aside", atom.Aside, []html.Attribute{{Key: "data-type", Val: "callout"}, {Key: "data-emoji", Val: emoji}, {Key: "data-color", Val: color}}, body) case hasClass(c, "confluence-embedded-file-wrapper"): // The picture (or file link) itself, without the wrapper. if img := find(c, atom.Img); img != nil { img.Parent.RemoveChild(img) // A thumbnail becomes the full picture. return confluenceNode(img) } return c case hasClass(c, "panel") && c.DataAtom == atom.Div && !hasClass(c, "code"): body := element("div", atom.Div, []html.Attribute{{Key: "class", Val: "callout-body"}}) if t := childWithClass(c, "panelHeader"); t != nil && strings.TrimSpace(textOf(t)) != "" { body.AppendChild(element("p", atom.P, nil, element("strong", atom.Strong, nil, textNode(strings.TrimSpace(textOf(t)))))) } src := childWithClass(c, "panelContent") if src == nil { src = c } moveChildren(src, body) return element("aside", atom.Aside, []html.Attribute{{Key: "data-type", Val: "callout"}, {Key: "data-emoji", Val: "📌"}, {Key: "data-color", Val: "gray"}}, body) case c.DataAtom == atom.Pre && (hasClass(c, "syntaxhighlighter-pre") || attrOf(c, "data-syntaxhighlighter-params") != ""): lang := "" if m := brushParam.FindStringSubmatch(attrOf(c, "data-syntaxhighlighter-params")); m != nil { lang = strings.ToLower(m[1]) if l, ok := confluenceLanguages[lang]; ok { lang = l } } code := element("code", atom.Code, nil, textNode(textOf(c))) if lang != "" { code.Attr = []html.Attribute{{Key: "class", Val: "language-" + lang}} } return element("pre", atom.Pre, nil, code) case hasClass(c, "expand-container"): title := "Details" if t := childWithClass(c, "expand-control-text"); t != nil && strings.TrimSpace(textOf(t)) != "" { title = strings.TrimSpace(textOf(t)) } d := element("details", atom.Details, nil, element("summary", atom.Summary, nil, textNode(title))) if body := childWithClass(c, "expand-content"); body != nil { moveChildren(body, d) } return d case c.DataAtom == atom.Ul && hasClass(c, "inline-task-list"): c.Attr = append(c.Attr, html.Attribute{Key: "data-type", Val: "taskList"}) for li := c.FirstChild; li != nil; li = li.NextSibling { if li.Type == html.ElementNode && li.DataAtom == atom.Li { checked := "false" if hasClass(li, "checked") { checked = "true" } li.Attr = append(li.Attr, html.Attribute{Key: "data-type", Val: "taskItem"}, html.Attribute{Key: "data-checked", Val: checked}) } } return c case c.DataAtom == atom.Img && hasClass(c, "emoticon"): alt := attrOf(c, "data-emoji-fallback") if alt == "" { alt = attrOf(c, "alt") } if alt == "" { return nil } return textNode(alt) case c.DataAtom == atom.Img && attrOf(c, "data-image-src") != "" && !strings.HasPrefix(attrOf(c, "src"), "attachments/"): // Thumbnails point at the full picture through data-image-src. src := attrOf(c, "data-image-src") if i := strings.Index(src, "attachments/"); i >= 0 { src = src[i:] } setAttr(c, "src", src) return c case hasClass(c, "status-macro") || hasClass(c, "aui-lozenge"): return element("strong", atom.Strong, nil, textNode(strings.ToUpper(strings.TrimSpace(textOf(c))))) case hasClass(c, "confluence-userlink") || hasClass(c, "user-mention"): return textNode("@" + strings.TrimSpace(textOf(c))) case attrOf(c, "id") == "likes-and-labels-container" || hasClass(c, "page-metadata") || hasClass(c, "plugin_pagetree") || c.DataAtom == atom.Script || c.DataAtom == atom.Style: return nil } return c } func childWithClass(n *html.Node, class string) *html.Node { for c := n.FirstChild; c != nil; c = c.NextSibling { if c.Type != html.ElementNode { continue } if hasClass(c, class) { return c } if found := childWithClass(c, class); found != nil { return found } } return nil } func moveChildren(from, to *html.Node) { for c := from.FirstChild; c != nil; { next := c.NextSibling from.RemoveChild(c) to.AppendChild(c) c = next } } func element(tag string, a atom.Atom, attrs []html.Attribute, children ...*html.Node) *html.Node { el := &html.Node{Type: html.ElementNode, Data: tag, DataAtom: a, Attr: attrs} for _, c := range children { if c.Parent != nil { c.Parent.RemoveChild(c) } el.AppendChild(c) } return el } func textNode(s string) *html.Node { return &html.Node{Type: html.TextNode, Data: s} } func setAttr(n *html.Node, key, val string) { for i := range n.Attr { if n.Attr[i].Key == key { n.Attr[i].Val = val return } } n.Attr = append(n.Attr, html.Attribute{Key: key, Val: val}) }