Files
Docwell/Server/internal/directory/cleanup.go
T
tajniak81andClaude Opus 5.5 9d674e9699
CI / go (Media) (push) Successful in 14m33s
CI / go (Server) (push) Failing after 23m30s
CI / go (Web-App) (push) Canceled after 0s
CI / frontend (push) Failing after 9m30s
CI / desktop (ubuntu-latest) (push) Successful in 1h21m24s
CI / mobile (push) Failing after 4m16s
CI / docker (push) Successful in 1h1m25s
Docs / build (push) Successful in 14m59s
Docs / deploy (push) Skipped
CI / desktop (macos-latest) (push) Canceled after 0s
CI / desktop (windows-latest) (push) Canceled after 0s
Add invite links with approval, sharing switches, page views and unused-file cleanup
Phase G of docs/AFFINE.md (ADR-17):

- Invite links: one per workspace (member or guest, optional end date,
  optional admin approval) on a new /join page. Requests are approved
  (optionally as another role) or declined from workspace settings;
  join_request, join_approved and join_declined notifications reach the
  inbox, phones and the email digest. Workspace admins decide, else the
  organization's admins, else superadmins. Signup honours ?redirect=.
- Workspace switches: allowSharing (off makes every share link answer 404
  until it is back on) and urlPreview (chat apps may show private pages'
  titles). docwell-web writes title and Open Graph tags for known
  link-preview bots, asking docwell-server via DOCWELL_PREVIEW_API_URL;
  search engines are left out.
- Page analytics: page_views counts opens per page, person and day from
  the existing visit call and share-link reads; editors see totals, a
  daily chart and recent viewers in the Info panel. analytics.prune
  drops rows after 400 days.
- Unused files: attachments whose id appears in no page's Yjs state,
  page icon or comment (older than a day) are listed and deleted from
  workspace settings.
- Migration, schema snapshot, OpenAPI, generated clients, translations
  in five languages, phone inbox, compose files and user docs.

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

166 lines
4.6 KiB
Go

// SPDX-License-Identifier: AGPL-3.0-or-later
package directory
import (
"bytes"
"context"
"fmt"
"slices"
"strings"
"time"
"docwell/server/internal/access"
"docwell/server/internal/apperr"
"docwell/server/internal/store/pocketbase"
)
// ---- Unused files ----------------------------------------------------------
//
// A file stays on the server after the block that showed it is deleted, so
// undo and copy-paste keep working. Workspace admins can list the files no
// page of the workspace uses any more and delete them (ADR-17). A file is in
// use when its id appears in the current document of any page in the
// workspace (trashed pages included, since they can be restored), in a page
// icon or in a comment. Files younger than unusedGrace never count as
// unused: they may be on their way into a page. Old page versions are not
// searched, so restoring a version from before a cleanup can show missing
// files; the settings page says so.
const unusedGrace = 24 * time.Hour
// UnusedFile is a file no page uses.
type UnusedFile struct {
Attachment
// PageTitle names the page the file was uploaded to; empty when the
// caller cannot open that page.
PageTitle string `json:"pageTitle"`
}
// UnusedFiles lists them with their total size.
type UnusedFiles struct {
Files []UnusedFile `json:"files"`
Size int64 `json:"size"`
}
// unusedFiles finds the workspace's unused attachments.
func (s *Service) unusedFiles(ctx context.Context, wsID string) ([]attachmentRecord, error) {
cutoff := pbTime(time.Now().Add(-unusedGrace))
files, err := listAll[attachmentRecord](ctx, s, "attachments", pocketbase.ListOptions{
Filter: fmt.Sprintf("workspace = '%s' && created < '%s'", wsID, cutoff), Sort: "created",
})
if err != nil || len(files) == 0 {
return nil, err
}
pending := map[string]bool{}
for _, f := range files {
pending[f.ID] = true
}
// mark crosses off every pending id found in b.
mark := func(b []byte) {
for id := range pending {
if bytes.Contains(b, []byte(id)) {
delete(pending, id)
}
}
}
pages, err := listAll[struct {
ID string `json:"id"`
Icon string `json:"icon"`
}](ctx, s, "pages", pocketbase.ListOptions{Filter: fmt.Sprintf("workspace = '%s'", wsID), Fields: "id,icon"})
if err != nil {
return nil, err
}
for _, p := range pages {
if len(pending) == 0 {
break
}
mark([]byte(p.Icon))
state, err := s.docs.State(ctx, p.ID)
if err != nil {
// Without the document nothing can be ruled out.
return nil, fmt.Errorf("unused files: page %s: %w", p.ID, err)
}
mark(state)
}
if len(pending) > 0 {
comments, err := listAll[struct {
Body string `json:"body"`
}](ctx, s, "comments", pocketbase.ListOptions{
Filter: fmt.Sprintf("page.workspace = '%s' && body ~ '/api/v1/files/'", wsID), Fields: "body",
})
if err != nil {
return nil, err
}
for _, c := range comments {
mark([]byte(c.Body))
}
}
out := files[:0]
for _, f := range files {
if pending[f.ID] {
out = append(out, f)
}
}
return out, nil
}
// ListUnusedFiles lists the files no page of the workspace uses (workspace admin).
func (s *Service) ListUnusedFiles(ctx context.Context, c access.Caller, wsID string) (UnusedFiles, error) {
ws, _, err := s.adminWorkspace(ctx, c, wsID)
if err != nil {
return UnusedFiles{}, err
}
files, err := s.unusedFiles(ctx, ws.ID)
if err != nil {
return UnusedFiles{}, err
}
out := UnusedFiles{Files: make([]UnusedFile, 0, len(files))}
titles := map[string]string{}
for _, f := range files {
title, seen := titles[f.Page]
if !seen {
if p, _, err := s.pageFor(ctx, c, f.Page); err == nil {
title = p.Title
if strings.TrimSpace(title) == "" {
title = "Untitled"
}
}
titles[f.Page] = title
}
out.Files = append(out.Files, UnusedFile{Attachment: f.view(), PageTitle: title})
out.Size += f.Size
}
return out, nil
}
// DeleteUnusedFiles deletes unused files of the workspace: the listed ones,
// or all of them when ids is empty. Files that came into use since the list
// was made are kept. It returns how many were deleted (workspace admin).
func (s *Service) DeleteUnusedFiles(ctx context.Context, c access.Caller, wsID string, ids []string) (int, error) {
ws, _, err := s.adminWorkspace(ctx, c, wsID)
if err != nil {
return 0, err
}
if len(ids) > 10000 {
return 0, apperr.Invalid("too many files")
}
files, err := s.unusedFiles(ctx, ws.ID)
if err != nil {
return 0, err
}
n := 0
for _, f := range files {
if len(ids) > 0 && !slices.Contains(ids, f.ID) {
continue
}
if err := s.pb.Delete(ctx, "attachments", f.ID); err != nil && !pocketbase.IsNotFound(err) {
return n, err
}
n++
}
return n, nil
}