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
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>
228 lines
6.8 KiB
Go
228 lines
6.8 KiB
Go
// SPDX-License-Identifier: AGPL-3.0-or-later
|
|
|
|
package directory
|
|
|
|
import (
|
|
"context"
|
|
"fmt"
|
|
"log/slog"
|
|
"sort"
|
|
"sync"
|
|
"time"
|
|
|
|
"docwell/server/internal/access"
|
|
"docwell/server/internal/apperr"
|
|
"docwell/server/internal/store/pocketbase"
|
|
)
|
|
|
|
// ---- Page analytics --------------------------------------------------------
|
|
//
|
|
// Opening a page counts a view (ADR-17): the apps already report each open
|
|
// for the recent list (RecordVisit), and share links count their visitors
|
|
// without a name. Views
|
|
// are kept per page, person and day, so a page's editors can see how often
|
|
// it is read, by how many people, and who read it last. Someone who keeps a
|
|
// page open and comes back to it counts once per viewGap.
|
|
|
|
// viewGap is how long a person's repeated opens of one page count as one view.
|
|
const viewGap = 30 * time.Minute
|
|
|
|
// viewRetention is how long daily view counts are kept.
|
|
const viewRetention = 400 * 24 * time.Hour
|
|
|
|
type pageViewRecord struct {
|
|
ID string `json:"id"`
|
|
Page string `json:"page"`
|
|
Workspace string `json:"workspace"`
|
|
User string `json:"user"`
|
|
Day string `json:"day"`
|
|
Views int `json:"views"`
|
|
Last string `json:"last"`
|
|
}
|
|
|
|
// viewLog remembers recent opens so repeated ones are not counted, and
|
|
// serialises the read-modify-write of the daily rows.
|
|
type viewLog struct {
|
|
mu sync.Mutex
|
|
seen map[string]time.Time
|
|
}
|
|
|
|
var views = &viewLog{seen: map[string]time.Time{}}
|
|
|
|
// fresh reports whether key's open counts, and remembers it.
|
|
func (l *viewLog) fresh(key string, now time.Time) bool {
|
|
if last, ok := l.seen[key]; ok && now.Sub(last) < viewGap {
|
|
return false
|
|
}
|
|
l.seen[key] = now
|
|
if len(l.seen) > 50000 {
|
|
for k, t := range l.seen {
|
|
if now.Sub(t) >= viewGap {
|
|
delete(l.seen, k)
|
|
}
|
|
}
|
|
}
|
|
return true
|
|
}
|
|
|
|
// recordView counts one open of p by userID ("" for a share-link visitor).
|
|
// It is best effort: a failure only loses the count.
|
|
func (s *Service) recordView(ctx context.Context, p pageRecord, userID string) {
|
|
now := time.Now().UTC()
|
|
views.mu.Lock()
|
|
defer views.mu.Unlock()
|
|
if userID != "" && !views.fresh(p.ID+"|"+userID, now) {
|
|
return
|
|
}
|
|
day := now.Format(time.DateOnly)
|
|
res, err := pocketbase.List[pageViewRecord](ctx, s.pb, "page_views", pocketbase.ListOptions{
|
|
PerPage: 1, Filter: fmt.Sprintf("page = '%s' && user = '%s' && day = '%s'", p.ID, userID, day),
|
|
})
|
|
if err == nil && len(res.Items) > 0 {
|
|
_, err = pocketbase.Update[struct{}](ctx, s.pb, "page_views", res.Items[0].ID, map[string]any{
|
|
"views+": 1, "last": pbTime(now),
|
|
})
|
|
} else if err == nil {
|
|
body := map[string]any{"page": p.ID, "workspace": p.Workspace, "day": day, "views": 1, "last": pbTime(now)}
|
|
if userID != "" {
|
|
body["user"] = userID
|
|
}
|
|
_, err = pocketbase.Create[struct{}](ctx, s.pb, "page_views", body)
|
|
}
|
|
if err != nil {
|
|
slog.Default().Warn("analytics: record view", "page", p.ID, "err", err)
|
|
}
|
|
}
|
|
|
|
// AnalyticsDay is one day of a page's views.
|
|
type AnalyticsDay struct {
|
|
Date string `json:"date"`
|
|
Views int `json:"views"`
|
|
Viewers int `json:"viewers"`
|
|
}
|
|
|
|
// PageViewer is someone who opened the page in the period.
|
|
type PageViewer struct {
|
|
User MemberUser `json:"user"`
|
|
Views int `json:"views"`
|
|
LastViewed string `json:"lastViewed"`
|
|
}
|
|
|
|
// PageAnalytics sums up a page's views over the last Days days.
|
|
type PageAnalytics struct {
|
|
Days int `json:"days"`
|
|
// Views counts every counted open; Viewers the different signed-in
|
|
// people; LinkViews the opens through a share link.
|
|
Views int `json:"views"`
|
|
Viewers int `json:"viewers"`
|
|
LinkViews int `json:"linkViews"`
|
|
Daily []AnalyticsDay `json:"daily"`
|
|
// Recent lists who opened the page, most recent first (at most 20).
|
|
Recent []PageViewer `json:"recent"`
|
|
}
|
|
|
|
// GetPageAnalytics returns a page's views for the last days days (7 to 90,
|
|
// default 30; editor).
|
|
func (s *Service) GetPageAnalytics(ctx context.Context, c access.Caller, pageID string, days int) (PageAnalytics, error) {
|
|
p, a, err := s.pageFor(ctx, c, pageID)
|
|
if err != nil {
|
|
return PageAnalytics{}, err
|
|
}
|
|
if err := access.EditPages(a.role); err != nil {
|
|
return PageAnalytics{}, apperr.Forbidden("only the page's editors can see its views")
|
|
}
|
|
if days == 0 {
|
|
days = 30
|
|
}
|
|
if days < 7 || days > 90 {
|
|
return PageAnalytics{}, apperr.InvalidFields(map[string]string{"days": "Pick 7 to 90 days."})
|
|
}
|
|
now := time.Now().UTC()
|
|
first := now.AddDate(0, 0, -(days - 1)).Format(time.DateOnly)
|
|
rows, err := listAll[pageViewRecord](ctx, s, "page_views", pocketbase.ListOptions{
|
|
Filter: fmt.Sprintf("page = '%s' && day >= '%s'", p.ID, first), Sort: "day",
|
|
})
|
|
if err != nil {
|
|
return PageAnalytics{}, err
|
|
}
|
|
return s.summarise(ctx, rows, now, days), nil
|
|
}
|
|
|
|
// summarise turns daily rows into PageAnalytics and names the recent viewers.
|
|
func (s *Service) summarise(ctx context.Context, rows []pageViewRecord, now time.Time, days int) PageAnalytics {
|
|
out, viewers := aggregateViews(rows, now, days)
|
|
who := s.people()
|
|
for _, v := range viewers {
|
|
if len(out.Recent) == 20 {
|
|
break
|
|
}
|
|
u := who.get(ctx, v.User.ID)
|
|
if u == nil {
|
|
continue
|
|
}
|
|
v.User = *u
|
|
out.Recent = append(out.Recent, v)
|
|
}
|
|
return out
|
|
}
|
|
|
|
// aggregateViews sums daily rows over the days ending today, with an entry
|
|
// for every day, and returns the signed-in viewers most recent first.
|
|
func aggregateViews(rows []pageViewRecord, now time.Time, days int) (PageAnalytics, []PageViewer) {
|
|
out := PageAnalytics{Days: days, Daily: make([]AnalyticsDay, days), Recent: []PageViewer{}}
|
|
index := map[string]int{}
|
|
for i := range days {
|
|
d := now.AddDate(0, 0, -(days - 1 - i)).Format(time.DateOnly)
|
|
out.Daily[i].Date = d
|
|
index[d] = i
|
|
}
|
|
people := map[string]*PageViewer{}
|
|
for _, r := range rows {
|
|
i, ok := index[r.Day]
|
|
if !ok {
|
|
continue
|
|
}
|
|
out.Views += r.Views
|
|
out.Daily[i].Views += r.Views
|
|
if r.User == "" {
|
|
out.LinkViews += r.Views
|
|
continue
|
|
}
|
|
out.Daily[i].Viewers++
|
|
v := people[r.User]
|
|
if v == nil {
|
|
v = &PageViewer{User: MemberUser{ID: r.User}}
|
|
people[r.User] = v
|
|
}
|
|
v.Views += r.Views
|
|
if r.Last > v.LastViewed {
|
|
v.LastViewed = r.Last
|
|
}
|
|
}
|
|
out.Viewers = len(people)
|
|
list := make([]PageViewer, 0, len(people))
|
|
for _, v := range people {
|
|
list = append(list, *v)
|
|
}
|
|
sort.Slice(list, func(i, j int) bool { return list[i].LastViewed > list[j].LastViewed })
|
|
return out, list
|
|
}
|
|
|
|
// PruneViews deletes daily view counts older than viewRetention. It is a
|
|
// background job.
|
|
func (s *Service) PruneViews(ctx context.Context) error {
|
|
cutoff := time.Now().UTC().Add(-viewRetention).Format(time.DateOnly)
|
|
rows, err := listAll[pageViewRecord](ctx, s, "page_views", pocketbase.ListOptions{
|
|
Filter: fmt.Sprintf("day < '%s'", cutoff), Fields: "id",
|
|
})
|
|
if err != nil {
|
|
return err
|
|
}
|
|
for _, r := range rows {
|
|
if err := s.pb.Delete(ctx, "page_views", r.ID); err != nil && !pocketbase.IsNotFound(err) {
|
|
return err
|
|
}
|
|
}
|
|
return nil
|
|
}
|