Add comment threads, reactions, notifications and page watching
Comments are now threads: replies hang off a thread's first comment, which alone points at text and can be resolved. Authors can edit their own comments, and anyone who can comment can react with an emoji. Resolved threads stop lighting text in the editor and fold away in the panel. Comments can @mention people. People watch the pages they create or comment on, and can watch or mute a page from its menu. Muting is remembered. The inbox collects comments on watched pages, replies in your threads, mentions (in comments and in page text), pages shared with you and resolved threads. It shows an unread badge in the sidebar, polled every minute, and links straight to the thread. Nobody hears about their own actions or about pages they cannot open, and a notification hides its text once access is lost. Unread notifications are emailed as a digest every few minutes unless the person turns that off. Read ones are pruned after 90 days. The jobs registry can now run jobs on a timer. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
7968e82cc2
commit
2b78c167e2
31 files changed
+3083
-166
No files matched your search
@@ -68,6 +68,11 @@ func run(log *slog.Logger) error {
|
||||
Store: collab.NewPBStore(db), Docs: ycrdt.NewPool(yrs, max(2, runtime.GOMAXPROCS(0))), Log: log,
|
||||
})
|
||||
dirSvc := directory.New(db, authSvc.Forget, hub)
|
||||
hub.OnSaved(func(page, editor string, doc []byte) {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), time.Minute)
|
||||
defer cancel()
|
||||
dirSvc.PageSaved(ctx, page, editor, doc)
|
||||
})
|
||||
// The search index follows PocketBase and can be rebuilt from it at any time.
|
||||
index, err := search.Open(cfg.DataDir, db, log)
|
||||
if err != nil {
|
||||
@@ -78,10 +83,14 @@ func run(log *slog.Logger) error {
|
||||
reg.Register("search.index", "Adds changed pages to the search index", 3*time.Second, nil)
|
||||
reg.Register("search.sweep", "Removes deleted pages from the search index", 10*time.Minute, index.Sweep)
|
||||
reg.Register("search.rebuild", "Rebuilds the whole search index from the database", 0, index.Rebuild)
|
||||
reg.Register("notify.digest", "Emails people their unread notifications", 5*time.Minute, dirSvc.SendDigests)
|
||||
reg.Register("notify.prune", "Deletes read notifications older than 90 days", 24*time.Hour, dirSvc.PruneNotifications)
|
||||
index.Track(reg.Track)
|
||||
indexCtx, stopIndex := context.WithCancel(context.Background())
|
||||
defer stopIndex()
|
||||
go index.Run(indexCtx, 3*time.Second, 10*time.Minute)
|
||||
go reg.Every(indexCtx, "notify.digest", 5*time.Minute)
|
||||
go reg.Every(indexCtx, "notify.prune", 24*time.Hour)
|
||||
dirSvc.UseSearch(index)
|
||||
dirSvc.SetPublicURL(cfg.PublicURL)
|
||||
dirSvc.SetMaxUpload(int64(cfg.MaxUploadMB) << 20)
|
||||
|
||||
@@ -181,3 +181,16 @@ func ViewGroups(wsRole string) error {
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// EditComment: only the author changes what they wrote.
|
||||
func EditComment(actorID, authorID string) error {
|
||||
if actorID == "" || actorID != authorID {
|
||||
return apperr.Forbidden("only the author can edit this comment")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// ResolveComment and ReactToComment need commenter, like writing one.
|
||||
func ResolveComment(pageRole string) error { return CommentPages(pageRole) }
|
||||
|
||||
func ReactToComment(pageRole string) error { return CommentPages(pageRole) }
|
||||
@@ -111,3 +111,24 @@ func TestCommentRules(t *testing.T) {
|
||||
t.Error("an empty author is nobody's comment")
|
||||
}
|
||||
}
|
||||
|
||||
func TestCommentActions(t *testing.T) {
|
||||
cases := []struct {
|
||||
name string
|
||||
err error
|
||||
want apperr.Kind
|
||||
}{
|
||||
{"author edits", EditComment("u1", "u1"), ok},
|
||||
{"others cannot edit", EditComment("u2", "u1"), forbidden},
|
||||
{"anonymous cannot edit", EditComment("", ""), forbidden},
|
||||
{"viewer cannot resolve", ResolveComment(SpaceViewer), forbidden},
|
||||
{"commenter resolves", ResolveComment(SpaceCommenter), ok},
|
||||
{"viewer cannot react", ReactToComment(SpaceViewer), forbidden},
|
||||
{"no access hides", ReactToComment(""), notFound},
|
||||
}
|
||||
for _, c := range cases {
|
||||
if got := kind(c.err); got != c.want {
|
||||
t.Errorf("%s: got kind %v, want %v (%v)", c.name, got, c.want, c.err)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -48,6 +48,51 @@ func (e InviteStatus) Valid() bool {
|
||||
}
|
||||
}
|
||||
|
||||
// Defines values for NotificationSettingsEmail.
|
||||
const (
|
||||
Digest NotificationSettingsEmail = "digest"
|
||||
Off NotificationSettingsEmail = "off"
|
||||
)
|
||||
|
||||
// Valid indicates whether the value is a known member of the NotificationSettingsEmail enum.
|
||||
func (e NotificationSettingsEmail) Valid() bool {
|
||||
switch e {
|
||||
case Digest:
|
||||
return true
|
||||
case Off:
|
||||
return true
|
||||
default:
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
// Defines values for NotificationType.
|
||||
const (
|
||||
NotificationTypeComment NotificationType = "comment"
|
||||
NotificationTypeMention NotificationType = "mention"
|
||||
NotificationTypeReply NotificationType = "reply"
|
||||
NotificationTypeResolved NotificationType = "resolved"
|
||||
NotificationTypeShare NotificationType = "share"
|
||||
)
|
||||
|
||||
// Valid indicates whether the value is a known member of the NotificationType enum.
|
||||
func (e NotificationType) Valid() bool {
|
||||
switch e {
|
||||
case NotificationTypeComment:
|
||||
return true
|
||||
case NotificationTypeMention:
|
||||
return true
|
||||
case NotificationTypeReply:
|
||||
return true
|
||||
case NotificationTypeResolved:
|
||||
return true
|
||||
case NotificationTypeShare:
|
||||
return true
|
||||
default:
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
// Defines values for PageGrantType.
|
||||
const (
|
||||
PageGrantTypeGroup PageGrantType = "group"
|
||||
@@ -398,10 +443,27 @@ type Comment struct {
|
||||
Author MemberUser `json:"author"`
|
||||
Body string `json:"body"`
|
||||
CanDelete bool `json:"canDelete"`
|
||||
Created string `json:"created"`
|
||||
Id string `json:"id"`
|
||||
Page string `json:"page"`
|
||||
Quote string `json:"quote"`
|
||||
CanEdit bool `json:"canEdit"`
|
||||
|
||||
// CanResolve A thread the caller may resolve or reopen
|
||||
CanResolve bool `json:"canResolve"`
|
||||
Created string `json:"created"`
|
||||
|
||||
// EditedAt Empty when never edited
|
||||
EditedAt string `json:"editedAt"`
|
||||
Id string `json:"id"`
|
||||
Page string `json:"page"`
|
||||
|
||||
// Parent The thread's first comment for a reply; empty for a thread
|
||||
Parent string `json:"parent"`
|
||||
Quote string `json:"quote"`
|
||||
|
||||
// Reactions Most used first
|
||||
Reactions []Reaction `json:"reactions"`
|
||||
|
||||
// ResolvedAt Empty unless the thread is resolved
|
||||
ResolvedAt string `json:"resolvedAt"`
|
||||
ResolvedBy *MemberUser `json:"resolvedBy"`
|
||||
}
|
||||
|
||||
// CreateInviteRequest defines model for CreateInviteRequest.
|
||||
@@ -568,6 +630,41 @@ type NameRequest struct {
|
||||
Name string `json:"name"`
|
||||
}
|
||||
|
||||
// Notification defines model for Notification.
|
||||
type Notification struct {
|
||||
Actor *MemberUser `json:"actor"`
|
||||
|
||||
// Comment The comment it is about
|
||||
Comment string `json:"comment"`
|
||||
Created string `json:"created"`
|
||||
Excerpt string `json:"excerpt"`
|
||||
Id string `json:"id"`
|
||||
|
||||
// Page Null when the page is gone or the caller lost access to it
|
||||
Page *PageRef `json:"page"`
|
||||
Read bool `json:"read"`
|
||||
Type NotificationType `json:"type"`
|
||||
Workspace string `json:"workspace"`
|
||||
}
|
||||
|
||||
// NotificationList defines model for NotificationList.
|
||||
type NotificationList struct {
|
||||
Items []Notification `json:"items"`
|
||||
Unread int `json:"unread"`
|
||||
}
|
||||
|
||||
// NotificationSettings defines model for NotificationSettings.
|
||||
type NotificationSettings struct {
|
||||
// Email Unread notifications by email every few minutes
|
||||
Email NotificationSettingsEmail `json:"email"`
|
||||
}
|
||||
|
||||
// NotificationSettingsEmail Unread notifications by email every few minutes
|
||||
type NotificationSettingsEmail string
|
||||
|
||||
// NotificationType defines model for NotificationType.
|
||||
type NotificationType string
|
||||
|
||||
// Organization defines model for Organization.
|
||||
type Organization struct {
|
||||
Created string `json:"created"`
|
||||
@@ -725,6 +822,16 @@ type PublicSettings struct {
|
||||
Signup bool `json:"signup"`
|
||||
}
|
||||
|
||||
// Reaction defines model for Reaction.
|
||||
type Reaction struct {
|
||||
Count int `json:"count"`
|
||||
Emoji string `json:"emoji"`
|
||||
Mine bool `json:"mine"`
|
||||
|
||||
// People Names of the people who reacted
|
||||
People []string `json:"people"`
|
||||
}
|
||||
|
||||
// Role Instance role. admin manages their own organization; superadmin manages everything.
|
||||
type Role string
|
||||
|
||||
@@ -958,6 +1065,11 @@ type Version struct {
|
||||
Version string `json:"version"`
|
||||
}
|
||||
|
||||
// WatchState defines model for WatchState.
|
||||
type WatchState struct {
|
||||
Watching bool `json:"watching"`
|
||||
}
|
||||
|
||||
// Workspace defines model for Workspace.
|
||||
type Workspace struct {
|
||||
Created string `json:"created"`
|
||||
@@ -1012,6 +1124,22 @@ type ConfirmVerificationJSONBody struct {
|
||||
Token string `json:"token"`
|
||||
}
|
||||
|
||||
// UpdateCommentJSONBody defines parameters for UpdateComment.
|
||||
type UpdateCommentJSONBody struct {
|
||||
Body string `json:"body"`
|
||||
}
|
||||
|
||||
// ReactToCommentJSONBody defines parameters for ReactToComment.
|
||||
type ReactToCommentJSONBody struct {
|
||||
Emoji string `json:"emoji"`
|
||||
On bool `json:"on"`
|
||||
}
|
||||
|
||||
// ResolveCommentJSONBody defines parameters for ResolveComment.
|
||||
type ResolveCommentJSONBody struct {
|
||||
Resolved bool `json:"resolved"`
|
||||
}
|
||||
|
||||
// DownloadFileParams defines parameters for DownloadFile.
|
||||
type DownloadFileParams struct {
|
||||
Token *string `form:"token,omitempty" json:"token,omitempty"`
|
||||
@@ -1025,6 +1153,19 @@ type ListInvitesParams struct {
|
||||
Organization *string `form:"organization,omitempty" json:"organization,omitempty"`
|
||||
}
|
||||
|
||||
// ListNotificationsParams defines parameters for ListNotifications.
|
||||
type ListNotificationsParams struct {
|
||||
// Unread Only unread ones
|
||||
Unread *bool `form:"unread,omitempty" json:"unread,omitempty"`
|
||||
Limit *int `form:"limit,omitempty" json:"limit,omitempty"`
|
||||
}
|
||||
|
||||
// MarkNotificationsReadJSONBody defines parameters for MarkNotificationsRead.
|
||||
type MarkNotificationsReadJSONBody struct {
|
||||
All *bool `json:"all,omitempty"`
|
||||
Ids *[]string `json:"ids,omitempty"`
|
||||
}
|
||||
|
||||
// DeletePageParams defines parameters for DeletePage.
|
||||
type DeletePageParams struct {
|
||||
Permanent *bool `form:"permanent,omitempty" json:"permanent,omitempty"`
|
||||
@@ -1059,11 +1200,17 @@ type UploadAttachmentMultipartBody struct {
|
||||
|
||||
// CreateCommentJSONBody defines parameters for CreateComment.
|
||||
type CreateCommentJSONBody struct {
|
||||
// Anchor The editor's encoding of the commented range (opaque to the server)
|
||||
// Anchor The editor's encoding of the commented range, opaque to the server (threads only)
|
||||
Anchor *map[string]interface{} `json:"anchor,omitempty"`
|
||||
Body string `json:"body"`
|
||||
|
||||
// Quote The commented text
|
||||
// Mentions Ids of the people mentioned in body
|
||||
Mentions *[]string `json:"mentions,omitempty"`
|
||||
|
||||
// Parent The thread to reply to
|
||||
Parent *string `json:"parent,omitempty"`
|
||||
|
||||
// Quote The commented text (threads only)
|
||||
Quote *string `json:"quote,omitempty"`
|
||||
}
|
||||
|
||||
@@ -1221,6 +1368,15 @@ type ConfirmVerificationJSONRequestBody ConfirmVerificationJSONBody
|
||||
// RequestVerificationJSONRequestBody defines body for RequestVerification for application/json ContentType.
|
||||
type RequestVerificationJSONRequestBody = EmailRequest
|
||||
|
||||
// UpdateCommentJSONRequestBody defines body for UpdateComment for application/json ContentType.
|
||||
type UpdateCommentJSONRequestBody UpdateCommentJSONBody
|
||||
|
||||
// ReactToCommentJSONRequestBody defines body for ReactToComment for application/json ContentType.
|
||||
type ReactToCommentJSONRequestBody ReactToCommentJSONBody
|
||||
|
||||
// ResolveCommentJSONRequestBody defines body for ResolveComment for application/json ContentType.
|
||||
type ResolveCommentJSONRequestBody ResolveCommentJSONBody
|
||||
|
||||
// UpdateGroupJSONRequestBody defines body for UpdateGroup for application/json ContentType.
|
||||
type UpdateGroupJSONRequestBody = GroupRequest
|
||||
|
||||
@@ -1230,6 +1386,12 @@ type AddGroupMemberJSONRequestBody = EmailRequest
|
||||
// CreateInviteJSONRequestBody defines body for CreateInvite for application/json ContentType.
|
||||
type CreateInviteJSONRequestBody = CreateInviteRequest
|
||||
|
||||
// MarkNotificationsReadJSONRequestBody defines body for MarkNotificationsRead for application/json ContentType.
|
||||
type MarkNotificationsReadJSONRequestBody MarkNotificationsReadJSONBody
|
||||
|
||||
// SetNotificationSettingsJSONRequestBody defines body for SetNotificationSettings for application/json ContentType.
|
||||
type SetNotificationSettingsJSONRequestBody = NotificationSettings
|
||||
|
||||
// CreateOrgJSONRequestBody defines body for CreateOrg for application/json ContentType.
|
||||
type CreateOrgJSONRequestBody = NameRequest
|
||||
|
||||
@@ -1263,6 +1425,9 @@ type MovePageJSONRequestBody MovePageJSONBody
|
||||
// SetShareLinkJSONRequestBody defines body for SetShareLink for application/json ContentType.
|
||||
type SetShareLinkJSONRequestBody SetShareLinkJSONBody
|
||||
|
||||
// SetPageWatchJSONRequestBody defines body for SetPageWatch for application/json ContentType.
|
||||
type SetPageWatchJSONRequestBody = WatchState
|
||||
|
||||
// UpdateSpaceJSONRequestBody defines body for UpdateSpace for application/json ContentType.
|
||||
type UpdateSpaceJSONRequestBody UpdateSpaceJSONBody
|
||||
|
||||
|
||||
@@ -36,13 +36,19 @@ type Options struct {
|
||||
}
|
||||
|
||||
type Hub struct {
|
||||
o Options
|
||||
mu sync.Mutex
|
||||
rooms map[string]*room
|
||||
done chan struct{}
|
||||
wg sync.WaitGroup
|
||||
o Options
|
||||
onSaved func(page, editor string, doc []byte)
|
||||
mu sync.Mutex
|
||||
rooms map[string]*room
|
||||
done chan struct{}
|
||||
wg sync.WaitGroup
|
||||
}
|
||||
|
||||
// OnSaved registers fn to run (in its own goroutine) after a page's content
|
||||
// was saved, with the last editor and the document as Tiptap JSON. Set it
|
||||
// before the hub serves anyone.
|
||||
func (h *Hub) OnSaved(fn func(page, editor string, doc []byte)) { h.onSaved = fn }
|
||||
|
||||
func NewHub(o Options) *Hub {
|
||||
if o.FlushEvery == 0 {
|
||||
o.FlushEvery = time.Second
|
||||
@@ -337,6 +343,9 @@ func (r *room) persistLocked(ctx context.Context, leaving bool) bool {
|
||||
snap.JSON, snap.Text = read.JSON, read.Text
|
||||
err = o.Store.SaveSnapshot(ctx, r.page, snap)
|
||||
}
|
||||
if err == nil && r.h.onSaved != nil {
|
||||
go r.h.onSaved(r.page, snap.LastEditor, snap.JSON)
|
||||
}
|
||||
if err == nil && version {
|
||||
if verr := o.Store.AddVersion(ctx, r.page, snap); verr != nil {
|
||||
o.Log.Error("collab: add version", "page", r.page, "err", verr)
|
||||
|
||||
@@ -6,74 +6,160 @@ import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"sort"
|
||||
"strings"
|
||||
"time"
|
||||
"unicode"
|
||||
|
||||
"docwell/server/internal/access"
|
||||
"docwell/server/internal/apperr"
|
||||
"docwell/server/internal/store/pocketbase"
|
||||
)
|
||||
|
||||
// ---- Inline comments -------------------------------------------------------
|
||||
// ---- Comments --------------------------------------------------------------
|
||||
//
|
||||
// Comments come in threads: the first comment of a thread may point at text
|
||||
// (anchor) and can be resolved; replies (parent = the first comment) only
|
||||
// hold text. Anyone who can comment may react with an emoji.
|
||||
|
||||
// maxReactions caps the distinct emojis on one comment.
|
||||
const maxReactions = 20
|
||||
|
||||
// Reaction is one emoji on a comment with who used it.
|
||||
type Reaction struct {
|
||||
Emoji string `json:"emoji"`
|
||||
Count int `json:"count"`
|
||||
// Mine is whether the caller reacted with it.
|
||||
Mine bool `json:"mine"`
|
||||
// People are the names of the people who reacted, for a tooltip.
|
||||
People []string `json:"people"`
|
||||
}
|
||||
|
||||
type Comment struct {
|
||||
ID string `json:"id"`
|
||||
ID string `json:"id"`
|
||||
// Parent is the thread's first comment for a reply ("" for a thread).
|
||||
Parent string `json:"parent"`
|
||||
Page string `json:"page"`
|
||||
Author MemberUser `json:"author"`
|
||||
Body string `json:"body"`
|
||||
Quote string `json:"quote"`
|
||||
// Anchor is the editor's encoding of the commented range; the server
|
||||
// stores it without looking inside.
|
||||
Anchor json.RawMessage `json:"anchor"`
|
||||
Created string `json:"created"`
|
||||
CanDelete bool `json:"canDelete"`
|
||||
Anchor json.RawMessage `json:"anchor"`
|
||||
Created string `json:"created"`
|
||||
EditedAt string `json:"editedAt"`
|
||||
ResolvedAt string `json:"resolvedAt"`
|
||||
ResolvedBy *MemberUser `json:"resolvedBy"`
|
||||
Reactions []Reaction `json:"reactions"`
|
||||
CanEdit bool `json:"canEdit"`
|
||||
CanDelete bool `json:"canDelete"`
|
||||
CanResolve bool `json:"canResolve"`
|
||||
}
|
||||
|
||||
type commentRecord struct {
|
||||
ID string `json:"id"`
|
||||
Page string `json:"page"`
|
||||
Author string `json:"author"`
|
||||
Body string `json:"body"`
|
||||
Quote string `json:"quote"`
|
||||
Anchor json.RawMessage `json:"anchor"`
|
||||
Created string `json:"created"`
|
||||
Expand struct {
|
||||
Author *struct {
|
||||
ID string `json:"id"`
|
||||
Email string `json:"email"`
|
||||
Name string `json:"name"`
|
||||
} `json:"author"`
|
||||
} `json:"expand"`
|
||||
ID string `json:"id"`
|
||||
Page string `json:"page"`
|
||||
Workspace string `json:"workspace"`
|
||||
Parent string `json:"parent"`
|
||||
Author string `json:"author"`
|
||||
Body string `json:"body"`
|
||||
Quote string `json:"quote"`
|
||||
Anchor json.RawMessage `json:"anchor"`
|
||||
Reactions map[string][]string `json:"reactions"`
|
||||
ResolvedAt string `json:"resolved_at"`
|
||||
ResolvedBy string `json:"resolved_by"`
|
||||
EditedAt string `json:"edited_at"`
|
||||
Created string `json:"created"`
|
||||
}
|
||||
|
||||
func (r commentRecord) view(c access.Caller, role string) Comment {
|
||||
// people resolves user ids to MemberUsers, remembering each lookup.
|
||||
type people struct {
|
||||
s *Service
|
||||
seen map[string]*MemberUser
|
||||
}
|
||||
|
||||
func (s *Service) people() *people { return &people{s: s, seen: map[string]*MemberUser{}} }
|
||||
|
||||
func (p *people) get(ctx context.Context, id string) *MemberUser {
|
||||
if id == "" {
|
||||
return nil
|
||||
}
|
||||
if m, ok := p.seen[id]; ok {
|
||||
return m
|
||||
}
|
||||
var m *MemberUser
|
||||
if u, err := p.s.getUser(ctx, id); err == nil {
|
||||
m = &MemberUser{ID: u.ID, Email: u.Email, Name: u.Name}
|
||||
}
|
||||
p.seen[id] = m
|
||||
return m
|
||||
}
|
||||
|
||||
func (m *MemberUser) display() string {
|
||||
if m == nil {
|
||||
return ""
|
||||
}
|
||||
if m.Name != "" {
|
||||
return m.Name
|
||||
}
|
||||
return m.Email
|
||||
}
|
||||
|
||||
func (r commentRecord) view(ctx context.Context, c access.Caller, role string, who *people) Comment {
|
||||
out := Comment{
|
||||
ID: r.ID, Page: r.Page, Body: r.Body, Quote: r.Quote, Anchor: r.Anchor, Created: r.Created,
|
||||
CanDelete: access.DeleteComment(c.ID, r.Author, role) == nil,
|
||||
ID: r.ID, Parent: r.Parent, Page: r.Page, Body: r.Body, Quote: r.Quote, Anchor: r.Anchor, Created: r.Created,
|
||||
EditedAt: r.EditedAt, ResolvedAt: r.ResolvedAt, Reactions: []Reaction{},
|
||||
CanEdit: access.EditComment(c.ID, r.Author) == nil,
|
||||
CanDelete: access.DeleteComment(c.ID, r.Author, role) == nil,
|
||||
CanResolve: r.Parent == "" && access.ResolveComment(role) == nil,
|
||||
}
|
||||
if len(out.Anchor) == 0 {
|
||||
out.Anchor = json.RawMessage("null")
|
||||
}
|
||||
if a := r.Expand.Author; a != nil {
|
||||
out.Author = MemberUser{ID: a.ID, Email: a.Email, Name: a.Name}
|
||||
if a := who.get(ctx, r.Author); a != nil {
|
||||
out.Author = *a
|
||||
}
|
||||
if r.ResolvedAt != "" {
|
||||
out.ResolvedBy = who.get(ctx, r.ResolvedBy)
|
||||
}
|
||||
for emoji, ids := range r.Reactions {
|
||||
if len(ids) == 0 {
|
||||
continue
|
||||
}
|
||||
re := Reaction{Emoji: emoji, Count: len(ids), People: []string{}}
|
||||
for _, id := range ids {
|
||||
re.Mine = re.Mine || id == c.ID
|
||||
if name := who.get(ctx, id).display(); name != "" {
|
||||
re.People = append(re.People, name)
|
||||
}
|
||||
}
|
||||
out.Reactions = append(out.Reactions, re)
|
||||
}
|
||||
sort.Slice(out.Reactions, func(i, j int) bool {
|
||||
if out.Reactions[i].Count != out.Reactions[j].Count {
|
||||
return out.Reactions[i].Count > out.Reactions[j].Count
|
||||
}
|
||||
return out.Reactions[i].Emoji < out.Reactions[j].Emoji
|
||||
})
|
||||
return out
|
||||
}
|
||||
|
||||
// ListComments lists a page's comments, oldest first (viewer).
|
||||
// ListComments lists a page's comments and replies, oldest first (viewer).
|
||||
func (s *Service) ListComments(ctx context.Context, c access.Caller, pageID string) ([]Comment, error) {
|
||||
p, a, err := s.pageFor(ctx, c, pageID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
recs, err := listAll[commentRecord](ctx, s, "comments", pocketbase.ListOptions{
|
||||
Filter: fmt.Sprintf("page = '%s'", p.ID), Sort: "created", Expand: "author",
|
||||
Filter: fmt.Sprintf("page = '%s'", p.ID), Sort: "created,id",
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
who := s.people()
|
||||
out := make([]Comment, 0, len(recs))
|
||||
for _, r := range recs {
|
||||
out = append(out, r.view(c, a.role))
|
||||
out = append(out, r.view(ctx, c, a.role, who))
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
@@ -82,9 +168,54 @@ type CreateCommentInput struct {
|
||||
Body string `json:"body"`
|
||||
Quote string `json:"quote"`
|
||||
Anchor json.RawMessage `json:"anchor"`
|
||||
// Parent makes this a reply to that thread.
|
||||
Parent string `json:"parent"`
|
||||
// Mentions are the ids of people mentioned in Body; they are notified.
|
||||
Mentions []string `json:"mentions"`
|
||||
}
|
||||
|
||||
// CreateComment adds a comment to a page (commenter; not in the trash).
|
||||
func cleanCommentBody(body string) (string, error) {
|
||||
body = strings.TrimSpace(body)
|
||||
switch {
|
||||
case body == "":
|
||||
return "", apperr.InvalidFields(map[string]string{"body": "Write something first."})
|
||||
case len(body) > 5000:
|
||||
return "", apperr.InvalidFields(map[string]string{"body": "The comment is too long (max 5000)."})
|
||||
}
|
||||
return body, nil
|
||||
}
|
||||
|
||||
func (s *Service) getComment(ctx context.Context, id string) (commentRecord, error) {
|
||||
if !validID(id) {
|
||||
return commentRecord{}, apperr.NotFound("comment not found")
|
||||
}
|
||||
rec, err := pocketbase.Get[commentRecord](ctx, s.pb, "comments", id)
|
||||
return rec, mapPB(err, "comment not found")
|
||||
}
|
||||
|
||||
// commentFor loads a comment and c's access to its page.
|
||||
func (s *Service) commentFor(ctx context.Context, c access.Caller, id string) (commentRecord, pageRecord, spaceAccess, error) {
|
||||
rec, err := s.getComment(ctx, id)
|
||||
if err != nil {
|
||||
return rec, pageRecord{}, spaceAccess{}, err
|
||||
}
|
||||
p, a, err := s.pageFor(ctx, c, rec.Page)
|
||||
if err != nil {
|
||||
return rec, p, a, apperr.NotFound("comment not found")
|
||||
}
|
||||
return rec, p, a, nil
|
||||
}
|
||||
|
||||
func (s *Service) commentView(ctx context.Context, c access.Caller, id, role string) (Comment, error) {
|
||||
rec, err := s.getComment(ctx, id)
|
||||
if err != nil {
|
||||
return Comment{}, err
|
||||
}
|
||||
return rec.view(ctx, c, role, s.people()), nil
|
||||
}
|
||||
|
||||
// CreateComment starts a thread on a page, or replies to one (commenter;
|
||||
// not in the trash). The author starts watching the page.
|
||||
func (s *Service) CreateComment(ctx context.Context, c access.Caller, pageID string, in CreateCommentInput) (Comment, error) {
|
||||
p, a, err := s.pageFor(ctx, c, pageID)
|
||||
if err != nil {
|
||||
@@ -96,46 +227,168 @@ func (s *Service) CreateComment(ctx context.Context, c access.Caller, pageID str
|
||||
if p.DeletedAt != "" {
|
||||
return Comment{}, apperr.Invalid("restore the page from the trash first")
|
||||
}
|
||||
body := strings.TrimSpace(in.Body)
|
||||
switch {
|
||||
case body == "":
|
||||
return Comment{}, apperr.InvalidFields(map[string]string{"body": "Write something first."})
|
||||
case len(body) > 5000:
|
||||
return Comment{}, apperr.InvalidFields(map[string]string{"body": "The comment is too long (max 5000)."})
|
||||
case len(in.Anchor) > 4096:
|
||||
return Comment{}, apperr.InvalidFields(map[string]string{"anchor": "The anchor is too large."})
|
||||
body, err := cleanCommentBody(in.Body)
|
||||
if err != nil {
|
||||
return Comment{}, err
|
||||
}
|
||||
quote := strings.TrimSpace(in.Quote)
|
||||
if r := []rune(quote); len(r) > 500 {
|
||||
quote = string(r[:500])
|
||||
}
|
||||
fields := map[string]any{"page": p.ID, "workspace": p.Workspace, "author": c.ID, "body": body, "quote": quote}
|
||||
if len(in.Anchor) > 0 && json.Valid(in.Anchor) {
|
||||
fields["anchor"] = in.Anchor
|
||||
fields := map[string]any{"page": p.ID, "workspace": p.Workspace, "author": c.ID, "body": body}
|
||||
var root commentRecord
|
||||
if in.Parent != "" {
|
||||
if root, err = s.getComment(ctx, in.Parent); err != nil || root.Page != p.ID {
|
||||
return Comment{}, apperr.InvalidFields(map[string]string{"parent": "That thread is not on this page."})
|
||||
}
|
||||
if root.Parent != "" {
|
||||
// Replies to a reply join the same thread.
|
||||
if root, err = s.getComment(ctx, root.Parent); err != nil {
|
||||
return Comment{}, err
|
||||
}
|
||||
}
|
||||
fields["parent"] = root.ID
|
||||
} else {
|
||||
if len(in.Anchor) > 4096 {
|
||||
return Comment{}, apperr.InvalidFields(map[string]string{"anchor": "The anchor is too large."})
|
||||
}
|
||||
quote := strings.TrimSpace(in.Quote)
|
||||
if r := []rune(quote); len(r) > 500 {
|
||||
quote = string(r[:500])
|
||||
}
|
||||
fields["quote"] = quote
|
||||
if len(in.Anchor) > 0 && json.Valid(in.Anchor) {
|
||||
fields["anchor"] = in.Anchor
|
||||
}
|
||||
}
|
||||
rec, err := pocketbase.Create[commentRecord](ctx, s.pb, "comments", fields)
|
||||
if err != nil {
|
||||
return Comment{}, mapPB(err, "page not found")
|
||||
}
|
||||
rec, err = pocketbase.GetExpand[commentRecord](ctx, s.pb, "comments", rec.ID, "author")
|
||||
if err != nil {
|
||||
return Comment{}, mapPB(err, "comment not found")
|
||||
}
|
||||
return rec.view(c, a.role), nil
|
||||
s.autoWatch(ctx, p.ID, c.ID)
|
||||
s.notifyComment(ctx, c, p, rec, root, in.Mentions)
|
||||
return rec.view(ctx, c, a.role, s.people()), nil
|
||||
}
|
||||
|
||||
// DeleteComment removes a comment (its author, or a space admin).
|
||||
// UpdateComment changes a comment's text (its author).
|
||||
func (s *Service) UpdateComment(ctx context.Context, c access.Caller, id, body string) (Comment, error) {
|
||||
rec, p, a, err := s.commentFor(ctx, c, id)
|
||||
if err != nil {
|
||||
return Comment{}, err
|
||||
}
|
||||
if err := access.EditComment(c.ID, rec.Author); err != nil {
|
||||
return Comment{}, err
|
||||
}
|
||||
if p.DeletedAt != "" {
|
||||
return Comment{}, apperr.Invalid("restore the page from the trash first")
|
||||
}
|
||||
if body, err = cleanCommentBody(body); err != nil {
|
||||
return Comment{}, err
|
||||
}
|
||||
if body != rec.Body {
|
||||
if _, err := pocketbase.Update[commentRecord](ctx, s.pb, "comments", rec.ID, map[string]any{
|
||||
"body": body, "edited_at": pbTime(time.Now()),
|
||||
}); err != nil {
|
||||
return Comment{}, mapPB(err, "comment not found")
|
||||
}
|
||||
}
|
||||
return s.commentView(ctx, c, rec.ID, a.role)
|
||||
}
|
||||
|
||||
// ResolveComment marks a thread resolved, or opens it again (commenter).
|
||||
// The people in the thread hear about it.
|
||||
func (s *Service) ResolveComment(ctx context.Context, c access.Caller, id string, resolved bool) (Comment, error) {
|
||||
rec, p, a, err := s.commentFor(ctx, c, id)
|
||||
if err != nil {
|
||||
return Comment{}, err
|
||||
}
|
||||
if err := access.ResolveComment(a.role); err != nil {
|
||||
return Comment{}, err
|
||||
}
|
||||
if rec.Parent != "" {
|
||||
return Comment{}, apperr.Invalid("only a thread's first comment can be resolved")
|
||||
}
|
||||
if resolved == (rec.ResolvedAt != "") {
|
||||
return s.commentView(ctx, c, rec.ID, a.role)
|
||||
}
|
||||
patch := map[string]any{"resolved_at": "", "resolved_by": ""}
|
||||
if resolved {
|
||||
patch = map[string]any{"resolved_at": pbTime(time.Now()), "resolved_by": c.ID}
|
||||
}
|
||||
if _, err := pocketbase.Update[commentRecord](ctx, s.pb, "comments", rec.ID, patch); err != nil {
|
||||
return Comment{}, mapPB(err, "comment not found")
|
||||
}
|
||||
if resolved {
|
||||
s.notifyResolved(ctx, c, p, rec)
|
||||
}
|
||||
return s.commentView(ctx, c, rec.ID, a.role)
|
||||
}
|
||||
|
||||
// validEmoji accepts a short run of symbols: no letters, digits or spaces.
|
||||
func validEmoji(e string) bool {
|
||||
r := []rune(e)
|
||||
if len(r) == 0 || len(r) > 8 || len(e) > 32 {
|
||||
return false
|
||||
}
|
||||
for _, ch := range r {
|
||||
if unicode.IsLetter(ch) || unicode.IsDigit(ch) || unicode.IsSpace(ch) || unicode.IsControl(ch) {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
// ReactToComment adds or removes the caller's emoji on a comment (commenter).
|
||||
func (s *Service) ReactToComment(ctx context.Context, c access.Caller, id, emoji string, on bool) (Comment, error) {
|
||||
rec, _, a, err := s.commentFor(ctx, c, id)
|
||||
if err != nil {
|
||||
return Comment{}, err
|
||||
}
|
||||
if err := access.ReactToComment(a.role); err != nil {
|
||||
return Comment{}, err
|
||||
}
|
||||
emoji = strings.TrimSpace(emoji)
|
||||
if !validEmoji(emoji) {
|
||||
return Comment{}, apperr.InvalidFields(map[string]string{"emoji": "Pick an emoji."})
|
||||
}
|
||||
reactions := rec.Reactions
|
||||
if reactions == nil {
|
||||
reactions = map[string][]string{}
|
||||
}
|
||||
ids := reactions[emoji]
|
||||
has := false
|
||||
kept := ids[:0:0]
|
||||
for _, uid := range ids {
|
||||
if uid == c.ID {
|
||||
has = true
|
||||
if !on {
|
||||
continue
|
||||
}
|
||||
}
|
||||
kept = append(kept, uid)
|
||||
}
|
||||
switch {
|
||||
case on && has, !on && !has:
|
||||
return rec.view(ctx, c, a.role, s.people()), nil
|
||||
case on:
|
||||
if len(ids) == 0 && len(reactions) >= maxReactions {
|
||||
return Comment{}, apperr.Invalid("this comment has as many different reactions as it can take")
|
||||
}
|
||||
kept = append(kept, c.ID)
|
||||
}
|
||||
if len(kept) == 0 {
|
||||
delete(reactions, emoji)
|
||||
} else {
|
||||
reactions[emoji] = kept
|
||||
}
|
||||
if _, err := pocketbase.Update[commentRecord](ctx, s.pb, "comments", rec.ID, map[string]any{"reactions": reactions}); err != nil {
|
||||
return Comment{}, mapPB(err, "comment not found")
|
||||
}
|
||||
return s.commentView(ctx, c, rec.ID, a.role)
|
||||
}
|
||||
|
||||
// DeleteComment removes a comment, and with a thread's first comment all of
|
||||
// its replies (its author, or a space admin).
|
||||
func (s *Service) DeleteComment(ctx context.Context, c access.Caller, id string) error {
|
||||
if !validID(id) {
|
||||
return apperr.NotFound("comment not found")
|
||||
}
|
||||
rec, err := pocketbase.Get[commentRecord](ctx, s.pb, "comments", id)
|
||||
rec, _, a, err := s.commentFor(ctx, c, id)
|
||||
if err != nil {
|
||||
return mapPB(err, "comment not found")
|
||||
}
|
||||
_, a, err := s.pageFor(ctx, c, rec.Page)
|
||||
if err != nil {
|
||||
return apperr.NotFound("comment not found")
|
||||
return err
|
||||
}
|
||||
if err := access.DeleteComment(c.ID, rec.Author, a.role); err != nil {
|
||||
return err
|
||||
|
||||
@@ -0,0 +1,574 @@
|
||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
package directory
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"net/url"
|
||||
"sort"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"docwell/server/internal/access"
|
||||
"docwell/server/internal/apperr"
|
||||
"docwell/server/internal/mail"
|
||||
"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. 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"
|
||||
)
|
||||
|
||||
// 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}
|
||||
|
||||
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
|
||||
}
|
||||
|
||||
// send stores the event's notifications, for recipients who can still open
|
||||
// the page (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)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 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 ""). People mentioned for the first time are
|
||||
// notified. 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"`
|
||||
}
|
||||
r, err := pocketbase.Get[rec](ctx, s.pb, "pages", pageID)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
now := mentionIDs(doc)
|
||||
var before []string
|
||||
known := len(r.Mentions) > 0 && string(r.Mentions) != "null"
|
||||
if known {
|
||||
_ = json.Unmarshal(r.Mentions, &before)
|
||||
}
|
||||
if strings.Join(before, ",") == strings.Join(now, ",") && known {
|
||||
return
|
||||
}
|
||||
if now == nil {
|
||||
now = []string{}
|
||||
}
|
||||
if _, err := pocketbase.Update[struct{}](ctx, s.pb, "pages", pageID, map[string]any{"mentions": now}); err != nil {
|
||||
return
|
||||
}
|
||||
if !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)
|
||||
}
|
||||
|
||||
// ---- 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"`
|
||||
}
|
||||
|
||||
func (s *Service) GetNotificationSettings(ctx context.Context, c access.Caller) (NotificationSettings, error) {
|
||||
r, err := pocketbase.Get[struct {
|
||||
NotifyEmail string `json:"notify_email"`
|
||||
}](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}, 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."})
|
||||
}
|
||||
if _, err := pocketbase.Update[struct{}](ctx, s.pb, "users", c.ID, map[string]any{"notify_email": in.Email}); err != nil {
|
||||
return NotificationSettings{}, mapPB(err, "user not found")
|
||||
}
|
||||
return in, nil
|
||||
}
|
||||
|
||||
// ---- 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) (digestItem, bool) {
|
||||
if n.Page == "" {
|
||||
return digestItem{}, false
|
||||
}
|
||||
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 = "Someone"
|
||||
}
|
||||
title := p.Title
|
||||
if title == "" {
|
||||
title = "Untitled"
|
||||
}
|
||||
verb := map[string]string{
|
||||
NotifyComment: "commented on",
|
||||
NotifyReply: "replied in",
|
||||
NotifyMention: "mentioned you in",
|
||||
NotifyShare: "shared",
|
||||
NotifyResolved: "resolved a thread in",
|
||||
}[n.Type]
|
||||
text := fmt.Sprintf("%s %s “%s”", actor, verb, title)
|
||||
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
|
||||
}
|
||||
|
||||
// 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"`
|
||||
}](ctx, s.pb, "users", userID)
|
||||
if err == nil && u.NotifyEmail != "off" && u.Status != "disabled" {
|
||||
var items []digestItem
|
||||
for _, n := range list {
|
||||
if it, ok := s.digestLine(ctx, n, who); ok {
|
||||
items = append(items, it)
|
||||
}
|
||||
}
|
||||
if len(items) > 0 {
|
||||
m, err := mail.Render(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 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 nil
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
package directory
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestMentionIDs(t *testing.T) {
|
||||
doc := `{"type":"doc","content":[
|
||||
{"type":"paragraph","content":[
|
||||
{"type":"text","text":"hi "},
|
||||
{"type":"mention","attrs":{"id":"bbbbbbbbbbbbbbb","label":"Bob"}},
|
||||
{"type":"mention","attrs":{"id":"aaaaaaaaaaaaaaa","label":"Ann"}}]},
|
||||
{"type":"bulletList","content":[{"type":"listItem","content":[{"type":"paragraph","content":[
|
||||
{"type":"mention","attrs":{"id":"bbbbbbbbbbbbbbb"}},
|
||||
{"type":"mention","attrs":{"id":"bad id!"}}]}]}]}]}`
|
||||
got := strings.Join(mentionIDs([]byte(doc)), ",")
|
||||
if got != "aaaaaaaaaaaaaaa,bbbbbbbbbbbbbbb" {
|
||||
t.Fatalf("mentionIDs = %q", got)
|
||||
}
|
||||
if mentionIDs([]byte("null")) != nil || mentionIDs([]byte("{")) != nil {
|
||||
t.Fatal("empty documents should have no mentions")
|
||||
}
|
||||
}
|
||||
|
||||
func TestValidEmoji(t *testing.T) {
|
||||
for _, e := range []string{"👍", "❤️", "🎉", "👩💻"} {
|
||||
if !validEmoji(e) {
|
||||
t.Errorf("%q should be accepted", e)
|
||||
}
|
||||
}
|
||||
for _, e := range []string{"", "ok", "a b", "1", "👍👍👍👍👍👍👍👍👍", "\n"} {
|
||||
if validEmoji(e) {
|
||||
t.Errorf("%q should be refused", e)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestExcerpt(t *testing.T) {
|
||||
if got := excerpt(" a\n\n b "); got != "a b" {
|
||||
t.Fatalf("excerpt = %q", got)
|
||||
}
|
||||
if got := []rune(excerpt(strings.Repeat("x", 300))); len(got) != 200 || got[199] != '…' {
|
||||
t.Fatalf("long excerpt has %d runes", len(got))
|
||||
}
|
||||
}
|
||||
@@ -342,6 +342,8 @@ func (s *Service) CreatePage(ctx context.Context, c access.Caller, spaceID strin
|
||||
body := map[string]any{
|
||||
"workspace": a.space.Workspace, "space": a.space.ID, "title": title, "position": pos,
|
||||
"creator": c.ID, "last_editor": c.ID,
|
||||
// Mention tracking starts empty, so first mentions notify (see PageSaved).
|
||||
"mentions": []string{},
|
||||
}
|
||||
if in.Parent != "" {
|
||||
body["parent"] = in.Parent
|
||||
@@ -350,6 +352,7 @@ func (s *Service) CreatePage(ctx context.Context, c access.Caller, spaceID strin
|
||||
if err != nil {
|
||||
return Page{}, mapPB(err, "page not found")
|
||||
}
|
||||
s.autoWatch(ctx, rec.ID, c.ID)
|
||||
return s.GetPage(ctx, c, rec.ID)
|
||||
}
|
||||
|
||||
|
||||
@@ -387,6 +387,7 @@ func (s *Service) SharePageWithUser(ctx context.Context, c access.Caller, id, em
|
||||
return SharePageResult{}, err
|
||||
}
|
||||
s.kickSubtree(ctx, p)
|
||||
s.notifyShare(ctx, c, p, u.ID)
|
||||
pa, err := s.GetPageAccess(ctx, c, p.ID)
|
||||
return SharePageResult{Access: pa}, err
|
||||
}
|
||||
|
||||
@@ -5,16 +5,29 @@ package httpapi
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
"strconv"
|
||||
|
||||
"docwell/server/internal/access"
|
||||
"docwell/server/internal/directory"
|
||||
)
|
||||
|
||||
// CommentService is the part of directory.Service for inline comments.
|
||||
// CommentService is the part of directory.Service for comments, page
|
||||
// watching and notifications.
|
||||
type CommentService interface {
|
||||
ListComments(ctx context.Context, c access.Caller, pageID string) ([]directory.Comment, error)
|
||||
CreateComment(ctx context.Context, c access.Caller, pageID string, in directory.CreateCommentInput) (directory.Comment, error)
|
||||
UpdateComment(ctx context.Context, c access.Caller, id, body string) (directory.Comment, error)
|
||||
ResolveComment(ctx context.Context, c access.Caller, id string, resolved bool) (directory.Comment, error)
|
||||
ReactToComment(ctx context.Context, c access.Caller, id, emoji string, on bool) (directory.Comment, error)
|
||||
DeleteComment(ctx context.Context, c access.Caller, id string) error
|
||||
|
||||
GetWatch(ctx context.Context, c access.Caller, pageID string) (directory.WatchState, error)
|
||||
SetWatch(ctx context.Context, c access.Caller, pageID string, on bool) (directory.WatchState, error)
|
||||
|
||||
ListNotifications(ctx context.Context, c access.Caller, unreadOnly bool, limit int) (directory.NotificationList, error)
|
||||
MarkNotificationsRead(ctx context.Context, c access.Caller, ids []string, all bool) (int, error)
|
||||
GetNotificationSettings(ctx context.Context, c access.Caller) (directory.NotificationSettings, error)
|
||||
SetNotificationSettings(ctx context.Context, c access.Caller, in directory.NotificationSettings) (directory.NotificationSettings, error)
|
||||
}
|
||||
|
||||
func (a *api) commentRoutes(mux *routeMux) {
|
||||
@@ -30,7 +43,77 @@ func (a *api) commentRoutes(mux *routeMux) {
|
||||
cm, err := a.dir.CreateComment(r.Context(), caller(r), r.PathValue("id"), in)
|
||||
a.respondStatus(w, http.StatusCreated, cm, err)
|
||||
}))
|
||||
mux.HandleFunc("PATCH /api/v1/comments/{id}", a.requireUser(func(w http.ResponseWriter, r *http.Request) {
|
||||
var in struct{ Body string }
|
||||
if !a.decode(w, r, &in) {
|
||||
return
|
||||
}
|
||||
cm, err := a.dir.UpdateComment(r.Context(), caller(r), r.PathValue("id"), in.Body)
|
||||
a.respond(w, cm, err)
|
||||
}))
|
||||
mux.HandleFunc("DELETE /api/v1/comments/{id}", a.requireUser(func(w http.ResponseWriter, r *http.Request) {
|
||||
a.respondNoContent(w, a.dir.DeleteComment(r.Context(), caller(r), r.PathValue("id")))
|
||||
}))
|
||||
mux.HandleFunc("POST /api/v1/comments/{id}/resolve", a.requireUser(func(w http.ResponseWriter, r *http.Request) {
|
||||
var in struct{ Resolved bool }
|
||||
if !a.decode(w, r, &in) {
|
||||
return
|
||||
}
|
||||
cm, err := a.dir.ResolveComment(r.Context(), caller(r), r.PathValue("id"), in.Resolved)
|
||||
a.respond(w, cm, err)
|
||||
}))
|
||||
mux.HandleFunc("POST /api/v1/comments/{id}/reactions", a.requireUser(func(w http.ResponseWriter, r *http.Request) {
|
||||
var in struct {
|
||||
Emoji string
|
||||
On bool
|
||||
}
|
||||
if !a.decode(w, r, &in) {
|
||||
return
|
||||
}
|
||||
cm, err := a.dir.ReactToComment(r.Context(), caller(r), r.PathValue("id"), in.Emoji, in.On)
|
||||
a.respond(w, cm, err)
|
||||
}))
|
||||
|
||||
mux.HandleFunc("GET /api/v1/pages/{id}/watch", a.requireUser(func(w http.ResponseWriter, r *http.Request) {
|
||||
st, err := a.dir.GetWatch(r.Context(), caller(r), r.PathValue("id"))
|
||||
a.respond(w, st, err)
|
||||
}))
|
||||
mux.HandleFunc("PUT /api/v1/pages/{id}/watch", a.requireUser(func(w http.ResponseWriter, r *http.Request) {
|
||||
var in struct{ Watching bool }
|
||||
if !a.decode(w, r, &in) {
|
||||
return
|
||||
}
|
||||
st, err := a.dir.SetWatch(r.Context(), caller(r), r.PathValue("id"), in.Watching)
|
||||
a.respond(w, st, err)
|
||||
}))
|
||||
|
||||
mux.HandleFunc("GET /api/v1/notifications", a.requireUser(func(w http.ResponseWriter, r *http.Request) {
|
||||
q := r.URL.Query()
|
||||
limit, _ := strconv.Atoi(q.Get("limit"))
|
||||
list, err := a.dir.ListNotifications(r.Context(), caller(r), q.Get("unread") == "true", limit)
|
||||
a.respond(w, list, err)
|
||||
}))
|
||||
mux.HandleFunc("POST /api/v1/notifications/read", a.requireUser(func(w http.ResponseWriter, r *http.Request) {
|
||||
var in struct {
|
||||
IDs []string
|
||||
All bool
|
||||
}
|
||||
if !a.decode(w, r, &in) {
|
||||
return
|
||||
}
|
||||
n, err := a.dir.MarkNotificationsRead(r.Context(), caller(r), in.IDs, in.All)
|
||||
a.respond(w, map[string]int{"unread": n}, err)
|
||||
}))
|
||||
mux.HandleFunc("GET /api/v1/notifications/settings", a.requireUser(func(w http.ResponseWriter, r *http.Request) {
|
||||
st, err := a.dir.GetNotificationSettings(r.Context(), caller(r))
|
||||
a.respond(w, st, err)
|
||||
}))
|
||||
mux.HandleFunc("PUT /api/v1/notifications/settings", a.requireUser(func(w http.ResponseWriter, r *http.Request) {
|
||||
var in directory.NotificationSettings
|
||||
if !a.decode(w, r, &in) {
|
||||
return
|
||||
}
|
||||
st, err := a.dir.SetNotificationSettings(r.Context(), caller(r), in)
|
||||
a.respond(w, st, err)
|
||||
}))
|
||||
}
|
||||
@@ -118,3 +118,28 @@ func (r *Registry) Run(name string) error {
|
||||
go func() { _ = r.Track(name, func() error { return run(context.Background()) }) }()
|
||||
return nil
|
||||
}
|
||||
|
||||
// Every runs job name every interval until ctx ends, skipping a tick while
|
||||
// the previous run (or one started by hand) is still going.
|
||||
func (r *Registry) Every(ctx context.Context, name string, interval time.Duration) {
|
||||
t := time.NewTicker(interval)
|
||||
defer t.Stop()
|
||||
for {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return
|
||||
case <-t.C:
|
||||
r.mu.Lock()
|
||||
e, ok := r.jobs[name]
|
||||
busy := !ok || e.run == nil || e.Running
|
||||
var run func(context.Context) error
|
||||
if !busy {
|
||||
run = e.run
|
||||
}
|
||||
r.mu.Unlock()
|
||||
if !busy {
|
||||
_ = r.Track(name, func() error { return run(ctx) })
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -49,3 +49,27 @@ func TestTrackAndRun(t *testing.T) {
|
||||
t.Error("unregistered jobs are tracked too")
|
||||
}
|
||||
}
|
||||
|
||||
func TestEvery(t *testing.T) {
|
||||
r := New()
|
||||
runs := make(chan struct{}, 10)
|
||||
r.Register("tick", "", time.Millisecond, func(context.Context) error {
|
||||
runs <- struct{}{}
|
||||
return nil
|
||||
})
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
done := make(chan struct{})
|
||||
go func() { r.Every(ctx, "tick", time.Millisecond); close(done) }()
|
||||
for range 2 {
|
||||
select {
|
||||
case <-runs:
|
||||
case <-time.After(2 * time.Second):
|
||||
t.Fatal("job did not run")
|
||||
}
|
||||
}
|
||||
cancel()
|
||||
<-done
|
||||
if r.List()[0].Runs < 2 {
|
||||
t.Fatalf("runs = %d", r.List()[0].Runs)
|
||||
}
|
||||
}
|
||||
@@ -22,3 +22,19 @@ func TestRender(t *testing.T) {
|
||||
t.Errorf("text must not repeat the subject: %q", m.Text)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDigest(t *testing.T) {
|
||||
m, err := Render("a@x.test", "digest", map[string]any{
|
||||
"AppName": "Docwell", "Name": "Ann", "Count": 2, "SettingsLink": "https://w/notifications",
|
||||
"Items": []struct{ Text, Link string }{{"Bob commented on “Plan”: <b>hi</b>", "https://w/p/1"}, {"x", "https://w/p/2"}},
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if m.Subject != "2 new notifications on Docwell" {
|
||||
t.Fatalf("subject = %q", m.Subject)
|
||||
}
|
||||
if !strings.Contains(m.HTML, "<b>hi</b>") || !strings.Contains(m.Text, "https://w/p/2") {
|
||||
t.Fatalf("body:\n%s\n%s", m.HTML, m.Text)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
<p>Hello{{if .Name}} {{.Name}}{{end}},</p>
|
||||
<p>Here is what happened while you were away:</p>
|
||||
<ul>
|
||||
{{range .Items}} <li><a href="{{.Link}}">{{.Text}}</a></li>
|
||||
{{end}}</ul>
|
||||
<p>You get this email because you have unread notifications. <a href="{{.SettingsLink}}">Turn these emails off</a> in your notification settings.</p>
|
||||
@@ -0,0 +1,9 @@
|
||||
{{.Count}} new {{if eq .Count 1}}notification{{else}}notifications{{end}} on {{.AppName}}
|
||||
Hello{{if .Name}} {{.Name}}{{end}},
|
||||
|
||||
Here is what happened while you were away:
|
||||
{{range .Items}}
|
||||
- {{.Text}}
|
||||
{{.Link}}
|
||||
{{end}}
|
||||
You get this email because you have unread notifications. Turn these emails off in your notification settings: {{.SettingsLink}}
|
||||
Reference in new issue
Block a user