diff --git a/Docs-Site/guide/using-docwell.md b/Docs-Site/guide/using-docwell.md
index ff3c077..7ede499 100644
--- a/Docs-Site/guide/using-docwell.md
+++ b/Docs-Site/guide/using-docwell.md
@@ -44,9 +44,17 @@ account. Turning it off makes the link stop working at once. Pages in the trash
## Import and export
-- **Export:** the **⋯** menu in the page header saves the page as Markdown or HTML.
-- **Import:** **Import** on a space's page list creates a page per Markdown (`.md`, `.txt`) or HTML file. A leading
- `# Heading` becomes the title. Up to 20 files at once.
+- **Export:** the **⋯** menu in the page header saves the page as Markdown, HTML or PDF. PDFs are A4, with a bookmark
+ per heading and the page's images. Draw.io and Excalidraw diagrams become a link to their file, and Mermaid charts
+ show their source.
+- **Import:** **Import** on a space's page list creates a page per Markdown (`.md`, `.txt`), HTML or Word (`.docx`)
+ file. A leading `# Heading`, or the Word document's title, becomes the page title. Word headings, lists, quotes,
+ links and images are kept. Up to 20 files at once.
+- **From Notion:** in Notion, choose **Settings → Export**, pick **Markdown & CSV** or **HTML** and include subpages and
+ files. Import the `.zip` you get (up to 100 MB, 2000 pages) as it is. Docwell rebuilds the page tree, keeps links
+ between the pages, and stores images and files as attachments. Each database becomes a page that lists its rows,
+ with the row pages under it. Tables in pages and databases come in as one line per row, since the editor has no
+ tables yet.
## Trash
diff --git a/Packages/api-client/src/index.ts b/Packages/api-client/src/index.ts
index 1f438c6..d580b8c 100644
--- a/Packages/api-client/src/index.ts
+++ b/Packages/api-client/src/index.ts
@@ -464,7 +464,7 @@ export function createClient(opts: ClientOptions) {
"DELETE",
`/api/v1/pages/${encodeURIComponent(id)}/access/groups/${encodeURIComponent(groupId)}`,
),
- export: (id: string, format: "markdown" | "html") =>
+ export: (id: string, format: "markdown" | "html" | "pdf") =>
download(`/api/v1/pages/${encodeURIComponent(id)}/export${query({ format })}`),
/** Records that the user opened the page, for their recent list. */
visit: (id: string) => post(`/api/v1/pages/${encodeURIComponent(id)}/visit`),
diff --git a/Packages/api-client/src/schema.d.ts b/Packages/api-client/src/schema.d.ts
index 946b127..fe13ec9 100644
--- a/Packages/api-client/src/schema.d.ts
+++ b/Packages/api-client/src/schema.d.ts
@@ -1327,8 +1327,8 @@ export interface paths {
cookie?: never;
};
/**
- * Download the page as Markdown or HTML
- * @description Attachment links point at DOCWELL_PUBLIC_URL and need a file token to open.
+ * Download the page as Markdown, HTML or PDF
+ * @description Attachment links point at DOCWELL_PUBLIC_URL and need a file token to open. PDFs are A4 with a bookmark per heading; images stored on the page are drawn in, diagrams become a link to their file and Mermaid charts show their source.
*/
get: operations["exportPage"];
put?: never;
@@ -1351,8 +1351,8 @@ export interface paths {
get?: never;
put?: never;
/**
- * Create pages from Markdown or HTML files (editor)
- * @description One page per file (.md, .markdown, .txt, .html, .htm; at most 20 files, 5 MB each, 25 MB in all). A leading level-1 heading becomes the title, otherwise the file name. HTML is reduced to what the editor supports; scripts and styles are dropped.
+ * Create pages from Markdown, HTML, Word files or a Notion export (editor)
+ * @description One page per Markdown, HTML or Word file (.md, .markdown, .txt, .html, .htm up to 5 MB; .docx up to 25 MB). A leading level-1 heading (a Word title) becomes the title, otherwise the file name. A .zip (up to 100 MB) is read as a Notion export, Markdown & CSV or HTML: its page tree, links between its pages, images and files are kept, and each database becomes a page listing its rows with the row pages under it. At most 20 files and 2000 pages at once. Content is reduced to what the editor supports; scripts and styles are dropped. The response lists the pages created at the parent's level.
*/
post: operations["importPages"];
delete?: never;
@@ -5074,7 +5074,7 @@ export interface operations {
exportPage: {
parameters: {
query?: {
- format?: "markdown" | "html";
+ format?: "markdown" | "html" | "pdf";
};
header?: never;
path: {
@@ -5092,6 +5092,7 @@ export interface operations {
content: {
"text/markdown": string;
"text/html": string;
+ "application/pdf": string;
};
};
400: components["responses"]["Error"];
@@ -5117,7 +5118,7 @@ export interface operations {
};
};
responses: {
- /** @description The created pages */
+ /** @description The pages created at the parent's level (subpages of a Notion export are under them) */
201: {
headers: {
[name: string]: unknown;
diff --git a/README.md b/README.md
index ea26c89..365fb89 100644
--- a/README.md
+++ b/README.md
@@ -10,7 +10,7 @@ What works today:
- Organizations, workspaces, groups, open and private spaces, and a page tree with drag and drop and a trash
- Real-time co-editing with live cursors and page history; a slash menu, a formatting toolbar, mentions, images and file attachments
- Inline comments, favorites, recently visited pages, full-text search with a Ctrl+K palette
-- Public read-only share links, Markdown and HTML import and export
+- Public read-only share links, Markdown and HTML import and export, Word and Notion import, PDF export
- An admin panel for users and invites, branding, sign-up rules, email, file storage (disk or S3), backups, background jobs and system health
- English and Polish, light and dark themes, phone-sized layouts
diff --git a/Server/go.mod b/Server/go.mod
index 8893cdb..dc38b80 100644
--- a/Server/go.mod
+++ b/Server/go.mod
@@ -5,10 +5,12 @@ go 1.26.0
require (
github.com/blevesearch/bleve/v2 v2.6.1
github.com/coder/websocket v1.8.15
+ github.com/go-pdf/fpdf v0.9.0
github.com/oapi-codegen/runtime v1.8.0
github.com/pquerna/otp v1.5.0
github.com/tetratelabs/wazero v1.12.0
github.com/yuin/goldmark v1.8.7
+ golang.org/x/image v0.47.0
golang.org/x/net v0.62.0
gopkg.in/yaml.v3 v3.0.1
)
@@ -34,7 +36,7 @@ require (
github.com/blevesearch/zapx/v15 v15.4.3 // indirect
github.com/blevesearch/zapx/v16 v16.3.4 // indirect
github.com/blevesearch/zapx/v17 v17.2.3 // indirect
- github.com/boombuler/barcode v1.0.1-0.20190219062509-6c824513bacc // indirect
+ github.com/boombuler/barcode v1.0.1 // indirect
github.com/dprotaso/go-yit v0.0.0-20220510233725-9ba8df137936 // indirect
github.com/getkin/kin-openapi v0.142.0 // indirect
github.com/go-openapi/jsonpointer v0.23.1 // indirect
diff --git a/Server/go.sum b/Server/go.sum
index d893b76..9aafaea 100644
--- a/Server/go.sum
+++ b/Server/go.sum
@@ -40,8 +40,9 @@ github.com/blevesearch/zapx/v16 v16.3.4 h1:hDAqA8qusZTNbPEL7//w5P65UZ2de6yhSeUaT
github.com/blevesearch/zapx/v16 v16.3.4/go.mod h1:zqkPPqs9GS9FzVWzCO3Wf1X044yWAV17+4zb+FTiEHg=
github.com/blevesearch/zapx/v17 v17.2.3 h1:UYYJPAt5b2tVxldx5h0jmv23RMsg8/UZKFVya7v92po=
github.com/blevesearch/zapx/v17 v17.2.3/go.mod h1:r7mb4QWbDQSkbAnOjCb9iCfkcrzajB4yBdJpuBIo/fE=
-github.com/boombuler/barcode v1.0.1-0.20190219062509-6c824513bacc h1:biVzkmvwrH8WK8raXaxBx6fRVTlJILwEwQGL1I/ByEI=
github.com/boombuler/barcode v1.0.1-0.20190219062509-6c824513bacc/go.mod h1:paBWMcWSl3LHKBqUq+rly7CNSldXjb2rDl3JlRe0mD8=
+github.com/boombuler/barcode v1.0.1 h1:NDBbPmhS+EqABEs5Kg3n/5ZNjy73Pz7SIV+KCeqyXcs=
+github.com/boombuler/barcode v1.0.1/go.mod h1:paBWMcWSl3LHKBqUq+rly7CNSldXjb2rDl3JlRe0mD8=
github.com/chzyer/logex v1.1.10/go.mod h1:+Ywpsq7O8HXn0nuIou7OrIPyXbp3wmkHB+jjWRnGsAI=
github.com/chzyer/readline v0.0.0-20180603132655-2972be24d48e/go.mod h1:nSuG5e5PlCu98SY8svDHJxuZscDgtXS6KTTbou5AhLI=
github.com/chzyer/test v0.0.0-20180213035817-a1ea475d72b1/go.mod h1:Q3SI9o4m/ZMnBNeIyt5eFwwo7qiLfzFZmjNmxjkiQlU=
@@ -67,6 +68,8 @@ github.com/go-openapi/swag/jsonname v0.26.0 h1:gV1NFX9M8avo0YSpmWogqfQISigCmpaiN
github.com/go-openapi/swag/jsonname v0.26.0/go.mod h1:urBBR8bZNoDYGr653ynhIx+gTeIz0ARZxHkAPktJK2M=
github.com/go-openapi/testify/v2 v2.4.2 h1:tiByHpvE9uHrrKjOszax7ZvKB7QOgizBWGBLuq0ePx4=
github.com/go-openapi/testify/v2 v2.4.2/go.mod h1:SgsVHtfooshd0tublTtJ50FPKhujf47YRqauXXOUxfw=
+github.com/go-pdf/fpdf v0.9.0 h1:PPvSaUuo1iMi9KkaAn90NuKi+P4gwMedWPHhj8YlJQw=
+github.com/go-pdf/fpdf v0.9.0/go.mod h1:oO8N111TkmKb9D7VvWGLvLJlaZUQVPM+6V42pp3iV4Y=
github.com/go-task/slim-sprig v0.0.0-20210107165309-348f09dbbbc0/go.mod h1:fyg7847qk6SyHyPtNmDHnmrv/HOrqktSC+C9fM+CJOE=
github.com/golang/protobuf v1.2.0/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U=
github.com/golang/protobuf v1.4.0-rc.1/go.mod h1:ceaxUfeHdC40wWswd/P6IGgMaK3YpKi5j83Wpe3EHw8=
@@ -165,6 +168,8 @@ go.yaml.in/yaml/v3 v3.0.4/go.mod h1:DhzuOOF2ATzADvBadXxruRBLzYTpT36CKvDb3+aBEFg=
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI=
golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto=
+golang.org/x/image v0.47.0 h1:za/8gVz++PPZqmZJBNSISICN5Rrj5zixP/8K++fgmqo=
+golang.org/x/image v0.47.0/go.mod h1:IkN5o4A7vq55vXN8FWjjnhg9Rs2GOtffqsSi9mWAKYE=
golang.org/x/mod v0.3.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA=
golang.org/x/mod v0.41.0 h1:qJmnOUb4YB+FsEuM3HcWucdZASCPGhsX6uljO6pog0c=
golang.org/x/mod v0.41.0/go.mod h1:Ek9pY8RKWXwsWvd3rQiHYtMqkjSUV+s1Rj7j4H5Ur6o=
diff --git a/Server/internal/api/api.gen.go b/Server/internal/api/api.gen.go
index fa5fbdc..a44f73e 100644
--- a/Server/internal/api/api.gen.go
+++ b/Server/internal/api/api.gen.go
@@ -475,6 +475,7 @@ func (e CreateApiTokenJSONBodyScope) Valid() bool {
const (
Html ExportPageParamsFormat = "html"
Markdown ExportPageParamsFormat = "markdown"
+ Pdf ExportPageParamsFormat = "pdf"
)
// Valid indicates whether the value is a known member of the ExportPageParamsFormat enum.
@@ -484,6 +485,8 @@ func (e ExportPageParamsFormat) Valid() bool {
return true
case Markdown:
return true
+ case Pdf:
+ return true
default:
return false
}
diff --git a/Server/internal/convert/docx.go b/Server/internal/convert/docx.go
new file mode 100644
index 0000000..0f57aaf
--- /dev/null
+++ b/Server/internal/convert/docx.go
@@ -0,0 +1,740 @@
+// SPDX-License-Identifier: AGPL-3.0-or-later
+
+package convert
+
+import (
+ "archive/zip"
+ "bytes"
+ "encoding/xml"
+ "errors"
+ "fmt"
+ "io"
+ "path"
+ "regexp"
+ "strconv"
+ "strings"
+)
+
+// Asset is a file an imported document refers to. The document uses Ref as
+// the file's URL until the importer has stored it and calls RewriteURLs.
+type Asset struct {
+ Ref string
+ Name string
+ Data []byte
+}
+
+// AssetRef is the placeholder URL of the n-th asset of an import.
+func AssetRef(n int) string { return "asset:" + strconv.Itoa(n) }
+
+// RewriteURLs replaces image sources, file and diagram URLs and link targets
+// through fn, which returns the new URL (or "" to drop a link mark, or an
+// image or file block).
+func RewriteURLs(n Node, fn func(string) string) Node {
+ switch n.Type {
+ case "image", "drawio", "excalidraw":
+ if src := n.attr("src"); src != "" {
+ n.Attrs = cloneAttrs(n.Attrs)
+ n.Attrs["src"] = fn(src)
+ }
+ case "fileAttachment":
+ if u := n.attr("url"); u != "" {
+ n.Attrs = cloneAttrs(n.Attrs)
+ n.Attrs["url"] = fn(u)
+ }
+ }
+ if len(n.Marks) > 0 {
+ marks := make([]Mark, 0, len(n.Marks))
+ for _, m := range n.Marks {
+ if m.Type == "link" {
+ href := fn(m.attr("href"))
+ if href == "" {
+ continue
+ }
+ m.Attrs = cloneAttrs(m.Attrs)
+ m.Attrs["href"] = href
+ }
+ marks = append(marks, m)
+ }
+ n.Marks = marks
+ }
+ if len(n.Content) > 0 {
+ kids := make([]Node, 0, len(n.Content))
+ for _, c := range n.Content {
+ c = RewriteURLs(c, fn)
+ if (c.Type == "image" && c.attr("src") == "") || (c.Type == "fileAttachment" && c.attr("url") == "") {
+ continue
+ }
+ kids = append(kids, c)
+ }
+ n.Content = kids
+ }
+ return n
+}
+
+func cloneAttrs(a map[string]any) map[string]any {
+ out := make(map[string]any, len(a)+1)
+ for k, v := range a {
+ out[k] = v
+ }
+ return out
+}
+
+// ---- Zip limits ------------------------------------------------------------
+
+// ErrTooLarge is returned when an archive unpacks to more than its limits.
+var ErrTooLarge = errors.New("the archive is too large")
+
+// readZipFile reads one archive entry, failing past limit bytes, so a small
+// archive cannot unpack into an unbounded amount of memory.
+func readZipFile(f *zip.File, limit int64) ([]byte, error) {
+ if f.UncompressedSize64 > uint64(limit) {
+ return nil, ErrTooLarge
+ }
+ rc, err := f.Open()
+ if err != nil {
+ return nil, err
+ }
+ defer func() { _ = rc.Close() }()
+ data, err := io.ReadAll(io.LimitReader(rc, limit+1))
+ if err != nil {
+ return nil, err
+ }
+ if int64(len(data)) > limit {
+ return nil, ErrTooLarge
+ }
+ return data, nil
+}
+
+// ---- A small XML tree ------------------------------------------------------
+
+// xnode is an XML element with attributes keyed by local name.
+type xnode struct {
+ name string
+ attrs map[string]string
+ kids []*xnode
+ text string
+}
+
+func parseXML(data []byte) (*xnode, error) {
+ d := xml.NewDecoder(bytes.NewReader(data))
+ d.Strict = false
+ root := &xnode{}
+ stack := []*xnode{root}
+ for {
+ tok, err := d.Token()
+ if err == io.EOF {
+ break
+ }
+ if err != nil {
+ return nil, err
+ }
+ top := stack[len(stack)-1]
+ switch t := tok.(type) {
+ case xml.StartElement:
+ n := &xnode{name: t.Name.Local, attrs: map[string]string{}}
+ for _, a := range t.Attr {
+ n.attrs[a.Name.Local] = a.Value
+ }
+ top.kids = append(top.kids, n)
+ stack = append(stack, n)
+ case xml.EndElement:
+ if len(stack) > 1 {
+ stack = stack[:len(stack)-1]
+ }
+ case xml.CharData:
+ top.text += string(t)
+ }
+ }
+ return root, nil
+}
+
+func (n *xnode) child(name string) *xnode {
+ if n == nil {
+ return nil
+ }
+ for _, k := range n.kids {
+ if k.name == name {
+ return k
+ }
+ }
+ return nil
+}
+
+func (n *xnode) val(name string) string {
+ if c := n.child(name); c != nil {
+ return c.attrs["val"]
+ }
+ return ""
+}
+
+// on tells whether a toggle property (, ) is set.
+func (n *xnode) on(name string) bool {
+ c := n.child(name)
+ if c == nil {
+ return false
+ }
+ v, ok := c.attrs["val"]
+ return !ok || (v != "0" && v != "false" && v != "none")
+}
+
+func (n *xnode) find(name string) *xnode {
+ if n == nil {
+ return nil
+ }
+ if n.name == name {
+ return n
+ }
+ for _, k := range n.kids {
+ if f := k.find(name); f != nil {
+ return f
+ }
+ }
+ return nil
+}
+
+// ---- DOCX ------------------------------------------------------------------
+
+// maxDocxPart caps one unpacked part of a Word file (the document XML, one image).
+const maxDocxPart = 50 << 20
+
+// FromDOCX reads a Word document. Headings, lists, quotes, code, bold,
+// italic, underline, strikethrough, links and images are kept; tables become
+// one paragraph per row, as in HTML import. Images come back as assets.
+func FromDOCX(data []byte) (Node, []Asset, error) {
+ zr, err := zip.NewReader(bytes.NewReader(data), int64(len(data)))
+ if err != nil {
+ return Node{}, nil, fmt.Errorf("not a Word file: %w", err)
+ }
+ files := map[string]*zip.File{}
+ for _, f := range zr.File {
+ files[strings.TrimPrefix(f.Name, "/")] = f
+ }
+ part := func(name string) (*xnode, error) {
+ f := files[name]
+ if f == nil {
+ return nil, nil
+ }
+ b, err := readZipFile(f, maxDocxPart)
+ if err != nil {
+ return nil, err
+ }
+ return parseXML(b)
+ }
+ body, err := part("word/document.xml")
+ if err != nil {
+ return Node{}, nil, err
+ }
+ if body == nil {
+ return Node{}, nil, errors.New("not a Word file: word/document.xml is missing")
+ }
+ d := &docxReader{files: files, rels: map[string]rel{}, styles: map[string]docxStyle{}, numFmt: map[string]bool{}}
+ if x, err := part("word/_rels/document.xml.rels"); err == nil && x != nil {
+ for _, r := range x.find("Relationships").kids {
+ d.rels[r.attrs["Id"]] = rel{target: r.attrs["Target"], external: r.attrs["TargetMode"] == "External"}
+ }
+ }
+ if x, err := part("word/styles.xml"); err == nil && x != nil {
+ d.readStyles(x)
+ }
+ if x, err := part("word/numbering.xml"); err == nil && x != nil {
+ d.readNumbering(x)
+ }
+ b := body.find("body")
+ if b == nil {
+ return Node{}, nil, errors.New("not a Word file: the document has no body")
+ }
+ doc := Node{Type: "doc", Content: d.blocks(b.kids)}
+ if d.err != nil {
+ return Node{}, nil, d.err
+ }
+ if len(doc.Content) == 0 {
+ doc.Content = []Node{{Type: "paragraph"}}
+ }
+ return doc, d.assets, nil
+}
+
+type rel struct {
+ target string
+ external bool
+}
+
+type docxStyle struct {
+ name string
+ basedOn string
+ outline int // heading level from w:outlineLvl, 0 when none
+ numID string
+}
+
+type docxReader struct {
+ files map[string]*zip.File
+ rels map[string]rel
+ styles map[string]docxStyle
+ // numFmt is true for an ordered list level, keyed "numId/ilvl".
+ numFmt map[string]bool
+ assets []Asset
+ images map[string]string // zip path -> asset ref
+ err error
+}
+
+func (d *docxReader) readStyles(x *xnode) {
+ root := x.find("styles")
+ if root == nil {
+ return
+ }
+ for _, s := range root.kids {
+ if s.name != "style" || s.attrs["type"] != "paragraph" {
+ continue
+ }
+ st := docxStyle{name: strings.ToLower(s.val("name")), basedOn: s.val("basedOn")}
+ if ppr := s.child("pPr"); ppr != nil {
+ if v, err := strconv.Atoi(ppr.val("outlineLvl")); err == nil && v < 9 {
+ st.outline = v + 1
+ }
+ if np := ppr.child("numPr"); np != nil {
+ st.numID = np.val("numId")
+ }
+ }
+ d.styles[s.attrs["styleId"]] = st
+ }
+}
+
+func (d *docxReader) readNumbering(x *xnode) {
+ root := x.find("numbering")
+ if root == nil {
+ return
+ }
+ abstract := map[string]map[string]bool{}
+ for _, a := range root.kids {
+ if a.name != "abstractNum" {
+ continue
+ }
+ levels := map[string]bool{}
+ for _, l := range a.kids {
+ if l.name == "lvl" {
+ f := l.val("numFmt")
+ levels[l.attrs["ilvl"]] = f != "" && f != "bullet" && f != "none"
+ }
+ }
+ abstract[a.attrs["abstractNumId"]] = levels
+ }
+ for _, n := range root.kids {
+ if n.name != "num" {
+ continue
+ }
+ for lvl, ordered := range abstract[n.val("abstractNumId")] {
+ d.numFmt[n.attrs["numId"]+"/"+lvl] = ordered
+ }
+ }
+}
+
+// style resolves a paragraph style through basedOn, with a depth guard
+// against style loops.
+func (d *docxReader) style(id string) (name string, outline int, numID string) {
+ for i := 0; id != "" && i < 10; i++ {
+ st, ok := d.styles[id]
+ if !ok {
+ break
+ }
+ if name == "" {
+ name = st.name
+ }
+ if outline == 0 {
+ outline = st.outline
+ }
+ if numID == "" {
+ numID = st.numID
+ }
+ id = st.basedOn
+ }
+ if name == "" {
+ name = strings.ToLower(id)
+ }
+ return name, outline, numID
+}
+
+var headingStyle = regexp.MustCompile(`^heading\s*([1-9])$`)
+
+// para is a Word paragraph after its style is known.
+type para struct {
+ kind string // paragraph, heading, quote, code, list
+ level int // heading level, or list depth
+ ordered bool
+ inline []Node
+ text string // code paragraphs keep their plain text
+ blocks []Node // images and other blocks lifted out of the paragraph
+}
+
+func (d *docxReader) blocks(nodes []*xnode) []Node {
+ var out []Node
+ var list []para
+ var code []string
+ flushList := func() {
+ for len(list) > 0 {
+ var l Node
+ l, list = buildList(list, list[0].level)
+ out = append(out, l)
+ }
+ }
+ flushCode := func() {
+ if code != nil {
+ c := Node{Type: "codeBlock", Attrs: map[string]any{"language": nil}}
+ if t := strings.Join(code, "\n"); t != "" {
+ c.Content = []Node{{Type: "text", Text: t}}
+ }
+ out = append(out, c)
+ code = nil
+ }
+ }
+ for _, n := range nodes {
+ switch n.name {
+ case "p":
+ p := d.paragraph(n)
+ if p.kind != "list" {
+ flushList()
+ }
+ if p.kind != "code" {
+ flushCode()
+ }
+ switch p.kind {
+ case "list":
+ list = append(list, p)
+ case "code":
+ code = append(code, p.text)
+ case "heading":
+ if inl := trimInline(p.inline); len(inl) > 0 {
+ out = append(out, Node{Type: "heading", Attrs: map[string]any{"level": float64(min(p.level, 3))}, Content: inl})
+ }
+ case "quote":
+ if inl := trimInline(p.inline); len(inl) > 0 {
+ q := Node{Type: "paragraph", Content: inl}
+ if l := len(out) - 1; l >= 0 && out[l].Type == "blockquote" {
+ out[l].Content = append(out[l].Content, q)
+ } else {
+ out = append(out, Node{Type: "blockquote", Content: []Node{q}})
+ }
+ }
+ default:
+ if inl := trimInline(p.inline); len(inl) > 0 {
+ out = append(out, Node{Type: "paragraph", Content: inl})
+ }
+ }
+ out = append(out, p.blocks...)
+ case "tbl":
+ flushList()
+ flushCode()
+ out = append(out, d.table(n)...)
+ case "sdt":
+ flushList()
+ flushCode()
+ out = append(out, d.blocks(n.child("sdtContent").kidsOrNil())...)
+ }
+ }
+ flushList()
+ flushCode()
+ return out
+}
+
+func (n *xnode) kidsOrNil() []*xnode {
+ if n == nil {
+ return nil
+ }
+ return n.kids
+}
+
+func (d *docxReader) table(t *xnode) []Node {
+ var out []Node
+ for _, tr := range t.kids {
+ if tr.name != "tr" {
+ continue
+ }
+ var cells []Node
+ for _, tc := range tr.kids {
+ if tc.name != "tc" {
+ continue
+ }
+ var cell []Node
+ for _, b := range d.blocks(tc.kids) {
+ if len(cell) > 0 {
+ cell = append(cell, Node{Type: "text", Text: " "})
+ }
+ if b.Type == "image" {
+ out = append(out, b)
+ continue
+ }
+ cell = append(cell, inlineOf(b)...)
+ }
+ if len(cells) > 0 {
+ cells = append(cells, Node{Type: "text", Text: " · "})
+ }
+ cells = append(cells, cell...)
+ }
+ if c := trimInline(cells); len(c) > 0 {
+ out = append(out, Node{Type: "paragraph", Content: c})
+ }
+ }
+ return out
+}
+
+// inlineOf flattens a block to its inline content.
+func inlineOf(b Node) []Node {
+ switch b.Type {
+ case "paragraph", "heading":
+ return b.Content
+ case "text", "hardBreak":
+ return []Node{b}
+ }
+ var out []Node
+ for _, c := range b.Content {
+ if len(out) > 0 && (c.Type == "paragraph" || c.Type == "listItem") {
+ out = append(out, Node{Type: "text", Text: " "})
+ }
+ out = append(out, inlineOf(c)...)
+ }
+ return out
+}
+
+func (d *docxReader) paragraph(p *xnode) para {
+ ppr := p.child("pPr")
+ name, outline, styleNum := d.style(ppr.val("pStyle"))
+ out := para{kind: "paragraph"}
+ if v, err := strconv.Atoi(ppr.val("outlineLvl")); err == nil && v < 9 {
+ outline = v + 1
+ }
+ switch {
+ case name == "title":
+ out.kind, out.level = "heading", 1
+ case headingStyle.MatchString(name):
+ lvl, _ := strconv.Atoi(headingStyle.FindStringSubmatch(name)[1])
+ out.kind, out.level = "heading", lvl
+ case outline > 0:
+ out.kind, out.level = "heading", outline
+ case name == "subtitle":
+ out.kind, out.level = "heading", 2
+ case strings.Contains(name, "quote"):
+ out.kind = "quote"
+ case strings.Contains(name, "code") || strings.Contains(name, "preformatted") || name == "source":
+ out.kind = "code"
+ }
+ numID, ilvl := styleNum, "0"
+ if np := ppr.child("numPr"); np != nil {
+ if v := np.val("numId"); v != "" {
+ numID = v
+ }
+ if v := np.val("ilvl"); v != "" {
+ ilvl = v
+ }
+ }
+ if numID != "" && numID != "0" && out.kind == "paragraph" {
+ out.kind = "list"
+ out.level, _ = strconv.Atoi(ilvl)
+ ordered, known := d.numFmt[numID+"/"+ilvl]
+ if !known {
+ ordered = strings.Contains(name, "number")
+ }
+ out.ordered = ordered
+ }
+ r := &runReader{d: d}
+ r.children(p.kids, nil)
+ out.inline, out.blocks = r.inline, r.blocks
+ if out.kind == "code" {
+ out.text = PlainText(Node{Content: r.inline})
+ }
+ return out
+}
+
+// buildList nests list paragraphs by depth, starting a new list where the
+// kind (bulleted or numbered) changes.
+func buildList(items []para, level int) (Node, []para) {
+ list := newList(items[0].ordered)
+ for len(items) > 0 {
+ it := items[0]
+ if it.level < level {
+ break
+ }
+ if it.level == level {
+ if it.ordered != (list.Type == "orderedList") {
+ break
+ }
+ p := Node{Type: "paragraph", Content: trimInline(it.inline)}
+ item := Node{Type: "listItem", Content: append([]Node{p}, it.blocks...)}
+ list.Content = append(list.Content, item)
+ items = items[1:]
+ continue
+ }
+ var sub Node
+ sub, items = buildList(items, it.level)
+ if len(list.Content) == 0 {
+ list.Content = []Node{{Type: "listItem", Content: []Node{{Type: "paragraph"}}}}
+ }
+ last := &list.Content[len(list.Content)-1]
+ last.Content = append(last.Content, sub)
+ }
+ return list, items
+}
+
+func newList(ordered bool) Node {
+ if ordered {
+ return Node{Type: "orderedList", Attrs: map[string]any{"start": float64(1)}}
+ }
+ return Node{Type: "bulletList"}
+}
+
+// runReader collects a paragraph's runs, following hyperlinks (both
+// and HYPERLINK fields) and lifting images out as blocks.
+type runReader struct {
+ d *docxReader
+ inline []Node
+ blocks []Node
+ // A complex field: instr gathers the instruction, link is its target
+ // once the field's result starts.
+ inField bool
+ instr string
+ link string
+}
+
+var hyperlinkField = regexp.MustCompile(`^\s*HYPERLINK\s+"([^"]+)"`)
+
+var monoFont = regexp.MustCompile(`(?i)courier|consolas|mono|menlo|monaco`)
+
+func (r *runReader) children(nodes []*xnode, marks []Mark) {
+ for _, n := range nodes {
+ switch n.name {
+ case "r":
+ r.run(n, marks)
+ case "hyperlink":
+ m := marks
+ if rl, ok := r.d.rels[n.attrs["id"]]; ok && rl.external && safeURL.MatchString(rl.target) {
+ m = withLink(marks, rl.target)
+ }
+ r.children(n.kids, m)
+ case "fldSimple":
+ m := marks
+ if f := hyperlinkField.FindStringSubmatch(n.attrs["instr"]); f != nil && safeURL.MatchString(f[1]) {
+ m = withLink(marks, f[1])
+ }
+ r.children(n.kids, m)
+ case "smartTag", "customXml", "ins", "sdt", "sdtContent":
+ r.children(n.kids, marks)
+ }
+ }
+}
+
+func withLink(marks []Mark, href string) []Mark {
+ return append(append([]Mark(nil), marks...), Mark{Type: "link", Attrs: map[string]any{
+ "href": href, "target": "_blank", "rel": "noopener noreferrer nofollow", "class": nil,
+ }})
+}
+
+func (r *runReader) run(n *xnode, marks []Mark) {
+ rpr := n.child("rPr")
+ add := func(t string) {
+ for _, m := range marks {
+ if m.Type == t {
+ return
+ }
+ }
+ marks = append(append([]Mark(nil), marks...), Mark{Type: t})
+ }
+ if rpr != nil {
+ if rpr.on("b") {
+ add("bold")
+ }
+ if rpr.on("i") {
+ add("italic")
+ }
+ if u := rpr.child("u"); u != nil && u.attrs["val"] != "none" && u.attrs["val"] != "0" {
+ add("underline")
+ }
+ if rpr.on("strike") || rpr.on("dstrike") {
+ add("strike")
+ }
+ if f := rpr.child("rFonts"); f != nil && monoFont.MatchString(f.attrs["ascii"]) {
+ add("code")
+ }
+ if s := strings.ToLower(rpr.val("rStyle")); strings.Contains(s, "code") {
+ add("code")
+ }
+ }
+ if r.link != "" {
+ marks = withLink(marks, r.link)
+ }
+ for _, c := range n.kids {
+ switch c.name {
+ case "fldChar":
+ switch c.attrs["fldCharType"] {
+ case "begin":
+ r.inField, r.instr, r.link = true, "", ""
+ case "separate":
+ if f := hyperlinkField.FindStringSubmatch(r.instr); f != nil && safeURL.MatchString(f[1]) {
+ r.link = f[1]
+ }
+ r.inField = false
+ case "end":
+ r.inField, r.link = false, ""
+ }
+ case "instrText":
+ if r.inField {
+ r.instr += c.text
+ }
+ case "t":
+ if !r.inField && c.text != "" {
+ r.inline = append(r.inline, Node{Type: "text", Text: c.text, Marks: marks})
+ }
+ case "tab":
+ r.inline = append(r.inline, Node{Type: "text", Text: " ", Marks: marks})
+ case "br", "cr":
+ if c.attrs["type"] != "page" && c.attrs["type"] != "column" {
+ r.inline = append(r.inline, Node{Type: "hardBreak"})
+ }
+ case "drawing", "pict":
+ r.image(c)
+ }
+ }
+}
+
+func (r *runReader) image(n *xnode) {
+ id := ""
+ if blip := n.find("blip"); blip != nil {
+ id = blip.attrs["embed"]
+ } else if im := n.find("imagedata"); im != nil {
+ id = im.attrs["id"]
+ }
+ rl, ok := r.d.rels[id]
+ if !ok || rl.external {
+ return
+ }
+ alt := ""
+ if dp := n.find("docPr"); dp != nil {
+ alt = dp.attrs["descr"]
+ }
+ ref := r.d.asset(path.Clean(path.Join("word", rl.target)))
+ if ref == "" {
+ return
+ }
+ r.blocks = append(r.blocks, Node{Type: "image", Attrs: map[string]any{"src": ref, "alt": alt, "title": nil}})
+}
+
+// asset adds a file from the archive (once) and returns its ref, or "".
+func (d *docxReader) asset(name string) string {
+ if ref, ok := d.images[name]; ok {
+ return ref
+ }
+ f := d.files[strings.TrimPrefix(name, "/")]
+ if f == nil {
+ return ""
+ }
+ data, err := readZipFile(f, maxDocxPart)
+ if err != nil {
+ if d.err == nil && errors.Is(err, ErrTooLarge) {
+ d.err = err
+ }
+ return ""
+ }
+ if d.images == nil {
+ d.images = map[string]string{}
+ }
+ ref := AssetRef(len(d.assets))
+ d.assets = append(d.assets, Asset{Ref: ref, Name: path.Base(name), Data: data})
+ d.images[name] = ref
+ return ref
+}
diff --git a/Server/internal/convert/import.go b/Server/internal/convert/import.go
index 4ed13c1..b93917e 100644
--- a/Server/internal/convert/import.go
+++ b/Server/internal/convert/import.go
@@ -14,21 +14,35 @@ import (
"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) {
+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 FromHTML(buf.String())
+ 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) {
+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
@@ -37,7 +51,7 @@ func FromHTML(src string) (Node, error) {
if body == nil {
body = root
}
- r := &reader{}
+ r := &reader{o: o}
doc := Node{Type: "doc", Content: r.blocks(body)}
if len(doc.Content) == 0 {
doc.Content = []Node{{Type: "paragraph"}}
@@ -81,7 +95,36 @@ var blockAtoms = map[atom.Atom]bool{
atom.Thead: true, atom.Tbody: true, atom.Tfoot: true, atom.Td: true, atom.Th: true,
}
-type reader struct{}
+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
@@ -100,6 +143,13 @@ func (r *reader) blocks(n *html.Node) []Node {
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)...)
@@ -171,8 +221,8 @@ func (r *reader) block(n *html.Node) []Node {
case atom.Hr:
return []Node{{Type: "horizontalRule"}}
case atom.Img:
- src := attrOf(n, "src")
- if !safeURL.MatchString(src) {
+ 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}}}
@@ -251,7 +301,7 @@ func (r *reader) inline(n *html.Node, marks []mark) []Node {
case atom.Code, atom.Kbd, atom.Samp:
marks = add(mark{Type: "code"})
case atom.A:
- if href := attrOf(n, "href"); safeURL.MatchString(href) {
+ 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,
}})
diff --git a/Server/internal/convert/notion.go b/Server/internal/convert/notion.go
new file mode 100644
index 0000000..70b622a
--- /dev/null
+++ b/Server/internal/convert/notion.go
@@ -0,0 +1,288 @@
+// SPDX-License-Identifier: AGPL-3.0-or-later
+
+package convert
+
+import (
+ "archive/zip"
+ "bytes"
+ "encoding/csv"
+ "errors"
+ "fmt"
+ "net/url"
+ "path"
+ "regexp"
+ "sort"
+ "strconv"
+ "strings"
+ "unicode/utf8"
+)
+
+// NotionPage is one page of a Notion export. Parent is the index of its
+// parent page in the list ReadNotion returns, or -1 at the top. Links to
+// other pages of the export use PageRef as their URL, files AssetRef.
+type NotionPage struct {
+ Title string
+ Parent int
+ Doc Node
+}
+
+// PageRef is the placeholder URL of the n-th page of an import.
+func PageRef(n int) string { return "page:" + strconv.Itoa(n) }
+
+// Limits of one Notion export.
+const (
+ maxNotionPages = 2000
+ maxNotionEntries = 20000
+ maxNotionFile = 50 << 20
+ maxNotionTotal = 512 << 20
+ maxNotionInner = 200 << 20
+)
+
+// ErrNotNotion is returned for an archive without Notion pages in it.
+var ErrNotNotion = errors.New("the archive holds no Markdown, HTML or CSV pages")
+
+// notionID is the id Notion appends to every exported file and folder name.
+var notionID = regexp.MustCompile(`\s+([0-9a-f]{32})$`)
+
+// notionURLID finds a page id in a notion.so / notion.site link.
+var notionURLID = regexp.MustCompile(`([0-9a-f]{32})(?:$|[?#])`)
+
+// ReadNotion reads a Notion workspace or page export ("Markdown & CSV" or
+// "HTML"), including exports split into several zip files inside one.
+// Pages come parents first. Databases become a page listing their rows,
+// with the row pages under it.
+func ReadNotion(data []byte) ([]NotionPage, []Asset, error) {
+ n := ¬ionReader{files: map[string]*zip.File{}, assetAt: map[string]string{}}
+ if err := n.open(data, true); err != nil {
+ return nil, nil, err
+ }
+
+ // Page files and their place in the tree.
+ type src struct {
+ file string
+ key string // the path without its extension, which is also its folder
+ depth int
+ }
+ var srcs []src
+ for name := range n.files {
+ ext := strings.ToLower(path.Ext(name))
+ if ext != ".md" && ext != ".html" && ext != ".htm" && ext != ".csv" {
+ continue
+ }
+ if ext == ".csv" && strings.HasSuffix(strings.TrimSuffix(name, path.Ext(name)), "_all") {
+ continue // Newer exports add a "_all" copy of every database.
+ }
+ srcs = append(srcs, src{file: name, key: strings.TrimSuffix(name, path.Ext(name)), depth: strings.Count(name, "/")})
+ }
+ if len(srcs) == 0 {
+ return nil, nil, ErrNotNotion
+ }
+ if len(srcs) > maxNotionPages {
+ return nil, nil, fmt.Errorf("the export has more than %d pages", maxNotionPages)
+ }
+ sort.Slice(srcs, func(i, j int) bool {
+ if srcs[i].depth != srcs[j].depth {
+ return srcs[i].depth < srcs[j].depth
+ }
+ return srcs[i].file < srcs[j].file
+ })
+ n.pageAt = map[string]int{}
+ n.pageByID = map[string]int{}
+ byKey := map[string]int{}
+ for i, s := range srcs {
+ n.pageAt[s.file] = i
+ byKey[s.key] = i
+ if m := notionID.FindStringSubmatch(path.Base(s.key)); m != nil {
+ n.pageByID[m[1]] = i
+ }
+ }
+
+ pages := make([]NotionPage, len(srcs))
+ for i, s := range srcs {
+ parent := -1
+ for dir := path.Dir(s.file); dir != "." && dir != "/"; dir = path.Dir(dir) {
+ if p, ok := byKey[dir]; ok {
+ parent = p
+ break
+ }
+ }
+ data, err := n.read(n.files[s.file])
+ if err != nil {
+ return nil, nil, fmt.Errorf("%s: %w", s.file, err)
+ }
+ if !utf8.Valid(data) {
+ return nil, nil, fmt.Errorf("%s is not UTF-8 text", s.file)
+ }
+ opts := ImportOptions{Resolve: func(u string) (string, bool) { return n.resolve(path.Dir(s.file), u) }}
+ var doc Node
+ switch strings.ToLower(path.Ext(s.file)) {
+ case ".md":
+ doc, err = FromMarkdownWith(string(bytes.TrimPrefix(data, []byte(utf8BOM))), opts)
+ case ".csv":
+ doc, err = notionTable(data)
+ default:
+ doc, err = FromHTMLWith(string(data), opts)
+ }
+ if err != nil {
+ return nil, nil, fmt.Errorf("%s could not be read: %w", s.file, err)
+ }
+ if n.err != nil {
+ return nil, nil, n.err
+ }
+ title, body := Title(doc)
+ if strings.TrimSpace(title) == "" {
+ title = notionName(path.Base(s.key))
+ }
+ if len(body.Content) == 0 {
+ body.Content = []Node{{Type: "paragraph"}}
+ }
+ pages[i] = NotionPage{Title: strings.TrimSpace(title), Parent: parent, Doc: body}
+ }
+ return pages, n.assets, nil
+}
+
+// notionName is a file or folder name without Notion's id.
+func notionName(name string) string {
+ name = strings.TrimSpace(notionID.ReplaceAllString(name, ""))
+ if name == "" {
+ return "Untitled"
+ }
+ return name
+}
+
+type notionReader struct {
+ files map[string]*zip.File
+ entries int
+ total int64 // bytes the archives say they hold
+ used int64 // bytes read so far
+ pageAt map[string]int // file path -> page index
+ pageByID map[string]int
+ assets []Asset
+ assetAt map[string]string // file path -> asset ref
+ err error
+}
+
+// open adds an archive's files; with nested, zip files inside it (the parts
+// of a large export) are opened too.
+func (n *notionReader) open(data []byte, nested bool) error {
+ zr, err := zip.NewReader(bytes.NewReader(data), int64(len(data)))
+ if err != nil {
+ return fmt.Errorf("not a zip file: %w", err)
+ }
+ for _, f := range zr.File {
+ if f.FileInfo().IsDir() {
+ continue
+ }
+ n.entries++
+ if n.entries > maxNotionEntries {
+ return ErrTooLarge
+ }
+ n.total += int64(f.UncompressedSize64)
+ if n.total > maxNotionTotal {
+ return ErrTooLarge
+ }
+ name := path.Clean(strings.TrimPrefix(strings.ReplaceAll(f.Name, "\\", "/"), "/"))
+ if name == "." || strings.HasPrefix(name, "../") || strings.HasPrefix(path.Base(name), ".") || strings.HasPrefix(name, "__MACOSX/") {
+ continue
+ }
+ if nested && strings.EqualFold(path.Ext(name), ".zip") {
+ inner, err := readZipFile(f, min(maxNotionInner, maxNotionTotal-n.used))
+ n.used += int64(len(inner))
+ if err != nil {
+ return err
+ }
+ if err := n.open(inner, false); err != nil {
+ return err
+ }
+ continue
+ }
+ n.files[name] = f
+ }
+ return nil
+}
+
+// read unpacks one file, keeping the export as a whole under its limit.
+func (n *notionReader) read(f *zip.File) ([]byte, error) {
+ data, err := readZipFile(f, min(maxNotionFile, maxNotionTotal-n.used))
+ n.used += int64(len(data))
+ return data, err
+}
+
+// resolve maps a link or image URL in the page file under dir.
+func (n *notionReader) resolve(dir, raw string) (string, bool) {
+ u, err := url.Parse(strings.TrimSpace(raw))
+ if err != nil {
+ return "", true
+ }
+ if u.Scheme != "" || u.Host != "" {
+ if strings.HasSuffix(u.Host, "notion.so") || strings.HasSuffix(u.Host, "notion.site") {
+ if m := notionURLID.FindStringSubmatch(strings.ReplaceAll(u.Path, "-", "")); m != nil {
+ if i, ok := n.pageByID[m[1]]; ok {
+ return PageRef(i), true
+ }
+ }
+ }
+ return "", false
+ }
+ if u.Path == "" {
+ return "", false // An anchor in the same page.
+ }
+ p := path.Clean(path.Join(dir, u.Path))
+ if i, ok := n.pageAt[p]; ok {
+ return PageRef(i), true
+ }
+ if ref, ok := n.assetAt[p]; ok {
+ return ref, true
+ }
+ f, ok := n.files[p]
+ if !ok {
+ return "", true // A file the export left out.
+ }
+ data, err := n.read(f)
+ if err != nil {
+ if n.err == nil {
+ n.err = fmt.Errorf("%s: %w", p, err)
+ }
+ return "", true
+ }
+ ref := AssetRef(len(n.assets))
+ n.assets = append(n.assets, Asset{Ref: ref, Name: path.Base(p), Data: data})
+ n.assetAt[p] = ref
+ return ref, true
+}
+
+// notionTable turns a database's CSV into paragraphs, one per row, with the
+// column names in bold first.
+func notionTable(data []byte) (Node, error) {
+ r := csv.NewReader(bytes.NewReader(bytes.TrimPrefix(data, []byte(utf8BOM))))
+ r.FieldsPerRecord = -1
+ r.LazyQuotes = true
+ rows, err := r.ReadAll()
+ if err != nil {
+ return Node{}, err
+ }
+ doc := Node{Type: "doc"}
+ for i, row := range rows {
+ var cells []Node
+ for _, cell := range row {
+ if cell = strings.TrimSpace(cell); cell == "" {
+ cell = "–"
+ }
+ if len(cells) > 0 {
+ cells = append(cells, Node{Type: "text", Text: " · "})
+ }
+ t := Node{Type: "text", Text: cell}
+ if i == 0 {
+ t.Marks = []Mark{{Type: "bold"}}
+ }
+ cells = append(cells, t)
+ }
+ if c := trimInline(cells); len(c) > 0 {
+ doc.Content = append(doc.Content, Node{Type: "paragraph", Content: c})
+ }
+ }
+ return doc, nil
+}
+
+// utf8BOM starts some exported text files.
+const utf8BOM = "\xef\xbb\xbf"
diff --git a/Server/internal/convert/pdf.go b/Server/internal/convert/pdf.go
new file mode 100644
index 0000000..14521c8
--- /dev/null
+++ b/Server/internal/convert/pdf.go
@@ -0,0 +1,447 @@
+// SPDX-License-Identifier: AGPL-3.0-or-later
+
+package convert
+
+import (
+ "bytes"
+ "fmt"
+ "image"
+ "image/draw"
+ _ "image/gif" // image.Decode reads GIF and JPEG attachments.
+ _ "image/jpeg"
+ "image/png"
+ "strconv"
+ "strings"
+
+ "github.com/go-pdf/fpdf"
+ "golang.org/x/image/font/gofont/gobold"
+ "golang.org/x/image/font/gofont/gobolditalic"
+ "golang.org/x/image/font/gofont/goitalic"
+ "golang.org/x/image/font/gofont/gomono"
+ "golang.org/x/image/font/gofont/gomonobold"
+ "golang.org/x/image/font/gofont/gomonobolditalic"
+ "golang.org/x/image/font/gofont/gomonoitalic"
+ "golang.org/x/image/font/gofont/goregular"
+ _ "golang.org/x/image/webp" // image.Decode reads WebP attachments too.
+)
+
+// PDFOptions adjust a PDF export.
+type PDFOptions struct {
+ Options
+ // BaseURL makes server paths (/p/, attachments) absolute links.
+ BaseURL string
+ // Image loads an image by its document URL; nil, or an error, leaves the
+ // image's description in its place.
+ Image func(src string) ([]byte, error)
+}
+
+// maxPDFImagePixels keeps one decoded image under about 200 MB of memory.
+const maxPDFImagePixels = 50_000_000
+
+// PDF renders a page as an A4 PDF with the title on top, a bookmark per
+// heading and page numbers. Diagrams (stored as SVG) and Mermaid charts are
+// not drawn: diagrams become a link to their file, Mermaid its source.
+func PDF(title string, doc Node, o PDFOptions) (out []byte, err error) {
+ defer func() {
+ // fpdf panics on some input instead of failing; one bad page must
+ // not take the server down.
+ if r := recover(); r != nil {
+ out, err = nil, fmt.Errorf("pdf: %v", r)
+ }
+ }()
+ f := fpdf.New("P", "mm", "A4", "")
+ for _, ft := range []struct {
+ family, style string
+ ttf []byte
+ }{
+ {"go", "", goregular.TTF}, {"go", "B", gobold.TTF}, {"go", "I", goitalic.TTF}, {"go", "BI", gobolditalic.TTF},
+ {"mono", "", gomono.TTF}, {"mono", "B", gomonobold.TTF}, {"mono", "I", gomonoitalic.TTF}, {"mono", "BI", gomonobolditalic.TTF},
+ } {
+ f.AddUTF8FontFromBytes(ft.family, ft.style, ft.ttf)
+ }
+ f.SetMargins(pdfMargin, pdfMargin, pdfMargin)
+ f.SetAutoPageBreak(true, pdfMargin)
+ f.SetTitle(pdfText(title), true)
+ f.SetCreator("Docwell", true)
+ f.AliasNbPages("")
+ f.SetFooterFunc(func() {
+ f.SetY(-12)
+ f.SetFont("go", "", 8)
+ f.SetTextColor(130, 130, 130)
+ f.CellFormat(0, 5, strconv.Itoa(f.PageNo())+" / {nb}", "", 0, "C", false, 0, "")
+ })
+ f.AddPage()
+ pageW, _ := f.GetPageSize()
+ w := &pdfWriter{f: f, o: o, width: pageW - 2*pdfMargin}
+
+ if strings.TrimSpace(title) != "" {
+ w.heading(title, 0, 22)
+ }
+ for _, n := range doc.Content {
+ w.block(n, 0, pdfGap)
+ }
+ var buf bytes.Buffer
+ if err := f.Output(&buf); err != nil {
+ return nil, err
+ }
+ return buf.Bytes(), nil
+}
+
+// Layout, in millimetres and points.
+const (
+ pdfMargin = 20.0
+ pdfGap = 3.0 // after a block
+ pdfTightGap = 1.2 // after a block in a list item
+ pdfBody = 11.0
+ pdfLine = 5.6
+ pdfIndent = 6.0
+)
+
+type pdfWriter struct {
+ f *fpdf.Fpdf
+ o PDFOptions
+ width float64
+ images int
+ quote int // depth of blockquotes, which grey the text
+}
+
+func (w *pdfWriter) at(indent float64) {
+ w.f.SetLeftMargin(pdfMargin + indent)
+ w.f.SetX(pdfMargin + indent)
+}
+
+func (w *pdfWriter) ink() {
+ if w.quote > 0 {
+ w.f.SetTextColor(95, 95, 95)
+ } else {
+ w.f.SetTextColor(25, 25, 25)
+ }
+}
+
+// link makes a document URL something a PDF reader can open, or "".
+func (w *pdfWriter) link(href string) string {
+ href = w.o.file(href)
+ if strings.HasPrefix(href, "/") && !strings.HasPrefix(href, "//") {
+ if w.o.BaseURL == "" {
+ return ""
+ }
+ href = strings.TrimRight(w.o.BaseURL, "/") + href
+ }
+ if !safeURL.MatchString(href) || strings.HasPrefix(href, "#") {
+ return ""
+ }
+ return href
+}
+
+// room starts a new page unless h millimetres fit on this one.
+func (w *pdfWriter) room(h float64) {
+ _, pageH := w.f.GetPageSize()
+ if w.f.GetY()+h > pageH-pdfMargin {
+ w.f.AddPage()
+ }
+}
+
+func (w *pdfWriter) heading(text string, level int, size float64) {
+ w.room(size*0.35 + 3*pdfLine)
+ w.at(0)
+ if level > 0 && w.f.GetY() > pdfMargin+1 {
+ w.f.Ln(2)
+ }
+ text = strings.TrimSpace(pdfText(text))
+ w.f.Bookmark(text, max(level-1, 0), -1)
+ w.f.SetFont("go", "B", size)
+ w.ink()
+ w.f.MultiCell(w.width, size*0.45, text, "", "L", false)
+ w.f.Ln(pdfGap)
+}
+
+var pdfHeadingSize = map[int]float64{1: 18, 2: 15, 3: 13}
+
+func (w *pdfWriter) block(n Node, indent, gap float64) {
+ switch n.Type {
+ case "paragraph":
+ w.at(indent)
+ w.inline(n.Content, "", pdfBody)
+ w.f.Ln(pdfLine)
+ w.f.Ln(gap)
+ case "heading":
+ level := min(max(n.intAttr("level", 1), 1), 3)
+ w.heading(PlainText(n), level, pdfHeadingSize[level])
+ case "bulletList", "orderedList":
+ start := n.intAttr("start", 1)
+ for i, item := range n.Content {
+ marker := "•"
+ if n.Type == "orderedList" {
+ marker = strconv.Itoa(start+i) + "."
+ }
+ w.room(pdfLine)
+ w.at(indent)
+ w.f.SetFont("go", "", pdfBody)
+ w.ink()
+ w.f.CellFormat(pdfIndent, pdfLine, marker, "", 0, "L", false, 0, "")
+ for j, c := range item.Content {
+ g := pdfTightGap
+ if j == len(item.Content)-1 && i == len(n.Content)-1 {
+ g = gap
+ }
+ if j == 0 && c.Type == "paragraph" {
+ // Text starts after the marker, on its line.
+ w.f.SetLeftMargin(pdfMargin + indent + pdfIndent)
+ w.inline(c.Content, "", pdfBody)
+ w.f.Ln(pdfLine)
+ w.f.Ln(g)
+ continue
+ }
+ if j == 0 {
+ w.f.Ln(pdfLine)
+ }
+ w.block(c, indent+pdfIndent, g)
+ }
+ if len(item.Content) == 0 {
+ w.f.Ln(pdfLine)
+ }
+ }
+ case "blockquote":
+ page, top := w.f.PageNo(), w.f.GetY()
+ w.quote++
+ for i, c := range n.Content {
+ g := pdfTightGap
+ if i == len(n.Content)-1 {
+ g = 0
+ }
+ w.block(c, indent+pdfIndent, g)
+ }
+ w.quote--
+ if w.f.PageNo() != page {
+ top = pdfMargin
+ }
+ x := pdfMargin + indent + 1.5
+ w.f.SetDrawColor(200, 200, 200)
+ w.f.SetLineWidth(0.8)
+ w.f.Line(x, top, x, w.f.GetY())
+ w.f.Ln(gap)
+ case "codeBlock":
+ w.code(PlainText(n), indent, "")
+ w.f.Ln(gap)
+ case "mermaid":
+ w.code(n.attr("code"), indent, "Mermaid")
+ w.f.Ln(gap)
+ case "blockMath":
+ w.at(indent)
+ w.f.SetFont("mono", "", 10)
+ w.ink()
+ w.f.MultiCell(w.width-indent, pdfLine, pdfText(n.attr("latex")), "", "C", false)
+ w.f.Ln(gap)
+ case "horizontalRule":
+ w.room(4)
+ y := w.f.GetY() + 1.5
+ w.f.SetDrawColor(210, 210, 210)
+ w.f.SetLineWidth(0.3)
+ w.f.Line(pdfMargin+indent, y, pdfMargin+w.width, y)
+ w.f.SetY(y + 1.5)
+ w.f.Ln(gap)
+ case "image":
+ w.image(n.attr("src"), n.attr("alt"), indent)
+ w.f.Ln(gap)
+ case "drawio", "excalidraw":
+ label := "Draw.io diagram"
+ if n.Type == "excalidraw" {
+ label = "Excalidraw drawing"
+ }
+ w.note(label, n.attr("src"), indent)
+ w.f.Ln(gap)
+ case "fileAttachment":
+ w.note("Attachment: "+n.attr("name"), n.attr("url"), indent)
+ w.f.Ln(gap)
+ case "tableOfContents":
+ // PDF readers list the headings as bookmarks.
+ default:
+ for _, c := range n.Content {
+ w.block(c, indent, gap)
+ }
+ }
+}
+
+// inline writes text runs from the current position, wrapping at the
+// current left margin.
+func (w *pdfWriter) inline(nodes []Node, style string, size float64) {
+ for _, n := range nodes {
+ switch n.Type {
+ case "text":
+ family, st, href := "go", style, ""
+ for _, m := range n.Marks {
+ switch m.Type {
+ case "bold":
+ st += "B"
+ case "italic":
+ st += "I"
+ case "underline":
+ st += "U"
+ case "strike":
+ st += "S"
+ case "code":
+ family = "mono"
+ case "link":
+ href = w.link(m.attr("href"))
+ }
+ }
+ fsize := size
+ if family == "mono" {
+ fsize = size - 1
+ }
+ if href != "" && !strings.Contains(st, "U") {
+ st += "U"
+ }
+ w.f.SetFont(family, pdfStyle(st), fsize)
+ if href != "" {
+ w.f.SetTextColor(37, 99, 235)
+ w.f.WriteLinkString(pdfLine, pdfText(n.Text), href)
+ } else {
+ w.ink()
+ w.f.Write(pdfLine, pdfText(n.Text))
+ }
+ case "hardBreak":
+ w.f.Ln(pdfLine)
+ case "inlineMath":
+ w.f.SetFont("mono", pdfStyle(style), size-1)
+ w.ink()
+ w.f.Write(pdfLine, pdfText(n.attr("latex")))
+ case "mention":
+ w.f.SetFont("go", pdfStyle(style+"B"), size)
+ w.ink()
+ w.f.Write(pdfLine, pdfText("@"+mentionLabel(n)))
+ default:
+ w.inline(n.Content, style, size)
+ }
+ }
+}
+
+// pdfText keeps characters fpdf can encode: it panics past U+FFFF, and the
+// Go fonts have no emoji anyway, so those are left out.
+func pdfText(s string) string {
+ return strings.Map(func(r rune) rune {
+ if r > 0xFFFF || r == 0xFE0F {
+ return -1
+ }
+ return r
+ }, s)
+}
+
+// pdfStyle orders and deduplicates style letters the way fpdf wants them.
+func pdfStyle(s string) string {
+ var out string
+ for _, c := range "BIUS" {
+ if strings.ContainsRune(s, c) {
+ out += string(c)
+ }
+ }
+ return out
+}
+
+func (w *pdfWriter) code(text string, indent float64, label string) {
+ w.at(indent)
+ if label != "" {
+ w.room(2 * pdfLine)
+ w.f.SetFont("go", "B", 8)
+ w.f.SetTextColor(130, 130, 130)
+ w.f.CellFormat(0, 4.5, label, "", 1, "L", false, 0, "")
+ w.at(indent)
+ }
+ w.f.SetFont("mono", "", 9.5)
+ w.ink()
+ w.f.SetFillColor(244, 244, 241)
+ text = pdfText(strings.ReplaceAll(text, "\t", " "))
+ if text == "" {
+ text = " "
+ }
+ w.f.MultiCell(w.width-indent, 4.6, text, "", "L", true)
+}
+
+// note is a line of grey text standing in for something the PDF cannot
+// show, linking to it where possible.
+func (w *pdfWriter) note(text, href string, indent float64) {
+ text = pdfText(text)
+ w.at(indent)
+ w.f.SetFont("go", "I", 10)
+ if link := w.link(href); link != "" {
+ w.f.SetTextColor(37, 99, 235)
+ w.f.WriteLinkString(pdfLine, text, link)
+ } else {
+ w.f.SetTextColor(120, 120, 120)
+ w.f.Write(pdfLine, text)
+ }
+ w.f.Ln(pdfLine)
+}
+
+func (w *pdfWriter) image(src, alt string, indent float64) {
+ placeholder := func() {
+ text := "Image"
+ if alt != "" {
+ text += ": " + alt
+ }
+ w.note("["+text+"]", src, indent)
+ }
+ if w.o.Image == nil || src == "" {
+ placeholder()
+ return
+ }
+ data, err := w.o.Image(src)
+ if err != nil {
+ placeholder()
+ return
+ }
+ kind, body, px, py, err := pdfImage(data)
+ if err != nil {
+ placeholder()
+ return
+ }
+ _, pageH := w.f.GetPageSize()
+ // 96 pixels to the inch, shrunk to fit the column and a page.
+ iw, ih := float64(px)*25.4/96, float64(py)*25.4/96
+ if maxW := w.width - indent; iw > maxW {
+ iw, ih = maxW, ih*maxW/iw
+ }
+ if maxH := pageH - 2*pdfMargin - 10; ih > maxH {
+ iw, ih = iw*maxH/ih, maxH
+ }
+ w.room(ih)
+ w.images++
+ name := "img" + strconv.Itoa(w.images)
+ opts := fpdf.ImageOptions{ImageType: kind}
+ w.f.RegisterImageOptionsReader(name, opts, bytes.NewReader(body))
+ if w.f.Err() {
+ w.f.ClearError()
+ placeholder()
+ return
+ }
+ y := w.f.GetY()
+ w.f.ImageOptions(name, pdfMargin+indent, y, iw, ih, false, opts, 0, "")
+ w.f.SetY(y + ih)
+}
+
+// pdfImage checks an image and hands JPEGs through as they are; other
+// formats (PNG, GIF, WebP) are drawn again as plain 8-bit PNGs, which fpdf
+// always reads (it refuses interlaced and 16-bit PNGs).
+func pdfImage(data []byte) (kind string, body []byte, w, h int, err error) {
+ cfg, format, err := image.DecodeConfig(bytes.NewReader(data))
+ if err != nil {
+ return "", nil, 0, 0, err
+ }
+ if cfg.Width <= 0 || cfg.Height <= 0 || cfg.Width*cfg.Height > maxPDFImagePixels {
+ return "", nil, 0, 0, fmt.Errorf("image is %dx%d", cfg.Width, cfg.Height)
+ }
+ if format == "jpeg" {
+ return "JPG", data, cfg.Width, cfg.Height, nil
+ }
+ img, _, err := image.Decode(bytes.NewReader(data))
+ if err != nil {
+ return "", nil, 0, 0, err
+ }
+ rgba := image.NewNRGBA(img.Bounds())
+ draw.Draw(rgba, rgba.Bounds(), img, img.Bounds().Min, draw.Src)
+ var buf bytes.Buffer
+ if err := png.Encode(&buf, rgba); err != nil {
+ return "", nil, 0, 0, err
+ }
+ return "PNG", buf.Bytes(), cfg.Width, cfg.Height, nil
+}
diff --git a/Server/internal/convert/transfer_test.go b/Server/internal/convert/transfer_test.go
new file mode 100644
index 0000000..50f92e8
--- /dev/null
+++ b/Server/internal/convert/transfer_test.go
@@ -0,0 +1,262 @@
+// SPDX-License-Identifier: AGPL-3.0-or-later
+
+package convert
+
+import (
+ "archive/zip"
+ "bytes"
+ "encoding/json"
+ "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```",
+ "",
+ "Name · Role\n\nAda · 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\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(
+ `` +
+ `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\nShip it · Done") {
+ t.Errorf("database = %s", md)
+ }
+ if md := Markdown(pages[row].Doc, Options{}); !strings.Contains(md, "Row body\n\n") {
+ 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})); err != ErrNotNotion {
+ t.Errorf("err = %v", err)
+ }
+}
+
+func TestRewriteURLs(t *testing.T) {
+ doc, err := FromMarkdown("[x](asset:0) [y](https://k.test)\n\n\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\n\n\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)
+ }
+}
diff --git a/Server/internal/directory/transfer.go b/Server/internal/directory/transfer.go
index 18f6dfb..c163f03 100644
--- a/Server/internal/directory/transfer.go
+++ b/Server/internal/directory/transfer.go
@@ -3,8 +3,12 @@
package directory
import (
+ "bytes"
"context"
"encoding/json"
+ "errors"
+ "fmt"
+ "io"
"path"
"regexp"
"strings"
@@ -17,8 +21,20 @@ import (
// ---- Import and export -----------------------------------------------------
-// maxImportBytes caps one imported file.
-const maxImportBytes = 5 << 20
+// 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.
@@ -44,7 +60,8 @@ func exportName(title, ext string) string {
return name + ext
}
-// ExportPage renders a page as Markdown ("markdown") or HTML ("html") (viewer).
+// 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 {
@@ -70,8 +87,43 @@ func (s *Service) ExportPage(ctx context.Context, c access.Caller, id, format st
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 or html."})
+ 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.
@@ -80,9 +132,19 @@ type ImportFile struct {
Data []byte
}
-// ImportPages creates a page per file under parent ("" = top level) (editor).
-// Markdown (.md, .markdown, .txt) and HTML (.html, .htm) are understood; a
-// leading level-1 heading becomes the title, otherwise the file name does.
+// 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 {
@@ -94,59 +156,161 @@ func (s *Service) ImportPages(ctx context.Context, c access.Caller, spaceID, par
if len(files) == 0 {
return nil, apperr.InvalidFields(map[string]string{"file": "Choose at least one file."})
}
- type parsed struct {
- title string
- doc convert.Node
- }
- var docs []parsed
+ // 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 {
- if len(f.Data) > maxImportBytes {
- return nil, apperr.InvalidFields(map[string]string{"file": f.Name + " is larger than 5 MB."})
- }
- if !utf8.Valid(f.Data) {
- return nil, apperr.InvalidFields(map[string]string{"file": f.Name + " is not UTF-8 text."})
- }
- ext := strings.ToLower(path.Ext(f.Name))
- var doc convert.Node
- switch ext {
- case ".md", ".markdown", ".txt":
- doc, err = convert.FromMarkdown(string(f.Data))
- case ".html", ".htm":
- doc, err = convert.FromHTML(string(f.Data))
- default:
- return nil, apperr.InvalidFields(map[string]string{"file": f.Name + ": only Markdown and HTML files can be imported."})
- }
+ b, err := readImport(f)
if err != nil {
- return nil, apperr.InvalidFields(map[string]string{"file": f.Name + " could not be read."})
+ 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 title == "" {
- title = strings.TrimSuffix(path.Base(strings.ReplaceAll(f.Name, "\\", "/")), path.Ext(f.Name))
+ if strings.TrimSpace(title) == "" {
+ title = strings.TrimSuffix(name, path.Ext(name))
}
if len(body.Content) == 0 {
body.Content = []convert.Node{{Type: "paragraph"}}
}
- docs = append(docs, parsed{title: strings.TrimSpace(title), doc: body})
+ return importBatch{pages: []convert.NotionPage{{Title: strings.TrimSpace(title), Parent: -1, Doc: body}}, assets: assets}
}
-
- out := make([]Page, 0, len(docs))
- for _, d := range docs {
- title := d.title
- if len(title) > 500 {
- title = title[:500]
+ 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))
}
- page, err := s.CreatePage(ctx, c, a.space.ID, CreatePageInput{Parent: parent, Title: title})
if err != nil {
- return out, err
+ 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.")
}
- raw, err := json.Marshal(d.doc)
if err != nil {
- return out, err
+ return bad(" is not a Word document (.docx).")
}
- if err := s.docs.Replace(ctx, page.ID, c.ID, raw, "import"); err != nil {
- return out, err
+ return page(doc, assets), nil
+ case ".zip":
+ if len(f.Data) > maxZipBytes {
+ return bad(" is larger than 100 MB.")
}
- out = append(out, page)
+ 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 out, nil
+ return bad(": only Markdown, HTML, Word (.docx) and Notion export (.zip) files can be imported.")
}
diff --git a/Server/internal/httpapi/transfer.go b/Server/internal/httpapi/transfer.go
index 31a04c4..9420e5b 100644
--- a/Server/internal/httpapi/transfer.go
+++ b/Server/internal/httpapi/transfer.go
@@ -19,9 +19,10 @@ type TransferService interface {
ImportPages(ctx context.Context, c access.Caller, spaceID, parent string, files []directory.ImportFile) ([]directory.Page, error)
}
-// maxImportRequest caps one import request: each file may be 5 MB, and up to
-// 20 files may come at once, but not more than 25 MB in all.
-const maxImportRequest = 25 << 20
+// maxImportRequest caps one import request: up to 20 files, each within its
+// kind's limit (5 MB of text, 25 MB for Word, 100 MB for a Notion export),
+// and not more than one Notion export's worth in all.
+const maxImportRequest = directory.MaxImportFile + 1<<20
func (a *api) transferRoutes(mux *routeMux) {
mux.HandleFunc("GET /api/v1/pages/{id}/export", a.requireUser(func(w http.ResponseWriter, r *http.Request) {
@@ -39,8 +40,8 @@ func (a *api) transferRoutes(mux *routeMux) {
}))
mux.HandleFunc("POST /api/v1/spaces/{id}/import", a.requireUser(func(w http.ResponseWriter, r *http.Request) {
r.Body = http.MaxBytesReader(w, r.Body, maxImportRequest)
- if err := r.ParseMultipartForm(maxImportRequest); err != nil {
- writeJSON(w, http.StatusBadRequest, map[string]string{"error": "invalid", "message": "expected multipart/form-data up to 25 MB"})
+ if err := r.ParseMultipartForm(32 << 20); err != nil { // Larger uploads spill to temporary files.
+ writeJSON(w, http.StatusBadRequest, map[string]string{"error": "invalid", "message": "expected multipart/form-data up to 100 MB"})
return
}
defer func() { _ = r.MultipartForm.RemoveAll() }()
@@ -55,7 +56,7 @@ func (a *api) transferRoutes(mux *routeMux) {
a.writeError(w, err)
return
}
- data, err := io.ReadAll(io.LimitReader(f, 5<<20+1))
+ data, err := io.ReadAll(io.LimitReader(f, directory.MaxImportFile+1))
_ = f.Close()
if err != nil {
a.writeError(w, err)
diff --git a/Web-App/frontend/src/locales/en.json b/Web-App/frontend/src/locales/en.json
index 214e9c6..50303e2 100644
--- a/Web-App/frontend/src/locales/en.json
+++ b/Web-App/frontend/src/locales/en.json
@@ -219,6 +219,8 @@
"viewer": "Viewer"
},
"import": "Import",
+ "importing": "Importing…",
+ "importHint": "Markdown, HTML, Word (.docx) or a Notion export (.zip)",
"sharedWithYou": "Shared with you"
},
"page": {
@@ -260,6 +262,7 @@
"more": "More actions",
"exportMarkdown": "Export as Markdown",
"exportHtml": "Export as HTML",
+ "exportPdf": "Export as PDF",
"backlinks": "Linked from {n} page | Linked from {n} pages"
},
"trash": {
diff --git a/Web-App/frontend/src/locales/pl.json b/Web-App/frontend/src/locales/pl.json
index d7fbf08..83c9940 100644
--- a/Web-App/frontend/src/locales/pl.json
+++ b/Web-App/frontend/src/locales/pl.json
@@ -219,6 +219,8 @@
"viewer": "Czytelnik"
},
"import": "Importuj",
+ "importing": "Importowanie…",
+ "importHint": "Markdown, HTML, Word (.docx) lub eksport z Notion (.zip)",
"sharedWithYou": "Udostępnione Tobie"
},
"page": {
@@ -260,6 +262,7 @@
"more": "Więcej działań",
"exportMarkdown": "Eksportuj jako Markdown",
"exportHtml": "Eksportuj jako HTML",
+ "exportPdf": "Eksportuj jako PDF",
"backlinks": "Linkuje tu {n} strona | Linkują tu {n} strony | Linkuje tu {n} stron"
},
"trash": {
diff --git a/Web-App/frontend/src/views/page/PageView.vue b/Web-App/frontend/src/views/page/PageView.vue
index 674d283..280b6bb 100644
--- a/Web-App/frontend/src/views/page/PageView.vue
+++ b/Web-App/frontend/src/views/page/PageView.vue
@@ -326,7 +326,7 @@ const toggleFavorite = () =>
if (page.value?.id === p.id) page.value = { ...page.value, favorite: !p.favorite };
});
-const exportAs = (format: "markdown" | "html") =>
+const exportAs = (format: "markdown" | "html" | "pdf") =>
run(async () => {
// Save first, so the file has the latest title.
await saveTitle();
@@ -351,6 +351,7 @@ const menu = computed