// SPDX-License-Identifier: AGPL-3.0-or-later package convert import ( "archive/zip" "bytes" "encoding/json" "errors" "image" "image/color" "image/png" "strings" "testing" ) func zipOf(t *testing.T, files map[string][]byte) []byte { t.Helper() var buf bytes.Buffer zw := zip.NewWriter(&buf) for name, data := range files { w, err := zw.Create(name) if err != nil { t.Fatal(err) } _, _ = w.Write(data) } if err := zw.Close(); err != nil { t.Fatal(err) } return buf.Bytes() } func pngOf(t *testing.T, w, h int) []byte { t.Helper() img := image.NewNRGBA(image.Rect(0, 0, w, h)) for x := range w { img.Set(x, x%h, color.NRGBA{R: 200, A: 255}) } var buf bytes.Buffer if err := png.Encode(&buf, img); err != nil { t.Fatal(err) } return buf.Bytes() } func asJSON(t *testing.T, n Node) string { t.Helper() b, err := json.Marshal(n) if err != nil { t.Fatal(err) } return string(b) } const docxNS = `xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main" ` + `xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships" ` + `xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main" ` + `xmlns:wp="http://schemas.openxmlformats.org/drawingml/2006/wordprocessingDrawing"` func TestFromDOCX(t *testing.T) { doc := ` Quarterly plan Goals Plain bold italic gone a link and a bad one HYPERLINK "https://docwell.test/field" field link one one-a two first Said someone x := 1 y := 2 NameRoleAdaLead Zażółć gęślą jaźń ` rels := ` ` styles := ` ` numbering := ` ` img := pngOf(t, 4, 3) data := zipOf(t, map[string][]byte{ "word/document.xml": []byte(doc), "word/_rels/document.xml.rels": []byte(rels), "word/styles.xml": []byte(styles), "word/numbering.xml": []byte(numbering), "word/media/image1.png": img, }) got, assets, err := FromDOCX(data) if err != nil { t.Fatal(err) } title, body := Title(got) if title != "Quarterly plan" { t.Errorf("title = %q", title) } md := Markdown(body, Options{}) for _, want := range []string{ "## Goals", "Plain **bold** *italic* ~~gone~~", "[a link](https://docwell.test/x) and a bad one", "[field link](https://docwell.test/field)", "- one\n\n - one-a\n- two", "1. first", "> Said someone", "```\nx := 1\ny := 2\n```", "![A chart](asset:0)", "| Name | Role |\n| --- | --- |\n| Ada | Lead |", "Zażółć gęślą jaźń", } { if !strings.Contains(md, want) { t.Errorf("Markdown lacks %q:\n%s", want, md) } } if len(assets) != 1 || assets[0].Name != "image1.png" || !bytes.Equal(assets[0].Data, img) { t.Errorf("assets = %+v", assets) } if _, _, err := FromDOCX([]byte("not a zip")); err == nil { t.Error("a non-zip file was read") } if _, _, err := FromDOCX(zipOf(t, map[string][]byte{"x.txt": nil})); err == nil { t.Error("a zip without word/document.xml was read") } } func TestReadNotion(t *testing.T) { const ( rootID = "0123456789abcdef0123456789abcdef" childID = "fedcba9876543210fedcba9876543210" dbID = "aaaabbbbccccddddeeeeffff00001111" rowID = "11112222333344445555666677778888" ) inner := zipOf(t, map[string][]byte{ "Team wiki " + rootID + ".md": []byte("\uFEFF# Team wiki\n\nSee [Onboarding](Team%20wiki%20" + rootID + "/Onboarding%20" + childID + ".md) " + "and [the same](https://www.notion.so/Onboarding-" + childID + "?pvs=4).\n\n![](Team%20wiki%20" + rootID + "/diagram.png)\n\n[gone](missing.pdf)\n"), "Team wiki " + rootID + "/Onboarding " + childID + ".md": []byte("# Onboarding\n\nBack to [wiki](../Team%20wiki%20" + rootID + ".md)\n"), "Team wiki " + rootID + "/diagram.png": pngOf(t, 2, 2), "Team wiki " + rootID + "/Tasks " + dbID + ".csv": []byte("Name,Status\nShip it,Done\n"), "Team wiki " + rootID + "/Tasks " + dbID + "_all.csv": []byte("Name,Status\nShip it,Done\n"), "Team wiki " + rootID + "/Tasks " + dbID + "/Ship it " + rowID + ".html": []byte( `

Ship it

` + `

Row body

`), }) pages, assets, err := ReadNotion(zipOf(t, map[string][]byte{"Export-1-Part-1.zip": inner})) if err != nil { t.Fatal(err) } byTitle := map[string]int{} for i, p := range pages { byTitle[p.Title] = i if p.Parent >= i { t.Errorf("%q comes before its parent", p.Title) } } if len(pages) != 4 { t.Fatalf("pages = %+v", pages) } root, child, db, row := byTitle["Team wiki"], byTitle["Onboarding"], byTitle["Tasks"], byTitle["Ship it"] if pages[root].Parent != -1 || pages[child].Parent != root || pages[db].Parent != root || pages[row].Parent != db { t.Errorf("tree = %+v", pages) } // Markdown export drops page: links, so look at the document itself. j := asJSON(t, pages[root].Doc) if strings.Count(j, `"href":"`+PageRef(child)+`"`) != 2 || !strings.Contains(j, `"src":"asset:0"`) || !strings.Contains(j, "gone") { t.Errorf("root = %s", j) } if strings.Contains(j, "missing.pdf") { t.Errorf("a link to a missing file was kept: %s", j) } if j := asJSON(t, pages[child].Doc); !strings.Contains(j, `"href":"`+PageRef(root)+`"`) { t.Errorf("child = %s", j) } if md := Markdown(pages[db].Doc, Options{}); !strings.Contains(md, "| Name | Status |\n| --- | --- |\n| Ship it | Done |") { t.Errorf("database = %s", md) } if md := Markdown(pages[row].Doc, Options{}); !strings.Contains(md, "Row body\n\n![](https://example.test/i.png)") { t.Errorf("row = %s", md) } if len(assets) != 1 || assets[0].Name != "diagram.png" { t.Errorf("assets = %+v", assets) } if _, _, err := ReadNotion(zipOf(t, map[string][]byte{"a.png": nil})); !errors.Is(err, ErrNotNotion) { t.Errorf("err = %v", err) } } func TestRewriteURLs(t *testing.T) { doc, err := FromMarkdown("[x](asset:0) [y](https://k.test)\n\n![a](asset:1)\n") if err != nil { t.Fatal(err) } // The safety check drops asset: links on a plain import. if strings.Contains(asJSON(t, doc), "asset:") { t.Fatalf("asset: URL kept: %s", asJSON(t, doc)) } doc = Node{Type: "doc", Content: []Node{ {Type: "paragraph", Content: []Node{{Type: "text", Text: "x", Marks: []Mark{{Type: "link", Attrs: map[string]any{"href": "asset:0"}}}}}}, {Type: "image", Attrs: map[string]any{"src": "asset:1"}}, {Type: "image", Attrs: map[string]any{"src": "asset:2"}}, }} out := RewriteURLs(doc, func(u string) string { return map[string]string{"asset:0": "/api/v1/files/a", "asset:1": "/api/v1/files/b"}[u] }) j := asJSON(t, out) if !strings.Contains(j, `"href":"/api/v1/files/a"`) || !strings.Contains(j, `"src":"/api/v1/files/b"`) || strings.Contains(j, "asset:2") { t.Errorf("rewritten = %s", j) } if strings.Contains(asJSON(t, doc), "/api/v1/files") { t.Error("RewriteURLs changed its input") } } func TestPDF(t *testing.T) { doc, err := FromMarkdown("## Plan\n\nZażółć **gęślą** *jaźń* `code` [link](/p/abc) 😀\n\n" + "- one\n - nested\n- two\n\n1. first\n\n> quoted\n\n```go\nfunc main() {}\n```\n\n---\n\n![pic](/api/v1/files/img)\n\n![missing](/api/v1/files/none)\n") if err != nil { t.Fatal(err) } doc.Content = append(doc.Content, Node{Type: "mermaid", Attrs: map[string]any{"code": "graph TD; A-->B"}}, Node{Type: "blockMath", Attrs: map[string]any{"latex": `E = mc^2`}}, Node{Type: "drawio", Attrs: map[string]any{"src": "/api/v1/files/d"}}, ) img := pngOf(t, 300, 200) var asked []string out, err := PDF("Ünïcode title", doc, PDFOptions{BaseURL: "https://docwell.test", Image: func(src string) ([]byte, error) { asked = append(asked, src) if src == "/api/v1/files/img" { return img, nil } return nil, ErrTooLarge }}) if err != nil { t.Fatal(err) } if !bytes.HasPrefix(out, []byte("%PDF-")) || !bytes.Contains(out, []byte("/Subtype /Image")) { t.Fatalf("not a PDF with an image (%d bytes)", len(out)) } if !bytes.Contains(out, []byte("https://docwell.test/p/abc")) { t.Error("the page link is not absolute") } if len(asked) != 2 { t.Errorf("images asked = %v", asked) } // An empty page still renders. if _, err := PDF("", Node{Type: "doc"}, PDFOptions{}); err != nil { t.Fatal(err) } }