CI / go (Server) (push) Failing after 8m51s
CI / go (Web-App) (push) Successful in 11m46s
CI / mobile (push) Failing after 3m44s
CI / docker (push) Successful in 54m15s
Docs / build (push) Successful in 12m28s
Docs / deploy (push) Skipped
CI / frontend (push) Failing after 7m47s
CI / desktop (ubuntu-latest) (push) Successful in 1h27m22s
CI / desktop (macos-latest) (push) Canceled after 0s
CI / desktop (windows-latest) (push) Canceled after 0s
Word export: pages download as .docx from the page menu and from
GET /pages/{id}/export?format=docx. The file keeps headings, alignment,
lists, to-dos, quotes, callouts, code, tables with a repeating header
row, text formatting, colours, highlights, links and the page's images.
Word import now reads callouts, to-dos and shaded highlights, so a page
exported to Word imports back as it was. The user guide says how to move
pages to Notion, whose Import reads Word and Markdown files.
Editor:
- Columns move like rows: a grip on the column's top edge drags it, and
the table toolbar and Ctrl+Alt+Left/Right move it from the keyboard.
Row and column moving share tablemove.ts.
- Ctrl+Shift+C copies a link to the block the cursor is in.
- Headings 4 to 6 sit under "Other headings" in the slash menu; a search
still finds them directly.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
330 lines
9.6 KiB
Go
330 lines
9.6 KiB
Go
// SPDX-License-Identifier: AGPL-3.0-or-later
|
|
|
|
package directory
|
|
|
|
import (
|
|
"bytes"
|
|
"context"
|
|
"encoding/json"
|
|
"errors"
|
|
"fmt"
|
|
"io"
|
|
"path"
|
|
"regexp"
|
|
"strings"
|
|
"unicode/utf8"
|
|
|
|
"docwell/server/internal/access"
|
|
"docwell/server/internal/apperr"
|
|
"docwell/server/internal/convert"
|
|
)
|
|
|
|
// ---- Import and export -----------------------------------------------------
|
|
|
|
// 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.
|
|
func (s *Service) SetPublicURL(u string) { s.publicURL = strings.TrimRight(u, "/") }
|
|
|
|
// Export is a page rendered as a file.
|
|
type Export struct {
|
|
Filename string
|
|
ContentType string
|
|
Body []byte
|
|
}
|
|
|
|
var unsafeFilename = regexp.MustCompile(`[^\p{L}\p{N} ._-]+`)
|
|
|
|
func exportName(title, ext string) string {
|
|
name := strings.TrimSpace(unsafeFilename.ReplaceAllString(title, ""))
|
|
if name == "" {
|
|
name = "Untitled"
|
|
}
|
|
if utf8.RuneCountInString(name) > 100 {
|
|
name = string([]rune(name)[:100])
|
|
}
|
|
return name + ext
|
|
}
|
|
|
|
// ExportPage renders a page as Markdown ("markdown"), HTML ("html"), PDF
|
|
// ("pdf") or Word ("docx") (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 {
|
|
return Export{}, err
|
|
}
|
|
raw, err := s.docs.Content(ctx, p.ID)
|
|
if err != nil {
|
|
return Export{}, err
|
|
}
|
|
doc, err := convert.Parse(raw)
|
|
if err != nil {
|
|
return Export{}, err
|
|
}
|
|
opts := convert.Options{FileURL: func(path string) string { return s.publicURL + path }}
|
|
switch format {
|
|
case "markdown", "md", "":
|
|
return Export{
|
|
Filename: exportName(p.Title, ".md"), ContentType: "text/markdown; charset=utf-8",
|
|
Body: []byte(convert.MarkdownPage(p.Title, doc, opts)),
|
|
}, nil
|
|
case "html":
|
|
return Export{
|
|
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
|
|
case "docx":
|
|
body, err := convert.DOCX(p.Title, doc, convert.DOCXOptions{
|
|
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, ".docx"),
|
|
ContentType: "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
|
|
Body: body,
|
|
}, nil
|
|
}
|
|
return Export{}, apperr.InvalidFields(map[string]string{"format": "Format must be markdown, html, pdf or docx."})
|
|
}
|
|
|
|
// pdfImage loads an attachment the caller can read for a PDF or Word 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.
|
|
type ImportFile struct {
|
|
Name string
|
|
Data []byte
|
|
}
|
|
|
|
// 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 {
|
|
return nil, err
|
|
}
|
|
if err := access.CreatePageUnder(a.role, rules.role(parent), parent == ""); err != nil {
|
|
return nil, err
|
|
}
|
|
if len(files) == 0 {
|
|
return nil, apperr.InvalidFields(map[string]string{"file": "Choose at least one file."})
|
|
}
|
|
// 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 {
|
|
b, err := readImport(f)
|
|
if err != nil {
|
|
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 strings.TrimSpace(title) == "" {
|
|
title = strings.TrimSuffix(name, path.Ext(name))
|
|
}
|
|
if len(body.Content) == 0 {
|
|
body.Content = []convert.Node{{Type: "paragraph"}}
|
|
}
|
|
return importBatch{pages: []convert.NotionPage{{Title: strings.TrimSpace(title), Parent: -1, Doc: body}}, assets: assets}
|
|
}
|
|
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))
|
|
}
|
|
if err != nil {
|
|
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.")
|
|
}
|
|
if err != nil {
|
|
return bad(" is not a Word document (.docx).")
|
|
}
|
|
return page(doc, assets), nil
|
|
case ".zip":
|
|
if len(f.Data) > maxZipBytes {
|
|
return bad(" is larger than 100 MB.")
|
|
}
|
|
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 bad(": only Markdown, HTML, Word (.docx) and Notion export (.zip) files can be imported.")
|
|
}
|