Add invite links with approval, sharing switches, page views and unused-file cleanup
CI / go (Media) (push) Successful in 14m33s
CI / go (Server) (push) Failing after 23m30s
CI / go (Web-App) (push) Canceled after 0s
CI / frontend (push) Failing after 9m30s
CI / desktop (ubuntu-latest) (push) Successful in 1h21m24s
CI / mobile (push) Failing after 4m16s
CI / docker (push) Successful in 1h1m25s
Docs / build (push) Successful in 14m59s
Docs / deploy (push) Skipped
CI / desktop (macos-latest) (push) Canceled after 0s
CI / desktop (windows-latest) (push) Canceled after 0s
CI / go (Media) (push) Successful in 14m33s
CI / go (Server) (push) Failing after 23m30s
CI / go (Web-App) (push) Canceled after 0s
CI / frontend (push) Failing after 9m30s
CI / desktop (ubuntu-latest) (push) Successful in 1h21m24s
CI / mobile (push) Failing after 4m16s
CI / docker (push) Successful in 1h1m25s
Docs / build (push) Successful in 14m59s
Docs / deploy (push) Skipped
CI / desktop (macos-latest) (push) Canceled after 0s
CI / desktop (windows-latest) (push) Canceled after 0s
Phase G of docs/AFFINE.md (ADR-17): - Invite links: one per workspace (member or guest, optional end date, optional admin approval) on a new /join page. Requests are approved (optionally as another role) or declined from workspace settings; join_request, join_approved and join_declined notifications reach the inbox, phones and the email digest. Workspace admins decide, else the organization's admins, else superadmins. Signup honours ?redirect=. - Workspace switches: allowSharing (off makes every share link answer 404 until it is back on) and urlPreview (chat apps may show private pages' titles). docwell-web writes title and Open Graph tags for known link-preview bots, asking docwell-server via DOCWELL_PREVIEW_API_URL; search engines are left out. - Page analytics: page_views counts opens per page, person and day from the existing visit call and share-link reads; editors see totals, a daily chart and recent viewers in the Info panel. analytics.prune drops rows after 400 days. - Unused files: attachments whose id appears in no page's Yjs state, page icon or comment (older than a day) are listed and deleted from workspace settings. - Migration, schema snapshot, OpenAPI, generated clients, translations in five languages, phone inbox, compose files and user docs. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
6984c7d162
commit
9d674e9699
51 files changed
+4963
-48
No files matched your search
@@ -0,0 +1,118 @@
|
||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
/// <reference path="../pb_data/types.d.ts" />
|
||||
|
||||
// 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);
|
||||
},
|
||||
);
|
||||
@@ -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"
|
||||
|
||||
@@ -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"
|
||||
|
||||
@@ -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"
|
||||
|
||||
@@ -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"
|
||||
|
||||
@@ -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"
|
||||
|
||||
|
||||
@@ -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
|
||||
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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<Session>("/api/v1/auth/otp/login", { otpId, code, mfaId }),
|
||||
refresh: () => request<Session>("POST", "/api/v1/auth/refresh"),
|
||||
me: () => request<User>("GET", "/api/v1/auth/me"),
|
||||
/** Describes a workspace invite link; status is filled in when signed in. */
|
||||
joinInfo: (token: string) => request<JoinInfo>("GET", `/api/v1/auth/join/${enc(token)}`),
|
||||
/** Joins through an invite link, or asks to when it needs approval. */
|
||||
join: (token: string) => post<JoinResult>(`/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<Workspace>("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<Workspace>("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<InviteLink>("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<InviteLink>("PUT", `/api/v1/workspaces/${enc(id)}/invite-link`, input),
|
||||
deleteInviteLink: (id: string) => request<void>("DELETE", `/api/v1/workspaces/${enc(id)}/invite-link`),
|
||||
joinRequests: (id: string) => request<JoinRequest[]>("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<UnusedFiles>("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<void>("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<Page>("GET", `/api/v1/pages/${encodeURIComponent(id)}`),
|
||||
/** How often and by whom the page was opened (editor). */
|
||||
analytics: (id: string, days?: number) =>
|
||||
request<PageAnalytics>("GET", `/api/v1/pages/${enc(id)}/analytics${query({ days })}`),
|
||||
update: (
|
||||
id: string,
|
||||
patch: {
|
||||
|
||||
Vendored
+653
-3
@@ -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?: {
|
||||
|
||||
@@ -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;
|
||||
@@ -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<String, dynamic> 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<String, dynamic> 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<String, dynamic> 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<String, dynamic> 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<String, dynamic> json) => JoinRequest(
|
||||
id: json['id'] as String,
|
||||
user: MemberUser.fromJson(json['user'] as Map<String, dynamic>),
|
||||
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<String, dynamic> 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<String, dynamic> 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<String, dynamic> 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<String, dynamic> json) => JoinResult(
|
||||
status: JoinResultStatus.fromJson(json['status'] as String),
|
||||
workspace: json['workspace'] as String,
|
||||
);
|
||||
|
||||
final JoinResultStatus status;
|
||||
|
||||
final String workspace;
|
||||
|
||||
Map<String, dynamic> 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<String, dynamic> 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<String, dynamic>))
|
||||
.toList(),
|
||||
recent: (json['recent'] as List)
|
||||
.map((e) => PageViewer.fromJson(e as Map<String, dynamic>))
|
||||
.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<AnalyticsDay> daily;
|
||||
|
||||
/// Who opened the page, most recent first (at most 20)
|
||||
final List<PageViewer> recent;
|
||||
|
||||
Map<String, dynamic> 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<String, dynamic> 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<String, dynamic> toJson() => {
|
||||
'date': date,
|
||||
'views': views,
|
||||
'viewers': viewers,
|
||||
};
|
||||
}
|
||||
|
||||
class PageViewer {
|
||||
const PageViewer({
|
||||
required this.user,
|
||||
required this.views,
|
||||
required this.lastViewed,
|
||||
});
|
||||
|
||||
factory PageViewer.fromJson(Map<String, dynamic> json) => PageViewer(
|
||||
user: MemberUser.fromJson(json['user'] as Map<String, dynamic>),
|
||||
views: (json['views'] as num).toInt(),
|
||||
lastViewed: json['lastViewed'] as String,
|
||||
);
|
||||
|
||||
final MemberUser user;
|
||||
|
||||
final int views;
|
||||
|
||||
final String lastViewed;
|
||||
|
||||
Map<String, dynamic> 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<String, dynamic> 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<String, dynamic> 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<String, dynamic> json) => UnusedFiles(
|
||||
files: (json['files'] as List)
|
||||
.map((e) => UnusedFile.fromJson(e as Map<String, dynamic>))
|
||||
.toList(),
|
||||
size: (json['size'] as num).toInt(),
|
||||
);
|
||||
|
||||
final List<UnusedFile> files;
|
||||
|
||||
/// Total bytes
|
||||
final int size;
|
||||
|
||||
Map<String, dynamic> 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<String, dynamic> 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<String, dynamic> toJson() => {
|
||||
'title': title,
|
||||
'description': description,
|
||||
'site': site,
|
||||
};
|
||||
}
|
||||
|
||||
/// Set when the hit is a database record; open it with the page link plus "#r-`<database>`-`<row>`"
|
||||
class SearchHitRecord {
|
||||
const SearchHitRecord({
|
||||
@@ -3150,13 +3585,17 @@ class WatchState {
|
||||
Map<String, dynamic> 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;
|
||||
|
||||
@@ -141,6 +141,9 @@ const appStrings = <String, Map<String, String>>{
|
||||
'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 = <String, Map<String, String>>{
|
||||
'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 = <String, Map<String, String>>{
|
||||
'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 = <String, Map<String, String>>{
|
||||
'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 = <String, Map<String, String>>{
|
||||
'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',
|
||||
|
||||
@@ -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<NotificationsScreen> {
|
||||
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,
|
||||
|
||||
@@ -40,6 +40,8 @@ const workspace = {
|
||||
'role': 'owner',
|
||||
'created': '2026-10-01 09:00:00.000Z',
|
||||
'defaultPageMode': 'page',
|
||||
'allowSharing': true,
|
||||
'urlPreview': false,
|
||||
};
|
||||
|
||||
const space = {
|
||||
|
||||
@@ -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)
|
||||
|
||||
+321
-10
@@ -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
|
||||
|
||||
|
||||
@@ -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
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
|
||||
|
||||
@@ -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",
|
||||
})
|
||||
|
||||
@@ -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})
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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.
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
|
||||
@@ -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
|
||||
}
|
||||
@@ -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),
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -47,6 +47,7 @@ type DirectoryService interface {
|
||||
WebhookService
|
||||
CommentService
|
||||
OrganizeService
|
||||
SharingService
|
||||
}
|
||||
|
||||
func caller(r *http.Request) access.Caller {
|
||||
|
||||
@@ -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)
|
||||
})
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
]
|
||||
@@ -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}
|
||||
|
||||
|
||||
@@ -0,0 +1,91 @@
|
||||
<!-- SPDX-License-Identifier: AGPL-3.0-or-later -->
|
||||
<script setup lang="ts">
|
||||
import type { PageAnalytics } from "@docwell/api-client";
|
||||
import { computed, ref, watch } from "vue";
|
||||
import { useI18n } from "vue-i18n";
|
||||
import { useApi } from "../api";
|
||||
|
||||
// How often a page was opened and by whom, for its editors (Info panel).
|
||||
const props = defineProps<{ page: string }>();
|
||||
const api = useApi();
|
||||
const { locale } = useI18n();
|
||||
|
||||
const days = ref(30);
|
||||
const data = ref<PageAnalytics | null>(null);
|
||||
const failed = ref(false);
|
||||
|
||||
async function load() {
|
||||
failed.value = false;
|
||||
try {
|
||||
data.value = await api.pages.analytics(props.page, days.value);
|
||||
} catch {
|
||||
failed.value = true;
|
||||
}
|
||||
}
|
||||
watch([() => props.page, days], load, { immediate: true });
|
||||
|
||||
const peak = computed(() => Math.max(1, ...(data.value?.daily.map((d) => d.views) ?? [1])));
|
||||
const dayLabel = (d: string) =>
|
||||
new Date(`${d}T00:00:00Z`).toLocaleDateString(locale.value, { day: "numeric", month: "short", timeZone: "UTC" });
|
||||
const when = (s: string) =>
|
||||
new Date(s.replace(" ", "T")).toLocaleString(locale.value, { dateStyle: "medium", timeStyle: "short" });
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<section data-testid="page-analytics">
|
||||
<div class="flex items-center justify-between gap-2">
|
||||
<h3 class="dw-label">{{ $t("analytics.title") }}</h3>
|
||||
<select v-model.number="days" class="dw-input h-7 text-ui-sm" :aria-label="$t('analytics.period')">
|
||||
<option :value="7">{{ $t("analytics.lastDays", 7) }}</option>
|
||||
<option :value="30">{{ $t("analytics.lastDays", 30) }}</option>
|
||||
<option :value="90">{{ $t("analytics.lastDays", 90) }}</option>
|
||||
</select>
|
||||
</div>
|
||||
<p v-if="failed" class="mt-2 text-ui-sm text-ink-muted">{{ $t("analytics.failed") }}</p>
|
||||
<template v-else-if="data">
|
||||
<dl class="mt-2 grid grid-cols-3 gap-2 text-center">
|
||||
<div class="rounded-sm bg-surface-sunken px-2 py-1.5">
|
||||
<dt class="text-ui-xs text-ink-muted">{{ $t("analytics.views") }}</dt>
|
||||
<dd class="text-ui-lg font-semibold tabular-nums" data-testid="analytics-views">{{ data.views }}</dd>
|
||||
</div>
|
||||
<div class="rounded-sm bg-surface-sunken px-2 py-1.5">
|
||||
<dt class="text-ui-xs text-ink-muted">{{ $t("analytics.viewers") }}</dt>
|
||||
<dd class="text-ui-lg font-semibold tabular-nums" data-testid="analytics-viewers">{{ data.viewers }}</dd>
|
||||
</div>
|
||||
<div class="rounded-sm bg-surface-sunken px-2 py-1.5">
|
||||
<dt class="text-ui-xs text-ink-muted">{{ $t("analytics.linkViews") }}</dt>
|
||||
<dd class="text-ui-lg font-semibold tabular-nums">{{ data.linkViews }}</dd>
|
||||
</div>
|
||||
</dl>
|
||||
<!-- One bar per day; the numbers are in each bar's tooltip and in the list below. -->
|
||||
<div
|
||||
class="mt-3 flex h-12 items-end gap-px"
|
||||
role="img"
|
||||
:aria-label="$t('analytics.chart', { n: data.views, days: data.days }, data.views)"
|
||||
>
|
||||
<span
|
||||
v-for="d in data.daily"
|
||||
:key="d.date"
|
||||
class="min-h-px flex-1 rounded-t-[2px]"
|
||||
:class="d.views ? 'bg-primary' : 'bg-line'"
|
||||
:style="{ height: `${Math.max(4, (d.views / peak) * 100)}%` }"
|
||||
:title="$t('analytics.day', { date: dayLabel(d.date), n: d.views }, d.views)"
|
||||
/>
|
||||
</div>
|
||||
<div class="mt-0.5 flex justify-between text-ui-xs text-ink-faint">
|
||||
<span>{{ dayLabel(data.daily[0]!.date) }}</span>
|
||||
<span>{{ dayLabel(data.daily[data.daily.length - 1]!.date) }}</span>
|
||||
</div>
|
||||
<h4 class="mt-3 text-ui-sm font-semibold">{{ $t("analytics.recent") }}</h4>
|
||||
<ul v-if="data.recent.length" class="mt-1 space-y-1" data-testid="analytics-recent">
|
||||
<li v-for="v in data.recent" :key="v.user.id" class="flex items-baseline justify-between gap-2 text-ui-sm">
|
||||
<span class="min-w-0 truncate">{{ v.user.name || v.user.email }}</span>
|
||||
<span class="shrink-0 text-ink-muted" :title="$t('analytics.timesOpened', v.views)">{{
|
||||
when(v.lastViewed)
|
||||
}}</span>
|
||||
</li>
|
||||
</ul>
|
||||
<p v-else class="mt-1 text-ui-sm text-ink-muted">{{ $t("analytics.nobody") }}</p>
|
||||
</template>
|
||||
</section>
|
||||
</template>
|
||||
@@ -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<PageGrantRole>("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) {
|
||||
|
||||
<section class="mt-6 border-t border-line pt-4">
|
||||
<h3 class="dw-label">{{ $t("share.public") }}</h3>
|
||||
<label class="mt-2 flex items-start gap-3 text-ui-md">
|
||||
<p v-if="sharingOff" class="mt-2 text-ui-sm text-ink-muted" data-testid="share-public-off">
|
||||
{{ $t("share.workspaceOff") }}
|
||||
</p>
|
||||
<label v-else class="mt-2 flex items-start gap-3 text-ui-md">
|
||||
<input
|
||||
type="checkbox"
|
||||
class="mt-1 accent-primary"
|
||||
@@ -409,7 +416,7 @@ async function copy(which: string, text: string) {
|
||||
<span class="block text-ui-sm text-ink-muted">{{ $t("share.publicHint") }}</span>
|
||||
</span>
|
||||
</label>
|
||||
<template v-if="link">
|
||||
<template v-if="link && !sharingOff">
|
||||
<label class="mt-3 flex items-center gap-3 text-ui-md">
|
||||
<input
|
||||
type="checkbox"
|
||||
@@ -433,7 +440,7 @@ async function copy(which: string, text: string) {
|
||||
</DwButton>
|
||||
</div>
|
||||
</template>
|
||||
<p v-if="!canEdit" class="mt-2 text-ui-sm text-ink-muted">{{ $t("share.editorsOnly") }}</p>
|
||||
<p v-if="!canEdit && !sharingOff" class="mt-2 text-ui-sm text-ink-muted">{{ $t("share.editorsOnly") }}</p>
|
||||
</section>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -0,0 +1,134 @@
|
||||
<!-- SPDX-License-Identifier: AGPL-3.0-or-later -->
|
||||
<script setup lang="ts">
|
||||
import type { UnusedFiles } from "@docwell/api-client";
|
||||
import { DwButton, DwCallout } from "@docwell/ui";
|
||||
import { computed, ref } from "vue";
|
||||
import { useI18n } from "vue-i18n";
|
||||
import { useApi } from "../api";
|
||||
import { useFormErrors } from "../composables/useFormErrors";
|
||||
|
||||
// Workspace admins: files that no page uses any more, to free their space.
|
||||
// Looking takes a while on big workspaces (every page is read), so it only
|
||||
// happens when asked.
|
||||
const props = defineProps<{ workspace: string }>();
|
||||
const api = useApi();
|
||||
const { t, locale } = useI18n();
|
||||
const errors = useFormErrors();
|
||||
|
||||
const result = ref<UnusedFiles | null>(null);
|
||||
const picked = ref<string[]>([]);
|
||||
const busy = ref(false);
|
||||
const deleted = ref<number | null>(null);
|
||||
|
||||
const size = (n: number) => {
|
||||
const units = ["B", "KB", "MB", "GB"];
|
||||
let i = 0;
|
||||
while (n >= 1024 && i < units.length - 1) {
|
||||
n /= 1024;
|
||||
i++;
|
||||
}
|
||||
return `${new Intl.NumberFormat(locale.value, { maximumFractionDigits: i ? 1 : 0 }).format(n)} ${units[i]}`;
|
||||
};
|
||||
const pickedSize = computed(() =>
|
||||
(result.value?.files ?? []).filter((f) => picked.value.includes(f.id)).reduce((s, f) => s + f.size, 0),
|
||||
);
|
||||
const allPicked = computed(() => !!result.value?.files.length && picked.value.length === result.value.files.length);
|
||||
|
||||
async function run(action: () => Promise<unknown>) {
|
||||
busy.value = true;
|
||||
errors.reset();
|
||||
try {
|
||||
await action();
|
||||
} catch (e) {
|
||||
errors.show(e);
|
||||
} finally {
|
||||
busy.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
const find = () =>
|
||||
run(async () => {
|
||||
deleted.value = null;
|
||||
result.value = await api.workspaces.unusedFiles(props.workspace);
|
||||
picked.value = result.value.files.map((f) => f.id);
|
||||
});
|
||||
|
||||
function remove() {
|
||||
if (
|
||||
!picked.value.length ||
|
||||
!confirm(t("files.confirmDelete", { n: picked.value.length, size: size(pickedSize.value) }, picked.value.length))
|
||||
)
|
||||
return;
|
||||
void run(async () => {
|
||||
const res = await api.workspaces.deleteUnusedFiles(props.workspace, picked.value);
|
||||
deleted.value = res.deleted;
|
||||
result.value = await api.workspaces.unusedFiles(props.workspace);
|
||||
picked.value = [];
|
||||
});
|
||||
}
|
||||
|
||||
const toggleAll = (on: boolean) => (picked.value = on ? (result.value?.files.map((f) => f.id) ?? []) : []);
|
||||
const day = (s: string) => new Date(s.replace(" ", "T")).toLocaleDateString(locale.value, { dateStyle: "medium" });
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<section class="dw-card" data-testid="workspace-files">
|
||||
<h2 class="text-ui-lg">{{ $t("files.title") }}</h2>
|
||||
<p class="mt-1 text-ui-sm text-ink-muted">{{ $t("files.hint") }}</p>
|
||||
<DwCallout v-if="errors.message.value" tone="danger" size="ui" class="mt-3">{{ errors.message.value }}</DwCallout>
|
||||
<DwCallout v-if="deleted !== null" tone="success" size="ui" class="mt-3">{{
|
||||
$t("files.deleted", deleted)
|
||||
}}</DwCallout>
|
||||
|
||||
<DwButton v-if="!result" icon="search" class="mt-3" :disabled="busy" data-testid="find-unused" @click="find">
|
||||
{{ $t(busy ? "files.looking" : "files.find") }}
|
||||
</DwButton>
|
||||
|
||||
<template v-else>
|
||||
<p v-if="!result.files.length" class="mt-3 text-ui-md text-ink-muted" data-testid="no-unused">
|
||||
{{ $t("files.none") }}
|
||||
</p>
|
||||
<template v-else>
|
||||
<div class="mt-3 flex flex-wrap items-center justify-between gap-2">
|
||||
<label class="flex items-center gap-2 text-ui-md">
|
||||
<input
|
||||
type="checkbox"
|
||||
class="accent-primary"
|
||||
:checked="allPicked"
|
||||
@change="toggleAll(($event.target as HTMLInputElement).checked)"
|
||||
/>
|
||||
{{ $t("files.summary", { n: result.files.length, size: size(result.size) }, result.files.length) }}
|
||||
</label>
|
||||
<DwButton
|
||||
variant="secondary"
|
||||
icon="trash"
|
||||
class="!text-danger"
|
||||
:disabled="busy || !picked.length"
|
||||
data-testid="delete-unused"
|
||||
@click="remove"
|
||||
>
|
||||
{{ $t("files.delete", { n: picked.length, size: size(pickedSize) }) }}
|
||||
</DwButton>
|
||||
</div>
|
||||
<ul class="mt-2 max-h-80 divide-y divide-line overflow-y-auto">
|
||||
<li
|
||||
v-for="f in result.files"
|
||||
:key="f.id"
|
||||
class="flex items-center gap-3 py-2 text-ui-md"
|
||||
data-testid="unused-file"
|
||||
>
|
||||
<input v-model="picked" type="checkbox" :value="f.id" class="accent-primary" :aria-label="f.name" />
|
||||
<span class="min-w-0 flex-1">
|
||||
<span class="block truncate font-medium">{{ f.name }}</span>
|
||||
<span class="block truncate text-ui-sm text-ink-muted">
|
||||
{{ size(f.size) }} · {{ day(f.created) }}
|
||||
<template v-if="f.pageTitle"> · {{ $t("files.from", { page: f.pageTitle }) }}</template>
|
||||
</span>
|
||||
</span>
|
||||
</li>
|
||||
</ul>
|
||||
</template>
|
||||
<button class="dw-link mt-3 text-ui-sm" :disabled="busy" @click="find">{{ $t("files.again") }}</button>
|
||||
</template>
|
||||
</section>
|
||||
</template>
|
||||
@@ -0,0 +1,249 @@
|
||||
<!-- SPDX-License-Identifier: AGPL-3.0-or-later -->
|
||||
<script setup lang="ts">
|
||||
import type { InviteLink, JoinRequest, Workspace, WorkspaceRole } from "@docwell/api-client";
|
||||
import { DwButton, DwCallout } from "@docwell/ui";
|
||||
import { computed, onMounted, ref } from "vue";
|
||||
import { useI18n } from "vue-i18n";
|
||||
import { useApi } from "../api";
|
||||
import { useFormErrors } from "../composables/useFormErrors";
|
||||
import { grantableRoles } from "../stores/workspaces";
|
||||
|
||||
// Workspace admins: the public-sharing switches, the invite link and the
|
||||
// requests to join that it collects.
|
||||
const props = defineProps<{ workspace: Workspace }>();
|
||||
const emit = defineEmits<{ changed: [] }>();
|
||||
const api = useApi();
|
||||
const { t, locale } = useI18n();
|
||||
const errors = useFormErrors();
|
||||
|
||||
const link = ref<InviteLink | null>(null);
|
||||
const requests = ref<JoinRequest[]>([]);
|
||||
const loaded = ref(false);
|
||||
const busy = ref(false);
|
||||
const copied = ref(false);
|
||||
// What a new link starts with, and what an existing one is changed to.
|
||||
const role = ref<"member" | "guest">("member");
|
||||
const approval = ref(true);
|
||||
const expires = ref(7);
|
||||
|
||||
const roles = computed(() => grantableRoles(props.workspace.role));
|
||||
|
||||
async function load() {
|
||||
link.value = await api.workspaces.inviteLink(props.workspace.id);
|
||||
requests.value = await api.workspaces.joinRequests(props.workspace.id);
|
||||
if (link.value) {
|
||||
role.value = link.value.role;
|
||||
approval.value = link.value.approval;
|
||||
if (!link.value.expires) expires.value = 0;
|
||||
}
|
||||
loaded.value = true;
|
||||
}
|
||||
onMounted(() => load().catch(errors.show));
|
||||
|
||||
async function run(action: () => Promise<unknown>, after?: () => void) {
|
||||
busy.value = true;
|
||||
errors.reset();
|
||||
try {
|
||||
await action();
|
||||
after?.();
|
||||
await load();
|
||||
} catch (e) {
|
||||
errors.show(e);
|
||||
} finally {
|
||||
busy.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
const setSwitch = (patch: { allowSharing?: boolean; urlPreview?: boolean }) =>
|
||||
run(
|
||||
() => api.workspaces.setSharing(props.workspace.id, patch),
|
||||
() => emit("changed"),
|
||||
);
|
||||
|
||||
const save = (reset = false) =>
|
||||
run(() =>
|
||||
api.workspaces.setInviteLink(props.workspace.id, {
|
||||
role: role.value,
|
||||
approval: approval.value,
|
||||
expiresInDays: expires.value,
|
||||
reset,
|
||||
}),
|
||||
);
|
||||
const changeLink = () =>
|
||||
run(() =>
|
||||
api.workspaces.setInviteLink(props.workspace.id, {
|
||||
role: role.value,
|
||||
approval: approval.value,
|
||||
expiresInDays: expires.value,
|
||||
}),
|
||||
);
|
||||
function turnOff() {
|
||||
if (!confirm(t("sharing.confirmOff"))) return;
|
||||
void run(() => api.workspaces.deleteInviteLink(props.workspace.id));
|
||||
}
|
||||
function reset() {
|
||||
if (!confirm(t("sharing.confirmReset"))) return;
|
||||
void save(true);
|
||||
}
|
||||
|
||||
async function copy() {
|
||||
if (!link.value) return;
|
||||
await navigator.clipboard.writeText(link.value.url);
|
||||
copied.value = true;
|
||||
setTimeout(() => (copied.value = false), 2000);
|
||||
}
|
||||
|
||||
const approve = (r: JoinRequest, as?: WorkspaceRole) =>
|
||||
run(
|
||||
() => api.workspaces.approveJoin(props.workspace.id, r.id, as),
|
||||
() => emit("changed"),
|
||||
);
|
||||
const decline = (r: JoinRequest) => run(() => api.workspaces.declineJoin(props.workspace.id, r.id));
|
||||
|
||||
const day = (s: string) => new Date(s.replace(" ", "T")).toLocaleDateString(locale.value, { dateStyle: "medium" });
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<section class="dw-card" data-testid="workspace-sharing">
|
||||
<h2 class="text-ui-lg">{{ $t("sharing.title") }}</h2>
|
||||
<DwCallout v-if="errors.message.value" tone="danger" size="ui" class="mt-3">{{ errors.message.value }}</DwCallout>
|
||||
|
||||
<label class="mt-4 flex items-start gap-3 text-ui-md">
|
||||
<input
|
||||
type="checkbox"
|
||||
class="mt-1 accent-primary"
|
||||
:checked="workspace.allowSharing"
|
||||
:disabled="busy"
|
||||
data-testid="allow-sharing"
|
||||
@change="setSwitch({ allowSharing: ($event.target as HTMLInputElement).checked })"
|
||||
/>
|
||||
<span>
|
||||
<span class="font-medium">{{ $t("sharing.allowSharing") }}</span>
|
||||
<span class="block text-ui-sm text-ink-muted">{{ $t("sharing.allowSharingHint") }}</span>
|
||||
</span>
|
||||
</label>
|
||||
<label class="mt-3 flex items-start gap-3 text-ui-md">
|
||||
<input
|
||||
type="checkbox"
|
||||
class="mt-1 accent-primary"
|
||||
:checked="workspace.urlPreview"
|
||||
:disabled="busy"
|
||||
data-testid="url-preview"
|
||||
@change="setSwitch({ urlPreview: ($event.target as HTMLInputElement).checked })"
|
||||
/>
|
||||
<span>
|
||||
<span class="font-medium">{{ $t("sharing.urlPreview") }}</span>
|
||||
<span class="block text-ui-sm text-ink-muted">{{ $t("sharing.urlPreviewHint") }}</span>
|
||||
</span>
|
||||
</label>
|
||||
|
||||
<h3 class="mt-6 text-ui-md font-semibold">{{ $t("sharing.inviteLink") }}</h3>
|
||||
<p class="mt-1 text-ui-sm text-ink-muted">{{ $t("sharing.inviteLinkHint") }}</p>
|
||||
|
||||
<div v-if="loaded" class="mt-3 flex flex-wrap items-end gap-3 text-ui-md">
|
||||
<label class="flex flex-col gap-1">
|
||||
<span class="text-ui-sm text-ink-muted">{{ $t("workspace.role") }}</span>
|
||||
<select v-model="role" class="dw-input" :disabled="busy" data-testid="invite-link-role">
|
||||
<option value="member">{{ $t("workspace.roles.member") }}</option>
|
||||
<option value="guest">{{ $t("workspace.roles.guest") }}</option>
|
||||
</select>
|
||||
</label>
|
||||
<label class="flex flex-col gap-1">
|
||||
<span class="text-ui-sm text-ink-muted">{{ $t("sharing.expires") }}</span>
|
||||
<select v-model.number="expires" class="dw-input" :disabled="busy" data-testid="invite-link-expires">
|
||||
<option :value="1">{{ $t("sharing.days", 1) }}</option>
|
||||
<option :value="7">{{ $t("sharing.days", 7) }}</option>
|
||||
<option :value="30">{{ $t("sharing.days", 30) }}</option>
|
||||
<option :value="0">{{ $t("sharing.never") }}</option>
|
||||
</select>
|
||||
</label>
|
||||
<label class="flex h-control-md items-center gap-2">
|
||||
<input
|
||||
v-model="approval"
|
||||
type="checkbox"
|
||||
class="accent-primary"
|
||||
:disabled="busy"
|
||||
data-testid="invite-link-approval"
|
||||
/>
|
||||
{{ $t("sharing.approval") }}
|
||||
</label>
|
||||
<DwButton
|
||||
v-if="!link"
|
||||
variant="primary"
|
||||
icon="link"
|
||||
:disabled="busy"
|
||||
data-testid="invite-link-create"
|
||||
@click="save()"
|
||||
>
|
||||
{{ $t("sharing.createLink") }}
|
||||
</DwButton>
|
||||
<DwButton v-else :disabled="busy" data-testid="invite-link-save" @click="changeLink">{{
|
||||
$t("common.save")
|
||||
}}</DwButton>
|
||||
</div>
|
||||
|
||||
<div v-if="link" class="mt-3 space-y-2" data-testid="invite-link">
|
||||
<div class="flex flex-wrap items-center gap-2">
|
||||
<input
|
||||
:value="link.url"
|
||||
readonly
|
||||
class="dw-input min-w-48 flex-1 font-mono text-ui-sm"
|
||||
:aria-label="$t('sharing.inviteLink')"
|
||||
@focus="($event.target as HTMLInputElement).select()"
|
||||
/>
|
||||
<DwButton icon="copy" @click="copy">{{ copied ? $t("workspace.copied") : $t("workspace.copyLink") }}</DwButton>
|
||||
</div>
|
||||
<p class="text-ui-sm text-ink-muted">
|
||||
{{ $t(`workspace.roles.${link.role}`) }} ·
|
||||
{{ link.approval ? $t("sharing.needsApproval") : $t("sharing.joinsDirectly") }} ·
|
||||
{{ link.expires ? $t("sharing.until", { date: day(link.expires) }) : $t("sharing.noEnd") }}
|
||||
</p>
|
||||
<div class="flex flex-wrap gap-3 text-ui-md">
|
||||
<button class="dw-link" :disabled="busy" @click="reset">{{ $t("sharing.resetLink") }}</button>
|
||||
<button class="text-danger hover:underline" :disabled="busy" data-testid="invite-link-off" @click="turnOff">
|
||||
{{ $t("sharing.turnOff") }}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<template v-if="requests.length">
|
||||
<h3 id="join-requests" class="mt-6 text-ui-md font-semibold">
|
||||
{{ $t("sharing.requests", { n: requests.length }) }}
|
||||
</h3>
|
||||
<ul class="mt-2 divide-y divide-line" data-testid="join-requests">
|
||||
<li
|
||||
v-for="r in requests"
|
||||
:key="r.id"
|
||||
class="flex flex-wrap items-center justify-between gap-2 py-2"
|
||||
data-testid="join-request"
|
||||
>
|
||||
<div class="min-w-0">
|
||||
<p class="truncate text-ui-md font-medium">{{ r.user.name || r.user.email }}</p>
|
||||
<p class="truncate text-ui-sm text-ink-muted">
|
||||
{{ r.user.email }} · {{ $t("sharing.asked", { date: day(r.created) }) }}
|
||||
</p>
|
||||
</div>
|
||||
<div class="flex items-center gap-2 text-ui-md">
|
||||
<select
|
||||
:aria-label="$t('workspace.role')"
|
||||
class="dw-input"
|
||||
:value="r.role"
|
||||
:disabled="busy"
|
||||
@change="r.role = ($event.target as HTMLSelectElement).value as JoinRequest['role']"
|
||||
>
|
||||
<option v-for="x in roles.filter((x) => x === 'member' || x === 'guest')" :key="x" :value="x">
|
||||
{{ $t(`workspace.roles.${x}`) }}
|
||||
</option>
|
||||
</select>
|
||||
<DwButton size="sm" variant="primary" :disabled="busy" data-testid="approve" @click="approve(r, r.role)">
|
||||
{{ $t("sharing.approve") }}
|
||||
</DwButton>
|
||||
<DwButton size="sm" :disabled="busy" data-testid="decline" @click="decline(r)">{{
|
||||
$t("sharing.decline")
|
||||
}}</DwButton>
|
||||
</div>
|
||||
</li>
|
||||
</ul>
|
||||
</template>
|
||||
</section>
|
||||
</template>
|
||||
@@ -403,7 +403,8 @@
|
||||
"restrictedBy": "Eingeschränkt, weil {page} eingeschränkt ist.",
|
||||
"restrictedBadge": "Eingeschränkt",
|
||||
"restrictedSpace": "Mitglieder von {space} können sie nur öffnen, wenn sie mit ihnen geteilt ist. Admins des Bereichs können es.",
|
||||
"limitedSpace": "Du siehst nur die Seiten von {space}, die mit dir geteilt sind."
|
||||
"limitedSpace": "Du siehst nur die Seiten von {space}, die mit dir geteilt sind.",
|
||||
"workspaceOff": "Öffentliche Links sind für diesen Arbeitsbereich ausgeschaltet. Seine Admins können sie in den Einstellungen des Arbeitsbereichs einschalten."
|
||||
},
|
||||
"editor": {
|
||||
"find": {
|
||||
@@ -1000,7 +1001,10 @@
|
||||
"mention": "{actor} hat dich in {page} erwähnt",
|
||||
"share": "{actor} hat {page} mit dir geteilt",
|
||||
"resolved": "{actor} hat eine Diskussion in {page} erledigt",
|
||||
"reminder": "Erinnerung in {page}"
|
||||
"reminder": "Erinnerung in {page}",
|
||||
"join_request": "{actor} bittet um Beitritt zu {workspace}",
|
||||
"join_approved": "Du kannst jetzt {workspace} öffnen",
|
||||
"join_declined": "Deine Anfrage zum Beitritt zu {workspace} wurde abgelehnt"
|
||||
},
|
||||
"settings": "E-Mail",
|
||||
"emailDigest": "Mir zu ungelesenen Benachrichtigungen E-Mails schicken",
|
||||
@@ -1015,7 +1019,8 @@
|
||||
"reply": "Antworten",
|
||||
"resolved": "Erledigten Threads",
|
||||
"share": "Mit mir geteilten Seiten",
|
||||
"reminder": "Erinnerungen"
|
||||
"reminder": "Erinnerungen",
|
||||
"join_request": "Bitten um Beitritt zu Arbeitsbereichen, die ich verwalte"
|
||||
}
|
||||
},
|
||||
"templates": {
|
||||
@@ -1506,5 +1511,75 @@
|
||||
"change": "Ändern",
|
||||
"disconnect": "Trennen",
|
||||
"confirmDisconnect": "Readwise trennen? Die bisher erstellten Seiten bleiben."
|
||||
},
|
||||
"sharing": {
|
||||
"title": "Teilen",
|
||||
"allowSharing": "Öffentliche Links erlauben",
|
||||
"allowSharingHint": "Bearbeitende können Seiten einen Link geben, den jeder lesen kann. Ausgeschaltet funktioniert kein öffentlicher Link des Arbeitsbereichs, bis es wieder an ist.",
|
||||
"urlPreview": "Seitentitel in Chat-Apps zeigen",
|
||||
"urlPreviewHint": "Postet jemand einen Link auf eine private Seite in Slack, Teams oder einer ähnlichen App, zeigt die App den Titel der Seite. Den Text der Seite bekommt niemand, und Seiten nur für bestimmte Personen zeigen nie einen.",
|
||||
"inviteLink": "Einladungslink",
|
||||
"inviteLinkHint": "Jeder mit diesem Link kann nach der Anmeldung dem Arbeitsbereich beitreten. Mit Freigabe bitten Personen um Beitritt und eine Admin-Person entscheidet.",
|
||||
"expires": "Gültig für",
|
||||
"days": "{n} Tag | {n} Tage",
|
||||
"never": "Ohne Ende",
|
||||
"approval": "Admins geben jede Person frei",
|
||||
"createLink": "Einladungslink erstellen",
|
||||
"needsApproval": "mit Freigabe",
|
||||
"joinsDirectly": "Beitritt sofort",
|
||||
"until": "bis {date}",
|
||||
"noEnd": "ohne Enddatum",
|
||||
"resetLink": "Neuen Link erstellen",
|
||||
"turnOff": "Link ausschalten",
|
||||
"confirmOff": "Einladungslink ausschalten? Er funktioniert dann nicht mehr. Bereits gestellte Anfragen bleiben zur Entscheidung.",
|
||||
"confirmReset": "Neuen Einladungslink erstellen? Der jetzige funktioniert dann nicht mehr.",
|
||||
"requests": "Bitten um Beitritt ({n})",
|
||||
"asked": "angefragt am {date}",
|
||||
"approve": "Freigeben",
|
||||
"decline": "Ablehnen"
|
||||
},
|
||||
"files": {
|
||||
"title": "Ungenutzte Dateien",
|
||||
"hint": "Dateien bleiben auf dem Server, nachdem das Bild oder der Anhang aus einer Seite gelöscht wurde, damit Rückgängig funktioniert. Dateien, die keine Seite, kein Symbol und kein Kommentar mehr nutzt, lassen sich hier löschen. Dateien vom letzten Tag zählen nie dazu. Eine alte Seitenversion kann danach fehlende Dateien zeigen.",
|
||||
"find": "Nach ungenutzten Dateien suchen",
|
||||
"looking": "Suche läuft…",
|
||||
"none": "Alle Dateien werden genutzt.",
|
||||
"summary": "{n} ungenutzte Datei, {size} | {n} ungenutzte Dateien, {size}",
|
||||
"delete": "{n} löschen ({size})",
|
||||
"confirmDelete": "{n} Datei ({size}) löschen? Das lässt sich nicht rückgängig machen. | {n} Dateien ({size}) löschen? Das lässt sich nicht rückgängig machen.",
|
||||
"deleted": "{n} Datei gelöscht. | {n} Dateien gelöscht.",
|
||||
"from": "hochgeladen in {page}",
|
||||
"again": "Erneut suchen"
|
||||
},
|
||||
"join": {
|
||||
"title": "Arbeitsbereich beitreten",
|
||||
"intro": "Du wurdest zu {workspace} in {org} eingeladen.",
|
||||
"directHint": "Du trittst als {role} bei.",
|
||||
"approvalHint": "Eine Admin-Person gibt jede Anfrage frei. Du trittst als {role} bei.",
|
||||
"signIn": "Zum Beitreten anmelden",
|
||||
"signUp": "Konto erstellen",
|
||||
"signupClosed": "Auf diesem Server kann man sich nicht selbst registrieren. Bitte eine Admin-Person um eine Einladung per E-Mail.",
|
||||
"signedInAs": "Angemeldet als {email}.",
|
||||
"join": "Arbeitsbereich beitreten",
|
||||
"ask": "Um Beitritt bitten",
|
||||
"pending": "Deine Anfrage wurde gesendet. Du bekommst eine Benachrichtigung, sobald entschieden ist.",
|
||||
"declined": "Deine letzte Anfrage wurde abgelehnt. Du kannst erneut fragen.",
|
||||
"already": "Du bist schon in diesem Arbeitsbereich.",
|
||||
"open": "Arbeitsbereich öffnen",
|
||||
"invalid": "Dieser Einladungslink funktioniert nicht mehr. Bitte die Person, die ihn geschickt hat, um einen neuen."
|
||||
},
|
||||
"analytics": {
|
||||
"title": "Aufrufe",
|
||||
"period": "Zeitraum",
|
||||
"lastDays": "Letzter {n} Tag | Letzte {n} Tage",
|
||||
"views": "Aufrufe",
|
||||
"viewers": "Personen",
|
||||
"linkViews": "Öffentlicher Link",
|
||||
"chart": "{n} Aufruf in den letzten {days} Tagen | {n} Aufrufe in den letzten {days} Tagen",
|
||||
"day": "{date}: {n} Aufruf | {date}: {n} Aufrufe",
|
||||
"recent": "Zuletzt geöffnet von",
|
||||
"nobody": "Niemand Angemeldetes hat sie in diesem Zeitraum geöffnet.",
|
||||
"timesOpened": "{n}-mal geöffnet | {n}-mal geöffnet",
|
||||
"failed": "Aufrufe konnten nicht geladen werden."
|
||||
}
|
||||
}
|
||||
@@ -403,7 +403,8 @@
|
||||
"restrictedBy": "Restricted because {page} is restricted.",
|
||||
"restrictedBadge": "Restricted",
|
||||
"restrictedSpace": "Members of {space} cannot open it unless it is shared with them. Space admins can.",
|
||||
"limitedSpace": "You see only the pages of {space} that are shared with you."
|
||||
"limitedSpace": "You see only the pages of {space} that are shared with you.",
|
||||
"workspaceOff": "Public links are turned off for this workspace. Its admins can turn them on in the workspace settings."
|
||||
},
|
||||
"editor": {
|
||||
"find": {
|
||||
@@ -1000,7 +1001,10 @@
|
||||
"mention": "{actor} mentioned you in {page}",
|
||||
"share": "{actor} shared {page} with you",
|
||||
"resolved": "{actor} resolved a thread in {page}",
|
||||
"reminder": "Reminder in {page}"
|
||||
"reminder": "Reminder in {page}",
|
||||
"join_request": "{actor} asks to join {workspace}",
|
||||
"join_approved": "You can now open {workspace}",
|
||||
"join_declined": "Your request to join {workspace} was declined"
|
||||
},
|
||||
"settings": "Email",
|
||||
"emailDigest": "Email me about unread notifications",
|
||||
@@ -1015,7 +1019,8 @@
|
||||
"reply": "Replies",
|
||||
"resolved": "Resolved threads",
|
||||
"share": "Pages shared with me",
|
||||
"reminder": "Reminders"
|
||||
"reminder": "Reminders",
|
||||
"join_request": "People asking to join a workspace I manage"
|
||||
}
|
||||
},
|
||||
"templates": {
|
||||
@@ -1506,5 +1511,75 @@
|
||||
"change": "Change",
|
||||
"disconnect": "Disconnect",
|
||||
"confirmDisconnect": "Disconnect Readwise? The pages made so far stay."
|
||||
},
|
||||
"sharing": {
|
||||
"title": "Sharing",
|
||||
"allowSharing": "Allow public links",
|
||||
"allowSharingHint": "Editors can give pages a link that anyone can read. Turning this off stops every public link of the workspace until it is on again.",
|
||||
"urlPreview": "Show page titles in chat apps",
|
||||
"urlPreviewHint": "When someone posts a link to a private page in Slack, Teams or a similar app, the app shows the page's title. Nobody gets the page's text, and pages limited to some people never show one.",
|
||||
"inviteLink": "Invite link",
|
||||
"inviteLinkHint": "Anyone with this link can join the workspace after signing in. With approval on, they ask to join and an admin decides.",
|
||||
"expires": "Works for",
|
||||
"days": "{n} day | {n} days",
|
||||
"never": "No end",
|
||||
"approval": "Admins approve each person",
|
||||
"createLink": "Create invite link",
|
||||
"needsApproval": "needs approval",
|
||||
"joinsDirectly": "joins right away",
|
||||
"until": "until {date}",
|
||||
"noEnd": "no end date",
|
||||
"resetLink": "Make a new link",
|
||||
"turnOff": "Turn the link off",
|
||||
"confirmOff": "Turn the invite link off? It stops working. Requests already made stay for you to decide.",
|
||||
"confirmReset": "Make a new invite link? The current one stops working.",
|
||||
"requests": "Asking to join ({n})",
|
||||
"asked": "asked {date}",
|
||||
"approve": "Approve",
|
||||
"decline": "Decline"
|
||||
},
|
||||
"files": {
|
||||
"title": "Unused files",
|
||||
"hint": "Files stay on the server after the image or attachment that showed them is deleted from a page, so undo keeps working. Files no page, icon or comment uses any more can be deleted here. Files uploaded in the last day are never counted. Restoring an old page version may then show missing files.",
|
||||
"find": "Look for unused files",
|
||||
"looking": "Looking…",
|
||||
"none": "Every file is in use.",
|
||||
"summary": "{n} unused file, {size} | {n} unused files, {size}",
|
||||
"delete": "Delete {n} ({size})",
|
||||
"confirmDelete": "Delete {n} file ({size})? This cannot be undone. | Delete {n} files ({size})? This cannot be undone.",
|
||||
"deleted": "{n} file deleted. | {n} files deleted.",
|
||||
"from": "uploaded to {page}",
|
||||
"again": "Look again"
|
||||
},
|
||||
"join": {
|
||||
"title": "Join a workspace",
|
||||
"intro": "You were invited to {workspace} in {org}.",
|
||||
"directHint": "You join as {role}.",
|
||||
"approvalHint": "An admin approves each request. You join as {role}.",
|
||||
"signIn": "Sign in to join",
|
||||
"signUp": "Create an account",
|
||||
"signupClosed": "This server does not let people sign up themselves. Ask an admin to invite you by email.",
|
||||
"signedInAs": "Signed in as {email}.",
|
||||
"join": "Join workspace",
|
||||
"ask": "Ask to join",
|
||||
"pending": "Your request was sent. You get a notification when an admin decides.",
|
||||
"declined": "Your last request was declined. You can ask again.",
|
||||
"already": "You are already in this workspace.",
|
||||
"open": "Open workspace",
|
||||
"invalid": "This invite link does not work any more. Ask the person who sent it for a new one."
|
||||
},
|
||||
"analytics": {
|
||||
"title": "Views",
|
||||
"period": "Period",
|
||||
"lastDays": "Last {n} day | Last {n} days",
|
||||
"views": "Views",
|
||||
"viewers": "People",
|
||||
"linkViews": "Public link",
|
||||
"chart": "{n} view in the last {days} days | {n} views in the last {days} days",
|
||||
"day": "{date}: {n} view | {date}: {n} views",
|
||||
"recent": "Last opened by",
|
||||
"nobody": "Nobody signed in opened it in this period.",
|
||||
"timesOpened": "Opened {n} time | Opened {n} times",
|
||||
"failed": "Views could not be loaded."
|
||||
}
|
||||
}
|
||||
@@ -403,7 +403,8 @@
|
||||
"restrictedBy": "Restringida porque {page} está restringida.",
|
||||
"restrictedBadge": "Restringida",
|
||||
"restrictedSpace": "Los miembros de {space} no pueden abrirla salvo que se comparta con ellos. Los admins del espacio sí pueden.",
|
||||
"limitedSpace": "Solo ves las páginas de {space} que se han compartido contigo."
|
||||
"limitedSpace": "Solo ves las páginas de {space} que se han compartido contigo.",
|
||||
"workspaceOff": "Los enlaces públicos están desactivados en este espacio de trabajo. Sus administradores pueden activarlos en la configuración del espacio de trabajo."
|
||||
},
|
||||
"editor": {
|
||||
"find": {
|
||||
@@ -1000,7 +1001,10 @@
|
||||
"mention": "{actor} te mencionó en {page}",
|
||||
"share": "{actor} compartió {page} contigo",
|
||||
"resolved": "{actor} resolvió una conversación en {page}",
|
||||
"reminder": "Recordatorio en {page}"
|
||||
"reminder": "Recordatorio en {page}",
|
||||
"join_request": "{actor} pide unirse a {workspace}",
|
||||
"join_approved": "Ya puedes abrir {workspace}",
|
||||
"join_declined": "Tu solicitud para unirte a {workspace} fue rechazada"
|
||||
},
|
||||
"settings": "Correo",
|
||||
"emailDigest": "Enviarme un correo sobre las notificaciones sin leer",
|
||||
@@ -1015,7 +1019,8 @@
|
||||
"reply": "Respuestas",
|
||||
"resolved": "Hilos resueltos",
|
||||
"share": "Páginas compartidas conmigo",
|
||||
"reminder": "Recordatorios"
|
||||
"reminder": "Recordatorios",
|
||||
"join_request": "Personas que piden unirse a un espacio de trabajo que administro"
|
||||
}
|
||||
},
|
||||
"templates": {
|
||||
@@ -1506,5 +1511,75 @@
|
||||
"change": "Cambiar",
|
||||
"disconnect": "Desconectar",
|
||||
"confirmDisconnect": "¿Desconectar Readwise? Las páginas creadas se mantienen."
|
||||
},
|
||||
"sharing": {
|
||||
"title": "Compartir",
|
||||
"allowSharing": "Permitir enlaces públicos",
|
||||
"allowSharingHint": "Los editores pueden dar a las páginas un enlace que cualquiera puede leer. Al desactivarlo, ningún enlace público del espacio de trabajo funciona hasta que se vuelva a activar.",
|
||||
"urlPreview": "Mostrar títulos de páginas en apps de chat",
|
||||
"urlPreviewHint": "Cuando alguien publica un enlace a una página privada en Slack, Teams o una app parecida, la app muestra el título de la página. Nadie recibe el texto de la página, y las páginas limitadas a ciertas personas nunca lo muestran.",
|
||||
"inviteLink": "Enlace de invitación",
|
||||
"inviteLinkHint": "Cualquiera con este enlace puede unirse al espacio de trabajo después de iniciar sesión. Con aprobación, piden unirse y un administrador decide.",
|
||||
"expires": "Válido durante",
|
||||
"days": "{n} día | {n} días",
|
||||
"never": "Sin fin",
|
||||
"approval": "Los administradores aprueban a cada persona",
|
||||
"createLink": "Crear enlace de invitación",
|
||||
"needsApproval": "requiere aprobación",
|
||||
"joinsDirectly": "se une al instante",
|
||||
"until": "hasta el {date}",
|
||||
"noEnd": "sin fecha de fin",
|
||||
"resetLink": "Crear un enlace nuevo",
|
||||
"turnOff": "Desactivar el enlace",
|
||||
"confirmOff": "¿Desactivar el enlace de invitación? Dejará de funcionar. Las solicitudes ya hechas quedan para que decidas.",
|
||||
"confirmReset": "¿Crear un enlace de invitación nuevo? El actual dejará de funcionar.",
|
||||
"requests": "Piden unirse ({n})",
|
||||
"asked": "lo pidió el {date}",
|
||||
"approve": "Aprobar",
|
||||
"decline": "Rechazar"
|
||||
},
|
||||
"files": {
|
||||
"title": "Archivos sin usar",
|
||||
"hint": "Los archivos se quedan en el servidor después de borrar de una página la imagen o el adjunto que los mostraba, para que deshacer siga funcionando. Aquí se pueden borrar los archivos que ya no usa ninguna página, icono ni comentario. Los archivos subidos en el último día nunca cuentan. Restaurar una versión antigua de una página puede mostrar archivos que faltan.",
|
||||
"find": "Buscar archivos sin usar",
|
||||
"looking": "Buscando…",
|
||||
"none": "Todos los archivos están en uso.",
|
||||
"summary": "{n} archivo sin usar, {size} | {n} archivos sin usar, {size}",
|
||||
"delete": "Borrar {n} ({size})",
|
||||
"confirmDelete": "¿Borrar {n} archivo ({size})? No se puede deshacer. | ¿Borrar {n} archivos ({size})? No se puede deshacer.",
|
||||
"deleted": "{n} archivo borrado. | {n} archivos borrados.",
|
||||
"from": "subido a {page}",
|
||||
"again": "Buscar de nuevo"
|
||||
},
|
||||
"join": {
|
||||
"title": "Unirse a un espacio de trabajo",
|
||||
"intro": "Te invitaron a {workspace} en {org}.",
|
||||
"directHint": "Te unes como {role}.",
|
||||
"approvalHint": "Un administrador aprueba cada solicitud. Te unes como {role}.",
|
||||
"signIn": "Inicia sesión para unirte",
|
||||
"signUp": "Crear una cuenta",
|
||||
"signupClosed": "Este servidor no permite registrarse por cuenta propia. Pide a un administrador que te invite por correo.",
|
||||
"signedInAs": "Sesión iniciada como {email}.",
|
||||
"join": "Unirse al espacio de trabajo",
|
||||
"ask": "Pedir unirse",
|
||||
"pending": "Tu solicitud se envió. Recibirás una notificación cuando un administrador decida.",
|
||||
"declined": "Tu última solicitud fue rechazada. Puedes volver a pedirlo.",
|
||||
"already": "Ya estás en este espacio de trabajo.",
|
||||
"open": "Abrir espacio de trabajo",
|
||||
"invalid": "Este enlace de invitación ya no funciona. Pide uno nuevo a quien te lo envió."
|
||||
},
|
||||
"analytics": {
|
||||
"title": "Vistas",
|
||||
"period": "Periodo",
|
||||
"lastDays": "Último {n} día | Últimos {n} días",
|
||||
"views": "Vistas",
|
||||
"viewers": "Personas",
|
||||
"linkViews": "Enlace público",
|
||||
"chart": "{n} vista en los últimos {days} días | {n} vistas en los últimos {days} días",
|
||||
"day": "{date}: {n} vista | {date}: {n} vistas",
|
||||
"recent": "Abierta por última vez por",
|
||||
"nobody": "Nadie con sesión iniciada la abrió en este periodo.",
|
||||
"timesOpened": "Abierta {n} vez | Abierta {n} veces",
|
||||
"failed": "No se pudieron cargar las vistas."
|
||||
}
|
||||
}
|
||||
@@ -403,7 +403,8 @@
|
||||
"restrictedBy": "Restreinte car {page} est restreinte.",
|
||||
"restrictedBadge": "Restreinte",
|
||||
"restrictedSpace": "Les membres de {space} ne peuvent l’ouvrir que si elle est partagée avec eux. Les admins de l’espace le peuvent.",
|
||||
"limitedSpace": "Vous ne voyez que les pages de {space} partagées avec vous."
|
||||
"limitedSpace": "Vous ne voyez que les pages de {space} partagées avec vous.",
|
||||
"workspaceOff": "Les liens publics sont désactivés pour cet espace de travail. Ses administrateurs peuvent les activer dans les paramètres de l'espace de travail."
|
||||
},
|
||||
"editor": {
|
||||
"find": {
|
||||
@@ -1000,7 +1001,10 @@
|
||||
"mention": "{actor} vous a mentionné dans {page}",
|
||||
"share": "{actor} a partagé {page} avec vous",
|
||||
"resolved": "{actor} a résolu une discussion dans {page}",
|
||||
"reminder": "Rappel dans {page}"
|
||||
"reminder": "Rappel dans {page}",
|
||||
"join_request": "{actor} demande à rejoindre {workspace}",
|
||||
"join_approved": "Vous pouvez maintenant ouvrir {workspace}",
|
||||
"join_declined": "Votre demande pour rejoindre {workspace} a été refusée"
|
||||
},
|
||||
"settings": "E-mail",
|
||||
"emailDigest": "M’envoyer un e-mail pour les notifications non lues",
|
||||
@@ -1015,7 +1019,8 @@
|
||||
"reply": "Les réponses",
|
||||
"resolved": "Les fils résolus",
|
||||
"share": "Les pages partagées avec moi",
|
||||
"reminder": "Les rappels"
|
||||
"reminder": "Les rappels",
|
||||
"join_request": "Demandes pour rejoindre un espace de travail que je gère"
|
||||
}
|
||||
},
|
||||
"templates": {
|
||||
@@ -1506,5 +1511,75 @@
|
||||
"change": "Modifier",
|
||||
"disconnect": "Déconnecter",
|
||||
"confirmDisconnect": "Déconnecter Readwise ? Les pages déjà créées restent."
|
||||
},
|
||||
"sharing": {
|
||||
"title": "Partage",
|
||||
"allowSharing": "Autoriser les liens publics",
|
||||
"allowSharingHint": "Les éditeurs peuvent donner aux pages un lien que tout le monde peut lire. Une fois désactivé, plus aucun lien public de l'espace de travail ne fonctionne jusqu'à sa réactivation.",
|
||||
"urlPreview": "Afficher les titres des pages dans les apps de discussion",
|
||||
"urlPreviewHint": "Quand quelqu'un publie un lien vers une page privée dans Slack, Teams ou une app semblable, l'app affiche le titre de la page. Personne ne reçoit le texte de la page, et les pages réservées à certaines personnes n'en affichent jamais.",
|
||||
"inviteLink": "Lien d'invitation",
|
||||
"inviteLinkHint": "Toute personne ayant ce lien peut rejoindre l'espace de travail après s'être connectée. Avec l'approbation, elle demande à rejoindre et un administrateur décide.",
|
||||
"expires": "Valable",
|
||||
"days": "{n} jour | {n} jours",
|
||||
"never": "Sans fin",
|
||||
"approval": "Les administrateurs approuvent chaque personne",
|
||||
"createLink": "Créer un lien d'invitation",
|
||||
"needsApproval": "avec approbation",
|
||||
"joinsDirectly": "accès immédiat",
|
||||
"until": "jusqu'au {date}",
|
||||
"noEnd": "sans date de fin",
|
||||
"resetLink": "Créer un nouveau lien",
|
||||
"turnOff": "Désactiver le lien",
|
||||
"confirmOff": "Désactiver le lien d'invitation ? Il ne fonctionnera plus. Les demandes déjà faites restent à traiter.",
|
||||
"confirmReset": "Créer un nouveau lien d'invitation ? L'actuel ne fonctionnera plus.",
|
||||
"requests": "Demandes pour rejoindre ({n})",
|
||||
"asked": "demandé le {date}",
|
||||
"approve": "Approuver",
|
||||
"decline": "Refuser"
|
||||
},
|
||||
"files": {
|
||||
"title": "Fichiers inutilisés",
|
||||
"hint": "Les fichiers restent sur le serveur après la suppression de l'image ou de la pièce jointe qui les affichait, pour que l'annulation fonctionne. Les fichiers qu'aucune page, icône ou commentaire n'utilise plus peuvent être supprimés ici. Les fichiers envoyés depuis moins d'un jour ne comptent jamais. Restaurer une ancienne version d'une page peut alors afficher des fichiers manquants.",
|
||||
"find": "Chercher les fichiers inutilisés",
|
||||
"looking": "Recherche…",
|
||||
"none": "Tous les fichiers sont utilisés.",
|
||||
"summary": "{n} fichier inutilisé, {size} | {n} fichiers inutilisés, {size}",
|
||||
"delete": "Supprimer {n} ({size})",
|
||||
"confirmDelete": "Supprimer {n} fichier ({size}) ? C'est définitif. | Supprimer {n} fichiers ({size}) ? C'est définitif.",
|
||||
"deleted": "{n} fichier supprimé. | {n} fichiers supprimés.",
|
||||
"from": "envoyé dans {page}",
|
||||
"again": "Chercher à nouveau"
|
||||
},
|
||||
"join": {
|
||||
"title": "Rejoindre un espace de travail",
|
||||
"intro": "Vous êtes invité à rejoindre {workspace} dans {org}.",
|
||||
"directHint": "Vous rejoignez en tant que {role}.",
|
||||
"approvalHint": "Un administrateur approuve chaque demande. Vous rejoignez en tant que {role}.",
|
||||
"signIn": "Se connecter pour rejoindre",
|
||||
"signUp": "Créer un compte",
|
||||
"signupClosed": "Ce serveur ne permet pas de s'inscrire soi-même. Demandez à un administrateur de vous inviter par e-mail.",
|
||||
"signedInAs": "Connecté en tant que {email}.",
|
||||
"join": "Rejoindre l'espace de travail",
|
||||
"ask": "Demander à rejoindre",
|
||||
"pending": "Votre demande a été envoyée. Vous recevrez une notification quand un administrateur aura décidé.",
|
||||
"declined": "Votre dernière demande a été refusée. Vous pouvez demander à nouveau.",
|
||||
"already": "Vous êtes déjà dans cet espace de travail.",
|
||||
"open": "Ouvrir l'espace de travail",
|
||||
"invalid": "Ce lien d'invitation ne fonctionne plus. Demandez-en un nouveau à la personne qui l'a envoyé."
|
||||
},
|
||||
"analytics": {
|
||||
"title": "Vues",
|
||||
"period": "Période",
|
||||
"lastDays": "{n} dernier jour | {n} derniers jours",
|
||||
"views": "Vues",
|
||||
"viewers": "Personnes",
|
||||
"linkViews": "Lien public",
|
||||
"chart": "{n} vue ces {days} derniers jours | {n} vues ces {days} derniers jours",
|
||||
"day": "{date} : {n} vue | {date} : {n} vues",
|
||||
"recent": "Ouverte récemment par",
|
||||
"nobody": "Personne de connecté ne l'a ouverte sur cette période.",
|
||||
"timesOpened": "Ouverte {n} fois | Ouverte {n} fois",
|
||||
"failed": "Impossible de charger les vues."
|
||||
}
|
||||
}
|
||||
@@ -403,7 +403,8 @@
|
||||
"restrictedBy": "Ograniczona, ponieważ strona {page} jest ograniczona.",
|
||||
"restrictedBadge": "Ograniczona",
|
||||
"restrictedSpace": "Członkowie {space} nie mogą jej otworzyć, chyba że zostanie im udostępniona. Administratorzy przestrzeni mogą.",
|
||||
"limitedSpace": "Widzisz tylko te strony z {space}, które Ci udostępniono."
|
||||
"limitedSpace": "Widzisz tylko te strony z {space}, które Ci udostępniono.",
|
||||
"workspaceOff": "Linki publiczne są wyłączone w tym obszarze roboczym. Jego administratorzy mogą je włączyć w ustawieniach obszaru roboczego."
|
||||
},
|
||||
"editor": {
|
||||
"find": {
|
||||
@@ -1000,7 +1001,10 @@
|
||||
"mention": "{actor} wspomniał(a) o Tobie na stronie {page}",
|
||||
"share": "{actor} udostępnił(a) Ci {page}",
|
||||
"resolved": "{actor} rozwiązał(a) wątek na stronie {page}",
|
||||
"reminder": "Przypomnienie na stronie {page}"
|
||||
"reminder": "Przypomnienie na stronie {page}",
|
||||
"join_request": "{actor} prosi o dołączenie do {workspace}",
|
||||
"join_approved": "Możesz już otworzyć {workspace}",
|
||||
"join_declined": "Twoja prośba o dołączenie do {workspace} została odrzucona"
|
||||
},
|
||||
"settings": "E-mail",
|
||||
"emailDigest": "Wysyłaj mi e-mail o nieprzeczytanych powiadomieniach",
|
||||
@@ -1015,7 +1019,8 @@
|
||||
"reply": "Odpowiedziach",
|
||||
"resolved": "Rozwiązanych wątkach",
|
||||
"share": "Stronach mi udostępnionych",
|
||||
"reminder": "Przypomnieniach"
|
||||
"reminder": "Przypomnieniach",
|
||||
"join_request": "Prośby o dołączenie do obszarów, którymi zarządzam"
|
||||
}
|
||||
},
|
||||
"templates": {
|
||||
@@ -1506,5 +1511,75 @@
|
||||
"change": "Zmień",
|
||||
"disconnect": "Odłącz",
|
||||
"confirmDisconnect": "Odłączyć Readwise? Utworzone strony pozostaną."
|
||||
},
|
||||
"sharing": {
|
||||
"title": "Udostępnianie",
|
||||
"allowSharing": "Zezwalaj na linki publiczne",
|
||||
"allowSharingHint": "Edytujący mogą nadać stronom link, który każdy może czytać. Po wyłączeniu żaden link publiczny obszaru roboczego nie działa, dopóki nie zostanie znowu włączony.",
|
||||
"urlPreview": "Pokazuj tytuły stron w komunikatorach",
|
||||
"urlPreviewHint": "Gdy ktoś wklei link do prywatnej strony w Slacku, Teams lub podobnej aplikacji, aplikacja pokaże tytuł strony. Nikt nie dostaje treści strony, a strony ograniczone do wybranych osób nigdy go nie pokazują.",
|
||||
"inviteLink": "Link z zaproszeniem",
|
||||
"inviteLinkHint": "Każdy z tym linkiem może dołączyć do obszaru roboczego po zalogowaniu. Z zatwierdzaniem prosi o dołączenie, a decyduje administrator.",
|
||||
"expires": "Ważny przez",
|
||||
"days": "{n} dzień | {n} dni | {n} dni",
|
||||
"never": "Bez końca",
|
||||
"approval": "Administratorzy zatwierdzają każdą osobę",
|
||||
"createLink": "Utwórz link z zaproszeniem",
|
||||
"needsApproval": "wymaga zatwierdzenia",
|
||||
"joinsDirectly": "dołączenie od razu",
|
||||
"until": "do {date}",
|
||||
"noEnd": "bez daty końca",
|
||||
"resetLink": "Utwórz nowy link",
|
||||
"turnOff": "Wyłącz link",
|
||||
"confirmOff": "Wyłączyć link z zaproszeniem? Przestanie działać. Złożone już prośby czekają na decyzję.",
|
||||
"confirmReset": "Utworzyć nowy link z zaproszeniem? Obecny przestanie działać.",
|
||||
"requests": "Prośby o dołączenie ({n})",
|
||||
"asked": "prośba z {date}",
|
||||
"approve": "Zatwierdź",
|
||||
"decline": "Odrzuć"
|
||||
},
|
||||
"files": {
|
||||
"title": "Nieużywane pliki",
|
||||
"hint": "Pliki zostają na serwerze po usunięciu ze strony obrazu lub załącznika, który je pokazywał, żeby cofanie działało. Tutaj można usunąć pliki, których nie używa już żadna strona, ikona ani komentarz. Pliki przesłane w ostatniej dobie nigdy się nie liczą. Przywrócenie starej wersji strony może wtedy pokazać brakujące pliki.",
|
||||
"find": "Szukaj nieużywanych plików",
|
||||
"looking": "Szukam…",
|
||||
"none": "Wszystkie pliki są używane.",
|
||||
"summary": "Nieużywane pliki: {n}, {size}",
|
||||
"delete": "Usuń {n} ({size})",
|
||||
"confirmDelete": "Usunąć pliki ({n}, {size})? Tego nie da się cofnąć.",
|
||||
"deleted": "Usunięto {n} plik. | Usunięto {n} pliki. | Usunięto {n} plików.",
|
||||
"from": "przesłany do {page}",
|
||||
"again": "Szukaj ponownie"
|
||||
},
|
||||
"join": {
|
||||
"title": "Dołącz do obszaru roboczego",
|
||||
"intro": "Zaproszono cię do {workspace} w {org}.",
|
||||
"directHint": "Dołączasz jako {role}.",
|
||||
"approvalHint": "Administrator zatwierdza każdą prośbę. Dołączasz jako {role}.",
|
||||
"signIn": "Zaloguj się, aby dołączyć",
|
||||
"signUp": "Utwórz konto",
|
||||
"signupClosed": "Na tym serwerze nie można samemu założyć konta. Poproś administratora o zaproszenie e-mailem.",
|
||||
"signedInAs": "Zalogowano jako {email}.",
|
||||
"join": "Dołącz do obszaru roboczego",
|
||||
"ask": "Poproś o dołączenie",
|
||||
"pending": "Twoja prośba została wysłana. Dostaniesz powiadomienie, gdy administrator zdecyduje.",
|
||||
"declined": "Twoja ostatnia prośba została odrzucona. Możesz poprosić ponownie.",
|
||||
"already": "Jesteś już w tym obszarze roboczym.",
|
||||
"open": "Otwórz obszar roboczy",
|
||||
"invalid": "Ten link z zaproszeniem już nie działa. Poproś osobę, która go wysłała, o nowy."
|
||||
},
|
||||
"analytics": {
|
||||
"title": "Wyświetlenia",
|
||||
"period": "Okres",
|
||||
"lastDays": "Ostatni {n} dzień | Ostatnie {n} dni | Ostatnie {n} dni",
|
||||
"views": "Wyświetlenia",
|
||||
"viewers": "Osoby",
|
||||
"linkViews": "Link publiczny",
|
||||
"chart": "Wyświetlenia w ostatnich {days} dniach: {n}",
|
||||
"day": "{date}: {n}",
|
||||
"recent": "Ostatnio otwierali",
|
||||
"nobody": "Nikt zalogowany nie otworzył jej w tym okresie.",
|
||||
"timesOpened": "Otwarta {n} raz | Otwarta {n} razy | Otwarta {n} razy",
|
||||
"failed": "Nie udało się wczytać wyświetleń."
|
||||
}
|
||||
}
|
||||
@@ -141,6 +141,13 @@ export function createDocwellRouter(platform: Platform) {
|
||||
component: () => import("./views/auth/InviteView.vue"),
|
||||
meta: { public: true },
|
||||
},
|
||||
// A workspace's invite link (anyone signed in can join, or ask to).
|
||||
{
|
||||
path: "/join",
|
||||
name: "join",
|
||||
component: () => import("./views/auth/JoinView.vue"),
|
||||
meta: { public: true },
|
||||
},
|
||||
{
|
||||
path: "/oauth/callback",
|
||||
name: "oauth-callback",
|
||||
|
||||
@@ -8,11 +8,13 @@ import { useRouter } from "vue-router";
|
||||
import { useApi } from "../api";
|
||||
import { useFormErrors } from "../composables/useFormErrors";
|
||||
import { useNotificationsStore } from "../stores/notifications";
|
||||
import { useWorkspacesStore } from "../stores/workspaces";
|
||||
|
||||
// The inbox: what happened on watched pages, replies, mentions, shares and
|
||||
// reminders, newest first, and whether unread ones also come by email.
|
||||
const api = useApi();
|
||||
const store = useNotificationsStore();
|
||||
const workspaces = useWorkspacesStore();
|
||||
const router = useRouter();
|
||||
const errors = useFormErrors();
|
||||
const { locale } = useI18n();
|
||||
@@ -36,10 +38,27 @@ const icons: Record<Notification["type"], IconName> = {
|
||||
share: "share",
|
||||
resolved: "check",
|
||||
reminder: "bell",
|
||||
join_request: "user-plus",
|
||||
join_approved: "users",
|
||||
join_declined: "users",
|
||||
};
|
||||
|
||||
// Workspace notifications have no page: they open the workspace instead.
|
||||
const isJoin = (n: Notification) => n.type.startsWith("join_");
|
||||
const opens = (n: Notification) => !!n.page || n.type === "join_request" || n.type === "join_approved";
|
||||
|
||||
async function open(n: Notification) {
|
||||
void store.markRead([n.id]).catch(() => {});
|
||||
if (n.type === "join_request") {
|
||||
await router.push({ name: "workspace-settings", params: { id: n.workspace }, hash: "#join-requests" });
|
||||
return;
|
||||
}
|
||||
if (n.type === "join_approved") {
|
||||
await workspaces.load().catch(() => {});
|
||||
workspaces.select(n.workspace);
|
||||
await router.push("/");
|
||||
return;
|
||||
}
|
||||
if (!n.page) return;
|
||||
await router.push({ name: "page", params: { id: n.page.id }, query: n.comment ? { comment: n.comment } : {} });
|
||||
}
|
||||
@@ -61,7 +80,7 @@ const setEmail = (on: boolean) =>
|
||||
settings.value = await api.notifications.setSettings({ email: on ? "digest" : "off" });
|
||||
});
|
||||
// Which kinds of notification the digest includes; the rest stay in the inbox.
|
||||
const emailKinds: NotificationType[] = ["mention", "comment", "reply", "resolved", "share", "reminder"];
|
||||
const emailKinds: NotificationType[] = ["mention", "comment", "reply", "resolved", "share", "reminder", "join_request"];
|
||||
const setEmailType = (type: NotificationType, on: boolean) =>
|
||||
run(async () => {
|
||||
const cur = settings.value?.emailTypes ?? emailKinds;
|
||||
@@ -99,7 +118,7 @@ const when = (s: string) =>
|
||||
<button
|
||||
class="flex w-full cursor-pointer items-start gap-3 rounded-md px-3 py-2.5 text-left hover:bg-surface-hover disabled:cursor-default"
|
||||
:class="n.read ? 'text-ink-muted' : ''"
|
||||
:disabled="!n.page"
|
||||
:disabled="!opens(n)"
|
||||
data-testid="notification"
|
||||
@click="open(n)"
|
||||
>
|
||||
@@ -110,6 +129,9 @@ const when = (s: string) =>
|
||||
<template #actor>
|
||||
<span class="font-semibold">{{ n.actor?.name || n.actor?.email || $t("page.someone") }}</span>
|
||||
</template>
|
||||
<template #workspace>
|
||||
<span class="font-semibold">{{ n.excerpt }}</span>
|
||||
</template>
|
||||
<template #page>
|
||||
<span class="font-semibold">{{
|
||||
n.page ? n.page.title || $t("home.untitled") : $t("notifications.pageGone")
|
||||
@@ -117,7 +139,10 @@ const when = (s: string) =>
|
||||
</template>
|
||||
</i18n-t>
|
||||
</span>
|
||||
<span v-if="n.excerpt && n.type !== 'share'" class="mt-0.5 line-clamp-2 block text-ui-sm text-ink-muted">
|
||||
<span
|
||||
v-if="n.excerpt && n.type !== 'share' && !isJoin(n)"
|
||||
class="mt-0.5 line-clamp-2 block text-ui-sm text-ink-muted"
|
||||
>
|
||||
{{ n.excerpt }}
|
||||
</span>
|
||||
<span class="mt-0.5 block text-ui-xs text-ink-faint">{{ when(n.created) }}</span>
|
||||
|
||||
@@ -0,0 +1,130 @@
|
||||
<!-- SPDX-License-Identifier: AGPL-3.0-or-later -->
|
||||
<script setup lang="ts">
|
||||
import type { JoinInfo } from "@docwell/api-client";
|
||||
import { DwButton, DwCallout } from "@docwell/ui";
|
||||
import { computed, onMounted, ref } from "vue";
|
||||
import { useRoute, useRouter } from "vue-router";
|
||||
import { useApi } from "../../api";
|
||||
import AuthCard from "../../components/AuthCard.vue";
|
||||
import { useFormErrors } from "../../composables/useFormErrors";
|
||||
import { useAuthStore } from "../../stores/auth";
|
||||
import { useWorkspacesStore } from "../../stores/workspaces";
|
||||
|
||||
// A workspace's invite link: /join?token=... Signed-out visitors sign in or
|
||||
// sign up first and come back here.
|
||||
const api = useApi();
|
||||
const auth = useAuthStore();
|
||||
const workspaces = useWorkspacesStore();
|
||||
const route = useRoute();
|
||||
const router = useRouter();
|
||||
const errors = useFormErrors();
|
||||
|
||||
const token = typeof route.query.token === "string" ? route.query.token : "";
|
||||
const info = ref<JoinInfo | null>(null);
|
||||
const failed = ref(false);
|
||||
const busy = ref(false);
|
||||
const signupOpen = ref(true);
|
||||
const here = computed(() => `/join?token=${encodeURIComponent(token)}`);
|
||||
|
||||
async function load() {
|
||||
if (!token) throw new Error("missing token");
|
||||
info.value = await api.auth.joinInfo(token);
|
||||
}
|
||||
|
||||
onMounted(async () => {
|
||||
try {
|
||||
await load();
|
||||
} catch {
|
||||
failed.value = true;
|
||||
}
|
||||
if (!auth.isSignedIn) {
|
||||
signupOpen.value = (await api.auth.methods().catch(() => null))?.signup !== false;
|
||||
}
|
||||
});
|
||||
|
||||
async function open(id: string) {
|
||||
await workspaces.load();
|
||||
workspaces.select(id);
|
||||
router.replace("/");
|
||||
}
|
||||
|
||||
async function join() {
|
||||
busy.value = true;
|
||||
errors.reset();
|
||||
try {
|
||||
const res = await api.auth.join(token);
|
||||
// Joining may have moved the account into the workspace's organization.
|
||||
await auth.reload().catch(() => {});
|
||||
if (res.status === "member") await open(res.workspace);
|
||||
else await load();
|
||||
} catch (e) {
|
||||
errors.show(e);
|
||||
} finally {
|
||||
busy.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
function switchAccount() {
|
||||
auth.logout();
|
||||
router.replace({ name: "login", query: { redirect: here.value } });
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<AuthCard :title="$t('join.title')">
|
||||
<p v-if="failed" role="alert" class="text-ui-md text-danger" data-testid="join-invalid">
|
||||
{{ $t("join.invalid") }}
|
||||
</p>
|
||||
<p v-else-if="!info" class="text-ui-md text-ink-muted">…</p>
|
||||
|
||||
<div v-else class="space-y-4" data-testid="join">
|
||||
<p class="text-ui-md">
|
||||
{{ $t("join.intro", { workspace: info.workspaceName, org: info.organizationName || info.workspaceName }) }}
|
||||
</p>
|
||||
<p class="text-ui-sm text-ink-muted">
|
||||
{{ $t(info.approval ? "join.approvalHint" : "join.directHint", { role: $t(`workspace.roles.${info.role}`) }) }}
|
||||
</p>
|
||||
<DwCallout v-if="errors.message.value" tone="danger" size="ui">{{ errors.message.value }}</DwCallout>
|
||||
|
||||
<template v-if="!auth.isSignedIn">
|
||||
<RouterLink
|
||||
:to="{ name: 'login', query: { redirect: here } }"
|
||||
class="inline-flex h-control-md w-full items-center justify-center rounded-sm bg-primary px-3 text-ui-md font-semibold text-on-primary hover:bg-primary-hover"
|
||||
>{{ $t("join.signIn") }}</RouterLink
|
||||
>
|
||||
<RouterLink
|
||||
v-if="signupOpen"
|
||||
:to="{ name: 'signup', query: { redirect: here } }"
|
||||
class="inline-flex h-control-md w-full items-center justify-center rounded-sm border border-line px-3 text-ui-md font-semibold hover:bg-surface-hover"
|
||||
>{{ $t("join.signUp") }}</RouterLink
|
||||
>
|
||||
<p v-else class="text-ui-sm text-ink-muted">{{ $t("join.signupClosed") }}</p>
|
||||
</template>
|
||||
|
||||
<template v-else-if="info.status === 'member'">
|
||||
<DwCallout tone="success" size="ui">{{ $t("join.already") }}</DwCallout>
|
||||
<DwButton variant="primary" class="w-full justify-center" @click="open(info.workspace)">{{
|
||||
$t("join.open")
|
||||
}}</DwButton>
|
||||
</template>
|
||||
|
||||
<DwCallout v-else-if="info.status === 'pending'" tone="info" size="ui" data-testid="join-pending">
|
||||
{{ $t("join.pending") }}
|
||||
</DwCallout>
|
||||
|
||||
<template v-else>
|
||||
<DwCallout v-if="info.status === 'declined'" tone="warning" size="ui">{{ $t("join.declined") }}</DwCallout>
|
||||
<p class="text-ui-sm text-ink-muted">{{ $t("join.signedInAs", { email: auth.user?.email }) }}</p>
|
||||
<DwButton
|
||||
variant="primary"
|
||||
class="w-full justify-center"
|
||||
:disabled="busy"
|
||||
data-testid="join-submit"
|
||||
@click="join"
|
||||
>{{ $t(info.approval ? "join.ask" : "join.join") }}</DwButton
|
||||
>
|
||||
<button class="dw-link text-ui-sm" @click="switchAccount">{{ $t("invite.switchAccount") }}</button>
|
||||
</template>
|
||||
</div>
|
||||
</AuthCard>
|
||||
</template>
|
||||
@@ -2,13 +2,14 @@
|
||||
<script setup lang="ts">
|
||||
import { DwButton, DwCallout } from "@docwell/ui";
|
||||
import { ref } from "vue";
|
||||
import { useRouter } from "vue-router";
|
||||
import { useRoute, useRouter } from "vue-router";
|
||||
import AuthCard from "../../components/AuthCard.vue";
|
||||
import FormField from "../../components/FormField.vue";
|
||||
import { useFormErrors } from "../../composables/useFormErrors";
|
||||
import { useAuthStore } from "../../stores/auth";
|
||||
|
||||
const auth = useAuthStore();
|
||||
const route = useRoute();
|
||||
const router = useRouter();
|
||||
const errors = useFormErrors();
|
||||
|
||||
@@ -22,7 +23,11 @@ async function submit() {
|
||||
errors.reset();
|
||||
try {
|
||||
await auth.signup({ name: name.value, email: email.value, password: password.value });
|
||||
router.replace("/");
|
||||
// Coming from an invite link (/join), go back there to use it.
|
||||
const redirect = route.query.redirect;
|
||||
router.replace(
|
||||
typeof redirect === "string" && redirect.startsWith("/") && !redirect.startsWith("//") ? redirect : "/",
|
||||
);
|
||||
} catch (e) {
|
||||
errors.show(e);
|
||||
} finally {
|
||||
|
||||
@@ -25,6 +25,7 @@ import PageHistory from "../../components/PageHistory.vue";
|
||||
import JournalEvents from "../../components/JournalEvents.vue";
|
||||
import JournalStrip from "../../components/JournalStrip.vue";
|
||||
import PageComments from "../../components/PageComments.vue";
|
||||
import PageAnalytics from "../../components/PageAnalytics.vue";
|
||||
import PageList from "../../components/PageList.vue";
|
||||
import PageProperties from "../../components/PageProperties.vue";
|
||||
import ShareDialog from "../../components/ShareDialog.vue";
|
||||
@@ -1073,6 +1074,7 @@ const purge = () =>
|
||||
</ul>
|
||||
<p class="mt-1 text-ui-xs text-ink-faint">{{ $t("collections.byHandHint") }}</p>
|
||||
</section>
|
||||
<PageAnalytics v-if="canEdit" :page="page.id" />
|
||||
<section v-if="canOrganize">
|
||||
<h3 class="dw-label">{{ $t("journal.title") }}</h3>
|
||||
<JournalStrip
|
||||
|
||||
@@ -8,7 +8,9 @@ import { useI18n } from "vue-i18n";
|
||||
import { useRouter } from "vue-router";
|
||||
import { useApi } from "../../api";
|
||||
import PageShell from "../../components/PageShell.vue";
|
||||
import WorkspaceFiles from "../../components/WorkspaceFiles.vue";
|
||||
import WorkspaceGroups from "../../components/WorkspaceGroups.vue";
|
||||
import WorkspaceSharing from "../../components/WorkspaceSharing.vue";
|
||||
import WorkspaceProperties from "../../components/WorkspaceProperties.vue";
|
||||
import WorkspaceTags from "../../components/WorkspaceTags.vue";
|
||||
import WorkspaceWebhooks from "../../components/WorkspaceWebhooks.vue";
|
||||
@@ -268,12 +270,16 @@ async function removeWorkspace() {
|
||||
</template>
|
||||
</section>
|
||||
|
||||
<WorkspaceSharing v-if="canManage" :workspace="ws" @changed="run(async () => {})" />
|
||||
|
||||
<WorkspaceGroups v-if="atLeast(myRole, 'member')" :workspace="ws.id" :can-manage="canManage" />
|
||||
<WorkspaceProperties :workspace="ws.id" :can-edit="atLeast(myRole, 'member')" />
|
||||
<WorkspaceTags :workspace="ws.id" :can-edit="atLeast(myRole, 'member')" />
|
||||
<WorkspaceWebhooks v-if="canManage" :workspace="ws.id" />
|
||||
<WorkspaceAI v-if="canManage" :workspace="ws.id" />
|
||||
|
||||
<WorkspaceFiles v-if="canManage" :workspace="ws.id" />
|
||||
|
||||
<section v-if="canManage" class="dw-card" data-testid="workspace-snapshot">
|
||||
<h2 class="text-ui-lg">{{ $t("workspace.snapshotTitle") }}</h2>
|
||||
<p class="mt-1 text-ui-sm text-ink-muted">{{ $t("workspace.snapshotHint") }}</p>
|
||||
|
||||
@@ -0,0 +1,137 @@
|
||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
package spa
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"html"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"regexp"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
)
|
||||
|
||||
// Link previews for chat apps (ADR-17). When Slack, Teams, Discord and the
|
||||
// like fetch a page or share link, the app shell they get has no title, so
|
||||
// for their bots docwell-web asks docwell-server what to show and writes it
|
||||
// into the page's meta tags. People's browsers never wait for this.
|
||||
|
||||
// Preview is what docwell-server's preview endpoints answer.
|
||||
type Preview struct {
|
||||
Title string `json:"title"`
|
||||
Description string `json:"description"`
|
||||
Site string `json:"site"`
|
||||
}
|
||||
|
||||
// previewBots matches the user agents of chat apps' link-preview fetchers.
|
||||
// Search engines are left out on purpose: they must not learn the titles of
|
||||
// private pages.
|
||||
var previewBots = regexp.MustCompile(`(?i)slackbot|slack-imgproxy|twitterbot|facebookexternalhit|discordbot|telegrambot|whatsapp|linkedinbot|mattermost|skypeuripreview|microsoftpreview|embedly|iframely|redditbot|zulip|rocket\.chat|synapse|nextcloud server crawler|viber`)
|
||||
|
||||
var (
|
||||
pagePath = regexp.MustCompile(`^/p/([A-Za-z0-9_-]{1,64})$`)
|
||||
sharePath = regexp.MustCompile(`^/share/([A-Za-z0-9_-]{1,64})(?:/p/([A-Za-z0-9_-]{1,64}))?$`)
|
||||
)
|
||||
|
||||
// previewer looks previews up on docwell-server and remembers them briefly.
|
||||
type previewer struct {
|
||||
api *url.URL
|
||||
client *http.Client
|
||||
mu sync.Mutex
|
||||
cache map[string]cachedPreview
|
||||
}
|
||||
|
||||
type cachedPreview struct {
|
||||
p *Preview
|
||||
exp time.Time
|
||||
}
|
||||
|
||||
func newPreviewer(api *url.URL) *previewer {
|
||||
return &previewer{api: api, client: &http.Client{Timeout: 3 * time.Second}, cache: map[string]cachedPreview{}}
|
||||
}
|
||||
|
||||
// endpoint maps an app path to its preview endpoint ("" when it has none).
|
||||
func endpoint(p string) string {
|
||||
if m := pagePath.FindStringSubmatch(p); m != nil {
|
||||
return "/api/v1/previews/pages/" + m[1]
|
||||
}
|
||||
if m := sharePath.FindStringSubmatch(p); m != nil {
|
||||
e := "/api/v1/previews/share/" + m[1]
|
||||
if m[2] != "" {
|
||||
e += "?page=" + url.QueryEscape(m[2])
|
||||
}
|
||||
return e
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
// lookup returns the preview for an app path, or nil.
|
||||
func (v *previewer) lookup(ctx context.Context, p string) *Preview {
|
||||
e := endpoint(p)
|
||||
if e == "" {
|
||||
return nil
|
||||
}
|
||||
now := time.Now()
|
||||
v.mu.Lock()
|
||||
if c, ok := v.cache[e]; ok && now.Before(c.exp) {
|
||||
v.mu.Unlock()
|
||||
return c.p
|
||||
}
|
||||
v.mu.Unlock()
|
||||
|
||||
var out *Preview
|
||||
// The host is docwell-server's from configuration; e only carries ids the
|
||||
// path patterns above allowed.
|
||||
u := strings.TrimRight(v.api.String(), "/") + e
|
||||
if req, err := http.NewRequestWithContext(ctx, http.MethodGet, u, nil); err == nil { //nolint:gosec // see above
|
||||
if resp, err := v.client.Do(req); err == nil { //nolint:gosec // see above
|
||||
if resp.StatusCode == http.StatusOK {
|
||||
var p Preview
|
||||
if json.NewDecoder(io.LimitReader(resp.Body, 64<<10)).Decode(&p) == nil && p.Title != "" {
|
||||
out = &p
|
||||
}
|
||||
}
|
||||
resp.Body.Close()
|
||||
}
|
||||
}
|
||||
|
||||
v.mu.Lock()
|
||||
if len(v.cache) > 1000 {
|
||||
v.cache = map[string]cachedPreview{}
|
||||
}
|
||||
v.cache[e] = cachedPreview{p: out, exp: now.Add(time.Minute)}
|
||||
v.mu.Unlock()
|
||||
return out
|
||||
}
|
||||
|
||||
// withPreview writes p's title and meta tags into the app shell's head.
|
||||
func withPreview(index []byte, p *Preview) []byte {
|
||||
esc := html.EscapeString
|
||||
var b strings.Builder
|
||||
b.WriteString("<title>" + esc(p.Title) + "</title>")
|
||||
b.WriteString(`<meta property="og:type" content="article">`)
|
||||
b.WriteString(`<meta property="og:title" content="` + esc(p.Title) + `">`)
|
||||
if p.Description != "" {
|
||||
b.WriteString(`<meta property="og:description" content="` + esc(p.Description) + `">`)
|
||||
b.WriteString(`<meta name="description" content="` + esc(p.Description) + `">`)
|
||||
}
|
||||
if p.Site != "" {
|
||||
b.WriteString(`<meta property="og:site_name" content="` + esc(p.Site) + `">`)
|
||||
}
|
||||
b.WriteString(`<meta name="twitter:card" content="summary">`)
|
||||
b.WriteString(`<meta name="robots" content="noindex">`)
|
||||
|
||||
// The shell's own <title> would come first and win.
|
||||
out := titleTag.ReplaceAll(index, nil)
|
||||
if i := bytes.Index(bytes.ToLower(out), []byte("</head>")); i >= 0 {
|
||||
return append(out[:i:i], append([]byte(b.String()), out[i:]...)...)
|
||||
}
|
||||
return append([]byte(b.String()), out...)
|
||||
}
|
||||
|
||||
var titleTag = regexp.MustCompile(`(?is)<title>.*?</title>`)
|
||||
@@ -0,0 +1,89 @@
|
||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
package spa
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"net/url"
|
||||
"strings"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
"testing/fstest"
|
||||
)
|
||||
|
||||
func TestEndpoint(t *testing.T) {
|
||||
cases := map[string]string{
|
||||
"/p/abc123": "/api/v1/previews/pages/abc123",
|
||||
"/share/tok_-9": "/api/v1/previews/share/tok_-9",
|
||||
"/share/tok/p/page1": "/api/v1/previews/share/tok?page=page1",
|
||||
"/p/abc/r/db/row": "",
|
||||
"/settings/account": "",
|
||||
"/p/../../admin": "",
|
||||
"/share/tok/p/a'b": "",
|
||||
"/share/tok/extra/path": "",
|
||||
}
|
||||
for in, want := range cases {
|
||||
if got := endpoint(in); got != want {
|
||||
t.Errorf("endpoint(%q) = %q, want %q", in, got, want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestBotsGetPreviewMetaTags(t *testing.T) {
|
||||
var calls atomic.Int32
|
||||
api := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
calls.Add(1)
|
||||
switch r.URL.Path {
|
||||
case "/api/v1/previews/pages/p1":
|
||||
w.Write([]byte(`{"title":"Q4 <plan>","description":"","site":"Acme"}`))
|
||||
case "/api/v1/previews/share/tok":
|
||||
w.Write([]byte(`{"title":"Handbook","description":"How we \"work\"","site":"Acme"}`))
|
||||
default:
|
||||
http.Error(w, `{"error":"not_found"}`, http.StatusNotFound)
|
||||
}
|
||||
}))
|
||||
defer api.Close()
|
||||
u, _ := url.Parse(api.URL)
|
||||
files := fstest.MapFS{"index.html": {Data: []byte("<!doctype html><html><head><title>Docwell</title></head><body></body></html>")}}
|
||||
h := Handler(Options{Files: files, PreviewAPI: u})
|
||||
|
||||
fetch := func(path, ua string) string {
|
||||
req := httptest.NewRequest("GET", path, nil)
|
||||
req.Header.Set("User-Agent", ua)
|
||||
rec := httptest.NewRecorder()
|
||||
h.ServeHTTP(rec, req)
|
||||
return rec.Body.String()
|
||||
}
|
||||
|
||||
body := fetch("/p/p1", "Slackbot-LinkExpanding 1.0 (+https://api.slack.com/robots)")
|
||||
if !strings.Contains(body, `<meta property="og:title" content="Q4 <plan>">`) ||
|
||||
!strings.Contains(body, `<title>Q4 <plan></title>`) || strings.Contains(body, "<title>Docwell</title>") {
|
||||
t.Errorf("bot page = %s", body)
|
||||
}
|
||||
body = fetch("/share/tok", "Mozilla/5.0 (compatible; Discordbot/2.0; +https://discordapp.com)")
|
||||
if !strings.Contains(body, `og:description" content="How we "work""`) {
|
||||
t.Errorf("bot share = %s", body)
|
||||
}
|
||||
|
||||
// People's browsers get the plain shell and cause no lookup.
|
||||
before := calls.Load()
|
||||
body = fetch("/p/p1", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 Chrome/142.0 Safari/537.36")
|
||||
if strings.Contains(body, "og:title") || calls.Load() != before {
|
||||
t.Errorf("browser got a preview: %s", body)
|
||||
}
|
||||
// Search engines too: they must not learn private titles.
|
||||
if body = fetch("/p/p1", "Mozilla/5.0 (compatible; Googlebot/2.1)"); strings.Contains(body, "og:title") {
|
||||
t.Errorf("search engine got a preview: %s", body)
|
||||
}
|
||||
// No preview (URL previews off): the plain shell.
|
||||
if body = fetch("/p/other", "Slackbot 1.0"); strings.Contains(body, "og:title") {
|
||||
t.Errorf("unknown page got a preview: %s", body)
|
||||
}
|
||||
// Answers are cached for a minute.
|
||||
before = calls.Load()
|
||||
fetch("/p/p1", "Slackbot 1.0")
|
||||
if calls.Load() != before {
|
||||
t.Error("second lookup was not cached")
|
||||
}
|
||||
}
|
||||
@@ -32,6 +32,9 @@ type Options struct {
|
||||
// ProxyTarget, when set, reverse-proxies /api/ and /collab to
|
||||
// docwell-server so the app and API share one origin.
|
||||
ProxyTarget *url.URL
|
||||
// PreviewAPI, when set, is the docwell-server that chat apps' link
|
||||
// previews of pages and share links are looked up on (preview.go).
|
||||
PreviewAPI *url.URL
|
||||
// Files overrides the embedded build (used in tests).
|
||||
Files fs.FS
|
||||
}
|
||||
@@ -43,6 +46,10 @@ func Handler(opts Options) http.Handler {
|
||||
}
|
||||
fileServer := http.FileServerFS(files)
|
||||
cfgJSON, _ := json.Marshal(opts.Config)
|
||||
var previews *previewer
|
||||
if opts.PreviewAPI != nil {
|
||||
previews = newPreviewer(opts.PreviewAPI)
|
||||
}
|
||||
|
||||
mux := http.NewServeMux()
|
||||
mux.HandleFunc("GET /config.json", func(w http.ResponseWriter, r *http.Request) {
|
||||
@@ -81,6 +88,16 @@ func Handler(opts Options) http.Handler {
|
||||
}
|
||||
if name == "index.html" {
|
||||
w.Header().Set("Cache-Control", "no-cache")
|
||||
if previews != nil && previewBots.MatchString(r.UserAgent()) {
|
||||
if p := previews.lookup(r.Context(), path.Clean(r.URL.Path)); p != nil {
|
||||
if index, err := fs.ReadFile(files, "index.html"); err == nil {
|
||||
w.Header().Set("Content-Type", "text/html; charset=utf-8")
|
||||
w.Header().Set("X-Robots-Tag", "noindex")
|
||||
w.Write(withPreview(index, p))
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
http.ServeFileFS(w, r, files, "index.html")
|
||||
return
|
||||
}
|
||||
|
||||
+330
-3
@@ -687,7 +687,7 @@ paths:
|
||||
patch:
|
||||
operationId: updateWorkspace
|
||||
tags: [workspaces]
|
||||
summary: Rename a workspace or change how its new pages open (workspace admin or above)
|
||||
summary: Rename a workspace, change how its new pages open, or its sharing switches (workspace admin or above)
|
||||
security: [{ bearer: [] }]
|
||||
requestBody:
|
||||
required: true
|
||||
@@ -698,6 +698,8 @@ paths:
|
||||
properties:
|
||||
name: { type: string, maxLength: 120 }
|
||||
defaultPageMode: { $ref: "#/components/schemas/PageMode" }
|
||||
allowSharing: { type: boolean, description: Off turns every share link of the workspace off until it is on again }
|
||||
urlPreview: { type: boolean, description: "Let chat apps show private pages' titles in link previews" }
|
||||
responses:
|
||||
"200":
|
||||
description: OK
|
||||
@@ -2146,6 +2148,233 @@ paths:
|
||||
application/octet-stream:
|
||||
schema: { type: string, format: binary }
|
||||
"404": { $ref: "#/components/responses/Error" }
|
||||
/api/v1/workspaces/{id}/invite-link:
|
||||
parameters:
|
||||
- { name: id, in: path, required: true, schema: { type: string } }
|
||||
get:
|
||||
operationId: getInviteLink
|
||||
tags: [sharing]
|
||||
summary: The workspace's invite link (404 when it has none; workspace admin)
|
||||
security: [{ bearer: [] }]
|
||||
responses:
|
||||
"200":
|
||||
description: OK
|
||||
content:
|
||||
application/json:
|
||||
schema: { $ref: "#/components/schemas/InviteLink" }
|
||||
"403": { $ref: "#/components/responses/Error" }
|
||||
"404": { $ref: "#/components/responses/Error" }
|
||||
put:
|
||||
operationId: setInviteLink
|
||||
tags: [sharing]
|
||||
summary: Create or change the invite link (workspace admin)
|
||||
description: An existing link keeps its URL unless reset is true.
|
||||
security: [{ bearer: [] }]
|
||||
requestBody:
|
||||
required: true
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
type: object
|
||||
properties:
|
||||
role: { type: string, enum: [member, guest], description: Default member }
|
||||
approval: { type: boolean, description: Joining needs an admin's approval }
|
||||
expiresInDays:
|
||||
type: integer
|
||||
minimum: 0
|
||||
maximum: 365
|
||||
description: Days from now; 0 means the link does not expire
|
||||
reset: { type: boolean, description: Make a new URL; the old one stops working }
|
||||
responses:
|
||||
"200":
|
||||
description: OK
|
||||
content:
|
||||
application/json:
|
||||
schema: { $ref: "#/components/schemas/InviteLink" }
|
||||
"400": { $ref: "#/components/responses/Error" }
|
||||
"403": { $ref: "#/components/responses/Error" }
|
||||
"404": { $ref: "#/components/responses/Error" }
|
||||
delete:
|
||||
operationId: deleteInviteLink
|
||||
tags: [sharing]
|
||||
summary: Turn the invite link off; its URL stops working (workspace admin)
|
||||
security: [{ bearer: [] }]
|
||||
responses:
|
||||
"204": { description: Off }
|
||||
"403": { $ref: "#/components/responses/Error" }
|
||||
"404": { $ref: "#/components/responses/Error" }
|
||||
/api/v1/workspaces/{id}/join-requests:
|
||||
parameters:
|
||||
- { name: id, in: path, required: true, schema: { type: string } }
|
||||
get:
|
||||
operationId: listJoinRequests
|
||||
tags: [sharing]
|
||||
summary: Requests to join through the invite link that wait for a decision (workspace admin)
|
||||
security: [{ bearer: [] }]
|
||||
responses:
|
||||
"200":
|
||||
description: Oldest first
|
||||
content:
|
||||
application/json:
|
||||
schema: { type: array, items: { $ref: "#/components/schemas/JoinRequest" } }
|
||||
"403": { $ref: "#/components/responses/Error" }
|
||||
"404": { $ref: "#/components/responses/Error" }
|
||||
/api/v1/workspaces/{id}/join-requests/{requestId}/approve:
|
||||
parameters:
|
||||
- { name: id, in: path, required: true, schema: { type: string } }
|
||||
- { name: requestId, in: path, required: true, schema: { type: string } }
|
||||
post:
|
||||
operationId: approveJoinRequest
|
||||
tags: [sharing]
|
||||
summary: Let the person in and tell them (workspace admin)
|
||||
security: [{ bearer: [] }]
|
||||
requestBody:
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
type: object
|
||||
properties:
|
||||
role: { $ref: "#/components/schemas/WorkspaceRole", description: Overrides the link's role }
|
||||
responses:
|
||||
"204": { description: Approved }
|
||||
"403": { $ref: "#/components/responses/Error" }
|
||||
"404": { $ref: "#/components/responses/Error" }
|
||||
"409": { $ref: "#/components/responses/Error" }
|
||||
/api/v1/workspaces/{id}/join-requests/{requestId}/decline:
|
||||
parameters:
|
||||
- { name: id, in: path, required: true, schema: { type: string } }
|
||||
- { name: requestId, in: path, required: true, schema: { type: string } }
|
||||
post:
|
||||
operationId: declineJoinRequest
|
||||
tags: [sharing]
|
||||
summary: Turn the request down and tell the person (workspace admin)
|
||||
security: [{ bearer: [] }]
|
||||
responses:
|
||||
"204": { description: Declined }
|
||||
"403": { $ref: "#/components/responses/Error" }
|
||||
"404": { $ref: "#/components/responses/Error" }
|
||||
/api/v1/auth/join/{token}:
|
||||
parameters:
|
||||
- { name: token, in: path, required: true, schema: { type: string } }
|
||||
get:
|
||||
operationId: getJoinInfo
|
||||
tags: [sharing]
|
||||
summary: Describe an invite link (no account needed; status is filled in when signed in)
|
||||
security: [{}, { bearer: [] }]
|
||||
responses:
|
||||
"200":
|
||||
description: OK
|
||||
content:
|
||||
application/json:
|
||||
schema: { $ref: "#/components/schemas/JoinInfo" }
|
||||
"401": { $ref: "#/components/responses/Error" }
|
||||
post:
|
||||
operationId: joinWorkspace
|
||||
tags: [sharing]
|
||||
summary: Join through an invite link, or ask to when it needs approval
|
||||
security: [{ bearer: [] }]
|
||||
responses:
|
||||
"200":
|
||||
description: OK
|
||||
content:
|
||||
application/json:
|
||||
schema: { $ref: "#/components/schemas/JoinResult" }
|
||||
"401": { $ref: "#/components/responses/Error" }
|
||||
"409": { $ref: "#/components/responses/Error" }
|
||||
/api/v1/pages/{id}/analytics:
|
||||
parameters:
|
||||
- { name: id, in: path, required: true, schema: { type: string } }
|
||||
- { name: days, in: query, schema: { type: integer, minimum: 7, maximum: 90, default: 30 } }
|
||||
get:
|
||||
operationId: getPageAnalytics
|
||||
tags: [sharing]
|
||||
summary: How often and by whom the page was opened (editor)
|
||||
security: [{ bearer: [] }]
|
||||
responses:
|
||||
"200":
|
||||
description: OK
|
||||
content:
|
||||
application/json:
|
||||
schema: { $ref: "#/components/schemas/PageAnalytics" }
|
||||
"400": { $ref: "#/components/responses/Error" }
|
||||
"403": { $ref: "#/components/responses/Error" }
|
||||
"404": { $ref: "#/components/responses/Error" }
|
||||
/api/v1/workspaces/{id}/unused-files:
|
||||
parameters:
|
||||
- { name: id, in: path, required: true, schema: { type: string } }
|
||||
get:
|
||||
operationId: listUnusedFiles
|
||||
tags: [files]
|
||||
summary: 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.
|
||||
security: [{ bearer: [] }]
|
||||
responses:
|
||||
"200":
|
||||
description: OK
|
||||
content:
|
||||
application/json:
|
||||
schema: { $ref: "#/components/schemas/UnusedFiles" }
|
||||
"403": { $ref: "#/components/responses/Error" }
|
||||
"404": { $ref: "#/components/responses/Error" }
|
||||
/api/v1/workspaces/{id}/unused-files/delete:
|
||||
parameters:
|
||||
- { name: id, in: path, required: true, schema: { type: string } }
|
||||
post:
|
||||
operationId: deleteUnusedFiles
|
||||
tags: [files]
|
||||
summary: 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.
|
||||
security: [{ bearer: [] }]
|
||||
requestBody:
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
type: object
|
||||
properties:
|
||||
ids: { type: array, items: { type: string } }
|
||||
responses:
|
||||
"200":
|
||||
description: OK
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
type: object
|
||||
required: [deleted]
|
||||
properties:
|
||||
deleted: { type: integer }
|
||||
"403": { $ref: "#/components/responses/Error" }
|
||||
"404": { $ref: "#/components/responses/Error" }
|
||||
/api/v1/previews/pages/{id}:
|
||||
parameters:
|
||||
- { name: id, in: path, required: true, schema: { type: string } }
|
||||
get:
|
||||
operationId: getPagePreview
|
||||
tags: [sharing]
|
||||
summary: Title of a private page for chat apps' link previews (only when the workspace turned URL previews on)
|
||||
responses:
|
||||
"200":
|
||||
description: OK
|
||||
content:
|
||||
application/json:
|
||||
schema: { $ref: "#/components/schemas/PagePreview" }
|
||||
"404": { $ref: "#/components/responses/Error" }
|
||||
/api/v1/previews/share/{token}:
|
||||
parameters:
|
||||
- { name: token, in: path, required: true, schema: { type: string } }
|
||||
- { name: page, in: query, description: A page under the shared one, schema: { type: string } }
|
||||
get:
|
||||
operationId: getSharePreview
|
||||
tags: [sharing]
|
||||
summary: Title and opening text of a page reached through a share link, for link previews
|
||||
responses:
|
||||
"200":
|
||||
description: OK
|
||||
content:
|
||||
application/json:
|
||||
schema: { $ref: "#/components/schemas/PagePreview" }
|
||||
"404": { $ref: "#/components/responses/Error" }
|
||||
/api/v1/workspaces/{id}/people:
|
||||
parameters:
|
||||
- { name: id, in: path, required: true, schema: { type: string } }
|
||||
@@ -3999,7 +4228,7 @@ components:
|
||||
workspaces: { type: integer }
|
||||
Workspace:
|
||||
type: object
|
||||
required: [id, name, slug, organization, organizationName, role, created, defaultPageMode]
|
||||
required: [id, name, slug, organization, organizationName, role, created, defaultPageMode, allowSharing, urlPreview]
|
||||
properties:
|
||||
id: { type: string }
|
||||
name: { type: string }
|
||||
@@ -4009,6 +4238,8 @@ components:
|
||||
role: { $ref: "#/components/schemas/WorkspaceRole" }
|
||||
created: { type: string }
|
||||
defaultPageMode: { $ref: "#/components/schemas/PageMode", description: The view new pages of the workspace open in }
|
||||
allowSharing: { type: boolean, description: False when public share links are off for the whole workspace }
|
||||
urlPreview: { type: boolean, description: "Chat apps may show private pages' titles in link previews" }
|
||||
WorkspaceMember:
|
||||
type: object
|
||||
required: [user, role]
|
||||
@@ -4572,6 +4803,99 @@ components:
|
||||
size: { type: integer, description: Bytes }
|
||||
url: { type: string, description: "API path, e.g. /api/v1/files/abc" }
|
||||
created: { type: string }
|
||||
InviteLink:
|
||||
type: object
|
||||
required: [token, url, role, approval, expires, created, pending]
|
||||
properties:
|
||||
token: { type: string }
|
||||
url: { type: string, description: "The link on docwell-web (DOCWELL_WEB_URL/join?token=...)" }
|
||||
role: { type: string, enum: [member, guest] }
|
||||
approval: { type: boolean, description: Joining needs an admin's approval }
|
||||
expires: { type: string, description: Empty when the link does not expire }
|
||||
created: { type: string }
|
||||
pending: { type: integer, description: Requests waiting for a decision }
|
||||
JoinRequest:
|
||||
type: object
|
||||
required: [id, user, role, created]
|
||||
properties:
|
||||
id: { type: string }
|
||||
user: { $ref: "#/components/schemas/MemberUser" }
|
||||
role: { type: string, enum: [member, guest] }
|
||||
created: { type: string }
|
||||
JoinInfo:
|
||||
type: object
|
||||
required: [workspace, workspaceName, organizationName, role, approval, status]
|
||||
properties:
|
||||
workspace: { type: string }
|
||||
workspaceName: { type: string }
|
||||
organizationName: { type: string }
|
||||
role: { type: string, enum: [member, guest] }
|
||||
approval: { type: boolean }
|
||||
status:
|
||||
type: string
|
||||
enum: ["", member, pending, declined]
|
||||
description: The caller's standing; empty when signed out or not asked yet
|
||||
JoinResult:
|
||||
type: object
|
||||
required: [status, workspace]
|
||||
properties:
|
||||
status: { type: string, enum: [member, pending] }
|
||||
workspace: { type: string }
|
||||
PageAnalytics:
|
||||
type: object
|
||||
required: [days, views, viewers, linkViews, daily, recent]
|
||||
properties:
|
||||
days: { type: integer }
|
||||
views: { type: integer, description: Opens in the period (repeat opens within 30 minutes count once) }
|
||||
viewers: { type: integer, description: Different signed-in people }
|
||||
linkViews: { type: integer, description: Opens through a share link }
|
||||
daily:
|
||||
type: array
|
||||
description: One entry per day (UTC), oldest first
|
||||
items: { $ref: "#/components/schemas/AnalyticsDay" }
|
||||
recent:
|
||||
type: array
|
||||
description: Who opened the page, most recent first (at most 20)
|
||||
items: { $ref: "#/components/schemas/PageViewer" }
|
||||
AnalyticsDay:
|
||||
type: object
|
||||
required: [date, views, viewers]
|
||||
properties:
|
||||
date: { type: string, description: "YYYY-MM-DD (UTC)" }
|
||||
views: { type: integer }
|
||||
viewers: { type: integer }
|
||||
PageViewer:
|
||||
type: object
|
||||
required: [user, views, lastViewed]
|
||||
properties:
|
||||
user: { $ref: "#/components/schemas/MemberUser" }
|
||||
views: { type: integer }
|
||||
lastViewed: { type: string }
|
||||
UnusedFile:
|
||||
type: object
|
||||
required: [id, page, name, mime, size, url, created, pageTitle]
|
||||
properties:
|
||||
id: { type: string }
|
||||
page: { type: string }
|
||||
name: { type: string }
|
||||
mime: { type: string }
|
||||
size: { type: integer, description: Bytes }
|
||||
url: { type: string }
|
||||
created: { type: string }
|
||||
pageTitle: { type: string, description: The page it was uploaded to; empty when the caller cannot open it }
|
||||
UnusedFiles:
|
||||
type: object
|
||||
required: [files, size]
|
||||
properties:
|
||||
files: { type: array, items: { $ref: "#/components/schemas/UnusedFile" } }
|
||||
size: { type: integer, description: Total bytes }
|
||||
PagePreview:
|
||||
type: object
|
||||
required: [title, description, site]
|
||||
properties:
|
||||
title: { type: string }
|
||||
description: { type: string }
|
||||
site: { type: string, description: The workspace's name }
|
||||
SearchHit:
|
||||
type: object
|
||||
required: [id, title, icon, space, spaceName, snippet, highlights, updated]
|
||||
@@ -4668,7 +4992,10 @@ components:
|
||||
required: [watching]
|
||||
properties:
|
||||
watching: { type: boolean }
|
||||
NotificationType: { type: string, enum: [comment, reply, mention, share, resolved, reminder] }
|
||||
NotificationType:
|
||||
type: string
|
||||
enum: [comment, reply, mention, share, resolved, reminder, join_request, join_approved, join_declined]
|
||||
description: The join_* types are about a workspace and have no page
|
||||
Notification:
|
||||
type: object
|
||||
required: [id, type, workspace, page, comment, actor, excerpt, created, read]
|
||||
|
||||
Reference in new issue
Block a user