Files
Docwell/Web-App/internal/spa/preview.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

138 lines
4.2 KiB
Go

// SPDX-License-Identifier: AGPL-3.0-or-later
package spa
import (
"bytes"
"context"
"encoding/json"
"html"
"io"
"net/http"
"net/url"
"regexp"
"strings"
"sync"
"time"
)
// Link previews for chat apps (ADR-17). When Slack, Teams, Discord and the
// like fetch a page or share link, the app shell they get has no title, so
// for their bots docwell-web asks docwell-server what to show and writes it
// into the page's meta tags. People's browsers never wait for this.
// Preview is what docwell-server's preview endpoints answer.
type Preview struct {
Title string `json:"title"`
Description string `json:"description"`
Site string `json:"site"`
}
// previewBots matches the user agents of chat apps' link-preview fetchers.
// Search engines are left out on purpose: they must not learn the titles of
// private pages.
var previewBots = regexp.MustCompile(`(?i)slackbot|slack-imgproxy|twitterbot|facebookexternalhit|discordbot|telegrambot|whatsapp|linkedinbot|mattermost|skypeuripreview|microsoftpreview|embedly|iframely|redditbot|zulip|rocket\.chat|synapse|nextcloud server crawler|viber`)
var (
pagePath = regexp.MustCompile(`^/p/([A-Za-z0-9_-]{1,64})$`)
sharePath = regexp.MustCompile(`^/share/([A-Za-z0-9_-]{1,64})(?:/p/([A-Za-z0-9_-]{1,64}))?$`)
)
// previewer looks previews up on docwell-server and remembers them briefly.
type previewer struct {
api *url.URL
client *http.Client
mu sync.Mutex
cache map[string]cachedPreview
}
type cachedPreview struct {
p *Preview
exp time.Time
}
func newPreviewer(api *url.URL) *previewer {
return &previewer{api: api, client: &http.Client{Timeout: 3 * time.Second}, cache: map[string]cachedPreview{}}
}
// endpoint maps an app path to its preview endpoint ("" when it has none).
func endpoint(p string) string {
if m := pagePath.FindStringSubmatch(p); m != nil {
return "/api/v1/previews/pages/" + m[1]
}
if m := sharePath.FindStringSubmatch(p); m != nil {
e := "/api/v1/previews/share/" + m[1]
if m[2] != "" {
e += "?page=" + url.QueryEscape(m[2])
}
return e
}
return ""
}
// lookup returns the preview for an app path, or nil.
func (v *previewer) lookup(ctx context.Context, p string) *Preview {
e := endpoint(p)
if e == "" {
return nil
}
now := time.Now()
v.mu.Lock()
if c, ok := v.cache[e]; ok && now.Before(c.exp) {
v.mu.Unlock()
return c.p
}
v.mu.Unlock()
var out *Preview
// The host is docwell-server's from configuration; e only carries ids the
// path patterns above allowed.
u := strings.TrimRight(v.api.String(), "/") + e
if req, err := http.NewRequestWithContext(ctx, http.MethodGet, u, nil); err == nil { //nolint:gosec // see above
if resp, err := v.client.Do(req); err == nil { //nolint:gosec // see above
if resp.StatusCode == http.StatusOK {
var p Preview
if json.NewDecoder(io.LimitReader(resp.Body, 64<<10)).Decode(&p) == nil && p.Title != "" {
out = &p
}
}
resp.Body.Close()
}
}
v.mu.Lock()
if len(v.cache) > 1000 {
v.cache = map[string]cachedPreview{}
}
v.cache[e] = cachedPreview{p: out, exp: now.Add(time.Minute)}
v.mu.Unlock()
return out
}
// withPreview writes p's title and meta tags into the app shell's head.
func withPreview(index []byte, p *Preview) []byte {
esc := html.EscapeString
var b strings.Builder
b.WriteString("<title>" + esc(p.Title) + "</title>")
b.WriteString(`<meta property="og:type" content="article">`)
b.WriteString(`<meta property="og:title" content="` + esc(p.Title) + `">`)
if p.Description != "" {
b.WriteString(`<meta property="og:description" content="` + esc(p.Description) + `">`)
b.WriteString(`<meta name="description" content="` + esc(p.Description) + `">`)
}
if p.Site != "" {
b.WriteString(`<meta property="og:site_name" content="` + esc(p.Site) + `">`)
}
b.WriteString(`<meta name="twitter:card" content="summary">`)
b.WriteString(`<meta name="robots" content="noindex">`)
// The shell's own <title> would come first and win.
out := titleTag.ReplaceAll(index, nil)
if i := bytes.Index(bytes.ToLower(out), []byte("</head>")); i >= 0 {
return append(out[:i:i], append([]byte(b.String()), out[i:]...)...)
}
return append([]byte(b.String()), out...)
}
var titleTag = regexp.MustCompile(`(?is)<title>.*?</title>`)