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>
725 lines
22 KiB
Go
725 lines
22 KiB
Go
// SPDX-License-Identifier: AGPL-3.0-or-later
|
|
|
|
package directory
|
|
|
|
import (
|
|
"archive/zip"
|
|
"bytes"
|
|
"context"
|
|
"encoding/json"
|
|
"errors"
|
|
"fmt"
|
|
"io"
|
|
"log/slog"
|
|
"regexp"
|
|
"sort"
|
|
"strings"
|
|
"time"
|
|
|
|
"docwell/server/internal/access"
|
|
"docwell/server/internal/apperr"
|
|
"docwell/server/internal/store/pocketbase"
|
|
)
|
|
|
|
// ---- Workspace snapshots ---------------------------------------------------
|
|
//
|
|
// A snapshot is one zip that restores a workspace as it was: its spaces and
|
|
// page tree, every page's document (pages/<id>.ydoc, the Yjs state, and
|
|
// pages/<id>.json, the same document as JSON), tags, properties,
|
|
// collections, comments, and every attached file (files/<id>). snapshot.json
|
|
// holds the records. It covers what the person exporting can read: other
|
|
// people's journals and pages hidden from them are left out. Members, page
|
|
// sharing, share links, webhooks, AI settings and history are not part of
|
|
// it, since they belong to the instance more than to the content.
|
|
//
|
|
// Restoring makes a new workspace. Every record gets a new id, and the old
|
|
// ids are replaced wherever they appear (links, mentions, embedded pages,
|
|
// relations, property values), so a snapshot can be restored next to the
|
|
// workspace it came from. Documents come back from their Yjs state with the
|
|
// ids swapped in place (see remapBinary), so they are the same Yjs documents
|
|
// and comments stay anchored; the JSON copy is the fallback.
|
|
|
|
const (
|
|
snapshotFormat = "docwell-snapshot"
|
|
snapshotVersion = 1
|
|
// MaxSnapshot caps a snapshot upload.
|
|
MaxSnapshot = 4 << 30
|
|
// maxSnapshotRecords caps the records of each kind.
|
|
maxSnapshotRecords = 50000
|
|
)
|
|
|
|
type snapshotManifest struct {
|
|
Format string `json:"format"`
|
|
Version int `json:"version"`
|
|
Exported string `json:"exported"`
|
|
Workspace map[string]any `json:"workspace"`
|
|
Spaces []map[string]any `json:"spaces"`
|
|
Pages []map[string]any `json:"pages"`
|
|
Tags []map[string]any `json:"tags"`
|
|
Properties []map[string]any `json:"properties"`
|
|
Collections []map[string]any `json:"collections"`
|
|
Attachments []map[string]any `json:"attachments"`
|
|
Comments []map[string]any `json:"comments"`
|
|
}
|
|
|
|
// The fields a snapshot keeps of each record.
|
|
var (
|
|
snapWorkspaceFields = "name,settings,default_page_mode"
|
|
snapSpaceFields = "id,name,slug,icon,description,visibility,default_role,journal_owner,journal_template"
|
|
snapPageFields = "id,space,parent,title,icon,position,is_template,archived_at,pinned_at,restricted,full_width,font,default_mode,tags,properties,journal_date,creator,created,updated"
|
|
snapTagFields = "id,name,color"
|
|
snapPropertyFields = "id,name,type,options,visibility,position"
|
|
snapCollectionFields = "id,creator,name,icon,filter,include,exclude,shared"
|
|
snapAttachmentFields = "id,page,name,mime,size,created"
|
|
snapCommentFields = "id,page,parent,author,body,quote,anchor,reactions,resolved_at,resolved_by,edited_at,created"
|
|
)
|
|
|
|
// Snapshot is a prepared workspace snapshot; WriteTo streams the zip.
|
|
type Snapshot struct {
|
|
Filename string
|
|
s *Service
|
|
manifest snapshotManifest
|
|
}
|
|
|
|
// PrepareSnapshot lists what a snapshot of the workspace holds (workspace
|
|
// admin).
|
|
func (s *Service) PrepareSnapshot(ctx context.Context, c access.Caller, wsID string) (*Snapshot, error) {
|
|
ws, role, err := s.workspaceFor(ctx, c, wsID)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
if err := access.RenameWorkspace(role); err != nil {
|
|
return nil, err
|
|
}
|
|
m := snapshotManifest{Format: snapshotFormat, Version: snapshotVersion, Exported: time.Now().UTC().Format(time.RFC3339)}
|
|
byWS := pocketbase.ListOptions{Filter: fmt.Sprintf("workspace = '%s'", ws.ID)}
|
|
wsRec, err := pocketbase.Get[map[string]any](ctx, s.pb, "workspaces", ws.ID)
|
|
if err != nil {
|
|
return nil, mapPB(err, "workspace not found")
|
|
}
|
|
m.Workspace = pick(wsRec, snapWorkspaceFields)
|
|
|
|
spaces, err := listAll[spaceRecord](ctx, s, "spaces", pocketbase.ListOptions{Filter: byWS.Filter, Sort: "created"})
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
keep := map[string]bool{}
|
|
for _, sp := range spaces {
|
|
if sp.JournalOwner != "" && sp.JournalOwner != c.ID {
|
|
continue // Someone else's journal.
|
|
}
|
|
_, rules, err := s.spaceRules(ctx, c, sp.ID)
|
|
if err != nil {
|
|
continue
|
|
}
|
|
t, err := s.loadTree(ctx, sp.ID)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
var walk func(parent string)
|
|
walk = func(parent string) {
|
|
for _, p := range t.children[parent] {
|
|
if rules.role(p.ID) == "" {
|
|
continue // Hidden from the caller, with everything under it.
|
|
}
|
|
keep[p.ID] = true
|
|
walk(p.ID)
|
|
}
|
|
}
|
|
walk("")
|
|
raw, err := pocketbase.Get[map[string]any](ctx, s.pb, "spaces", sp.ID)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
m.Spaces = append(m.Spaces, pick(raw, snapSpaceFields))
|
|
}
|
|
pages, err := listRaw(ctx, s, "pages", byWS.Filter+" && deleted_at = ''", snapPageFields)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
for _, p := range pages {
|
|
if keep[str(p["id"])] {
|
|
m.Pages = append(m.Pages, p)
|
|
}
|
|
}
|
|
for _, part := range []struct {
|
|
collection, fields string
|
|
into *[]map[string]any
|
|
}{
|
|
{"tags", snapTagFields, &m.Tags},
|
|
{"workspace_properties", snapPropertyFields, &m.Properties},
|
|
{"page_collections", snapCollectionFields, &m.Collections},
|
|
} {
|
|
if *part.into, err = listRaw(ctx, s, part.collection, byWS.Filter, part.fields); err != nil {
|
|
return nil, err
|
|
}
|
|
}
|
|
// Collections that are someone else's own are not shared with the caller.
|
|
shared := m.Collections[:0]
|
|
for _, col := range m.Collections {
|
|
if col["shared"] == true || str(col["creator"]) == c.ID {
|
|
shared = append(shared, col)
|
|
}
|
|
}
|
|
m.Collections = shared
|
|
for _, part := range []struct {
|
|
collection, fields string
|
|
into *[]map[string]any
|
|
}{
|
|
{"attachments", snapAttachmentFields, &m.Attachments},
|
|
{"comments", snapCommentFields, &m.Comments},
|
|
} {
|
|
all, err := listRaw(ctx, s, part.collection, byWS.Filter, part.fields)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
for _, r := range all {
|
|
if keep[str(r["page"])] {
|
|
*part.into = append(*part.into, r)
|
|
}
|
|
}
|
|
}
|
|
stamp := time.Now().UTC().Format("2006-01-02")
|
|
return &Snapshot{Filename: exportName(ws.Name+" snapshot "+stamp, ".zip"), s: s, manifest: m}, nil
|
|
}
|
|
|
|
// listRaw lists records as plain maps with the named fields.
|
|
func listRaw(ctx context.Context, s *Service, collection, filter, fields string) ([]map[string]any, error) {
|
|
rows, err := listAll[map[string]any](ctx, s, collection, pocketbase.ListOptions{Filter: filter, Fields: fields, Sort: "created"})
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
if len(rows) > maxSnapshotRecords {
|
|
return nil, apperr.Invalid(fmt.Sprintf("the workspace has more than %d %s", maxSnapshotRecords, collection))
|
|
}
|
|
out := make([]map[string]any, len(rows))
|
|
for i, r := range rows {
|
|
out[i] = pick(r, fields)
|
|
}
|
|
return out, nil
|
|
}
|
|
|
|
// pick keeps the named fields of a record.
|
|
func pick(r map[string]any, fields string) map[string]any {
|
|
out := map[string]any{}
|
|
for _, f := range strings.Split(fields, ",") {
|
|
if v, ok := r[f]; ok {
|
|
out[f] = v
|
|
}
|
|
}
|
|
return out
|
|
}
|
|
|
|
func str(v any) string {
|
|
s, _ := v.(string)
|
|
return s
|
|
}
|
|
|
|
// WriteTo writes the zip. A page or file that fails to load is left out and
|
|
// logged, so one broken attachment does not lose the whole snapshot.
|
|
func (e *Snapshot) WriteTo(ctx context.Context, w io.Writer) error {
|
|
z := zip.NewWriter(w)
|
|
manifest, err := json.MarshalIndent(e.manifest, "", " ")
|
|
if err != nil {
|
|
return err
|
|
}
|
|
if err := writeZipFile(z, "snapshot.json", time.Now(), manifest); err != nil {
|
|
return err
|
|
}
|
|
for _, p := range e.manifest.Pages {
|
|
id := str(p["id"])
|
|
mod := modTime(str(p["updated"]))
|
|
if raw, err := e.s.docs.Content(ctx, id); err != nil {
|
|
slog.Warn("snapshot: page content skipped", "page", id, "err", err)
|
|
} else if len(raw) > 0 && string(raw) != "null" {
|
|
if err := writeZipFile(z, "pages/"+id+".json", mod, raw); err != nil {
|
|
return err
|
|
}
|
|
}
|
|
if state, err := e.s.docs.State(ctx, id); err != nil {
|
|
slog.Warn("snapshot: page state skipped", "page", id, "err", err)
|
|
} else if len(state) > 0 {
|
|
if err := writeZipFile(z, "pages/"+id+".ydoc", mod, state); err != nil {
|
|
return err
|
|
}
|
|
}
|
|
}
|
|
for _, a := range e.manifest.Attachments {
|
|
rec := attachmentRecord{ID: str(a["id"])}
|
|
full, err := e.s.getAttachment(ctx, rec.ID)
|
|
if err != nil {
|
|
slog.Warn("snapshot: file skipped", "file", rec.ID, "err", err)
|
|
continue
|
|
}
|
|
if err := (&SpaceExport{s: e.s}).copyFile(ctx, z, exportedFile{rec: full, path: "files/" + rec.ID}); err != nil {
|
|
return err
|
|
}
|
|
}
|
|
return z.Close()
|
|
}
|
|
|
|
// ---- Restore ---------------------------------------------------------------
|
|
|
|
// RestoreInput names where a snapshot is restored and what it is.
|
|
type RestoreInput struct {
|
|
// Organization is required for superadmins (see CreateWorkspace).
|
|
Organization string
|
|
// Name is the new workspace's name; "" keeps the snapshot's.
|
|
Name string
|
|
File io.ReaderAt
|
|
Size int64
|
|
}
|
|
|
|
// pbID finds PocketBase record ids (15 lower-case letters and digits) in a
|
|
// JSON document.
|
|
var pbID = regexp.MustCompile(`\b[a-z0-9]{15}\b`)
|
|
|
|
type idMap map[string]string
|
|
|
|
// remap replaces old record ids in v (any JSON value) with the new ones.
|
|
func (m idMap) remap(v any) any {
|
|
raw, err := json.Marshal(v)
|
|
if err != nil {
|
|
return v
|
|
}
|
|
var out any
|
|
if json.Unmarshal(m.remapJSON(raw), &out) != nil {
|
|
return v
|
|
}
|
|
return out
|
|
}
|
|
|
|
func (m idMap) remapJSON(raw []byte) []byte {
|
|
return pbID.ReplaceAllFunc(raw, func(b []byte) []byte {
|
|
if n, ok := m[string(b)]; ok {
|
|
return []byte(n)
|
|
}
|
|
return b
|
|
})
|
|
}
|
|
|
|
// ids maps a list of old ids, dropping the ones that were not restored.
|
|
func (m idMap) ids(v any) []string {
|
|
out := []string{}
|
|
list, _ := v.([]any)
|
|
for _, item := range list {
|
|
if n, ok := m[str(item)]; ok {
|
|
out = append(out, n)
|
|
}
|
|
}
|
|
return out
|
|
}
|
|
|
|
// RestoreSnapshot makes a new workspace from a snapshot (org admins, in
|
|
// their organization; superadmins, in the one they name). The caller owns
|
|
// it through the cascade and is the creator of everything in it, except
|
|
// comments and collections by people who exist on this instance.
|
|
func (s *Service) RestoreSnapshot(ctx context.Context, c access.Caller, in RestoreInput) (Workspace, error) {
|
|
bad := func(msg string) (Workspace, error) {
|
|
return Workspace{}, apperr.InvalidFields(map[string]string{"file": msg})
|
|
}
|
|
z, err := zip.NewReader(in.File, in.Size)
|
|
if err != nil {
|
|
return bad("The file is not a Docwell snapshot (.zip).")
|
|
}
|
|
files := map[string]*zip.File{}
|
|
for _, f := range z.File {
|
|
files[f.Name] = f
|
|
}
|
|
mf := files["snapshot.json"]
|
|
if mf == nil {
|
|
return bad("The zip holds no snapshot.json: it is not a Docwell snapshot.")
|
|
}
|
|
raw, err := readZipEntry(mf, 256<<20)
|
|
if err != nil {
|
|
return bad("snapshot.json could not be read.")
|
|
}
|
|
var m snapshotManifest
|
|
if json.Unmarshal(raw, &m) != nil || m.Format != snapshotFormat {
|
|
return bad("snapshot.json is not a Docwell snapshot.")
|
|
}
|
|
if m.Version > snapshotVersion {
|
|
return bad("The snapshot comes from a newer Docwell; update this server first.")
|
|
}
|
|
name := strings.TrimSpace(in.Name)
|
|
if name == "" {
|
|
name = str(m.Workspace["name"])
|
|
}
|
|
ws, err := s.CreateWorkspace(ctx, c, CreateWorkspaceInput{Name: name, Organization: in.Organization})
|
|
if err != nil {
|
|
return Workspace{}, err
|
|
}
|
|
r := &restorer{s: s, c: c, ws: ws.ID, files: files, ids: idMap{}, m: m}
|
|
if err := r.run(ctx); err != nil {
|
|
// Leave nothing half restored.
|
|
if derr := s.pb.Delete(context.WithoutCancel(ctx), "workspaces", ws.ID); derr != nil {
|
|
slog.Warn("snapshot restore: cleanup failed", "workspace", ws.ID, "err", derr)
|
|
}
|
|
return Workspace{}, err
|
|
}
|
|
full, err := s.getWorkspace(ctx, ws.ID)
|
|
if err != nil {
|
|
return Workspace{}, err
|
|
}
|
|
return full.view(ws.Role), nil
|
|
}
|
|
|
|
func readZipEntry(f *zip.File, limit int64) ([]byte, error) {
|
|
if limit < 0 || f.UncompressedSize64 > uint64(limit) {
|
|
return nil, errors.New("too large")
|
|
}
|
|
rc, err := f.Open()
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
defer func() { _ = rc.Close() }()
|
|
data, err := io.ReadAll(io.LimitReader(rc, limit+1))
|
|
if err == nil && int64(len(data)) > limit {
|
|
err = errors.New("too large")
|
|
}
|
|
return data, err
|
|
}
|
|
|
|
type restorer struct {
|
|
s *Service
|
|
c access.Caller
|
|
ws string
|
|
files map[string]*zip.File
|
|
ids idMap
|
|
m snapshotManifest
|
|
users map[string]bool // people of the snapshot who exist here
|
|
}
|
|
|
|
func (r *restorer) create(ctx context.Context, collection string, body map[string]any) (string, error) {
|
|
rec, err := pocketbase.Create[struct {
|
|
ID string `json:"id"`
|
|
}](ctx, r.s.pb, collection, body)
|
|
if err != nil {
|
|
return "", fmt.Errorf("restoring %s: %w", collection, mapPB(err, "not found"))
|
|
}
|
|
return rec.ID, nil
|
|
}
|
|
|
|
func (r *restorer) run(ctx context.Context) error {
|
|
if err := r.loadUsers(ctx); err != nil {
|
|
return err
|
|
}
|
|
patch := map[string]any{}
|
|
if v, ok := r.m.Workspace["settings"]; ok && v != nil {
|
|
patch["settings"] = v
|
|
}
|
|
if v := str(r.m.Workspace["default_page_mode"]); v != "" {
|
|
patch["default_page_mode"] = v
|
|
}
|
|
if len(patch) > 0 {
|
|
if _, err := pocketbase.Update[map[string]any](ctx, r.s.pb, "workspaces", r.ws, patch); err != nil {
|
|
return mapPB(err, "workspace not found")
|
|
}
|
|
}
|
|
for _, t := range r.m.Tags {
|
|
id, err := r.create(ctx, "tags", map[string]any{"workspace": r.ws, "name": t["name"], "color": t["color"]})
|
|
if err != nil {
|
|
return err
|
|
}
|
|
r.ids[str(t["id"])] = id
|
|
}
|
|
for _, p := range r.m.Properties {
|
|
id, err := r.create(ctx, "workspace_properties", map[string]any{
|
|
"workspace": r.ws, "name": p["name"], "type": p["type"], "options": p["options"],
|
|
"visibility": p["visibility"], "position": p["position"],
|
|
})
|
|
if err != nil {
|
|
return err
|
|
}
|
|
r.ids[str(p["id"])] = id
|
|
}
|
|
for _, sp := range r.m.Spaces {
|
|
body := map[string]any{
|
|
"workspace": r.ws, "name": sp["name"], "slug": sp["slug"], "icon": sp["icon"],
|
|
"description": sp["description"], "visibility": sp["visibility"], "default_role": sp["default_role"],
|
|
}
|
|
if owner := str(sp["journal_owner"]); owner != "" {
|
|
if !r.users[owner] {
|
|
owner = r.c.ID // The journal's owner is not on this instance: it becomes the restorer's.
|
|
}
|
|
body["journal_owner"] = owner
|
|
}
|
|
id, err := r.create(ctx, "spaces", body)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
r.ids[str(sp["id"])] = id
|
|
}
|
|
if err := r.pages(ctx); err != nil {
|
|
return err
|
|
}
|
|
for _, sp := range r.m.Spaces {
|
|
if t := r.ids[str(sp["journal_template"])]; t != "" {
|
|
if _, err := pocketbase.Update[map[string]any](ctx, r.s.pb, "spaces", r.ids[str(sp["id"])], map[string]any{"journal_template": t}); err != nil {
|
|
return mapPB(err, "space not found")
|
|
}
|
|
}
|
|
}
|
|
if err := r.attachments(ctx); err != nil {
|
|
return err
|
|
}
|
|
if err := r.contents(ctx); err != nil {
|
|
return err
|
|
}
|
|
for _, col := range r.m.Collections {
|
|
creator := str(col["creator"])
|
|
if !r.users[creator] {
|
|
creator = r.c.ID
|
|
}
|
|
if _, err := r.create(ctx, "page_collections", map[string]any{
|
|
"workspace": r.ws, "creator": creator, "name": col["name"], "icon": col["icon"],
|
|
"filter": r.ids.remap(col["filter"]), "include": r.ids.ids(col["include"]), "exclude": r.ids.ids(col["exclude"]),
|
|
"shared": col["shared"],
|
|
}); err != nil {
|
|
return err
|
|
}
|
|
}
|
|
return r.comments(ctx)
|
|
}
|
|
|
|
// loadUsers finds which people the snapshot names exist on this instance.
|
|
func (r *restorer) loadUsers(ctx context.Context) error {
|
|
want := map[string]bool{}
|
|
add := func(v any) {
|
|
if id := str(v); validID(id) {
|
|
want[id] = true
|
|
}
|
|
}
|
|
for _, sp := range r.m.Spaces {
|
|
add(sp["journal_owner"])
|
|
}
|
|
for _, col := range r.m.Collections {
|
|
add(col["creator"])
|
|
}
|
|
for _, cm := range r.m.Comments {
|
|
add(cm["author"])
|
|
add(cm["resolved_by"])
|
|
if re, ok := cm["reactions"].(map[string]any); ok {
|
|
for _, who := range re {
|
|
list, _ := who.([]any)
|
|
for _, id := range list {
|
|
add(id)
|
|
}
|
|
}
|
|
}
|
|
}
|
|
r.users = map[string]bool{r.c.ID: true}
|
|
ids := make([]string, 0, len(want))
|
|
for id := range want {
|
|
ids = append(ids, id)
|
|
}
|
|
sort.Strings(ids)
|
|
for len(ids) > 0 {
|
|
n := min(len(ids), 50)
|
|
var parts []string
|
|
for _, id := range ids[:n] {
|
|
parts = append(parts, fmt.Sprintf("id = '%s'", id))
|
|
}
|
|
ids = ids[n:]
|
|
found, err := listAll[struct {
|
|
ID string `json:"id"`
|
|
}](ctx, r.s, "users", pocketbase.ListOptions{Filter: strings.Join(parts, " || "), Fields: "id"})
|
|
if err != nil {
|
|
return err
|
|
}
|
|
for _, u := range found {
|
|
r.users[u.ID] = true
|
|
}
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// pages creates the pages, parents first.
|
|
func (r *restorer) pages(ctx context.Context) error {
|
|
byID := map[string]map[string]any{}
|
|
for _, p := range r.m.Pages {
|
|
byID[str(p["id"])] = p
|
|
}
|
|
depth := func(p map[string]any) int {
|
|
d := 0
|
|
for parent := str(p["parent"]); parent != "" && d < 1000; d++ {
|
|
next, ok := byID[parent]
|
|
if !ok {
|
|
break
|
|
}
|
|
parent = str(next["parent"])
|
|
}
|
|
return d
|
|
}
|
|
order := append([]map[string]any(nil), r.m.Pages...)
|
|
sort.SliceStable(order, func(i, j int) bool { return depth(order[i]) < depth(order[j]) })
|
|
for _, p := range order {
|
|
space := r.ids[str(p["space"])]
|
|
if space == "" {
|
|
continue
|
|
}
|
|
body := map[string]any{
|
|
"workspace": r.ws, "space": space, "title": p["title"], "icon": p["icon"], "position": p["position"],
|
|
"creator": r.c.ID, "last_editor": r.c.ID, "mentions": []string{}, "links": []string{},
|
|
"is_template": p["is_template"], "archived_at": p["archived_at"], "pinned_at": p["pinned_at"],
|
|
"restricted": p["restricted"], "full_width": p["full_width"], "font": p["font"],
|
|
"default_mode": p["default_mode"], "journal_date": p["journal_date"],
|
|
"tags": r.ids.ids(p["tags"]),
|
|
}
|
|
if parent := str(p["parent"]); parent != "" {
|
|
if body["parent"] = r.ids[parent]; body["parent"] == "" {
|
|
continue // Its parent was not restored either.
|
|
}
|
|
}
|
|
if props, ok := p["properties"].(map[string]any); ok && len(props) > 0 {
|
|
body["properties"] = r.ids.remap(props)
|
|
}
|
|
id, err := r.create(ctx, "pages", body)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
r.ids[str(p["id"])] = id
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func (r *restorer) attachments(ctx context.Context) error {
|
|
for _, a := range r.m.Attachments {
|
|
page := r.ids[str(a["page"])]
|
|
f := r.files["files/"+str(a["id"])]
|
|
if page == "" || f == nil {
|
|
continue
|
|
}
|
|
name := cleanFilename(str(a["name"]))
|
|
rc, err := f.Open()
|
|
if err != nil {
|
|
return fmt.Errorf("restoring %s: %w", name, err)
|
|
}
|
|
rec, err := pocketbase.CreateWithFile[attachmentRecord](ctx, r.s.pb, "attachments", map[string]string{
|
|
"workspace": r.ws, "page": page, "name": name, "mime": str(a["mime"]), "uploader": r.c.ID,
|
|
"size": fmt.Sprint(f.UncompressedSize64),
|
|
}, "file", name, rc)
|
|
_ = rc.Close()
|
|
if err != nil {
|
|
return fmt.Errorf("restoring %s: %w", name, mapPB(err, "page not found"))
|
|
}
|
|
r.ids[str(a["id"])] = rec.ID
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// contents writes every page's document with the new ids in it: its Yjs
|
|
// state where the snapshot has one, so comment anchors (Yjs positions) keep
|
|
// pointing at their text, otherwise its JSON.
|
|
func (r *restorer) contents(ctx context.Context) error {
|
|
for _, p := range r.m.Pages {
|
|
id := r.ids[str(p["id"])]
|
|
if id == "" {
|
|
continue
|
|
}
|
|
fail := func(err error) error { return fmt.Errorf("restoring %q: %w", str(p["title"]), err) }
|
|
if f := r.files["pages/"+str(p["id"])+".ydoc"]; f != nil {
|
|
state, err := readZipEntry(f, 256<<20)
|
|
if err != nil {
|
|
return fail(err)
|
|
}
|
|
if err := r.s.docs.Apply(ctx, id, r.c.ID, r.ids.remapBinary(state)); err == nil {
|
|
continue
|
|
} else {
|
|
slog.Warn("snapshot restore: Yjs state refused, using JSON", "page", id, "err", err)
|
|
}
|
|
}
|
|
f := r.files["pages/"+str(p["id"])+".json"]
|
|
if f == nil {
|
|
continue
|
|
}
|
|
raw, err := readZipEntry(f, 256<<20)
|
|
if err != nil {
|
|
return fail(err)
|
|
}
|
|
if !json.Valid(raw) {
|
|
return fail(errors.New("its document is not JSON"))
|
|
}
|
|
if err := r.s.docs.Replace(ctx, id, r.c.ID, r.ids.remapJSON(bytes.TrimSpace(raw)), "import"); err != nil {
|
|
return fail(err)
|
|
}
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// remapBinary swaps old ids for new ones in a Yjs update. Ids are 15 ASCII
|
|
// bytes both ways, so every string keeps its length (and every clock its
|
|
// value): the update stays valid byte for byte.
|
|
func (m idMap) remapBinary(data []byte) []byte {
|
|
out := append([]byte(nil), data...)
|
|
isID := func(b byte) bool { return b >= 'a' && b <= 'z' || b >= '0' && b <= '9' }
|
|
for i := 0; i < len(out); {
|
|
if !isID(out[i]) {
|
|
i++
|
|
continue
|
|
}
|
|
j := i
|
|
for j < len(out) && isID(out[j]) {
|
|
j++
|
|
}
|
|
// Within a run of id characters, look at every 15-byte window.
|
|
for k := i; k+15 <= j; k++ {
|
|
if n, ok := m[string(out[k:k+15])]; ok && len(n) == 15 {
|
|
copy(out[k:k+15], n)
|
|
k += 14
|
|
}
|
|
}
|
|
i = j
|
|
}
|
|
return out
|
|
}
|
|
|
|
// comments restores threads, then their replies.
|
|
func (r *restorer) comments(ctx context.Context) error {
|
|
for _, replies := range []bool{false, true} {
|
|
for _, cm := range r.m.Comments {
|
|
if (str(cm["parent"]) != "") != replies {
|
|
continue
|
|
}
|
|
page := r.ids[str(cm["page"])]
|
|
if page == "" {
|
|
continue
|
|
}
|
|
author := str(cm["author"])
|
|
if !r.users[author] {
|
|
author = r.c.ID
|
|
}
|
|
body := map[string]any{
|
|
"workspace": r.ws, "page": page, "author": author, "body": cm["body"], "quote": cm["quote"],
|
|
"anchor": r.ids.remap(cm["anchor"]), "resolved_at": cm["resolved_at"], "edited_at": cm["edited_at"],
|
|
}
|
|
if replies {
|
|
if body["parent"] = r.ids[str(cm["parent"])]; body["parent"] == "" {
|
|
continue
|
|
}
|
|
}
|
|
if by := str(cm["resolved_by"]); r.users[by] {
|
|
body["resolved_by"] = by
|
|
}
|
|
if re, ok := cm["reactions"].(map[string]any); ok {
|
|
kept := map[string][]string{}
|
|
for emoji, who := range re {
|
|
list, _ := who.([]any)
|
|
for _, id := range list {
|
|
if r.users[str(id)] {
|
|
kept[emoji] = append(kept[emoji], str(id))
|
|
}
|
|
}
|
|
}
|
|
body["reactions"] = kept
|
|
}
|
|
id, err := r.create(ctx, "comments", body)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
r.ids[str(cm["id"])] = id
|
|
}
|
|
}
|
|
return nil
|
|
}
|