diff --git a/Database/pb_migrations/1764500000_sharing_extras.js b/Database/pb_migrations/1764500000_sharing_extras.js new file mode 100644 index 0000000..3e6b148 --- /dev/null +++ b/Database/pb_migrations/1764500000_sharing_extras.js @@ -0,0 +1,118 @@ +// SPDX-License-Identifier: AGPL-3.0-or-later + +/// + +// Phase G of docs/AFFINE.md: sharing extras (ADR-17). +// +// - invite_links: one join link per workspace. Anyone signed in who opens it +// joins with its role, or, with approval on, asks to join. +// - invite_requests: those asks; workspace admins approve or decline them. +// - workspaces.sharing_off turns public share links off for the whole +// workspace; workspaces.url_preview lets chat apps show the titles of +// private pages when a link to one is posted. +// - page_views: one row per page, person (empty for visitors through a share +// link) and day, counting that day's opens. +// - notifications gain the join_request, join_approved and join_declined types. + +migrate( + (app) => { + const users = app.findCollectionByNameOrId("users"); + const workspaces = app.findCollectionByNameOrId("workspaces"); + const pages = app.findCollectionByNameOrId("pages"); + + workspaces.fields.add(new BoolField({ name: "sharing_off" })); + workspaces.fields.add(new BoolField({ name: "url_preview" })); + app.save(workspaces); + + app.save( + new Collection({ + type: "base", + name: "invite_links", + fields: [ + { name: "workspace", type: "relation", collectionId: workspaces.id, maxSelect: 1, required: true, cascadeDelete: true }, + { name: "token", type: "text", required: true, max: 64 }, + { name: "role", type: "select", values: ["member", "guest"], maxSelect: 1, required: true }, + { name: "approval", type: "bool" }, + { name: "created_by", type: "relation", collectionId: users.id, maxSelect: 1, cascadeDelete: false }, + // Empty means the link does not expire. + { name: "expires", type: "date" }, + { name: "created", type: "autodate", onCreate: true, onUpdate: false }, + { name: "updated", type: "autodate", onCreate: true, onUpdate: true }, + ], + indexes: [ + "CREATE UNIQUE INDEX idx_invite_links_workspace ON invite_links (workspace)", + "CREATE UNIQUE INDEX idx_invite_links_token ON invite_links (token)", + ], + }), + ); + + app.save( + new Collection({ + type: "base", + name: "invite_requests", + fields: [ + { name: "workspace", type: "relation", collectionId: workspaces.id, maxSelect: 1, required: true, cascadeDelete: true }, + { name: "user", type: "relation", collectionId: users.id, maxSelect: 1, required: true, cascadeDelete: true }, + { name: "role", type: "select", values: ["member", "guest"], maxSelect: 1, required: true }, + { name: "status", type: "select", values: ["pending", "approved", "declined"], maxSelect: 1, required: true }, + { name: "reviewed_by", type: "relation", collectionId: users.id, maxSelect: 1, cascadeDelete: false }, + { name: "reviewed_at", type: "date" }, + { name: "created", type: "autodate", onCreate: true, onUpdate: false }, + { name: "updated", type: "autodate", onCreate: true, onUpdate: true }, + ], + indexes: [ + "CREATE UNIQUE INDEX idx_invite_requests_user ON invite_requests (workspace, user)", + "CREATE INDEX idx_invite_requests_status ON invite_requests (workspace, status)", + ], + }), + ); + + app.save( + new Collection({ + type: "base", + name: "page_views", + fields: [ + { name: "page", type: "relation", collectionId: pages.id, maxSelect: 1, required: true, cascadeDelete: true }, + { name: "workspace", type: "relation", collectionId: workspaces.id, maxSelect: 1, required: true, cascadeDelete: true }, + { name: "user", type: "relation", collectionId: users.id, maxSelect: 1, cascadeDelete: true }, + // The UTC day, YYYY-MM-DD. + { name: "day", type: "text", required: true, max: 10 }, + { name: "views", type: "number", onlyInt: true, min: 0 }, + { name: "last", type: "date" }, + ], + indexes: [ + "CREATE UNIQUE INDEX idx_page_views_key ON page_views (page, user, day)", + "CREATE INDEX idx_page_views_day ON page_views (day)", + ], + }), + ); + + const notifications = app.findCollectionByNameOrId("notifications"); + notifications.fields.getByName("type").values = [ + "comment", + "reply", + "mention", + "share", + "resolved", + "reminder", + "join_request", + "join_approved", + "join_declined", + ]; + app.save(notifications); + }, + (app) => { + for (const name of ["page_views", "invite_requests", "invite_links"]) { + try { + app.delete(app.findCollectionByNameOrId(name)); + } catch (_) {} + } + const workspaces = app.findCollectionByNameOrId("workspaces"); + workspaces.fields.removeByName("sharing_off"); + workspaces.fields.removeByName("url_preview"); + app.save(workspaces); + const notifications = app.findCollectionByNameOrId("notifications"); + notifications.fields.getByName("type").values = ["comment", "reply", "mention", "share", "resolved", "reminder"]; + app.save(notifications); + }, +); diff --git a/Docker/docker-compose.prod.s3.yml b/Docker/docker-compose.prod.s3.yml index f0e7e65..ab7ce32 100644 --- a/Docker/docker-compose.prod.s3.yml +++ b/Docker/docker-compose.prod.s3.yml @@ -191,6 +191,8 @@ services: DOCWELL_API_URL: "${DOCWELL_PUBLIC_URL:-http://localhost:8080}" DOCWELL_COLLAB_URL: "${DOCWELL_COLLAB_URL:-ws://localhost:8080/collab}" DOCWELL_DRAWIO_URL: "${DOCWELL_DRAWIO_URL:-}" + # Where docwell-web asks for link previews of pages (chat-app unfurls). + DOCWELL_PREVIEW_API_URL: http://server:8080 ports: # The public front door. - "${WEB_BIND:-0.0.0.0}:${WEB_PORT:-3000}:3000" diff --git a/Docker/docker-compose.prod.seaweedfs.split.yml b/Docker/docker-compose.prod.seaweedfs.split.yml index 2d39da6..8969d0e 100644 --- a/Docker/docker-compose.prod.seaweedfs.split.yml +++ b/Docker/docker-compose.prod.seaweedfs.split.yml @@ -360,6 +360,8 @@ services: DOCWELL_API_URL: "${DOCWELL_PUBLIC_URL:-http://localhost:8080}" DOCWELL_COLLAB_URL: "${DOCWELL_COLLAB_URL:-ws://localhost:8080/collab}" DOCWELL_DRAWIO_URL: "${DOCWELL_DRAWIO_URL:-}" + # Where docwell-web asks for link previews of pages (chat-app unfurls). + DOCWELL_PREVIEW_API_URL: http://server:8080 ports: # The public front door. - "${WEB_BIND:-0.0.0.0}:${WEB_PORT:-3000}:3000" diff --git a/Docker/docker-compose.prod.seaweedfs.yml b/Docker/docker-compose.prod.seaweedfs.yml index 78d47c0..17599f0 100644 --- a/Docker/docker-compose.prod.seaweedfs.yml +++ b/Docker/docker-compose.prod.seaweedfs.yml @@ -236,6 +236,8 @@ services: DOCWELL_API_URL: "${DOCWELL_PUBLIC_URL:-http://localhost:8080}" DOCWELL_COLLAB_URL: "${DOCWELL_COLLAB_URL:-ws://localhost:8080/collab}" DOCWELL_DRAWIO_URL: "${DOCWELL_DRAWIO_URL:-}" + # Where docwell-web asks for link previews of pages (chat-app unfurls). + DOCWELL_PREVIEW_API_URL: http://server:8080 ports: # The public front door. - "${WEB_BIND:-0.0.0.0}:${WEB_PORT:-3000}:3000" diff --git a/Docker/docker-compose.prod.yml b/Docker/docker-compose.prod.yml index a2efbeb..69c4bd8 100644 --- a/Docker/docker-compose.prod.yml +++ b/Docker/docker-compose.prod.yml @@ -165,6 +165,8 @@ services: DOCWELL_API_URL: "${DOCWELL_PUBLIC_URL:-http://localhost:8080}" DOCWELL_COLLAB_URL: "${DOCWELL_COLLAB_URL:-ws://localhost:8080/collab}" DOCWELL_DRAWIO_URL: "${DOCWELL_DRAWIO_URL:-}" + # Where docwell-web asks for link previews of pages (chat-app unfurls). + DOCWELL_PREVIEW_API_URL: http://server:8080 ports: # The public front door. - "${WEB_BIND:-0.0.0.0}:${WEB_PORT:-3000}:3000" diff --git a/Docker/docker-compose.yml b/Docker/docker-compose.yml index 9e8c063..70c38ed 100644 --- a/Docker/docker-compose.yml +++ b/Docker/docker-compose.yml @@ -105,6 +105,8 @@ services: DOCWELL_API_URL: ${DOCWELL_PUBLIC_URL:-http://localhost:8080} DOCWELL_COLLAB_URL: ${DOCWELL_COLLAB_URL:-ws://localhost:8080/collab} DOCWELL_DRAWIO_URL: ${DOCWELL_DRAWIO_URL:-} + # Where docwell-web asks for link previews of pages (chat-app unfurls). + DOCWELL_PREVIEW_API_URL: http://server:8080 ports: - "3000:3000" diff --git a/Docs-Site/guide/configuration.md b/Docs-Site/guide/configuration.md index f44772c..670bfb6 100644 --- a/Docs-Site/guide/configuration.md +++ b/Docs-Site/guide/configuration.md @@ -70,6 +70,7 @@ docwell-server writes these into PocketBase every time it starts. | `DOCWELL_COLLAB_URL` | `ws://localhost:8080/collab` | The live-editing WebSocket (`wss://` behind HTTPS). | | `DOCWELL_DRAWIO_URL` | | The Draw.io editor to embed for diagrams. Empty uses the public `https://embed.diagrams.net`; point it at a self-hosted [jgraph/drawio](https://hub.docker.com/r/jgraph/drawio) to keep drawings on your network. | | `DOCWELL_PROXY_TARGET` | | When set (for example `http://server:8080`), docwell-web forwards `/api`, `/collab` and `/admin` to docwell-server, so browsers only talk to one address. The all-in-one image does this. | +| `DOCWELL_PREVIEW_API_URL` | `DOCWELL_PROXY_TARGET`, else `DOCWELL_API_URL` | Where docwell-web asks docwell-server for the titles that chat apps (Slack, Teams, Discord, …) show when a page link is posted. The compose files set it to `http://server:8080`. | ## Compose diff --git a/Docs-Site/guide/using-docwell.md b/Docs-Site/guide/using-docwell.md index e5f72a3..3dc5884 100644 --- a/Docs-Site/guide/using-docwell.md +++ b/Docs-Site/guide/using-docwell.md @@ -121,7 +121,8 @@ the **Comments** panel. People with the *commenter* role can comment without bei admins can delete comments. The **Inbox** lists your notifications. Under its settings you choose whether they also come by email, and which -kinds (mentions, comments, replies, resolved threads, shared pages, reminders). +kinds (mentions, comments, replies, resolved threads, shared pages, reminders, people asking to join a workspace you +manage). ## Finding things @@ -199,6 +200,36 @@ turn on a **public link**: anyone with it can read the page (and, if you choose, account. Readers can copy links to its blocks and database records from there, and those links open on the public page too. Turning it off makes the link stop working at once. Pages in the trash are never shown through a link. +### Workspace sharing settings + +Workspace admins find these under **Settings → Sharing** of the workspace: + +- **Allow public links.** Off, nobody in the workspace can make a public link, and existing ones stop working. They + come back, with the same addresses, when you turn it on again. +- **Show page titles in chat apps.** When someone posts a link to a private page in Slack, Teams, Discord or a similar + app, the app shows the page's title and the workspace's name. Nobody gets the page's text, pages limited to some + people never show a title, and search engines never get one. Public links always show their title and the start of + the page. +- **Invite link.** One link per workspace that lets people join after signing in (or signing up, where that is open). + Pick the role they get (member or guest), how long the link works, and whether an admin approves each person. With + approval on, the people asking show up under **Asking to join** and admins get a notification; approve them (with + the link's role or another) or decline, and they are told either way. **Make a new link** stops the old one; + **Turn the link off** stops it without making a new one. People from another organization cannot use a link; invite + them by email instead. + +### Page views + +Editors see how often a page was opened in its **Info** panel: views, how many people, opens through its public link, +a bar per day for the last 7, 30 or 90 days, and who opened it last. Opening a page again within half an hour counts +once. Readers and commenters do not see this. + +### Unused files + +Deleting an image or attachment from a page leaves the file on the server, so undo and copy-paste keep working. Under +**Unused files** in the workspace settings, admins can look for files that no page, page icon or comment uses any more +and delete them. Files from the last day are never listed. Old page versions are not searched, so restoring a version +from before a cleanup can show missing files. + ## Import and export - **Export:** the **⋯** menu in the page header saves the page as Markdown, HTML, PDF or Word. PDFs are A4, with a diff --git a/Packages/api-client/src/index.ts b/Packages/api-client/src/index.ts index a0b072b..a9077e1 100644 --- a/Packages/api-client/src/index.ts +++ b/Packages/api-client/src/index.ts @@ -124,6 +124,21 @@ export type AiWriteInput = Schemas["AiWriteInput"]; export type AiUsage = Schemas["AiUsage"]; export type AiInstanceSettings = Schemas["AiInstanceSettings"]; export type AiTranscript = Schemas["AiTranscript"]; +export type InviteLink = Schemas["InviteLink"]; +export type JoinRequest = Schemas["JoinRequest"]; +export type JoinInfo = Schemas["JoinInfo"]; +export type JoinResult = Schemas["JoinResult"]; +export type PageAnalytics = Schemas["PageAnalytics"]; +export type AnalyticsDay = Schemas["AnalyticsDay"]; +export type PageViewer = Schemas["PageViewer"]; +export type UnusedFile = Schemas["UnusedFile"]; +export type UnusedFiles = Schemas["UnusedFiles"]; +export type InviteLinkInput = { + role?: "member" | "guest"; + approval?: boolean; + expiresInDays?: number; + reset?: boolean; +}; /** One server-sent event of a streamed AI answer. */ export interface AiStreamEvent { @@ -297,6 +312,10 @@ export function createClient(opts: ClientOptions) { post("/api/v1/auth/otp/login", { otpId, code, mfaId }), refresh: () => request("POST", "/api/v1/auth/refresh"), me: () => request("GET", "/api/v1/auth/me"), + /** Describes a workspace invite link; status is filled in when signed in. */ + joinInfo: (token: string) => request("GET", `/api/v1/auth/join/${enc(token)}`), + /** Joins through an invite link, or asks to when it needs approval. */ + join: (token: string) => post(`/api/v1/auth/join/${enc(token)}`), requestPasswordReset: (email: string) => post("/api/v1/auth/password-reset/request", { email }), confirmPasswordReset: (token: string, password: string) => post("/api/v1/auth/password-reset/confirm", { token, password }), @@ -502,6 +521,31 @@ export function createClient(opts: ClientOptions) { /** Changes how the workspace's new pages open: as text or as a canvas. */ setDefaultPageMode: (id: string, defaultPageMode: PageMode) => request("PATCH", `/api/v1/workspaces/${encodeURIComponent(id)}`, { defaultPageMode }), + /** Turns public share links and chat-app link previews of private pages on or off. */ + setSharing: (id: string, patch: { allowSharing?: boolean; urlPreview?: boolean }) => + request("PATCH", `/api/v1/workspaces/${enc(id)}`, patch), + /** The workspace's invite link, or null when it has none (workspace admin). */ + inviteLink: async (id: string) => { + try { + return await request("GET", `/api/v1/workspaces/${enc(id)}/invite-link`); + } catch (e) { + if (e instanceof ApiError && e.status === 404) return null; + throw e; + } + }, + setInviteLink: (id: string, input: InviteLinkInput) => + request("PUT", `/api/v1/workspaces/${enc(id)}/invite-link`, input), + deleteInviteLink: (id: string) => request("DELETE", `/api/v1/workspaces/${enc(id)}/invite-link`), + joinRequests: (id: string) => request("GET", `/api/v1/workspaces/${enc(id)}/join-requests`), + approveJoin: (id: string, requestId: string, role?: WorkspaceRole) => + post(`/api/v1/workspaces/${enc(id)}/join-requests/${enc(requestId)}/approve`, role ? { role } : {}), + declineJoin: (id: string, requestId: string) => + post(`/api/v1/workspaces/${enc(id)}/join-requests/${enc(requestId)}/decline`), + /** Files no page of the workspace uses any more (workspace admin). */ + unusedFiles: (id: string) => request("GET", `/api/v1/workspaces/${enc(id)}/unused-files`), + /** Deletes the given unused files, or all of them without ids. */ + deleteUnusedFiles: (id: string, ids?: string[]) => + post<{ deleted: number }>(`/api/v1/workspaces/${enc(id)}/unused-files/delete`, ids ? { ids } : {}), remove: (id: string) => request("DELETE", `/api/v1/workspaces/${encodeURIComponent(id)}`), /** A zip that restores the workspace 1:1 (workspace admin). */ snapshot: (id: string) => download(`/api/v1/workspaces/${encodeURIComponent(id)}/snapshot`), @@ -675,6 +719,9 @@ export function createClient(opts: ClientOptions) { pages: { get: (id: string) => request("GET", `/api/v1/pages/${encodeURIComponent(id)}`), + /** How often and by whom the page was opened (editor). */ + analytics: (id: string, days?: number) => + request("GET", `/api/v1/pages/${enc(id)}/analytics${query({ days })}`), update: ( id: string, patch: { diff --git a/Packages/api-client/src/schema.d.ts b/Packages/api-client/src/schema.d.ts index df2875c..34a3807 100644 --- a/Packages/api-client/src/schema.d.ts +++ b/Packages/api-client/src/schema.d.ts @@ -608,7 +608,7 @@ export interface paths { delete: operations["deleteWorkspace"]; options?: never; head?: never; - /** Rename a workspace or change how its new pages open (workspace admin or above) */ + /** Rename a workspace, change how its new pages open, or its sharing switches (workspace admin or above) */ patch: operations["updateWorkspace"]; trace?: never; }; @@ -1753,6 +1753,215 @@ export interface paths { patch?: never; trace?: never; }; + "/api/v1/workspaces/{id}/invite-link": { + parameters: { + query?: never; + header?: never; + path: { + id: string; + }; + cookie?: never; + }; + /** The workspace's invite link (404 when it has none; workspace admin) */ + get: operations["getInviteLink"]; + /** + * Create or change the invite link (workspace admin) + * @description An existing link keeps its URL unless reset is true. + */ + put: operations["setInviteLink"]; + post?: never; + /** Turn the invite link off; its URL stops working (workspace admin) */ + delete: operations["deleteInviteLink"]; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/v1/workspaces/{id}/join-requests": { + parameters: { + query?: never; + header?: never; + path: { + id: string; + }; + cookie?: never; + }; + /** Requests to join through the invite link that wait for a decision (workspace admin) */ + get: operations["listJoinRequests"]; + put?: never; + post?: never; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/v1/workspaces/{id}/join-requests/{requestId}/approve": { + parameters: { + query?: never; + header?: never; + path: { + id: string; + requestId: string; + }; + cookie?: never; + }; + get?: never; + put?: never; + /** Let the person in and tell them (workspace admin) */ + post: operations["approveJoinRequest"]; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/v1/workspaces/{id}/join-requests/{requestId}/decline": { + parameters: { + query?: never; + header?: never; + path: { + id: string; + requestId: string; + }; + cookie?: never; + }; + get?: never; + put?: never; + /** Turn the request down and tell the person (workspace admin) */ + post: operations["declineJoinRequest"]; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/v1/auth/join/{token}": { + parameters: { + query?: never; + header?: never; + path: { + token: string; + }; + cookie?: never; + }; + /** Describe an invite link (no account needed; status is filled in when signed in) */ + get: operations["getJoinInfo"]; + put?: never; + /** Join through an invite link, or ask to when it needs approval */ + post: operations["joinWorkspace"]; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/v1/pages/{id}/analytics": { + parameters: { + query?: { + days?: number; + }; + header?: never; + path: { + id: string; + }; + cookie?: never; + }; + /** How often and by whom the page was opened (editor) */ + get: operations["getPageAnalytics"]; + put?: never; + post?: never; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/v1/workspaces/{id}/unused-files": { + parameters: { + query?: never; + header?: never; + path: { + id: string; + }; + cookie?: never; + }; + /** + * Files no page of the workspace uses any more (workspace admin) + * @description A file is in use when a page's current document (trashed pages included), a page icon or a comment refers to it. Files uploaded in the last 24 hours are never listed. Old page versions are not searched. + */ + get: operations["listUnusedFiles"]; + put?: never; + post?: never; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/v1/workspaces/{id}/unused-files/delete": { + parameters: { + query?: never; + header?: never; + path: { + id: string; + }; + cookie?: never; + }; + get?: never; + put?: never; + /** + * Delete unused files (workspace admin) + * @description Deletes the listed files, or every unused file when ids is empty. Files that came into use since are kept. + */ + post: operations["deleteUnusedFiles"]; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/v1/previews/pages/{id}": { + parameters: { + query?: never; + header?: never; + path: { + id: string; + }; + cookie?: never; + }; + /** Title of a private page for chat apps' link previews (only when the workspace turned URL previews on) */ + get: operations["getPagePreview"]; + put?: never; + post?: never; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/v1/previews/share/{token}": { + parameters: { + query?: { + /** @description A page under the shared one */ + page?: string; + }; + header?: never; + path: { + token: string; + }; + cookie?: never; + }; + /** Title and opening text of a page reached through a share link, for link previews */ + get: operations["getSharePreview"]; + put?: never; + post?: never; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; "/api/v1/workspaces/{id}/people": { parameters: { query?: never; @@ -3264,6 +3473,10 @@ export interface components { created: string; /** @description The view new pages of the workspace open in */ defaultPageMode: components["schemas"]["PageMode"]; + /** @description False when public share links are off for the whole workspace */ + allowSharing: boolean; + /** @description Chat apps may show private pages' titles in link previews */ + urlPreview: boolean; }; WorkspaceMember: { user: { @@ -3786,6 +3999,92 @@ export interface components { url: string; created: string; }; + InviteLink: { + token: string; + /** @description The link on docwell-web (DOCWELL_WEB_URL/join?token=...) */ + url: string; + /** @enum {string} */ + role: "member" | "guest"; + /** @description Joining needs an admin's approval */ + approval: boolean; + /** @description Empty when the link does not expire */ + expires: string; + created: string; + /** @description Requests waiting for a decision */ + pending: number; + }; + JoinRequest: { + id: string; + user: components["schemas"]["MemberUser"]; + /** @enum {string} */ + role: "member" | "guest"; + created: string; + }; + JoinInfo: { + workspace: string; + workspaceName: string; + organizationName: string; + /** @enum {string} */ + role: "member" | "guest"; + approval: boolean; + /** + * @description The caller's standing; empty when signed out or not asked yet + * @enum {string} + */ + status: "" | "member" | "pending" | "declined"; + }; + JoinResult: { + /** @enum {string} */ + status: "member" | "pending"; + workspace: string; + }; + PageAnalytics: { + days: number; + /** @description Opens in the period (repeat opens within 30 minutes count once) */ + views: number; + /** @description Different signed-in people */ + viewers: number; + /** @description Opens through a share link */ + linkViews: number; + /** @description One entry per day (UTC), oldest first */ + daily: components["schemas"]["AnalyticsDay"][]; + /** @description Who opened the page, most recent first (at most 20) */ + recent: components["schemas"]["PageViewer"][]; + }; + AnalyticsDay: { + /** @description YYYY-MM-DD (UTC) */ + date: string; + views: number; + viewers: number; + }; + PageViewer: { + user: components["schemas"]["MemberUser"]; + views: number; + lastViewed: string; + }; + UnusedFile: { + id: string; + page: string; + name: string; + mime: string; + /** @description Bytes */ + size: number; + url: string; + created: string; + /** @description The page it was uploaded to; empty when the caller cannot open it */ + pageTitle: string; + }; + UnusedFiles: { + files: components["schemas"]["UnusedFile"][]; + /** @description Total bytes */ + size: number; + }; + PagePreview: { + title: string; + description: string; + /** @description The workspace's name */ + site: string; + }; SearchHit: { /** @description The page (also for a record: the page that holds it) */ id: string; @@ -3873,8 +4172,11 @@ export interface components { WatchState: { watching: boolean; }; - /** @enum {string} */ - NotificationType: "comment" | "reply" | "mention" | "share" | "resolved" | "reminder"; + /** + * @description The join_* types are about a workspace and have no page + * @enum {string} + */ + NotificationType: "comment" | "reply" | "mention" | "share" | "resolved" | "reminder" | "join_request" | "join_approved" | "join_declined"; Notification: { id: string; type: components["schemas"]["NotificationType"]; @@ -5381,6 +5683,10 @@ export interface operations { "application/json": { name?: string; defaultPageMode?: components["schemas"]["PageMode"]; + /** @description Off turns every share link of the workspace off until it is on again */ + allowSharing?: boolean; + /** @description Let chat apps show private pages' titles in link previews */ + urlPreview?: boolean; }; }; }; @@ -7437,6 +7743,350 @@ export interface operations { 404: components["responses"]["Error"]; }; }; + getInviteLink: { + 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"]["InviteLink"]; + }; + }; + 403: components["responses"]["Error"]; + 404: components["responses"]["Error"]; + }; + }; + setInviteLink: { + parameters: { + query?: never; + header?: never; + path: { + id: string; + }; + cookie?: never; + }; + requestBody: { + content: { + "application/json": { + /** + * @description Default member + * @enum {string} + */ + role?: "member" | "guest"; + /** @description Joining needs an admin's approval */ + approval?: boolean; + /** @description Days from now; 0 means the link does not expire */ + expiresInDays?: number; + /** @description Make a new URL; the old one stops working */ + reset?: boolean; + }; + }; + }; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["InviteLink"]; + }; + }; + 400: components["responses"]["Error"]; + 403: components["responses"]["Error"]; + 404: components["responses"]["Error"]; + }; + }; + deleteInviteLink: { + parameters: { + query?: never; + header?: never; + path: { + id: string; + }; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description Off */ + 204: { + headers: { + [name: string]: unknown; + }; + content?: never; + }; + 403: components["responses"]["Error"]; + 404: components["responses"]["Error"]; + }; + }; + listJoinRequests: { + parameters: { + query?: never; + header?: never; + path: { + id: string; + }; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description Oldest first */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["JoinRequest"][]; + }; + }; + 403: components["responses"]["Error"]; + 404: components["responses"]["Error"]; + }; + }; + approveJoinRequest: { + parameters: { + query?: never; + header?: never; + path: { + id: string; + requestId: string; + }; + cookie?: never; + }; + requestBody?: { + content: { + "application/json": { + /** @description Overrides the link's role */ + role?: components["schemas"]["WorkspaceRole"]; + }; + }; + }; + responses: { + /** @description Approved */ + 204: { + headers: { + [name: string]: unknown; + }; + content?: never; + }; + 403: components["responses"]["Error"]; + 404: components["responses"]["Error"]; + 409: components["responses"]["Error"]; + }; + }; + declineJoinRequest: { + parameters: { + query?: never; + header?: never; + path: { + id: string; + requestId: string; + }; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description Declined */ + 204: { + headers: { + [name: string]: unknown; + }; + content?: never; + }; + 403: components["responses"]["Error"]; + 404: components["responses"]["Error"]; + }; + }; + getJoinInfo: { + parameters: { + query?: never; + header?: never; + path: { + token: string; + }; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["JoinInfo"]; + }; + }; + 401: components["responses"]["Error"]; + }; + }; + joinWorkspace: { + parameters: { + query?: never; + header?: never; + path: { + token: string; + }; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["JoinResult"]; + }; + }; + 401: components["responses"]["Error"]; + 409: components["responses"]["Error"]; + }; + }; + getPageAnalytics: { + parameters: { + query?: { + days?: number; + }; + header?: never; + path: { + id: string; + }; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["PageAnalytics"]; + }; + }; + 400: components["responses"]["Error"]; + 403: components["responses"]["Error"]; + 404: components["responses"]["Error"]; + }; + }; + listUnusedFiles: { + 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"]["UnusedFiles"]; + }; + }; + 403: components["responses"]["Error"]; + 404: components["responses"]["Error"]; + }; + }; + deleteUnusedFiles: { + parameters: { + query?: never; + header?: never; + path: { + id: string; + }; + cookie?: never; + }; + requestBody?: { + content: { + "application/json": { + ids?: string[]; + }; + }; + }; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": { + deleted: number; + }; + }; + }; + 403: components["responses"]["Error"]; + 404: components["responses"]["Error"]; + }; + }; + getPagePreview: { + 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"]["PagePreview"]; + }; + }; + 404: components["responses"]["Error"]; + }; + }; + getSharePreview: { + parameters: { + query?: { + /** @description A page under the shared one */ + page?: string; + }; + header?: never; + path: { + token: string; + }; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["PagePreview"]; + }; + }; + 404: components["responses"]["Error"]; + }; + }; listPeople: { parameters: { query?: { diff --git a/Packages/ui/src/icons.ts b/Packages/ui/src/icons.ts index 46e6ac9..75d6618 100644 --- a/Packages/ui/src/icons.ts +++ b/Packages/ui/src/icons.ts @@ -185,6 +185,14 @@ export const iconPaths = { "M15 5h4", ], send: ["M4 12l16-8-6 16-2-6z", "M12 14l8-10"], + // Sharing extras (Phase G): page views, people asking to join. + eye: ["M2 12s3.5-7 10-7 10 7 10 7-3.5 7-10 7S2 12 2 12z", "M12 9a3 3 0 1 0 0 6a3 3 0 1 0 0-6z"], + "user-plus": [ + "M15 20v-1a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v1", + "M8.5 4a3.5 3.5 0 1 0 0 7a3.5 3.5 0 1 0 0-7z", + "M19 8v6", + "M16 11h6", + ], } as const; export type IconName = keyof typeof iconPaths; diff --git a/Phone-App/lib/api/generated/models.dart b/Phone-App/lib/api/generated/models.dart index 8b34023..eb4762a 100644 --- a/Phone-App/lib/api/generated/models.dart +++ b/Phone-App/lib/api/generated/models.dart @@ -345,6 +345,8 @@ class Workspace { required this.role, required this.created, required this.defaultPageMode, + required this.allowSharing, + required this.urlPreview, }); factory Workspace.fromJson(Map json) => Workspace( @@ -356,6 +358,8 @@ class Workspace { role: WorkspaceRole.fromJson(json['role'] as String), created: json['created'] as String, defaultPageMode: PageMode.fromJson(json['defaultPageMode'] as String), + allowSharing: json['allowSharing'] as bool, + urlPreview: json['urlPreview'] as bool, ); final String id; @@ -375,6 +379,12 @@ class Workspace { /// The view new pages of the workspace open in final PageMode defaultPageMode; + /// False when public share links are off for the whole workspace + final bool allowSharing; + + /// Chat apps may show private pages' titles in link previews + final bool urlPreview; + Map toJson() => { 'id': id, 'name': name, @@ -384,6 +394,8 @@ class Workspace { 'role': role.toJson(), 'created': created, 'defaultPageMode': defaultPageMode.toJson(), + 'allowSharing': allowSharing, + 'urlPreview': urlPreview, }; } @@ -2771,6 +2783,429 @@ class Attachment { }; } +enum InviteLinkRole { + member('member'), + guest('guest'); + + const InviteLinkRole(this.value); + final String value; + + static InviteLinkRole fromJson(String value) => values.firstWhere( + (e) => e.value == value, + orElse: () => throw FormatException('unknown InviteLinkRole', value), + ); + + String toJson() => value; +} + +class InviteLink { + const InviteLink({ + required this.token, + required this.url, + required this.role, + required this.approval, + required this.expires, + required this.created, + required this.pending, + }); + + factory InviteLink.fromJson(Map json) => InviteLink( + token: json['token'] as String, + url: json['url'] as String, + role: InviteLinkRole.fromJson(json['role'] as String), + approval: json['approval'] as bool, + expires: json['expires'] as String, + created: json['created'] as String, + pending: (json['pending'] as num).toInt(), + ); + + final String token; + + /// The link on docwell-web (DOCWELL_WEB_URL/join?token=...) + final String url; + + final InviteLinkRole role; + + /// Joining needs an admin's approval + final bool approval; + + /// Empty when the link does not expire + final String expires; + + final String created; + + /// Requests waiting for a decision + final int pending; + + Map toJson() => { + 'token': token, + 'url': url, + 'role': role.toJson(), + 'approval': approval, + 'expires': expires, + 'created': created, + 'pending': pending, + }; +} + +enum JoinRequestRole { + member('member'), + guest('guest'); + + const JoinRequestRole(this.value); + final String value; + + static JoinRequestRole fromJson(String value) => values.firstWhere( + (e) => e.value == value, + orElse: () => throw FormatException('unknown JoinRequestRole', value), + ); + + String toJson() => value; +} + +class JoinRequest { + const JoinRequest({ + required this.id, + required this.user, + required this.role, + required this.created, + }); + + factory JoinRequest.fromJson(Map json) => JoinRequest( + id: json['id'] as String, + user: MemberUser.fromJson(json['user'] as Map), + role: JoinRequestRole.fromJson(json['role'] as String), + created: json['created'] as String, + ); + + final String id; + + final MemberUser user; + + final JoinRequestRole role; + + final String created; + + Map toJson() => { + 'id': id, + 'user': user.toJson(), + 'role': role.toJson(), + 'created': created, + }; +} + +enum JoinInfoRole { + member('member'), + guest('guest'); + + const JoinInfoRole(this.value); + final String value; + + static JoinInfoRole fromJson(String value) => values.firstWhere( + (e) => e.value == value, + orElse: () => throw FormatException('unknown JoinInfoRole', value), + ); + + String toJson() => value; +} + +/// The caller's standing; empty when signed out or not asked yet +enum JoinInfoStatus { + none(''), + member('member'), + pending('pending'), + declined('declined'); + + const JoinInfoStatus(this.value); + final String value; + + static JoinInfoStatus fromJson(String value) => values.firstWhere( + (e) => e.value == value, + orElse: () => throw FormatException('unknown JoinInfoStatus', value), + ); + + String toJson() => value; +} + +class JoinInfo { + const JoinInfo({ + required this.workspace, + required this.workspaceName, + required this.organizationName, + required this.role, + required this.approval, + required this.status, + }); + + factory JoinInfo.fromJson(Map json) => JoinInfo( + workspace: json['workspace'] as String, + workspaceName: json['workspaceName'] as String, + organizationName: json['organizationName'] as String, + role: JoinInfoRole.fromJson(json['role'] as String), + approval: json['approval'] as bool, + status: JoinInfoStatus.fromJson(json['status'] as String), + ); + + final String workspace; + + final String workspaceName; + + final String organizationName; + + final JoinInfoRole role; + + final bool approval; + + /// The caller's standing; empty when signed out or not asked yet + final JoinInfoStatus status; + + Map toJson() => { + 'workspace': workspace, + 'workspaceName': workspaceName, + 'organizationName': organizationName, + 'role': role.toJson(), + 'approval': approval, + 'status': status.toJson(), + }; +} + +enum JoinResultStatus { + member('member'), + pending('pending'); + + const JoinResultStatus(this.value); + final String value; + + static JoinResultStatus fromJson(String value) => values.firstWhere( + (e) => e.value == value, + orElse: () => throw FormatException('unknown JoinResultStatus', value), + ); + + String toJson() => value; +} + +class JoinResult { + const JoinResult({required this.status, required this.workspace}); + + factory JoinResult.fromJson(Map json) => JoinResult( + status: JoinResultStatus.fromJson(json['status'] as String), + workspace: json['workspace'] as String, + ); + + final JoinResultStatus status; + + final String workspace; + + Map toJson() => { + 'status': status.toJson(), + 'workspace': workspace, + }; +} + +class PageAnalytics { + const PageAnalytics({ + required this.days, + required this.views, + required this.viewers, + required this.linkViews, + required this.daily, + required this.recent, + }); + + factory PageAnalytics.fromJson(Map json) => PageAnalytics( + days: (json['days'] as num).toInt(), + views: (json['views'] as num).toInt(), + viewers: (json['viewers'] as num).toInt(), + linkViews: (json['linkViews'] as num).toInt(), + daily: (json['daily'] as List) + .map((e) => AnalyticsDay.fromJson(e as Map)) + .toList(), + recent: (json['recent'] as List) + .map((e) => PageViewer.fromJson(e as Map)) + .toList(), + ); + + final int days; + + /// Opens in the period (repeat opens within 30 minutes count once) + final int views; + + /// Different signed-in people + final int viewers; + + /// Opens through a share link + final int linkViews; + + /// One entry per day (UTC), oldest first + final List daily; + + /// Who opened the page, most recent first (at most 20) + final List recent; + + Map toJson() => { + 'days': days, + 'views': views, + 'viewers': viewers, + 'linkViews': linkViews, + 'daily': daily.map((e) => e.toJson()).toList(), + 'recent': recent.map((e) => e.toJson()).toList(), + }; +} + +class AnalyticsDay { + const AnalyticsDay({ + required this.date, + required this.views, + required this.viewers, + }); + + factory AnalyticsDay.fromJson(Map json) => AnalyticsDay( + date: json['date'] as String, + views: (json['views'] as num).toInt(), + viewers: (json['viewers'] as num).toInt(), + ); + + /// YYYY-MM-DD (UTC) + final String date; + + final int views; + + final int viewers; + + Map toJson() => { + 'date': date, + 'views': views, + 'viewers': viewers, + }; +} + +class PageViewer { + const PageViewer({ + required this.user, + required this.views, + required this.lastViewed, + }); + + factory PageViewer.fromJson(Map json) => PageViewer( + user: MemberUser.fromJson(json['user'] as Map), + views: (json['views'] as num).toInt(), + lastViewed: json['lastViewed'] as String, + ); + + final MemberUser user; + + final int views; + + final String lastViewed; + + Map toJson() => { + 'user': user.toJson(), + 'views': views, + 'lastViewed': lastViewed, + }; +} + +class UnusedFile { + const UnusedFile({ + required this.id, + required this.page, + required this.name, + required this.mime, + required this.size, + required this.url, + required this.created, + required this.pageTitle, + }); + + factory UnusedFile.fromJson(Map json) => UnusedFile( + id: json['id'] as String, + page: json['page'] as String, + name: json['name'] as String, + mime: json['mime'] as String, + size: (json['size'] as num).toInt(), + url: json['url'] as String, + created: json['created'] as String, + pageTitle: json['pageTitle'] as String, + ); + + final String id; + + final String page; + + final String name; + + final String mime; + + /// Bytes + final int size; + + final String url; + + final String created; + + /// The page it was uploaded to; empty when the caller cannot open it + final String pageTitle; + + Map toJson() => { + 'id': id, + 'page': page, + 'name': name, + 'mime': mime, + 'size': size, + 'url': url, + 'created': created, + 'pageTitle': pageTitle, + }; +} + +class UnusedFiles { + const UnusedFiles({required this.files, required this.size}); + + factory UnusedFiles.fromJson(Map json) => UnusedFiles( + files: (json['files'] as List) + .map((e) => UnusedFile.fromJson(e as Map)) + .toList(), + size: (json['size'] as num).toInt(), + ); + + final List files; + + /// Total bytes + final int size; + + Map toJson() => { + 'files': files.map((e) => e.toJson()).toList(), + 'size': size, + }; +} + +class PagePreview { + const PagePreview({ + required this.title, + required this.description, + required this.site, + }); + + factory PagePreview.fromJson(Map json) => PagePreview( + title: json['title'] as String, + description: json['description'] as String, + site: json['site'] as String, + ); + + final String title; + + final String description; + + /// The workspace's name + final String site; + + Map toJson() => { + 'title': title, + 'description': description, + 'site': site, + }; +} + /// Set when the hit is a database record; open it with the page link plus "#r-``-``" class SearchHitRecord { const SearchHitRecord({ @@ -3150,13 +3585,17 @@ class WatchState { Map toJson() => {'watching': watching}; } +/// The join_* types are about a workspace and have no page enum NotificationType { comment('comment'), reply('reply'), mention('mention'), share('share'), resolved('resolved'), - reminder('reminder'); + reminder('reminder'), + joinRequest('join_request'), + joinApproved('join_approved'), + joinDeclined('join_declined'); const NotificationType(this.value); final String value; diff --git a/Phone-App/lib/l10n.dart b/Phone-App/lib/l10n.dart index 9626a82..a5aff2a 100644 --- a/Phone-App/lib/l10n.dart +++ b/Phone-App/lib/l10n.dart @@ -141,6 +141,9 @@ const appStrings = >{ 'notifShare': '{who} shared a page with you', 'notifResolved': '{who} resolved a thread', 'notifReminder': 'Reminder', + 'notifJoinRequest': '{who} asks to join', + 'notifJoinApproved': 'You can now open this workspace', + 'notifJoinDeclined': 'Your request to join was declined', 'markAllRead': 'Mark all read', 'allCaughtUp': "You're all caught up.", 'hideResolved': 'Hide resolved', @@ -285,6 +288,9 @@ const appStrings = >{ 'notifShare': '{who} udostępnia Ci stronę', 'notifResolved': '{who} rozwiązuje wątek', 'notifReminder': 'Przypomnienie', + 'notifJoinRequest': '{who} prosi o dołączenie', + 'notifJoinApproved': 'Możesz już otworzyć ten obszar roboczy', + 'notifJoinDeclined': 'Twoja prośba o dołączenie została odrzucona', 'markAllRead': 'Oznacz wszystko jako przeczytane', 'allCaughtUp': 'Wszystko przeczytane.', 'hideResolved': 'Ukryj rozwiązane', @@ -432,6 +438,9 @@ const appStrings = >{ 'notifShare': '{who} hat eine Seite mit dir geteilt', 'notifResolved': '{who} hat einen Thread erledigt', 'notifReminder': 'Erinnerung', + 'notifJoinRequest': '{who} bittet um Beitritt', + 'notifJoinApproved': 'Du kannst diesen Arbeitsbereich jetzt öffnen', + 'notifJoinDeclined': 'Deine Anfrage zum Beitritt wurde abgelehnt', 'markAllRead': 'Alle als gelesen markieren', 'allCaughtUp': 'Du bist auf dem neuesten Stand.', 'hideResolved': 'Erledigte ausblenden', @@ -580,6 +589,9 @@ const appStrings = >{ 'notifShare': '{who} a partagé une page avec vous', 'notifResolved': '{who} a résolu une discussion', 'notifReminder': 'Rappel', + 'notifJoinRequest': '{who} demande à rejoindre', + 'notifJoinApproved': 'Vous pouvez maintenant ouvrir cet espace de travail', + 'notifJoinDeclined': 'Votre demande pour rejoindre a été refusée', 'markAllRead': 'Tout marquer comme lu', 'allCaughtUp': 'Vous êtes à jour.', 'hideResolved': 'Masquer les résolues', @@ -726,6 +738,9 @@ const appStrings = >{ 'notifShare': '{who} compartió una página contigo', 'notifResolved': '{who} resolvió un hilo', 'notifReminder': 'Recordatorio', + 'notifJoinRequest': '{who} pide unirse', + 'notifJoinApproved': 'Ya puedes abrir este espacio de trabajo', + 'notifJoinDeclined': 'Tu solicitud para unirte fue rechazada', 'markAllRead': 'Marcar todo como leído', 'allCaughtUp': 'Estás al día.', 'hideResolved': 'Ocultar resueltos', diff --git a/Phone-App/lib/screens/notifications_screen.dart b/Phone-App/lib/screens/notifications_screen.dart index 6e76498..12feebf 100644 --- a/Phone-App/lib/screens/notifications_screen.dart +++ b/Phone-App/lib/screens/notifications_screen.dart @@ -19,9 +19,18 @@ String notificationText(Notification n) { NotificationType.share => tr('notifShare', {'who': who}), NotificationType.resolved => tr('notifResolved', {'who': who}), NotificationType.reminder => tr('notifReminder'), + NotificationType.joinRequest => tr('notifJoinRequest', {'who': who}), + NotificationType.joinApproved => tr('notifJoinApproved'), + NotificationType.joinDeclined => tr('notifJoinDeclined'), }; } +/// Workspace notifications have no page; their excerpt is the workspace's name. +bool isWorkspaceNotification(Notification n) => + n.type == NotificationType.joinRequest || + n.type == NotificationType.joinApproved || + n.type == NotificationType.joinDeclined; + /// The inbox: mentions, replies, comments, shares and reminders, newest first. class NotificationsScreen extends StatefulWidget { const NotificationsScreen({super.key, required this.session}); @@ -112,12 +121,14 @@ class _NotificationsScreenState extends State { color: n.read ? null : Theme.of(context).colorScheme.primary, ), title: Text( - '${notificationText(n)} · ${(n.page?.title ?? '').isNotEmpty ? n.page!.title : tr('untitled')}', + isWorkspaceNotification(n) + ? '${notificationText(n)} · ${n.excerpt}' + : '${notificationText(n)} · ${(n.page?.title ?? '').isNotEmpty ? n.page!.title : tr('untitled')}', style: TextStyle(fontWeight: n.read ? null : FontWeight.w600), ), subtitle: Text( [ - n.excerpt, + if (!isWorkspaceNotification(n)) n.excerpt, shortDate(n.created), ].where((s) => s.isNotEmpty).join('\n'), maxLines: 3, diff --git a/Phone-App/test/widget_test.dart b/Phone-App/test/widget_test.dart index 80e714f..8d9de3a 100644 --- a/Phone-App/test/widget_test.dart +++ b/Phone-App/test/widget_test.dart @@ -40,6 +40,8 @@ const workspace = { 'role': 'owner', 'created': '2026-10-01 09:00:00.000Z', 'defaultPageMode': 'page', + 'allowSharing': true, + 'urlPreview': false, }; const space = { diff --git a/Server/cmd/docwell-server/main.go b/Server/cmd/docwell-server/main.go index 8ab1bb8..19d1ca2 100644 --- a/Server/cmd/docwell-server/main.go +++ b/Server/cmd/docwell-server/main.go @@ -138,6 +138,7 @@ func run(log *slog.Logger) error { 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 and sent reminders older than 90 days", 24*time.Hour, dirSvc.PruneNotifications) + reg.Register("analytics.prune", "Deletes page view counts older than 400 days", 24*time.Hour, dirSvc.PruneViews) reg.Register("notify.reminders", "Sends reminders for dates in pages that are due", time.Minute, dirSvc.SendReminders) reg.Register("links.backfill", "Works out page links for pages saved before backlinks existed", 0, dirSvc.BackfillLinks) index.Track(reg.Track) diff --git a/Server/internal/api/api.gen.go b/Server/internal/api/api.gen.go index 0dfbf6b..7b3ad22 100644 --- a/Server/internal/api/api.gen.go +++ b/Server/internal/api/api.gen.go @@ -294,6 +294,102 @@ func (e InviteStatus) Valid() bool { } } +// Defines values for InviteLinkRole. +const ( + InviteLinkRoleGuest InviteLinkRole = "guest" + InviteLinkRoleMember InviteLinkRole = "member" +) + +// Valid indicates whether the value is a known member of the InviteLinkRole enum. +func (e InviteLinkRole) Valid() bool { + switch e { + case InviteLinkRoleGuest: + return true + case InviteLinkRoleMember: + return true + default: + return false + } +} + +// Defines values for JoinInfoRole. +const ( + JoinInfoRoleGuest JoinInfoRole = "guest" + JoinInfoRoleMember JoinInfoRole = "member" +) + +// Valid indicates whether the value is a known member of the JoinInfoRole enum. +func (e JoinInfoRole) Valid() bool { + switch e { + case JoinInfoRoleGuest: + return true + case JoinInfoRoleMember: + return true + default: + return false + } +} + +// Defines values for JoinInfoStatus. +const ( + JoinInfoStatusDeclined JoinInfoStatus = "declined" + JoinInfoStatusEmpty JoinInfoStatus = "" + JoinInfoStatusMember JoinInfoStatus = "member" + JoinInfoStatusPending JoinInfoStatus = "pending" +) + +// Valid indicates whether the value is a known member of the JoinInfoStatus enum. +func (e JoinInfoStatus) Valid() bool { + switch e { + case JoinInfoStatusDeclined: + return true + case JoinInfoStatusEmpty: + return true + case JoinInfoStatusMember: + return true + case JoinInfoStatusPending: + return true + default: + return false + } +} + +// Defines values for JoinRequestRole. +const ( + JoinRequestRoleGuest JoinRequestRole = "guest" + JoinRequestRoleMember JoinRequestRole = "member" +) + +// Valid indicates whether the value is a known member of the JoinRequestRole enum. +func (e JoinRequestRole) Valid() bool { + switch e { + case JoinRequestRoleGuest: + return true + case JoinRequestRoleMember: + return true + default: + return false + } +} + +// Defines values for JoinResultStatus. +const ( + JoinResultStatusMember JoinResultStatus = "member" + JoinResultStatusPending JoinResultStatus = "pending" +) + +// Valid indicates whether the value is a known member of the JoinResultStatus enum. +func (e JoinResultStatus) Valid() bool { + switch e { + case JoinResultStatusMember: + return true + case JoinResultStatusPending: + return true + default: + return false + } +} + // Defines values for LabelColor. const ( LabelColorBlue LabelColor = "blue" @@ -374,12 +470,15 @@ func (e NotificationSettingsEmail) Valid() bool { // Defines values for NotificationType. const ( - NotificationTypeComment NotificationType = "comment" - NotificationTypeMention NotificationType = "mention" - NotificationTypeReminder NotificationType = "reminder" - NotificationTypeReply NotificationType = "reply" - NotificationTypeResolved NotificationType = "resolved" - NotificationTypeShare NotificationType = "share" + NotificationTypeComment NotificationType = "comment" + NotificationTypeJoinApproved NotificationType = "join_approved" + NotificationTypeJoinDeclined NotificationType = "join_declined" + NotificationTypeJoinRequest NotificationType = "join_request" + NotificationTypeMention NotificationType = "mention" + NotificationTypeReminder NotificationType = "reminder" + NotificationTypeReply NotificationType = "reply" + NotificationTypeResolved NotificationType = "resolved" + NotificationTypeShare NotificationType = "share" ) // Valid indicates whether the value is a known member of the NotificationType enum. @@ -387,6 +486,12 @@ func (e NotificationType) Valid() bool { switch e { case NotificationTypeComment: return true + case NotificationTypeJoinApproved: + return true + case NotificationTypeJoinDeclined: + return true + case NotificationTypeJoinRequest: + return true case NotificationTypeMention: return true case NotificationTypeReminder: @@ -909,6 +1014,24 @@ func (e ExportSpaceParamsFormat) Valid() bool { } } +// Defines values for SetInviteLinkJSONBodyRole. +const ( + SetInviteLinkJSONBodyRoleGuest SetInviteLinkJSONBodyRole = "guest" + SetInviteLinkJSONBodyRoleMember SetInviteLinkJSONBodyRole = "member" +) + +// Valid indicates whether the value is a known member of the SetInviteLinkJSONBodyRole enum. +func (e SetInviteLinkJSONBodyRole) Valid() bool { + switch e { + case SetInviteLinkJSONBodyRoleGuest: + return true + case SetInviteLinkJSONBodyRoleMember: + return true + default: + return false + } +} + // AdminHealth defines model for AdminHealth. type AdminHealth struct { Database struct { @@ -1215,6 +1338,14 @@ type AiWriteInput struct { Text string `json:"text"` } +// AnalyticsDay defines model for AnalyticsDay. +type AnalyticsDay struct { + // Date YYYY-MM-DD (UTC) + Date string `json:"date"` + Viewers int `json:"viewers"` + Views int `json:"views"` +} + // ApiToken defines model for ApiToken. type ApiToken struct { Created string `json:"created"` @@ -1665,6 +1796,27 @@ type InviteInfo struct { WorkspaceName string `json:"workspaceName"` } +// InviteLink defines model for InviteLink. +type InviteLink struct { + // Approval Joining needs an admin's approval + Approval bool `json:"approval"` + Created string `json:"created"` + + // Expires Empty when the link does not expire + Expires string `json:"expires"` + + // Pending Requests waiting for a decision + Pending int `json:"pending"` + Role InviteLinkRole `json:"role"` + Token string `json:"token"` + + // Url The link on docwell-web (DOCWELL_WEB_URL/join?token=...) + Url string `json:"url"` +} + +// InviteLinkRole defines model for InviteLink.Role. +type InviteLinkRole string + // Job defines model for Job. type Job struct { Description string `json:"description"` @@ -1687,6 +1839,44 @@ type Job struct { Runs int `json:"runs"` } +// JoinInfo defines model for JoinInfo. +type JoinInfo struct { + Approval bool `json:"approval"` + OrganizationName string `json:"organizationName"` + Role JoinInfoRole `json:"role"` + + // Status The caller's standing; empty when signed out or not asked yet + Status JoinInfoStatus `json:"status"` + Workspace string `json:"workspace"` + WorkspaceName string `json:"workspaceName"` +} + +// JoinInfoRole defines model for JoinInfo.Role. +type JoinInfoRole string + +// JoinInfoStatus The caller's standing; empty when signed out or not asked yet +type JoinInfoStatus string + +// JoinRequest defines model for JoinRequest. +type JoinRequest struct { + Created string `json:"created"` + Id string `json:"id"` + Role JoinRequestRole `json:"role"` + User MemberUser `json:"user"` +} + +// JoinRequestRole defines model for JoinRequest.Role. +type JoinRequestRole string + +// JoinResult defines model for JoinResult. +type JoinResult struct { + Status JoinResultStatus `json:"status"` + Workspace string `json:"workspace"` +} + +// JoinResultStatus defines model for JoinResult.Status. +type JoinResultStatus string + // JournalDay defines model for JournalDay. type JournalDay struct { Date openapi_types.Date `json:"date"` @@ -1777,8 +1967,10 @@ type Notification struct { 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"` + Page *PageRef `json:"page"` + Read bool `json:"read"` + + // Type The join_* types are about a workspace and have no page Type NotificationType `json:"type"` Workspace string `json:"workspace"` } @@ -1801,7 +1993,7 @@ type NotificationSettings struct { // NotificationSettingsEmail Unread notifications by email every few minutes type NotificationSettingsEmail string -// NotificationType defines model for NotificationType. +// NotificationType The join_* types are about a workspace and have no page type NotificationType string // OAuthProviderSettings defines model for OAuthProviderSettings. @@ -1953,6 +2145,25 @@ type PageAccess struct { Role SpaceRole `json:"role"` } +// PageAnalytics defines model for PageAnalytics. +type PageAnalytics struct { + // Daily One entry per day (UTC), oldest first + Daily []AnalyticsDay `json:"daily"` + Days int `json:"days"` + + // LinkViews Opens through a share link + LinkViews int `json:"linkViews"` + + // Recent Who opened the page, most recent first (at most 20) + Recent []PageViewer `json:"recent"` + + // Viewers Different signed-in people + Viewers int `json:"viewers"` + + // Views Opens in the period (repeat opens within 30 minutes count once) + Views int `json:"views"` +} + // PageContent defines model for PageContent. type PageContent struct { // Content Tiptap JSON with type "doc"; null for a page that was never edited @@ -2024,6 +2235,15 @@ type PageNode struct { Updated string `json:"updated"` } +// PagePreview defines model for PagePreview. +type PagePreview struct { + Description string `json:"description"` + + // Site The workspace's name + Site string `json:"site"` + Title string `json:"title"` +} + // PageRef defines model for PageRef. type PageRef struct { Icon string `json:"icon"` @@ -2048,6 +2268,13 @@ type PageVersion struct { Label string `json:"label"` } +// PageViewer defines model for PageViewer. +type PageViewer struct { + LastViewed string `json:"lastViewed"` + User MemberUser `json:"user"` + Views int `json:"views"` +} + // PinnedPage defines model for PinnedPage. type PinnedPage struct { Icon string `json:"icon"` @@ -2398,6 +2625,30 @@ type TrashedPage struct { Title string `json:"title"` } +// UnusedFile defines model for UnusedFile. +type UnusedFile struct { + Created string `json:"created"` + Id string `json:"id"` + Mime string `json:"mime"` + Name string `json:"name"` + Page string `json:"page"` + + // PageTitle The page it was uploaded to; empty when the caller cannot open it + PageTitle string `json:"pageTitle"` + + // Size Bytes + Size int `json:"size"` + Url string `json:"url"` +} + +// UnusedFiles defines model for UnusedFiles. +type UnusedFiles struct { + Files []UnusedFile `json:"files"` + + // Size Total bytes + Size int `json:"size"` +} + // UpdateUserRequest defines model for UpdateUserRequest. type UpdateUserRequest struct { Email *openapi_types.Email `json:"email,omitempty"` @@ -2507,7 +2758,9 @@ type WebhookInput struct { // Workspace defines model for Workspace. type Workspace struct { - Created string `json:"created"` + // AllowSharing False when public share links are off for the whole workspace + AllowSharing bool `json:"allowSharing"` + Created string `json:"created"` // DefaultPageMode The view new pages of the workspace open in DefaultPageMode PageMode `json:"defaultPageMode"` @@ -2517,6 +2770,9 @@ type Workspace struct { OrganizationName string `json:"organizationName"` Role WorkspaceRole `json:"role"` Slug string `json:"slug"` + + // UrlPreview Chat apps may show private pages' titles in link previews + UrlPreview bool `json:"urlPreview"` } // WorkspaceMember defines model for WorkspaceMember. @@ -2768,6 +3024,11 @@ type SharePageWithUserJSONBody struct { Role PageGrantRole `json:"role"` } +// GetPageAnalyticsParams defines parameters for GetPageAnalytics. +type GetPageAnalyticsParams struct { + Days *int `form:"days,omitempty" json:"days,omitempty"` +} + // ApplyTemplateJSONBody defines parameters for ApplyTemplate. type ApplyTemplateJSONBody struct { // Template A template page of the same workspace @@ -2823,6 +3084,12 @@ type SetShareLinkJSONBody struct { IncludeSubpages *bool `json:"includeSubpages,omitempty"` } +// GetSharePreviewParams defines parameters for GetSharePreview. +type GetSharePreviewParams struct { + // Page A page under the shared one + Page *string `form:"page,omitempty" json:"page,omitempty"` +} + // UpdateSpaceJSONBody defines parameters for UpdateSpace. type UpdateSpaceJSONBody struct { // DefaultRole Role that workspace members (not guests) get in an open space without an explicit role. @@ -2910,9 +3177,15 @@ type RestoreWorkspaceSnapshotMultipartBody struct { // UpdateWorkspaceJSONBody defines parameters for UpdateWorkspace. type UpdateWorkspaceJSONBody struct { + // AllowSharing Off turns every share link of the workspace off until it is on again + AllowSharing *bool `json:"allowSharing,omitempty"` + // DefaultPageMode The view a page opens in for everyone, its text or the edgeless canvas; "?mode=" in an address overrides it DefaultPageMode *PageMode `json:"defaultPageMode,omitempty"` Name *string `json:"name,omitempty"` + + // UrlPreview Let chat apps show private pages' titles in link previews + UrlPreview *bool `json:"urlPreview,omitempty"` } // AddAiFileMultipartBody defines parameters for AddAiFile. @@ -2935,6 +3208,30 @@ type ListDocsParams struct { Filter *string `form:"filter,omitempty" json:"filter,omitempty"` } +// SetInviteLinkJSONBody defines parameters for SetInviteLink. +type SetInviteLinkJSONBody struct { + // Approval Joining needs an admin's approval + Approval *bool `json:"approval,omitempty"` + + // ExpiresInDays Days from now; 0 means the link does not expire + ExpiresInDays *int `json:"expiresInDays,omitempty"` + + // Reset Make a new URL; the old one stops working + Reset *bool `json:"reset,omitempty"` + + // Role Default member + Role *SetInviteLinkJSONBodyRole `json:"role,omitempty"` +} + +// SetInviteLinkJSONBodyRole defines parameters for SetInviteLink. +type SetInviteLinkJSONBodyRole string + +// ApproveJoinRequestJSONBody defines parameters for ApproveJoinRequest. +type ApproveJoinRequestJSONBody struct { + // Role Overrides the link's role + Role *WorkspaceRole `json:"role,omitempty"` +} + // GetJournalParams defines parameters for GetJournal. type GetJournalParams struct { From openapi_types.Date `form:"from" json:"from"` @@ -3000,6 +3297,11 @@ type CreateSpaceJSONBody struct { Visibility *SpaceVisibility `json:"visibility,omitempty"` } +// DeleteUnusedFilesJSONBody defines parameters for DeleteUnusedFiles. +type DeleteUnusedFilesJSONBody struct { + Ids *[]string `json:"ids,omitempty"` +} + // McpJSONBody defines parameters for Mcp. type McpJSONBody map[string]interface{} @@ -3225,6 +3527,12 @@ type CreateCollectionJSONRequestBody = CollectionInput // CreateGroupJSONRequestBody defines body for CreateGroup for application/json ContentType. type CreateGroupJSONRequestBody = GroupRequest +// SetInviteLinkJSONRequestBody defines body for SetInviteLink for application/json ContentType. +type SetInviteLinkJSONRequestBody SetInviteLinkJSONBody + +// ApproveJoinRequestJSONRequestBody defines body for ApproveJoinRequest for application/json ContentType. +type ApproveJoinRequestJSONRequestBody ApproveJoinRequestJSONBody + // SetJournalTemplateJSONRequestBody defines body for SetJournalTemplate for application/json ContentType. type SetJournalTemplateJSONRequestBody SetJournalTemplateJSONBody @@ -3243,6 +3551,9 @@ type CreateSpaceJSONRequestBody CreateSpaceJSONBody // CreateTagJSONRequestBody defines body for CreateTag for application/json ContentType. type CreateTagJSONRequestBody = TagInput +// DeleteUnusedFilesJSONRequestBody defines body for DeleteUnusedFiles for application/json ContentType. +type DeleteUnusedFilesJSONRequestBody DeleteUnusedFilesJSONBody + // CreateWebhookJSONRequestBody defines body for CreateWebhook for application/json ContentType. type CreateWebhookJSONRequestBody = WebhookInput diff --git a/Server/internal/directory/analytics.go b/Server/internal/directory/analytics.go new file mode 100644 index 0000000..7ee9295 --- /dev/null +++ b/Server/internal/directory/analytics.go @@ -0,0 +1,227 @@ +// SPDX-License-Identifier: AGPL-3.0-or-later + +package directory + +import ( + "context" + "fmt" + "log/slog" + "sort" + "sync" + "time" + + "docwell/server/internal/access" + "docwell/server/internal/apperr" + "docwell/server/internal/store/pocketbase" +) + +// ---- Page analytics -------------------------------------------------------- +// +// Opening a page counts a view (ADR-17): the apps already report each open +// for the recent list (RecordVisit), and share links count their visitors +// without a name. Views +// are kept per page, person and day, so a page's editors can see how often +// it is read, by how many people, and who read it last. Someone who keeps a +// page open and comes back to it counts once per viewGap. + +// viewGap is how long a person's repeated opens of one page count as one view. +const viewGap = 30 * time.Minute + +// viewRetention is how long daily view counts are kept. +const viewRetention = 400 * 24 * time.Hour + +type pageViewRecord struct { + ID string `json:"id"` + Page string `json:"page"` + Workspace string `json:"workspace"` + User string `json:"user"` + Day string `json:"day"` + Views int `json:"views"` + Last string `json:"last"` +} + +// viewLog remembers recent opens so repeated ones are not counted, and +// serialises the read-modify-write of the daily rows. +type viewLog struct { + mu sync.Mutex + seen map[string]time.Time +} + +var views = &viewLog{seen: map[string]time.Time{}} + +// fresh reports whether key's open counts, and remembers it. +func (l *viewLog) fresh(key string, now time.Time) bool { + if last, ok := l.seen[key]; ok && now.Sub(last) < viewGap { + return false + } + l.seen[key] = now + if len(l.seen) > 50000 { + for k, t := range l.seen { + if now.Sub(t) >= viewGap { + delete(l.seen, k) + } + } + } + return true +} + +// recordView counts one open of p by userID ("" for a share-link visitor). +// It is best effort: a failure only loses the count. +func (s *Service) recordView(ctx context.Context, p pageRecord, userID string) { + now := time.Now().UTC() + views.mu.Lock() + defer views.mu.Unlock() + if userID != "" && !views.fresh(p.ID+"|"+userID, now) { + return + } + day := now.Format(time.DateOnly) + res, err := pocketbase.List[pageViewRecord](ctx, s.pb, "page_views", pocketbase.ListOptions{ + PerPage: 1, Filter: fmt.Sprintf("page = '%s' && user = '%s' && day = '%s'", p.ID, userID, day), + }) + if err == nil && len(res.Items) > 0 { + _, err = pocketbase.Update[struct{}](ctx, s.pb, "page_views", res.Items[0].ID, map[string]any{ + "views+": 1, "last": pbTime(now), + }) + } else if err == nil { + body := map[string]any{"page": p.ID, "workspace": p.Workspace, "day": day, "views": 1, "last": pbTime(now)} + if userID != "" { + body["user"] = userID + } + _, err = pocketbase.Create[struct{}](ctx, s.pb, "page_views", body) + } + if err != nil { + slog.Default().Warn("analytics: record view", "page", p.ID, "err", err) + } +} + +// AnalyticsDay is one day of a page's views. +type AnalyticsDay struct { + Date string `json:"date"` + Views int `json:"views"` + Viewers int `json:"viewers"` +} + +// PageViewer is someone who opened the page in the period. +type PageViewer struct { + User MemberUser `json:"user"` + Views int `json:"views"` + LastViewed string `json:"lastViewed"` +} + +// PageAnalytics sums up a page's views over the last Days days. +type PageAnalytics struct { + Days int `json:"days"` + // Views counts every counted open; Viewers the different signed-in + // people; LinkViews the opens through a share link. + Views int `json:"views"` + Viewers int `json:"viewers"` + LinkViews int `json:"linkViews"` + Daily []AnalyticsDay `json:"daily"` + // Recent lists who opened the page, most recent first (at most 20). + Recent []PageViewer `json:"recent"` +} + +// GetPageAnalytics returns a page's views for the last days days (7 to 90, +// default 30; editor). +func (s *Service) GetPageAnalytics(ctx context.Context, c access.Caller, pageID string, days int) (PageAnalytics, error) { + p, a, err := s.pageFor(ctx, c, pageID) + if err != nil { + return PageAnalytics{}, err + } + if err := access.EditPages(a.role); err != nil { + return PageAnalytics{}, apperr.Forbidden("only the page's editors can see its views") + } + if days == 0 { + days = 30 + } + if days < 7 || days > 90 { + return PageAnalytics{}, apperr.InvalidFields(map[string]string{"days": "Pick 7 to 90 days."}) + } + now := time.Now().UTC() + first := now.AddDate(0, 0, -(days - 1)).Format(time.DateOnly) + rows, err := listAll[pageViewRecord](ctx, s, "page_views", pocketbase.ListOptions{ + Filter: fmt.Sprintf("page = '%s' && day >= '%s'", p.ID, first), Sort: "day", + }) + if err != nil { + return PageAnalytics{}, err + } + return s.summarise(ctx, rows, now, days), nil +} + +// summarise turns daily rows into PageAnalytics and names the recent viewers. +func (s *Service) summarise(ctx context.Context, rows []pageViewRecord, now time.Time, days int) PageAnalytics { + out, viewers := aggregateViews(rows, now, days) + who := s.people() + for _, v := range viewers { + if len(out.Recent) == 20 { + break + } + u := who.get(ctx, v.User.ID) + if u == nil { + continue + } + v.User = *u + out.Recent = append(out.Recent, v) + } + return out +} + +// aggregateViews sums daily rows over the days ending today, with an entry +// for every day, and returns the signed-in viewers most recent first. +func aggregateViews(rows []pageViewRecord, now time.Time, days int) (PageAnalytics, []PageViewer) { + out := PageAnalytics{Days: days, Daily: make([]AnalyticsDay, days), Recent: []PageViewer{}} + index := map[string]int{} + for i := range days { + d := now.AddDate(0, 0, -(days - 1 - i)).Format(time.DateOnly) + out.Daily[i].Date = d + index[d] = i + } + people := map[string]*PageViewer{} + for _, r := range rows { + i, ok := index[r.Day] + if !ok { + continue + } + out.Views += r.Views + out.Daily[i].Views += r.Views + if r.User == "" { + out.LinkViews += r.Views + continue + } + out.Daily[i].Viewers++ + v := people[r.User] + if v == nil { + v = &PageViewer{User: MemberUser{ID: r.User}} + people[r.User] = v + } + v.Views += r.Views + if r.Last > v.LastViewed { + v.LastViewed = r.Last + } + } + out.Viewers = len(people) + list := make([]PageViewer, 0, len(people)) + for _, v := range people { + list = append(list, *v) + } + sort.Slice(list, func(i, j int) bool { return list[i].LastViewed > list[j].LastViewed }) + return out, list +} + +// PruneViews deletes daily view counts older than viewRetention. It is a +// background job. +func (s *Service) PruneViews(ctx context.Context) error { + cutoff := time.Now().UTC().Add(-viewRetention).Format(time.DateOnly) + rows, err := listAll[pageViewRecord](ctx, s, "page_views", pocketbase.ListOptions{ + Filter: fmt.Sprintf("day < '%s'", cutoff), Fields: "id", + }) + if err != nil { + return err + } + for _, r := range rows { + if err := s.pb.Delete(ctx, "page_views", r.ID); err != nil && !pocketbase.IsNotFound(err) { + return err + } + } + return nil +} diff --git a/Server/internal/directory/analytics_test.go b/Server/internal/directory/analytics_test.go new file mode 100644 index 0000000..d7e442d --- /dev/null +++ b/Server/internal/directory/analytics_test.go @@ -0,0 +1,80 @@ +// SPDX-License-Identifier: AGPL-3.0-or-later + +package directory + +import ( + "testing" + "time" +) + +func TestAggregateViews(t *testing.T) { + now := time.Date(2026, 11, 16, 12, 0, 0, 0, time.UTC) + rows := []pageViewRecord{ + {User: "ann", Day: "2026-11-16", Views: 3, Last: "2026-11-16 11:00:00.000Z"}, + {User: "bob", Day: "2026-11-16", Views: 1, Last: "2026-11-16 09:00:00.000Z"}, + {User: "", Day: "2026-11-16", Views: 5, Last: "2026-11-16 10:00:00.000Z"}, + {User: "bob", Day: "2026-11-15", Views: 2, Last: "2026-11-15 20:00:00.000Z"}, + // Outside the 7 days: ignored. + {User: "cat", Day: "2026-11-01", Views: 9, Last: "2026-11-01 08:00:00.000Z"}, + } + out, viewers := aggregateViews(rows, now, 7) + + if out.Views != 11 || out.LinkViews != 5 || out.Viewers != 2 { + t.Fatalf("totals = %d views, %d link views, %d viewers; want 11, 5, 2", out.Views, out.LinkViews, out.Viewers) + } + if len(out.Daily) != 7 || out.Daily[0].Date != "2026-11-10" || out.Daily[6].Date != "2026-11-16" { + t.Fatalf("daily = %+v, want 7 days ending today", out.Daily) + } + if d := out.Daily[6]; d.Views != 9 || d.Viewers != 2 { + t.Errorf("today = %+v, want 9 views by 2 people", d) + } + if d := out.Daily[5]; d.Views != 2 || d.Viewers != 1 { + t.Errorf("yesterday = %+v, want 2 views by 1 person", d) + } + if len(viewers) != 2 || viewers[0].User.ID != "ann" || viewers[1].User.ID != "bob" || viewers[1].Views != 3 { + t.Errorf("viewers = %+v, want ann then bob (3 views)", viewers) + } +} + +func TestViewLogCountsRepeatOpensOnce(t *testing.T) { + l := &viewLog{seen: map[string]time.Time{}} + t0 := time.Date(2026, 11, 16, 12, 0, 0, 0, time.UTC) + if !l.fresh("p|u", t0) { + t.Fatal("first open should count") + } + if l.fresh("p|u", t0.Add(10*time.Minute)) { + t.Error("an open 10 minutes later should not count") + } + if !l.fresh("p|other", t0.Add(10*time.Minute)) { + t.Error("another person's open should count") + } + if !l.fresh("p|u", t0.Add(41*time.Minute)) { + t.Error("an open after the gap should count") + } +} + +func TestJoinLinkExpiry(t *testing.T) { + now := time.Date(2026, 11, 16, 12, 0, 0, 0, time.UTC) + cases := []struct { + expires string + want bool + }{ + {"", false}, + {"2026-11-17 12:00:00.000Z", false}, + {"2026-11-16 11:59:59.000Z", true}, + } + for _, c := range cases { + if got := (joinLinkRecord{Expires: c.expires}).expired(now); got != c.want { + t.Errorf("expired(%q) = %v, want %v", c.expires, got, c.want) + } + } +} + +func TestPreviewTitle(t *testing.T) { + if got := previewTitle(pageRecord{Title: " ", Icon: "📄"}); got != "📄 Untitled" { + t.Errorf("got %q", got) + } + if got := previewTitle(pageRecord{Title: "Plan"}); got != "Plan" { + t.Errorf("got %q", got) + } +} diff --git a/Server/internal/directory/cleanup.go b/Server/internal/directory/cleanup.go new file mode 100644 index 0000000..406dbd9 --- /dev/null +++ b/Server/internal/directory/cleanup.go @@ -0,0 +1,165 @@ +// SPDX-License-Identifier: AGPL-3.0-or-later + +package directory + +import ( + "bytes" + "context" + "fmt" + "slices" + "strings" + "time" + + "docwell/server/internal/access" + "docwell/server/internal/apperr" + "docwell/server/internal/store/pocketbase" +) + +// ---- Unused files ---------------------------------------------------------- +// +// A file stays on the server after the block that showed it is deleted, so +// undo and copy-paste keep working. Workspace admins can list the files no +// page of the workspace uses any more and delete them (ADR-17). A file is in +// use when its id appears in the current document of any page in the +// workspace (trashed pages included, since they can be restored), in a page +// icon or in a comment. Files younger than unusedGrace never count as +// unused: they may be on their way into a page. Old page versions are not +// searched, so restoring a version from before a cleanup can show missing +// files; the settings page says so. + +const unusedGrace = 24 * time.Hour + +// UnusedFile is a file no page uses. +type UnusedFile struct { + Attachment + // PageTitle names the page the file was uploaded to; empty when the + // caller cannot open that page. + PageTitle string `json:"pageTitle"` +} + +// UnusedFiles lists them with their total size. +type UnusedFiles struct { + Files []UnusedFile `json:"files"` + Size int64 `json:"size"` +} + +// unusedFiles finds the workspace's unused attachments. +func (s *Service) unusedFiles(ctx context.Context, wsID string) ([]attachmentRecord, error) { + cutoff := pbTime(time.Now().Add(-unusedGrace)) + files, err := listAll[attachmentRecord](ctx, s, "attachments", pocketbase.ListOptions{ + Filter: fmt.Sprintf("workspace = '%s' && created < '%s'", wsID, cutoff), Sort: "created", + }) + if err != nil || len(files) == 0 { + return nil, err + } + pending := map[string]bool{} + for _, f := range files { + pending[f.ID] = true + } + // mark crosses off every pending id found in b. + mark := func(b []byte) { + for id := range pending { + if bytes.Contains(b, []byte(id)) { + delete(pending, id) + } + } + } + + pages, err := listAll[struct { + ID string `json:"id"` + Icon string `json:"icon"` + }](ctx, s, "pages", pocketbase.ListOptions{Filter: fmt.Sprintf("workspace = '%s'", wsID), Fields: "id,icon"}) + if err != nil { + return nil, err + } + for _, p := range pages { + if len(pending) == 0 { + break + } + mark([]byte(p.Icon)) + state, err := s.docs.State(ctx, p.ID) + if err != nil { + // Without the document nothing can be ruled out. + return nil, fmt.Errorf("unused files: page %s: %w", p.ID, err) + } + mark(state) + } + if len(pending) > 0 { + comments, err := listAll[struct { + Body string `json:"body"` + }](ctx, s, "comments", pocketbase.ListOptions{ + Filter: fmt.Sprintf("page.workspace = '%s' && body ~ '/api/v1/files/'", wsID), Fields: "body", + }) + if err != nil { + return nil, err + } + for _, c := range comments { + mark([]byte(c.Body)) + } + } + + out := files[:0] + for _, f := range files { + if pending[f.ID] { + out = append(out, f) + } + } + return out, nil +} + +// ListUnusedFiles lists the files no page of the workspace uses (workspace admin). +func (s *Service) ListUnusedFiles(ctx context.Context, c access.Caller, wsID string) (UnusedFiles, error) { + ws, _, err := s.adminWorkspace(ctx, c, wsID) + if err != nil { + return UnusedFiles{}, err + } + files, err := s.unusedFiles(ctx, ws.ID) + if err != nil { + return UnusedFiles{}, err + } + out := UnusedFiles{Files: make([]UnusedFile, 0, len(files))} + titles := map[string]string{} + for _, f := range files { + title, seen := titles[f.Page] + if !seen { + if p, _, err := s.pageFor(ctx, c, f.Page); err == nil { + title = p.Title + if strings.TrimSpace(title) == "" { + title = "Untitled" + } + } + titles[f.Page] = title + } + out.Files = append(out.Files, UnusedFile{Attachment: f.view(), PageTitle: title}) + out.Size += f.Size + } + return out, nil +} + +// DeleteUnusedFiles deletes unused files of the workspace: the listed ones, +// or all of them when ids is empty. Files that came into use since the list +// was made are kept. It returns how many were deleted (workspace admin). +func (s *Service) DeleteUnusedFiles(ctx context.Context, c access.Caller, wsID string, ids []string) (int, error) { + ws, _, err := s.adminWorkspace(ctx, c, wsID) + if err != nil { + return 0, err + } + if len(ids) > 10000 { + return 0, apperr.Invalid("too many files") + } + files, err := s.unusedFiles(ctx, ws.ID) + if err != nil { + return 0, err + } + n := 0 + for _, f := range files { + if len(ids) > 0 && !slices.Contains(ids, f.ID) { + continue + } + if err := s.pb.Delete(ctx, "attachments", f.ID); err != nil && !pocketbase.IsNotFound(err) { + return n, err + } + n++ + } + return n, nil +} diff --git a/Server/internal/directory/directory.go b/Server/internal/directory/directory.go index 21dc1eb..ab22de6 100644 --- a/Server/internal/directory/directory.go +++ b/Server/internal/directory/directory.go @@ -567,6 +567,10 @@ type Workspace struct { Created string `json:"created"` // DefaultPageMode is the view new pages open in: "page" or "edgeless". DefaultPageMode string `json:"defaultPageMode"` + // AllowSharing is false when public share links are off workspace-wide. + AllowSharing bool `json:"allowSharing"` + // URLPreview lets chat apps show private pages' titles in link previews. + URLPreview bool `json:"urlPreview"` } type workspaceRecord struct { @@ -577,6 +581,8 @@ type workspaceRecord struct { Created string `json:"created"` // DefaultPageMode is "edgeless" when new pages open as a canvas. DefaultPageMode string `json:"default_page_mode"` + SharingOff bool `json:"sharing_off"` + URLPreview bool `json:"url_preview"` Expand struct { Organization *struct { Name string `json:"name"` @@ -587,7 +593,7 @@ type workspaceRecord struct { func (r workspaceRecord) view(role string) Workspace { w := Workspace{ ID: r.ID, Name: r.Name, Slug: r.Slug, Organization: r.Organization, Role: role, Created: r.Created, - DefaultPageMode: pageMode(r.DefaultPageMode), + DefaultPageMode: pageMode(r.DefaultPageMode), AllowSharing: !r.SharingOff, URLPreview: r.URLPreview, } if r.Expand.Organization != nil { w.OrganizationName = r.Expand.Organization.Name @@ -756,6 +762,11 @@ type UpdateWorkspaceInput struct { Name *string `json:"name"` // DefaultPageMode is "page" or "edgeless": how new pages open. DefaultPageMode *string `json:"defaultPageMode"` + // AllowSharing off turns every public share link of the workspace off + // (they come back when it is turned on again). + AllowSharing *bool `json:"allowSharing"` + // URLPreview on lets chat apps show private pages' titles. + URLPreview *bool `json:"urlPreview"` } // UpdateWorkspace renames a workspace or changes how its new pages open @@ -779,6 +790,12 @@ func (s *Service) UpdateWorkspace(ctx context.Context, c access.Caller, id strin return Workspace{}, apperr.InvalidFields(map[string]string{"defaultPageMode": "Mode must be page or edgeless."}) } } + if in.AllowSharing != nil { + patch["sharing_off"] = !*in.AllowSharing + } + if in.URLPreview != nil { + patch["url_preview"] = *in.URLPreview + } ws, role, err := s.workspaceFor(ctx, c, id) if err != nil { return Workspace{}, err @@ -798,6 +815,12 @@ func (s *Service) UpdateWorkspace(ctx context.Context, c access.Caller, id strin if v, ok := patch["default_page_mode"].(string); ok { ws.DefaultPageMode = v } + if v, ok := patch["sharing_off"].(bool); ok { + ws.SharingOff = v + } + if v, ok := patch["url_preview"].(bool); ok { + ws.URLPreview = v + } return ws.view(role), nil } diff --git a/Server/internal/directory/favorites.go b/Server/internal/directory/favorites.go index 0f4ad5f..a382fa7 100644 --- a/Server/internal/directory/favorites.go +++ b/Server/internal/directory/favorites.go @@ -127,6 +127,10 @@ func (s *Service) RecordVisit(ctx context.Context, c access.Caller, pageID strin if err != nil { return err } + // The same open counts towards the page's analytics (analytics.go). + if p.DeletedAt == "" { + s.recordView(ctx, p, c.ID) + } res, err := pocketbase.List[userPageRecord](ctx, s.pb, "page_visits", pocketbase.ListOptions{ PerPage: 1, Filter: fmt.Sprintf("user = '%s' && page = '%s'", c.ID, p.ID), Fields: "id", }) diff --git a/Server/internal/directory/joinlinks.go b/Server/internal/directory/joinlinks.go new file mode 100644 index 0000000..d08632e --- /dev/null +++ b/Server/internal/directory/joinlinks.go @@ -0,0 +1,513 @@ +// SPDX-License-Identifier: AGPL-3.0-or-later + +package directory + +import ( + "context" + "crypto/rand" + "encoding/base64" + "fmt" + "log/slog" + "net/url" + "strings" + "time" + + "docwell/server/internal/access" + "docwell/server/internal/apperr" + "docwell/server/internal/auth" + "docwell/server/internal/push" + "docwell/server/internal/store/pocketbase" +) + +// ---- Invite links ---------------------------------------------------------- +// +// A workspace can have one invite link (ADR-17). Unlike an email invite it is +// not tied to a person: whoever opens it signs in (or signs up, where signup +// is open) and joins with the link's role. With approval on, opening it only +// asks to join: the workspace's admins hear about the request and approve or +// decline it, and the person hears back. Accounts without an organization +// join the workspace's organization; accounts of other organizations and +// superadmins cannot use a link, as with email invites. + +// JoinLink is a workspace's invite link, as its admins see it. +type JoinLink struct { + Token string `json:"token"` + URL string `json:"url"` + Role string `json:"role"` + Approval bool `json:"approval"` + // Expires is empty for a link that does not expire. + Expires string `json:"expires"` + Created string `json:"created"` + // Pending counts the requests waiting for a decision. + Pending int `json:"pending"` +} + +type joinLinkRecord struct { + ID string `json:"id"` + Workspace string `json:"workspace"` + Token string `json:"token"` + Role string `json:"role"` + Approval bool `json:"approval"` + CreatedBy string `json:"created_by"` + Expires string `json:"expires"` + Created string `json:"created"` +} + +func (r joinLinkRecord) expired(now time.Time) bool { + if r.Expires == "" { + return false + } + t, err := parsePBTime(r.Expires) + return err == nil && now.After(t) +} + +func (s *Service) joinLinkView(r joinLinkRecord, pending int) JoinLink { + return JoinLink{ + Token: r.Token, URL: strings.TrimRight(s.mailer.WebURL, "/") + "/join?token=" + url.QueryEscape(r.Token), + Role: r.Role, Approval: r.Approval, Expires: r.Expires, Created: r.Created, Pending: pending, + } +} + +func (s *Service) joinLinkOf(ctx context.Context, wsID string) (joinLinkRecord, error) { + res, err := pocketbase.List[joinLinkRecord](ctx, s.pb, "invite_links", pocketbase.ListOptions{ + PerPage: 1, Filter: fmt.Sprintf("workspace = '%s'", wsID), + }) + if err != nil || len(res.Items) == 0 { + return joinLinkRecord{}, err + } + return res.Items[0], nil +} + +// adminWorkspace loads a workspace c administers. +func (s *Service) adminWorkspace(ctx context.Context, c access.Caller, wsID string) (workspaceRecord, string, error) { + ws, role, err := s.workspaceFor(ctx, c, wsID) + if err != nil { + return ws, role, err + } + if !access.AtLeast(role, access.WorkspaceAdmin) { + return ws, role, apperr.Forbidden("workspace admin role required") + } + return ws, role, nil +} + +func (s *Service) pendingRequests(ctx context.Context, wsID string) (int, error) { + return s.count(ctx, "invite_requests", fmt.Sprintf("workspace = '%s' && status = 'pending'", wsID)) +} + +// GetJoinLink returns a workspace's invite link; ok is false when it has none +// (workspace admin). +func (s *Service) GetJoinLink(ctx context.Context, c access.Caller, wsID string) (JoinLink, bool, error) { + ws, _, err := s.adminWorkspace(ctx, c, wsID) + if err != nil { + return JoinLink{}, false, err + } + rec, err := s.joinLinkOf(ctx, ws.ID) + if err != nil || rec.ID == "" { + return JoinLink{}, false, err + } + n, err := s.pendingRequests(ctx, ws.ID) + return s.joinLinkView(rec, n), err == nil, err +} + +type SetJoinLinkInput struct { + // Role is member (default) or guest. + Role string `json:"role"` + Approval bool `json:"approval"` + // ExpiresInDays is 1 to 365; 0 means the link does not expire. A change + // counts from now. + ExpiresInDays int `json:"expiresInDays"` + // Reset makes a new URL; the old one stops working. + Reset bool `json:"reset"` +} + +// SetJoinLink creates or changes a workspace's invite link (workspace admin). +// An existing link keeps its URL unless Reset is set. +func (s *Service) SetJoinLink(ctx context.Context, c access.Caller, wsID string, in SetJoinLinkInput) (JoinLink, error) { + ws, actorRole, err := s.adminWorkspace(ctx, c, wsID) + if err != nil { + return JoinLink{}, err + } + role := in.Role + if role == "" { + role = access.WorkspaceMember + } + if role != access.WorkspaceMember && role != access.WorkspaceGuest { + return JoinLink{}, apperr.InvalidFields(map[string]string{"role": "Role must be member or guest."}) + } + if err := access.InviteToWorkspace(actorRole, role); err != nil { + return JoinLink{}, err + } + if in.ExpiresInDays < 0 || in.ExpiresInDays > 365 { + return JoinLink{}, apperr.InvalidFields(map[string]string{"expiresInDays": "Pick 1 to 365 days, or 0 for no end."}) + } + body := map[string]any{"role": role, "approval": in.Approval, "expires": ""} + if in.ExpiresInDays > 0 { + body["expires"] = pbTime(time.Now().Add(time.Duration(in.ExpiresInDays) * 24 * time.Hour)) + } + rec, err := s.joinLinkOf(ctx, ws.ID) + if err != nil { + return JoinLink{}, err + } + if rec.ID == "" || in.Reset { + token, err := newJoinToken() + if err != nil { + return JoinLink{}, err + } + body["token"] = token + } + if rec.ID != "" { + rec, err = pocketbase.Update[joinLinkRecord](ctx, s.pb, "invite_links", rec.ID, body) + } else { + body["workspace"], body["created_by"] = ws.ID, c.ID + rec, err = pocketbase.Create[joinLinkRecord](ctx, s.pb, "invite_links", body) + } + if err != nil { + return JoinLink{}, mapPB(err, "workspace not found") + } + n, err := s.pendingRequests(ctx, ws.ID) + return s.joinLinkView(rec, n), err +} + +func newJoinToken() (string, error) { + b := make([]byte, 24) + if _, err := rand.Read(b); err != nil { + return "", err + } + return base64.RawURLEncoding.EncodeToString(b), nil +} + +// DeleteJoinLink turns a workspace's invite link off; its URL stops working. +// Requests already made stay for the admins to decide (workspace admin). +func (s *Service) DeleteJoinLink(ctx context.Context, c access.Caller, wsID string) error { + ws, _, err := s.adminWorkspace(ctx, c, wsID) + if err != nil { + return err + } + rec, err := s.joinLinkOf(ctx, ws.ID) + if err != nil || rec.ID == "" { + return err + } + return mapPB(s.pb.Delete(ctx, "invite_links", rec.ID), "workspace not found") +} + +// openJoinLink finds a working link; unknown and expired tokens are both +// auth.ErrInvalidToken. +func (s *Service) openJoinLink(ctx context.Context, token string) (joinLinkRecord, workspaceRecord, error) { + token = strings.TrimSpace(token) + if len(token) < 24 || len(token) > 64 || !validID(token) { + return joinLinkRecord{}, workspaceRecord{}, auth.ErrInvalidToken + } + res, err := pocketbase.List[joinLinkRecord](ctx, s.pb, "invite_links", pocketbase.ListOptions{ + PerPage: 1, Filter: fmt.Sprintf("token = '%s'", token), + }) + if err != nil { + return joinLinkRecord{}, workspaceRecord{}, err + } + if len(res.Items) == 0 || res.Items[0].expired(time.Now()) { + return joinLinkRecord{}, workspaceRecord{}, auth.ErrInvalidToken + } + ws, err := s.getWorkspace(ctx, res.Items[0].Workspace) + if err != nil { + return joinLinkRecord{}, workspaceRecord{}, auth.ErrInvalidToken + } + return res.Items[0], ws, nil +} + +// JoinInfo is what the /join page shows. Status is the caller's standing: +// "" (signed out or not asked yet), member, pending or declined. +type JoinInfo struct { + Workspace string `json:"workspace"` + WorkspaceName string `json:"workspaceName"` + OrganizationName string `json:"organizationName"` + Role string `json:"role"` + Approval bool `json:"approval"` + Status string `json:"status"` +} + +type joinRequestRecord struct { + ID string `json:"id"` + Workspace string `json:"workspace"` + User string `json:"user"` + Role string `json:"role"` + Status string `json:"status"` + ReviewedBy string `json:"reviewed_by"` + ReviewedAt string `json:"reviewed_at"` + Created string `json:"created"` +} + +func (s *Service) joinRequestOf(ctx context.Context, wsID, userID string) (joinRequestRecord, error) { + res, err := pocketbase.List[joinRequestRecord](ctx, s.pb, "invite_requests", pocketbase.ListOptions{ + PerPage: 1, Filter: fmt.Sprintf("workspace = '%s' && user = '%s'", wsID, userID), + }) + if err != nil || len(res.Items) == 0 { + return joinRequestRecord{}, err + } + return res.Items[0], nil +} + +// GetJoinInfo describes a working invite link; me may be nil. +func (s *Service) GetJoinInfo(ctx context.Context, me *auth.User, token string) (JoinInfo, error) { + link, ws, err := s.openJoinLink(ctx, token) + if err != nil { + return JoinInfo{}, err + } + info := JoinInfo{Workspace: ws.ID, WorkspaceName: ws.Name, Role: link.Role, Approval: link.Approval} + if ws.Expand.Organization != nil { + info.OrganizationName = ws.Expand.Organization.Name + } + if me != nil { + if info.Status, err = s.joinStatus(ctx, me.Caller(), ws); err != nil { + return JoinInfo{}, err + } + } + return info, nil +} + +func (s *Service) joinStatus(ctx context.Context, c access.Caller, ws workspaceRecord) (string, error) { + if role, err := s.effective(ctx, c, ws); err != nil { + return "", err + } else if role != "" { + return "member", nil + } + req, err := s.joinRequestOf(ctx, ws.ID, c.ID) + if err != nil { + return "", err + } + switch req.Status { + case "pending", "declined": + return req.Status, nil + } + return "", nil +} + +// JoinResult says what using a link did: "member" (joined, or was already +// in) or "pending" (asked; an admin decides). +type JoinResult struct { + Status string `json:"status"` + Workspace string `json:"workspace"` +} + +// Join uses an invite link for the signed-in person. +func (s *Service) Join(ctx context.Context, me auth.User, token string) (JoinResult, error) { + link, ws, err := s.openJoinLink(ctx, token) + if err != nil { + return JoinResult{}, err + } + out := JoinResult{Workspace: ws.ID} + status, err := s.joinStatus(ctx, me.Caller(), ws) + if err != nil { + return out, err + } + switch status { + case "member", "pending": + out.Status = status + return out, nil + } + if err := access.AcceptInvite(me.Role, me.Organization, ws.Organization); err != nil { + return out, err + } + if !link.Approval { + if err := s.addJoiner(ctx, ws, me.ID, link.Role); err != nil { + return out, err + } + out.Status = "member" + return out, nil + } + + // Asking again after a decline starts a new request. + prev, err := s.joinRequestOf(ctx, ws.ID, me.ID) + if err != nil { + return out, err + } + body := map[string]any{"role": link.Role, "status": "pending", "reviewed_by": "", "reviewed_at": ""} + if prev.ID != "" { + _, err = pocketbase.Update[joinRequestRecord](ctx, s.pb, "invite_requests", prev.ID, body) + } else { + body["workspace"], body["user"] = ws.ID, me.ID + _, err = pocketbase.Create[joinRequestRecord](ctx, s.pb, "invite_requests", body) + } + if err != nil { + return out, mapPB(err, "workspace not found") + } + s.notifyWorkspace(ctx, ws, me.ID, s.workspaceAdmins(ctx, ws), NotifyJoinRequest) + out.Status = "pending" + return out, nil +} + +// addJoiner moves an account without an organization into the workspace's +// and makes it a member with role. +func (s *Service) addJoiner(ctx context.Context, ws workspaceRecord, userID, role string) error { + u, err := s.getUser(ctx, userID) + if err != nil { + return err + } + if err := access.AcceptInvite(u.Role, u.Organization, ws.Organization); err != nil { + return err + } + if u.Organization != ws.Organization { + if _, err := pocketbase.Update[auth.UserRecord](ctx, s.pb, "users", u.ID, map[string]any{ + "organization": ws.Organization, "role": access.RoleUser, + }); err != nil { + return mapPB(err, "user not found") + } + } + current, err := s.membership(ctx, ws.ID, u.ID) + if err != nil { + return err + } + if current.ID == "" { + if _, err := pocketbase.Create[memberRecord](ctx, s.pb, "workspace_members", map[string]any{ + "workspace": ws.ID, "user": u.ID, "role": role, + }); err != nil { + return mapPB(err, "workspace not found") + } + } + s.forget(u.ID) + return nil +} + +// JoinRequest is a request to join, as admins see it. +type JoinRequest struct { + ID string `json:"id"` + User MemberUser `json:"user"` + Role string `json:"role"` + Created string `json:"created"` +} + +// ListJoinRequests lists the requests waiting for a decision, oldest first +// (workspace admin). +func (s *Service) ListJoinRequests(ctx context.Context, c access.Caller, wsID string) ([]JoinRequest, error) { + ws, _, err := s.adminWorkspace(ctx, c, wsID) + if err != nil { + return nil, err + } + recs, err := listAll[joinRequestRecord](ctx, s, "invite_requests", pocketbase.ListOptions{ + Filter: fmt.Sprintf("workspace = '%s' && status = 'pending'", ws.ID), Sort: "created", + }) + if err != nil { + return nil, err + } + who := s.people() + out := make([]JoinRequest, 0, len(recs)) + for _, r := range recs { + u := who.get(ctx, r.User) + if u == nil { + continue + } + out = append(out, JoinRequest{ID: r.ID, User: *u, Role: r.Role, Created: r.Created}) + } + return out, nil +} + +// ReviewJoinRequest approves or declines a pending request (workspace admin) +// and tells the person. role, when set, overrides the requested role on +// approval. +func (s *Service) ReviewJoinRequest(ctx context.Context, c access.Caller, wsID, id string, approve bool, role string) error { + ws, actorRole, err := s.adminWorkspace(ctx, c, wsID) + if err != nil { + return err + } + if !validID(id) { + return apperr.NotFound("request not found") + } + req, err := pocketbase.Get[joinRequestRecord](ctx, s.pb, "invite_requests", id) + if err != nil || req.Workspace != ws.ID || req.Status != "pending" { + return apperr.NotFound("request not found") + } + status := "declined" + if approve { + if role == "" { + role = req.Role + } + if err := access.InviteToWorkspace(actorRole, role); err != nil { + return err + } + if err := s.addJoiner(ctx, ws, req.User, role); err != nil { + return err + } + status = "approved" + } + if _, err := pocketbase.Update[joinRequestRecord](ctx, s.pb, "invite_requests", req.ID, map[string]any{ + "status": status, "reviewed_by": c.ID, "reviewed_at": pbTime(time.Now()), + }); err != nil { + return mapPB(err, "request not found") + } + kind := NotifyJoinDeclined + if approve { + kind = NotifyJoinApproved + } + s.notifyWorkspace(ctx, ws, c.ID, []string{req.User}, kind) + return nil +} + +// workspaceAdmins lists who hears about join requests: the workspace's +// explicit admins and owners; when it has none, its organization's admins; +// when the organization has none either, the superadmins. +func (s *Service) workspaceAdmins(ctx context.Context, ws workspaceRecord) []string { + members, err := listAll[memberRecord](ctx, s, "workspace_members", pocketbase.ListOptions{ + Filter: fmt.Sprintf("workspace = '%s' && (role = 'admin' || role = 'owner')", ws.ID), + }) + if err != nil { + slog.Default().Warn("join: list admins", "workspace", ws.ID, "err", err) + return nil + } + var out []string + for _, m := range members { + out = append(out, m.User) + } + if len(out) > 0 { + return out + } + for _, filter := range []string{ + fmt.Sprintf("organization = '%s' && role = 'admin' && status != 'disabled'", ws.Organization), + "role = 'superadmin' && status != 'disabled'", + } { + admins, err := listAll[auth.UserRecord](ctx, s, "users", pocketbase.ListOptions{Filter: filter, Fields: "id"}) + if err != nil { + slog.Default().Warn("join: list admins", "workspace", ws.ID, "err", err) + return nil + } + for _, u := range admins { + out = append(out, u.ID) + } + if len(out) > 0 { + break + } + } + return out +} + +// notifyWorkspace stores a workspace notification (one without a page) for +// each recipient and pushes it to their phones (best effort). +func (s *Service) notifyWorkspace(ctx context.Context, ws workspaceRecord, actor string, to []string, kind string) { + who := "Someone" + if u, err := s.getUser(ctx, actor); err == nil { + who = u.Name + if who == "" { + who = u.Email + } + } + var body, route string + switch kind { + case NotifyJoinRequest: + body, route = who+" asks to join", "/w/"+ws.ID+"/settings" + case NotifyJoinApproved: + body, route = "You can now open this workspace", "/" + case NotifyJoinDeclined: + body, route = "Your request to join was declined", "/" + } + for _, userID := range to { + if userID == "" || userID == actor || !validID(userID) { + continue + } + if _, err := pocketbase.Create[struct{}](ctx, s.pb, "notifications", map[string]any{ + "user": userID, "workspace": ws.ID, "type": kind, "actor": actor, "excerpt": excerpt(ws.Name), + }); err != nil { + slog.Default().Warn("notify: create", "user", userID, "err", err) + continue + } + if s.push != nil { + s.push.Notify(userID, push.Message{Title: ws.Name, Body: body, Route: route}) + } + } +} diff --git a/Server/internal/directory/notify.go b/Server/internal/directory/notify.go index c69d5c9..0d7e729 100644 --- a/Server/internal/directory/notify.go +++ b/Server/internal/directory/notify.go @@ -37,6 +37,10 @@ const ( NotifyMention = "mention" NotifyShare = "share" NotifyResolved = "resolved" + // Workspace notifications, without a page (joinlinks.go). + NotifyJoinRequest = "join_request" + NotifyJoinApproved = "join_approved" + NotifyJoinDeclined = "join_declined" ) // notifyRank decides which type wins when one event reaches someone for @@ -509,7 +513,7 @@ type NotificationSettings struct { } // notificationTypes are every type a notification can have, in menu order. -var notificationTypes = []string{"mention", "comment", "reply", "resolved", "share", "reminder"} +var notificationTypes = []string{"mention", "comment", "reply", "resolved", "share", "reminder", "join_request"} // emailTypes is every notification type except the ones turned off. func emailTypes(off []string) []string { @@ -576,7 +580,7 @@ type digestItem struct { func (s *Service) digestLine(ctx context.Context, n notificationRecord, who *people) (digestItem, bool) { if n.Page == "" { - return digestItem{}, false + return s.workspaceDigestLine(ctx, n, who) } p, err := s.getPage(ctx, n.Page) if err != nil || p.DeletedAt != "" { @@ -611,6 +615,28 @@ func (s *Service) digestLine(ctx context.Context, n notificationRecord, who *peo return digestItem{Text: text, Link: link}, true } +// workspaceDigestLine is the digest line of a notification without a page. +func (s *Service) workspaceDigestLine(ctx context.Context, n notificationRecord, who *people) (digestItem, bool) { + ws, err := s.getWorkspace(ctx, n.Workspace) + if err != nil { + return digestItem{}, false + } + actor := who.get(ctx, n.Actor).display() + if actor == "" { + actor = "Someone" + } + base := strings.TrimRight(s.mailer.WebURL, "/") + switch n.Type { + case NotifyJoinRequest: + return digestItem{Text: fmt.Sprintf("%s asks to join “%s”", actor, ws.Name), Link: base + "/w/" + url.PathEscape(ws.ID) + "/settings"}, true + case NotifyJoinApproved: + return digestItem{Text: fmt.Sprintf("You can now open “%s”", ws.Name), Link: base + "/"}, true + case NotifyJoinDeclined: + return digestItem{Text: fmt.Sprintf("Your request to join “%s” was declined", ws.Name), Link: base + "/"}, true + } + return digestItem{}, false +} + // SendDigests emails each person their unread notifications that were not // mailed yet and are older than digestDelay, then marks them mailed. People // who turned email off are marked without a mail. It is a background job. diff --git a/Server/internal/directory/notify_test.go b/Server/internal/directory/notify_test.go index 35060e4..3fc3f1f 100644 --- a/Server/internal/directory/notify_test.go +++ b/Server/internal/directory/notify_test.go @@ -70,7 +70,7 @@ func TestLinkIDs(t *testing.T) { func TestEmailTypesLeaveOutTheOnesTurnedOff(t *testing.T) { got := emailTypes([]string{"comment", "share"}) - want := []string{"mention", "reply", "resolved", "reminder"} + want := []string{"mention", "reply", "resolved", "reminder", "join_request"} if strings.Join(got, ",") != strings.Join(want, ",") { t.Errorf("emailTypes = %v, want %v", got, want) } diff --git a/Server/internal/directory/previews.go b/Server/internal/directory/previews.go new file mode 100644 index 0000000..4719ce2 --- /dev/null +++ b/Server/internal/directory/previews.go @@ -0,0 +1,76 @@ +// SPDX-License-Identifier: AGPL-3.0-or-later + +package directory + +import ( + "context" + "fmt" + "strings" + + "docwell/server/internal/apperr" + "docwell/server/internal/store/pocketbase" +) + +// ---- Link previews for chat apps ------------------------------------------- +// +// When a Docwell link is posted in Slack, Teams, Mattermost and the like, +// their bots fetch it to show a preview. docwell-web asks these lookups for +// what to put in the page's meta tags (ADR-17). A share link always gets its +// page's title and the start of its text, since anyone can read it anyway. +// A private page gets only its title and workspace, and only when the +// workspace turned URL previews on; pages restricted to some people never +// get one. + +// PagePreview is what a chat app's link preview shows. +type PagePreview struct { + Title string `json:"title"` + Description string `json:"description"` + // Site is the workspace's name. + Site string `json:"site"` +} + +func previewTitle(p pageRecord) string { + t := strings.TrimSpace(p.Title) + if t == "" { + t = "Untitled" + } + if p.Icon != "" { + t = p.Icon + " " + t + } + return t +} + +// GetPagePreview previews a private page for a link; it is not found unless +// the page's workspace turned URL previews on. +func (s *Service) GetPagePreview(ctx context.Context, pageID string) (PagePreview, error) { + notFound := apperr.NotFound("no preview") + p, err := s.getPage(ctx, pageID) + if err != nil || p.DeletedAt != "" || p.Restricted { + return PagePreview{}, notFound + } + ws, err := s.getWorkspace(ctx, p.Workspace) + if err != nil || !ws.URLPreview { + return PagePreview{}, notFound + } + return PagePreview{Title: previewTitle(p), Site: ws.Name}, nil +} + +// GetSharePreview previews a page reached through a share link (pageID "" +// for the shared page itself). +func (s *Service) GetSharePreview(ctx context.Context, token, pageID string) (PagePreview, error) { + link, p, _, err := s.sharedScope(ctx, token, pageID) + if err != nil { + return PagePreview{}, err + } + out := PagePreview{Title: previewTitle(p)} + if ws, err := s.getWorkspace(ctx, link.Workspace); err == nil { + out.Site = ws.Name + } + res, err := pocketbase.List[struct { + ContentText string `json:"content_text"` + }](ctx, s.pb, "pages", pocketbase.ListOptions{PerPage: 1, Filter: fmt.Sprintf("id = '%s'", p.ID), Fields: "content_text"}) + if err == nil && len(res.Items) > 0 { + out.Description = excerpt(res.Items[0].ContentText) + } + return out, nil +} diff --git a/Server/internal/directory/shares.go b/Server/internal/directory/shares.go index a28cd07..0af8fe1 100644 --- a/Server/internal/directory/shares.go +++ b/Server/internal/directory/shares.go @@ -21,6 +21,8 @@ import ( // A share link lets anyone read a page without an account; with subpages, the // pages under it too. Editors turn it on and off. Reads through a link never // see trashed pages, and attachments are reachable only for shared pages. +// A workspace admin can turn sharing off for the whole workspace: links can +// no longer be made, and existing ones stop working until it is back on. // ShareLink is a page's public link, as editors see it. type ShareLink struct { @@ -76,6 +78,11 @@ func (s *Service) SetShareLink(ctx context.Context, c access.Caller, pageID stri if err != nil { return ShareLink{}, err } + if off, err := s.sharingOff(ctx, p.Workspace); err != nil { + return ShareLink{}, err + } else if off { + return ShareLink{}, apperr.Forbidden("public links are turned off in this workspace") + } rec, err := s.shareOf(ctx, p.ID) if err != nil { return ShareLink{}, err @@ -116,6 +123,15 @@ func (s *Service) DeleteShareLink(ctx context.Context, c access.Caller, pageID s return mapPB(s.pb.Delete(ctx, "share_links", rec.ID), "page not found") } +// sharingOff reports whether a workspace turned public links off. +func (s *Service) sharingOff(ctx context.Context, wsID string) (bool, error) { + ws, err := s.getWorkspace(ctx, wsID) + if err != nil { + return false, err + } + return ws.SharingOff, nil +} + // SharedPage is what a link's visitors see. type SharedPage struct { ID string `json:"id"` @@ -149,6 +165,9 @@ func (s *Service) sharedScope(ctx context.Context, token, pageID string) (shareR return shareRecord{}, pageRecord{}, tree{}, notFound } link := res.Items[0] + if off, err := s.sharingOff(ctx, link.Workspace); err != nil || off { + return link, pageRecord{}, tree{}, notFound + } root, err := s.getPage(ctx, link.Page) if err != nil { return link, pageRecord{}, tree{}, notFound @@ -181,6 +200,7 @@ func (s *Service) GetSharedPage(ctx context.Context, token, pageID string) (Shar if err != nil { return SharedPage{}, err } + s.recordView(ctx, p, "") root := t.byID[link.Page] out := SharedPage{ ID: p.ID, Title: p.Title, Icon: p.Icon, Updated: p.Updated, Content: doc, Mode: pageMode(p.DefaultMode), diff --git a/Server/internal/httpapi/auth.go b/Server/internal/httpapi/auth.go index c25e813..39e6a9e 100644 --- a/Server/internal/httpapi/auth.go +++ b/Server/internal/httpapi/auth.go @@ -220,6 +220,7 @@ func (a *api) routes(mux *routeMux) { a.searchRoutes(mux) a.transferRoutes(mux) a.shareRoutes(mux) + a.sharingRoutes(mux) a.permissionRoutes(mux) a.linkRoutes(mux) a.pushRoutes(mux) diff --git a/Server/internal/httpapi/directory.go b/Server/internal/httpapi/directory.go index dd686ae..0b1c97f 100644 --- a/Server/internal/httpapi/directory.go +++ b/Server/internal/httpapi/directory.go @@ -47,6 +47,7 @@ type DirectoryService interface { WebhookService CommentService OrganizeService + SharingService } func caller(r *http.Request) access.Caller { diff --git a/Server/internal/httpapi/sharing.go b/Server/internal/httpapi/sharing.go new file mode 100644 index 0000000..4364aa6 --- /dev/null +++ b/Server/internal/httpapi/sharing.go @@ -0,0 +1,119 @@ +// SPDX-License-Identifier: AGPL-3.0-or-later + +package httpapi + +import ( + "context" + "net/http" + "strconv" + + "docwell/server/internal/access" + "docwell/server/internal/auth" + "docwell/server/internal/directory" +) + +// SharingService is the part of directory.Service for the sharing extras +// (ADR-17): invite links and join requests, page analytics, unused-file +// cleanup and link previews for chat apps. +type SharingService interface { + GetJoinLink(ctx context.Context, c access.Caller, wsID string) (directory.JoinLink, bool, error) + SetJoinLink(ctx context.Context, c access.Caller, wsID string, in directory.SetJoinLinkInput) (directory.JoinLink, error) + DeleteJoinLink(ctx context.Context, c access.Caller, wsID string) error + GetJoinInfo(ctx context.Context, me *auth.User, token string) (directory.JoinInfo, error) + Join(ctx context.Context, me auth.User, token string) (directory.JoinResult, error) + ListJoinRequests(ctx context.Context, c access.Caller, wsID string) ([]directory.JoinRequest, error) + ReviewJoinRequest(ctx context.Context, c access.Caller, wsID, id string, approve bool, role string) error + + GetPageAnalytics(ctx context.Context, c access.Caller, pageID string, days int) (directory.PageAnalytics, error) + + ListUnusedFiles(ctx context.Context, c access.Caller, wsID string) (directory.UnusedFiles, error) + DeleteUnusedFiles(ctx context.Context, c access.Caller, wsID string, ids []string) (int, error) + + GetPagePreview(ctx context.Context, pageID string) (directory.PagePreview, error) + GetSharePreview(ctx context.Context, token, pageID string) (directory.PagePreview, error) +} + +func (a *api) sharingRoutes(mux *routeMux) { + // Invite links (workspace admins). + mux.HandleFunc("GET /api/v1/workspaces/{id}/invite-link", a.requireUser(func(w http.ResponseWriter, r *http.Request) { + link, ok, err := a.dir.GetJoinLink(r.Context(), caller(r), r.PathValue("id")) + if err == nil && !ok { + writeJSON(w, http.StatusNotFound, map[string]string{"error": "not_found", "message": "no invite link"}) + return + } + a.respond(w, link, err) + })) + mux.HandleFunc("PUT /api/v1/workspaces/{id}/invite-link", a.requireUser(func(w http.ResponseWriter, r *http.Request) { + var in directory.SetJoinLinkInput + if !a.decode(w, r, &in) { + return + } + link, err := a.dir.SetJoinLink(r.Context(), caller(r), r.PathValue("id"), in) + a.respond(w, link, err) + })) + mux.HandleFunc("DELETE /api/v1/workspaces/{id}/invite-link", a.requireUser(func(w http.ResponseWriter, r *http.Request) { + a.respondNoContent(w, a.dir.DeleteJoinLink(r.Context(), caller(r), r.PathValue("id"))) + })) + mux.HandleFunc("GET /api/v1/workspaces/{id}/join-requests", a.requireUser(func(w http.ResponseWriter, r *http.Request) { + list, err := a.dir.ListJoinRequests(r.Context(), caller(r), r.PathValue("id")) + a.respond(w, list, err) + })) + mux.HandleFunc("POST /api/v1/workspaces/{id}/join-requests/{requestId}/approve", a.requireUser(func(w http.ResponseWriter, r *http.Request) { + var in struct{ Role string } + if r.ContentLength != 0 && !a.decode(w, r, &in) { + return + } + a.respondNoContent(w, a.dir.ReviewJoinRequest(r.Context(), caller(r), r.PathValue("id"), r.PathValue("requestId"), true, in.Role)) + })) + mux.HandleFunc("POST /api/v1/workspaces/{id}/join-requests/{requestId}/decline", a.requireUser(func(w http.ResponseWriter, r *http.Request) { + a.respondNoContent(w, a.dir.ReviewJoinRequest(r.Context(), caller(r), r.PathValue("id"), r.PathValue("requestId"), false, "")) + })) + + // The /join page: anyone may look; joining needs an account. + mux.HandleFunc("GET /api/v1/auth/join/{token}", func(w http.ResponseWriter, r *http.Request) { + var me *auth.User + if token := auth.BearerToken(r); token != "" { + if u, err := a.auth.Verify(r.Context(), token); err == nil { + me = &u + } + } + info, err := a.dir.GetJoinInfo(r.Context(), me, r.PathValue("token")) + a.respond(w, info, err) + }) + mux.HandleFunc("POST /api/v1/auth/join/{token}", a.requireUser(func(w http.ResponseWriter, r *http.Request) { + me, _ := CurrentUser(r.Context()) + res, err := a.dir.Join(r.Context(), me, r.PathValue("token")) + a.respond(w, res, err) + })) + + mux.HandleFunc("GET /api/v1/pages/{id}/analytics", a.requireUser(func(w http.ResponseWriter, r *http.Request) { + days, _ := strconv.Atoi(r.URL.Query().Get("days")) + out, err := a.dir.GetPageAnalytics(r.Context(), caller(r), r.PathValue("id"), days) + a.respond(w, out, err) + })) + + mux.HandleFunc("GET /api/v1/workspaces/{id}/unused-files", a.requireUser(func(w http.ResponseWriter, r *http.Request) { + out, err := a.dir.ListUnusedFiles(r.Context(), caller(r), r.PathValue("id")) + a.respond(w, out, err) + })) + mux.HandleFunc("POST /api/v1/workspaces/{id}/unused-files/delete", a.requireUser(func(w http.ResponseWriter, r *http.Request) { + var in struct{ IDs []string } + if r.ContentLength != 0 && !a.decode(w, r, &in) { + return + } + n, err := a.dir.DeleteUnusedFiles(r.Context(), caller(r), r.PathValue("id"), in.IDs) + a.respond(w, map[string]int{"deleted": n}, err) + })) + + // Link previews for chat apps, asked by docwell-web: no account, never indexed. + mux.HandleFunc("GET /api/v1/previews/pages/{id}", func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("X-Robots-Tag", "noindex") + out, err := a.dir.GetPagePreview(r.Context(), r.PathValue("id")) + a.respond(w, out, err) + }) + mux.HandleFunc("GET /api/v1/previews/share/{token}", func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("X-Robots-Tag", "noindex") + out, err := a.dir.GetSharePreview(r.Context(), r.PathValue("token"), r.URL.Query().Get("page")) + a.respond(w, out, err) + }) +} diff --git a/Server/internal/pbschema/schema.json b/Server/internal/pbschema/schema.json index 86642b7..8bcbf30 100644 --- a/Server/internal/pbschema/schema.json +++ b/Server/internal/pbschema/schema.json @@ -502,6 +502,26 @@ "required": false, "system": false, "type": "json" + }, + { + "help": "", + "hidden": false, + "id": "bool726373748", + "name": "sharing_off", + "presentable": false, + "required": false, + "system": false, + "type": "bool" + }, + { + "help": "", + "hidden": false, + "id": "bool83261804", + "name": "url_preview", + "presentable": false, + "required": false, + "system": false, + "type": "bool" } ], "id": "pbc_2170078043", @@ -3126,7 +3146,10 @@ "mention", "share", "resolved", - "reminder" + "reminder", + "join_request", + "join_approved", + "join_declined" ] }, { @@ -5779,5 +5802,388 @@ "type": "base", "updateRule": null, "viewRule": null + }, + { + "createRule": null, + "deleteRule": null, + "fields": [ + { + "autogeneratePattern": "[a-z0-9]{15}", + "help": "", + "hidden": false, + "id": "text3208210256", + "max": 15, + "min": 15, + "name": "id", + "pattern": "^[a-z0-9]+$", + "presentable": false, + "primaryKey": true, + "required": true, + "system": true, + "type": "text" + }, + { + "cascadeDelete": true, + "collectionId": "pbc_2170078043", + "help": "", + "hidden": false, + "id": "relation2375286809", + "maxSelect": 1, + "minSelect": 0, + "name": "workspace", + "presentable": false, + "required": true, + "system": false, + "type": "relation" + }, + { + "autogeneratePattern": "", + "help": "", + "hidden": false, + "id": "text1597481275", + "max": 64, + "min": 0, + "name": "token", + "pattern": "", + "presentable": false, + "primaryKey": false, + "required": true, + "system": false, + "type": "text" + }, + { + "help": "", + "hidden": false, + "id": "select1466534506", + "maxSelect": 1, + "name": "role", + "presentable": false, + "required": true, + "system": false, + "type": "select", + "values": [ + "member", + "guest" + ] + }, + { + "help": "", + "hidden": false, + "id": "bool383817003", + "name": "approval", + "presentable": false, + "required": false, + "system": false, + "type": "bool" + }, + { + "cascadeDelete": false, + "collectionId": "_pb_users_auth_", + "help": "", + "hidden": false, + "id": "relation3725765462", + "maxSelect": 1, + "minSelect": 0, + "name": "created_by", + "presentable": false, + "required": false, + "system": false, + "type": "relation" + }, + { + "help": "", + "hidden": false, + "id": "date2593941644", + "max": "", + "min": "", + "name": "expires", + "presentable": false, + "required": false, + "system": false, + "type": "date" + }, + { + "hidden": false, + "id": "autodate2990389176", + "name": "created", + "onCreate": true, + "onUpdate": false, + "presentable": false, + "system": false, + "type": "autodate" + }, + { + "hidden": false, + "id": "autodate3332085495", + "name": "updated", + "onCreate": true, + "onUpdate": true, + "presentable": false, + "system": false, + "type": "autodate" + } + ], + "id": "pbc_2339355617", + "indexes": [ + "CREATE UNIQUE INDEX idx_invite_links_workspace ON invite_links (workspace)", + "CREATE UNIQUE INDEX idx_invite_links_token ON invite_links (token)" + ], + "listRule": null, + "name": "invite_links", + "system": false, + "type": "base", + "updateRule": null, + "viewRule": null + }, + { + "createRule": null, + "deleteRule": null, + "fields": [ + { + "autogeneratePattern": "[a-z0-9]{15}", + "help": "", + "hidden": false, + "id": "text3208210256", + "max": 15, + "min": 15, + "name": "id", + "pattern": "^[a-z0-9]+$", + "presentable": false, + "primaryKey": true, + "required": true, + "system": true, + "type": "text" + }, + { + "cascadeDelete": true, + "collectionId": "pbc_2170078043", + "help": "", + "hidden": false, + "id": "relation2375286809", + "maxSelect": 1, + "minSelect": 0, + "name": "workspace", + "presentable": false, + "required": true, + "system": false, + "type": "relation" + }, + { + "cascadeDelete": true, + "collectionId": "_pb_users_auth_", + "help": "", + "hidden": false, + "id": "relation2375276105", + "maxSelect": 1, + "minSelect": 0, + "name": "user", + "presentable": false, + "required": true, + "system": false, + "type": "relation" + }, + { + "help": "", + "hidden": false, + "id": "select1466534506", + "maxSelect": 1, + "name": "role", + "presentable": false, + "required": true, + "system": false, + "type": "select", + "values": [ + "member", + "guest" + ] + }, + { + "help": "", + "hidden": false, + "id": "select2063623452", + "maxSelect": 1, + "name": "status", + "presentable": false, + "required": true, + "system": false, + "type": "select", + "values": [ + "pending", + "approved", + "declined" + ] + }, + { + "cascadeDelete": false, + "collectionId": "_pb_users_auth_", + "help": "", + "hidden": false, + "id": "relation2245524295", + "maxSelect": 1, + "minSelect": 0, + "name": "reviewed_by", + "presentable": false, + "required": false, + "system": false, + "type": "relation" + }, + { + "help": "", + "hidden": false, + "id": "date3494630457", + "max": "", + "min": "", + "name": "reviewed_at", + "presentable": false, + "required": false, + "system": false, + "type": "date" + }, + { + "hidden": false, + "id": "autodate2990389176", + "name": "created", + "onCreate": true, + "onUpdate": false, + "presentable": false, + "system": false, + "type": "autodate" + }, + { + "hidden": false, + "id": "autodate3332085495", + "name": "updated", + "onCreate": true, + "onUpdate": true, + "presentable": false, + "system": false, + "type": "autodate" + } + ], + "id": "pbc_2936470090", + "indexes": [ + "CREATE UNIQUE INDEX idx_invite_requests_user ON invite_requests (workspace, user)", + "CREATE INDEX idx_invite_requests_status ON invite_requests (workspace, status)" + ], + "listRule": null, + "name": "invite_requests", + "system": false, + "type": "base", + "updateRule": null, + "viewRule": null + }, + { + "createRule": null, + "deleteRule": null, + "fields": [ + { + "autogeneratePattern": "[a-z0-9]{15}", + "help": "", + "hidden": false, + "id": "text3208210256", + "max": 15, + "min": 15, + "name": "id", + "pattern": "^[a-z0-9]+$", + "presentable": false, + "primaryKey": true, + "required": true, + "system": true, + "type": "text" + }, + { + "cascadeDelete": true, + "collectionId": "pbc_3945946014", + "help": "", + "hidden": false, + "id": "relation336246304", + "maxSelect": 1, + "minSelect": 0, + "name": "page", + "presentable": false, + "required": true, + "system": false, + "type": "relation" + }, + { + "cascadeDelete": true, + "collectionId": "pbc_2170078043", + "help": "", + "hidden": false, + "id": "relation2375286809", + "maxSelect": 1, + "minSelect": 0, + "name": "workspace", + "presentable": false, + "required": true, + "system": false, + "type": "relation" + }, + { + "cascadeDelete": true, + "collectionId": "_pb_users_auth_", + "help": "", + "hidden": false, + "id": "relation2375276105", + "maxSelect": 1, + "minSelect": 0, + "name": "user", + "presentable": false, + "required": false, + "system": false, + "type": "relation" + }, + { + "autogeneratePattern": "", + "help": "", + "hidden": false, + "id": "text3852478864", + "max": 10, + "min": 0, + "name": "day", + "pattern": "", + "presentable": false, + "primaryKey": false, + "required": true, + "system": false, + "type": "text" + }, + { + "help": "", + "hidden": false, + "id": "number300981383", + "max": null, + "min": 0, + "name": "views", + "onlyInt": true, + "presentable": false, + "required": false, + "system": false, + "type": "number" + }, + { + "help": "", + "hidden": false, + "id": "date1255909792", + "max": "", + "min": "", + "name": "last", + "presentable": false, + "required": false, + "system": false, + "type": "date" + } + ], + "id": "pbc_2311148481", + "indexes": [ + "CREATE UNIQUE INDEX idx_page_views_key ON page_views (page, user, day)", + "CREATE INDEX idx_page_views_day ON page_views (day)" + ], + "listRule": null, + "name": "page_views", + "system": false, + "type": "base", + "updateRule": null, + "viewRule": null } ] diff --git a/Web-App/cmd/docwell-web/main.go b/Web-App/cmd/docwell-web/main.go index 7bacbf0..81d66a9 100644 --- a/Web-App/cmd/docwell-web/main.go +++ b/Web-App/cmd/docwell-web/main.go @@ -54,6 +54,15 @@ func run(log *slog.Logger) error { opts.Config.APIURL = "" opts.Config.CollabURL = "" } + // Link previews for chat apps ask docwell-server directly: through + // DOCWELL_PREVIEW_API_URL, else the proxy target, else the public API URL. + previewAPI := env("DOCWELL_PREVIEW_API_URL", os.Getenv("DOCWELL_PROXY_TARGET")) + if previewAPI == "" { + previewAPI = env("DOCWELL_API_URL", "http://localhost:8080") + } + if u, err := url.Parse(previewAPI); err == nil && (u.Scheme == "http" || u.Scheme == "https") { + opts.PreviewAPI = u + } srv := &http.Server{Addr: addr, Handler: spa.Handler(opts), ReadHeaderTimeout: 10 * time.Second} diff --git a/Web-App/frontend/src/components/PageAnalytics.vue b/Web-App/frontend/src/components/PageAnalytics.vue new file mode 100644 index 0000000..241f31e --- /dev/null +++ b/Web-App/frontend/src/components/PageAnalytics.vue @@ -0,0 +1,91 @@ + + + + diff --git a/Web-App/frontend/src/components/ShareDialog.vue b/Web-App/frontend/src/components/ShareDialog.vue index 0a313a5..6ea0ab8 100644 --- a/Web-App/frontend/src/components/ShareDialog.vue +++ b/Web-App/frontend/src/components/ShareDialog.vue @@ -17,6 +17,7 @@ import { computed, nextTick, ref, watch } from "vue"; import { useApi } from "../api"; import { useFormErrors } from "../composables/useFormErrors"; import { spaceAtLeast } from "../stores/spaces"; +import { useWorkspacesStore } from "../stores/workspaces"; // Who can open a page, and its public link. The space gives the baseline // (changed in the space settings); the page adds people and groups, and can @@ -47,6 +48,9 @@ const whoRole = ref("viewer"); const canEdit = computed(() => spaceAtLeast(props.page.role, "editor") && !props.page.inTrash); const canManage = computed(() => !!pageAccess.value?.canManage && !props.page.inTrash); +const workspaces = useWorkspacesStore(); +// A workspace admin turned public links off for the whole workspace. +const sharingOff = computed(() => workspaces.items.find((w) => w.id === props.page.workspace)?.allowSharing === false); const pageUrl = computed(() => `${location.origin}/p/${props.page.id}`); const ownGrants = computed(() => pageAccess.value?.grants.filter((g) => !g.inherited) ?? []); const inheritedGrants = computed(() => pageAccess.value?.grants.filter((g) => g.inherited) ?? []); @@ -395,7 +399,10 @@ async function copy(which: string, text: string) {

{{ $t("share.public") }}

-