// SPDX-License-Identifier: AGPL-3.0-or-later package directory import ( "context" "encoding/json" "fmt" "sort" "strings" "time" "unicode" "docwell/server/internal/access" "docwell/server/internal/apperr" "docwell/server/internal/store/pocketbase" ) // ---- 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"` // 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"` 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"` 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"` } // 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, 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 := 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 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,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(ctx, c, a.role, who)) } return out, nil } 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"` } 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 { return Comment{}, err } if err := access.CommentPages(a.role); err != nil { return Comment{}, err } if p.DeletedAt != "" { return Comment{}, apperr.Invalid("restore the page from the trash first") } body, err := cleanCommentBody(in.Body) if err != nil { return Comment{}, err } 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") } s.autoWatch(ctx, p.ID, c.ID) s.notifyComment(ctx, c, p, rec, root, in.Mentions) s.emitPage(ctx, "comment.created", p, c.ID, map[string]any{ "comment": map[string]string{"id": rec.ID, "parent": rec.Parent, "body": rec.Body}, }) return rec.view(ctx, c, a.role, s.people()), nil } // 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) s.emitPage(ctx, "comment.resolved", p, c.ID, map[string]any{"comment": map[string]string{"id": rec.ID}}) } 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 { rec, _, a, err := s.commentFor(ctx, c, id) if err != nil { return err } if err := access.DeleteComment(c.ID, rec.Author, a.role); err != nil { return err } return mapPB(s.pb.Delete(ctx, "comments", rec.ID), "comment not found") }