Link previews: link cards for GitHub issues, pull requests and repositories, Linear issues and Figma files are read through the services' APIs and show a status pill (Open, Merged, In Progress…) and a line of details. Public items need nothing; a workspace's tokens, set by its admins under Workspace settings → Integrations and checked with each service before being sealed, reach private ones and Linear. GET /link-preview takes the workspace; the link card stores kind, status, state and meta. Slack: each workspace connects its own Slack app, made from a manifest the settings page fills in. Docwell posts chosen page and comment events to a channel (edits at most every 30 minutes per page), previews links to Docwell pages posted in Slack, and answers /docwell with a search as the member whose email matches the Slack user, shown only to them. Only pages every member can open are posted or previewed. Requests from Slack are signature-checked; the webhook dispatcher gained listeners so Slack follows the same events. Confluence: a space's HTML export imports with its page tree (from index.html, else breadcrumbs), links between pages, pictures and attachments. Panels become callouts, code macros code blocks with their language, expand macros toggles, task lists to-dos. New collection workspace_integrations (schema snapshot regenerated), OpenAPI and generated Go, TypeScript and Dart types, strings in all five languages, the user guide, and a rebuilt mobile editor bundle. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
408 lines
13 KiB
Go
408 lines
13 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)
|
|
}
|
|
|
|
return s.createBatches(ctx, c, a, parent, batches)
|
|
}
|
|
|
|
// ImportConverted creates pages that were already read from another source
|
|
// (a OneNote notebook) under parent ("" = top level) (editor), like
|
|
// ImportPages does with files. Pages link to each other with
|
|
// convert.PageRef and to assets with convert.AssetRef.
|
|
func (s *Service) ImportConverted(ctx context.Context, c access.Caller, spaceID, parent string, pages []convert.NotionPage, assets []convert.Asset) ([]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(pages) > maxImportPages {
|
|
return nil, apperr.InvalidFields(map[string]string{"file": fmt.Sprintf("Import at most %d pages at once.", maxImportPages)})
|
|
}
|
|
return s.createBatches(ctx, c, a, parent, []importBatch{{pages: pages, assets: assets}})
|
|
}
|
|
|
|
// createBatches makes the pages of read imports and returns the top ones.
|
|
func (s *Service) createBatches(ctx context.Context, c access.Caller, a spaceAccess, parent string, batches []importBatch) ([]Page, error) {
|
|
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
|
|
switch kind {
|
|
case convert.VaultNotion:
|
|
pages, assets, err = convert.ReadNotion(f.Data)
|
|
case convert.VaultConfluence:
|
|
pages, assets, err = convert.ReadConfluence(f.Data)
|
|
default:
|
|
pages, assets, err = convert.ReadVault(f.Data, kind)
|
|
}
|
|
switch {
|
|
case errors.Is(err, convert.ErrNotNotion), errors.Is(err, convert.ErrNoNotes), errors.Is(err, convert.ErrNoConfluence):
|
|
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.")
|
|
}
|