Files
Docwell/Server/internal/convert/notion.go
T
tajniak81andClaude Opus 5.5 f20e5f96f9 Add search filters, space pins, find and replace and page layout
- Search can be narrowed by space, author and last change; the index
  records a mapping version and rebuilds when it changes.
- Editors can pin up to 12 pages to a space's home.
- Find and replace in the editor (Ctrl+F), with match case.
- Pages can be set to full width and a serif or mono font.
- Tailwind now scans the editor package, so its classes are generated.
- Fix golangci-lint findings, including push device names that were
  saved before being trimmed and capped.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-02 14:35:18 +01:00

292 lines
8.1 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
// 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(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 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"