Files
Docwell/Server/internal/directory/transfer.go
T
tajniak81andClaude Opus 5.5 3d1cf362d7 Add calendars, a web clipper, more importers and workspace snapshots
Phase F of the AFFiNE plan (ADR-16):

- Calendars: people subscribe to iCal feeds (webcal, Google's secret
  address, Outlook) or CalDAV accounts in account settings; their
  events show at the top of journal pages in the reader's time zone.
  Repeats, moved and cancelled occurrences, IANA and Windows zones
  are handled. Events are read on demand and kept in memory for 15
  minutes; passwords are sealed with DOCWELL_SECRET_KEY; sources
  follow the webhook address rules. New calendar_accounts collection.
- Importers: zips of Markdown (Obsidian vaults, Bear TextBundles and
  .bear2bk, Readwise's Markdown, Docwell's own space export) keep
  folders as pages, resolve [[wikilinks]] and embeds by name, and turn
  front matter and #tags into properties and tags. OneNote .mht
  exports, Readwise CSV, and any other CSV as a database page.
- Exports: PNG of a page drawn in the browser, print styles that print
  only the page in the light theme, and workspace snapshots (records,
  Yjs states, JSON and files in one zip) that restore as a new
  workspace. Old ids are swapped byte for byte inside the Yjs updates,
  so links point at the restored pages and comments stay anchored.
- Web-Clipper/: a Manifest V3 extension for Chrome, Edge and Firefox
  that saves the article or the selection as Markdown through the
  import API with a personal API token.
- OpenAPI, generated clients, translations and user docs.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-16 11:56:03 +01:00

382 lines
11 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, HTML or CSV file, one Word file, one archive
// (a zip, a Bear backup or an MHTML file).
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 (an archive).
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 CSV file becomes a page with a database,
// or, from Readwise, a page of highlights per book. An MHTML file (.mht,
// from OneNote) becomes a page per page it holds. A .zip is read as a Notion
// export, or as a folder of Markdown notes (an Obsidian vault, Bear's
// TextBundles, any Markdown with images); a Bear backup (.bear2bk) too.
// Archives keep their page tree, links between their pages, and their
// images and files; front matter and #tags become properties and tags.
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{}
meta := s.newImportMeta(c, a.space.Workspace)
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
}
meta.apply(ctx, created[i].ID, p)
}
}
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 ".csv":
if len(f.Data) > maxImportBytes {
return bad(" is larger than 5 MB.")
}
if !utf8.Valid(f.Data) {
return bad(" is not UTF-8 text.")
}
if convert.IsReadwiseCSV(f.Data) {
pages, err := convert.ReadReadwise(f.Data)
if err != nil {
return bad(" holds no Readwise highlights.")
}
return importBatch{pages: pages}, nil
}
doc, err := convert.FromCSV(f.Data)
if err != nil {
return bad(" could not be read as CSV.")
}
return page(doc, nil), nil
case ".mht", ".mhtml":
if len(f.Data) > maxZipBytes {
return bad(" is larger than 100 MB.")
}
pages, assets, err := convert.ReadMHT(f.Data, name)
switch {
case errors.Is(err, convert.ErrTooLarge):
return bad(" holds a part larger than 50 MB.")
case err != nil:
return bad(" is not a web archive (.mht) with pages in it.")
}
return importBatch{pages: pages, assets: assets}, nil
case ".zip", ".bear2bk":
if len(f.Data) > maxZipBytes {
return bad(" is larger than 100 MB.")
}
kind := convert.VaultBear
if ext == ".zip" {
var err error
if kind, err = convert.DetectArchive(f.Data); err != nil {
return bad(" is not a zip file.")
}
}
var pages []convert.NotionPage
var assets []convert.Asset
var err error
if kind == convert.VaultNotion {
pages, assets, err = convert.ReadNotion(f.Data)
} else {
pages, assets, err = convert.ReadVault(f.Data, kind)
}
switch {
case errors.Is(err, convert.ErrNotNotion), errors.Is(err, convert.ErrNoNotes):
return bad(" 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), CSV, web archive (.mht), Bear backup (.bear2bk) and zip files can be imported.")
}