// SPDX-License-Identifier: AGPL-3.0-or-later package directory import ( "context" "encoding/json" "fmt" "log/slog" "net/url" "slices" "sort" "strings" "time" "docwell/server/internal/access" "docwell/server/internal/apperr" "docwell/server/internal/i18n" "docwell/server/internal/mail" "docwell/server/internal/push" "docwell/server/internal/store/pocketbase" ) // ---- Watching pages and notifications -------------------------------------- // // People watch a page explicitly, or automatically when they create it or // comment on it (unless they muted it). Watchers hear about new comments; // thread participants about replies and resolutions; people about being // mentioned or having a page shared with them, and about their own // reminders (reminders.go). Nobody is notified about their own actions, or // about a page they cannot open. Unread notifications go out as an email // digest unless the person turned that off. // Notification types stored in notifications.type. const ( NotifyComment = "comment" NotifyReply = "reply" NotifyMention = "mention" NotifyShare = "share" NotifyResolved = "resolved" // Workspace notifications, without a page (joinlinks.go). NotifyJoinRequest = "join_request" NotifyJoinApproved = "join_approved" NotifyJoinDeclined = "join_declined" ) // notifyRank decides which type wins when one event reaches someone for // several reasons (a mentioned watcher gets one "mention"). var notifyRank = map[string]int{NotifyComment: 1, NotifyResolved: 2, NotifyReply: 3, NotifyShare: 4, NotifyMention: 5, NotifyReminder: 6, NotifyVerifyExpired: 7} type watchRecord struct { ID string `json:"id"` Page string `json:"page"` User string `json:"user"` Watching bool `json:"watching"` } func (s *Service) watchRow(ctx context.Context, pageID, userID string) (watchRecord, error) { res, err := pocketbase.List[watchRecord](ctx, s.pb, "page_watchers", pocketbase.ListOptions{ PerPage: 1, Filter: fmt.Sprintf("page = '%s' && user = '%s'", pageID, userID), }) if err != nil || len(res.Items) == 0 { return watchRecord{}, err } return res.Items[0], nil } // WatchState is whether the caller watches a page. type WatchState struct { Watching bool `json:"watching"` } // GetWatch reports whether the caller watches a page (viewer). func (s *Service) GetWatch(ctx context.Context, c access.Caller, pageID string) (WatchState, error) { p, _, err := s.pageFor(ctx, c, pageID) if err != nil { return WatchState{}, err } row, err := s.watchRow(ctx, p.ID, c.ID) return WatchState{Watching: row.Watching}, err } // SetWatch starts or stops watching a page (viewer). Stopping is remembered, // so commenting later does not start it again. func (s *Service) SetWatch(ctx context.Context, c access.Caller, pageID string, on bool) (WatchState, error) { p, _, err := s.pageFor(ctx, c, pageID) if err != nil { return WatchState{}, err } row, err := s.watchRow(ctx, p.ID, c.ID) if err != nil { return WatchState{}, err } switch { case row.ID == "": _, err = pocketbase.Create[watchRecord](ctx, s.pb, "page_watchers", map[string]any{"page": p.ID, "user": c.ID, "watching": on}) case row.Watching != on: _, err = pocketbase.Update[watchRecord](ctx, s.pb, "page_watchers", row.ID, map[string]any{"watching": on}) } if err != nil { return WatchState{}, mapPB(err, "page not found") } return WatchState{Watching: on}, nil } // autoWatch starts watching for someone who took part in a page, unless they // already decided either way (best effort). func (s *Service) autoWatch(ctx context.Context, pageID, userID string) { row, err := s.watchRow(ctx, pageID, userID) if err != nil || row.ID != "" { return } _, _ = pocketbase.Create[watchRecord](ctx, s.pb, "page_watchers", map[string]any{"page": pageID, "user": userID, "watching": true}) } func (s *Service) watchers(ctx context.Context, pageID string) []string { rows, err := listAll[watchRecord](ctx, s, "page_watchers", pocketbase.ListOptions{ Filter: fmt.Sprintf("page = '%s' && watching = true", pageID), Fields: "user", }) if err != nil { return nil } out := make([]string, len(rows)) for i, r := range rows { out[i] = r.User } return out } // event is one thing that happened on a page, to tell people about. type event struct { actor string page pageRecord comment string excerpt string // to maps recipients to the notification type each gets. to map[string]string } func (e *event) add(userID, kind string) { if userID == "" || userID == e.actor { return } if notifyRank[kind] > notifyRank[e.to[userID]] { e.to[userID] = kind } } func excerpt(s string) string { s = strings.Join(strings.Fields(s), " ") if r := []rune(s); len(r) > 200 { return string(r[:199]) + "…" } return s } // Pusher sends a notification to a person's phones (package push). type Pusher interface { Notify(user string, m push.Message) } // UsePush turns on push notifications to phones. func (s *Service) UsePush(p Pusher) { s.push = p } // pushMessage is the phone notification for one stored notification. func (s *Service) pushMessage(ctx context.Context, e event, kind, lang string) push.Message { who := i18n.Sprintf(lang, "Someone") if e.actor != "" { if u, err := s.getUser(ctx, e.actor); err == nil { who = u.Name if who == "" { who = u.Email } } } title := strings.TrimSpace(e.page.Icon + " " + e.page.Title) if strings.TrimSpace(e.page.Title) == "" { title = strings.TrimSpace(e.page.Icon + " " + i18n.Sprintf(lang, "Untitled")) } var body string switch kind { case NotifyComment: body = i18n.Sprintf(lang, "%s commented", who) case NotifyReply: body = i18n.Sprintf(lang, "%s replied", who) case NotifyMention: body = i18n.Sprintf(lang, "%s mentioned you", who) case NotifyShare: body = i18n.Sprintf(lang, "%s shared this page with you", who) case NotifyResolved: body = i18n.Sprintf(lang, "%s resolved a thread", who) case NotifyReminder: body = i18n.Sprintf(lang, "Reminder") case NotifyVerifyExpired: body = i18n.Sprintf(lang, "Your verification of this page ran out") } if x := excerpt(e.excerpt); x != "" && kind != NotifyShare { body += ": " + x } route := "/p/" + e.page.ID if e.comment != "" { route += "?comment=" + url.QueryEscape(e.comment) } return push.Message{Title: title, Body: body, Route: route} } // send stores the event's notifications, for recipients who can still open // the page, and pushes them to their phones (best effort: a failure only // loses notifications). func (s *Service) send(ctx context.Context, e event) { for userID, kind := range e.to { if !validID(userID) { continue } u, err := s.getUser(ctx, userID) if err != nil || u.Status == "disabled" { continue } if _, _, _, err := s.pageAccess(ctx, u.Caller(), e.page.ID); err != nil { continue } body := map[string]any{ "user": userID, "workspace": e.page.Workspace, "page": e.page.ID, "type": kind, "excerpt": excerpt(e.excerpt), } if e.actor != "" { body["actor"] = e.actor } if e.comment != "" { body["comment"] = e.comment } if _, err := pocketbase.Create[struct{}](ctx, s.pb, "notifications", body); err != nil { slog.Default().Warn("notify: create", "user", userID, "err", err) continue } if s.push != nil { s.push.Notify(userID, s.pushMessage(ctx, e, kind, userLang(u.Locale))) } } } // notifyComment tells watchers about a new thread or reply, the thread's // people about a reply, and mentioned people that they were mentioned. func (s *Service) notifyComment(ctx context.Context, c access.Caller, p pageRecord, rec, root commentRecord, mentions []string) { e := event{actor: c.ID, page: p, comment: rec.ID, excerpt: rec.Body, to: map[string]string{}} for _, w := range s.watchers(ctx, p.ID) { e.add(w, NotifyComment) } if root.ID != "" { for _, uid := range s.threadPeople(ctx, root) { e.add(uid, NotifyReply) } } for i, uid := range mentions { if i >= 50 { break } e.add(uid, NotifyMention) } s.send(ctx, e) } // threadPeople are the authors in a thread. func (s *Service) threadPeople(ctx context.Context, root commentRecord) []string { out := []string{root.Author} replies, err := listAll[commentRecord](ctx, s, "comments", pocketbase.ListOptions{ Filter: fmt.Sprintf("parent = '%s'", root.ID), Fields: "author", }) if err == nil { for _, r := range replies { out = append(out, r.Author) } } return out } func (s *Service) notifyResolved(ctx context.Context, c access.Caller, p pageRecord, root commentRecord) { e := event{actor: c.ID, page: p, comment: root.ID, excerpt: root.Body, to: map[string]string{}} for _, uid := range s.threadPeople(ctx, root) { e.add(uid, NotifyResolved) } s.send(ctx, e) } func (s *Service) notifyShare(ctx context.Context, c access.Caller, p pageRecord, userID string) { e := event{actor: c.ID, page: p, excerpt: p.Title, to: map[string]string{}} e.add(userID, NotifyShare) s.send(ctx, e) } // mentionIDs collects the user ids of mention nodes in a Tiptap document. func mentionIDs(doc json.RawMessage) []string { var root any if json.Unmarshal(doc, &root) != nil { return nil } seen := map[string]bool{} var out []string var walk func(n any) walk = func(n any) { m, ok := n.(map[string]any) if !ok { return } if m["type"] == "mention" { if attrs, ok := m["attrs"].(map[string]any); ok { if id, ok := attrs["id"].(string); ok && validID(id) && !seen[id] { seen[id] = true out = append(out, id) } } } if kids, ok := m["content"].([]any); ok { for _, k := range kids { walk(k) } } } walk(root) sort.Strings(out) return out } // PageSaved is called after a page's content was saved by editor (the last // person who edited, possibly ""). It records which pages the page links to // (for backlinks) and notifies people mentioned for the first time. A page // that predates mention tracking (mentions still null) only records who it // mentions, so upgrading does not notify about old mentions. func (s *Service) PageSaved(ctx context.Context, pageID, editor string, doc json.RawMessage) { type rec struct { pageRecord Mentions json.RawMessage `json:"mentions"` Links json.RawMessage `json:"links"` } r, err := pocketbase.Get[rec](ctx, s.pb, "pages", pageID) if err != nil { return } if r.DeletedAt == "" { s.emitPage(ctx, "page.updated", r.pageRecord, editor, map[string]any{"change": "content"}) s.syncReminders(ctx, r.pageRecord, doc) } patch := map[string]any{} if links := linkIDs(doc, pageID); !sameIDs(r.Links, links) { patch["links"] = links } now := mentionIDs(doc) if now == nil { now = []string{} } known := len(r.Mentions) > 0 && string(r.Mentions) != "null" var before []string if known { _ = json.Unmarshal(r.Mentions, &before) } if !known || !sameIDs(r.Mentions, now) { patch["mentions"] = now } if len(patch) == 0 { return } if _, err := pocketbase.Update[struct{}](ctx, s.pb, "pages", pageID, patch); err != nil { return } if _, changed := patch["mentions"]; !changed || !known || r.DeletedAt != "" { return } had := map[string]bool{} for _, id := range before { had[id] = true } e := event{actor: editor, page: r.pageRecord, excerpt: r.Title, to: map[string]string{}} for _, id := range now { if !had[id] { e.add(id, NotifyMention) } } s.send(ctx, e) } // sameIDs reports whether a stored id list (JSON) holds exactly ids. func sameIDs(stored json.RawMessage, ids []string) bool { if len(stored) == 0 || string(stored) == "null" { return false } var have []string if json.Unmarshal(stored, &have) != nil { return false } return strings.Join(have, ",") == strings.Join(ids, ",") } // ---- Reading notifications ------------------------------------------------- type Notification struct { ID string `json:"id"` Type string `json:"type"` Workspace string `json:"workspace"` // Page is nil when the page is gone or the caller lost access to it. Page *PageRef `json:"page"` Comment string `json:"comment"` Actor *MemberUser `json:"actor"` Excerpt string `json:"excerpt"` Created string `json:"created"` Read bool `json:"read"` } type NotificationList struct { Items []Notification `json:"items"` Unread int `json:"unread"` } type notificationRecord struct { ID string `json:"id"` User string `json:"user"` Workspace string `json:"workspace"` Page string `json:"page"` Comment string `json:"comment"` Actor string `json:"actor"` Type string `json:"type"` Excerpt string `json:"excerpt"` ReadAt string `json:"read_at"` EmailedAt string `json:"emailed_at"` Created string `json:"created"` } func (s *Service) unreadCount(ctx context.Context, userID string) (int, error) { return s.count(ctx, "notifications", fmt.Sprintf("user = '%s' && read_at = ''", userID)) } // ListNotifications lists the caller's newest notifications (all, or only // unread ones) with the unread count. func (s *Service) ListNotifications(ctx context.Context, c access.Caller, unreadOnly bool, limit int) (NotificationList, error) { if limit <= 0 || limit > 100 { limit = 50 } filter := fmt.Sprintf("user = '%s'", c.ID) if unreadOnly { filter += " && read_at = ''" } res, err := pocketbase.List[notificationRecord](ctx, s.pb, "notifications", pocketbase.ListOptions{ PerPage: limit, Filter: filter, Sort: "-created,-id", }) if err != nil { return NotificationList{}, err } out := NotificationList{Items: []Notification{}} who := s.people() pages := map[string]*PageRef{} for _, r := range res.Items { n := Notification{ ID: r.ID, Type: r.Type, Workspace: r.Workspace, Comment: r.Comment, Actor: who.get(ctx, r.Actor), Excerpt: r.Excerpt, Created: r.Created, Read: r.ReadAt != "", } if r.Page != "" { ref, seen := pages[r.Page] if !seen { if p, _, err := s.pageFor(ctx, c, r.Page); err == nil && p.DeletedAt == "" { ref = &PageRef{ID: p.ID, Title: p.Title, Icon: p.Icon} } pages[r.Page] = ref } if ref == nil { // What happened on a page the caller can no longer open stays hidden. n.Excerpt, n.Comment = "", "" } n.Page = ref } out.Items = append(out.Items, n) } if out.Unread, err = s.unreadCount(ctx, c.ID); err != nil { return NotificationList{}, err } return out, nil } // MarkNotificationsRead marks the caller's notifications read: the listed // ones, or all of them. It returns the unread count afterwards. func (s *Service) MarkNotificationsRead(ctx context.Context, c access.Caller, ids []string, all bool) (int, error) { now := pbTime(time.Now()) if all { rows, err := listAll[notificationRecord](ctx, s, "notifications", pocketbase.ListOptions{ Filter: fmt.Sprintf("user = '%s' && read_at = ''", c.ID), Fields: "id", }) if err != nil { return 0, err } for _, r := range rows { ids = append(ids, r.ID) } } if len(ids) > 1000 { return 0, apperr.Invalid("too many notifications at once") } for _, id := range ids { if !validID(id) { continue } rec, err := pocketbase.Get[notificationRecord](ctx, s.pb, "notifications", id) if err != nil || rec.User != c.ID || rec.ReadAt != "" { continue // someone else's or already read: nothing to do } if _, err := pocketbase.Update[struct{}](ctx, s.pb, "notifications", id, map[string]any{"read_at": now}); err != nil { return 0, mapPB(err, "notification not found") } } return s.unreadCount(ctx, c.ID) } // NotificationSettings are the caller's notification preferences. type NotificationSettings struct { // Email is "digest" (unread notifications by email every few minutes) or "off". Email string `json:"email"` // EmailTypes are the notification types the digest includes; the others // only reach the inbox. Nil when setting means "leave as it is". EmailTypes []string `json:"emailTypes"` } // notificationTypes are every type a notification can have, in menu order. var notificationTypes = []string{"mention", "comment", "reply", "resolved", "share", "reminder", "verify_expired", "join_request"} // emailTypes is every notification type except the ones turned off. func emailTypes(off []string) []string { out := []string{} for _, t := range notificationTypes { if !slices.Contains(off, t) { out = append(out, t) } } return out } type notifyPrefs struct { NotifyEmail string `json:"notify_email"` NotifyEmailOff []string `json:"notify_email_off"` } func (s *Service) GetNotificationSettings(ctx context.Context, c access.Caller) (NotificationSettings, error) { r, err := pocketbase.Get[notifyPrefs](ctx, s.pb, "users", c.ID) if err != nil { return NotificationSettings{}, mapPB(err, "user not found") } if r.NotifyEmail != "off" { r.NotifyEmail = "digest" } return NotificationSettings{Email: r.NotifyEmail, EmailTypes: emailTypes(r.NotifyEmailOff)}, nil } func (s *Service) SetNotificationSettings(ctx context.Context, c access.Caller, in NotificationSettings) (NotificationSettings, error) { if in.Email != "digest" && in.Email != "off" { return NotificationSettings{}, apperr.InvalidFields(map[string]string{"email": "Choose digest or off."}) } patch := map[string]any{"notify_email": in.Email} if in.EmailTypes != nil { off := []string{} for _, t := range in.EmailTypes { if !slices.Contains(notificationTypes, t) { return NotificationSettings{}, apperr.InvalidFields(map[string]string{"emailTypes": "Unknown notification type " + t + "."}) } } for _, t := range notificationTypes { if !slices.Contains(in.EmailTypes, t) { off = append(off, t) } } patch["notify_email_off"] = off } if _, err := pocketbase.Update[struct{}](ctx, s.pb, "users", c.ID, patch); err != nil { return NotificationSettings{}, mapPB(err, "user not found") } return s.GetNotificationSettings(ctx, c) } // ---- Email digest ---------------------------------------------------------- // digestDelay leaves time to read a notification in the app before it is mailed. const digestDelay = 10 * time.Minute // digestItem is one line of a digest email. type digestItem struct { Text string Link string } func (s *Service) digestLine(ctx context.Context, n notificationRecord, who *people, lang string) (digestItem, bool) { if n.Page == "" { return s.workspaceDigestLine(ctx, n, who, lang) } p, err := s.getPage(ctx, n.Page) if err != nil || p.DeletedAt != "" { return digestItem{}, false } actor := who.get(ctx, n.Actor).display() if actor == "" { actor = i18n.Sprintf(lang, "Someone") } title := p.Title if title == "" { title = i18n.Sprintf(lang, "Untitled") } var text string switch n.Type { case NotifyComment: text = i18n.Sprintf(lang, "%s commented on “%s”", actor, title) case NotifyReply: text = i18n.Sprintf(lang, "%s replied in “%s”", actor, title) case NotifyMention: text = i18n.Sprintf(lang, "%s mentioned you in “%s”", actor, title) case NotifyShare: text = i18n.Sprintf(lang, "%s shared “%s”", actor, title) case NotifyResolved: text = i18n.Sprintf(lang, "%s resolved a thread in “%s”", actor, title) case NotifyReminder: text = i18n.Sprintf(lang, "Reminder in “%s”", title) case NotifyVerifyExpired: text = i18n.Sprintf(lang, "Your verification of “%s” ran out", title) default: return digestItem{}, false } if n.Excerpt != "" && n.Type != NotifyShare && n.Excerpt != p.Title { text += ": " + n.Excerpt } link := strings.TrimRight(s.mailer.WebURL, "/") + "/p/" + url.PathEscape(p.ID) if n.Comment != "" { link += "?comment=" + url.QueryEscape(n.Comment) } return digestItem{Text: text, Link: link}, true } // workspaceDigestLine is the digest line of a notification without a page. func (s *Service) workspaceDigestLine(ctx context.Context, n notificationRecord, who *people, lang string) (digestItem, bool) { ws, err := s.getWorkspace(ctx, n.Workspace) if err != nil { return digestItem{}, false } actor := who.get(ctx, n.Actor).display() if actor == "" { actor = i18n.Sprintf(lang, "Someone") } base := strings.TrimRight(s.mailer.WebURL, "/") switch n.Type { case NotifyJoinRequest: return digestItem{Text: i18n.Sprintf(lang, "%s asks to join “%s”", actor, ws.Name), Link: base + "/w/" + url.PathEscape(ws.ID) + "/settings"}, true case NotifyJoinApproved: return digestItem{Text: i18n.Sprintf(lang, "You can now open “%s”", ws.Name), Link: base + "/"}, true case NotifyJoinDeclined: return digestItem{Text: i18n.Sprintf(lang, "Your request to join “%s” was declined", ws.Name), Link: base + "/"}, true } return digestItem{}, false } // SendDigests emails each person their unread notifications that were not // mailed yet and are older than digestDelay, then marks them mailed. People // who turned email off are marked without a mail. It is a background job. func (s *Service) SendDigests(ctx context.Context) error { if s.mailer.Sender == nil { return nil } cutoff := pbTime(time.Now().Add(-digestDelay)) rows, err := listAll[notificationRecord](ctx, s, "notifications", pocketbase.ListOptions{ Filter: fmt.Sprintf("emailed_at = '' && read_at = '' && created <= '%s'", cutoff), Sort: "created", }) if err != nil { return err } byUser := map[string][]notificationRecord{} for _, r := range rows { byUser[r.User] = append(byUser[r.User], r) } appName := "Docwell" if s.mailer.AppName != nil { appName = s.mailer.AppName(ctx) } who := s.people() var firstErr error for userID, list := range byUser { u, err := pocketbase.Get[struct { Email string `json:"email"` Name string `json:"name"` Status string `json:"status"` NotifyEmail string `json:"notify_email"` NotifyEmailOff []string `json:"notify_email_off"` Locale string `json:"locale"` }](ctx, s.pb, "users", userID) if err == nil && u.NotifyEmail != "off" && u.Status != "disabled" { var items []digestItem for _, n := range list { // Types turned off stay in the inbox only (and are marked below). if slices.Contains(u.NotifyEmailOff, n.Type) { continue } if it, ok := s.digestLine(ctx, n, who, userLang(u.Locale)); ok { items = append(items, it) } } if len(items) > 0 { m, err := mail.RenderIn(userLang(u.Locale), u.Email, "digest", map[string]any{ "AppName": appName, "Name": u.Name, "Count": len(items), "Items": items, "SettingsLink": strings.TrimRight(s.mailer.WebURL, "/") + "/notifications", }) if err == nil { err = s.mailer.Sender.Send(ctx, m) } if err != nil { // Leave them unmailed; the next run tries again. if firstErr == nil { firstErr = err } continue } } } now := pbTime(time.Now()) for _, n := range list { _, _ = pocketbase.Update[struct{}](ctx, s.pb, "notifications", n.ID, map[string]any{"emailed_at": now}) } } return firstErr } // PruneNotifications deletes read notifications, and sent reminders, older // than 90 days. It is a background job. func (s *Service) PruneNotifications(ctx context.Context) error { cutoff := pbTime(time.Now().Add(-90 * 24 * time.Hour)) rows, err := listAll[notificationRecord](ctx, s, "notifications", pocketbase.ListOptions{ Filter: fmt.Sprintf("read_at != '' && created < '%s'", cutoff), Fields: "id", }) if err != nil { return err } for _, r := range rows { if err := s.pb.Delete(ctx, "notifications", r.ID); err != nil && !pocketbase.IsNotFound(err) { return err } } return s.pruneReminders(ctx) } // userLang is the language to write to a person in: the one they last used // the app in, else English. func userLang(locale string) string { if i18n.IsSupported(locale) { return locale } return i18n.Default }