Files
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

126 lines
5.2 KiB
Go

// SPDX-License-Identifier: AGPL-3.0-or-later
package httpapi
import (
"context"
"io"
"mime"
"net/http"
"strconv"
"docwell/server/internal/access"
"docwell/server/internal/directory"
)
// TransferService is the part of directory.Service that imports and exports pages.
type TransferService interface {
ExportPage(ctx context.Context, c access.Caller, id, format string) (directory.Export, error)
ImportPages(ctx context.Context, c access.Caller, spaceID, parent string, files []directory.ImportFile) ([]directory.Page, error)
PrepareSpaceExport(ctx context.Context, c access.Caller, spaceID, format string) (*directory.SpaceExport, error)
PrepareSnapshot(ctx context.Context, c access.Caller, wsID string) (*directory.Snapshot, error)
RestoreSnapshot(ctx context.Context, c access.Caller, in directory.RestoreInput) (directory.Workspace, error)
}
// maxImportRequest caps one import request: up to 20 files, each within its
// kind's limit (5 MB of text, 25 MB for Word, 100 MB for a Notion export),
// and not more than one Notion export's worth in all.
const maxImportRequest = directory.MaxImportFile + 1<<20
func (a *api) transferRoutes(mux *routeMux) {
mux.HandleFunc("GET /api/v1/pages/{id}/export", a.requireUser(func(w http.ResponseWriter, r *http.Request) {
e, err := a.dir.ExportPage(r.Context(), caller(r), r.PathValue("id"), r.URL.Query().Get("format"))
if err != nil {
a.writeError(w, err)
return
}
h := w.Header()
h.Set("Content-Type", e.ContentType)
h.Set("Content-Disposition", mime.FormatMediaType("attachment", map[string]string{"filename": e.Filename}))
h.Set("Content-Length", strconv.Itoa(len(e.Body)))
h.Set("X-Content-Type-Options", "nosniff")
_, _ = w.Write(e.Body)
}))
mux.HandleFunc("GET /api/v1/spaces/{id}/export", a.requireUser(func(w http.ResponseWriter, r *http.Request) {
e, err := a.dir.PrepareSpaceExport(r.Context(), caller(r), r.PathValue("id"), r.URL.Query().Get("format"))
if err != nil {
a.writeError(w, err)
return
}
h := w.Header()
h.Set("Content-Type", "application/zip")
h.Set("Content-Disposition", mime.FormatMediaType("attachment", map[string]string{"filename": e.Filename}))
h.Set("X-Content-Type-Options", "nosniff")
// The zip streams as it is built; a failure half-way can only cut it short.
if err := e.WriteTo(r.Context(), w); err != nil {
a.log.Warn("space export failed", "space", r.PathValue("id"), "err", err)
}
}))
mux.HandleFunc("GET /api/v1/workspaces/{id}/snapshot", a.requireUser(func(w http.ResponseWriter, r *http.Request) {
e, err := a.dir.PrepareSnapshot(r.Context(), caller(r), r.PathValue("id"))
if err != nil {
a.writeError(w, err)
return
}
h := w.Header()
h.Set("Content-Type", "application/zip")
h.Set("Content-Disposition", mime.FormatMediaType("attachment", map[string]string{"filename": e.Filename}))
h.Set("X-Content-Type-Options", "nosniff")
if err := e.WriteTo(r.Context(), w); err != nil {
a.log.Warn("snapshot failed", "workspace", r.PathValue("id"), "err", err)
}
}))
mux.HandleFunc("POST /api/v1/workspaces/restore", a.requireUser(func(w http.ResponseWriter, r *http.Request) {
r.Body = http.MaxBytesReader(w, r.Body, directory.MaxSnapshot+1<<20)
if err := r.ParseMultipartForm(32 << 20); err != nil { // The snapshot spills to a temporary file.
writeJSON(w, http.StatusBadRequest, map[string]string{"error": "invalid", "message": "expected multipart/form-data with a snapshot file"})
return
}
defer func() { _ = r.MultipartForm.RemoveAll() }()
files := r.MultipartForm.File["file"]
if len(files) != 1 {
writeJSON(w, http.StatusBadRequest, map[string]string{"error": "invalid", "message": "send one snapshot file"})
return
}
f, err := files[0].Open()
if err != nil {
a.writeError(w, err)
return
}
defer func() { _ = f.Close() }()
ws, err := a.dir.RestoreSnapshot(r.Context(), caller(r), directory.RestoreInput{
Organization: r.FormValue("organization"), Name: r.FormValue("name"), File: f, Size: files[0].Size,
})
a.respondStatus(w, http.StatusCreated, ws, err)
}))
mux.HandleFunc("POST /api/v1/spaces/{id}/import", a.requireUser(func(w http.ResponseWriter, r *http.Request) {
r.Body = http.MaxBytesReader(w, r.Body, maxImportRequest)
if err := r.ParseMultipartForm(32 << 20); err != nil { // Larger uploads spill to temporary files.
writeJSON(w, http.StatusBadRequest, map[string]string{"error": "invalid", "message": "expected multipart/form-data up to 100 MB"})
return
}
defer func() { _ = r.MultipartForm.RemoveAll() }()
var files []directory.ImportFile
for _, fh := range r.MultipartForm.File["file"] {
if len(files) == 20 {
writeJSON(w, http.StatusBadRequest, map[string]string{"error": "invalid", "message": "import at most 20 files at once"})
return
}
f, err := fh.Open()
if err != nil {
a.writeError(w, err)
return
}
data, err := io.ReadAll(io.LimitReader(f, directory.MaxImportFile+1))
_ = f.Close()
if err != nil {
a.writeError(w, err)
return
}
files = append(files, directory.ImportFile{Name: fh.Filename, Data: data})
}
pages, err := a.dir.ImportPages(r.Context(), caller(r), r.PathValue("id"), r.FormValue("parent"), files)
a.respondStatus(w, http.StatusCreated, pages, err)
}))
}