From 2b78c167e2dc1fd7aed6a18fffffe461af716f8d Mon Sep 17 00:00:00 2001 From: tajniak81 <13187254+tajniak81@users.noreply.github.com> Date: Sat, 31 Oct 2026 22:27:55 +0100 Subject: [PATCH] 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 --- .../1762900000_threads_notifications.js | 110 ++++ Packages/api-client/src/index.ts | 41 +- Packages/api-client/src/schema.d.ts | 423 ++++++++++++- Packages/ui/src/icons.ts | 5 + Phone-App/lib/api/generated/models.dart | 219 +++++++ Server/cmd/docwell-server/main.go | 9 + Server/internal/access/spaces.go | 13 + Server/internal/access/spaces_test.go | 21 + Server/internal/api/api.gen.go | 177 +++++- Server/internal/collab/hub.go | 19 +- Server/internal/directory/comments.go | 369 +++++++++-- Server/internal/directory/notify.go | 574 ++++++++++++++++++ Server/internal/directory/notify_test.go | 48 ++ Server/internal/directory/pages.go | 3 + Server/internal/directory/permissions.go | 1 + Server/internal/httpapi/comments.go | 85 ++- Server/internal/jobs/jobs.go | 25 + Server/internal/jobs/jobs_test.go | 24 + Server/internal/mail/mail_test.go | 16 + Server/internal/mail/templates/digest.html | 6 + Server/internal/mail/templates/digest.txt | 9 + Web-App/frontend/src/components/AppLayout.vue | 13 + .../frontend/src/components/CommentBox.vue | 163 +++++ .../frontend/src/components/PageComments.vue | 308 +++++++--- Web-App/frontend/src/locales/en.json | 33 +- Web-App/frontend/src/locales/pl.json | 33 +- Web-App/frontend/src/router.ts | 1 + Web-App/frontend/src/stores/notifications.ts | 64 ++ .../frontend/src/views/NotificationsView.vue | 151 +++++ Web-App/frontend/src/views/page/PageView.vue | 41 +- api/openapi.yaml | 245 +++++++- 31 files changed, 3083 insertions(+), 166 deletions(-) create mode 100644 Database/pb_migrations/1762900000_threads_notifications.js create mode 100644 Server/internal/directory/notify.go create mode 100644 Server/internal/directory/notify_test.go create mode 100644 Server/internal/mail/templates/digest.html create mode 100644 Server/internal/mail/templates/digest.txt create mode 100644 Web-App/frontend/src/components/CommentBox.vue create mode 100644 Web-App/frontend/src/stores/notifications.ts create mode 100644 Web-App/frontend/src/views/NotificationsView.vue diff --git a/Database/pb_migrations/1762900000_threads_notifications.js b/Database/pb_migrations/1762900000_threads_notifications.js new file mode 100644 index 0000000..695c5ef --- /dev/null +++ b/Database/pb_migrations/1762900000_threads_notifications.js @@ -0,0 +1,110 @@ +// SPDX-License-Identifier: AGPL-3.0-or-later + +/// + +// Comment threads, reactions, page watching and notifications. +// +// A reply is a comment with a parent (always the thread's first comment, +// which alone carries the anchor and can be resolved). reactions maps an +// emoji to the ids of the people who reacted with it. +// +// page_watchers.watching false means the person muted the page, so taking +// part in it later does not start watching it again. +// +// pages.mentions remembers who the page already mentions, so a save only +// notifies people who were newly mentioned. +// +// users.notify_email is "digest" (default when empty) or "off". + +migrate( + (app) => { + const users = app.findCollectionByNameOrId("users"); + const pages = app.findCollectionByNameOrId("pages"); + const workspaces = app.findCollectionByNameOrId("workspaces"); + const comments = app.findCollectionByNameOrId("comments"); + + comments.fields.add(new RelationField({ name: "parent", collectionId: comments.id, maxSelect: 1, cascadeDelete: true })); + comments.fields.add(new DateField({ name: "resolved_at" })); + comments.fields.add(new RelationField({ name: "resolved_by", collectionId: users.id, maxSelect: 1, cascadeDelete: false })); + comments.fields.add(new JSONField({ name: "reactions", maxSize: 20000 })); + comments.fields.add(new DateField({ name: "edited_at" })); + comments.indexes = [ + "CREATE INDEX idx_comments_page ON comments (page, created)", + "CREATE INDEX idx_comments_parent ON comments (parent)", + ]; + app.save(comments); + + pages.fields.add(new JSONField({ name: "mentions", maxSize: 20000 })); + app.save(pages); + + users.fields.add(new SelectField({ name: "notify_email", values: ["digest", "off"], maxSelect: 1 })); + app.save(users); + + app.save( + new Collection({ + type: "base", + name: "page_watchers", + fields: [ + { name: "page", type: "relation", collectionId: pages.id, maxSelect: 1, required: true, cascadeDelete: true }, + { name: "user", type: "relation", collectionId: users.id, maxSelect: 1, required: true, cascadeDelete: true }, + { name: "watching", type: "bool" }, + { name: "created", type: "autodate", onCreate: true, onUpdate: false }, + { name: "updated", type: "autodate", onCreate: true, onUpdate: true }, + ], + indexes: [ + "CREATE UNIQUE INDEX idx_page_watchers_unique ON page_watchers (page, user)", + "CREATE INDEX idx_page_watchers_user ON page_watchers (user)", + ], + }), + ); + + app.save( + new Collection({ + type: "base", + name: "notifications", + fields: [ + { name: "user", type: "relation", collectionId: users.id, maxSelect: 1, required: true, cascadeDelete: true }, + { name: "workspace", type: "relation", collectionId: workspaces.id, maxSelect: 1, cascadeDelete: true }, + { name: "page", type: "relation", collectionId: pages.id, maxSelect: 1, cascadeDelete: true }, + { name: "comment", type: "relation", collectionId: comments.id, maxSelect: 1, cascadeDelete: true }, + { name: "actor", type: "relation", collectionId: users.id, maxSelect: 1, cascadeDelete: false }, + { + name: "type", + type: "select", + values: ["comment", "reply", "mention", "share", "resolved"], + maxSelect: 1, + required: true, + }, + // What the notification says beyond its links, e.g. a comment excerpt. + { name: "excerpt", type: "text", max: 300 }, + { name: "read_at", type: "date" }, + { name: "emailed_at", type: "date" }, + { name: "created", type: "autodate", onCreate: true, onUpdate: false }, + { name: "updated", type: "autodate", onCreate: true, onUpdate: true }, + ], + indexes: [ + "CREATE INDEX idx_notifications_user ON notifications (user, created)", + "CREATE INDEX idx_notifications_unread ON notifications (user, read_at)", + "CREATE INDEX idx_notifications_mail ON notifications (emailed_at, read_at)", + ], + }), + ); + }, + (app) => { + for (const name of ["notifications", "page_watchers"]) { + try { + app.delete(app.findCollectionByNameOrId(name)); + } catch (_) {} + } + const users = app.findCollectionByNameOrId("users"); + users.fields.removeByName("notify_email"); + app.save(users); + const pages = app.findCollectionByNameOrId("pages"); + pages.fields.removeByName("mentions"); + app.save(pages); + const comments = app.findCollectionByNameOrId("comments"); + for (const f of ["edited_at", "reactions", "resolved_by", "resolved_at", "parent"]) comments.fields.removeByName(f); + comments.indexes = ["CREATE INDEX idx_comments_page ON comments (page, created)"]; + app.save(comments); + }, +); diff --git a/Packages/api-client/src/index.ts b/Packages/api-client/src/index.ts index 2cbdaca..38111cb 100644 --- a/Packages/api-client/src/index.ts +++ b/Packages/api-client/src/index.ts @@ -45,6 +45,12 @@ export type Job = Schemas["Job"]; export type Backup = Schemas["Backup"]; export type SharedPage = Schemas["SharedPage"]; export type PageGrantRole = Schemas["PageGrantRole"]; +export type Reaction = Schemas["Reaction"]; +export type WatchState = Schemas["WatchState"]; +export type NotificationType = Schemas["NotificationType"]; +export type Notification = Schemas["Notification"]; +export type NotificationList = Schemas["NotificationList"]; +export type NotificationSettings = Schemas["NotificationSettings"]; export type PageGrant = Schemas["PageGrant"]; export type PageInvite = Schemas["PageInvite"]; export type PageAccess = Schemas["PageAccess"]; @@ -177,7 +183,27 @@ export function createClient(opts: ClientOptions) { }, comments: { + update: (id: string, body: string) => + request("PATCH", `/api/v1/comments/${encodeURIComponent(id)}`, { body }), remove: (id: string) => request("DELETE", `/api/v1/comments/${encodeURIComponent(id)}`), + resolve: (id: string, resolved: boolean) => + post(`/api/v1/comments/${encodeURIComponent(id)}/resolve`, { resolved }), + react: (id: string, emoji: string, on: boolean) => + post(`/api/v1/comments/${encodeURIComponent(id)}/reactions`, { emoji, on }), + }, + + notifications: { + list: (opts: { unread?: boolean; limit?: number } = {}) => + request( + "GET", + `/api/v1/notifications${query({ unread: opts.unread ? "true" : undefined, limit: opts.limit?.toString() })}`, + ), + /** Marks the listed notifications read, or all of them; resolves to the unread count. */ + markRead: (input: { ids?: string[]; all?: boolean }) => + post<{ unread: number }>("/api/v1/notifications/read", input), + settings: () => request("GET", "/api/v1/notifications/settings"), + setSettings: (input: NotificationSettings) => + request("PUT", "/api/v1/notifications/settings", input), }, files: { @@ -337,8 +363,19 @@ export function createClient(opts: ClientOptions) { return upload(`/api/v1/pages/${encodeURIComponent(id)}/attachments`, form); }, comments: (id: string) => request("GET", `/api/v1/pages/${encodeURIComponent(id)}/comments`), - addComment: (id: string, input: { body: string; quote?: string; anchor?: Record | null }) => - post(`/api/v1/pages/${encodeURIComponent(id)}/comments`, input), + watch: (id: string) => request("GET", `/api/v1/pages/${encodeURIComponent(id)}/watch`), + setWatch: (id: string, watching: boolean) => + request("PUT", `/api/v1/pages/${encodeURIComponent(id)}/watch`, { watching }), + addComment: ( + id: string, + input: { + body: string; + quote?: string; + anchor?: Record | null; + parent?: string; + mentions?: string[]; + }, + ) => post(`/api/v1/pages/${encodeURIComponent(id)}/comments`, input), /** The public link; rejects with a 404 ApiError when sharing is off. */ shareLink: (id: string) => request("GET", `/api/v1/pages/${encodeURIComponent(id)}/share`), setShareLink: (id: string, includeSubpages: boolean) => diff --git a/Packages/api-client/src/schema.d.ts b/Packages/api-client/src/schema.d.ts index 3e10ecd..a54f687 100644 --- a/Packages/api-client/src/schema.d.ts +++ b/Packages/api-client/src/schema.d.ts @@ -1387,10 +1387,13 @@ export interface paths { }; cookie?: never; }; - /** The page's inline comments, oldest first */ + /** The page's comments and replies, oldest first (threads are the ones without a parent) */ get: operations["listComments"]; put?: never; - /** Comment on the page (commenter) */ + /** + * Start a thread on the page, or reply to one (commenter) + * @description The author starts watching the page. Watchers, the thread's people and mentioned people are notified. + */ post: operations["createComment"]; delete?: never; options?: never; @@ -1410,10 +1413,124 @@ export interface paths { get?: never; put?: never; post?: never; - /** Delete a comment (its author, or a space admin) */ + /** Delete a comment, and a thread's replies with it (its author, or a space admin) */ delete: operations["deleteComment"]; options?: never; head?: never; + /** Change a comment's text (its author) */ + patch: operations["updateComment"]; + trace?: never; + }; + "/api/v1/comments/{id}/resolve": { + parameters: { + query?: never; + header?: never; + path: { + id: string; + }; + cookie?: never; + }; + get?: never; + put?: never; + /** Resolve a thread, or open it again (commenter) */ + post: operations["resolveComment"]; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/v1/comments/{id}/reactions": { + parameters: { + query?: never; + header?: never; + path: { + id: string; + }; + cookie?: never; + }; + get?: never; + put?: never; + /** Add or remove the caller's emoji reaction (commenter) */ + post: operations["reactToComment"]; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/v1/pages/{id}/watch": { + parameters: { + query?: never; + header?: never; + path: { + id: string; + }; + cookie?: never; + }; + /** Whether the caller watches the page */ + get: operations["getPageWatch"]; + /** + * Watch the page, or mute it + * @description Muting is remembered, so commenting later does not start watching again. + */ + put: operations["setPageWatch"]; + post?: never; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/v1/notifications": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + /** The caller's newest notifications with the unread count */ + get: operations["listNotifications"]; + put?: never; + post?: never; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/v1/notifications/read": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + /** Mark notifications read (the listed ones, or all) */ + post: operations["markNotificationsRead"]; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/v1/notifications/settings": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + /** The caller's notification preferences */ + get: operations["getNotificationSettings"]; + /** Change the caller's notification preferences */ + put: operations["setNotificationSettings"]; + post?: never; + delete?: never; + options?: never; + head?: never; patch?: never; trace?: never; }; @@ -1983,6 +2100,8 @@ export interface components { }; Comment: { id: string; + /** @description The thread's first comment for a reply; empty for a thread */ + parent: string; page: string; author: components["schemas"]["MemberUser"]; body: string; @@ -1992,7 +2111,53 @@ export interface components { [key: string]: unknown; } | null; created: string; + /** @description Empty when never edited */ + editedAt: string; + /** @description Empty unless the thread is resolved */ + resolvedAt: string; + resolvedBy: components["schemas"]["MemberUser"] | null; + /** @description Most used first */ + reactions: components["schemas"]["Reaction"][]; + canEdit: boolean; canDelete: boolean; + /** @description A thread the caller may resolve or reopen */ + canResolve: boolean; + }; + Reaction: { + emoji: string; + count: number; + mine: boolean; + /** @description Names of the people who reacted */ + people: string[]; + }; + WatchState: { + watching: boolean; + }; + /** @enum {string} */ + NotificationType: "comment" | "reply" | "mention" | "share" | "resolved"; + Notification: { + id: string; + type: components["schemas"]["NotificationType"]; + workspace: string; + /** @description Null when the page is gone or the caller lost access to it */ + page: components["schemas"]["PageRef"] | null; + /** @description The comment it is about */ + comment: string; + actor: components["schemas"]["MemberUser"] | null; + excerpt: string; + created: string; + read: boolean; + }; + NotificationList: { + items: components["schemas"]["Notification"][]; + unread: number; + }; + NotificationSettings: { + /** + * @description Unread notifications by email every few minutes + * @enum {string} + */ + email: "digest" | "off"; }; AdminStats: { /** @enum {string} */ @@ -4562,12 +4727,16 @@ export interface operations { content: { "application/json": { body: string; - /** @description The commented text */ + /** @description The commented text (threads only) */ quote?: string; - /** @description The editor's encoding of the commented range (opaque to the server) */ + /** @description The editor's encoding of the commented range, opaque to the server (threads only) */ anchor?: { [key: string]: unknown; }; + /** @description The thread to reply to */ + parent?: string; + /** @description Ids of the people mentioned in body */ + mentions?: string[]; }; }; }; @@ -4608,6 +4777,250 @@ export interface operations { 404: components["responses"]["Error"]; }; }; + updateComment: { + parameters: { + query?: never; + header?: never; + path: { + id: string; + }; + cookie?: never; + }; + requestBody: { + content: { + "application/json": { + body: string; + }; + }; + }; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["Comment"]; + }; + }; + 400: components["responses"]["Error"]; + 403: components["responses"]["Error"]; + 404: components["responses"]["Error"]; + }; + }; + resolveComment: { + parameters: { + query?: never; + header?: never; + path: { + id: string; + }; + cookie?: never; + }; + requestBody: { + content: { + "application/json": { + resolved: boolean; + }; + }; + }; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["Comment"]; + }; + }; + 400: components["responses"]["Error"]; + 403: components["responses"]["Error"]; + 404: components["responses"]["Error"]; + }; + }; + reactToComment: { + parameters: { + query?: never; + header?: never; + path: { + id: string; + }; + cookie?: never; + }; + requestBody: { + content: { + "application/json": { + emoji: string; + on: boolean; + }; + }; + }; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["Comment"]; + }; + }; + 400: components["responses"]["Error"]; + 403: components["responses"]["Error"]; + 404: components["responses"]["Error"]; + }; + }; + getPageWatch: { + parameters: { + query?: never; + header?: never; + path: { + id: string; + }; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["WatchState"]; + }; + }; + 404: components["responses"]["Error"]; + }; + }; + setPageWatch: { + parameters: { + query?: never; + header?: never; + path: { + id: string; + }; + cookie?: never; + }; + requestBody: { + content: { + "application/json": components["schemas"]["WatchState"]; + }; + }; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["WatchState"]; + }; + }; + 404: components["responses"]["Error"]; + }; + }; + listNotifications: { + parameters: { + query?: { + /** @description Only unread ones */ + unread?: boolean; + limit?: number; + }; + header?: never; + path?: never; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["NotificationList"]; + }; + }; + 401: components["responses"]["Error"]; + }; + }; + markNotificationsRead: { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + requestBody: { + content: { + "application/json": { + ids?: string[]; + all?: boolean; + }; + }; + }; + responses: { + /** @description The unread count afterwards */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": { + unread: number; + }; + }; + }; + 400: components["responses"]["Error"]; + }; + }; + getNotificationSettings: { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["NotificationSettings"]; + }; + }; + }; + }; + setNotificationSettings: { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + requestBody: { + content: { + "application/json": components["schemas"]["NotificationSettings"]; + }; + }; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["NotificationSettings"]; + }; + }; + 400: components["responses"]["Error"]; + }; + }; getAdminStats: { parameters: { query?: never; diff --git a/Packages/ui/src/icons.ts b/Packages/ui/src/icons.ts index 9157ec0..dbccfe2 100644 --- a/Packages/ui/src/icons.ts +++ b/Packages/ui/src/icons.ts @@ -76,6 +76,11 @@ export const iconPaths = { "M12 3c2.5 2.5 3.5 5.5 3.5 9s-1 6.5-3.5 9", "M12 3C9.5 5.5 8.5 8.5 8.5 12s1 6.5 3.5 9", ], + bell: ["M6 16V11a6 6 0 0 1 12 0v5l1.5 2h-15z", "M10 20a2 2 0 0 0 4 0"], + "bell-off": ["M6 16V11a6 6 0 0 1 9.5-4.9", "M18 11v5l1.5 2H8", "M10 20a2 2 0 0 0 4 0", "M4 4l16 16"], + smile: ["M12 3a9 9 0 1 0 0 18a9 9 0 1 0 0-18z", "M8.5 14a4 4 0 0 0 7 0", "M9 9.5h.01", "M15 9.5h.01"], + reply: ["M9 7L4 12l5 5", "M4 12h10a6 6 0 0 1 6 6v1"], + pencil: ["M15 5l4 4L8 20H4v-4z"], users: [ "M9 11a3.5 3.5 0 1 0 0-7a3.5 3.5 0 1 0 0 7z", "M3 20a6 6 0 0 1 12 0", diff --git a/Phone-App/lib/api/generated/models.dart b/Phone-App/lib/api/generated/models.dart index c013016..2e96dc9 100644 --- a/Phone-App/lib/api/generated/models.dart +++ b/Phone-App/lib/api/generated/models.dart @@ -2047,17 +2047,25 @@ class SharedPage { class Comment { const Comment({ required this.id, + required this.parent, required this.page, required this.author, required this.body, required this.quote, required this.anchor, required this.created, + required this.editedAt, + required this.resolvedAt, + required this.resolvedBy, + required this.reactions, + required this.canEdit, required this.canDelete, + required this.canResolve, }); factory Comment.fromJson(Map json) => Comment( id: json['id'] as String, + parent: json['parent'] as String, page: json['page'] as String, author: MemberUser.fromJson(json['author'] as Map), body: json['body'] as String, @@ -2066,11 +2074,24 @@ class Comment { ? null : json['anchor'] as Map, created: json['created'] as String, + editedAt: json['editedAt'] as String, + resolvedAt: json['resolvedAt'] as String, + resolvedBy: json['resolvedBy'] == null + ? null + : MemberUser.fromJson(json['resolvedBy'] as Map), + reactions: (json['reactions'] as List) + .map((e) => Reaction.fromJson(e as Map)) + .toList(), + canEdit: json['canEdit'] as bool, canDelete: json['canDelete'] as bool, + canResolve: json['canResolve'] as bool, ); final String id; + /// The thread's first comment for a reply; empty for a thread + final String parent; + final String page; final MemberUser author; @@ -2084,20 +2105,218 @@ class Comment { final String created; + /// Empty when never edited + final String editedAt; + + /// Empty unless the thread is resolved + final String resolvedAt; + + final MemberUser? resolvedBy; + + /// Most used first + final List reactions; + + final bool canEdit; + final bool canDelete; + /// A thread the caller may resolve or reopen + final bool canResolve; + Map toJson() => { 'id': id, + 'parent': parent, 'page': page, 'author': author.toJson(), 'body': body, 'quote': quote, 'anchor': anchor, 'created': created, + 'editedAt': editedAt, + 'resolvedAt': resolvedAt, + 'resolvedBy': resolvedBy?.toJson(), + 'reactions': reactions.map((e) => e.toJson()).toList(), + 'canEdit': canEdit, 'canDelete': canDelete, + 'canResolve': canResolve, }; } +class Reaction { + const Reaction({ + required this.emoji, + required this.count, + required this.mine, + required this.people, + }); + + factory Reaction.fromJson(Map json) => Reaction( + emoji: json['emoji'] as String, + count: (json['count'] as num).toInt(), + mine: json['mine'] as bool, + people: (json['people'] as List).map((e) => e as String).toList(), + ); + + final String emoji; + + final int count; + + final bool mine; + + /// Names of the people who reacted + final List people; + + Map toJson() => { + 'emoji': emoji, + 'count': count, + 'mine': mine, + 'people': people.map((e) => e).toList(), + }; +} + +class WatchState { + const WatchState({required this.watching}); + + factory WatchState.fromJson(Map json) => + WatchState(watching: json['watching'] as bool); + + final bool watching; + + Map toJson() => {'watching': watching}; +} + +enum NotificationType { + comment('comment'), + reply('reply'), + mention('mention'), + share('share'), + resolved('resolved'); + + const NotificationType(this.value); + final String value; + + static NotificationType fromJson(String value) => values.firstWhere( + (e) => e.value == value, + orElse: () => throw FormatException('unknown NotificationType', value), + ); + + String toJson() => value; +} + +class Notification { + const Notification({ + required this.id, + required this.type, + required this.workspace, + required this.page, + required this.comment, + required this.actor, + required this.excerpt, + required this.created, + required this.read, + }); + + factory Notification.fromJson(Map json) => Notification( + id: json['id'] as String, + type: NotificationType.fromJson(json['type'] as String), + workspace: json['workspace'] as String, + page: json['page'] == null + ? null + : PageRef.fromJson(json['page'] as Map), + comment: json['comment'] as String, + actor: json['actor'] == null + ? null + : MemberUser.fromJson(json['actor'] as Map), + excerpt: json['excerpt'] as String, + created: json['created'] as String, + read: json['read'] as bool, + ); + + final String id; + + final NotificationType type; + + final String workspace; + + /// Null when the page is gone or the caller lost access to it + final PageRef? page; + + /// The comment it is about + final String comment; + + final MemberUser? actor; + + final String excerpt; + + final String created; + + final bool read; + + Map toJson() => { + 'id': id, + 'type': type.toJson(), + 'workspace': workspace, + 'page': page?.toJson(), + 'comment': comment, + 'actor': actor?.toJson(), + 'excerpt': excerpt, + 'created': created, + 'read': read, + }; +} + +class NotificationList { + const NotificationList({required this.items, required this.unread}); + + factory NotificationList.fromJson(Map json) => + NotificationList( + items: (json['items'] as List) + .map((e) => Notification.fromJson(e as Map)) + .toList(), + unread: (json['unread'] as num).toInt(), + ); + + final List items; + + final int unread; + + Map toJson() => { + 'items': items.map((e) => e.toJson()).toList(), + 'unread': unread, + }; +} + +/// Unread notifications by email every few minutes +enum NotificationSettingsEmail { + digest('digest'), + off('off'); + + const NotificationSettingsEmail(this.value); + final String value; + + static NotificationSettingsEmail fromJson(String value) => values.firstWhere( + (e) => e.value == value, + orElse: () => + throw FormatException('unknown NotificationSettingsEmail', value), + ); + + String toJson() => value; +} + +class NotificationSettings { + const NotificationSettings({required this.email}); + + factory NotificationSettings.fromJson(Map json) => + NotificationSettings( + email: NotificationSettingsEmail.fromJson(json['email'] as String), + ); + + /// Unread notifications by email every few minutes + final NotificationSettingsEmail email; + + Map toJson() => {'email': email.toJson()}; +} + enum AdminStatsScope { instance('instance'), organization('organization'); diff --git a/Server/cmd/docwell-server/main.go b/Server/cmd/docwell-server/main.go index 6d70374..6bebd26 100644 --- a/Server/cmd/docwell-server/main.go +++ b/Server/cmd/docwell-server/main.go @@ -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) diff --git a/Server/internal/access/spaces.go b/Server/internal/access/spaces.go index 8ebcabe..451bdb0 100644 --- a/Server/internal/access/spaces.go +++ b/Server/internal/access/spaces.go @@ -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) } diff --git a/Server/internal/access/spaces_test.go b/Server/internal/access/spaces_test.go index d6ae730..bc551a5 100644 --- a/Server/internal/access/spaces_test.go +++ b/Server/internal/access/spaces_test.go @@ -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) + } + } +} diff --git a/Server/internal/api/api.gen.go b/Server/internal/api/api.gen.go index 9897708..7d00e21 100644 --- a/Server/internal/api/api.gen.go +++ b/Server/internal/api/api.gen.go @@ -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 diff --git a/Server/internal/collab/hub.go b/Server/internal/collab/hub.go index 58e5636..6f6cc69 100644 --- a/Server/internal/collab/hub.go +++ b/Server/internal/collab/hub.go @@ -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) diff --git a/Server/internal/directory/comments.go b/Server/internal/directory/comments.go index b0a633e..427c3c9 100644 --- a/Server/internal/directory/comments.go +++ b/Server/internal/directory/comments.go @@ -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 diff --git a/Server/internal/directory/notify.go b/Server/internal/directory/notify.go new file mode 100644 index 0000000..ac33051 --- /dev/null +++ b/Server/internal/directory/notify.go @@ -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 +} diff --git a/Server/internal/directory/notify_test.go b/Server/internal/directory/notify_test.go new file mode 100644 index 0000000..90e5f69 --- /dev/null +++ b/Server/internal/directory/notify_test.go @@ -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)) + } +} diff --git a/Server/internal/directory/pages.go b/Server/internal/directory/pages.go index 8687f90..67d5593 100644 --- a/Server/internal/directory/pages.go +++ b/Server/internal/directory/pages.go @@ -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) } diff --git a/Server/internal/directory/permissions.go b/Server/internal/directory/permissions.go index 7d3ecfc..5978281 100644 --- a/Server/internal/directory/permissions.go +++ b/Server/internal/directory/permissions.go @@ -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 } diff --git a/Server/internal/httpapi/comments.go b/Server/internal/httpapi/comments.go index 1b36ecf..ea4fc51 100644 --- a/Server/internal/httpapi/comments.go +++ b/Server/internal/httpapi/comments.go @@ -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) + })) } diff --git a/Server/internal/jobs/jobs.go b/Server/internal/jobs/jobs.go index 2398228..9bafc63 100644 --- a/Server/internal/jobs/jobs.go +++ b/Server/internal/jobs/jobs.go @@ -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) }) + } + } + } +} diff --git a/Server/internal/jobs/jobs_test.go b/Server/internal/jobs/jobs_test.go index f7dfde7..1380124 100644 --- a/Server/internal/jobs/jobs_test.go +++ b/Server/internal/jobs/jobs_test.go @@ -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) + } +} diff --git a/Server/internal/mail/mail_test.go b/Server/internal/mail/mail_test.go index 352cb21..898aee5 100644 --- a/Server/internal/mail/mail_test.go +++ b/Server/internal/mail/mail_test.go @@ -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”: hi", "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) + } +} diff --git a/Server/internal/mail/templates/digest.html b/Server/internal/mail/templates/digest.html new file mode 100644 index 0000000..17e72d8 --- /dev/null +++ b/Server/internal/mail/templates/digest.html @@ -0,0 +1,6 @@ +

Hello{{if .Name}} {{.Name}}{{end}},

+

Here is what happened while you were away:

+ +

You get this email because you have unread notifications. Turn these emails off in your notification settings.

diff --git a/Server/internal/mail/templates/digest.txt b/Server/internal/mail/templates/digest.txt new file mode 100644 index 0000000..8ec04e5 --- /dev/null +++ b/Server/internal/mail/templates/digest.txt @@ -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}} diff --git a/Web-App/frontend/src/components/AppLayout.vue b/Web-App/frontend/src/components/AppLayout.vue index 46365b0..a36018d 100644 --- a/Web-App/frontend/src/components/AppLayout.vue +++ b/Web-App/frontend/src/components/AppLayout.vue @@ -8,6 +8,7 @@ import { useFormErrors } from "../composables/useFormErrors"; import { SIDEBAR_DEFAULT, clampWidth, useSidebar } from "../composables/useSidebar"; import { useAuthStore } from "../stores/auth"; import { useFavoritesStore } from "../stores/favorites"; +import { useNotificationsStore } from "../stores/notifications"; import { useSpacesStore } from "../stores/spaces"; import { atLeast, useWorkspacesStore } from "../stores/workspaces"; import PageTreeNode from "./PageTreeNode.vue"; @@ -22,6 +23,7 @@ const auth = useAuthStore(); const workspaces = useWorkspacesStore(); const spaces = useSpacesStore(); const favorites = useFavoritesStore(); +const notifications = useNotificationsStore(); const router = useRouter(); const route = useRoute(); const { mode } = useTheme(); @@ -37,6 +39,8 @@ function showError(e: unknown) { } onMounted(() => workspaces.load().catch(showError)); +onMounted(() => notifications.start()); +onBeforeUnmount(() => notifications.stop()); watch( () => workspaces.current?.id, (id) => { @@ -192,6 +196,15 @@ function signOut() { {{ $t("sidebar.home") }} + + {{ $t("notifications.title") }} + {{ notifications.unread > 99 ? "99+" : notifications.unread }} + + + +