Files
Docwell/Server/internal/convert/notion.go
T
tajniak81andClaude Opus 5.5 d28f1e02db Add tables, to-dos, callouts and the rest of editor parity
The editor gains the blocks and formatting it lacked next to AFFiNE:

- Tables with a header row, resizable columns, a toolbar to add, delete,
  merge and split, and rows that move by a drag grip, toolbar buttons or
  Ctrl+Alt+Up/Down.
- To-do lists (also from "[] "), callouts with an emoji and colour, and
  headings down to level 6 (Ctrl+Shift+0-6 for text and headings).
- Text colour and highlights from a fixed palette that follows the theme,
  and left, centre and right alignment.
- Optional line numbers on code blocks, with a default hosts can set.
- PDF attachments show their pages inline; pdf.js loads only then, and
  the mobile bundle leaves it out.
- The selection toolbar adds underline, colour, align, inline math, make a
  linked page and copy block link. A grip beside each block drags it and
  opens a menu: turn into, move, duplicate, copy, copy link, delete.
- The slash menu adds Today, Tomorrow, Yesterday, Now and New page.

The web app translates the new words and makes linked pages as children
of the open page. The mobile bridge gets underline, to-do, callout and
table commands, so its protocol moves to version 2 and the bundle is
rebuilt.

docwell-server's converters learn the new nodes: Markdown writes task
lists, GitHub alerts and tables and reads them back; HTML keeps colours
and alignment and reads its own output back; PDF draws tables, to-dos,
callouts and coloured text; Word import keeps tables, alignment, H4-H6
and colours; Notion import turns databases into tables and keeps
callouts and to-dos. Imported tables and H4-H6 headings no longer
collapse into paragraphs and H3.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-14 12:20:08 +01:00

316 lines
9.0 KiB
Go

// 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 := &notionReader{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(notionAsides(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
}
if f.UncompressedSize64 > maxNotionTotal {
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 a table, its first row the header.
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
}
cols := 0
for _, row := range rows {
cols = max(cols, len(row))
}
doc := Node{Type: "doc"}
if cols == 0 {
return doc, nil
}
table := Node{Type: "table"}
for i, row := range rows {
tr := Node{Type: "tableRow"}
for c := range cols {
kind := "tableCell"
if i == 0 {
kind = "tableHeader"
}
p := Node{Type: "paragraph"}
if c < len(row) {
if cell := strings.TrimSpace(row[c]); cell != "" {
p.Content = []Node{{Type: "text", Text: cell}}
}
}
attrs := map[string]any{"colspan": float64(1), "rowspan": float64(1), "colwidth": nil}
tr.Content = append(tr.Content, Node{Type: kind, Attrs: attrs, Content: []Node{p}})
}
table.Content = append(table.Content, tr)
}
doc.Content = []Node{table}
return doc, nil
}
// notionAside finds the <aside> blocks Notion writes callouts as in its
// Markdown export. Markdown readers drop raw HTML, text and all.
var notionAside = regexp.MustCompile(`(?ms)^[ \t]*<aside>[ \t]*\n(.*?)\n?[ \t]*</aside>[ \t]*$`)
// notionAsides rewrites Notion's callouts as GitHub alerts, which import
// reads as callouts (with the emoji Notion puts first in the text).
func notionAsides(md string) string {
return notionAside.ReplaceAllStringFunc(md, func(block string) string {
body := strings.TrimSpace(notionAside.FindStringSubmatch(block)[1])
lines := []string{"> [!NOTE]"}
for _, l := range strings.Split(body, "\n") {
lines = append(lines, strings.TrimRight("> "+l, " "))
}
return strings.Join(lines, "\n")
})
}
// utf8BOM starts some exported text files.
const utf8BOM = "\xef\xbb\xbf"